@opentiny/next-sdk 0.4.1 → 0.4.2

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 (64) hide show
  1. package/dist/{SimulatorMask-BHVXyogh-iNUb4dyF.js → SimulatorMask-BHVXyogh-CARX3Rff.js} +1 -1
  2. package/dist/core.js +1 -1
  3. package/dist/{index-CXK8CcKq.js → index-R_HIbfUX.js} +1698 -1170
  4. package/dist/index.d.ts +11 -0
  5. package/dist/index.js +69 -50
  6. package/dist/{initialize-builtin-WebMCP-rALfqS-o.js → initialize-builtin-WebMCP-JaoKwVlm.js} +355 -346
  7. package/dist/page-tools/a11y/build.d.ts +3 -4
  8. package/dist/page-tools/a11y/config.d.ts +96 -0
  9. package/dist/page-tools/a11y/constants.d.ts +2 -0
  10. package/dist/page-tools/a11y/search.d.ts +1 -1
  11. package/dist/page-tools/a11y/types.d.ts +13 -22
  12. package/dist/page-tools/a11y/utils.d.ts +32 -11
  13. package/dist/page-tools/a11y/vnode.d.ts +14 -11
  14. package/dist/page-tools/a11y-tree.d.ts +1 -0
  15. package/dist/page-tools/configs/console-cloud.d.ts +6 -0
  16. package/dist/page-tools/constants.d.ts +5 -17
  17. package/dist/page-tools/context.d.ts +12 -0
  18. package/dist/page-tools/handlers/searchTree.d.ts +2 -1
  19. package/dist/page-tools/page-agent-highlight/index.d.ts +12 -0
  20. package/dist/page-tools/page-agent-mask/SimulatorMask.d.ts +2 -0
  21. package/dist/page-tools/page-agent-tool-event.d.ts +26 -0
  22. package/dist/page-tools/schema.d.ts +1 -0
  23. package/dist/page-tools/tool-config.d.ts +50 -0
  24. package/dist/runtime.d.ts +4 -1
  25. package/dist/runtime.js +37 -49
  26. package/dist/vitest.config.d.ts +2 -0
  27. package/index.ts +35 -0
  28. package/package.json +21 -16
  29. package/page-tools/a11y/build.ts +38 -34
  30. package/page-tools/a11y/config.ts +465 -0
  31. package/page-tools/a11y/constants.ts +21 -0
  32. package/page-tools/a11y/search.ts +1 -3
  33. package/page-tools/a11y/types.ts +14 -17
  34. package/page-tools/a11y/utils.ts +129 -156
  35. package/page-tools/a11y/vnode.ts +277 -67
  36. package/page-tools/a11y-tree.ts +1 -0
  37. package/page-tools/bridge.ts +22 -2
  38. package/page-tools/configs/console-cloud.ts +172 -0
  39. package/page-tools/constants.ts +5 -65
  40. package/page-tools/context.ts +38 -1
  41. package/page-tools/handlers/click.ts +6 -2
  42. package/page-tools/handlers/fill.ts +10 -5
  43. package/page-tools/handlers/searchTree.ts +7 -10
  44. package/page-tools/handlers/select.ts +10 -5
  45. package/page-tools/page-agent-highlight/index.ts +66 -19
  46. package/page-tools/page-agent-mask/SimulatorMask.ts +42 -22
  47. package/page-tools/page-agent-mask/hauwei.svg +25 -0
  48. package/page-tools/page-agent-prompt.md +1 -1
  49. package/page-tools/page-agent-tool-event.ts +113 -0
  50. package/page-tools/page-agent-tool.ts +85 -53
  51. package/page-tools/schema.ts +1 -0
  52. package/page-tools/tool-config.ts +100 -0
  53. package/page-tools/utils/dom.ts +6 -3
  54. package/runtime.ts +37 -6
  55. package/test/page-tools/a11y/build.test.ts +638 -0
  56. package/test/page-tools/a11y/config.test.ts +370 -0
  57. package/test/page-tools/configs/console-cloud.test.ts +168 -0
  58. package/test/page-tools/page-agent-highlight.test.ts +110 -0
  59. package/test/page-tools/page-agent-tool-dispatch.test.ts +208 -0
  60. package/test/page-tools/page-agent-tool.test.ts +102 -0
  61. package/test/page-tools/tool-config.test.ts +112 -0
  62. package/test/page-tools/utils/dom.test.ts +122 -0
  63. package/vite.config.runtime.ts +1 -1
  64. package/vitest.config.ts +10 -0
package/dist/runtime.js CHANGED
@@ -1,7 +1,7 @@
1
- var NextSDK=(function(exports){"use strict";function deepCompareStrict(t,e){const r=typeof t;if(r!==typeof e)return!1;if(Array.isArray(t)){if(!Array.isArray(e))return!1;const n=t.length;if(n!==e.length)return!1;for(let i=0;i<n;i++)if(!deepCompareStrict(t[i],e[i]))return!1;return!0}if(r==="object"){if(!t||!e)return t===e;const n=Object.keys(t),i=Object.keys(e);if(n.length!==i.length)return!1;for(const s of n)if(!deepCompareStrict(t[s],e[s]))return!1;return!0}return t===e}function encodePointer(t){return encodeURI(escapePointer(t))}function escapePointer(t){return t.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(t,e=Object.create(null),r=initialBaseURI,n=""){if(t&&typeof t=="object"&&!Array.isArray(t)){const o=t.$id||t.id;if(o){const s=new URL(o,r.href);s.hash.length>1?e[s.href]=t:(s.hash="",n===""?r=s:dereference(t,e,r))}}else if(t!==!0&&t!==!1)return e;const i=r.href+(n?"#"+n:"");if(e[i]!==void 0)throw new Error(`Duplicate schema URI "${i}".`);if(e[i]=t,t===!0||t===!1)return e;if(t.__absolute_uri__===void 0&&Object.defineProperty(t,"__absolute_uri__",{enumerable:!1,value:i}),t.$ref&&t.__absolute_ref__===void 0){const o=new URL(t.$ref,r.href);o.hash=o.hash,Object.defineProperty(t,"__absolute_ref__",{enumerable:!1,value:o.href})}if(t.$recursiveRef&&t.__absolute_recursive_ref__===void 0){const o=new URL(t.$recursiveRef,r.href);o.hash=o.hash,Object.defineProperty(t,"__absolute_recursive_ref__",{enumerable:!1,value:o.href})}if(t.$anchor){const o=new URL("#"+t.$anchor,r.href);e[o.href]=t}for(let o in t){if(ignoredKeyword[o])continue;const s=`${n}/${encodePointer(o)}`,a=t[o];if(Array.isArray(a)){if(schemaArrayKeyword[o]){const l=a.length;for(let d=0;d<l;d++)dereference(a[d],e,r,`${s}/${d}`)}}else if(schemaMapKeyword[o])for(let l in a)dereference(a[l],e,r,`${s}/${encodePointer(l)}`);else dereference(a,e,r,s)}return e}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=t=>{if(t[0]==='"')return!1;const[e,r,...n]=t.split("@");return!e||!r||n.length!==0||e.length>64||r.length>253||e[0]==="."||e.endsWith(".")||e.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(e)?!1:r.split(".").every(i=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(i))},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=t=>t.length>1&&t.length<80&&(/^P\d+([.,]\d+)?W$/.test(t)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(t)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(t));function bind(t){return t.test.bind(t)}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(t){return t%4===0&&(t%100!==0||t%400===0)}function date(t){const e=t.match(DATE);if(!e)return!1;const r=+e[1],n=+e[2],i=+e[3];return n>=1&&n<=12&&i>=1&&i<=(n==2&&isLeapYear(r)?29:DAYS[n])}function time(t,e){const r=e.match(TIME);if(!r)return!1;const n=+r[1],i=+r[2],o=+r[3],s=!!r[5];return(n<=23&&i<=59&&o<=59||n==23&&i==59&&o==60)&&(!t||s)}const DATE_TIME_SEPARATOR=/t|\s/i;function date_time(t){const e=t.split(DATE_TIME_SEPARATOR);return e.length==2&&date(e[0])&&time(!0,e[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(t){return NOT_URI_FRAGMENT.test(t)&&URI_PATTERN.test(t)}const Z_ANCHOR=/[^\\]\\Z/;function regex(t){if(Z_ANCHOR.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}function ucs2length(t){let e=0,r=t.length,n=0,i;for(;n<r;)e++,i=t.charCodeAt(n++),i>=55296&&i<=56319&&n<r&&(i=t.charCodeAt(n),(i&64512)==56320&&n++);return e}function validate(t,e,r="2019-09",n=dereference(e),i=!0,o=null,s="#",a="#",l=Object.create(null)){if(e===!0)return{valid:!0,errors:[]};if(e===!1)return{valid:!1,errors:[{instanceLocation:s,keyword:"false",keywordLocation:s,error:"False boolean schema."}]};const d=typeof t;let u;switch(d){case"boolean":case"number":case"string":u=d;break;case"object":t===null?u="null":Array.isArray(t)?u="array":u="object";break;default:throw new Error(`Instances of "${d}" type are not supported.`)}const{$ref:f,$recursiveRef:p,$recursiveAnchor:g,type:y,const:Z,enum:x,required:h,not:S,anyOf:I,allOf:A,oneOf:O,if:C,then:w,else:V,format:F,properties:j,patternProperties:H,additionalProperties:W,unevaluatedProperties:te,minProperties:X,maxProperties:re,propertyNames:oe,dependentRequired:ne,dependentSchemas:Q,dependencies:K,prefixItems:de,items:c,additionalItems:v,unevaluatedItems:z,contains:_,minContains:P,maxContains:B,minItems:E,maxItems:M,uniqueItems:L,minimum:U,maximum:Y,exclusiveMinimum:G,exclusiveMaximum:ee,multipleOf:J,minLength:ae,maxLength:ie,pattern:ue,__absolute_ref__:le,__absolute_recursive_ref__:ce}=e,T=[];if(g===!0&&o===null&&(o=e),p==="#"){const D=o===null?n[ce]:o,R=`${a}/$recursiveRef`,k=validate(t,o===null?e:o,r,n,i,D,s,R,l);k.valid||T.push({instanceLocation:s,keyword:"$recursiveRef",keywordLocation:R,error:"A subschema had errors."},...k.errors)}if(f!==void 0){const R=n[le||f];if(R===void 0){let m=`Unresolved $ref "${f}".`;throw le&&le!==f&&(m+=` Absolute URI "${le}".`),m+=`
1
+ var WebMCPSDK=(function(exports){"use strict";function deepCompareStrict(t,e){const r=typeof t;if(r!==typeof e)return!1;if(Array.isArray(t)){if(!Array.isArray(e))return!1;const n=t.length;if(n!==e.length)return!1;for(let i=0;i<n;i++)if(!deepCompareStrict(t[i],e[i]))return!1;return!0}if(r==="object"){if(!t||!e)return t===e;const n=Object.keys(t),i=Object.keys(e);if(n.length!==i.length)return!1;for(const s of n)if(!deepCompareStrict(t[s],e[s]))return!1;return!0}return t===e}function encodePointer(t){return encodeURI(escapePointer(t))}function escapePointer(t){return t.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(t,e=Object.create(null),r=initialBaseURI,n=""){if(t&&typeof t=="object"&&!Array.isArray(t)){const o=t.$id||t.id;if(o){const s=new URL(o,r.href);s.hash.length>1?e[s.href]=t:(s.hash="",n===""?r=s:dereference(t,e,r))}}else if(t!==!0&&t!==!1)return e;const i=r.href+(n?"#"+n:"");if(e[i]!==void 0)throw new Error(`Duplicate schema URI "${i}".`);if(e[i]=t,t===!0||t===!1)return e;if(t.__absolute_uri__===void 0&&Object.defineProperty(t,"__absolute_uri__",{enumerable:!1,value:i}),t.$ref&&t.__absolute_ref__===void 0){const o=new URL(t.$ref,r.href);o.hash=o.hash,Object.defineProperty(t,"__absolute_ref__",{enumerable:!1,value:o.href})}if(t.$recursiveRef&&t.__absolute_recursive_ref__===void 0){const o=new URL(t.$recursiveRef,r.href);o.hash=o.hash,Object.defineProperty(t,"__absolute_recursive_ref__",{enumerable:!1,value:o.href})}if(t.$anchor){const o=new URL("#"+t.$anchor,r.href);e[o.href]=t}for(let o in t){if(ignoredKeyword[o])continue;const s=`${n}/${encodePointer(o)}`,a=t[o];if(Array.isArray(a)){if(schemaArrayKeyword[o]){const l=a.length;for(let c=0;c<l;c++)dereference(a[c],e,r,`${s}/${c}`)}}else if(schemaMapKeyword[o])for(let l in a)dereference(a[l],e,r,`${s}/${encodePointer(l)}`);else dereference(a,e,r,s)}return e}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=t=>{if(t[0]==='"')return!1;const[e,r,...n]=t.split("@");return!e||!r||n.length!==0||e.length>64||r.length>253||e[0]==="."||e.endsWith(".")||e.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(e)?!1:r.split(".").every(i=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(i))},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=t=>t.length>1&&t.length<80&&(/^P\d+([.,]\d+)?W$/.test(t)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(t)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(t));function bind(t){return t.test.bind(t)}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(t){return t%4===0&&(t%100!==0||t%400===0)}function date(t){const e=t.match(DATE);if(!e)return!1;const r=+e[1],n=+e[2],i=+e[3];return n>=1&&n<=12&&i>=1&&i<=(n==2&&isLeapYear(r)?29:DAYS[n])}function time(t,e){const r=e.match(TIME);if(!r)return!1;const n=+r[1],i=+r[2],o=+r[3],s=!!r[5];return(n<=23&&i<=59&&o<=59||n==23&&i==59&&o==60)&&(!t||s)}const DATE_TIME_SEPARATOR=/t|\s/i;function date_time(t){const e=t.split(DATE_TIME_SEPARATOR);return e.length==2&&date(e[0])&&time(!0,e[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(t){return NOT_URI_FRAGMENT.test(t)&&URI_PATTERN.test(t)}const Z_ANCHOR=/[^\\]\\Z/;function regex(t){if(Z_ANCHOR.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}function ucs2length(t){let e=0,r=t.length,n=0,i;for(;n<r;)e++,i=t.charCodeAt(n++),i>=55296&&i<=56319&&n<r&&(i=t.charCodeAt(n),(i&64512)==56320&&n++);return e}function validate(t,e,r="2019-09",n=dereference(e),i=!0,o=null,s="#",a="#",l=Object.create(null)){if(e===!0)return{valid:!0,errors:[]};if(e===!1)return{valid:!1,errors:[{instanceLocation:s,keyword:"false",keywordLocation:s,error:"False boolean schema."}]};const c=typeof t;let u;switch(c){case"boolean":case"number":case"string":u=c;break;case"object":t===null?u="null":Array.isArray(t)?u="array":u="object";break;default:throw new Error(`Instances of "${c}" type are not supported.`)}const{$ref:h,$recursiveRef:f,$recursiveAnchor:g,type:b,const:P,enum:w,required:p,not:m,anyOf:A,allOf:T,oneOf:k,if:Z,then:R,else:V,format:j,properties:H,patternProperties:B,additionalProperties:G,unevaluatedProperties:ie,minProperties:X,maxProperties:te,propertyNames:oe,dependentRequired:re,dependentSchemas:Q,dependencies:K,prefixItems:ce,items:d,additionalItems:x,unevaluatedItems:U,contains:_,minContains:I,maxContains:z,minItems:C,maxItems:M,uniqueItems:O,minimum:F,maximum:Y,exclusiveMinimum:W,exclusiveMaximum:ee,multipleOf:J,minLength:ae,maxLength:ne,pattern:ue,__absolute_ref__:le,__absolute_recursive_ref__:de}=e,E=[];if(g===!0&&o===null&&(o=e),f==="#"){const D=o===null?n[de]:o,$=`${a}/$recursiveRef`,S=validate(t,o===null?e:o,r,n,i,D,s,$,l);S.valid||E.push({instanceLocation:s,keyword:"$recursiveRef",keywordLocation:$,error:"A subschema had errors."},...S.errors)}if(h!==void 0){const $=n[le||h];if($===void 0){let y=`Unresolved $ref "${h}".`;throw le&&le!==h&&(y+=` Absolute URI "${le}".`),y+=`
2
2
  Known schemas:
3
3
  - ${Object.keys(n).join(`
4
- - `)}`,new Error(m)}const k=`${a}/$ref`,b=validate(t,R,r,n,i,o,s,k,l);if(b.valid||T.push({instanceLocation:s,keyword:"$ref",keywordLocation:k,error:"A subschema had errors."},...b.errors),r==="4"||r==="7")return{valid:T.length===0,errors:T}}if(Array.isArray(y)){let D=y.length,R=!1;for(let k=0;k<D;k++)if(u===y[k]||y[k]==="integer"&&u==="number"&&t%1===0&&t===t){R=!0;break}R||T.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${y.join('", "')}".`})}else y==="integer"?(u!=="number"||t%1||t!==t)&&T.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${y}".`}):y!==void 0&&u!==y&&T.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${y}".`});if(Z!==void 0&&(u==="object"||u==="array"?deepCompareStrict(t,Z)||T.push({instanceLocation:s,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(Z)}.`}):t!==Z&&T.push({instanceLocation:s,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(Z)}.`})),x!==void 0&&(u==="object"||u==="array"?x.some(D=>deepCompareStrict(t,D))||T.push({instanceLocation:s,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(x)}.`}):x.some(D=>t===D)||T.push({instanceLocation:s,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(x)}.`})),S!==void 0){const D=`${a}/not`;validate(t,S,r,n,i,o,s,D).valid&&T.push({instanceLocation:s,keyword:"not",keywordLocation:D,error:'Instance matched "not" schema.'})}let fe=[];if(I!==void 0){const D=`${a}/anyOf`,R=T.length;let k=!1;for(let b=0;b<I.length;b++){const m=I[b],$=Object.create(l),N=validate(t,m,r,n,i,g===!0?o:null,s,`${D}/${b}`,$);T.push(...N.errors),k=k||N.valid,N.valid&&fe.push($)}k?T.length=R:T.splice(R,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:D,error:"Instance does not match any subschemas."})}if(A!==void 0){const D=`${a}/allOf`,R=T.length;let k=!0;for(let b=0;b<A.length;b++){const m=A[b],$=Object.create(l),N=validate(t,m,r,n,i,g===!0?o:null,s,`${D}/${b}`,$);T.push(...N.errors),k=k&&N.valid,N.valid&&fe.push($)}k?T.length=R:T.splice(R,0,{instanceLocation:s,keyword:"allOf",keywordLocation:D,error:"Instance does not match every subschema."})}if(O!==void 0){const D=`${a}/oneOf`,R=T.length,k=O.filter((b,m)=>{const $=Object.create(l),N=validate(t,b,r,n,i,g===!0?o:null,s,`${D}/${m}`,$);return T.push(...N.errors),N.valid&&fe.push($),N.valid}).length;k===1?T.length=R:T.splice(R,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:D,error:`Instance does not match exactly one subschema (${k} matches).`})}if((u==="object"||u==="array")&&Object.assign(l,...fe),C!==void 0){const D=`${a}/if`;if(validate(t,C,r,n,i,o,s,D,l).valid){if(w!==void 0){const k=validate(t,w,r,n,i,o,s,`${a}/then`,l);k.valid||T.push({instanceLocation:s,keyword:"if",keywordLocation:D,error:'Instance does not match "then" schema.'},...k.errors)}}else if(V!==void 0){const k=validate(t,V,r,n,i,o,s,`${a}/else`,l);k.valid||T.push({instanceLocation:s,keyword:"if",keywordLocation:D,error:'Instance does not match "else" schema.'},...k.errors)}}if(u==="object"){if(h!==void 0)for(const b of h)b in t||T.push({instanceLocation:s,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${b}".`});const D=Object.keys(t);if(X!==void 0&&D.length<X&&T.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${X} properties.`}),re!==void 0&&D.length>re&&T.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${re} properties.`}),oe!==void 0){const b=`${a}/propertyNames`;for(const m in t){const $=`${s}/${encodePointer(m)}`,N=validate(m,oe,r,n,i,o,$,b);N.valid||T.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:b,error:`Property name "${m}" does not match schema.`},...N.errors)}}if(ne!==void 0){const b=`${a}/dependantRequired`;for(const m in ne)if(m in t){const $=ne[m];for(const N of $)N in t||T.push({instanceLocation:s,keyword:"dependentRequired",keywordLocation:b,error:`Instance has "${m}" but does not have "${N}".`})}}if(Q!==void 0)for(const b in Q){const m=`${a}/dependentSchemas`;if(b in t){const $=validate(t,Q[b],r,n,i,o,s,`${m}/${encodePointer(b)}`,l);$.valid||T.push({instanceLocation:s,keyword:"dependentSchemas",keywordLocation:m,error:`Instance has "${b}" but does not match dependant schema.`},...$.errors)}}if(K!==void 0){const b=`${a}/dependencies`;for(const m in K)if(m in t){const $=K[m];if(Array.isArray($))for(const N of $)N in t||T.push({instanceLocation:s,keyword:"dependencies",keywordLocation:b,error:`Instance has "${m}" but does not have "${N}".`});else{const N=validate(t,$,r,n,i,o,s,`${b}/${encodePointer(m)}`);N.valid||T.push({instanceLocation:s,keyword:"dependencies",keywordLocation:b,error:`Instance has "${m}" but does not match dependant schema.`},...N.errors)}}}const R=Object.create(null);let k=!1;if(j!==void 0){const b=`${a}/properties`;for(const m in j){if(!(m in t))continue;const $=`${s}/${encodePointer(m)}`,N=validate(t[m],j[m],r,n,i,o,$,`${b}/${encodePointer(m)}`);if(N.valid)l[m]=R[m]=!0;else if(k=i,T.push({instanceLocation:s,keyword:"properties",keywordLocation:b,error:`Property "${m}" does not match schema.`},...N.errors),k)break}}if(!k&&H!==void 0){const b=`${a}/patternProperties`;for(const m in H){const $=new RegExp(m,"u"),N=H[m];for(const q in t){if(!$.test(q))continue;const se=`${s}/${encodePointer(q)}`,pe=validate(t[q],N,r,n,i,o,se,`${b}/${encodePointer(m)}`);pe.valid?l[q]=R[q]=!0:(k=i,T.push({instanceLocation:s,keyword:"patternProperties",keywordLocation:b,error:`Property "${q}" matches pattern "${m}" but does not match associated schema.`},...pe.errors))}}}if(!k&&W!==void 0){const b=`${a}/additionalProperties`;for(const m in t){if(R[m])continue;const $=`${s}/${encodePointer(m)}`,N=validate(t[m],W,r,n,i,o,$,b);N.valid?l[m]=!0:(k=i,T.push({instanceLocation:s,keyword:"additionalProperties",keywordLocation:b,error:`Property "${m}" does not match additional properties schema.`},...N.errors))}}else if(!k&&te!==void 0){const b=`${a}/unevaluatedProperties`;for(const m in t)if(!l[m]){const $=`${s}/${encodePointer(m)}`,N=validate(t[m],te,r,n,i,o,$,b);N.valid?l[m]=!0:T.push({instanceLocation:s,keyword:"unevaluatedProperties",keywordLocation:b,error:`Property "${m}" does not match unevaluated properties schema.`},...N.errors)}}}else if(u==="array"){M!==void 0&&t.length>M&&T.push({instanceLocation:s,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${t.length} > ${M}).`}),E!==void 0&&t.length<E&&T.push({instanceLocation:s,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${t.length} < ${E}).`});const D=t.length;let R=0,k=!1;if(de!==void 0){const b=`${a}/prefixItems`,m=Math.min(de.length,D);for(;R<m;R++){const $=validate(t[R],de[R],r,n,i,o,`${s}/${R}`,`${b}/${R}`);if(l[R]=!0,!$.valid&&(k=i,T.push({instanceLocation:s,keyword:"prefixItems",keywordLocation:b,error:"Items did not match schema."},...$.errors),k))break}}if(c!==void 0){const b=`${a}/items`;if(Array.isArray(c)){const m=Math.min(c.length,D);for(;R<m;R++){const $=validate(t[R],c[R],r,n,i,o,`${s}/${R}`,`${b}/${R}`);if(l[R]=!0,!$.valid&&(k=i,T.push({instanceLocation:s,keyword:"items",keywordLocation:b,error:"Items did not match schema."},...$.errors),k))break}}else for(;R<D;R++){const m=validate(t[R],c,r,n,i,o,`${s}/${R}`,b);if(l[R]=!0,!m.valid&&(k=i,T.push({instanceLocation:s,keyword:"items",keywordLocation:b,error:"Items did not match schema."},...m.errors),k))break}if(!k&&v!==void 0){const m=`${a}/additionalItems`;for(;R<D;R++){const $=validate(t[R],v,r,n,i,o,`${s}/${R}`,m);l[R]=!0,$.valid||(k=i,T.push({instanceLocation:s,keyword:"additionalItems",keywordLocation:m,error:"Items did not match additional items schema."},...$.errors))}}}if(_!==void 0)if(D===0&&P===void 0)T.push({instanceLocation:s,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(P!==void 0&&D<P)T.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${D}) than minContains (${P}).`});else{const b=`${a}/contains`,m=T.length;let $=0;for(let N=0;N<D;N++){const q=validate(t[N],_,r,n,i,o,`${s}/${N}`,b);q.valid?(l[N]=!0,$++):T.push(...q.errors)}$>=(P||0)&&(T.length=m),P===void 0&&B===void 0&&$===0?T.splice(m,0,{instanceLocation:s,keyword:"contains",keywordLocation:b,error:"Array does not contain item matching schema."}):P!==void 0&&$<P?T.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${P} items matching schema. Only ${$} items were found.`}):B!==void 0&&$>B&&T.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${B} items matching schema. ${$} items were found.`})}if(!k&&z!==void 0){const b=`${a}/unevaluatedItems`;for(R;R<D;R++){if(l[R])continue;const m=validate(t[R],z,r,n,i,o,`${s}/${R}`,b);l[R]=!0,m.valid||T.push({instanceLocation:s,keyword:"unevaluatedItems",keywordLocation:b,error:"Items did not match unevaluated items schema."},...m.errors)}}if(L)for(let b=0;b<D;b++){const m=t[b],$=typeof m=="object"&&m!==null;for(let N=0;N<D;N++){if(b===N)continue;const q=t[N];(m===q||$&&(typeof q=="object"&&q!==null)&&deepCompareStrict(m,q))&&(T.push({instanceLocation:s,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${b} and ${N}.`}),b=Number.MAX_SAFE_INTEGER,N=Number.MAX_SAFE_INTEGER)}}}else if(u==="number"){if(r==="4"?(U!==void 0&&(G===!0&&t<=U||t<U)&&T.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${t} is less than ${G?"or equal to ":""} ${U}.`}),Y!==void 0&&(ee===!0&&t>=Y||t>Y)&&T.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${t} is greater than ${ee?"or equal to ":""} ${Y}.`})):(U!==void 0&&t<U&&T.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${t} is less than ${U}.`}),Y!==void 0&&t>Y&&T.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${t} is greater than ${Y}.`}),G!==void 0&&t<=G&&T.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${t} is less than ${G}.`}),ee!==void 0&&t>=ee&&T.push({instanceLocation:s,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${t} is greater than or equal to ${ee}.`})),J!==void 0){const D=t%J;Math.abs(0-D)>=11920929e-14&&Math.abs(J-D)>=11920929e-14&&T.push({instanceLocation:s,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${t} is not a multiple of ${J}.`})}}else if(u==="string"){const D=ae===void 0&&ie===void 0?0:ucs2length(t);ae!==void 0&&D<ae&&T.push({instanceLocation:s,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${D} < ${ae}).`}),ie!==void 0&&D>ie&&T.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${D} > ${ie}).`}),ue!==void 0&&!new RegExp(ue,"u").test(t)&&T.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."}),F!==void 0&&format[F]&&!format[F](t)&&T.push({instanceLocation:s,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${F}".`})}return{valid:T.length===0,errors:T}}class Validator{schema;draft;shortCircuit;lookup;constructor(e,r="2019-09",n=!0){this.schema=e,this.draft=r,this.shortCircuit=n,this.lookup=dereference(e)}validate(e){return validate(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,r){r&&(e={...e,$id:r}),dereference(e,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(t){this._ontoolchange=t}registerTool(t,e){const r=e?.signal;if(r?.aborted){console.warn(`[WebMCPPolyfill] registerTool("${t?.name??"<unknown>"}") skipped: options.signal was already aborted.`);return}const n=normalizeToolDescriptor(t,this.tools);this.tools.set(n.name,n),this.notifyToolsChanged(),r&&r.addEventListener("abort",()=>{this.tools.delete(n.name)&&this.notifyToolsChanged()},{once:!0})}unregisterTool(t){this.warnUnregisterToolDeprecationOnce();const e=getToolNameForUnregister(t);this.tools.delete(e)&&this.notifyToolsChanged()}getTools(){return Promise.resolve(this.getRegisteredToolInfos())}executeTool(t,e,r){return this.executeToolByName(t.name,e,r,!1)}getTestingShim(){return this.testingShim||(this.testingShim=new PolyfillTestingShim(this)),this.testingShim}getToolInfos(){return[...this.tools.values()].map(t=>{let e;try{e=JSON.stringify(t.inputSchema??{type:"object"})}catch{e='{"type":"object"}'}return{name:t.name,description:t.description,inputSchema:e}})}getRegisteredToolInfos(){return this.getToolInfos().map(t=>{const e=this.tools.get(t.name);return{...t,title:e?.title??"",origin:globalThis.location?.origin??"",window:globalThis.window}})}async executeToolForTesting(t,e,r){return this.executeToolByName(t,e,r,!0)}async executeToolByName(t,e,r,n){if(r?.signal?.aborted)throw createUnknownError(TOOL_CANCELLED_MESSAGE);const i=this.tools.get(t);if(!i)throw createUnknownError(`Tool not found: ${t}`);const o=parseInputArgsJson(e),s=await validateArgsForTool(o,i);if(s)throw createUnknownError(s);let a=!0;const l={requestUserInteraction:async d=>{if(!a)throw new Error(`ModelContextClient for tool "${t}" is no longer active after execute() resolved`);if(typeof d!="function")throw new TypeError("requestUserInteraction(callback) requires a function callback");return d()}};try{const d=i.execute(o,l),u=await withAbortSignal(Promise.resolve(d),r?.signal);if(n)return toSerializedTestingResult(normalizeToolResponse(u));const f=JSON.stringify(u);return f===void 0?null:f}catch(d){throw createUnknownError(d instanceof Error?`${TOOL_INVOCATION_FAILED_MESSAGE}: ${d.message}`:TOOL_INVOCATION_FAILED_MESSAGE)}finally{a=!1}}notifyToolsChanged(){queueMicrotask(()=>{const t=new Event("toolchange");try{this._ontoolchange?.call(this,t)}catch(e){console.warn("[WebMCPPolyfill] navigator.modelContext.ontoolchange handler threw:",e)}this.dispatchEvent(t),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(t){super(),this.context=t}listTools(){return this.context.getToolInfos()}executeTool(t,e,r){return this.context.executeToolForTesting(t,e,r)}getCrossDocumentScriptToolResult(){return Promise.resolve("[]")}get ontoolchange(){return this._ontoolchange}set ontoolchange(t){this._ontoolchange=t}registerToolsChangedCallback(t){if(typeof t!="function")throw new TypeError("Failed to execute 'registerToolsChangedCallback' on 'ModelContextTesting': parameter 1 is not of type 'Function'.");this.addEventListener("toolchange",t)}dispatchToolChange(){const t=new Event("toolchange");try{this._ontoolchange?.call(this,t)}catch(e){console.warn("[WebMCPPolyfill] ontoolchange handler threw:",e)}this.dispatchEvent(t),this.dispatchEvent(new Event("toolschanged"))}};function createUnknownError(t){try{return new DOMException(t,"UnknownError")}catch{const e=new Error(t);return e.name="UnknownError",e}}function parseInputArgsJson(t){let e;try{e=JSON.parse(t)}catch{throw createUnknownError(FAILED_TO_PARSE_INPUT_ARGUMENTS_MESSAGE)}if(!e||typeof e!="object"||Array.isArray(e))throw createUnknownError(FAILED_TO_PARSE_INPUT_ARGUMENTS_MESSAGE);return e}function getToolNameForUnregister(t){if(typeof t=="string")return t;if(isPlainObject(t)&&typeof t.name=="string")return t.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(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function getStandardProps(t){if(!isPlainObject(t))return null;const e=t["~standard"];return isPlainObject(e)?e:null}function isStandardInputValidatorSchema(t){const e=getStandardProps(t);return!!(e&&e.version===1&&typeof e.validate=="function")}function isStandardInputJsonSchema(t){const e=getStandardProps(t);return!e||e.version!==1||!isPlainObject(e.jsonSchema)?!1:typeof e.jsonSchema.input=="function"}function createStandardValidatorFromJsonSchema(t){return{"~standard":{version:1,vendor:"@mcp-b/webmcp-polyfill-json-schema",validate(e){if(!isPlainObject(e))return{issues:[{message:"expected object arguments"}]};const r=validateArgsWithSchema(e,t);return r?{issues:[r]}:{value:e}}}}}function convertStandardInputSchema(t){for(const e of STANDARD_JSON_SCHEMA_TARGETS)try{const r=t["~standard"].jsonSchema.input({target:e});return validateInputSchema(r),r}catch(r){console.warn(`[WebMCPPolyfill] Standard JSON Schema conversion failed for target "${e}":`,r)}throw new Error("Failed to convert Standard JSON Schema inputSchema to a JSON Schema object")}function normalizeInputSchema(t){if(t===void 0){const r=DEFAULT_INPUT_SCHEMA;return{inputSchema:r,standardValidator:createStandardValidatorFromJsonSchema(r)}}if(isStandardInputJsonSchema(t)){const r=convertStandardInputSchema(t);return{inputSchema:r,standardValidator:createStandardValidatorFromJsonSchema(r)}}if(isStandardInputValidatorSchema(t))return{inputSchema:DEFAULT_INPUT_SCHEMA,standardValidator:t};if(validateInputSchema(t),Object.keys(t).length===0)return{inputSchema:DEFAULT_INPUT_SCHEMA,standardValidator:createStandardValidatorFromJsonSchema(DEFAULT_INPUT_SCHEMA)};const e=t.type===void 0?{type:"object",...t}:t;return{inputSchema:e,standardValidator:createStandardValidatorFromJsonSchema(e)}}function validateInputSchema(t){if(!isPlainObject(t))throw new Error("inputSchema must be a JSON Schema object");validateJsonSchemaNode(t,"$")}function validateJsonSchemaNode(t,e){const r=t.type;if(r!==void 0&&typeof r!="string"&&!(Array.isArray(r)&&r.every(a=>typeof a=="string"&&a.length>0)))throw new Error(`Invalid JSON Schema at ${e}: "type" must be a string or string[]`);const n=t.required;if(n!==void 0&&!(Array.isArray(n)&&n.every(a=>typeof a=="string")))throw new Error(`Invalid JSON Schema at ${e}: "required" must be an array of strings`);const i=t.properties;if(i!==void 0){if(!isPlainObject(i))throw new Error(`Invalid JSON Schema at ${e}: "properties" must be an object`);for(const[a,l]of Object.entries(i)){if(!isPlainObject(l))throw new Error(`Invalid JSON Schema at ${e}.properties.${a}: expected object schema`);validateJsonSchemaNode(l,`${e}.properties.${a}`)}}const o=t.items;if(o!==void 0)if(Array.isArray(o))for(const[a,l]of o.entries()){if(!isPlainObject(l))throw new Error(`Invalid JSON Schema at ${e}.items[${a}]: expected object schema`);validateJsonSchemaNode(l,`${e}.items[${a}]`)}else if(isPlainObject(o))validateJsonSchemaNode(o,`${e}.items`);else throw new Error(`Invalid JSON Schema at ${e}: "items" must be an object or object[]`);for(const a of["allOf","anyOf","oneOf"]){const l=t[a];if(l!==void 0){if(!Array.isArray(l))throw new Error(`Invalid JSON Schema at ${e}: "${a}" must be an array`);for(const[d,u]of l.entries()){if(!isPlainObject(u))throw new Error(`Invalid JSON Schema at ${e}.${a}[${d}]: expected object schema`);validateJsonSchemaNode(u,`${e}.${a}[${d}]`)}}}const s=t.not;if(s!==void 0){if(!isPlainObject(s))throw new Error(`Invalid JSON Schema at ${e}: "not" must be an object schema`);validateJsonSchemaNode(s,`${e}.not`)}try{JSON.stringify(t)}catch{throw new Error(`Invalid JSON Schema at ${e}: schema must be JSON-serializable`)}}function normalizeToolDescriptor(t,e){if(!t||typeof t!="object")throw new TypeError("registerTool(tool) requires a tool object");if(typeof t.name!="string"||t.name.length===0)throw new TypeError('Tool "name" must be a non-empty string');if(typeof t.description!="string"||t.description.length===0)throw new TypeError('Tool "description" must be a non-empty string');if(typeof t.execute!="function")throw new TypeError('Tool "execute" must be a function');if(e.has(t.name))throw new Error(`Tool already registered: ${t.name}`);const r=normalizeInputSchema(t.inputSchema),n=t.annotations,i=n?{...n,...n.readOnlyHint==="true"?{readOnlyHint:!0}:n.readOnlyHint==="false"?{readOnlyHint:!1}:{},...n.destructiveHint==="true"?{destructiveHint:!0}:n.destructiveHint==="false"?{destructiveHint:!1}:{},...n.idempotentHint==="true"?{idempotentHint:!0}:n.idempotentHint==="false"?{idempotentHint:!1}:{},...n.openWorldHint==="true"?{openWorldHint:!0}:n.openWorldHint==="false"?{openWorldHint:!1}:{}}:void 0;return{...t,...i?{annotations:i}:{},inputSchema:r.inputSchema,[STANDARD_VALIDATOR_SYMBOL]:r.standardValidator}}function validateArgsWithSchema(t,e){const r=new Validator(e,"2020-12",!0).validate(t);if(r.valid)return null;const n=r.errors[r.errors.length-1];return n?{message:n.error}:{message:"Input validation failed"}}function formatStandardIssuePath(t){if(!t||t.length===0)return null;const e=t.map(r=>isPlainObject(r)&&"key"in r?r.key:r).map(r=>String(r)).filter(r=>r.length>0);return e.length===0?null:e.join(".")}async function validateArgsWithStandardSchema(t,e){let r;try{r=await Promise.resolve(e["~standard"].validate(t))}catch(o){const s=o instanceof Error?`: ${o.message}`:"";return console.error("[WebMCPPolyfill] Standard Schema validation threw unexpectedly:",o),`Input validation error: schema validation failed${s}`}if(!r.issues||r.issues.length===0)return null;const n=r.issues[0];if(!n)return"Input validation error";const i=formatStandardIssuePath(n?.path);return i?`Input validation error: ${n.message} at ${i}`:`Input validation error: ${n.message}`}async function validateArgsForTool(t,e){return validateArgsWithStandardSchema(t,e[STANDARD_VALIDATOR_SYMBOL])}function isCallToolResult(t){return isPlainObject(t)&&Array.isArray(t.content)}function isJsonPrimitive(t){return t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"}function isJsonValue(t){return isJsonPrimitive(t)?Number.isFinite(t)||typeof t!="number":Array.isArray(t)?t.every(e=>isJsonValue(e)):isPlainObject(t)?Object.values(t).every(e=>isJsonValue(e)):!1}function toStructuredContent(t){if(!(!isPlainObject(t)||!isJsonValue(t)))return t}function serializeTextContent(t){if(typeof t=="string")return t;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}function normalizeToolResponse(t){if(isCallToolResult(t))return t;const e=toStructuredContent(t);return{content:[{type:"text",text:serializeTextContent(t)}],...e?{structuredContent:e}:{},isError:!1}}function getFirstTextBlock(t){for(const e of t.content??[])if(e.type==="text"&&"text"in e&&typeof e.text=="string")return e.text;return null}function toSerializedTestingResult(t){if(t.isError)throw createUnknownError(getFirstTextBlock(t)?.replace(/^Error:\s*/i,"").trim()||TOOL_INVOCATION_FAILED_MESSAGE);const e=t.metadata;if(e&&typeof e=="object"&&e.willNavigate)return null;try{return JSON.stringify(t)}catch{throw createUnknownError(TOOL_INVOCATION_FAILED_MESSAGE)}}function withAbortSignal(t,e){return e?e.aborted?Promise.reject(createUnknownError(TOOL_CANCELLED_MESSAGE)):new Promise((r,n)=>{const i=()=>{o(),n(createUnknownError(TOOL_CANCELLED_MESSAGE))},o=()=>{e.removeEventListener("abort",i)};e.addEventListener("abort",i,{once:!0}),t.then(s=>{o(),r(s)},s=>{o(),n(s)})}):t}function getNavigator(){return typeof navigator<"u"?navigator:null}function getDocument(){return typeof document<"u"?document:null}function defineNavigatorProperty(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,writable:!1,value:r})}function defineDocumentModelContextProperty(t,e){Object.defineProperty(t,"modelContext",{configurable:!0,enumerable:!0,writable:!1,value:e})}let navigatorModelContextDeprecationWarned=!1;function defineDeprecatedNavigatorModelContext(t,e){Object.defineProperty(t,"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.")),e}})}function initializeWebMCPPolyfill(t){const e=getNavigator(),r=getDocument();if(!e&&!r||r?.modelContext)return;const i=e?.modelContext,o=!!i;if(installState.installed&&cleanupWebMCPPolyfill(),r&&i){installState.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(r,"modelContext"),defineDocumentModelContextProperty(r,i),installState.installedDocumentModelContext=!0,installState.installed=!0;return}if(o)return;const s=new StrictWebMCPContext,a=s;if(a[POLYFILL_MARKER_PROPERTY]=!0,r&&(installState.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(r,"modelContext"),defineDocumentModelContextProperty(r,a),installState.installedDocumentModelContext=!0),e){installState.previousNavigatorModelContextDescriptor=Object.getOwnPropertyDescriptor(e,"modelContext"),installState.previousNavigatorModelContextTestingDescriptor=Object.getOwnPropertyDescriptor(e,"modelContextTesting"),navigatorModelContextDeprecationWarned=!1,defineDeprecatedNavigatorModelContext(e,a),installState.installedNavigatorModelContext=!0;const l=t?.installTestingShim??"if-missing",d=!!e.modelContextTesting;(l==="always"||(l===!0||l==="if-missing")&&!d)&&(defineNavigatorProperty(e,"modelContextTesting",s.getTestingShim()),installState.installedNavigatorModelContextTesting=!0)}installState.installed=!0}function cleanupWebMCPPolyfill(){if(!installState.installed)return;const t=(n,i,o)=>{if(o){Object.defineProperty(n,i,o);return}delete n[i]},e=getNavigator(),r=getDocument();r&&installState.installedDocumentModelContext&&t(r,"modelContext",installState.previousDocumentModelContextDescriptor),e&&installState.installedNavigatorModelContext&&t(e,"modelContext",installState.previousNavigatorModelContextDescriptor),e&&installState.installedNavigatorModelContextTesting&&t(e,"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 t=window.__webMCPPolyfillOptions;if(t?.autoInitialize!==!1)try{initializeWebMCPPolyfill(t)}catch(e){console.error("[WebMCPPolyfill] Auto-initialization failed:",e)}}const randomUUID=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)}),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 t=document.createElement("style");t.textContent=`
4
+ - `)}`,new Error(y)}const S=`${a}/$ref`,v=validate(t,$,r,n,i,o,s,S,l);if(v.valid||E.push({instanceLocation:s,keyword:"$ref",keywordLocation:S,error:"A subschema had errors."},...v.errors),r==="4"||r==="7")return{valid:E.length===0,errors:E}}if(Array.isArray(b)){let D=b.length,$=!1;for(let S=0;S<D;S++)if(u===b[S]||b[S]==="integer"&&u==="number"&&t%1===0&&t===t){$=!0;break}$||E.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${b.join('", "')}".`})}else b==="integer"?(u!=="number"||t%1||t!==t)&&E.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${b}".`}):b!==void 0&&u!==b&&E.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${b}".`});if(P!==void 0&&(u==="object"||u==="array"?deepCompareStrict(t,P)||E.push({instanceLocation:s,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(P)}.`}):t!==P&&E.push({instanceLocation:s,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(P)}.`})),w!==void 0&&(u==="object"||u==="array"?w.some(D=>deepCompareStrict(t,D))||E.push({instanceLocation:s,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(w)}.`}):w.some(D=>t===D)||E.push({instanceLocation:s,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(w)}.`})),m!==void 0){const D=`${a}/not`;validate(t,m,r,n,i,o,s,D).valid&&E.push({instanceLocation:s,keyword:"not",keywordLocation:D,error:'Instance matched "not" schema.'})}let fe=[];if(A!==void 0){const D=`${a}/anyOf`,$=E.length;let S=!1;for(let v=0;v<A.length;v++){const y=A[v],L=Object.create(l),N=validate(t,y,r,n,i,g===!0?o:null,s,`${D}/${v}`,L);E.push(...N.errors),S=S||N.valid,N.valid&&fe.push(L)}S?E.length=$:E.splice($,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:D,error:"Instance does not match any subschemas."})}if(T!==void 0){const D=`${a}/allOf`,$=E.length;let S=!0;for(let v=0;v<T.length;v++){const y=T[v],L=Object.create(l),N=validate(t,y,r,n,i,g===!0?o:null,s,`${D}/${v}`,L);E.push(...N.errors),S=S&&N.valid,N.valid&&fe.push(L)}S?E.length=$:E.splice($,0,{instanceLocation:s,keyword:"allOf",keywordLocation:D,error:"Instance does not match every subschema."})}if(k!==void 0){const D=`${a}/oneOf`,$=E.length,S=k.filter((v,y)=>{const L=Object.create(l),N=validate(t,v,r,n,i,g===!0?o:null,s,`${D}/${y}`,L);return E.push(...N.errors),N.valid&&fe.push(L),N.valid}).length;S===1?E.length=$:E.splice($,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:D,error:`Instance does not match exactly one subschema (${S} matches).`})}if((u==="object"||u==="array")&&Object.assign(l,...fe),Z!==void 0){const D=`${a}/if`;if(validate(t,Z,r,n,i,o,s,D,l).valid){if(R!==void 0){const S=validate(t,R,r,n,i,o,s,`${a}/then`,l);S.valid||E.push({instanceLocation:s,keyword:"if",keywordLocation:D,error:'Instance does not match "then" schema.'},...S.errors)}}else if(V!==void 0){const S=validate(t,V,r,n,i,o,s,`${a}/else`,l);S.valid||E.push({instanceLocation:s,keyword:"if",keywordLocation:D,error:'Instance does not match "else" schema.'},...S.errors)}}if(u==="object"){if(p!==void 0)for(const v of p)v in t||E.push({instanceLocation:s,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${v}".`});const D=Object.keys(t);if(X!==void 0&&D.length<X&&E.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${X} properties.`}),te!==void 0&&D.length>te&&E.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${te} properties.`}),oe!==void 0){const v=`${a}/propertyNames`;for(const y in t){const L=`${s}/${encodePointer(y)}`,N=validate(y,oe,r,n,i,o,L,v);N.valid||E.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:v,error:`Property name "${y}" does not match schema.`},...N.errors)}}if(re!==void 0){const v=`${a}/dependantRequired`;for(const y in re)if(y in t){const L=re[y];for(const N of L)N in t||E.push({instanceLocation:s,keyword:"dependentRequired",keywordLocation:v,error:`Instance has "${y}" but does not have "${N}".`})}}if(Q!==void 0)for(const v in Q){const y=`${a}/dependentSchemas`;if(v in t){const L=validate(t,Q[v],r,n,i,o,s,`${y}/${encodePointer(v)}`,l);L.valid||E.push({instanceLocation:s,keyword:"dependentSchemas",keywordLocation:y,error:`Instance has "${v}" but does not match dependant schema.`},...L.errors)}}if(K!==void 0){const v=`${a}/dependencies`;for(const y in K)if(y in t){const L=K[y];if(Array.isArray(L))for(const N of L)N in t||E.push({instanceLocation:s,keyword:"dependencies",keywordLocation:v,error:`Instance has "${y}" but does not have "${N}".`});else{const N=validate(t,L,r,n,i,o,s,`${v}/${encodePointer(y)}`);N.valid||E.push({instanceLocation:s,keyword:"dependencies",keywordLocation:v,error:`Instance has "${y}" but does not match dependant schema.`},...N.errors)}}}const $=Object.create(null);let S=!1;if(H!==void 0){const v=`${a}/properties`;for(const y in H){if(!(y in t))continue;const L=`${s}/${encodePointer(y)}`,N=validate(t[y],H[y],r,n,i,o,L,`${v}/${encodePointer(y)}`);if(N.valid)l[y]=$[y]=!0;else if(S=i,E.push({instanceLocation:s,keyword:"properties",keywordLocation:v,error:`Property "${y}" does not match schema.`},...N.errors),S)break}}if(!S&&B!==void 0){const v=`${a}/patternProperties`;for(const y in B){const L=new RegExp(y,"u"),N=B[y];for(const q in t){if(!L.test(q))continue;const se=`${s}/${encodePointer(q)}`,pe=validate(t[q],N,r,n,i,o,se,`${v}/${encodePointer(y)}`);pe.valid?l[q]=$[q]=!0:(S=i,E.push({instanceLocation:s,keyword:"patternProperties",keywordLocation:v,error:`Property "${q}" matches pattern "${y}" but does not match associated schema.`},...pe.errors))}}}if(!S&&G!==void 0){const v=`${a}/additionalProperties`;for(const y in t){if($[y])continue;const L=`${s}/${encodePointer(y)}`,N=validate(t[y],G,r,n,i,o,L,v);N.valid?l[y]=!0:(S=i,E.push({instanceLocation:s,keyword:"additionalProperties",keywordLocation:v,error:`Property "${y}" does not match additional properties schema.`},...N.errors))}}else if(!S&&ie!==void 0){const v=`${a}/unevaluatedProperties`;for(const y in t)if(!l[y]){const L=`${s}/${encodePointer(y)}`,N=validate(t[y],ie,r,n,i,o,L,v);N.valid?l[y]=!0:E.push({instanceLocation:s,keyword:"unevaluatedProperties",keywordLocation:v,error:`Property "${y}" does not match unevaluated properties schema.`},...N.errors)}}}else if(u==="array"){M!==void 0&&t.length>M&&E.push({instanceLocation:s,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${t.length} > ${M}).`}),C!==void 0&&t.length<C&&E.push({instanceLocation:s,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${t.length} < ${C}).`});const D=t.length;let $=0,S=!1;if(ce!==void 0){const v=`${a}/prefixItems`,y=Math.min(ce.length,D);for(;$<y;$++){const L=validate(t[$],ce[$],r,n,i,o,`${s}/${$}`,`${v}/${$}`);if(l[$]=!0,!L.valid&&(S=i,E.push({instanceLocation:s,keyword:"prefixItems",keywordLocation:v,error:"Items did not match schema."},...L.errors),S))break}}if(d!==void 0){const v=`${a}/items`;if(Array.isArray(d)){const y=Math.min(d.length,D);for(;$<y;$++){const L=validate(t[$],d[$],r,n,i,o,`${s}/${$}`,`${v}/${$}`);if(l[$]=!0,!L.valid&&(S=i,E.push({instanceLocation:s,keyword:"items",keywordLocation:v,error:"Items did not match schema."},...L.errors),S))break}}else for(;$<D;$++){const y=validate(t[$],d,r,n,i,o,`${s}/${$}`,v);if(l[$]=!0,!y.valid&&(S=i,E.push({instanceLocation:s,keyword:"items",keywordLocation:v,error:"Items did not match schema."},...y.errors),S))break}if(!S&&x!==void 0){const y=`${a}/additionalItems`;for(;$<D;$++){const L=validate(t[$],x,r,n,i,o,`${s}/${$}`,y);l[$]=!0,L.valid||(S=i,E.push({instanceLocation:s,keyword:"additionalItems",keywordLocation:y,error:"Items did not match additional items schema."},...L.errors))}}}if(_!==void 0)if(D===0&&I===void 0)E.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&&D<I)E.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${D}) than minContains (${I}).`});else{const v=`${a}/contains`,y=E.length;let L=0;for(let N=0;N<D;N++){const q=validate(t[N],_,r,n,i,o,`${s}/${N}`,v);q.valid?(l[N]=!0,L++):E.push(...q.errors)}L>=(I||0)&&(E.length=y),I===void 0&&z===void 0&&L===0?E.splice(y,0,{instanceLocation:s,keyword:"contains",keywordLocation:v,error:"Array does not contain item matching schema."}):I!==void 0&&L<I?E.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${I} items matching schema. Only ${L} items were found.`}):z!==void 0&&L>z&&E.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${z} items matching schema. ${L} items were found.`})}if(!S&&U!==void 0){const v=`${a}/unevaluatedItems`;for($;$<D;$++){if(l[$])continue;const y=validate(t[$],U,r,n,i,o,`${s}/${$}`,v);l[$]=!0,y.valid||E.push({instanceLocation:s,keyword:"unevaluatedItems",keywordLocation:v,error:"Items did not match unevaluated items schema."},...y.errors)}}if(O)for(let v=0;v<D;v++){const y=t[v],L=typeof y=="object"&&y!==null;for(let N=0;N<D;N++){if(v===N)continue;const q=t[N];(y===q||L&&(typeof q=="object"&&q!==null)&&deepCompareStrict(y,q))&&(E.push({instanceLocation:s,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${v} and ${N}.`}),v=Number.MAX_SAFE_INTEGER,N=Number.MAX_SAFE_INTEGER)}}}else if(u==="number"){if(r==="4"?(F!==void 0&&(W===!0&&t<=F||t<F)&&E.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${t} is less than ${W?"or equal to ":""} ${F}.`}),Y!==void 0&&(ee===!0&&t>=Y||t>Y)&&E.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${t} is greater than ${ee?"or equal to ":""} ${Y}.`})):(F!==void 0&&t<F&&E.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${t} is less than ${F}.`}),Y!==void 0&&t>Y&&E.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${t} is greater than ${Y}.`}),W!==void 0&&t<=W&&E.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${t} is less than ${W}.`}),ee!==void 0&&t>=ee&&E.push({instanceLocation:s,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${t} is greater than or equal to ${ee}.`})),J!==void 0){const D=t%J;Math.abs(0-D)>=11920929e-14&&Math.abs(J-D)>=11920929e-14&&E.push({instanceLocation:s,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${t} is not a multiple of ${J}.`})}}else if(u==="string"){const D=ae===void 0&&ne===void 0?0:ucs2length(t);ae!==void 0&&D<ae&&E.push({instanceLocation:s,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${D} < ${ae}).`}),ne!==void 0&&D>ne&&E.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${D} > ${ne}).`}),ue!==void 0&&!new RegExp(ue,"u").test(t)&&E.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."}),j!==void 0&&format[j]&&!format[j](t)&&E.push({instanceLocation:s,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${j}".`})}return{valid:E.length===0,errors:E}}class Validator{schema;draft;shortCircuit;lookup;constructor(e,r="2019-09",n=!0){this.schema=e,this.draft=r,this.shortCircuit=n,this.lookup=dereference(e)}validate(e){return validate(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,r){r&&(e={...e,$id:r}),dereference(e,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(t){this._ontoolchange=t}registerTool(t,e){const r=e?.signal;if(r?.aborted){console.warn(`[WebMCPPolyfill] registerTool("${t?.name??"<unknown>"}") skipped: options.signal was already aborted.`);return}const n=normalizeToolDescriptor(t,this.tools);this.tools.set(n.name,n),this.notifyToolsChanged(),r&&r.addEventListener("abort",()=>{this.tools.delete(n.name)&&this.notifyToolsChanged()},{once:!0})}unregisterTool(t){this.warnUnregisterToolDeprecationOnce();const e=getToolNameForUnregister(t);this.tools.delete(e)&&this.notifyToolsChanged()}getTools(){return Promise.resolve(this.getRegisteredToolInfos())}executeTool(t,e,r){return this.executeToolByName(t.name,e,r,!1)}getTestingShim(){return this.testingShim||(this.testingShim=new PolyfillTestingShim(this)),this.testingShim}getToolInfos(){return[...this.tools.values()].map(t=>{let e;try{e=JSON.stringify(t.inputSchema??{type:"object"})}catch{e='{"type":"object"}'}return{name:t.name,description:t.description,inputSchema:e}})}getRegisteredToolInfos(){return this.getToolInfos().map(t=>{const e=this.tools.get(t.name);return{...t,title:e?.title??"",origin:globalThis.location?.origin??"",window:globalThis.window}})}async executeToolForTesting(t,e,r){return this.executeToolByName(t,e,r,!0)}async executeToolByName(t,e,r,n){if(r?.signal?.aborted)throw createUnknownError(TOOL_CANCELLED_MESSAGE);const i=this.tools.get(t);if(!i)throw createUnknownError(`Tool not found: ${t}`);const o=parseInputArgsJson(e),s=await validateArgsForTool(o,i);if(s)throw createUnknownError(s);let a=!0;const l={requestUserInteraction:async c=>{if(!a)throw new Error(`ModelContextClient for tool "${t}" 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=i.execute(o,l),u=await withAbortSignal(Promise.resolve(c),r?.signal);if(n)return toSerializedTestingResult(normalizeToolResponse(u));const h=JSON.stringify(u);return h===void 0?null:h}catch(c){throw createUnknownError(c instanceof Error?`${TOOL_INVOCATION_FAILED_MESSAGE}: ${c.message}`:TOOL_INVOCATION_FAILED_MESSAGE)}finally{a=!1}}notifyToolsChanged(){queueMicrotask(()=>{const t=new Event("toolchange");try{this._ontoolchange?.call(this,t)}catch(e){console.warn("[WebMCPPolyfill] navigator.modelContext.ontoolchange handler threw:",e)}this.dispatchEvent(t),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(t){super(),this.context=t}listTools(){return this.context.getToolInfos()}executeTool(t,e,r){return this.context.executeToolForTesting(t,e,r)}getCrossDocumentScriptToolResult(){return Promise.resolve("[]")}get ontoolchange(){return this._ontoolchange}set ontoolchange(t){this._ontoolchange=t}registerToolsChangedCallback(t){if(typeof t!="function")throw new TypeError("Failed to execute 'registerToolsChangedCallback' on 'ModelContextTesting': parameter 1 is not of type 'Function'.");this.addEventListener("toolchange",t)}dispatchToolChange(){const t=new Event("toolchange");try{this._ontoolchange?.call(this,t)}catch(e){console.warn("[WebMCPPolyfill] ontoolchange handler threw:",e)}this.dispatchEvent(t),this.dispatchEvent(new Event("toolschanged"))}};function createUnknownError(t){try{return new DOMException(t,"UnknownError")}catch{const e=new Error(t);return e.name="UnknownError",e}}function parseInputArgsJson(t){let e;try{e=JSON.parse(t)}catch{throw createUnknownError(FAILED_TO_PARSE_INPUT_ARGUMENTS_MESSAGE)}if(!e||typeof e!="object"||Array.isArray(e))throw createUnknownError(FAILED_TO_PARSE_INPUT_ARGUMENTS_MESSAGE);return e}function getToolNameForUnregister(t){if(typeof t=="string")return t;if(isPlainObject(t)&&typeof t.name=="string")return t.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(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function getStandardProps(t){if(!isPlainObject(t))return null;const e=t["~standard"];return isPlainObject(e)?e:null}function isStandardInputValidatorSchema(t){const e=getStandardProps(t);return!!(e&&e.version===1&&typeof e.validate=="function")}function isStandardInputJsonSchema(t){const e=getStandardProps(t);return!e||e.version!==1||!isPlainObject(e.jsonSchema)?!1:typeof e.jsonSchema.input=="function"}function createStandardValidatorFromJsonSchema(t){return{"~standard":{version:1,vendor:"@mcp-b/webmcp-polyfill-json-schema",validate(e){if(!isPlainObject(e))return{issues:[{message:"expected object arguments"}]};const r=validateArgsWithSchema(e,t);return r?{issues:[r]}:{value:e}}}}}function convertStandardInputSchema(t){for(const e of STANDARD_JSON_SCHEMA_TARGETS)try{const r=t["~standard"].jsonSchema.input({target:e});return validateInputSchema(r),r}catch(r){console.warn(`[WebMCPPolyfill] Standard JSON Schema conversion failed for target "${e}":`,r)}throw new Error("Failed to convert Standard JSON Schema inputSchema to a JSON Schema object")}function normalizeInputSchema(t){if(t===void 0){const r=DEFAULT_INPUT_SCHEMA;return{inputSchema:r,standardValidator:createStandardValidatorFromJsonSchema(r)}}if(isStandardInputJsonSchema(t)){const r=convertStandardInputSchema(t);return{inputSchema:r,standardValidator:createStandardValidatorFromJsonSchema(r)}}if(isStandardInputValidatorSchema(t))return{inputSchema:DEFAULT_INPUT_SCHEMA,standardValidator:t};if(validateInputSchema(t),Object.keys(t).length===0)return{inputSchema:DEFAULT_INPUT_SCHEMA,standardValidator:createStandardValidatorFromJsonSchema(DEFAULT_INPUT_SCHEMA)};const e=t.type===void 0?{type:"object",...t}:t;return{inputSchema:e,standardValidator:createStandardValidatorFromJsonSchema(e)}}function validateInputSchema(t){if(!isPlainObject(t))throw new Error("inputSchema must be a JSON Schema object");validateJsonSchemaNode(t,"$")}function validateJsonSchemaNode(t,e){const r=t.type;if(r!==void 0&&typeof r!="string"&&!(Array.isArray(r)&&r.every(a=>typeof a=="string"&&a.length>0)))throw new Error(`Invalid JSON Schema at ${e}: "type" must be a string or string[]`);const n=t.required;if(n!==void 0&&!(Array.isArray(n)&&n.every(a=>typeof a=="string")))throw new Error(`Invalid JSON Schema at ${e}: "required" must be an array of strings`);const i=t.properties;if(i!==void 0){if(!isPlainObject(i))throw new Error(`Invalid JSON Schema at ${e}: "properties" must be an object`);for(const[a,l]of Object.entries(i)){if(!isPlainObject(l))throw new Error(`Invalid JSON Schema at ${e}.properties.${a}: expected object schema`);validateJsonSchemaNode(l,`${e}.properties.${a}`)}}const o=t.items;if(o!==void 0)if(Array.isArray(o))for(const[a,l]of o.entries()){if(!isPlainObject(l))throw new Error(`Invalid JSON Schema at ${e}.items[${a}]: expected object schema`);validateJsonSchemaNode(l,`${e}.items[${a}]`)}else if(isPlainObject(o))validateJsonSchemaNode(o,`${e}.items`);else throw new Error(`Invalid JSON Schema at ${e}: "items" must be an object or object[]`);for(const a of["allOf","anyOf","oneOf"]){const l=t[a];if(l!==void 0){if(!Array.isArray(l))throw new Error(`Invalid JSON Schema at ${e}: "${a}" must be an array`);for(const[c,u]of l.entries()){if(!isPlainObject(u))throw new Error(`Invalid JSON Schema at ${e}.${a}[${c}]: expected object schema`);validateJsonSchemaNode(u,`${e}.${a}[${c}]`)}}}const s=t.not;if(s!==void 0){if(!isPlainObject(s))throw new Error(`Invalid JSON Schema at ${e}: "not" must be an object schema`);validateJsonSchemaNode(s,`${e}.not`)}try{JSON.stringify(t)}catch{throw new Error(`Invalid JSON Schema at ${e}: schema must be JSON-serializable`)}}function normalizeToolDescriptor(t,e){if(!t||typeof t!="object")throw new TypeError("registerTool(tool) requires a tool object");if(typeof t.name!="string"||t.name.length===0)throw new TypeError('Tool "name" must be a non-empty string');if(typeof t.description!="string"||t.description.length===0)throw new TypeError('Tool "description" must be a non-empty string');if(typeof t.execute!="function")throw new TypeError('Tool "execute" must be a function');if(e.has(t.name))throw new Error(`Tool already registered: ${t.name}`);const r=normalizeInputSchema(t.inputSchema),n=t.annotations,i=n?{...n,...n.readOnlyHint==="true"?{readOnlyHint:!0}:n.readOnlyHint==="false"?{readOnlyHint:!1}:{},...n.destructiveHint==="true"?{destructiveHint:!0}:n.destructiveHint==="false"?{destructiveHint:!1}:{},...n.idempotentHint==="true"?{idempotentHint:!0}:n.idempotentHint==="false"?{idempotentHint:!1}:{},...n.openWorldHint==="true"?{openWorldHint:!0}:n.openWorldHint==="false"?{openWorldHint:!1}:{}}:void 0;return{...t,...i?{annotations:i}:{},inputSchema:r.inputSchema,[STANDARD_VALIDATOR_SYMBOL]:r.standardValidator}}function validateArgsWithSchema(t,e){const r=new Validator(e,"2020-12",!0).validate(t);if(r.valid)return null;const n=r.errors[r.errors.length-1];return n?{message:n.error}:{message:"Input validation failed"}}function formatStandardIssuePath(t){if(!t||t.length===0)return null;const e=t.map(r=>isPlainObject(r)&&"key"in r?r.key:r).map(r=>String(r)).filter(r=>r.length>0);return e.length===0?null:e.join(".")}async function validateArgsWithStandardSchema(t,e){let r;try{r=await Promise.resolve(e["~standard"].validate(t))}catch(o){const s=o instanceof Error?`: ${o.message}`:"";return console.error("[WebMCPPolyfill] Standard Schema validation threw unexpectedly:",o),`Input validation error: schema validation failed${s}`}if(!r.issues||r.issues.length===0)return null;const n=r.issues[0];if(!n)return"Input validation error";const i=formatStandardIssuePath(n?.path);return i?`Input validation error: ${n.message} at ${i}`:`Input validation error: ${n.message}`}async function validateArgsForTool(t,e){return validateArgsWithStandardSchema(t,e[STANDARD_VALIDATOR_SYMBOL])}function isCallToolResult(t){return isPlainObject(t)&&Array.isArray(t.content)}function isJsonPrimitive(t){return t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"}function isJsonValue(t){return isJsonPrimitive(t)?Number.isFinite(t)||typeof t!="number":Array.isArray(t)?t.every(e=>isJsonValue(e)):isPlainObject(t)?Object.values(t).every(e=>isJsonValue(e)):!1}function toStructuredContent(t){if(!(!isPlainObject(t)||!isJsonValue(t)))return t}function serializeTextContent(t){if(typeof t=="string")return t;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}function normalizeToolResponse(t){if(isCallToolResult(t))return t;const e=toStructuredContent(t);return{content:[{type:"text",text:serializeTextContent(t)}],...e?{structuredContent:e}:{},isError:!1}}function getFirstTextBlock(t){for(const e of t.content??[])if(e.type==="text"&&"text"in e&&typeof e.text=="string")return e.text;return null}function toSerializedTestingResult(t){if(t.isError)throw createUnknownError(getFirstTextBlock(t)?.replace(/^Error:\s*/i,"").trim()||TOOL_INVOCATION_FAILED_MESSAGE);const e=t.metadata;if(e&&typeof e=="object"&&e.willNavigate)return null;try{return JSON.stringify(t)}catch{throw createUnknownError(TOOL_INVOCATION_FAILED_MESSAGE)}}function withAbortSignal(t,e){return e?e.aborted?Promise.reject(createUnknownError(TOOL_CANCELLED_MESSAGE)):new Promise((r,n)=>{const i=()=>{o(),n(createUnknownError(TOOL_CANCELLED_MESSAGE))},o=()=>{e.removeEventListener("abort",i)};e.addEventListener("abort",i,{once:!0}),t.then(s=>{o(),r(s)},s=>{o(),n(s)})}):t}function getNavigator(){return typeof navigator<"u"?navigator:null}function getDocument(){return typeof document<"u"?document:null}function defineNavigatorProperty(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,writable:!1,value:r})}function defineDocumentModelContextProperty(t,e){Object.defineProperty(t,"modelContext",{configurable:!0,enumerable:!0,writable:!1,value:e})}let navigatorModelContextDeprecationWarned=!1;function defineDeprecatedNavigatorModelContext(t,e){Object.defineProperty(t,"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.")),e}})}function initializeWebMCPPolyfill(t){const e=getNavigator(),r=getDocument();if(!e&&!r||r?.modelContext)return;const i=e?.modelContext,o=!!i;if(installState.installed&&cleanupWebMCPPolyfill(),r&&i){installState.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(r,"modelContext"),defineDocumentModelContextProperty(r,i),installState.installedDocumentModelContext=!0,installState.installed=!0;return}if(o)return;const s=new StrictWebMCPContext,a=s;if(a[POLYFILL_MARKER_PROPERTY]=!0,r&&(installState.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(r,"modelContext"),defineDocumentModelContextProperty(r,a),installState.installedDocumentModelContext=!0),e){installState.previousNavigatorModelContextDescriptor=Object.getOwnPropertyDescriptor(e,"modelContext"),installState.previousNavigatorModelContextTestingDescriptor=Object.getOwnPropertyDescriptor(e,"modelContextTesting"),navigatorModelContextDeprecationWarned=!1,defineDeprecatedNavigatorModelContext(e,a),installState.installedNavigatorModelContext=!0;const l=t?.installTestingShim??"if-missing",c=!!e.modelContextTesting;(l==="always"||(l===!0||l==="if-missing")&&!c)&&(defineNavigatorProperty(e,"modelContextTesting",s.getTestingShim()),installState.installedNavigatorModelContextTesting=!0)}installState.installed=!0}function cleanupWebMCPPolyfill(){if(!installState.installed)return;const t=(n,i,o)=>{if(o){Object.defineProperty(n,i,o);return}delete n[i]},e=getNavigator(),r=getDocument();r&&installState.installedDocumentModelContext&&t(r,"modelContext",installState.previousDocumentModelContextDescriptor),e&&installState.installedNavigatorModelContext&&t(e,"modelContext",installState.previousNavigatorModelContextDescriptor),e&&installState.installedNavigatorModelContextTesting&&t(e,"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 t=window.__webMCPPolyfillOptions;if(t?.autoInitialize!==!1)try{initializeWebMCPPolyfill(t)}catch(e){console.error("[WebMCPPolyfill] Auto-initialization failed:",e)}}const randomUUID=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)}),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 t=document.createElement("style");t.textContent=`
5
5
  .${BODY_GLOW_CLASS} {
6
6
  position: relative;
7
7
  }
@@ -169,11 +169,11 @@ Known schemas:
169
169
  transform: scale(1) translateY(0);
170
170
  }
171
171
  }
172
- `,document.head.appendChild(t),styleElement=t}function ensureOverlayElement(){if(!ensureDomReady()||overlayElement)return;ensureStyleElement();const t=document.createElement("div");t.className="next-sdk-tool-overlay";const e=document.createElement("div");e.className="next-sdk-tool-overlay__glow-ring";const r=document.createElement("div");r.className="next-sdk-tool-overlay__panel";const n=document.createElement("div");n.className="next-sdk-tool-overlay__indicator";const i=document.createElement("div");i.className="next-sdk-tool-overlay__indicator-orbit";const o=document.createElement("div");o.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 d=document.createElement("div");d.className="next-sdk-tool-overlay__label",a.prepend(l),s.appendChild(a),s.appendChild(d),n.appendChild(i),n.appendChild(o),r.appendChild(n),r.appendChild(s),t.appendChild(e),t.appendChild(r),document.body.appendChild(t),overlayElement=t,labelElement=d}function updateOverlay(t){ensureDomReady()&&(ensureOverlayElement(),!(!overlayElement||!labelElement)&&(overlayElement.classList.remove("next-sdk-tool-overlay--exit"),labelElement.textContent=t.label))}function removeOverlayWithAnimation(){if(!overlayElement)return;overlayElement.classList.add("next-sdk-tool-overlay--exit");const t=overlayElement;let e=!1,r;const n=()=>{e||(e=!0,r!==void 0&&(clearTimeout(r),r=void 0),t.parentNode&&t.parentNode.removeChild(t),overlayElement===t&&(overlayElement=null,labelElement=null),t.removeEventListener("animationend",n))};t.addEventListener("animationend",n),r=setTimeout(n,500)}function showToolInvokeEffect(t){ensureDomReady()&&(activeCount+=1,updateOverlay(t))}function hideToolInvokeEffect(){!ensureDomReady()||activeCount<=0||(activeCount-=1,activeCount===0&&removeOverlayWithAnimation())}function resolveRuntimeEffectConfig(t,e,r){if(!r)return;const n=e||t;return typeof r=="boolean"?r?{label:n}:void 0:{label:r.label||n}}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=t=>t.replace(/\/+$/,"")||"/",broadcastTargets=new Set;function initBroadcastTargets(){isBrowser()&&broadcastTargets.add({win:window,origin:window.location.origin||"*"})}initBroadcastTargets();function broadcastToolChange(t){if(!isBrowser())return;const e={type:t};broadcastTargets.forEach(({win:r,origin:n})=>{try{r.postMessage(e,n)}catch{}})}function setupIframeRemoterBridge(){isBrowser()&&window.addEventListener("message",t=>{if(t.data?.type!==MSG_REMOTER_READY||!t.source||t.origin!==window.location.origin)return;const e=t.source;broadcastTargets.add({win:e,origin:t.origin||"*"})})}setupIframeRemoterBridge();function isToolReadyOnRoute(t,e){const r=activePages.get(t);return!!r&&r.has(e)}let _navigator=null;function buildPageHandler(t,e,r=3e4,n){return i=>{const o=randomUUID();return new Promise((s,a)=>{let l,d;const u=()=>{clearTimeout(l),window.removeEventListener("message",f),d&&window.removeEventListener("message",d),n&&hideToolInvokeEffect()};l=setTimeout(()=>{u(),a(new Error(`工具 [${t}] 调用超时 (${r}ms),请检查目标页面是否正确调用了 registerPageTool`))},r);const f=x=>{x.source===window&&x.data?.type===MSG_TOOL_RESPONSE&&x.data.callId===o&&(u(),x.data.error?a(new Error(x.data.error)):s(x.data.result))};window.addEventListener("message",f);const p=()=>{window.postMessage({type:MSG_TOOL_CALL,callId:o,toolName:t,route:e,input:i},window.location.origin||"*")};let g=!1;const y=()=>{g||(g=!0,p())};(async()=>{try{if(n&&showToolInvokeEffect(n),isToolReadyOnRoute(e,t)){y();return}d=x=>{x.source!==window||x.data?.type!==MSG_TOOL_REGISTERED||(window.removeEventListener("message",d),y())},window.addEventListener("message",d),isToolReadyOnRoute(e,t)&&(window.removeEventListener("message",d),y())}catch(x){u(),a(x instanceof Error?x:new Error(String(x)))}})()})}}const _registeredTools=new Map;function setupModelContextBridge(){if(typeof document>"u")return;const e=document.modelContext;if(!e||e.__isNextSdkBridgeSetup)return;isBrowser()&&(window.__nextSdkRegisteredTools=()=>Array.from(_registeredTools.values()));const r=e.registerTool?.bind(e),n=e.unregisterTool?.bind(e);typeof r=="function"&&(e.registerTool=(i,o)=>{const s=i.name,a={...i};o?.signal&&o.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 d=normalizeRoute(l.route),u=resolveRuntimeEffectConfig(s,a.title,l.invokeEffect),f=buildPageHandler(s,d,l.timeout,u);a.execute=f,delete a.routeConfig}_registeredTools.set(s,{name:s,title:i.title,description:i.description,inputSchema:i.inputSchema});try{r(a,o),broadcastToolChange(MSG_TOOL_REGISTERED)}catch{_registeredTools.delete(s)}}),e.unregisterTool=i=>{try{typeof n=="function"&&n(i)}catch{}finally{_registeredTools.delete(i),broadcastToolChange(MSG_TOOL_UNREGISTERED)}},e.__isNextSdkBridgeSetup=!0}let initialized=!1;const initializeBuiltinWebMCP=()=>{if(isBrowser())try{if(initialized)return;initializeWebMCPPolyfill(),setupModelContextBridge(),initialized=!0}catch(t){console.warn("[next-sdk] 自动注入 modelContext polyfill 和桥接同步失败:",t)}},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=t=>({...defaultOptions,...t}),getRefs=t=>{const e=getDefaultOptions(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,i])=>[i._def,{def:i._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function addErrorMessage(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function setResponseValueAndErrors(t,e,r,n,i){t[e]=r,addErrorMessage(t,e,n,i)}const getRelativePath=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};var util;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{const o={};for(const s of i)o[s]=s;return o},t.getValidEnumValues=i=>{const o=t.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),s={};for(const a of o)s[a]=i[a];return t.objectValues(s)},t.objectValues=i=>t.objectKeys(i).map(function(o){return i[o]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{const o=[];for(const s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},t.find=(i,o)=>{for(const s of i)if(o(s))return s},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}t.joinValues=n,t.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(util||(util={}));var objectUtil;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(objectUtil||(objectUtil={}));const ZodParsedType=util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),getParsedType=t=>{switch(typeof t){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return Number.isNaN(t)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":return Array.isArray(t)?ZodParsedType.array:t===null?ZodParsedType.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?ZodParsedType.promise:typeof Map<"u"&&t instanceof Map?ZodParsedType.map:typeof Set<"u"&&t instanceof Set?ZodParsedType.set:typeof Date<"u"&&t instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ZodError extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){const r=e||function(o){return o.message},n={_errors:[]},i=o=>{for(const s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)n._errors.push(r(s));else{let a=n,l=0;for(;l<s.path.length;){const d=s.path[l];l===s.path.length-1?(a[d]=a[d]||{_errors:[]},a[d]._errors.push(r(s))):a[d]=a[d]||{_errors:[]},a=a[d],l++}}};return i(this),n}static assert(e){if(!(e instanceof ZodError))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){const r={},n=[];for(const i of this.issues)if(i.path.length>0){const o=i.path[0];r[o]=r[o]||[],r[o].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}ZodError.create=t=>new ZodError(t);const errorMap=(t,e)=>{let r;switch(t.code){case ZodIssueCode.invalid_type:t.received===ZodParsedType.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case ZodIssueCode.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:r=`Unrecognized key(s) in object: ${util.joinValues(t.keys,", ")}`;break;case ZodIssueCode.invalid_union:r="Invalid input";break;case ZodIssueCode.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${util.joinValues(t.options)}`;break;case ZodIssueCode.invalid_enum_value:r=`Invalid enum value. Expected ${util.joinValues(t.options)}, received '${t.received}'`;break;case ZodIssueCode.invalid_arguments:r="Invalid function arguments";break;case ZodIssueCode.invalid_return_type:r="Invalid function return type";break;case ZodIssueCode.invalid_date:r="Invalid date";break;case ZodIssueCode.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:util.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case ZodIssueCode.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case ZodIssueCode.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case ZodIssueCode.custom:r="Invalid input";break;case ZodIssueCode.invalid_intersection_types:r="Intersection results could not be merged";break;case ZodIssueCode.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case ZodIssueCode.not_finite:r="Number must be finite";break;default:r=e.defaultError,util.assertNever(t)}return{message:r}};let overrideErrorMap=errorMap;function getErrorMap(){return overrideErrorMap}const makeIssue=t=>{const{data:e,path:r,errorMaps:n,issueData:i}=t,o=[...r,...i.path||[]],s={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let a="";const l=n.filter(d=>!!d).slice().reverse();for(const d of l)a=d(s,{data:e,defaultError:a}).message;return{...i,path:o,message:a}};function addIssueToContext(t,e){const r=getErrorMap(),n=makeIssue({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===errorMap?void 0:errorMap].filter(i=>!!i)});t.common.issues.push(n)}class ParseStatus{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){const n=[];for(const i of r){if(i.status==="aborted")return INVALID;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){const n=[];for(const i of r){const o=await i.key,s=await i.value;n.push({key:o,value:s})}return ParseStatus.mergeObjectSync(e,n)}static mergeObjectSync(e,r){const n={};for(const i of r){const{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return INVALID;o.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(n[o.value]=s.value)}return{status:e.value,value:n}}}const INVALID=Object.freeze({status:"aborted"}),DIRTY=t=>({status:"dirty",value:t}),OK=t=>({status:"valid",value:t}),isAborted=t=>t.status==="aborted",isDirty=t=>t.status==="dirty",isValid=t=>t.status==="valid",isAsync=t=>typeof Promise<"u"&&t instanceof Promise;var errorUtil;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(errorUtil||(errorUtil={}));class ParseInputLazyPath{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const handleResult=(t,e)=>{if(isValid(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new ZodError(t.common.issues);return this._error=r,this._error}}};function processCreateParams(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(s,a)=>{const{message:l}=t;return s.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??n??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:l??r??a.defaultError}},description:i}}class ZodType{get description(){return this._def.description}_getType(e){return getParsedType(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(isAsync(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){const r=this._parse(e);return Promise.resolve(r)}parse(e,r){const n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){const n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},i=this._parseSync({data:e,path:n.path,parent:n});return handleResult(n,i)}"~validate"(e){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:r});return isValid(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>isValid(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){const n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){const n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},i=this._parse({data:e,path:n.path,parent:n}),o=await(isAsync(i)?i:Promise.resolve(i));return handleResult(n,o)}refine(e,r){const n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,o)=>{const s=e(i),a=()=>o.addIssue({code:ZodIssueCode.custom,...n(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(l=>l?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(e){return ZodUnion.create([this,e],this._def)}and(e){return ZodIntersection.create(this,e,this._def)}transform(e){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:r,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:r,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return ZodPipeline.create(this,e)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[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}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let emojiRegex$1;const ipv4Regex=/^(?:(?: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])$/,ipv4CidrRegex=/^(?:(?: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])$/,ipv6Regex=/^(([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]))$/,ipv6CidrRegex=/^(([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])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",dateRegex=new RegExp(`^${dateRegexSource}$`);function timeRegexSource(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function timeRegex(t){return new RegExp(`^${timeRegexSource(t)}$`)}function datetimeRegex(t){let e=`${dateRegexSource}T${timeRegexSource(t)}`;const r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function isValidIP(t,e){return!!((e==="v4"||!e)&&ipv4Regex.test(t)||(e==="v6"||!e)&&ipv6Regex.test(t))}function isValidJWT(t,e){if(!jwtRegex.test(t))return!1;try{const[r]=t.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function isValidCidr(t,e){return!!((e==="v4"||!e)&&ipv4CidrRegex.test(t)||(e==="v6"||!e)&&ipv6CidrRegex.test(t))}class ZodString extends ZodType{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ZodParsedType.string){const o=this._getOrReturnCtx(e);return addIssueToContext(o,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:o.parsedType}),INVALID}const n=new ParseStatus;let i;for(const o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){const s=e.data.length>o.value,a=e.data.length<o.value;(s||a)&&(i=this._getOrReturnCtx(e,i),s?addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")emailRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"email",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")emojiRegex$1||(emojiRegex$1=new RegExp(_emojiRegex,"u")),emojiRegex$1.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"emoji",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")uuidRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"uuid",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")nanoidRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")cuidRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"cuid",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")cuid2Regex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")ulidRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"ulid",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"url",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"regex",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?datetimeRegex(o).test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?dateRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?timeRegex(o).test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?durationRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"duration",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?isValidIP(e.data,o.version)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"ip",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?isValidJWT(e.data,o.alg)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"jwt",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?isValidCidr(e.data,o.version)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"cidr",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?base64Regex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"base64",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?base64urlRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"base64url",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty()):util.assertNever(o);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(i=>e.test(i),{validation:r,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(n)})}_addCheck(e){return new ZodString({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...errorUtil.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...errorUtil.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...errorUtil.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...errorUtil.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...errorUtil.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...errorUtil.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...errorUtil.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...errorUtil.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...errorUtil.errToObj(r)})}nonempty(e){return this.min(1,errorUtil.errToObj(e))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}ZodString.create=t=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:t?.coerce??!1,...processCreateParams(t)});function floatSafeRemainder(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,o=Number.parseInt(t.toFixed(i).replace(".","")),s=Number.parseInt(e.toFixed(i).replace(".",""));return o%s/10**i}class ZodNumber extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==ZodParsedType.number){const o=this._getOrReturnCtx(e);return addIssueToContext(o,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:o.parsedType}),INVALID}let n;const i=new ParseStatus;for(const o of this._def.checks)o.kind==="int"?util.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?floatSafeRemainder(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.not_finite,message:o.message}),i.dirty()):util.assertNever(o);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,errorUtil.toString(r))}gt(e,r){return this.setLimit("min",e,!1,errorUtil.toString(r))}lte(e,r){return this.setLimit("max",e,!0,errorUtil.toString(r))}lt(e,r){return this.setLimit("max",e,!1,errorUtil.toString(r))}setLimit(e,r,n,i){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:errorUtil.toString(i)}]})}_addCheck(e){return new ZodNumber({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil.toString(e)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&util.isInteger(e.value))}get isFinite(){let e=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}}ZodNumber.create=t=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:t?.coerce||!1,...processCreateParams(t)});class ZodBigInt extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ZodParsedType.bigint)return this._getInvalidInput(e);let n;const i=new ParseStatus;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):util.assertNever(o);return{status:i.value,value:e.data}}_getInvalidInput(e){const r=this._getOrReturnCtx(e);return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:r.parsedType}),INVALID}gte(e,r){return this.setLimit("min",e,!0,errorUtil.toString(r))}gt(e,r){return this.setLimit("min",e,!1,errorUtil.toString(r))}lte(e,r){return this.setLimit("max",e,!0,errorUtil.toString(r))}lt(e,r){return this.setLimit("max",e,!1,errorUtil.toString(r))}setLimit(e,r,n,i){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:errorUtil.toString(i)}]})}_addCheck(e){return new ZodBigInt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(r)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}ZodBigInt.create=t=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:t?.coerce??!1,...processCreateParams(t)});class ZodBoolean extends ZodType{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ZodParsedType.boolean){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:n.parsedType}),INVALID}return OK(e.data)}}ZodBoolean.create=t=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:t?.coerce||!1,...processCreateParams(t)});class ZodDate extends ZodType{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ZodParsedType.date){const o=this._getOrReturnCtx(e);return addIssueToContext(o,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:o.parsedType}),INVALID}if(Number.isNaN(e.data.getTime())){const o=this._getOrReturnCtx(e);return addIssueToContext(o,{code:ZodIssueCode.invalid_date}),INVALID}const n=new ParseStatus;let i;for(const o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):util.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ZodDate({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:errorUtil.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:errorUtil.toString(r)})}get minDate(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}}ZodDate.create=t=>new ZodDate({checks:[],coerce:t?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(t)});class ZodSymbol extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.symbol){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:n.parsedType}),INVALID}return OK(e.data)}}ZodSymbol.create=t=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(t)});class ZodUndefined extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:n.parsedType}),INVALID}return OK(e.data)}}ZodUndefined.create=t=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(t)});class ZodNull extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.null){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:n.parsedType}),INVALID}return OK(e.data)}}ZodNull.create=t=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(t)});class ZodAny extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(e){return OK(e.data)}}ZodAny.create=t=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(t)});class ZodUnknown extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(e){return OK(e.data)}}ZodUnknown.create=t=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(t)});class ZodNever extends ZodType{_parse(e){const r=this._getOrReturnCtx(e);return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:r.parsedType}),INVALID}}ZodNever.create=t=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(t)});class ZodVoid extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:n.parsedType}),INVALID}return OK(e.data)}}ZodVoid.create=t=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(t)});class ZodArray extends ZodType{_parse(e){const{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==ZodParsedType.array)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:r.parsedType}),INVALID;if(i.exactLength!==null){const s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(addIssueToContext(r,{code:s?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:a?i.exactLength.value:void 0,maximum:s?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((s,a)=>i.type._parseAsync(new ParseInputLazyPath(r,s,r.path,a)))).then(s=>ParseStatus.mergeArray(n,s));const o=[...r.data].map((s,a)=>i.type._parseSync(new ParseInputLazyPath(r,s,r.path,a)));return ParseStatus.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new ZodArray({...this._def,minLength:{value:e,message:errorUtil.toString(r)}})}max(e,r){return new ZodArray({...this._def,maxLength:{value:e,message:errorUtil.toString(r)}})}length(e,r){return new ZodArray({...this._def,exactLength:{value:e,message:errorUtil.toString(r)}})}nonempty(e){return this.min(1,e)}}ZodArray.create=(t,e)=>new ZodArray({type:t,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(e)});function deepPartialify(t){if(t instanceof ZodObject){const e={};for(const r in t.shape){const n=t.shape[r];e[r]=ZodOptional.create(deepPartialify(n))}return new ZodObject({...t._def,shape:()=>e})}else return t instanceof ZodArray?new ZodArray({...t._def,type:deepPartialify(t.element)}):t instanceof ZodOptional?ZodOptional.create(deepPartialify(t.unwrap())):t instanceof ZodNullable?ZodNullable.create(deepPartialify(t.unwrap())):t instanceof ZodTuple?ZodTuple.create(t.items.map(e=>deepPartialify(e))):t}class ZodObject extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),r=util.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==ZodParsedType.object){const d=this._getOrReturnCtx(e);return addIssueToContext(d,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:d.parsedType}),INVALID}const{status:n,ctx:i}=this._processInputParams(e),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys==="strip"))for(const d in i.data)s.includes(d)||a.push(d);const l=[];for(const d of s){const u=o[d],f=i.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new ParseInputLazyPath(i,f,i.path,d)),alwaysSet:d in i.data})}if(this._def.catchall instanceof ZodNever){const d=this._def.unknownKeys;if(d==="passthrough")for(const u of a)l.push({key:{status:"valid",value:u},value:{status:"valid",value:i.data[u]}});else if(d==="strict")a.length>0&&(addIssueToContext(i,{code:ZodIssueCode.unrecognized_keys,keys:a}),n.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const u of a){const f=i.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new ParseInputLazyPath(i,f,i.path,u)),alwaysSet:u in i.data})}}return i.common.async?Promise.resolve().then(async()=>{const d=[];for(const u of l){const f=await u.key,p=await u.value;d.push({key:f,value:p,alwaysSet:u.alwaysSet})}return d}).then(d=>ParseStatus.mergeObjectSync(n,d)):ParseStatus.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return errorUtil.errToObj,new ZodObject({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{const i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:errorUtil.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new ZodObject({...this._def,unknownKeys:"strip"})}passthrough(){return new ZodObject({...this._def,unknownKeys:"passthrough"})}extend(e){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ZodObject({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new ZodObject({...this._def,catchall:e})}pick(e){const r={};for(const n of util.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new ZodObject({...this._def,shape:()=>r})}omit(e){const r={};for(const n of util.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new ZodObject({...this._def,shape:()=>r})}deepPartial(){return deepPartialify(this)}partial(e){const r={};for(const n of util.objectKeys(this.shape)){const i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}return new ZodObject({...this._def,shape:()=>r})}required(e){const r={};for(const n of util.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof ZodOptional;)o=o._def.innerType;r[n]=o}return new ZodObject({...this._def,shape:()=>r})}keyof(){return createZodEnum(util.objectKeys(this.shape))}}ZodObject.create=(t,e)=>new ZodObject({shape:()=>t,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)}),ZodObject.strictCreate=(t,e)=>new ZodObject({shape:()=>t,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)}),ZodObject.lazycreate=(t,e)=>new ZodObject({shape:t,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});class ZodUnion extends ZodType{_parse(e){const{ctx:r}=this._processInputParams(e),n=this._def.options;function i(o){for(const a of o)if(a.result.status==="valid")return a.result;for(const a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;const s=o.map(a=>new ZodError(a.ctx.common.issues));return addIssueToContext(r,{code:ZodIssueCode.invalid_union,unionErrors:s}),INVALID}if(r.common.async)return Promise.all(n.map(async o=>{const s={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(i);{let o;const s=[];for(const l of n){const d={...r,common:{...r.common,issues:[]},parent:null},u=l._parseSync({data:r.data,path:r.path,parent:d});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:d}),d.common.issues.length&&s.push(d.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;const a=s.map(l=>new ZodError(l));return addIssueToContext(r,{code:ZodIssueCode.invalid_union,unionErrors:a}),INVALID}}get options(){return this._def.options}}ZodUnion.create=(t,e)=>new ZodUnion({options:t,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(e)});function mergeValues(t,e){const r=getParsedType(t),n=getParsedType(e);if(t===e)return{valid:!0,data:t};if(r===ZodParsedType.object&&n===ZodParsedType.object){const i=util.objectKeys(e),o=util.objectKeys(t).filter(a=>i.indexOf(a)!==-1),s={...t,...e};for(const a of o){const l=mergeValues(t[a],e[a]);if(!l.valid)return{valid:!1};s[a]=l.data}return{valid:!0,data:s}}else if(r===ZodParsedType.array&&n===ZodParsedType.array){if(t.length!==e.length)return{valid:!1};const i=[];for(let o=0;o<t.length;o++){const s=t[o],a=e[o],l=mergeValues(s,a);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return r===ZodParsedType.date&&n===ZodParsedType.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class ZodIntersection extends ZodType{_parse(e){const{status:r,ctx:n}=this._processInputParams(e),i=(o,s)=>{if(isAborted(o)||isAborted(s))return INVALID;const a=mergeValues(o.value,s.value);return a.valid?((isDirty(o)||isDirty(s))&&r.dirty(),{status:r.value,value:a.data}):(addIssueToContext(n,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}ZodIntersection.create=(t,e,r)=>new ZodIntersection({left:t,right:e,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(r)});class ZodTuple extends ZodType{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ZodParsedType.array)return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:n.parsedType}),INVALID;if(n.data.length<this._def.items.length)return addIssueToContext(n,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;!this._def.rest&&n.data.length>this._def.items.length&&(addIssueToContext(n,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const o=[...n.data].map((s,a)=>{const l=this._def.items[a]||this._def.rest;return l?l._parse(new ParseInputLazyPath(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>ParseStatus.mergeArray(r,s)):ParseStatus.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new ZodTuple({...this._def,rest:e})}}ZodTuple.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:t,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(e)})};class ZodMap extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ZodParsedType.map)return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:n.parsedType}),INVALID;const i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,l],d)=>({key:i._parse(new ParseInputLazyPath(n,a,n.path,[d,"key"])),value:o._parse(new ParseInputLazyPath(n,l,n.path,[d,"value"]))}));if(n.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const l of s){const d=await l.key,u=await l.value;if(d.status==="aborted"||u.status==="aborted")return INVALID;(d.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(d.value,u.value)}return{status:r.value,value:a}})}else{const a=new Map;for(const l of s){const d=l.key,u=l.value;if(d.status==="aborted"||u.status==="aborted")return INVALID;(d.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(d.value,u.value)}return{status:r.value,value:a}}}}ZodMap.create=(t,e,r)=>new ZodMap({valueType:e,keyType:t,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(r)});class ZodSet extends ZodType{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ZodParsedType.set)return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:n.parsedType}),INVALID;const i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(addIssueToContext(n,{code:ZodIssueCode.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(addIssueToContext(n,{code:ZodIssueCode.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());const o=this._def.valueType;function s(l){const d=new Set;for(const u of l){if(u.status==="aborted")return INVALID;u.status==="dirty"&&r.dirty(),d.add(u.value)}return{status:r.value,value:d}}const a=[...n.data.values()].map((l,d)=>o._parse(new ParseInputLazyPath(n,l,n.path,d)));return n.common.async?Promise.all(a).then(l=>s(l)):s(a)}min(e,r){return new ZodSet({...this._def,minSize:{value:e,message:errorUtil.toString(r)}})}max(e,r){return new ZodSet({...this._def,maxSize:{value:e,message:errorUtil.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}ZodSet.create=(t,e)=>new ZodSet({valueType:t,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(e)});class ZodLazy extends ZodType{get schema(){return this._def.getter()}_parse(e){const{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}ZodLazy.create=(t,e)=>new ZodLazy({getter:t,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(e)});class ZodLiteral extends ZodType{_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return addIssueToContext(r,{received:r.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}}ZodLiteral.create=(t,e)=>new ZodLiteral({value:t,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(e)});function createZodEnum(t,e){return new ZodEnum({values:t,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(e)})}class ZodEnum extends ZodType{_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),n=this._def.values;return addIssueToContext(r,{expected:util.joinValues(n),received:r.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const r=this._getOrReturnCtx(e),n=this._def.values;return addIssueToContext(r,{received:r.data,code:ZodIssueCode.invalid_enum_value,options:n}),INVALID}return OK(e.data)}get options(){return this._def.values}get enum(){const e={};for(const r of this._def.values)e[r]=r;return e}get Values(){const e={};for(const r of this._def.values)e[r]=r;return e}get Enum(){const e={};for(const r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return ZodEnum.create(e,{...this._def,...r})}exclude(e,r=this._def){return ZodEnum.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}}ZodEnum.create=createZodEnum;class ZodNativeEnum extends ZodType{_parse(e){const r=util.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==ZodParsedType.string&&n.parsedType!==ZodParsedType.number){const i=util.objectValues(r);return addIssueToContext(n,{expected:util.joinValues(i),received:n.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const i=util.objectValues(r);return addIssueToContext(n,{received:n.data,code:ZodIssueCode.invalid_enum_value,options:i}),INVALID}return OK(e.data)}get enum(){return this._def.values}}ZodNativeEnum.create=(t,e)=>new ZodNativeEnum({values:t,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(e)});class ZodPromise extends ZodType{unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==ZodParsedType.promise&&r.common.async===!1)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:r.parsedType}),INVALID;const n=r.parsedType===ZodParsedType.promise?r.data:Promise.resolve(r.data);return OK(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}}ZodPromise.create=(t,e)=>new ZodPromise({type:t,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(e)});class ZodEffects extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,o={addIssue:s=>{addIssueToContext(n,s),s.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){const s=i.transform(n.data,o);if(n.common.async)return Promise.resolve(s).then(async a=>{if(r.value==="aborted")return INVALID;const l=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return l.status==="aborted"?INVALID:l.status==="dirty"||r.value==="dirty"?DIRTY(l.value):l});{if(r.value==="aborted")return INVALID;const a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?INVALID:a.status==="dirty"||r.value==="dirty"?DIRTY(a.value):a}}if(i.type==="refinement"){const s=a=>{const l=i.refinement(a,o);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?INVALID:(a.status==="dirty"&&r.dirty(),s(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?INVALID:(a.status==="dirty"&&r.dirty(),s(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){const s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!isValid(s))return INVALID;const a=i.transform(s.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>isValid(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):INVALID);util.assertNever(i)}}ZodEffects.create=(t,e,r)=>new ZodEffects({schema:t,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:e,...processCreateParams(r)}),ZodEffects.createWithPreprocess=(t,e,r)=>new ZodEffects({schema:e,effect:{type:"preprocess",transform:t},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(r)});class ZodOptional extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodOptional.create=(t,e)=>new ZodOptional({innerType:t,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(e)});class ZodNullable extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.null?OK(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodNullable.create=(t,e)=>new ZodNullable({innerType:t,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(e)});class ZodDefault extends ZodType{_parse(e){const{ctx:r}=this._processInputParams(e);let n=r.data;return r.parsedType===ZodParsedType.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}ZodDefault.create=(t,e)=>new ZodDefault({innerType:t,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...processCreateParams(e)});class ZodCatch extends ZodType{_parse(e){const{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return isAsync(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ZodError(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ZodError(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}ZodCatch.create=(t,e)=>new ZodCatch({innerType:t,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...processCreateParams(e)});class ZodNaN extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.nan){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:n.parsedType}),INVALID}return{status:"valid",value:e.data}}}ZodNaN.create=t=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(t)});class ZodBranded extends ZodType{_parse(e){const{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class ZodPipeline extends ZodType{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?INVALID:o.status==="dirty"?(r.dirty(),DIRTY(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{const i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?INVALID:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new ZodPipeline({in:e,out:r,typeName:ZodFirstPartyTypeKind.ZodPipeline})}}class ZodReadonly extends ZodType{_parse(e){const r=this._def.innerType._parse(e),n=i=>(isValid(i)&&(i.value=Object.freeze(i.value)),i);return isAsync(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}}ZodReadonly.create=(t,e)=>new ZodReadonly({innerType:t,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(e)});var ZodFirstPartyTypeKind;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));const stringType=ZodString.create,numberType=ZodNumber.create,booleanType=ZodBoolean.create;ZodNever.create,ZodArray.create;const objectType=ZodObject.create;ZodUnion.create,ZodIntersection.create,ZodTuple.create;const enumType=ZodEnum.create;ZodPromise.create,ZodOptional.create,ZodNullable.create;function parseAnyDef(t){if(t.target!=="openAi")return{};const e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?getRelativePath(e,t.currentPath):e.join("/")}}function parseArrayDef(t,e){const r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==ZodFirstPartyTypeKind.ZodAny&&(r.items=parseDef(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&setResponseValueAndErrors(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&setResponseValueAndErrors(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(setResponseValueAndErrors(r,"minItems",t.exactLength.value,t.exactLength.message,e),setResponseValueAndErrors(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function parseBigintDef(t,e){const r={type:"integer",format:"int64"};if(!t.checks)return r;for(const n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?setResponseValueAndErrors(r,"minimum",n.value,n.message,e):setResponseValueAndErrors(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),setResponseValueAndErrors(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?setResponseValueAndErrors(r,"maximum",n.value,n.message,e):setResponseValueAndErrors(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),setResponseValueAndErrors(r,"maximum",n.value,n.message,e));break;case"multipleOf":setResponseValueAndErrors(r,"multipleOf",n.value,n.message,e);break}return r}function parseBooleanDef(){return{type:"boolean"}}function parseBrandedDef(t,e){return parseDef(t.type._def,e)}const parseCatchDef=(t,e)=>parseDef(t.innerType._def,e);function parseDateDef(t,e,r){const n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((i,o)=>parseDateDef(t,e,i))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return integerDateParser(t,e)}}const integerDateParser=(t,e)=>{const r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(const n of t.checks)switch(n.kind){case"min":setResponseValueAndErrors(r,"minimum",n.value,n.message,e);break;case"max":setResponseValueAndErrors(r,"maximum",n.value,n.message,e);break}return r};function parseDefaultDef(t,e){return{...parseDef(t.innerType._def,e),default:t.defaultValue()}}function parseEffectsDef(t,e){return e.effectStrategy==="input"?parseDef(t.schema._def,e):parseAnyDef(e)}function parseEnumDef(t){return{type:"string",enum:Array.from(t.values)}}const isJsonSchema7AllOfType=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function parseIntersectionDef(t,e){const r=[parseDef(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),parseDef(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o);let n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const i=[];return r.forEach(o=>{if(isJsonSchema7AllOfType(o))i.push(...o.allOf),o.unevaluatedProperties===void 0&&(n=void 0);else{let s=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:a,...l}=o;s=l}else n=void 0;i.push(s)}}),i.length?{allOf:i,...n}:void 0}function parseLiteralDef(t,e){const r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.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(t,e){const r={type:"string"};if(t.checks)for(const n of t.checks)switch(n.kind){case"min":setResponseValueAndErrors(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":setResponseValueAndErrors(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":addFormat(r,"email",n.message,e);break;case"format:idn-email":addFormat(r,"idn-email",n.message,e);break;case"pattern:zod":addPattern(r,zodPatterns.email,n.message,e);break}break;case"url":addFormat(r,"uri",n.message,e);break;case"uuid":addFormat(r,"uuid",n.message,e);break;case"regex":addPattern(r,n.regex,n.message,e);break;case"cuid":addPattern(r,zodPatterns.cuid,n.message,e);break;case"cuid2":addPattern(r,zodPatterns.cuid2,n.message,e);break;case"startsWith":addPattern(r,RegExp(`^${escapeLiteralCheckValue(n.value,e)}`),n.message,e);break;case"endsWith":addPattern(r,RegExp(`${escapeLiteralCheckValue(n.value,e)}$`),n.message,e);break;case"datetime":addFormat(r,"date-time",n.message,e);break;case"date":addFormat(r,"date",n.message,e);break;case"time":addFormat(r,"time",n.message,e);break;case"duration":addFormat(r,"duration",n.message,e);break;case"length":setResponseValueAndErrors(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),setResponseValueAndErrors(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{addPattern(r,RegExp(escapeLiteralCheckValue(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&addFormat(r,"ipv4",n.message,e),n.version!=="v4"&&addFormat(r,"ipv6",n.message,e);break}case"base64url":addPattern(r,zodPatterns.base64url,n.message,e);break;case"jwt":addPattern(r,zodPatterns.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&addPattern(r,zodPatterns.ipv4Cidr,n.message,e),n.version!=="v4"&&addPattern(r,zodPatterns.ipv6Cidr,n.message,e);break}case"emoji":addPattern(r,zodPatterns.emoji(),n.message,e);break;case"ulid":{addPattern(r,zodPatterns.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{addFormat(r,"binary",n.message,e);break}case"contentEncoding:base64":{setResponseValueAndErrors(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{addPattern(r,zodPatterns.base64,n.message,e);break}}break}case"nanoid":addPattern(r,zodPatterns.nanoid,n.message,e)}return r}function escapeLiteralCheckValue(t,e){return e.patternStrategy==="escape"?escapeNonAlphaNumeric(t):t}const ALPHA_NUMERIC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function escapeNonAlphaNumeric(t){let e="";for(let r=0;r<t.length;r++)ALPHA_NUMERIC.has(t[r])||(e+="\\"),e+=t[r];return e}function addFormat(t,e,r,n){t.format||t.anyOf?.some(i=>i.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):setResponseValueAndErrors(t,"format",e,r,n)}function addPattern(t,e,r,n){t.pattern||t.allOf?.some(i=>i.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:stringifyRegExpWithFlags(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):setResponseValueAndErrors(t,"pattern",stringifyRegExpWithFlags(e,n),r,n)}function stringifyRegExpWithFlags(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;const r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source;let i="",o=!1,s=!1,a=!1;for(let l=0;l<n.length;l++){if(o){i+=n[l],o=!1;continue}if(r.i){if(s){if(n[l].match(/[a-z]/)){a?(i+=n[l],i+=`${n[l-2]}-${n[l]}`.toUpperCase(),a=!1):n[l+1]==="-"&&n[l+2]?.match(/[a-z]/)?(i+=n[l],a=!0):i+=`${n[l]}${n[l].toUpperCase()}`;continue}}else if(n[l].match(/[a-z]/)){i+=`[${n[l]}${n[l].toUpperCase()}]`;continue}}if(r.m){if(n[l]==="^"){i+=`(^|(?<=[\r
172
+ `,document.head.appendChild(t),styleElement=t}function ensureOverlayElement(){if(!ensureDomReady()||overlayElement)return;ensureStyleElement();const t=document.createElement("div");t.className="next-sdk-tool-overlay";const e=document.createElement("div");e.className="next-sdk-tool-overlay__glow-ring";const r=document.createElement("div");r.className="next-sdk-tool-overlay__panel";const n=document.createElement("div");n.className="next-sdk-tool-overlay__indicator";const i=document.createElement("div");i.className="next-sdk-tool-overlay__indicator-orbit";const o=document.createElement("div");o.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),n.appendChild(i),n.appendChild(o),r.appendChild(n),r.appendChild(s),t.appendChild(e),t.appendChild(r),document.body.appendChild(t),overlayElement=t,labelElement=c}function updateOverlay(t){ensureDomReady()&&(ensureOverlayElement(),!(!overlayElement||!labelElement)&&(overlayElement.classList.remove("next-sdk-tool-overlay--exit"),labelElement.textContent=t.label))}function removeOverlayWithAnimation(){if(!overlayElement)return;overlayElement.classList.add("next-sdk-tool-overlay--exit");const t=overlayElement;let e=!1,r;const n=()=>{e||(e=!0,r!==void 0&&(clearTimeout(r),r=void 0),t.parentNode&&t.parentNode.removeChild(t),overlayElement===t&&(overlayElement=null,labelElement=null),t.removeEventListener("animationend",n))};t.addEventListener("animationend",n),r=setTimeout(n,500)}function showToolInvokeEffect(t){ensureDomReady()&&(activeCount+=1,updateOverlay(t))}function hideToolInvokeEffect(){!ensureDomReady()||activeCount<=0||(activeCount-=1,activeCount===0&&removeOverlayWithAnimation())}function resolveRuntimeEffectConfig(t,e,r){if(!r)return;const n=e||t;return typeof r=="boolean"?r?{label:n}:void 0:{label:r.label||n}}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=t=>t.replace(/\/+$/,"")||"/",broadcastTargets=new Set;function initBroadcastTargets(){isBrowser()&&broadcastTargets.add({win:window,origin:window.location.origin||"*"})}initBroadcastTargets();function broadcastToolChange(t){if(!isBrowser())return;const e={type:t};broadcastTargets.forEach(({win:r,origin:n})=>{try{r.postMessage(e,n)}catch{}})}function setupIframeRemoterBridge(){isBrowser()&&window.addEventListener("message",t=>{if(t.data?.type!==MSG_REMOTER_READY||!t.source||t.origin!==window.location.origin)return;const e=t.source;broadcastTargets.add({win:e,origin:t.origin||"*"})})}setupIframeRemoterBridge();function isToolReadyOnRoute(t,e){const r=activePages.get(t);return!!r&&r.has(e)}let _navigator=null;function buildPageHandler(t,e,r=3e4,n){return i=>{const o=randomUUID();return new Promise((s,a)=>{let l,c;const u=()=>{clearTimeout(l),window.removeEventListener("message",h),c&&window.removeEventListener("message",c),n&&hideToolInvokeEffect()};l=setTimeout(()=>{u(),a(new Error(`工具 [${t}] 调用超时 (${r}ms),请检查目标页面是否正确调用了 registerPageTool`))},r);const h=w=>{w.source===window&&w.data?.type===MSG_TOOL_RESPONSE&&w.data.callId===o&&(u(),w.data.error?a(new Error(w.data.error)):s(w.data.result))};window.addEventListener("message",h);const f=()=>{window.postMessage({type:MSG_TOOL_CALL,callId:o,toolName:t,route:e,input:i},window.location.origin||"*")};let g=!1;const b=()=>{g||(g=!0,f())};(async()=>{try{if(n&&showToolInvokeEffect(n),isToolReadyOnRoute(e,t)){b();return}c=w=>{w.source!==window||w.data?.type!==MSG_TOOL_REGISTERED||(window.removeEventListener("message",c),b())},window.addEventListener("message",c),isToolReadyOnRoute(e,t)&&(window.removeEventListener("message",c),b())}catch(w){u(),a(w instanceof Error?w:new Error(String(w)))}})()})}}const _registeredTools=new Map;function setupModelContextBridge(){if(typeof document>"u")return;const t=document,e=typeof navigator<"u"?navigator:void 0,r=t.modelContext||e?.modelContext;if(!r||r.__isNextSdkBridgeSetup)return;!t.modelContext&&e?.modelContext&&(t.modelContext=e.modelContext),isBrowser()&&(window.__nextSdkRegisteredTools=()=>Array.from(_registeredTools.values()));const n=r.registerTool?.bind(r),i=r.unregisterTool?.bind(r);typeof n=="function"&&(r.registerTool=(o,s)=>{const a=o.name,l={...o};s?.signal&&s.signal.addEventListener("abort",()=>{_registeredTools.delete(a),broadcastToolChange(MSG_TOOL_UNREGISTERED)});const c=l.routeConfig&&typeof l.routeConfig=="object"&&"route"in l.routeConfig?l.routeConfig:null;if(c){const u=normalizeRoute(c.route),h=resolveRuntimeEffectConfig(a,l.title,c.invokeEffect),f=buildPageHandler(a,u,c.timeout,h);l.execute=f,delete l.routeConfig}_registeredTools.set(a,{name:a,title:o.title,description:o.description,inputSchema:o.inputSchema});try{n(l,s),broadcastToolChange(MSG_TOOL_REGISTERED)}catch{_registeredTools.delete(a)}}),r.unregisterTool=o=>{try{typeof i=="function"&&i(o)}catch{}finally{_registeredTools.delete(o),broadcastToolChange(MSG_TOOL_UNREGISTERED)}},r.__isNextSdkBridgeSetup=!0}let initialized=!1;const initializeBuiltinWebMCP=()=>{if(isBrowser())try{if(initialized)return;initializeWebMCPPolyfill(),setupModelContextBridge(),initialized=!0}catch(t){console.warn("[next-sdk] 自动注入 modelContext polyfill 和桥接同步失败:",t)}},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=t=>({...defaultOptions,...t}),getRefs=t=>{const e=getDefaultOptions(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,i])=>[i._def,{def:i._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function addErrorMessage(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function setResponseValueAndErrors(t,e,r,n,i){t[e]=r,addErrorMessage(t,e,n,i)}const getRelativePath=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};var util;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{const o={};for(const s of i)o[s]=s;return o},t.getValidEnumValues=i=>{const o=t.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),s={};for(const a of o)s[a]=i[a];return t.objectValues(s)},t.objectValues=i=>t.objectKeys(i).map(function(o){return i[o]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{const o=[];for(const s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},t.find=(i,o)=>{for(const s of i)if(o(s))return s},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}t.joinValues=n,t.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(util||(util={}));var objectUtil;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(objectUtil||(objectUtil={}));const ZodParsedType=util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),getParsedType=t=>{switch(typeof t){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return Number.isNaN(t)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":return Array.isArray(t)?ZodParsedType.array:t===null?ZodParsedType.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?ZodParsedType.promise:typeof Map<"u"&&t instanceof Map?ZodParsedType.map:typeof Set<"u"&&t instanceof Set?ZodParsedType.set:typeof Date<"u"&&t instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ZodError extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){const r=e||function(o){return o.message},n={_errors:[]},i=o=>{for(const s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)n._errors.push(r(s));else{let a=n,l=0;for(;l<s.path.length;){const c=s.path[l];l===s.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(r(s))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return i(this),n}static assert(e){if(!(e instanceof ZodError))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){const r={},n=[];for(const i of this.issues)if(i.path.length>0){const o=i.path[0];r[o]=r[o]||[],r[o].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}ZodError.create=t=>new ZodError(t);const errorMap=(t,e)=>{let r;switch(t.code){case ZodIssueCode.invalid_type:t.received===ZodParsedType.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case ZodIssueCode.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:r=`Unrecognized key(s) in object: ${util.joinValues(t.keys,", ")}`;break;case ZodIssueCode.invalid_union:r="Invalid input";break;case ZodIssueCode.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${util.joinValues(t.options)}`;break;case ZodIssueCode.invalid_enum_value:r=`Invalid enum value. Expected ${util.joinValues(t.options)}, received '${t.received}'`;break;case ZodIssueCode.invalid_arguments:r="Invalid function arguments";break;case ZodIssueCode.invalid_return_type:r="Invalid function return type";break;case ZodIssueCode.invalid_date:r="Invalid date";break;case ZodIssueCode.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:util.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case ZodIssueCode.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case ZodIssueCode.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case ZodIssueCode.custom:r="Invalid input";break;case ZodIssueCode.invalid_intersection_types:r="Intersection results could not be merged";break;case ZodIssueCode.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case ZodIssueCode.not_finite:r="Number must be finite";break;default:r=e.defaultError,util.assertNever(t)}return{message:r}};let overrideErrorMap=errorMap;function getErrorMap(){return overrideErrorMap}const makeIssue=t=>{const{data:e,path:r,errorMaps:n,issueData:i}=t,o=[...r,...i.path||[]],s={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let a="";const l=n.filter(c=>!!c).slice().reverse();for(const c of l)a=c(s,{data:e,defaultError:a}).message;return{...i,path:o,message:a}};function addIssueToContext(t,e){const r=getErrorMap(),n=makeIssue({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===errorMap?void 0:errorMap].filter(i=>!!i)});t.common.issues.push(n)}class ParseStatus{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){const n=[];for(const i of r){if(i.status==="aborted")return INVALID;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){const n=[];for(const i of r){const o=await i.key,s=await i.value;n.push({key:o,value:s})}return ParseStatus.mergeObjectSync(e,n)}static mergeObjectSync(e,r){const n={};for(const i of r){const{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return INVALID;o.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(n[o.value]=s.value)}return{status:e.value,value:n}}}const INVALID=Object.freeze({status:"aborted"}),DIRTY=t=>({status:"dirty",value:t}),OK=t=>({status:"valid",value:t}),isAborted=t=>t.status==="aborted",isDirty=t=>t.status==="dirty",isValid=t=>t.status==="valid",isAsync=t=>typeof Promise<"u"&&t instanceof Promise;var errorUtil;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(errorUtil||(errorUtil={}));class ParseInputLazyPath{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const handleResult=(t,e)=>{if(isValid(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new ZodError(t.common.issues);return this._error=r,this._error}}};function processCreateParams(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(s,a)=>{const{message:l}=t;return s.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??n??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:l??r??a.defaultError}},description:i}}class ZodType{get description(){return this._def.description}_getType(e){return getParsedType(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(isAsync(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){const r=this._parse(e);return Promise.resolve(r)}parse(e,r){const n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){const n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},i=this._parseSync({data:e,path:n.path,parent:n});return handleResult(n,i)}"~validate"(e){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:r});return isValid(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>isValid(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){const n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){const n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},i=this._parse({data:e,path:n.path,parent:n}),o=await(isAsync(i)?i:Promise.resolve(i));return handleResult(n,o)}refine(e,r){const n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,o)=>{const s=e(i),a=()=>o.addIssue({code:ZodIssueCode.custom,...n(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(l=>l?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(e){return ZodUnion.create([this,e],this._def)}and(e){return ZodIntersection.create(this,e,this._def)}transform(e){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:r,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:r,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return ZodPipeline.create(this,e)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[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}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let emojiRegex$1;const ipv4Regex=/^(?:(?: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])$/,ipv4CidrRegex=/^(?:(?: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])$/,ipv6Regex=/^(([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]))$/,ipv6CidrRegex=/^(([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])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",dateRegex=new RegExp(`^${dateRegexSource}$`);function timeRegexSource(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function timeRegex(t){return new RegExp(`^${timeRegexSource(t)}$`)}function datetimeRegex(t){let e=`${dateRegexSource}T${timeRegexSource(t)}`;const r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function isValidIP(t,e){return!!((e==="v4"||!e)&&ipv4Regex.test(t)||(e==="v6"||!e)&&ipv6Regex.test(t))}function isValidJWT(t,e){if(!jwtRegex.test(t))return!1;try{const[r]=t.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function isValidCidr(t,e){return!!((e==="v4"||!e)&&ipv4CidrRegex.test(t)||(e==="v6"||!e)&&ipv6CidrRegex.test(t))}class ZodString extends ZodType{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ZodParsedType.string){const o=this._getOrReturnCtx(e);return addIssueToContext(o,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:o.parsedType}),INVALID}const n=new ParseStatus;let i;for(const o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){const s=e.data.length>o.value,a=e.data.length<o.value;(s||a)&&(i=this._getOrReturnCtx(e,i),s?addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")emailRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"email",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")emojiRegex$1||(emojiRegex$1=new RegExp(_emojiRegex,"u")),emojiRegex$1.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"emoji",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")uuidRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"uuid",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")nanoidRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")cuidRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"cuid",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")cuid2Regex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")ulidRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"ulid",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"url",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"regex",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?datetimeRegex(o).test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?dateRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?timeRegex(o).test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?durationRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"duration",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?isValidIP(e.data,o.version)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"ip",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?isValidJWT(e.data,o.alg)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"jwt",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?isValidCidr(e.data,o.version)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"cidr",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?base64Regex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"base64",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?base64urlRegex.test(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{validation:"base64url",code:ZodIssueCode.invalid_string,message:o.message}),n.dirty()):util.assertNever(o);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(i=>e.test(i),{validation:r,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(n)})}_addCheck(e){return new ZodString({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...errorUtil.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...errorUtil.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...errorUtil.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...errorUtil.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...errorUtil.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...errorUtil.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...errorUtil.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...errorUtil.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...errorUtil.errToObj(r)})}nonempty(e){return this.min(1,errorUtil.errToObj(e))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}ZodString.create=t=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:t?.coerce??!1,...processCreateParams(t)});function floatSafeRemainder(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,o=Number.parseInt(t.toFixed(i).replace(".","")),s=Number.parseInt(e.toFixed(i).replace(".",""));return o%s/10**i}class ZodNumber extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==ZodParsedType.number){const o=this._getOrReturnCtx(e);return addIssueToContext(o,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:o.parsedType}),INVALID}let n;const i=new ParseStatus;for(const o of this._def.checks)o.kind==="int"?util.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?floatSafeRemainder(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.not_finite,message:o.message}),i.dirty()):util.assertNever(o);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,errorUtil.toString(r))}gt(e,r){return this.setLimit("min",e,!1,errorUtil.toString(r))}lte(e,r){return this.setLimit("max",e,!0,errorUtil.toString(r))}lt(e,r){return this.setLimit("max",e,!1,errorUtil.toString(r))}setLimit(e,r,n,i){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:errorUtil.toString(i)}]})}_addCheck(e){return new ZodNumber({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil.toString(e)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&util.isInteger(e.value))}get isFinite(){let e=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}}ZodNumber.create=t=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:t?.coerce||!1,...processCreateParams(t)});class ZodBigInt extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ZodParsedType.bigint)return this._getInvalidInput(e);let n;const i=new ParseStatus;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):util.assertNever(o);return{status:i.value,value:e.data}}_getInvalidInput(e){const r=this._getOrReturnCtx(e);return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:r.parsedType}),INVALID}gte(e,r){return this.setLimit("min",e,!0,errorUtil.toString(r))}gt(e,r){return this.setLimit("min",e,!1,errorUtil.toString(r))}lte(e,r){return this.setLimit("max",e,!0,errorUtil.toString(r))}lt(e,r){return this.setLimit("max",e,!1,errorUtil.toString(r))}setLimit(e,r,n,i){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:errorUtil.toString(i)}]})}_addCheck(e){return new ZodBigInt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(r)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}ZodBigInt.create=t=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:t?.coerce??!1,...processCreateParams(t)});class ZodBoolean extends ZodType{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ZodParsedType.boolean){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:n.parsedType}),INVALID}return OK(e.data)}}ZodBoolean.create=t=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:t?.coerce||!1,...processCreateParams(t)});class ZodDate extends ZodType{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ZodParsedType.date){const o=this._getOrReturnCtx(e);return addIssueToContext(o,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:o.parsedType}),INVALID}if(Number.isNaN(e.data.getTime())){const o=this._getOrReturnCtx(e);return addIssueToContext(o,{code:ZodIssueCode.invalid_date}),INVALID}const n=new ParseStatus;let i;for(const o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):util.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ZodDate({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:errorUtil.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:errorUtil.toString(r)})}get minDate(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}}ZodDate.create=t=>new ZodDate({checks:[],coerce:t?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(t)});class ZodSymbol extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.symbol){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:n.parsedType}),INVALID}return OK(e.data)}}ZodSymbol.create=t=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(t)});class ZodUndefined extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:n.parsedType}),INVALID}return OK(e.data)}}ZodUndefined.create=t=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(t)});class ZodNull extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.null){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:n.parsedType}),INVALID}return OK(e.data)}}ZodNull.create=t=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(t)});class ZodAny extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(e){return OK(e.data)}}ZodAny.create=t=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(t)});class ZodUnknown extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(e){return OK(e.data)}}ZodUnknown.create=t=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(t)});class ZodNever extends ZodType{_parse(e){const r=this._getOrReturnCtx(e);return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:r.parsedType}),INVALID}}ZodNever.create=t=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(t)});class ZodVoid extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:n.parsedType}),INVALID}return OK(e.data)}}ZodVoid.create=t=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(t)});class ZodArray extends ZodType{_parse(e){const{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==ZodParsedType.array)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:r.parsedType}),INVALID;if(i.exactLength!==null){const s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(addIssueToContext(r,{code:s?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:a?i.exactLength.value:void 0,maximum:s?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((s,a)=>i.type._parseAsync(new ParseInputLazyPath(r,s,r.path,a)))).then(s=>ParseStatus.mergeArray(n,s));const o=[...r.data].map((s,a)=>i.type._parseSync(new ParseInputLazyPath(r,s,r.path,a)));return ParseStatus.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new ZodArray({...this._def,minLength:{value:e,message:errorUtil.toString(r)}})}max(e,r){return new ZodArray({...this._def,maxLength:{value:e,message:errorUtil.toString(r)}})}length(e,r){return new ZodArray({...this._def,exactLength:{value:e,message:errorUtil.toString(r)}})}nonempty(e){return this.min(1,e)}}ZodArray.create=(t,e)=>new ZodArray({type:t,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(e)});function deepPartialify(t){if(t instanceof ZodObject){const e={};for(const r in t.shape){const n=t.shape[r];e[r]=ZodOptional.create(deepPartialify(n))}return new ZodObject({...t._def,shape:()=>e})}else return t instanceof ZodArray?new ZodArray({...t._def,type:deepPartialify(t.element)}):t instanceof ZodOptional?ZodOptional.create(deepPartialify(t.unwrap())):t instanceof ZodNullable?ZodNullable.create(deepPartialify(t.unwrap())):t instanceof ZodTuple?ZodTuple.create(t.items.map(e=>deepPartialify(e))):t}class ZodObject extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),r=util.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==ZodParsedType.object){const c=this._getOrReturnCtx(e);return addIssueToContext(c,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:c.parsedType}),INVALID}const{status:n,ctx:i}=this._processInputParams(e),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys==="strip"))for(const c in i.data)s.includes(c)||a.push(c);const l=[];for(const c of s){const u=o[c],h=i.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new ParseInputLazyPath(i,h,i.path,c)),alwaysSet:c in i.data})}if(this._def.catchall instanceof ZodNever){const c=this._def.unknownKeys;if(c==="passthrough")for(const u of a)l.push({key:{status:"valid",value:u},value:{status:"valid",value:i.data[u]}});else if(c==="strict")a.length>0&&(addIssueToContext(i,{code:ZodIssueCode.unrecognized_keys,keys:a}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const u of a){const h=i.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new ParseInputLazyPath(i,h,i.path,u)),alwaysSet:u in i.data})}}return i.common.async?Promise.resolve().then(async()=>{const c=[];for(const u of l){const h=await u.key,f=await u.value;c.push({key:h,value:f,alwaysSet:u.alwaysSet})}return c}).then(c=>ParseStatus.mergeObjectSync(n,c)):ParseStatus.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return errorUtil.errToObj,new ZodObject({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{const i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:errorUtil.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new ZodObject({...this._def,unknownKeys:"strip"})}passthrough(){return new ZodObject({...this._def,unknownKeys:"passthrough"})}extend(e){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ZodObject({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new ZodObject({...this._def,catchall:e})}pick(e){const r={};for(const n of util.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new ZodObject({...this._def,shape:()=>r})}omit(e){const r={};for(const n of util.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new ZodObject({...this._def,shape:()=>r})}deepPartial(){return deepPartialify(this)}partial(e){const r={};for(const n of util.objectKeys(this.shape)){const i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}return new ZodObject({...this._def,shape:()=>r})}required(e){const r={};for(const n of util.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof ZodOptional;)o=o._def.innerType;r[n]=o}return new ZodObject({...this._def,shape:()=>r})}keyof(){return createZodEnum(util.objectKeys(this.shape))}}ZodObject.create=(t,e)=>new ZodObject({shape:()=>t,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)}),ZodObject.strictCreate=(t,e)=>new ZodObject({shape:()=>t,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)}),ZodObject.lazycreate=(t,e)=>new ZodObject({shape:t,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});class ZodUnion extends ZodType{_parse(e){const{ctx:r}=this._processInputParams(e),n=this._def.options;function i(o){for(const a of o)if(a.result.status==="valid")return a.result;for(const a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;const s=o.map(a=>new ZodError(a.ctx.common.issues));return addIssueToContext(r,{code:ZodIssueCode.invalid_union,unionErrors:s}),INVALID}if(r.common.async)return Promise.all(n.map(async o=>{const s={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(i);{let o;const s=[];for(const l of n){const c={...r,common:{...r.common,issues:[]},parent:null},u=l._parseSync({data:r.data,path:r.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:c}),c.common.issues.length&&s.push(c.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;const a=s.map(l=>new ZodError(l));return addIssueToContext(r,{code:ZodIssueCode.invalid_union,unionErrors:a}),INVALID}}get options(){return this._def.options}}ZodUnion.create=(t,e)=>new ZodUnion({options:t,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(e)});function mergeValues(t,e){const r=getParsedType(t),n=getParsedType(e);if(t===e)return{valid:!0,data:t};if(r===ZodParsedType.object&&n===ZodParsedType.object){const i=util.objectKeys(e),o=util.objectKeys(t).filter(a=>i.indexOf(a)!==-1),s={...t,...e};for(const a of o){const l=mergeValues(t[a],e[a]);if(!l.valid)return{valid:!1};s[a]=l.data}return{valid:!0,data:s}}else if(r===ZodParsedType.array&&n===ZodParsedType.array){if(t.length!==e.length)return{valid:!1};const i=[];for(let o=0;o<t.length;o++){const s=t[o],a=e[o],l=mergeValues(s,a);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return r===ZodParsedType.date&&n===ZodParsedType.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class ZodIntersection extends ZodType{_parse(e){const{status:r,ctx:n}=this._processInputParams(e),i=(o,s)=>{if(isAborted(o)||isAborted(s))return INVALID;const a=mergeValues(o.value,s.value);return a.valid?((isDirty(o)||isDirty(s))&&r.dirty(),{status:r.value,value:a.data}):(addIssueToContext(n,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}ZodIntersection.create=(t,e,r)=>new ZodIntersection({left:t,right:e,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(r)});class ZodTuple extends ZodType{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ZodParsedType.array)return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:n.parsedType}),INVALID;if(n.data.length<this._def.items.length)return addIssueToContext(n,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;!this._def.rest&&n.data.length>this._def.items.length&&(addIssueToContext(n,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const o=[...n.data].map((s,a)=>{const l=this._def.items[a]||this._def.rest;return l?l._parse(new ParseInputLazyPath(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>ParseStatus.mergeArray(r,s)):ParseStatus.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new ZodTuple({...this._def,rest:e})}}ZodTuple.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:t,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(e)})};class ZodMap extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ZodParsedType.map)return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:n.parsedType}),INVALID;const i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,l],c)=>({key:i._parse(new ParseInputLazyPath(n,a,n.path,[c,"key"])),value:o._parse(new ParseInputLazyPath(n,l,n.path,[c,"value"]))}));if(n.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const l of s){const c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return INVALID;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(c.value,u.value)}return{status:r.value,value:a}})}else{const a=new Map;for(const l of s){const c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return INVALID;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(c.value,u.value)}return{status:r.value,value:a}}}}ZodMap.create=(t,e,r)=>new ZodMap({valueType:e,keyType:t,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(r)});class ZodSet extends ZodType{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ZodParsedType.set)return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:n.parsedType}),INVALID;const i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(addIssueToContext(n,{code:ZodIssueCode.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(addIssueToContext(n,{code:ZodIssueCode.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());const o=this._def.valueType;function s(l){const c=new Set;for(const u of l){if(u.status==="aborted")return INVALID;u.status==="dirty"&&r.dirty(),c.add(u.value)}return{status:r.value,value:c}}const a=[...n.data.values()].map((l,c)=>o._parse(new ParseInputLazyPath(n,l,n.path,c)));return n.common.async?Promise.all(a).then(l=>s(l)):s(a)}min(e,r){return new ZodSet({...this._def,minSize:{value:e,message:errorUtil.toString(r)}})}max(e,r){return new ZodSet({...this._def,maxSize:{value:e,message:errorUtil.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}ZodSet.create=(t,e)=>new ZodSet({valueType:t,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(e)});class ZodLazy extends ZodType{get schema(){return this._def.getter()}_parse(e){const{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}ZodLazy.create=(t,e)=>new ZodLazy({getter:t,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(e)});class ZodLiteral extends ZodType{_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return addIssueToContext(r,{received:r.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}}ZodLiteral.create=(t,e)=>new ZodLiteral({value:t,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(e)});function createZodEnum(t,e){return new ZodEnum({values:t,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(e)})}class ZodEnum extends ZodType{_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),n=this._def.values;return addIssueToContext(r,{expected:util.joinValues(n),received:r.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const r=this._getOrReturnCtx(e),n=this._def.values;return addIssueToContext(r,{received:r.data,code:ZodIssueCode.invalid_enum_value,options:n}),INVALID}return OK(e.data)}get options(){return this._def.values}get enum(){const e={};for(const r of this._def.values)e[r]=r;return e}get Values(){const e={};for(const r of this._def.values)e[r]=r;return e}get Enum(){const e={};for(const r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return ZodEnum.create(e,{...this._def,...r})}exclude(e,r=this._def){return ZodEnum.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}}ZodEnum.create=createZodEnum;class ZodNativeEnum extends ZodType{_parse(e){const r=util.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==ZodParsedType.string&&n.parsedType!==ZodParsedType.number){const i=util.objectValues(r);return addIssueToContext(n,{expected:util.joinValues(i),received:n.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const i=util.objectValues(r);return addIssueToContext(n,{received:n.data,code:ZodIssueCode.invalid_enum_value,options:i}),INVALID}return OK(e.data)}get enum(){return this._def.values}}ZodNativeEnum.create=(t,e)=>new ZodNativeEnum({values:t,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(e)});class ZodPromise extends ZodType{unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==ZodParsedType.promise&&r.common.async===!1)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:r.parsedType}),INVALID;const n=r.parsedType===ZodParsedType.promise?r.data:Promise.resolve(r.data);return OK(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}}ZodPromise.create=(t,e)=>new ZodPromise({type:t,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(e)});class ZodEffects extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,o={addIssue:s=>{addIssueToContext(n,s),s.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){const s=i.transform(n.data,o);if(n.common.async)return Promise.resolve(s).then(async a=>{if(r.value==="aborted")return INVALID;const l=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return l.status==="aborted"?INVALID:l.status==="dirty"||r.value==="dirty"?DIRTY(l.value):l});{if(r.value==="aborted")return INVALID;const a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?INVALID:a.status==="dirty"||r.value==="dirty"?DIRTY(a.value):a}}if(i.type==="refinement"){const s=a=>{const l=i.refinement(a,o);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?INVALID:(a.status==="dirty"&&r.dirty(),s(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?INVALID:(a.status==="dirty"&&r.dirty(),s(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){const s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!isValid(s))return INVALID;const a=i.transform(s.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>isValid(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):INVALID);util.assertNever(i)}}ZodEffects.create=(t,e,r)=>new ZodEffects({schema:t,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:e,...processCreateParams(r)}),ZodEffects.createWithPreprocess=(t,e,r)=>new ZodEffects({schema:e,effect:{type:"preprocess",transform:t},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(r)});class ZodOptional extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodOptional.create=(t,e)=>new ZodOptional({innerType:t,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(e)});class ZodNullable extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.null?OK(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodNullable.create=(t,e)=>new ZodNullable({innerType:t,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(e)});class ZodDefault extends ZodType{_parse(e){const{ctx:r}=this._processInputParams(e);let n=r.data;return r.parsedType===ZodParsedType.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}ZodDefault.create=(t,e)=>new ZodDefault({innerType:t,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...processCreateParams(e)});class ZodCatch extends ZodType{_parse(e){const{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return isAsync(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ZodError(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ZodError(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}ZodCatch.create=(t,e)=>new ZodCatch({innerType:t,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...processCreateParams(e)});class ZodNaN extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.nan){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:n.parsedType}),INVALID}return{status:"valid",value:e.data}}}ZodNaN.create=t=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(t)});class ZodBranded extends ZodType{_parse(e){const{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class ZodPipeline extends ZodType{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?INVALID:o.status==="dirty"?(r.dirty(),DIRTY(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{const i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?INVALID:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new ZodPipeline({in:e,out:r,typeName:ZodFirstPartyTypeKind.ZodPipeline})}}class ZodReadonly extends ZodType{_parse(e){const r=this._def.innerType._parse(e),n=i=>(isValid(i)&&(i.value=Object.freeze(i.value)),i);return isAsync(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}}ZodReadonly.create=(t,e)=>new ZodReadonly({innerType:t,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(e)});var ZodFirstPartyTypeKind;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));const stringType=ZodString.create,numberType=ZodNumber.create,booleanType=ZodBoolean.create;ZodNever.create,ZodArray.create;const objectType=ZodObject.create;ZodUnion.create,ZodIntersection.create,ZodTuple.create;const enumType=ZodEnum.create;ZodPromise.create,ZodOptional.create,ZodNullable.create;function parseAnyDef(t){if(t.target!=="openAi")return{};const e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?getRelativePath(e,t.currentPath):e.join("/")}}function parseArrayDef(t,e){const r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==ZodFirstPartyTypeKind.ZodAny&&(r.items=parseDef(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&setResponseValueAndErrors(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&setResponseValueAndErrors(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(setResponseValueAndErrors(r,"minItems",t.exactLength.value,t.exactLength.message,e),setResponseValueAndErrors(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function parseBigintDef(t,e){const r={type:"integer",format:"int64"};if(!t.checks)return r;for(const n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?setResponseValueAndErrors(r,"minimum",n.value,n.message,e):setResponseValueAndErrors(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),setResponseValueAndErrors(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?setResponseValueAndErrors(r,"maximum",n.value,n.message,e):setResponseValueAndErrors(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),setResponseValueAndErrors(r,"maximum",n.value,n.message,e));break;case"multipleOf":setResponseValueAndErrors(r,"multipleOf",n.value,n.message,e);break}return r}function parseBooleanDef(){return{type:"boolean"}}function parseBrandedDef(t,e){return parseDef(t.type._def,e)}const parseCatchDef=(t,e)=>parseDef(t.innerType._def,e);function parseDateDef(t,e,r){const n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((i,o)=>parseDateDef(t,e,i))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return integerDateParser(t,e)}}const integerDateParser=(t,e)=>{const r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(const n of t.checks)switch(n.kind){case"min":setResponseValueAndErrors(r,"minimum",n.value,n.message,e);break;case"max":setResponseValueAndErrors(r,"maximum",n.value,n.message,e);break}return r};function parseDefaultDef(t,e){return{...parseDef(t.innerType._def,e),default:t.defaultValue()}}function parseEffectsDef(t,e){return e.effectStrategy==="input"?parseDef(t.schema._def,e):parseAnyDef(e)}function parseEnumDef(t){return{type:"string",enum:Array.from(t.values)}}const isJsonSchema7AllOfType=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function parseIntersectionDef(t,e){const r=[parseDef(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),parseDef(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o);let n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const i=[];return r.forEach(o=>{if(isJsonSchema7AllOfType(o))i.push(...o.allOf),o.unevaluatedProperties===void 0&&(n=void 0);else{let s=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:a,...l}=o;s=l}else n=void 0;i.push(s)}}),i.length?{allOf:i,...n}:void 0}function parseLiteralDef(t,e){const r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.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(t,e){const r={type:"string"};if(t.checks)for(const n of t.checks)switch(n.kind){case"min":setResponseValueAndErrors(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":setResponseValueAndErrors(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":addFormat(r,"email",n.message,e);break;case"format:idn-email":addFormat(r,"idn-email",n.message,e);break;case"pattern:zod":addPattern(r,zodPatterns.email,n.message,e);break}break;case"url":addFormat(r,"uri",n.message,e);break;case"uuid":addFormat(r,"uuid",n.message,e);break;case"regex":addPattern(r,n.regex,n.message,e);break;case"cuid":addPattern(r,zodPatterns.cuid,n.message,e);break;case"cuid2":addPattern(r,zodPatterns.cuid2,n.message,e);break;case"startsWith":addPattern(r,RegExp(`^${escapeLiteralCheckValue(n.value,e)}`),n.message,e);break;case"endsWith":addPattern(r,RegExp(`${escapeLiteralCheckValue(n.value,e)}$`),n.message,e);break;case"datetime":addFormat(r,"date-time",n.message,e);break;case"date":addFormat(r,"date",n.message,e);break;case"time":addFormat(r,"time",n.message,e);break;case"duration":addFormat(r,"duration",n.message,e);break;case"length":setResponseValueAndErrors(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),setResponseValueAndErrors(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{addPattern(r,RegExp(escapeLiteralCheckValue(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&addFormat(r,"ipv4",n.message,e),n.version!=="v4"&&addFormat(r,"ipv6",n.message,e);break}case"base64url":addPattern(r,zodPatterns.base64url,n.message,e);break;case"jwt":addPattern(r,zodPatterns.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&addPattern(r,zodPatterns.ipv4Cidr,n.message,e),n.version!=="v4"&&addPattern(r,zodPatterns.ipv6Cidr,n.message,e);break}case"emoji":addPattern(r,zodPatterns.emoji(),n.message,e);break;case"ulid":{addPattern(r,zodPatterns.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{addFormat(r,"binary",n.message,e);break}case"contentEncoding:base64":{setResponseValueAndErrors(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{addPattern(r,zodPatterns.base64,n.message,e);break}}break}case"nanoid":addPattern(r,zodPatterns.nanoid,n.message,e)}return r}function escapeLiteralCheckValue(t,e){return e.patternStrategy==="escape"?escapeNonAlphaNumeric(t):t}const ALPHA_NUMERIC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function escapeNonAlphaNumeric(t){let e="";for(let r=0;r<t.length;r++)ALPHA_NUMERIC.has(t[r])||(e+="\\"),e+=t[r];return e}function addFormat(t,e,r,n){t.format||t.anyOf?.some(i=>i.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):setResponseValueAndErrors(t,"format",e,r,n)}function addPattern(t,e,r,n){t.pattern||t.allOf?.some(i=>i.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:stringifyRegExpWithFlags(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):setResponseValueAndErrors(t,"pattern",stringifyRegExpWithFlags(e,n),r,n)}function stringifyRegExpWithFlags(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;const r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source;let i="",o=!1,s=!1,a=!1;for(let l=0;l<n.length;l++){if(o){i+=n[l],o=!1;continue}if(r.i){if(s){if(n[l].match(/[a-z]/)){a?(i+=n[l],i+=`${n[l-2]}-${n[l]}`.toUpperCase(),a=!1):n[l+1]==="-"&&n[l+2]?.match(/[a-z]/)?(i+=n[l],a=!0):i+=`${n[l]}${n[l].toUpperCase()}`;continue}}else if(n[l].match(/[a-z]/)){i+=`[${n[l]}${n[l].toUpperCase()}]`;continue}}if(r.m){if(n[l]==="^"){i+=`(^|(?<=[\r
173
173
  ]))`;continue}else if(n[l]==="$"){i+=`($|(?=[\r
174
174
  ]))`;continue}}if(r.s&&n[l]==="."){i+=s?`${n[l]}\r
175
175
  `:`[${n[l]}\r
176
- ]`;continue}i+=n[l],n[l]==="\\"?o=!0:s&&n[l]==="]"?s=!1:!s&&n[l]==="["&&(s=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return i}function parseRecordDef(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,i)=>({...n,[i]:parseDef(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",i]})??parseAnyDef(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};const r={type:"object",additionalProperties:parseDef(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodString&&t.keyType._def.checks?.length){const{type:n,...i}=parseStringDef(t.keyType._def,e);return{...r,propertyNames:i}}else{if(t.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodBranded&&t.keyType._def.type._def.typeName===ZodFirstPartyTypeKind.ZodString&&t.keyType._def.type._def.checks?.length){const{type:n,...i}=parseBrandedDef(t.keyType._def,e);return{...r,propertyNames:i}}}return r}function parseMapDef(t,e){if(e.mapStrategy==="record")return parseRecordDef(t,e);const r=parseDef(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||parseAnyDef(e),n=parseDef(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||parseAnyDef(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function parseNativeEnumDef(t){const e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),i=Array.from(new Set(n.map(o=>typeof o)));return{type:i.length===1?i[0]==="string"?"string":"number":["string","number"],enum:n}}function parseNeverDef(t){return t.target==="openAi"?void 0:{not:parseAnyDef({...t,currentPath:[...t.currentPath,"not"]})}}function parseNullDef(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function parseUnionDef(t,e){if(e.target==="openApi3")return asAnyOf(t,e);const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in primitiveMappings&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((i,o)=>{const s=primitiveMappings[o._def.typeName];return s&&!i.includes(s)?[...i,s]:i},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((i,o)=>{const s=typeof o._def.value;switch(s){case"string":case"number":case"boolean":return[...i,s];case"bigint":return[...i,"integer"];case"object":if(o._def.value===null)return[...i,"null"];case"symbol":case"undefined":case"function":default:return i}},[]);if(n.length===r.length){const i=n.filter((o,s,a)=>a.indexOf(o)===s);return{type:i.length>1?i:i[0],enum:r.reduce((o,s)=>o.includes(s._def.value)?o:[...o,s._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,i)=>[...n,...i._def.values.filter(o=>!n.includes(o))],[])};return asAnyOf(t,e)}const asAnyOf=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,i)=>parseDef(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${i}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function parseNullableDef(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:primitiveMappings[t.innerType._def.typeName],nullable:!0}:{type:[primitiveMappings[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const n=parseDef(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const r=parseDef(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function parseNumberDef(t,e){const r={type:"number"};if(!t.checks)return r;for(const n of t.checks)switch(n.kind){case"int":r.type="integer",addErrorMessage(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?setResponseValueAndErrors(r,"minimum",n.value,n.message,e):setResponseValueAndErrors(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),setResponseValueAndErrors(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?setResponseValueAndErrors(r,"maximum",n.value,n.message,e):setResponseValueAndErrors(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),setResponseValueAndErrors(r,"maximum",n.value,n.message,e));break;case"multipleOf":setResponseValueAndErrors(r,"multipleOf",n.value,n.message,e);break}return r}function parseObjectDef(t,e){const r=e.target==="openAi",n={type:"object",properties:{}},i=[],o=t.shape();for(const a in o){let l=o[a];if(l===void 0||l._def===void 0)continue;let d=safeIsOptional(l);d&&r&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),d=!1);const u=parseDef(l._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});u!==void 0&&(n.properties[a]=u,d||i.push(a))}i.length&&(n.required=i);const s=decideAdditionalProperties(t,e);return s!==void 0&&(n.additionalProperties=s),n}function decideAdditionalProperties(t,e){if(t.catchall._def.typeName!=="ZodNever")return parseDef(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function safeIsOptional(t){try{return t.isOptional()}catch{return!0}}const parseOptionalDef=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return parseDef(t.innerType._def,e);const r=parseDef(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:parseAnyDef(e)},r]}:parseAnyDef(e)},parsePipelineDef=(t,e)=>{if(e.pipeStrategy==="input")return parseDef(t.in._def,e);if(e.pipeStrategy==="output")return parseDef(t.out._def,e);const r=parseDef(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=parseDef(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(i=>i!==void 0)}};function parsePromiseDef(t,e){return parseDef(t.type._def,e)}function parseSetDef(t,e){const n={type:"array",uniqueItems:!0,items:parseDef(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&setResponseValueAndErrors(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&setResponseValueAndErrors(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function parseTupleDef(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>parseDef(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:parseDef(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>parseDef(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function parseUndefinedDef(t){return{not:parseAnyDef(t)}}function parseUnknownDef(t){return parseAnyDef(t)}const parseReadonlyDef=(t,e)=>parseDef(t.innerType._def,e),selectParser=(t,e,r)=>{switch(e){case ZodFirstPartyTypeKind.ZodString:return parseStringDef(t,r);case ZodFirstPartyTypeKind.ZodNumber:return parseNumberDef(t,r);case ZodFirstPartyTypeKind.ZodObject:return parseObjectDef(t,r);case ZodFirstPartyTypeKind.ZodBigInt:return parseBigintDef(t,r);case ZodFirstPartyTypeKind.ZodBoolean:return parseBooleanDef();case ZodFirstPartyTypeKind.ZodDate:return parseDateDef(t,r);case ZodFirstPartyTypeKind.ZodUndefined:return parseUndefinedDef(r);case ZodFirstPartyTypeKind.ZodNull:return parseNullDef(r);case ZodFirstPartyTypeKind.ZodArray:return parseArrayDef(t,r);case ZodFirstPartyTypeKind.ZodUnion:case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return parseUnionDef(t,r);case ZodFirstPartyTypeKind.ZodIntersection:return parseIntersectionDef(t,r);case ZodFirstPartyTypeKind.ZodTuple:return parseTupleDef(t,r);case ZodFirstPartyTypeKind.ZodRecord:return parseRecordDef(t,r);case ZodFirstPartyTypeKind.ZodLiteral:return parseLiteralDef(t,r);case ZodFirstPartyTypeKind.ZodEnum:return parseEnumDef(t);case ZodFirstPartyTypeKind.ZodNativeEnum:return parseNativeEnumDef(t);case ZodFirstPartyTypeKind.ZodNullable:return parseNullableDef(t,r);case ZodFirstPartyTypeKind.ZodOptional:return parseOptionalDef(t,r);case ZodFirstPartyTypeKind.ZodMap:return parseMapDef(t,r);case ZodFirstPartyTypeKind.ZodSet:return parseSetDef(t,r);case ZodFirstPartyTypeKind.ZodLazy:return()=>t.getter()._def;case ZodFirstPartyTypeKind.ZodPromise:return parsePromiseDef(t,r);case ZodFirstPartyTypeKind.ZodNaN:case ZodFirstPartyTypeKind.ZodNever:return parseNeverDef(r);case ZodFirstPartyTypeKind.ZodEffects:return parseEffectsDef(t,r);case ZodFirstPartyTypeKind.ZodAny:return parseAnyDef(r);case ZodFirstPartyTypeKind.ZodUnknown:return parseUnknownDef(r);case ZodFirstPartyTypeKind.ZodDefault:return parseDefaultDef(t,r);case ZodFirstPartyTypeKind.ZodBranded:return parseBrandedDef(t,r);case ZodFirstPartyTypeKind.ZodReadonly:return parseReadonlyDef(t,r);case ZodFirstPartyTypeKind.ZodCatch:return parseCatchDef(t,r);case ZodFirstPartyTypeKind.ZodPipeline:return parsePipelineDef(t,r);case ZodFirstPartyTypeKind.ZodFunction:case ZodFirstPartyTypeKind.ZodVoid:case ZodFirstPartyTypeKind.ZodSymbol:return;default:return(n=>{})()}};function parseDef(t,e,r=!1){const n=e.seen.get(t);if(e.override){const a=e.override?.(t,e,n,r);if(a!==ignoreOverride)return a}if(n&&!r){const a=get$ref(n,e);if(a!==void 0)return a}const i={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,i);const o=selectParser(t,t.typeName,e),s=typeof o=="function"?parseDef(o(),e):o;if(s&&addMeta(t,e,s),e.postProcess){const a=e.postProcess(s,t,e);return i.jsonSchema=s,a}return i.jsonSchema=s,s}const get$ref=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:getRelativePath(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),parseAnyDef(e)):e.$refStrategy==="seen"?parseAnyDef(e):void 0}},addMeta=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r),zodToJsonSchema=(t,e)=>{const r=getRefs(e);let n;const i=e?.name,o=parseDef(t._def,r,!1)??parseAnyDef(r);r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));const s=i===void 0?n?{...o,[r.definitionPath]:n}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,i].join("/"),[r.definitionPath]:{...n,[i]:o}};return r.target==="jsonSchema7"?s.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),r.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=`## 角色
176
+ ]`;continue}i+=n[l],n[l]==="\\"?o=!0:s&&n[l]==="]"?s=!1:!s&&n[l]==="["&&(s=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return i}function parseRecordDef(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,i)=>({...n,[i]:parseDef(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",i]})??parseAnyDef(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};const r={type:"object",additionalProperties:parseDef(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodString&&t.keyType._def.checks?.length){const{type:n,...i}=parseStringDef(t.keyType._def,e);return{...r,propertyNames:i}}else{if(t.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodBranded&&t.keyType._def.type._def.typeName===ZodFirstPartyTypeKind.ZodString&&t.keyType._def.type._def.checks?.length){const{type:n,...i}=parseBrandedDef(t.keyType._def,e);return{...r,propertyNames:i}}}return r}function parseMapDef(t,e){if(e.mapStrategy==="record")return parseRecordDef(t,e);const r=parseDef(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||parseAnyDef(e),n=parseDef(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||parseAnyDef(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function parseNativeEnumDef(t){const e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),i=Array.from(new Set(n.map(o=>typeof o)));return{type:i.length===1?i[0]==="string"?"string":"number":["string","number"],enum:n}}function parseNeverDef(t){return t.target==="openAi"?void 0:{not:parseAnyDef({...t,currentPath:[...t.currentPath,"not"]})}}function parseNullDef(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function parseUnionDef(t,e){if(e.target==="openApi3")return asAnyOf(t,e);const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in primitiveMappings&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((i,o)=>{const s=primitiveMappings[o._def.typeName];return s&&!i.includes(s)?[...i,s]:i},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((i,o)=>{const s=typeof o._def.value;switch(s){case"string":case"number":case"boolean":return[...i,s];case"bigint":return[...i,"integer"];case"object":if(o._def.value===null)return[...i,"null"];case"symbol":case"undefined":case"function":default:return i}},[]);if(n.length===r.length){const i=n.filter((o,s,a)=>a.indexOf(o)===s);return{type:i.length>1?i:i[0],enum:r.reduce((o,s)=>o.includes(s._def.value)?o:[...o,s._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,i)=>[...n,...i._def.values.filter(o=>!n.includes(o))],[])};return asAnyOf(t,e)}const asAnyOf=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,i)=>parseDef(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${i}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function parseNullableDef(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:primitiveMappings[t.innerType._def.typeName],nullable:!0}:{type:[primitiveMappings[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const n=parseDef(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const r=parseDef(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function parseNumberDef(t,e){const r={type:"number"};if(!t.checks)return r;for(const n of t.checks)switch(n.kind){case"int":r.type="integer",addErrorMessage(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?setResponseValueAndErrors(r,"minimum",n.value,n.message,e):setResponseValueAndErrors(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),setResponseValueAndErrors(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?setResponseValueAndErrors(r,"maximum",n.value,n.message,e):setResponseValueAndErrors(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),setResponseValueAndErrors(r,"maximum",n.value,n.message,e));break;case"multipleOf":setResponseValueAndErrors(r,"multipleOf",n.value,n.message,e);break}return r}function parseObjectDef(t,e){const r=e.target==="openAi",n={type:"object",properties:{}},i=[],o=t.shape();for(const a in o){let l=o[a];if(l===void 0||l._def===void 0)continue;let c=safeIsOptional(l);c&&r&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),c=!1);const u=parseDef(l._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});u!==void 0&&(n.properties[a]=u,c||i.push(a))}i.length&&(n.required=i);const s=decideAdditionalProperties(t,e);return s!==void 0&&(n.additionalProperties=s),n}function decideAdditionalProperties(t,e){if(t.catchall._def.typeName!=="ZodNever")return parseDef(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function safeIsOptional(t){try{return t.isOptional()}catch{return!0}}const parseOptionalDef=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return parseDef(t.innerType._def,e);const r=parseDef(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:parseAnyDef(e)},r]}:parseAnyDef(e)},parsePipelineDef=(t,e)=>{if(e.pipeStrategy==="input")return parseDef(t.in._def,e);if(e.pipeStrategy==="output")return parseDef(t.out._def,e);const r=parseDef(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=parseDef(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(i=>i!==void 0)}};function parsePromiseDef(t,e){return parseDef(t.type._def,e)}function parseSetDef(t,e){const n={type:"array",uniqueItems:!0,items:parseDef(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&setResponseValueAndErrors(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&setResponseValueAndErrors(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function parseTupleDef(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>parseDef(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:parseDef(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>parseDef(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function parseUndefinedDef(t){return{not:parseAnyDef(t)}}function parseUnknownDef(t){return parseAnyDef(t)}const parseReadonlyDef=(t,e)=>parseDef(t.innerType._def,e),selectParser=(t,e,r)=>{switch(e){case ZodFirstPartyTypeKind.ZodString:return parseStringDef(t,r);case ZodFirstPartyTypeKind.ZodNumber:return parseNumberDef(t,r);case ZodFirstPartyTypeKind.ZodObject:return parseObjectDef(t,r);case ZodFirstPartyTypeKind.ZodBigInt:return parseBigintDef(t,r);case ZodFirstPartyTypeKind.ZodBoolean:return parseBooleanDef();case ZodFirstPartyTypeKind.ZodDate:return parseDateDef(t,r);case ZodFirstPartyTypeKind.ZodUndefined:return parseUndefinedDef(r);case ZodFirstPartyTypeKind.ZodNull:return parseNullDef(r);case ZodFirstPartyTypeKind.ZodArray:return parseArrayDef(t,r);case ZodFirstPartyTypeKind.ZodUnion:case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return parseUnionDef(t,r);case ZodFirstPartyTypeKind.ZodIntersection:return parseIntersectionDef(t,r);case ZodFirstPartyTypeKind.ZodTuple:return parseTupleDef(t,r);case ZodFirstPartyTypeKind.ZodRecord:return parseRecordDef(t,r);case ZodFirstPartyTypeKind.ZodLiteral:return parseLiteralDef(t,r);case ZodFirstPartyTypeKind.ZodEnum:return parseEnumDef(t);case ZodFirstPartyTypeKind.ZodNativeEnum:return parseNativeEnumDef(t);case ZodFirstPartyTypeKind.ZodNullable:return parseNullableDef(t,r);case ZodFirstPartyTypeKind.ZodOptional:return parseOptionalDef(t,r);case ZodFirstPartyTypeKind.ZodMap:return parseMapDef(t,r);case ZodFirstPartyTypeKind.ZodSet:return parseSetDef(t,r);case ZodFirstPartyTypeKind.ZodLazy:return()=>t.getter()._def;case ZodFirstPartyTypeKind.ZodPromise:return parsePromiseDef(t,r);case ZodFirstPartyTypeKind.ZodNaN:case ZodFirstPartyTypeKind.ZodNever:return parseNeverDef(r);case ZodFirstPartyTypeKind.ZodEffects:return parseEffectsDef(t,r);case ZodFirstPartyTypeKind.ZodAny:return parseAnyDef(r);case ZodFirstPartyTypeKind.ZodUnknown:return parseUnknownDef(r);case ZodFirstPartyTypeKind.ZodDefault:return parseDefaultDef(t,r);case ZodFirstPartyTypeKind.ZodBranded:return parseBrandedDef(t,r);case ZodFirstPartyTypeKind.ZodReadonly:return parseReadonlyDef(t,r);case ZodFirstPartyTypeKind.ZodCatch:return parseCatchDef(t,r);case ZodFirstPartyTypeKind.ZodPipeline:return parsePipelineDef(t,r);case ZodFirstPartyTypeKind.ZodFunction:case ZodFirstPartyTypeKind.ZodVoid:case ZodFirstPartyTypeKind.ZodSymbol:return;default:return(n=>{})()}};function parseDef(t,e,r=!1){const n=e.seen.get(t);if(e.override){const a=e.override?.(t,e,n,r);if(a!==ignoreOverride)return a}if(n&&!r){const a=get$ref(n,e);if(a!==void 0)return a}const i={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,i);const o=selectParser(t,t.typeName,e),s=typeof o=="function"?parseDef(o(),e):o;if(s&&addMeta(t,e,s),e.postProcess){const a=e.postProcess(s,t,e);return i.jsonSchema=s,a}return i.jsonSchema=s,s}const get$ref=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:getRelativePath(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),parseAnyDef(e)):e.$refStrategy==="seen"?parseAnyDef(e):void 0}},addMeta=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r),zodToJsonSchema=(t,e)=>{const r=getRefs(e);let n;const i=e?.name,o=parseDef(t._def,r,!1)??parseAnyDef(r);r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));const s=i===void 0?n?{...o,[r.definitionPath]:n}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,i].join("/"),[r.definitionPath]:{...n,[i]:o}};return r.target==="jsonSchema7"?s.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),r.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
177
 
178
178
  你是浏览器页面的操作工具,你拥有识别网页内容,点击,填写,选择下拉框和滚动页面等功能。
179
179
 
@@ -218,7 +218,7 @@ Known schemas:
218
218
  - \`- role #N [token1] [token2] "accessible name"\`
219
219
  - \`role\`:ARIA 语义角色(如 button/link/radio/heading/listitem/generic 等)
220
220
  - \`#N\`:可交互元素的唯一操作索引,**只有带 \`#N\` 的节点才能被操作**,操作时将 N 作为 \`index\` 参数传入
221
- - \`[token]\`:可选 token,包括状态标记(如 \`[checked]\` \`[selected]\` \`[disabled]\` \`[cursor=pointer]\`)和定制属性(如 \`[cf-uba="..."]\`)
221
+ - \`[token]\`:可选 token,包括状态标记(如 \`[checked]\` \`[selected]\` \`[pressed]\` \`[current]\` \`[expanded]\` \`[disabled]\` \`[readonly]\` \`[required]\` \`[invalid]\` \`[busy]\` \`[error]\` \`[warning]\` \`[cursor=pointer]\`)和定制属性(如 \`[cf-uba="..."]\`)
222
222
  - \`"accessible name"\`:元素的语义化名称,**用双引号包裹**(通过 aria-label/aria-labelledby/innerText 等计算得出);无名称的节点此字段省略
223
223
  - 缩进表示父子关系
224
224
 
@@ -312,7 +312,7 @@ Diff 格式示例如下:
312
312
  - 如果绝对不可能继续。
313
313
 
314
314
  </task_completion_rules>
315
- `;function isHTMLElement(t){return!!t&&t.nodeType===1}function isInputElement(t){return t?.nodeType===1&&t.tagName==="INPUT"}function isTextAreaElement(t){return t?.nodeType===1&&t.tagName==="TEXTAREA"}function isSelectElement(t){return t?.nodeType===1&&t.tagName==="SELECT"}function isAnchorElement(t){return t?.nodeType===1&&t.tagName==="A"}function getIframeOffset(t){const e=t.ownerDocument.defaultView?.frameElement;if(!e)return{x:0,y:0};const r=e.getBoundingClientRect();return{x:r.left,y:r.top}}function getNativeValueSetter(t){return Object.getOwnPropertyDescriptor(Object.getPrototypeOf(t),"value").set}async function waitFor(t){await new Promise(e=>setTimeout(e,t*1e3))}async function movePointerToElement(t,e,r){const n=getIframeOffset(t);window.dispatchEvent(new CustomEvent("PageAgent::MovePointerTo",{detail:{x:e+n.x,y:r+n.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(t,e){const r=t.get(e);if(!r)throw new Error(`No interactive element found at index ${e}`);const n=r.ref;if(!n)throw new Error(`Element at index ${e} does not have a reference`);if(!isHTMLElement(n))throw new Error(`Element at index ${e} is not an HTMLElement`);return n}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(t){blurLastClickedElement(),lastClickedElement=t,await scrollIntoViewIfNeeded(t);const e=t.ownerDocument.defaultView?.frameElement;e&&await scrollIntoViewIfNeeded(e);const r=t.getBoundingClientRect(),n=r.left+r.width/2,i=r.top+r.height/2;await movePointerToElement(t,n,i),await clickPointer(),await waitFor(.1);const o=t.ownerDocument;await enablePassThrough();const s=o.elementFromPoint(n,i);await disablePassThrough();const a=s instanceof HTMLElement&&t.contains(s)?s:t,l={bubbles:!0,cancelable:!0,clientX:n,clientY:i,pointerType:"mouse"},d={bubbles:!0,cancelable:!0,clientX:n,clientY:i,button:0};a.dispatchEvent(new PointerEvent("pointerover",l)),a.dispatchEvent(new PointerEvent("pointerenter",{...l,bubbles:!1})),a.dispatchEvent(new MouseEvent("mouseover",d)),a.dispatchEvent(new MouseEvent("mouseenter",{...d,bubbles:!1})),a.dispatchEvent(new PointerEvent("pointerdown",l)),a.dispatchEvent(new MouseEvent("mousedown",d)),t.focus({preventScroll:!0}),a.dispatchEvent(new PointerEvent("pointerup",l)),a.dispatchEvent(new MouseEvent("mouseup",d)),a.click(),await waitFor(.2)}async function inputTextElement(t,e){const r=t.isContentEditable;if(!isInputElement(t)&&!isTextAreaElement(t)&&!r)throw new Error("Element is not an input, textarea, or contenteditable");if(await clickElement(t),r){if(t.dispatchEvent(new InputEvent("beforeinput",{bubbles:!0,cancelable:!0,inputType:"deleteContent"}))&&(t.innerText="",t.dispatchEvent(new InputEvent("input",{bubbles:!0,inputType:"deleteContent"}))),t.dispatchEvent(new InputEvent("beforeinput",{bubbles:!0,cancelable:!0,inputType:"insertText",data:e}))&&(t.innerText=e,t.dispatchEvent(new InputEvent("input",{bubbles:!0,inputType:"insertText",data:e}))),t.innerText.trim()!==e.trim()){t.focus();const n=t.ownerDocument,i=(n.defaultView||window).getSelection(),o=n.createRange();o.selectNodeContents(t),i?.removeAllRanges(),i?.addRange(o),n.execCommand("delete",!1),n.execCommand("insertText",!1,e)}t.dispatchEvent(new Event("change",{bubbles:!0})),t.blur()}else getNativeValueSetter(t).call(t,e);r||t.dispatchEvent(new Event("input",{bubbles:!0})),await waitFor(.1),blurLastClickedElement()}async function selectOptionElement(t,e){if(!isSelectElement(t))throw new Error("Element is not a select element");const r=Array.from(t.options).find(n=>n.textContent?.trim()===e.trim());if(!r)throw new Error(`Option with text "${e}" not found in select element`);t.value=r.value,t.dispatchEvent(new Event("change",{bubbles:!0})),await waitFor(.1)}async function scrollIntoViewIfNeeded(t){const e=t;typeof e.scrollIntoViewIfNeeded=="function"?e.scrollIntoViewIfNeeded():t.scrollIntoView({behavior:"auto",block:"center",inline:"nearest"})}async function scrollVertically(t,e){if(e){const s=e;let a=s,l=!1,d=null,u=0,f=0;const p=t;for(;a&&f<10;){const g=window.getComputedStyle(a),y=/(auto|scroll|overlay)/.test(g.overflowY)||g.scrollbarWidth&&g.scrollbarWidth!=="auto"||g.scrollbarGutter&&g.scrollbarGutter!=="auto",Z=a.scrollHeight>a.clientHeight;if(y&&Z){const x=a.scrollTop,h=a.scrollHeight-a.clientHeight;let S=p/3;S>0?S=Math.min(S,h-x):S=Math.max(S,-x),a.scrollTop=x+S;const I=a.scrollTop-x;if(Math.abs(I)>.5){l=!0,d=a,u=I;break}}if(a===document.body||a===document.documentElement)break;a=a.parentElement,f++}return l?`Scrolled container (${d?.tagName}) by ${u}px`:`No scrollable container found for element (${s.tagName})`}const r=t,n=s=>s.clientHeight>=window.innerHeight*.5,i=s=>!!(s&&/(auto|scroll|overlay)/.test(getComputedStyle(s).overflowY)&&s.scrollHeight>s.clientHeight&&n(s));let o=document.activeElement;for(;o&&!i(o)&&o!==document.body;)o=o.parentElement;if(o=i(o)?o:Array.from(document.querySelectorAll("*")).find(i)||document.scrollingElement||document.documentElement,o===document.scrollingElement||o===document.documentElement||o===document.body){const s=window.scrollY,a=document.documentElement.scrollHeight-window.innerHeight;window.scrollBy(0,r);const l=window.scrollY,d=l-s;if(Math.abs(d)<1)return r>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=r>0&&l>=a-1,f=r<0&&l<=1;return u?`✅ Scrolled page by ${d}px. Reached the bottom of the page.`:f?`✅ Scrolled page by ${d}px. Reached the top of the page.`:`✅ Scrolled page by ${d}px.`}else{const s="The document is not scrollable. Falling back to container scroll.";console.log(`[PageController] ${s}`);const a=o.scrollTop,l=o.scrollHeight-o.clientHeight;o.scrollBy({top:r,behavior:"smooth"}),await waitFor(.1);const d=o.scrollTop,u=d-a;if(Math.abs(u)<1)return r>0?`⚠️ ${s} Already at the bottom of container (${o.tagName}), cannot scroll down further.`:`⚠️ ${s} Already at the top of container (${o.tagName}), cannot scroll up further.`;const f=r>0&&d>=l-1,p=r<0&&d<=1;return f?`✅ ${s} Scrolled container (${o.tagName}) by ${u}px. Reached the bottom.`:p?`✅ ${s} Scrolled container (${o.tagName}) by ${u}px. Reached the top.`:`✅ ${s} Scrolled container (${o.tagName}) by ${u}px.`}}async function scrollHorizontally(t,e){if(e){const s=e;let a=s,l=!1,d=null,u=0,f=0;const p=t;for(;a&&f<10;){const g=window.getComputedStyle(a),y=/(auto|scroll|overlay)/.test(g.overflowX)||g.scrollbarWidth&&g.scrollbarWidth!=="auto"||g.scrollbarGutter&&g.scrollbarGutter!=="auto",Z=a.scrollWidth>a.clientWidth;if(y&&Z){const x=a.scrollLeft,h=a.scrollWidth-a.clientWidth;let S=p/3;S>0?S=Math.min(S,h-x):S=Math.max(S,-x),a.scrollLeft=x+S;const I=a.scrollLeft-x;if(Math.abs(I)>.5){l=!0,d=a,u=I;break}}if(a===document.body||a===document.documentElement)break;a=a.parentElement,f++}return l?`Scrolled container (${d?.tagName}) horizontally by ${u}px`:`No horizontally scrollable container found for element (${s.tagName})`}const r=t,n=s=>s.clientWidth>=window.innerWidth*.5,i=s=>!!(s&&/(auto|scroll|overlay)/.test(getComputedStyle(s).overflowX)&&s.scrollWidth>s.clientWidth&&n(s));let o=document.activeElement;for(;o&&!i(o)&&o!==document.body;)o=o.parentElement;if(o=i(o)?o:Array.from(document.querySelectorAll("*")).find(i)||document.scrollingElement||document.documentElement,o===document.scrollingElement||o===document.documentElement||o===document.body){const s=window.scrollX,a=document.documentElement.scrollWidth-window.innerWidth;window.scrollBy(r,0);const l=window.scrollX,d=l-s;if(Math.abs(d)<1)return r>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=r>0&&l>=a-1,f=r<0&&l<=1;return u?`✅ Scrolled page by ${d}px. Reached the right edge of the page.`:f?`✅ Scrolled page by ${d}px. Reached the left edge of the page.`:`✅ Scrolled page horizontally by ${d}px.`}else{const s="The document is not scrollable. Falling back to container scroll.";console.log(`[PageController] ${s}`);const a=o.scrollLeft,l=o.scrollWidth-o.clientWidth;o.scrollBy({left:r,behavior:"smooth"}),await waitFor(.1);const d=o.scrollLeft,u=d-a;if(Math.abs(u)<1)return r>0?`⚠️ ${s} Already at the right edge of container (${o.tagName}), cannot scroll right further.`:`⚠️ ${s} Already at the left edge of container (${o.tagName}), cannot scroll left further.`;const f=r>0&&d>=l-1,p=r<0&&d<=1;return f?`✅ ${s} Scrolled container (${o.tagName}) by ${u}px. Reached the right edge.`:p?`✅ ${s} Scrolled container (${o.tagName}) by ${u}px. Reached the left edge.`:`✅ ${s} Scrolled container (${o.tagName}) horizontally by ${u}px.`}}var dom_tree_default=(t={doHighlightElements:!0,focusHighlightIndex:-1,viewportExpansion:0,debugMode:!1,interactiveBlacklist:[],interactiveWhitelist:[],highlightOpacity:.1,highlightLabelOpacity:.5})=>{const{interactiveBlacklist:e,interactiveWhitelist:r,highlightOpacity:n,highlightLabelOpacity:i}=t,{doHighlightElements:o,focusHighlightIndex:s,viewportExpansion:a,debugMode:l}=t;let d=0;const u=new WeakMap;function f(c,v){!c||c.nodeType!==Node.ELEMENT_NODE||u.set(c,{...u.get(c),...v})}const p={boundingRects:new WeakMap,clientRects:new WeakMap,computedStyles:new WeakMap,clearCache:()=>{p.boundingRects=new WeakMap,p.clientRects=new WeakMap,p.computedStyles=new WeakMap}};function g(c){if(!c)return null;if(p.boundingRects.has(c))return p.boundingRects.get(c);const v=c.getBoundingClientRect();return v&&p.boundingRects.set(c,v),v}function y(c){if(!c)return null;if(p.computedStyles.has(c))return p.computedStyles.get(c);const v=window.getComputedStyle(c);return v&&p.computedStyles.set(c,v),v}function Z(c){if(!c)return null;if(p.clientRects.has(c))return p.clientRects.get(c);const v=c.getClientRects();return v&&p.clientRects.set(c,v),v}const x={},h={current:0},S="playwright-highlight-container";function I(c,v,z=null){if(!c)return v;const _=[];let P=null,B=20,E=16,M=null;try{let L=document.getElementById(S);L||(L=document.createElement("div"),L.id=S,L.style.position="fixed",L.style.pointerEvents="none",L.style.top="0",L.style.left="0",L.style.width="100%",L.style.height="100%",L.style.zIndex="2147483640",L.style.backgroundColor="transparent",document.body.appendChild(L));const U=c.getClientRects();if(!U||U.length===0)return v;const Y=["#FF0000","#00FF00","#0000FF","#FFA500","#800080","#008080","#FF69B4","#4B0082","#FF4500","#2E8B57","#DC143C","#4682B4"];let G=Y[v%Y.length];const ee=G+Math.floor(n*255).toString(16).padStart(2,"0");G=G+Math.floor(i*255).toString(16).padStart(2,"0");let J={x:0,y:0};if(z){const k=z.getBoundingClientRect();J.x=k.left,J.y=k.top}const ae=document.createDocumentFragment();for(const k of U){if(k.width===0||k.height===0)continue;const b=document.createElement("div");b.style.position="fixed",b.style.border=`2px solid ${G}`,b.style.backgroundColor=ee,b.style.pointerEvents="none",b.style.boxSizing="border-box";const m=k.top+J.y,$=k.left+J.x;b.style.top=`${m}px`,b.style.left=`${$}px`,b.style.width=`${k.width}px`,b.style.height=`${k.height}px`,ae.appendChild(b),_.push({element:b,initialRect:k})}const ie=U[0];P=document.createElement("div"),P.className="playwright-highlight-label",P.style.position="fixed",P.style.background=G,P.style.color="white",P.style.padding="1px 4px",P.style.borderRadius="4px",P.style.fontSize=`${Math.min(12,Math.max(8,ie.height/2))}px`,P.textContent=v.toString(),B=P.offsetWidth>0?P.offsetWidth:B,E=P.offsetHeight>0?P.offsetHeight:E;const ue=ie.top+J.y,le=ie.left+J.x;let ce=ue+2,T=le+ie.width-B-2;(ie.width<B+4||ie.height<E+4)&&(ce=ue-E-2,T=le+ie.width-B,T<J.x&&(T=le)),ce=Math.max(0,Math.min(ce,window.innerHeight-E)),T=Math.max(0,Math.min(T,window.innerWidth-B)),P.style.top=`${ce}px`,P.style.left=`${T}px`,ae.appendChild(P);const R=((k,b)=>{let m=0;return(...$)=>{const N=performance.now();if(!(N-m<b))return m=N,k(...$)}})(()=>{const k=c.getClientRects();let b={x:0,y:0};if(z){const m=z.getBoundingClientRect();b.x=m.left,b.y=m.top}if(_.forEach((m,$)=>{if($<k.length){const N=k[$],q=N.top+b.y,se=N.left+b.x;m.element.style.top=`${q}px`,m.element.style.left=`${se}px`,m.element.style.width=`${N.width}px`,m.element.style.height=`${N.height}px`,m.element.style.display=N.width===0||N.height===0?"none":"block"}else m.element.style.display="none"}),k.length<_.length)for(let m=k.length;m<_.length;m++)_[m].element.style.display="none";if(P&&k.length>0){const m=k[0],$=m.top+b.y,N=m.left+b.x;let q=$+2,se=N+m.width-B-2;(m.width<B+4||m.height<E+4)&&(q=$-E-2,se=N+m.width-B,se<b.x&&(se=N)),q=Math.max(0,Math.min(q,window.innerHeight-E)),se=Math.max(0,Math.min(se,window.innerWidth-B)),P.style.top=`${q}px`,P.style.left=`${se}px`,P.style.display="block"}else P&&(P.style.display="none")},16);return window.addEventListener("scroll",R,!0),window.addEventListener("resize",R),M=()=>{window.removeEventListener("scroll",R,!0),window.removeEventListener("resize",R),_.forEach(k=>k.element.remove()),P&&P.remove()},L.appendChild(ae),v+1}finally{M&&(window._highlightCleanupFunctions=window._highlightCleanupFunctions||[]).push(M)}}function A(c){if(!c||c.nodeType!==Node.ELEMENT_NODE)return null;const v=y(c);if(!v)return null;const z=v.display;if(z==="inline"||z==="inline-block")return null;const _=v.overflowX,P=v.overflowY,B=v.scrollbarWidth&&v.scrollbarWidth!=="auto"||v.scrollbarGutter&&v.scrollbarGutter!=="auto",E=_==="auto"||_==="scroll",M=P==="auto"||P==="scroll";if(!E&&!M&&!B)return null;const L=c.scrollWidth-c.clientWidth,U=c.scrollHeight-c.clientHeight,Y=4;if(L<Y&&U<Y||!M&&!B&&L<Y||!E&&!B&&U<Y)return null;const G=c.scrollTop,ee=c.scrollLeft,J={top:G,right:c.scrollWidth-c.clientWidth-c.scrollLeft,bottom:c.scrollHeight-c.clientHeight-c.scrollTop,left:ee};return f(c,{scrollable:!0,scrollData:J}),J}function O(c){try{if(a===-1){const E=c.parentElement;if(!E)return!1;try{return E.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{const L=window.getComputedStyle(E);return L.display!=="none"&&L.visibility!=="hidden"&&L.opacity!=="0"}}const v=document.createRange();v.selectNodeContents(c);const z=v.getClientRects();if(!z||z.length===0)return!1;let _=!1,P=!1;for(const E of z)if(E.width>0&&E.height>0&&(_=!0,!(E.bottom<-a||E.top>window.innerHeight+a||E.right<-a||E.left>window.innerWidth+a))){P=!0;break}if(!_||!P)return!1;const B=c.parentElement;if(!B)return!1;try{return B.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{const M=window.getComputedStyle(B);return M.display!=="none"&&M.visibility!=="hidden"&&M.opacity!=="0"}}catch(v){return console.warn("Error checking text node visibility:",v),!1}}function C(c){if(!c||!c.tagName)return!1;const v=new Set(["body","div","main","article","section","nav","header","footer"]),z=c.tagName.toLowerCase();return v.has(z)?!0:!new Set(["svg","script","style","link","meta","noscript","template"]).has(z)}function w(c){const v=y(c);return c.offsetWidth>0&&c.offsetHeight>0&&v?.visibility!=="hidden"&&v?.display!=="none"}function V(c){if(!c||c.nodeType!==Node.ELEMENT_NODE||e.includes(c))return!1;if(r.includes(c))return!0;const v=c.tagName.toLowerCase(),z=y(c),_=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"]),P=new Set(["not-allowed","no-drop","wait","progress","initial","inherit"]);function B(G){return G.tagName.toLowerCase()==="html"?!1:!!(z?.cursor&&_.has(z.cursor))}if(B(c))return!0;const E=new Set(["a","button","input","select","textarea","details","summary","label","option","optgroup","fieldset","legend"]),M=new Set(["disabled","readonly"]);if(E.has(v)){if(z?.cursor&&P.has(z.cursor))return!1;for(const G of M)if(c.hasAttribute(G)||c.getAttribute(G)==="true"||c.getAttribute(G)==="")return!1;return!(c.disabled||c.readOnly||c.inert)}const L=c.getAttribute("role"),U=c.getAttribute("aria-role");if(c.getAttribute("contenteditable")==="true"||c.isContentEditable||c.classList&&(c.classList.contains("button")||c.classList.contains("dropdown-toggle")||c.getAttribute("data-index")||c.getAttribute("data-toggle")==="dropdown"||c.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(E.has(v)||L&&Y.has(L)||U&&Y.has(U))return!0;try{if(typeof getEventListeners=="function"){const ee=getEventListeners(c);for(const J of["click","mousedown","mouseup","dblclick"])if(ee[J]&&ee[J].length>0)return!0}const G=c?.ownerDocument?.defaultView?.getEventListenersForNode||window.getEventListenersForNode;if(typeof G=="function"){const ee=G(c);for(const J of["click","mousedown","mouseup","keydown","keyup","submit","change","input","focus","blur"])for(const ae of ee)if(ae.type===J)return!0}for(const ee of["onclick","onmousedown","onmouseup","ondblclick"])if(c.hasAttribute(ee)||typeof c[ee]=="function")return!0}catch{}return!!A(c)}function F(c){if(a===-1)return!0;const v=Z(c);if(!v||v.length===0)return!1;let z=!1;for(const E of v)if(E.width>0&&E.height>0&&!(E.bottom<-a||E.top>window.innerHeight+a||E.right<-a||E.left>window.innerWidth+a)){z=!0;break}if(!z)return!1;if(c.ownerDocument!==window.document)return!0;let _=Array.from(v).find(E=>E.width>0&&E.height>0);if(!_)return!1;const P=c.getRootNode();if(P instanceof ShadowRoot){const E=_.left+_.width/2,M=_.top+_.height/2;try{const L=P.elementFromPoint(E,M);if(!L)return!1;let U=L;for(;U&&U!==P;){if(U===c)return!0;U=U.parentElement}return!1}catch{return!0}}const B=5;return[{x:_.left+_.width/2,y:_.top+_.height/2},{x:_.left+B,y:_.top+B},{x:_.right-B,y:_.bottom-B}].some(({x:E,y:M})=>{try{const L=document.elementFromPoint(E,M);if(!L)return!1;let U=L;for(;U&&U!==document.documentElement;){if(U===c)return!0;U=U.parentElement}return!1}catch{return!0}})}function j(c,v){if(v===-1)return!0;const z=c.getClientRects();if(!z||z.length===0){const _=g(c);return!_||_.width===0||_.height===0?!1:!(_.bottom<-v||_.top>window.innerHeight+v||_.right<-v||_.left>window.innerWidth+v)}for(const _ of z)if(!(_.width===0||_.height===0)&&!(_.bottom<-v||_.top>window.innerHeight+v||_.right<-v||_.left>window.innerWidth+v))return!0;return!1}const H=["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 W(c){for(let v=0;v<H.length;v++)if(c.hasAttribute(H[v]))return!0;return!1}function te(c){if(!c||c.nodeType!==Node.ELEMENT_NODE)return!1;const v=c.tagName.toLowerCase();return new Set(["a","button","input","select","textarea","details","summary","label"]).has(v)?!0:c.hasAttribute("onclick")||c.hasAttribute("role")||c.hasAttribute("tabindex")||W(c)||c.hasAttribute("data-action")||c.getAttribute("contenteditable")==="true"}const X=new Set(["a","button","input","select","textarea","summary","details","label","option","li"]),re=new Set(["button","link","menuitem","menuitemradio","menuitemcheckbox","radio","checkbox","tab","switch","slider","spinbutton","combobox","searchbox","textbox","listbox","listitem","treeitem","row","option","scrollbar"]);function oe(c){if(!c||c.nodeType!==Node.ELEMENT_NODE||!w(c))return!1;const v=c.hasAttribute("role")||c.hasAttribute("tabindex")||c.hasAttribute("onclick")||typeof c.onclick=="function",z=/\b(btn|clickable|menu|item|entry|link)\b/i.test(c.className||""),_=!!c.closest('button,a,[role="button"],.menu,.dropdown,.list,.toolbar'),P=[...c.children].some(w),B=c.parentElement&&c.parentElement.isSameNode(document.body);return(V(c)||v||z)&&P&&_&&!B}function ne(c){if(!c||c.nodeType!==Node.ELEMENT_NODE)return!1;const v=c.tagName.toLowerCase(),z=c.getAttribute("role");if(v==="iframe"||X.has(v)||z&&re.has(z)||c.isContentEditable||c.getAttribute("contenteditable")==="true"||c.hasAttribute("data-testid")||c.hasAttribute("data-cy")||c.hasAttribute("data-test")||c.hasAttribute("onclick")||typeof c.onclick=="function"||W(c))return!0;try{const _=c?.ownerDocument?.defaultView?.getEventListenersForNode||window.getEventListenersForNode;if(typeof _=="function"){const P=_(c);for(const B of["click","mousedown","mouseup","keydown","keyup","submit","change","input","focus","blur"])for(const E of P)if(E.type===B)return!0}if(["onmousedown","onmouseup","onkeydown","onkeyup","onsubmit","onchange","oninput","onfocus","onblur"].some(P=>c.hasAttribute(P)))return!0}catch{}return!!(oe(c)||u.get(c)?.scrollable)}function Q(c,v,z,_){if(!c.isInteractive)return!1;let P=!1;return _?ne(v)?P=!0:P=!1:P=!0,P&&(c.isInViewport=j(v,a),(c.isInViewport||a===-1)&&(c.highlightIndex=d++,o))?(s>=0?s===c.highlightIndex&&I(v,c.highlightIndex,z):I(v,c.highlightIndex,z),!0):!1}function K(c,v=null,z=!1){if(!c||c.id===S||c.nodeType!==Node.ELEMENT_NODE&&c.nodeType!==Node.TEXT_NODE||!c||c.id===S||c.dataset?.browserUseIgnore==="true"||c.dataset?.pageAgentIgnore==="true"||c.getAttribute&&c.getAttribute("aria-hidden")==="true")return null;if(c===document.body){const E={tagName:"body",attributes:{},xpath:"/body",children:[]};for(const L of c.childNodes){const U=K(L,v,!1);U&&E.children.push(U)}const M=`${h.current++}`;return x[M]=E,M}if(c.nodeType!==Node.ELEMENT_NODE&&c.nodeType!==Node.TEXT_NODE)return null;if(c.nodeType===Node.TEXT_NODE){const E=c.textContent?.trim();if(!E)return null;const M=c.parentElement;if(!M||M.tagName.toLowerCase()==="script")return null;const L=`${h.current++}`;return x[L]={type:"TEXT_NODE",text:E,isVisible:O(c)},L}if(c.nodeType===Node.ELEMENT_NODE&&!C(c))return null;if(a!==-1&&!c.shadowRoot){const E=g(c),M=y(c),L=M&&(M.position==="fixed"||M.position==="sticky"),U=c.offsetWidth>0||c.offsetHeight>0;if(!E||!L&&!U&&(E.bottom<-a||E.top>window.innerHeight+a||E.right<-a||E.left>window.innerWidth+a))return null}const _={tagName:c.tagName.toLowerCase(),attributes:{},children:[]};if(te(c)||c.tagName.toLowerCase()==="iframe"||c.tagName.toLowerCase()==="body"){const E=c.getAttributeNames?.()||[];for(const M of E){const L=c.getAttribute(M);_.attributes[M]=L}c.tagName.toLowerCase()==="input"&&(c.type==="checkbox"||c.type==="radio")&&(_.attributes.checked=c.checked?"true":"false")}let P=!1;if(c.nodeType===Node.ELEMENT_NODE&&(_.isVisible=w(c),_.isVisible)){_.isTopElement=F(c);const E=c.getAttribute("role"),M=E==="menu"||E==="menubar"||E==="listbox";if((_.isTopElement||M)&&(_.isInteractive=V(c),P=Q(_,c,v,z),_.ref=c,_.isInteractive&&Object.keys(_.attributes).length===0)){const L=c.getAttributeNames?.()||[];for(const U of L){const Y=c.getAttribute(U);_.attributes[U]=Y}}}if(c.tagName){const E=c.tagName.toLowerCase();if(E==="iframe")try{const M=c.contentDocument||c.contentWindow?.document;if(M)for(const L of M.childNodes){const U=K(L,c,!1);U&&_.children.push(U)}}catch(M){console.warn("Unable to access iframe:",M)}else if(c.isContentEditable||c.getAttribute("contenteditable")==="true"||c.id==="tinymce"||c.classList.contains("mce-content-body")||E==="body"&&c.getAttribute("data-id")?.startsWith("mce_"))for(const M of c.childNodes){const L=K(M,v,P);L&&_.children.push(L)}else{if(c.shadowRoot){_.shadowRoot=!0;for(const M of c.shadowRoot.childNodes){const L=K(M,v,P);L&&_.children.push(L)}}for(const M of c.childNodes){const L=K(M,v,P||z);L&&_.children.push(L)}}}if(_.tagName==="a"&&_.children.length===0&&!_.attributes.href){const E=g(c);if(!(E&&E.width>0&&E.height>0||c.offsetWidth>0||c.offsetHeight>0))return null}_.extra=u.get(c)||null;const B=`${h.current++}`;return x[B]=_,B}const de=K(document.body);return p.clearCache(),{rootId:de,map:x}},DEFAULT_VIEWPORT_EXPANSION=-1;function resolveViewportExpansion(t){return t??DEFAULT_VIEWPORT_EXPANSION}var SEMANTIC_TAGS=new Set(["nav","menu","header","footer","aside","dialog"]),newElementsCache=new WeakMap;function getFlatTree(t){const e=resolveViewportExpansion(t.viewportExpansion),r=[];for(const s of t.interactiveBlacklist||[])typeof s=="function"?r.push(s()):r.push(s);const n=[];for(const s of t.interactiveWhitelist||[])typeof s=="function"?n.push(s()):n.push(s);const i=dom_tree_default({doHighlightElements:!0,debugMode:!0,focusHighlightIndex:-1,viewportExpansion:e,interactiveBlacklist:r,interactiveWhitelist:n,highlightOpacity:t.highlightOpacity??0,highlightLabelOpacity:t.highlightLabelOpacity??.1}),o=window.location.href;for(const s in i.map){const a=i.map[s];if(a.isInteractive&&a.ref){const l=a.ref;newElementsCache.has(l)||(newElementsCache.set(l,o),a.isNew=!0)}}return i}var globRegexCache=new Map;function globToRegex(t){let e=globRegexCache.get(t);if(!e){const r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&");e=new RegExp(`^${r.replace(/\*/g,".*")}$`),globRegexCache.set(t,e)}return e}function matchAttributes(t,e){const r={};for(const n of e)if(n.includes("*")){const i=globToRegex(n);for(const o of Object.keys(t))i.test(o)&&t[o].trim()&&(r[o]=t[o].trim())}else{const i=t[n];i&&i.trim()&&(r[n]=i.trim())}return r}function flatTreeToString(t,e=[],r=!1){const n=["title","type","checked","name","role","value","placeholder","data-date-format","alt","aria-label","aria-expanded","data-state","aria-checked","id","for","target","aria-haspopup","aria-controls","aria-owns","contenteditable"],i=[...e,...n],o=(p,g)=>p.length>g?p.substring(0,g)+"...":p,s=p=>{const g=t.map[p];if(!g)return null;if(g.type==="TEXT_NODE"){const y=g;return{type:"text",text:y.text,isVisible:y.isVisible,parent:null,children:[]}}else{const y=g,Z=[];if(y.children)for(const x of y.children){const h=s(x);h&&(h.parent=null,Z.push(h))}return{type:"element",tagName:y.tagName,attributes:y.attributes??{},isVisible:y.isVisible??!1,isInteractive:y.isInteractive??!1,isTopElement:y.isTopElement??!1,isNew:y.isNew??!1,highlightIndex:y.highlightIndex,parent:null,children:Z,extra:y.extra??{}}}},a=(p,g=null)=>{p.parent=g;for(const y of p.children)a(y,p)},l=s(t.rootId);if(!l)return"";a(l);const d=p=>{let g=p.parent;for(;g;){if(g.type==="element"&&g.highlightIndex!==void 0)return!0;g=g.parent}return!1},u=(p,g,y)=>{let Z=g;const x=" ".repeat(g);if(p.type==="element"){const h=r&&p.tagName&&SEMANTIC_TAGS.has(p.tagName);if(p.highlightIndex!==void 0){Z+=1;const A=getAllTextTillNextClickableElement(p);let O="";if(i.length>0&&p.attributes){const w=matchAttributes(p.attributes,i),V=Object.keys(w);if(V.length>1){const F=new Set,j={};for(const H of V){const W=w[H];W.length>5&&(W in j?F.add(H):j[W]=H)}for(const H of F)delete w[H]}w.role===p.tagName&&delete w.role;for(const F of["aria-label","placeholder","title"])w[F]&&w[F].toLowerCase().trim()===A.toLowerCase().trim()&&delete w[F];Object.keys(w).length>0&&(O=Object.entries(w).map(([F,j])=>`${F}=${o(j,20)}`).join(" "))}let C=`${x}${p.isNew?`*[${p.highlightIndex}]`:`[${p.highlightIndex}]`}<${p.tagName??""}`;if(O&&(C+=` ${O}`),p.extra&&p.extra.scrollable){let w="";p.extra.scrollData?.left&&(w+=`left=${p.extra.scrollData.left}, `),p.extra.scrollData?.top&&(w+=`top=${p.extra.scrollData.top}, `),p.extra.scrollData?.right&&(w+=`right=${p.extra.scrollData.right}, `),p.extra.scrollData?.bottom&&(w+=`bottom=${p.extra.scrollData.bottom}`),C+=` data-scrollable="${w}"`}if(A){const w=A.trim();O||(C+=" "),C+=`>${w}`}else O||(C+=" ");C+=" />",y.push(C)}const S=h&&p.highlightIndex===void 0,I=S?y.length:-1;S&&(y.push(`${x}<${p.tagName}>`),Z+=1);for(const A of p.children)u(A,Z,y);S&&(y.length===I+1?y.pop():y.push(`${x}</${p.tagName}>`))}else if(p.type==="text"){if(d(p))return;p.parent&&p.parent.type==="element"&&p.parent.isVisible&&p.parent.isTopElement&&y.push(`${x}${p.text??""}`)}},f=[];return u(l,0,f),f.join(`
315
+ `;function isHTMLElement(t){return!!t&&t.nodeType===1}function isInputElement(t){return t?.nodeType===1&&t.tagName==="INPUT"}function isTextAreaElement(t){return t?.nodeType===1&&t.tagName==="TEXTAREA"}function isSelectElement(t){return t?.nodeType===1&&t.tagName==="SELECT"}function isAnchorElement(t){return t?.nodeType===1&&t.tagName==="A"}function getIframeOffset(t){const e=t.ownerDocument.defaultView?.frameElement;if(!e)return{x:0,y:0};const r=e.getBoundingClientRect();return{x:r.left,y:r.top}}function getNativeValueSetter(t){return Object.getOwnPropertyDescriptor(Object.getPrototypeOf(t),"value").set}async function waitFor(t){await new Promise(e=>setTimeout(e,t*1e3))}async function movePointerToElement(t,e,r){const n=getIframeOffset(t);window.dispatchEvent(new CustomEvent("PageAgent::MovePointerTo",{detail:{x:e+n.x,y:r+n.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(t,e){const r=t.get(e);if(!r)throw new Error(`No interactive element found at index ${e}`);const n=r.ref;if(!n)throw new Error(`Element at index ${e} does not have a reference`);if(!isHTMLElement(n))throw new Error(`Element at index ${e} is not an HTMLElement`);return n}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(t){blurLastClickedElement(),lastClickedElement=t,await scrollIntoViewIfNeeded(t);const e=t.ownerDocument.defaultView?.frameElement;e&&await scrollIntoViewIfNeeded(e);const r=t.getBoundingClientRect(),n=r.left+r.width/2,i=r.top+r.height/2;await movePointerToElement(t,n,i),await clickPointer(),await waitFor(.1);const o=t.ownerDocument;await enablePassThrough();const s=o.elementFromPoint(n,i);await disablePassThrough();const a=s instanceof HTMLElement&&t.contains(s)?s:t,l={bubbles:!0,cancelable:!0,clientX:n,clientY:i,pointerType:"mouse"},c={bubbles:!0,cancelable:!0,clientX:n,clientY:i,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)),t.focus({preventScroll:!0}),a.dispatchEvent(new PointerEvent("pointerup",l)),a.dispatchEvent(new MouseEvent("mouseup",c)),a.click(),await waitFor(.2)}async function inputTextElement(t,e){const r=t.isContentEditable;if(!isInputElement(t)&&!isTextAreaElement(t)&&!r)throw new Error("Element is not an input, textarea, or contenteditable");if(await clickElement(t),r){if(t.dispatchEvent(new InputEvent("beforeinput",{bubbles:!0,cancelable:!0,inputType:"deleteContent"}))&&(t.innerText="",t.dispatchEvent(new InputEvent("input",{bubbles:!0,inputType:"deleteContent"}))),t.dispatchEvent(new InputEvent("beforeinput",{bubbles:!0,cancelable:!0,inputType:"insertText",data:e}))&&(t.innerText=e,t.dispatchEvent(new InputEvent("input",{bubbles:!0,inputType:"insertText",data:e}))),t.innerText.trim()!==e.trim()){t.focus();const n=t.ownerDocument,i=(n.defaultView||window).getSelection(),o=n.createRange();o.selectNodeContents(t),i?.removeAllRanges(),i?.addRange(o),n.execCommand("delete",!1),n.execCommand("insertText",!1,e)}t.dispatchEvent(new Event("change",{bubbles:!0})),t.blur()}else getNativeValueSetter(t).call(t,e);r||t.dispatchEvent(new Event("input",{bubbles:!0})),await waitFor(.1),blurLastClickedElement()}async function selectOptionElement(t,e){if(!isSelectElement(t))throw new Error("Element is not a select element");const r=Array.from(t.options).find(n=>n.textContent?.trim()===e.trim());if(!r)throw new Error(`Option with text "${e}" not found in select element`);t.value=r.value,t.dispatchEvent(new Event("change",{bubbles:!0})),await waitFor(.1)}async function scrollIntoViewIfNeeded(t){const e=t;typeof e.scrollIntoViewIfNeeded=="function"?e.scrollIntoViewIfNeeded():t.scrollIntoView({behavior:"auto",block:"center",inline:"nearest"})}async function scrollVertically(t,e){if(e){const s=e;let a=s,l=!1,c=null,u=0,h=0;const f=t;for(;a&&h<10;){const g=window.getComputedStyle(a),b=/(auto|scroll|overlay)/.test(g.overflowY)||g.scrollbarWidth&&g.scrollbarWidth!=="auto"||g.scrollbarGutter&&g.scrollbarGutter!=="auto",P=a.scrollHeight>a.clientHeight;if(b&&P){const w=a.scrollTop,p=a.scrollHeight-a.clientHeight;let m=f/3;m>0?m=Math.min(m,p-w):m=Math.max(m,-w),a.scrollTop=w+m;const A=a.scrollTop-w;if(Math.abs(A)>.5){l=!0,c=a,u=A;break}}if(a===document.body||a===document.documentElement)break;a=a.parentElement,h++}return l?`Scrolled container (${c?.tagName}) by ${u}px`:`No scrollable container found for element (${s.tagName})`}const r=t,n=s=>s.clientHeight>=window.innerHeight*.5,i=s=>!!(s&&/(auto|scroll|overlay)/.test(getComputedStyle(s).overflowY)&&s.scrollHeight>s.clientHeight&&n(s));let o=document.activeElement;for(;o&&!i(o)&&o!==document.body;)o=o.parentElement;if(o=i(o)?o:Array.from(document.querySelectorAll("*")).find(i)||document.scrollingElement||document.documentElement,o===document.scrollingElement||o===document.documentElement||o===document.body){const s=window.scrollY,a=document.documentElement.scrollHeight-window.innerHeight;window.scrollBy(0,r);const l=window.scrollY,c=l-s;if(Math.abs(c)<1)return r>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=r>0&&l>=a-1,h=r<0&&l<=1;return u?`✅ Scrolled page by ${c}px. Reached the bottom of the page.`:h?`✅ 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=o.scrollTop,l=o.scrollHeight-o.clientHeight;o.scrollBy({top:r,behavior:"smooth"}),await waitFor(.1);const c=o.scrollTop,u=c-a;if(Math.abs(u)<1)return r>0?`⚠️ ${s} Already at the bottom of container (${o.tagName}), cannot scroll down further.`:`⚠️ ${s} Already at the top of container (${o.tagName}), cannot scroll up further.`;const h=r>0&&c>=l-1,f=r<0&&c<=1;return h?`✅ ${s} Scrolled container (${o.tagName}) by ${u}px. Reached the bottom.`:f?`✅ ${s} Scrolled container (${o.tagName}) by ${u}px. Reached the top.`:`✅ ${s} Scrolled container (${o.tagName}) by ${u}px.`}}async function scrollHorizontally(t,e){if(e){const s=e;let a=s,l=!1,c=null,u=0,h=0;const f=t;for(;a&&h<10;){const g=window.getComputedStyle(a),b=/(auto|scroll|overlay)/.test(g.overflowX)||g.scrollbarWidth&&g.scrollbarWidth!=="auto"||g.scrollbarGutter&&g.scrollbarGutter!=="auto",P=a.scrollWidth>a.clientWidth;if(b&&P){const w=a.scrollLeft,p=a.scrollWidth-a.clientWidth;let m=f/3;m>0?m=Math.min(m,p-w):m=Math.max(m,-w),a.scrollLeft=w+m;const A=a.scrollLeft-w;if(Math.abs(A)>.5){l=!0,c=a,u=A;break}}if(a===document.body||a===document.documentElement)break;a=a.parentElement,h++}return l?`Scrolled container (${c?.tagName}) horizontally by ${u}px`:`No horizontally scrollable container found for element (${s.tagName})`}const r=t,n=s=>s.clientWidth>=window.innerWidth*.5,i=s=>!!(s&&/(auto|scroll|overlay)/.test(getComputedStyle(s).overflowX)&&s.scrollWidth>s.clientWidth&&n(s));let o=document.activeElement;for(;o&&!i(o)&&o!==document.body;)o=o.parentElement;if(o=i(o)?o:Array.from(document.querySelectorAll("*")).find(i)||document.scrollingElement||document.documentElement,o===document.scrollingElement||o===document.documentElement||o===document.body){const s=window.scrollX,a=document.documentElement.scrollWidth-window.innerWidth;window.scrollBy(r,0);const l=window.scrollX,c=l-s;if(Math.abs(c)<1)return r>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=r>0&&l>=a-1,h=r<0&&l<=1;return u?`✅ Scrolled page by ${c}px. Reached the right edge of the page.`:h?`✅ 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=o.scrollLeft,l=o.scrollWidth-o.clientWidth;o.scrollBy({left:r,behavior:"smooth"}),await waitFor(.1);const c=o.scrollLeft,u=c-a;if(Math.abs(u)<1)return r>0?`⚠️ ${s} Already at the right edge of container (${o.tagName}), cannot scroll right further.`:`⚠️ ${s} Already at the left edge of container (${o.tagName}), cannot scroll left further.`;const h=r>0&&c>=l-1,f=r<0&&c<=1;return h?`✅ ${s} Scrolled container (${o.tagName}) by ${u}px. Reached the right edge.`:f?`✅ ${s} Scrolled container (${o.tagName}) by ${u}px. Reached the left edge.`:`✅ ${s} Scrolled container (${o.tagName}) horizontally by ${u}px.`}}var dom_tree_default=(t={doHighlightElements:!0,focusHighlightIndex:-1,viewportExpansion:0,debugMode:!1,interactiveBlacklist:[],interactiveWhitelist:[],highlightOpacity:.1,highlightLabelOpacity:.5})=>{const{interactiveBlacklist:e,interactiveWhitelist:r,highlightOpacity:n,highlightLabelOpacity:i}=t,{doHighlightElements:o,focusHighlightIndex:s,viewportExpansion:a,debugMode:l}=t;let c=0;const u=new WeakMap;function h(d,x){!d||d.nodeType!==Node.ELEMENT_NODE||u.set(d,{...u.get(d),...x})}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 g(d){if(!d)return null;if(f.boundingRects.has(d))return f.boundingRects.get(d);const x=d.getBoundingClientRect();return x&&f.boundingRects.set(d,x),x}function b(d){if(!d)return null;if(f.computedStyles.has(d))return f.computedStyles.get(d);const x=window.getComputedStyle(d);return x&&f.computedStyles.set(d,x),x}function P(d){if(!d)return null;if(f.clientRects.has(d))return f.clientRects.get(d);const x=d.getClientRects();return x&&f.clientRects.set(d,x),x}const w={},p={current:0},m="playwright-highlight-container";function A(d,x,U=null){if(!d)return x;const _=[];let I=null,z=20,C=16,M=null;try{let O=document.getElementById(m);O||(O=document.createElement("div"),O.id=m,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 F=d.getClientRects();if(!F||F.length===0)return x;const Y=["#FF0000","#00FF00","#0000FF","#FFA500","#800080","#008080","#FF69B4","#4B0082","#FF4500","#2E8B57","#DC143C","#4682B4"];let W=Y[x%Y.length];const ee=W+Math.floor(n*255).toString(16).padStart(2,"0");W=W+Math.floor(i*255).toString(16).padStart(2,"0");let J={x:0,y:0};if(U){const S=U.getBoundingClientRect();J.x=S.left,J.y=S.top}const ae=document.createDocumentFragment();for(const S of F){if(S.width===0||S.height===0)continue;const v=document.createElement("div");v.style.position="fixed",v.style.border=`2px solid ${W}`,v.style.backgroundColor=ee,v.style.pointerEvents="none",v.style.boxSizing="border-box";const y=S.top+J.y,L=S.left+J.x;v.style.top=`${y}px`,v.style.left=`${L}px`,v.style.width=`${S.width}px`,v.style.height=`${S.height}px`,ae.appendChild(v),_.push({element:v,initialRect:S})}const ne=F[0];I=document.createElement("div"),I.className="playwright-highlight-label",I.style.position="fixed",I.style.background=W,I.style.color="white",I.style.padding="1px 4px",I.style.borderRadius="4px",I.style.fontSize=`${Math.min(12,Math.max(8,ne.height/2))}px`,I.textContent=x.toString(),z=I.offsetWidth>0?I.offsetWidth:z,C=I.offsetHeight>0?I.offsetHeight:C;const ue=ne.top+J.y,le=ne.left+J.x;let de=ue+2,E=le+ne.width-z-2;(ne.width<z+4||ne.height<C+4)&&(de=ue-C-2,E=le+ne.width-z,E<J.x&&(E=le)),de=Math.max(0,Math.min(de,window.innerHeight-C)),E=Math.max(0,Math.min(E,window.innerWidth-z)),I.style.top=`${de}px`,I.style.left=`${E}px`,ae.appendChild(I);const $=((S,v)=>{let y=0;return(...L)=>{const N=performance.now();if(!(N-y<v))return y=N,S(...L)}})(()=>{const S=d.getClientRects();let v={x:0,y:0};if(U){const y=U.getBoundingClientRect();v.x=y.left,v.y=y.top}if(_.forEach((y,L)=>{if(L<S.length){const N=S[L],q=N.top+v.y,se=N.left+v.x;y.element.style.top=`${q}px`,y.element.style.left=`${se}px`,y.element.style.width=`${N.width}px`,y.element.style.height=`${N.height}px`,y.element.style.display=N.width===0||N.height===0?"none":"block"}else y.element.style.display="none"}),S.length<_.length)for(let y=S.length;y<_.length;y++)_[y].element.style.display="none";if(I&&S.length>0){const y=S[0],L=y.top+v.y,N=y.left+v.x;let q=L+2,se=N+y.width-z-2;(y.width<z+4||y.height<C+4)&&(q=L-C-2,se=N+y.width-z,se<v.x&&(se=N)),q=Math.max(0,Math.min(q,window.innerHeight-C)),se=Math.max(0,Math.min(se,window.innerWidth-z)),I.style.top=`${q}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",$),M=()=>{window.removeEventListener("scroll",$,!0),window.removeEventListener("resize",$),_.forEach(S=>S.element.remove()),I&&I.remove()},O.appendChild(ae),x+1}finally{M&&(window._highlightCleanupFunctions=window._highlightCleanupFunctions||[]).push(M)}}function T(d){if(!d||d.nodeType!==Node.ELEMENT_NODE)return null;const x=b(d);if(!x)return null;const U=x.display;if(U==="inline"||U==="inline-block")return null;const _=x.overflowX,I=x.overflowY,z=x.scrollbarWidth&&x.scrollbarWidth!=="auto"||x.scrollbarGutter&&x.scrollbarGutter!=="auto",C=_==="auto"||_==="scroll",M=I==="auto"||I==="scroll";if(!C&&!M&&!z)return null;const O=d.scrollWidth-d.clientWidth,F=d.scrollHeight-d.clientHeight,Y=4;if(O<Y&&F<Y||!M&&!z&&O<Y||!C&&!z&&F<Y)return null;const W=d.scrollTop,ee=d.scrollLeft,J={top:W,right:d.scrollWidth-d.clientWidth-d.scrollLeft,bottom:d.scrollHeight-d.clientHeight-d.scrollTop,left:ee};return h(d,{scrollable:!0,scrollData:J}),J}function k(d){try{if(a===-1){const C=d.parentElement;if(!C)return!1;try{return C.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{const O=window.getComputedStyle(C);return O.display!=="none"&&O.visibility!=="hidden"&&O.opacity!=="0"}}const x=document.createRange();x.selectNodeContents(d);const U=x.getClientRects();if(!U||U.length===0)return!1;let _=!1,I=!1;for(const C of U)if(C.width>0&&C.height>0&&(_=!0,!(C.bottom<-a||C.top>window.innerHeight+a||C.right<-a||C.left>window.innerWidth+a))){I=!0;break}if(!_||!I)return!1;const z=d.parentElement;if(!z)return!1;try{return z.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{const M=window.getComputedStyle(z);return M.display!=="none"&&M.visibility!=="hidden"&&M.opacity!=="0"}}catch(x){return console.warn("Error checking text node visibility:",x),!1}}function Z(d){if(!d||!d.tagName)return!1;const x=new Set(["body","div","main","article","section","nav","header","footer"]),U=d.tagName.toLowerCase();return x.has(U)?!0:!new Set(["svg","script","style","link","meta","noscript","template"]).has(U)}function R(d){const x=b(d);return d.offsetWidth>0&&d.offsetHeight>0&&x?.visibility!=="hidden"&&x?.display!=="none"}function V(d){if(!d||d.nodeType!==Node.ELEMENT_NODE||e.includes(d))return!1;if(r.includes(d))return!0;const x=d.tagName.toLowerCase(),U=b(d),_=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 z(W){return W.tagName.toLowerCase()==="html"?!1:!!(U?.cursor&&_.has(U.cursor))}if(z(d))return!0;const C=new Set(["a","button","input","select","textarea","details","summary","label","option","optgroup","fieldset","legend"]),M=new Set(["disabled","readonly"]);if(C.has(x)){if(U?.cursor&&I.has(U.cursor))return!1;for(const W of M)if(d.hasAttribute(W)||d.getAttribute(W)==="true"||d.getAttribute(W)==="")return!1;return!(d.disabled||d.readOnly||d.inert)}const O=d.getAttribute("role"),F=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(C.has(x)||O&&Y.has(O)||F&&Y.has(F))return!0;try{if(typeof getEventListeners=="function"){const ee=getEventListeners(d);for(const J of["click","mousedown","mouseup","dblclick"])if(ee[J]&&ee[J].length>0)return!0}const W=d?.ownerDocument?.defaultView?.getEventListenersForNode||window.getEventListenersForNode;if(typeof W=="function"){const ee=W(d);for(const J of["click","mousedown","mouseup","keydown","keyup","submit","change","input","focus","blur"])for(const ae of ee)if(ae.type===J)return!0}for(const ee of["onclick","onmousedown","onmouseup","ondblclick"])if(d.hasAttribute(ee)||typeof d[ee]=="function")return!0}catch{}return!!T(d)}function j(d){if(a===-1)return!0;const x=P(d);if(!x||x.length===0)return!1;let U=!1;for(const C of x)if(C.width>0&&C.height>0&&!(C.bottom<-a||C.top>window.innerHeight+a||C.right<-a||C.left>window.innerWidth+a)){U=!0;break}if(!U)return!1;if(d.ownerDocument!==window.document)return!0;let _=Array.from(x).find(C=>C.width>0&&C.height>0);if(!_)return!1;const I=d.getRootNode();if(I instanceof ShadowRoot){const C=_.left+_.width/2,M=_.top+_.height/2;try{const O=I.elementFromPoint(C,M);if(!O)return!1;let F=O;for(;F&&F!==I;){if(F===d)return!0;F=F.parentElement}return!1}catch{return!0}}const z=5;return[{x:_.left+_.width/2,y:_.top+_.height/2},{x:_.left+z,y:_.top+z},{x:_.right-z,y:_.bottom-z}].some(({x:C,y:M})=>{try{const O=document.elementFromPoint(C,M);if(!O)return!1;let F=O;for(;F&&F!==document.documentElement;){if(F===d)return!0;F=F.parentElement}return!1}catch{return!0}})}function H(d,x){if(x===-1)return!0;const U=d.getClientRects();if(!U||U.length===0){const _=g(d);return!_||_.width===0||_.height===0?!1:!(_.bottom<-x||_.top>window.innerHeight+x||_.right<-x||_.left>window.innerWidth+x)}for(const _ of U)if(!(_.width===0||_.height===0)&&!(_.bottom<-x||_.top>window.innerHeight+x||_.right<-x||_.left>window.innerWidth+x))return!0;return!1}const B=["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 G(d){for(let x=0;x<B.length;x++)if(d.hasAttribute(B[x]))return!0;return!1}function ie(d){if(!d||d.nodeType!==Node.ELEMENT_NODE)return!1;const x=d.tagName.toLowerCase();return new Set(["a","button","input","select","textarea","details","summary","label"]).has(x)?!0:d.hasAttribute("onclick")||d.hasAttribute("role")||d.hasAttribute("tabindex")||G(d)||d.hasAttribute("data-action")||d.getAttribute("contenteditable")==="true"}const X=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 oe(d){if(!d||d.nodeType!==Node.ELEMENT_NODE||!R(d))return!1;const x=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||""),_=!!d.closest('button,a,[role="button"],.menu,.dropdown,.list,.toolbar'),I=[...d.children].some(R),z=d.parentElement&&d.parentElement.isSameNode(document.body);return(V(d)||x||U)&&I&&_&&!z}function re(d){if(!d||d.nodeType!==Node.ELEMENT_NODE)return!1;const x=d.tagName.toLowerCase(),U=d.getAttribute("role");if(x==="iframe"||X.has(x)||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"||G(d))return!0;try{const _=d?.ownerDocument?.defaultView?.getEventListenersForNode||window.getEventListenersForNode;if(typeof _=="function"){const I=_(d);for(const z of["click","mousedown","mouseup","keydown","keyup","submit","change","input","focus","blur"])for(const C of I)if(C.type===z)return!0}if(["onmousedown","onmouseup","onkeydown","onkeyup","onsubmit","onchange","oninput","onfocus","onblur"].some(I=>d.hasAttribute(I)))return!0}catch{}return!!(oe(d)||u.get(d)?.scrollable)}function Q(d,x,U,_){if(!d.isInteractive)return!1;let I=!1;return _?re(x)?I=!0:I=!1:I=!0,I&&(d.isInViewport=H(x,a),(d.isInViewport||a===-1)&&(d.highlightIndex=c++,o))?(s>=0?s===d.highlightIndex&&A(x,d.highlightIndex,U):A(x,d.highlightIndex,U),!0):!1}function K(d,x=null,U=!1){if(!d||d.id===m||d.nodeType!==Node.ELEMENT_NODE&&d.nodeType!==Node.TEXT_NODE||!d||d.id===m||d.dataset?.browserUseIgnore==="true"||d.dataset?.pageAgentIgnore==="true"||d.getAttribute&&d.getAttribute("aria-hidden")==="true")return null;if(d===document.body){const C={tagName:"body",attributes:{},xpath:"/body",children:[]};for(const O of d.childNodes){const F=K(O,x,!1);F&&C.children.push(F)}const M=`${p.current++}`;return w[M]=C,M}if(d.nodeType!==Node.ELEMENT_NODE&&d.nodeType!==Node.TEXT_NODE)return null;if(d.nodeType===Node.TEXT_NODE){const C=d.textContent?.trim();if(!C)return null;const M=d.parentElement;if(!M||M.tagName.toLowerCase()==="script")return null;const O=`${p.current++}`;return w[O]={type:"TEXT_NODE",text:C,isVisible:k(d)},O}if(d.nodeType===Node.ELEMENT_NODE&&!Z(d))return null;if(a!==-1&&!d.shadowRoot){const C=g(d),M=b(d),O=M&&(M.position==="fixed"||M.position==="sticky"),F=d.offsetWidth>0||d.offsetHeight>0;if(!C||!O&&!F&&(C.bottom<-a||C.top>window.innerHeight+a||C.right<-a||C.left>window.innerWidth+a))return null}const _={tagName:d.tagName.toLowerCase(),attributes:{},children:[]};if(ie(d)||d.tagName.toLowerCase()==="iframe"||d.tagName.toLowerCase()==="body"){const C=d.getAttributeNames?.()||[];for(const M of C){const O=d.getAttribute(M);_.attributes[M]=O}d.tagName.toLowerCase()==="input"&&(d.type==="checkbox"||d.type==="radio")&&(_.attributes.checked=d.checked?"true":"false")}let I=!1;if(d.nodeType===Node.ELEMENT_NODE&&(_.isVisible=R(d),_.isVisible)){_.isTopElement=j(d);const C=d.getAttribute("role"),M=C==="menu"||C==="menubar"||C==="listbox";if((_.isTopElement||M)&&(_.isInteractive=V(d),I=Q(_,d,x,U),_.ref=d,_.isInteractive&&Object.keys(_.attributes).length===0)){const O=d.getAttributeNames?.()||[];for(const F of O){const Y=d.getAttribute(F);_.attributes[F]=Y}}}if(d.tagName){const C=d.tagName.toLowerCase();if(C==="iframe")try{const M=d.contentDocument||d.contentWindow?.document;if(M)for(const O of M.childNodes){const F=K(O,d,!1);F&&_.children.push(F)}}catch(M){console.warn("Unable to access iframe:",M)}else if(d.isContentEditable||d.getAttribute("contenteditable")==="true"||d.id==="tinymce"||d.classList.contains("mce-content-body")||C==="body"&&d.getAttribute("data-id")?.startsWith("mce_"))for(const M of d.childNodes){const O=K(M,x,I);O&&_.children.push(O)}else{if(d.shadowRoot){_.shadowRoot=!0;for(const M of d.shadowRoot.childNodes){const O=K(M,x,I);O&&_.children.push(O)}}for(const M of d.childNodes){const O=K(M,x,I||U);O&&_.children.push(O)}}}if(_.tagName==="a"&&_.children.length===0&&!_.attributes.href){const C=g(d);if(!(C&&C.width>0&&C.height>0||d.offsetWidth>0||d.offsetHeight>0))return null}_.extra=u.get(d)||null;const z=`${p.current++}`;return w[z]=_,z}const ce=K(document.body);return f.clearCache(),{rootId:ce,map:w}},DEFAULT_VIEWPORT_EXPANSION=-1;function resolveViewportExpansion(t){return t??DEFAULT_VIEWPORT_EXPANSION}var SEMANTIC_TAGS=new Set(["nav","menu","header","footer","aside","dialog"]),newElementsCache=new WeakMap;function getFlatTree(t){const e=resolveViewportExpansion(t.viewportExpansion),r=[];for(const s of t.interactiveBlacklist||[])typeof s=="function"?r.push(s()):r.push(s);const n=[];for(const s of t.interactiveWhitelist||[])typeof s=="function"?n.push(s()):n.push(s);const i=dom_tree_default({doHighlightElements:!0,debugMode:!0,focusHighlightIndex:-1,viewportExpansion:e,interactiveBlacklist:r,interactiveWhitelist:n,highlightOpacity:t.highlightOpacity??0,highlightLabelOpacity:t.highlightLabelOpacity??.1}),o=window.location.href;for(const s in i.map){const a=i.map[s];if(a.isInteractive&&a.ref){const l=a.ref;newElementsCache.has(l)||(newElementsCache.set(l,o),a.isNew=!0)}}return i}var globRegexCache=new Map;function globToRegex(t){let e=globRegexCache.get(t);if(!e){const r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&");e=new RegExp(`^${r.replace(/\*/g,".*")}$`),globRegexCache.set(t,e)}return e}function matchAttributes(t,e){const r={};for(const n of e)if(n.includes("*")){const i=globToRegex(n);for(const o of Object.keys(t))i.test(o)&&t[o].trim()&&(r[o]=t[o].trim())}else{const i=t[n];i&&i.trim()&&(r[n]=i.trim())}return r}function flatTreeToString(t,e=[],r=!1){const n=["title","type","checked","name","role","value","placeholder","data-date-format","alt","aria-label","aria-expanded","data-state","aria-checked","id","for","target","aria-haspopup","aria-controls","aria-owns","contenteditable"],i=[...e,...n],o=(f,g)=>f.length>g?f.substring(0,g)+"...":f,s=f=>{const g=t.map[f];if(!g)return null;if(g.type==="TEXT_NODE"){const b=g;return{type:"text",text:b.text,isVisible:b.isVisible,parent:null,children:[]}}else{const b=g,P=[];if(b.children)for(const w of b.children){const p=s(w);p&&(p.parent=null,P.push(p))}return{type:"element",tagName:b.tagName,attributes:b.attributes??{},isVisible:b.isVisible??!1,isInteractive:b.isInteractive??!1,isTopElement:b.isTopElement??!1,isNew:b.isNew??!1,highlightIndex:b.highlightIndex,parent:null,children:P,extra:b.extra??{}}}},a=(f,g=null)=>{f.parent=g;for(const b of f.children)a(b,f)},l=s(t.rootId);if(!l)return"";a(l);const c=f=>{let g=f.parent;for(;g;){if(g.type==="element"&&g.highlightIndex!==void 0)return!0;g=g.parent}return!1},u=(f,g,b)=>{let P=g;const w=" ".repeat(g);if(f.type==="element"){const p=r&&f.tagName&&SEMANTIC_TAGS.has(f.tagName);if(f.highlightIndex!==void 0){P+=1;const T=getAllTextTillNextClickableElement(f);let k="";if(i.length>0&&f.attributes){const R=matchAttributes(f.attributes,i),V=Object.keys(R);if(V.length>1){const j=new Set,H={};for(const B of V){const G=R[B];G.length>5&&(G in H?j.add(B):H[G]=B)}for(const B of j)delete R[B]}R.role===f.tagName&&delete R.role;for(const j of["aria-label","placeholder","title"])R[j]&&R[j].toLowerCase().trim()===T.toLowerCase().trim()&&delete R[j];Object.keys(R).length>0&&(k=Object.entries(R).map(([j,H])=>`${j}=${o(H,20)}`).join(" "))}let Z=`${w}${f.isNew?`*[${f.highlightIndex}]`:`[${f.highlightIndex}]`}<${f.tagName??""}`;if(k&&(Z+=` ${k}`),f.extra&&f.extra.scrollable){let R="";f.extra.scrollData?.left&&(R+=`left=${f.extra.scrollData.left}, `),f.extra.scrollData?.top&&(R+=`top=${f.extra.scrollData.top}, `),f.extra.scrollData?.right&&(R+=`right=${f.extra.scrollData.right}, `),f.extra.scrollData?.bottom&&(R+=`bottom=${f.extra.scrollData.bottom}`),Z+=` data-scrollable="${R}"`}if(T){const R=T.trim();k||(Z+=" "),Z+=`>${R}`}else k||(Z+=" ");Z+=" />",b.push(Z)}const m=p&&f.highlightIndex===void 0,A=m?b.length:-1;m&&(b.push(`${w}<${f.tagName}>`),P+=1);for(const T of f.children)u(T,P,b);m&&(b.length===A+1?b.pop():b.push(`${w}</${f.tagName}>`))}else if(f.type==="text"){if(c(f))return;f.parent&&f.parent.type==="element"&&f.parent.isVisible&&f.parent.isTopElement&&b.push(`${w}${f.text??""}`)}},h=[];return u(l,0,h),h.join(`
316
316
  `)}var getAllTextTillNextClickableElement=(t,e=-1)=>{const r=[],n=(i,o)=>{if(!(e!==-1&&o>e)&&!(i.type==="element"&&i!==t&&i.highlightIndex!==void 0)){if(i.type==="text"&&i.text)r.push(i.text);else if(i.type==="element")for(const s of i.children)n(s,o+1)}};return n(t,0),r.join(`
317
317
  `).trim()};function getSelectorMap(t){const e=new Map,r=Object.keys(t.map);for(const n of r){const i=t.map[n];i.isInteractive&&typeof i.highlightIndex=="number"&&e.set(i.highlightIndex,i)}return e}function getElementTextMap(t){const e=t.split(`
318
318
  `).map(n=>n.trim()).filter(n=>n.length>0),r=new Map;for(const n of e){const i=/^\[(\d+)\]<[^>]+>([^<]*)/.exec(n);if(i){const o=parseInt(i[1],10);r.set(o,n)}}return r}function cleanUpHighlights(){const t=window._highlightCleanupFunctions||[];for(const e of t)typeof e=="function"&&e();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 t=window.location.href;setInterval(()=>{window.location.href!==t&&(t=window.location.href,cleanUpHighlights())},500)}function getPageInfo(){const t=window.innerWidth,e=window.innerHeight,r=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth||0),n=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight||0),i=window.scrollX||window.pageXOffset||document.documentElement.scrollLeft||0,o=window.scrollY||window.pageYOffset||document.documentElement.scrollTop||0,s=Math.max(0,n-(window.innerHeight+o)),a=Math.max(0,r-(window.innerWidth+i));return{viewport_width:t,viewport_height:e,page_width:r,page_height:n,scroll_x:i,scroll_y:o,pixels_above:o,pixels_below:s,pages_above:e>0?o/e:0,pages_below:e>0?s/e:0,total_pages:e>0?n/e:0,current_page_position:o/Math.max(1,n-e),pixels_left:i,pixels_right:a}}function patchReact(t){const e=document.querySelectorAll('[data-reactroot], [data-reactid], [data-react-checksum], #root, #app, [id^="root-"], [id^="app-"], #adex-wrapper, #adex-root');for(const r of e)r.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(t={}){super(),this.config=t,patchReact(),t.enableMask&&this.initMask()}initMask(){this.maskReady===null&&(this.maskReady=(async()=>{const{SimulatorMask:t}=await Promise.resolve().then(()=>SimulatorMaskBHVXyogh);this.mask=new t})())}async getCurrentUrl(){return window.location.href}async getLastUpdateTime(){return this.lastTimeUpdate}async getBrowserState(){const t=window.location.href,e=document.title,r=getPageInfo(),n=resolveViewportExpansion(this.config.viewportExpansion);await this.updateTree();const i=this.simplifiedHTML;return{url:t,title:e,header:`${`Current Page: [${e}](${t})`}
@@ -320,7 +320,15 @@ ${`Page info: ${r.viewport_width}x${r.viewport_height}px viewport, ${r.page_widt
320
320
 
321
321
  ${n===-1?"Interactive elements from top layer of the current page (full page):":"Interactive elements from top layer of the current page inside the viewport:"}
322
322
 
323
- ${r.pixels_above>4&&n!==-1?`... ${r.pixels_above} pixels above (${r.pages_above.toFixed(1)} pages) - scroll to see more ...`:"[Start of page]"}`,content:i,footer:r.pixels_below>4&&n!==-1?`... ${r.pixels_below} pixels below (${r.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 t=[...this.config.interactiveBlacklist||[],...Array.from(document.querySelectorAll("[data-page-agent-not-interactive]"))];return this.flatTree=getFlatTree({...this.config,interactiveBlacklist:t}),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(t){try{this.assertIndexed();const e=getElementByIndex(this.selectorMap,t),r=this.elementTextMap.get(t);return await clickElement(e),isAnchorElement(e)&&e.target==="_blank"?{success:!0,message:`✅ Clicked element (${r??t}). ⚠️ Link opened in a new tab.`}:{success:!0,message:`✅ Clicked element (${r??t}).`}}catch(e){return{success:!1,message:`❌ Failed to click element: ${e}`}}}async inputText(t,e){try{this.assertIndexed();const r=getElementByIndex(this.selectorMap,t),n=this.elementTextMap.get(t);return await inputTextElement(r,e),{success:!0,message:`✅ Input text (${e}) into element (${n??t}).`}}catch(r){return{success:!1,message:`❌ Failed to input text: ${r}`}}}async selectOption(t,e){try{this.assertIndexed();const r=getElementByIndex(this.selectorMap,t),n=this.elementTextMap.get(t);return await selectOptionElement(r,e),{success:!0,message:`✅ Selected option (${e}) in element (${n??t}).`}}catch(r){return{success:!1,message:`❌ Failed to select option: ${r}`}}}async scroll(t){try{const{down:e,numPages:r,pixels:n,index:i}=t;return this.assertIndexed(),{success:!0,message:await scrollVertically((n??r*window.innerHeight)*(e?1:-1),i!==void 0?getElementByIndex(this.selectorMap,i):null)}}catch(e){return{success:!1,message:`❌ Failed to scroll: ${e}`}}}async scrollHorizontally(t){try{const{right:e,pixels:r,index:n}=t;return this.assertIndexed(),{success:!0,message:await scrollHorizontally(r*(e?1:-1),n!==void 0?getElementByIndex(this.selectorMap,n):null)}}catch(e){return{success:!1,message:`❌ Failed to scroll horizontally: ${e}`}}}async executeJavascript(script,signal){try{const asyncFunction=eval(`(async (signal) => { ${script} })`),result=await asyncFunction(signal);return{success:!0,message:`✅ Executed JavaScript. Result: ${result}`}}catch(t){return{success:!1,message:`❌ Error executing JavaScript: ${t}`}}}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}};const DEFAULT_ERROR_SELECTORS$1=['[role="alert"]','[aria-invalid="true"]',".ti3-unifyvalid-error",".ti3-error",".ti-error",".lego-text-error",".lego-error",".el-form-item__error",".ant-form-item-explain-error",".is-invalid",".invalid-feedback",".ng-invalid",".error-msg",".error-message",".error-text",".field-error",".form-error",".is-error",".has-error",".validate-error",".valid-error"],DEFAULT_WARNING_SELECTORS=[".ti3-warning",".ti-warning",".lego-text-warning",".warning-msg",".warning-text",".is-warning",".has-warning"],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",textarea:"textbox",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"};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] *)"],candidateSelector=candidateSelectors.join(","),NoElement=typeof Element>"u",matches=NoElement?function(){}:Element.prototype.matches||Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector,getRootNode=!NoElement&&Element.prototype.getRootNode?function(t){var e;return t==null||(e=t.getRootNode)===null||e===void 0?void 0:e.call(t)}:function(t){return t?.ownerDocument},isContentEditable=function t(e){var r,n=e==null||(r=e.getAttribute)===null||r===void 0?void 0:r.call(e,"contenteditable");return n===""||n==="true"},hasTabIndex=function t(e){return!isNaN(parseInt(e.getAttribute("tabindex"),10))},getTabIndex=function t(e){if(!e)throw new Error("No node provided");return e.tabIndex<0&&(/^(AUDIO|VIDEO|DETAILS)$/.test(e.tagName)||isContentEditable(e))&&!hasTabIndex(e)?0:e.tabIndex},isInput=function t(e){return e.tagName==="INPUT"},isHiddenInput=function t(e){return isInput(e)&&e.type==="hidden"},isDetailsWithSummary=function t(e){var r=e.tagName==="DETAILS"&&Array.prototype.slice.apply(e.children).some(function(n){return n.tagName==="SUMMARY"});return r},getCheckedRadio=function t(e,r){for(var n=0;n<e.length;n++)if(e[n].checked&&e[n].form===r)return e[n]},isTabbableRadio=function t(e){if(!e.name)return!0;var r=e.form||getRootNode(e),n=function(a){return r.querySelectorAll('input[type="radio"][name="'+a+'"]')},i;if(typeof window<"u"&&typeof window.CSS<"u"&&typeof window.CSS.escape=="function")i=n(window.CSS.escape(e.name));else try{i=n(e.name)}catch(s){return console.error("Looks like you have a radio button with a name attribute containing invalid CSS selector characters and need the CSS.escape polyfill: %s",s.message),!1}var o=getCheckedRadio(i,e.form);return!o||o===e},isRadio=function t(e){return isInput(e)&&e.type==="radio"},isNonTabbableRadio=function t(e){return isRadio(e)&&!isTabbableRadio(e)},isNodeAttached=function t(e){var r,n=e&&getRootNode(e),i=(r=n)===null||r===void 0?void 0:r.host,o=!1;if(n&&n!==e){var s,a,l;for(o=!!((s=i)!==null&&s!==void 0&&(a=s.ownerDocument)!==null&&a!==void 0&&a.contains(i)||e!=null&&(l=e.ownerDocument)!==null&&l!==void 0&&l.contains(e));!o&&i;){var d,u,f;n=getRootNode(i),i=(d=n)===null||d===void 0?void 0:d.host,o=!!((u=i)!==null&&u!==void 0&&(f=u.ownerDocument)!==null&&f!==void 0&&f.contains(i))}}return o},isZeroArea=function t(e){var r=e.getBoundingClientRect(),n=r.width,i=r.height;return n===0&&i===0},isHidden$2=function t(e,r){var n=r.displayCheck,i=r.getShadowRoot;if(n==="full-native"&&"checkVisibility"in e){var o=e.checkVisibility({checkOpacity:!1,opacityProperty:!1,contentVisibilityAuto:!0,visibilityProperty:!0,checkVisibilityCSS:!0});return!o}var s=getComputedStyle(e),a=s.visibility;if(a==="hidden"||a==="collapse")return!0;var l=matches.call(e,"details>summary:first-of-type"),d=l?e.parentElement:e;if(matches.call(d,"details:not([open]) *"))return!0;if(!n||n==="full"||n==="full-native"||n==="legacy-full"){if(typeof i=="function"){for(var u=e;e;){var f=e.parentElement,p=getRootNode(e);if(f&&!f.shadowRoot&&i(f)===!0)return isZeroArea(e);e.assignedSlot?e=e.assignedSlot:!f&&p!==e.ownerDocument?e=p.host:e=f}e=u}if(isNodeAttached(e))return!e.getClientRects().length;if(n!=="legacy-full")return!0}else if(n==="non-zero-area")return isZeroArea(e);return!1},isDisabledFromFieldset=function t(e){if(/^(INPUT|BUTTON|SELECT|TEXTAREA)$/.test(e.tagName))for(var r=e.parentElement;r;){if(r.tagName==="FIELDSET"&&r.disabled){for(var n=0;n<r.children.length;n++){var i=r.children.item(n);if(i.tagName==="LEGEND")return matches.call(r,"fieldset[disabled] *")?!0:!i.contains(e)}return!0}r=r.parentElement}return!1},isNodeMatchingSelectorFocusable=function t(e,r){return!(r.disabled||isHiddenInput(r)||isHidden$2(r,e)||isDetailsWithSummary(r)||isDisabledFromFieldset(r))},isNodeMatchingSelectorTabbable=function t(e,r){return!(isNonTabbableRadio(r)||getTabIndex(r)<0||!isNodeMatchingSelectorFocusable(e,r))},isTabbable=function t(e,r){if(r=r||{},!e)throw new Error("No node provided");return matches.call(e,candidateSelector)===!1?!1:isNodeMatchingSelectorTabbable(r,e)};function inferRole(t){const e=t.getAttribute("role");if(e&&e!=="presentation"&&e!=="none")return e;const r=t.tagName.toLowerCase();if(r==="input"){const n=t.type?.toLowerCase()??"text";return INPUT_TYPE_ROLE[n]??"textbox"}return TAG_ROLE_MAP[r]??"generic"}function getStateTokens(t,e,r,n){const i=[],o=C=>t.getAttribute(C),s=o("aria-checked");if(s==="true")i.push("checked");else if(s==="false")i.push("unchecked");else{const C=t.tagName.toLowerCase();let w;if(C==="input"&&(t.type==="checkbox"||t.type==="radio"))w=t.checked;else if(C==="label"&&t.hasAttribute("for")){const V=document.getElementById(t.getAttribute("for"));V instanceof HTMLInputElement&&(V.type==="checkbox"||V.type==="radio")&&(w=V.checked)}w!==void 0&&i.push(w?"checked":"unchecked")}o("aria-selected")==="true"&&i.push("selected"),(o("aria-disabled")==="true"||t.disabled)&&i.push("disabled");const l=o("aria-haspopup");l&&l!=="false"&&i.push("hasPopup"),o("aria-expanded")==="true"&&i.push("expanded");const d=t.tagName.match(/^H([1-6])$/);d&&i.push(`level=${d[1]}`);const u=o("aria-level");u&&!d&&i.push(`level=${u}`);try{window.getComputedStyle(t).cursor==="pointer"&&i.push("cursor=pointer")}catch{}const f=t.tagName.toLowerCase();if(f==="input"||f==="textarea"||f==="select"){const C=t.value;C!==void 0&&C!==""&&i.push(`value="${C}"`)}const p=t.getAttribute("aria-valuenow");p&&i.push(`valuenow="${p}"`),t.tagName.toLowerCase()==="a"&&t.getAttribute("target")==="_blank"&&i.push("opens-new-tab");const g=typeof t.className=="string"?t.className:"",Z=["is-active","isActive","is-selected","isSelected","is-current","isCurrent","active-item","activeItem","tab-active","tabActive",/\bactive\b/,/\bselected\b/,/\bcurrent\b/].some(C=>typeof C=="string"?g.split(/\s+/).includes(C):C.test(g)),S=(t.getAttribute("role")||t.tagName.toLowerCase()).split(/\s+/).some(C=>["button","option","a","li","generic"].includes(C)||C.startsWith("tab"));Z&&S&&!i.includes("checked")&&!i.includes("selected")&&i.push("active");const I=Array.isArray(r)?r.join(", "):r||DEFAULT_ERROR_SELECTORS$1.join(", "),A=Array.isArray(n)?n.join(", "):n||DEFAULT_WARNING_SELECTORS.join(", ");let O=null;if(I)try{O=t.closest(I)}catch{}if(O)i.push("error");else{let C=null;if(A)try{C=t.closest(A)}catch{}C&&i.push("warning")}if(e)for(const C of e){const w=t.getAttribute(C);w!==null&&i.push(`${C}="${w}"`)}return i}function isHidden$1(t){if(t.getAttribute("aria-hidden")==="true"||t.hidden)return!0;try{const e=window.getComputedStyle(t);if(e.display==="none"||e.visibility==="hidden"||e.opacity==="0")return!0;const r=e.overflowX!=="visible",n=e.overflowY!=="visible";if(parseFloat(e.width)===0&&r||parseFloat(e.height)===0&&n)return!0}catch{}return!1}function collectDescendantText(t){let e="";const r=n=>{if(n.nodeType===Node.TEXT_NODE)e+=(n.textContent??"")+" ";else if(n.nodeType===Node.ELEMENT_NODE){const i=n;if(isHidden$1(i))return;if(i!==t){const o=i.tagName.toLowerCase(),s=inferRole(i),a=["button","a","input","select","textarea","li","option"].includes(o),l=["button","link","checkbox","radio","textbox","listitem","option","combobox","listbox"].includes(s),d=isTabbable(i);let u=!1;try{u=window.getComputedStyle(i).cursor==="pointer"}catch{}if(d&&!(s==="generic"&&!u)||a||l)return}for(const o of Array.from(i.childNodes))r(o)}};return r(t),e.trim().replace(/\s+/g," ")}function getComposedChildren(t){const e=t.shadowRoot?t.shadowRoot.children:t.children,r=[];for(const n of Array.from(e))if(n instanceof HTMLSlotElement){const i=n.assignedElements({flatten:!0});r.push(...i.length>0?i:Array.from(n.children))}else r.push(n);return r}var toStr=Object.prototype.toString;function isCallable(t){return typeof t=="function"||toStr.call(t)==="[object Function]"}function toInteger(t){var e=Number(t);return isNaN(e)?0:e===0||!isFinite(e)?e:(e>0?1:-1)*Math.floor(Math.abs(e))}var maxSafeInteger=Math.pow(2,53)-1;function toLength(t){var e=toInteger(t);return Math.min(Math.max(e,0),maxSafeInteger)}function arrayFrom(t,e){var r=Array,n=Object(t);if(t==null)throw new TypeError("Array.from requires an array-like object - not null or undefined");for(var i=toLength(n.length),o=isCallable(r)?Object(new r(i)):new Array(i),s=0,a;s<i;)a=n[s],o[s]=a,s+=1;return o.length=i,o}function _typeof$1(t){"@babel/helpers - typeof";return _typeof$1=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$1(t)}function _classCallCheck(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function _defineProperties(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,_toPropertyKey(n.key),n)}}function _createClass(t,e,r){return e&&_defineProperties(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t}function _defineProperty(t,e,r){return e=_toPropertyKey(e),e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function _toPropertyKey(t){var e=_toPrimitive(t,"string");return _typeof$1(e)==="symbol"?e:String(e)}function _toPrimitive(t,e){if(_typeof$1(t)!=="object"||t===null)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e);if(_typeof$1(n)!=="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var SetLike=(function(){function t(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];_classCallCheck(this,t),_defineProperty(this,"items",void 0),this.items=e}return _createClass(t,[{key:"add",value:function(r){return this.has(r)===!1&&this.items.push(r),this}},{key:"clear",value:function(){this.items=[]}},{key:"delete",value:function(r){var n=this.items.length;return this.items=this.items.filter(function(i){return i!==r}),n!==this.items.length}},{key:"forEach",value:function(r){var n=this;this.items.forEach(function(i){r(i,i,n)})}},{key:"has",value:function(r){return this.items.indexOf(r)!==-1}},{key:"size",get:function(){return this.items.length}}]),t})();const SetLike$1=typeof Set>"u"?Set:SetLike;function getLocalName(t){var e;return(e=t.localName)!==null&&e!==void 0?e:t.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(t,e){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(r){var n;return t.hasAttribute(r)&&!((n=prohibitedAttributes[e])!==null&&n!==void 0&&n.has(r))})}function ignorePresentationalRole(t,e){return hasGlobalAriaAttributes(t,e)}function getRole(t){var e=getExplicitRole(t);if(e===null||presentationRoles.indexOf(e)!==-1){var r=getImplicitRole(t);if(presentationRoles.indexOf(e||"")===-1||ignorePresentationalRole(t,r||""))return r}return e}function getImplicitRole(t){var e=localNameToRoleMappings[getLocalName(t)];if(e!==void 0)return e;switch(getLocalName(t)){case"a":case"area":case"link":if(t.hasAttribute("href"))return"link";break;case"img":return t.getAttribute("alt")===""&&!ignorePresentationalRole(t,"img")?"presentation":"img";case"input":{var r=t,n=r.type;switch(n){case"button":case"image":case"reset":case"submit":return"button";case"checkbox":case"radio":return n;case"range":return"slider";case"email":case"tel":case"text":case"url":return t.hasAttribute("list")?"combobox":"textbox";case"search":return t.hasAttribute("list")?"combobox":"searchbox";case"number":return"spinbutton";default:return null}}case"select":return t.hasAttribute("multiple")||t.size>1?"listbox":"combobox"}return null}function getExplicitRole(t){var e=t.getAttribute("role");if(e!==null){var r=e.trim().split(" ")[0];if(r.length>0)return r}return null}var presentationRoles=["presentation","none"];function isElement(t){return t!==null&&t.nodeType===t.ELEMENT_NODE}function isHTMLTableCaptionElement(t){return isElement(t)&&getLocalName(t)==="caption"}function isHTMLInputElement(t){return isElement(t)&&getLocalName(t)==="input"}function isHTMLOptGroupElement(t){return isElement(t)&&getLocalName(t)==="optgroup"}function isHTMLSelectElement(t){return isElement(t)&&getLocalName(t)==="select"}function isHTMLTableElement(t){return isElement(t)&&getLocalName(t)==="table"}function isHTMLTextAreaElement(t){return isElement(t)&&getLocalName(t)==="textarea"}function safeWindow(t){var e=t.ownerDocument===null?t:t.ownerDocument,r=e.defaultView;if(r===null)throw new TypeError("no window available");return r}function isHTMLFieldSetElement(t){return isElement(t)&&getLocalName(t)==="fieldset"}function isHTMLLegendElement(t){return isElement(t)&&getLocalName(t)==="legend"}function isHTMLSlotElement(t){return isElement(t)&&getLocalName(t)==="slot"}function isSVGElement(t){return isElement(t)&&t.ownerSVGElement!==void 0}function isSVGSVGElement(t){return isElement(t)&&getLocalName(t)==="svg"}function isSVGTitleElement(t){return isSVGElement(t)&&getLocalName(t)==="title"}function queryIdRefs(t,e){if(isElement(t)&&t.hasAttribute(e)){var r=t.getAttribute(e).split(" "),n=t.getRootNode?t.getRootNode():t.ownerDocument;return r.map(function(i){return n.getElementById(i)}).filter(function(i){return i!==null})}return[]}function hasAnyConcreteRoles(t,e){return isElement(t)?e.indexOf(getRole(t))!==-1:!1}function asFlatString(t){return t.trim().replace(/\s\s+/g," ")}function isHidden(t,e){if(!isElement(t))return!1;if(t.hasAttribute("hidden")||t.getAttribute("aria-hidden")==="true")return!0;var r=e(t);return r.getPropertyValue("display")==="none"||r.getPropertyValue("visibility")==="hidden"}function isControl(t){return hasAnyConcreteRoles(t,["button","combobox","listbox","textbox"])||hasAbstractRole(t,"range")}function hasAbstractRole(t,e){if(!isElement(t))return!1;switch(e){case"range":return hasAnyConcreteRoles(t,["meter","progressbar","scrollbar","slider","spinbutton"]);default:throw new TypeError("No knowledge about abstract role '".concat(e,"'. This is likely a bug :("))}}function querySelectorAllSubtree(t,e){var r=arrayFrom(t.querySelectorAll(e));return queryIdRefs(t,"aria-owns").forEach(function(n){r.push.apply(r,arrayFrom(n.querySelectorAll(e)))}),r}function querySelectedOptions(t){return isHTMLSelectElement(t)?t.selectedOptions||querySelectorAllSubtree(t,"[selected]"):querySelectorAllSubtree(t,'[aria-selected="true"]')}function isMarkedPresentational(t){return hasAnyConcreteRoles(t,presentationRoles)}function isNativeHostLanguageTextAlternativeElement(t){return isHTMLTableCaptionElement(t)}function allowsNameFromContent(t){return hasAnyConcreteRoles(t,["button","cell","checkbox","columnheader","gridcell","heading","label","legend","link","menuitem","menuitemcheckbox","menuitemradio","option","radio","row","rowheader","switch","tab","tooltip","treeitem"])}function isDescendantOfNativeHostLanguageTextAlternativeElement(t){return!1}function getValueOfTextbox(t){return isHTMLInputElement(t)||isHTMLTextAreaElement(t)?t.value:t.textContent||""}function getTextualContent(t){var e=t.getPropertyValue("content");return/^["'].*["']$/.test(e)?e.slice(1,-1):""}function isLabelableElement(t){var e=getLocalName(t);return e==="button"||e==="input"&&t.getAttribute("type")!=="hidden"||e==="meter"||e==="output"||e==="progress"||e==="select"||e==="textarea"}function findLabelableElement(t){if(isLabelableElement(t))return t;var e=null;return t.childNodes.forEach(function(r){if(e===null&&isElement(r)){var n=findLabelableElement(r);n!==null&&(e=n)}}),e}function getControlOfLabel(t){if(t.control!==void 0)return t.control;var e=t.getAttribute("for");return e!==null?t.ownerDocument.getElementById(e):findLabelableElement(t)}function getLabels(t){var e=t.labels;if(e===null)return e;if(e!==void 0)return arrayFrom(e);if(!isLabelableElement(t))return null;var r=t.ownerDocument;return arrayFrom(r.querySelectorAll("label")).filter(function(n){return getControlOfLabel(n)===t})}function getSlotContents(t){var e=t.assignedNodes();return e.length===0?arrayFrom(t.childNodes):e}function computeTextAlternative(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=new SetLike$1,n=safeWindow(t),i=e.compute,o=i===void 0?"name":i,s=e.computedStyleSupportsPseudoElements,a=s===void 0?e.getComputedStyle!==void 0:s,l=e.getComputedStyle,d=l===void 0?n.getComputedStyle.bind(n):l,u=e.hidden,f=u===void 0?!1:u;function p(h,S){var I="";if(isElement(h)&&a){var A=d(h,"::before"),O=getTextualContent(A);I="".concat(O," ").concat(I)}var C=isHTMLSlotElement(h)?getSlotContents(h):arrayFrom(h.childNodes).concat(queryIdRefs(h,"aria-owns"));if(C.forEach(function(F){var j=x(F,{isEmbeddedInLabel:S.isEmbeddedInLabel,isReferenced:!1,recursion:!0}),H=isElement(F)?d(F).getPropertyValue("display"):"inline",W=H!=="inline"?" ":"";I+="".concat(W).concat(j).concat(W)}),isElement(h)&&a){var w=d(h,"::after"),V=getTextualContent(w);I="".concat(I," ").concat(V)}return I.trim()}function g(h,S){var I=h.getAttributeNode(S);return I!==null&&!r.has(I)&&I.value.trim()!==""?(r.add(I),I.value):null}function y(h){return isElement(h)?g(h,"title"):null}function Z(h){if(!isElement(h))return null;if(isHTMLFieldSetElement(h)){r.add(h);for(var S=arrayFrom(h.childNodes),I=0;I<S.length;I+=1){var A=S[I];if(isHTMLLegendElement(A))return x(A,{isEmbeddedInLabel:!1,isReferenced:!1,recursion:!1})}}else if(isHTMLTableElement(h)){r.add(h);for(var O=arrayFrom(h.childNodes),C=0;C<O.length;C+=1){var w=O[C];if(isHTMLTableCaptionElement(w))return x(w,{isEmbeddedInLabel:!1,isReferenced:!1,recursion:!1})}}else if(isSVGSVGElement(h)){r.add(h);for(var V=arrayFrom(h.childNodes),F=0;F<V.length;F+=1){var j=V[F];if(isSVGTitleElement(j))return j.textContent}return null}else if(getLocalName(h)==="img"||getLocalName(h)==="area"){var H=g(h,"alt");if(H!==null)return H}else if(isHTMLOptGroupElement(h)){var W=g(h,"label");if(W!==null)return W}if(isHTMLInputElement(h)&&(h.type==="button"||h.type==="submit"||h.type==="reset")){var te=g(h,"value");if(te!==null)return te;if(h.type==="submit")return"Submit";if(h.type==="reset")return"Reset"}var X=getLabels(h);if(X!==null&&X.length!==0)return r.add(h),arrayFrom(X).map(function(Q){return x(Q,{isEmbeddedInLabel:!0,isReferenced:!1,recursion:!0})}).filter(function(Q){return Q.length>0}).join(" ");if(isHTMLInputElement(h)&&h.type==="image"){var re=g(h,"alt");if(re!==null)return re;var oe=g(h,"title");return oe!==null?oe:"Submit Query"}if(hasAnyConcreteRoles(h,["button"])){var ne=p(h,{isEmbeddedInLabel:!1});if(ne!=="")return ne}return null}function x(h,S){if(r.has(h))return"";if(!f&&isHidden(h,d)&&!S.isReferenced)return r.add(h),"";var I=isElement(h)?h.getAttributeNode("aria-labelledby"):null,A=I!==null&&!r.has(I)?queryIdRefs(h,"aria-labelledby"):[];if(o==="name"&&!S.isReferenced&&A.length>0)return r.add(I),A.map(function(H){return x(H,{isEmbeddedInLabel:S.isEmbeddedInLabel,isReferenced:!0,recursion:!1})}).join(" ");var O=S.recursion&&isControl(h)&&o==="name";if(!O){var C=(isElement(h)&&h.getAttribute("aria-label")||"").trim();if(C!==""&&o==="name")return r.add(h),C;if(!isMarkedPresentational(h)){var w=Z(h);if(w!==null)return r.add(h),w}}if(hasAnyConcreteRoles(h,["menu"]))return r.add(h),"";if(O||S.isEmbeddedInLabel||S.isReferenced){if(hasAnyConcreteRoles(h,["combobox","listbox"])){r.add(h);var V=querySelectedOptions(h);return V.length===0?isHTMLInputElement(h)?h.value:"":arrayFrom(V).map(function(H){return x(H,{isEmbeddedInLabel:S.isEmbeddedInLabel,isReferenced:!1,recursion:!0})}).join(" ")}if(hasAbstractRole(h,"range"))return r.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 r.add(h),getValueOfTextbox(h)}if(allowsNameFromContent(h)||isElement(h)&&S.isReferenced||isNativeHostLanguageTextAlternativeElement(h)||isDescendantOfNativeHostLanguageTextAlternativeElement()){var F=p(h,{isEmbeddedInLabel:S.isEmbeddedInLabel});if(F!=="")return r.add(h),F}if(h.nodeType===h.TEXT_NODE)return r.add(h),h.textContent||"";if(S.recursion)return r.add(h),p(h,{isEmbeddedInLabel:S.isEmbeddedInLabel});var j=y(h);return j!==null?(r.add(h),j):(r.add(h),"")}return asFlatString(x(t,{isEmbeddedInLabel:!1,isReferenced:o==="description",recursion:!1}))}function prohibitsNaming(t){return hasAnyConcreteRoles(t,["caption","code","deletion","emphasis","generic","insertion","none","paragraph","presentation","strong","subscript","superscript"])}function computeAccessibleName(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return prohibitsNaming(t)?"":computeTextAlternative(t,e)}function buildVNode(t,e,r,n,i,o,s,a,l=!1){if(isHidden$1(t)||n.has(t))return null;const d=inferRole(t),u=getStateTokens(t,o,s,a);let f=computeAccessibleName(t);const p=isTabbable(t),g=u.includes("cursor=pointer"),y=i.has(t)||(o?.some(C=>t.hasAttribute(C))??!1),Z=t.tagName.toLowerCase()==="label"&&t.hasAttribute("for");if(!f.trim()){const C=t.tagName.toLowerCase();if(!(C==="select"||d==="combobox"||d==="listbox")){const V=["button","a","input","textarea","li","label"].includes(C);(p||y||g||V||d==="listitem"||d==="option")&&(f=collectDescendantText(t))}}if(!f.trim()&&!(getComposedChildren(t).length>0)){const w=collectDescendantText(t);w&&(f=w)}const x=t.tagName.toLowerCase(),h=x==="a"&&t.hasAttribute("href")||["button","input","select","textarea"].includes(x)&&!t.hasAttribute("disabled"),I=p&&!(d==="generic"&&!g)||y||Z||h||!l&&g&&(d!=="generic"||f!=="");let A;I&&(A=e.value,r.set(A,t),e.value++);const O=[];for(const C of getComposedChildren(t)){const w=buildVNode(C,e,r,n,i,o,s,a,I||l);w&&O.push(w)}return{role:d,name:f,tokens:u,ref:A,el:t,children:O}}function hasValue(t){return t.ref!==void 0||t.name.trim()!==""?!0:t.children.some(hasValue)}function hasInteractiveDescendant(t){return t.children.some(e=>e.ref!==void 0||hasInteractiveDescendant(e))}function findSingleRefDescendant(t){const e=[],r=n=>{n.ref!==void 0&&e.push(n),!(e.length>1)&&n.children.forEach(r)};return t.children.forEach(r),e.length===1?e[0]:null}function shouldPassThrough(t,e){return!(!e.pruneUnnamed||e.preserveRoles.includes(t.role)||t.ref!==void 0||t.name.trim()!=="")}function serializeVNode(t,e,r){if(shouldPassThrough(t,r))return t.children.filter(f=>hasValue(f)).flatMap(f=>serializeVNode(f,e,r));const n=" ".repeat(e),i=t.ref!==void 0?` #${t.ref}`:"",o=t.tokens.map(f=>f.replace(/[\r\n]+/g," ").replace(/"/g,'\\"')),s=o.length>0?` [${o.join(" ")}]`:"";if(t.ref!==void 0){if(!hasInteractiveDescendant(t)){const p=t.name?t.name.replace(/[\r\n]+/g," ").replace(/"/g,'\\"'):"",g=p?` "${p}"`:"";return[`${n}- ${t.role}${i}${s}${g}`]}const f=findSingleRefDescendant(t);if(f&&f.role==="generic"&&!hasInteractiveDescendant(f)){const p=(t.name.trim()||f.name.trim()).replace(/[\r\n]+/g," ").replace(/"/g,'\\"'),g=p?` "${p}"`:"";return[`${n}- ${t.role}${i}${s}${g}`]}}const a=t.name?t.name.replace(/[\r\n]+/g," ").replace(/"/g,'\\"'):"",l=a?` "${a}"`:"",d=`${n}- ${t.role}${i}${s}${l}`,u=t.children.flatMap(f=>serializeVNode(f,e+1,r));return[d,...u]}const HIGHLIGHT_CONTAINER_ID="webmcpcli-highlight-container",HIGHLIGHT_CONTAINER_STYLE_ID="webmcpcli-highlight-container-style",colors=["#FF0000","#00FF00","#0000FF","#FFA500","#800080","#008080","#FF69B4","#4B0082","#FF4500","#2E8B57","#DC143C","#4682B4"],opacity=Math.floor(.3*255).toString(16).padStart(2,"0"),injectStyles$1=`
323
+ ${r.pixels_above>4&&n!==-1?`... ${r.pixels_above} pixels above (${r.pages_above.toFixed(1)} pages) - scroll to see more ...`:"[Start of page]"}`,content:i,footer:r.pixels_below>4&&n!==-1?`... ${r.pixels_below} pixels below (${r.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 t=[...this.config.interactiveBlacklist||[],...Array.from(document.querySelectorAll("[data-page-agent-not-interactive]"))];return this.flatTree=getFlatTree({...this.config,interactiveBlacklist:t}),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(t){try{this.assertIndexed();const e=getElementByIndex(this.selectorMap,t),r=this.elementTextMap.get(t);return await clickElement(e),isAnchorElement(e)&&e.target==="_blank"?{success:!0,message:`✅ Clicked element (${r??t}). ⚠️ Link opened in a new tab.`}:{success:!0,message:`✅ Clicked element (${r??t}).`}}catch(e){return{success:!1,message:`❌ Failed to click element: ${e}`}}}async inputText(t,e){try{this.assertIndexed();const r=getElementByIndex(this.selectorMap,t),n=this.elementTextMap.get(t);return await inputTextElement(r,e),{success:!0,message:`✅ Input text (${e}) into element (${n??t}).`}}catch(r){return{success:!1,message:`❌ Failed to input text: ${r}`}}}async selectOption(t,e){try{this.assertIndexed();const r=getElementByIndex(this.selectorMap,t),n=this.elementTextMap.get(t);return await selectOptionElement(r,e),{success:!0,message:`✅ Selected option (${e}) in element (${n??t}).`}}catch(r){return{success:!1,message:`❌ Failed to select option: ${r}`}}}async scroll(t){try{const{down:e,numPages:r,pixels:n,index:i}=t;return this.assertIndexed(),{success:!0,message:await scrollVertically((n??r*window.innerHeight)*(e?1:-1),i!==void 0?getElementByIndex(this.selectorMap,i):null)}}catch(e){return{success:!1,message:`❌ Failed to scroll: ${e}`}}}async scrollHorizontally(t){try{const{right:e,pixels:r,index:n}=t;return this.assertIndexed(),{success:!0,message:await scrollHorizontally(r*(e?1:-1),n!==void 0?getElementByIndex(this.selectorMap,n):null)}}catch(e){return{success:!1,message:`❌ Failed to scroll horizontally: ${e}`}}}async executeJavascript(script,signal){try{const asyncFunction=eval(`(async (signal) => { ${script} })`),result=await asyncFunction(signal);return{success:!0,message:`✅ Executed JavaScript. Result: ${result}`}}catch(t){return{success:!1,message:`❌ Error executing JavaScript: ${t}`}}}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}};const DEFAULT_ERROR_SELECTORS=['[role="alert"]','[aria-invalid="true"]',".ti3-unifyvalid-error",".ti3-error",".ti-error",".lego-text-error",".lego-error",".el-form-item__error",".ant-form-item-explain-error",".is-invalid",".invalid-feedback",".ng-invalid",".error-msg",".error-message",".error-text",".field-error",".form-error",".is-error",".has-error",".validate-error",".valid-error"],DEFAULT_WARNING_SELECTORS=[".ti3-warning",".ti-warning",".lego-text-warning",".warning-msg",".warning-text",".is-warning",".has-warning"],DEFAULT_DIALOG_SELECTORS=['[role="dialog"]','[role="alertdialog"]','[class*="ti3-modal"]','[class*="ti3-message-box"]','[class*="el-dialog"]','[class*="el-message-box"]','[class*="ant-modal"]','[class*="modal-content"]','[class*="v-dialog"]','[class*="n-modal"]'],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",textarea:"textbox",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"},RESOLVED_A11Y_BRAND=Symbol.for("@opentiny/next-sdk:ResolvedA11yConfig");function markResolved(t){return Object.assign(t,{[RESOLVED_A11Y_BRAND]:!0})}function isResolvedA11yConfig(t){return!!t&&t[RESOLVED_A11Y_BRAND]===!0}const STANDARD_STATE_NAMES=["checked","selected","pressed","current","expanded","hasPopup","disabled","readonly","required","invalid","busy","error","warning"],DEFAULT_SELECTED_CLASS_RE=/\b(is-active|isActive|is-selected|isSelected|is-current|isCurrent|active-item|activeItem|tab-active|tabActive|active|selected|current)\b/;function defaultSelectedMatch(t){const e=typeof t.className=="string"?t.className:"";if(!e||!DEFAULT_SELECTED_CLASS_RE.test(e))return!1;const r=t.getAttribute("role")||t.tagName.toLowerCase();return["button","option","a","li","generic"].includes(r)||r.startsWith("tab")}const DEFAULT_A11Y_CONFIG=markResolved({roles:[],states:{selected:[{match:defaultSelectedMatch},{selector:".ti3-btn-item-container.ti3-active"}],error:[{selector:DEFAULT_ERROR_SELECTORS}],warning:[{selector:DEFAULT_WARNING_SELECTORS}]},whitelist:[],blacklist:[],exposedAttributes:[],dialogSelectors:DEFAULT_DIALOG_SELECTORS});function normalizeSelector(t){return t&&(Array.isArray(t)?t.filter(Boolean).join(", "):t)||void 0}function matchesRule(t,e){if(e.match)try{return!!e.match(t)}catch{return!1}const r=normalizeSelector(e.selector);if(r)try{return!!t.closest(r)}catch{return!1}return!1}function matchesRoleRule(t,e){if(e.match)try{return!!e.match(t)}catch{return!1}const r=normalizeSelector(e.selector);if(r)try{return!!t.matches(r)}catch{return!1}return!1}function matchesAnyRule(t,e){return e?(Array.isArray(e)?e:[e]).some(n=>matchesRule(t,n)):!1}function extractSelectors(t){return t?(Array.isArray(t)?t:[t]).flatMap(r=>Array.isArray(r.selector)?r.selector.filter(Boolean):r.selector?[r.selector]:[]):[]}function concatArr(t,e){return[...t??[],...e??[]]}function normalizeMatcherList(t){return t?Array.isArray(t)?t:[t]:[]}function mergeStates(t,e){const r={},n=new Set([...Object.keys(t??{}),...Object.keys(e??{})]);for(const i of n)r[i]=[...normalizeMatcherList(t?.[i]),...normalizeMatcherList(e?.[i])];return r}function mergeA11yConfigs(t,e){return markResolved({roles:concatArr(t.roles,e.roles),states:mergeStates(t.states,e.states),whitelist:concatArr(t.whitelist,e.whitelist),blacklist:concatArr(t.blacklist,e.blacklist),exposedAttributes:concatArr(t.exposedAttributes,e.exposedAttributes),dialogSelectors:concatArr(t.dialogSelectors,e.dialogSelectors)})}function mergeA11yConfig(t){return isResolvedA11yConfig(t)?t:mergeA11yConfigs(DEFAULT_A11Y_CONFIG,t??{})}function ensureResolvedA11yConfig(t){return isResolvedA11yConfig(t)?t:mergeA11yConfig(t)}function defineA11yConfig(t){return t}function computeRole(t,e){const r=t.getAttribute("role"),n=!!r&&r!=="presentation"&&r!=="none";for(const o of e.roles)if(!(n&&!o.force)&&matchesRoleRule(t,o))return o.role;if(n)return r;const i=t.tagName.toLowerCase();if(i==="input"){const o=t.type?.toLowerCase()??"text";return INPUT_TYPE_ROLE[o]??"textbox"}return TAG_ROLE_MAP[i]??"generic"}function computeStates(t,e){const r=[],n=m=>t.getAttribute(m),i=e.states,o=m=>matchesAnyRule(t,i[m]),s=n("aria-checked");if(s==="true")r.push("checked");else if(s==="mixed")r.push("checked=mixed");else if(s==="false")r.push("unchecked");else{const m=t.tagName.toLowerCase();let A;if(m==="input"&&(t.type==="checkbox"||t.type==="radio"))A=t.checked;else if(m==="label"&&t.hasAttribute("for")){const T=document.getElementById(t.getAttribute("for"));T instanceof HTMLInputElement&&(T.type==="checkbox"||T.type==="radio")&&(A=T.checked)}A!==void 0?r.push(A?"checked":"unchecked"):o("checked")&&r.push("checked")}(n("aria-selected")==="true"||o("selected"))&&r.push("selected");const a=n("aria-pressed");a==="true"?r.push("pressed"):a==="mixed"?r.push("pressed=mixed"):a!=="false"&&o("pressed")&&r.push("pressed");const l=n("aria-current");l&&l!=="false"?r.push(l==="true"?"current":`current=${l}`):o("current")&&r.push("current"),(n("aria-disabled")==="true"||t.disabled||o("disabled"))&&r.push("disabled");const c=n("aria-haspopup");(c&&c!=="false"||o("hasPopup"))&&r.push("hasPopup"),(n("aria-expanded")==="true"||o("expanded"))&&r.push("expanded");const u=n("aria-invalid");u&&u!=="false"?r.push(u==="true"?"invalid":`invalid=${u}`):o("invalid")&&r.push("invalid"),(n("aria-readonly")==="true"||t.readOnly||o("readonly"))&&r.push("readonly"),(n("aria-required")==="true"||t.required||o("required"))&&r.push("required"),(n("aria-busy")==="true"||o("busy"))&&r.push("busy");const h=n("aria-orientation");h&&r.push(`orientation=${h}`);const f=n("aria-sort");f&&f!=="none"&&r.push(`sort=${f}`),n("aria-multiselectable")==="true"&&r.push("multiselectable");const g=t.tagName.match(/^H([1-6])$/);g&&r.push(`level=${g[1]}`);const b=n("aria-level");b&&!g&&r.push(`level=${b}`);try{window.getComputedStyle(t).cursor==="pointer"&&r.push("cursor=pointer")}catch{}const P=t.tagName.toLowerCase();if(P==="input"||P==="textarea"||P==="select"){const m=t.value;m!==void 0&&m!==""&&r.push(`value="${m}"`)}const w=n("aria-valuenow");w&&r.push(`valuenow="${w}"`);const p=n("aria-valuetext");if(p&&r.push(`valuetext="${p}"`),P==="a"){const m=n("target");m&&r.push(`target=${m}`)}o("error")?r.push("error"):o("warning")&&r.push("warning");for(const m of Object.keys(i))STANDARD_STATE_NAMES.includes(m)||matchesAnyRule(t,i[m])&&r.push(m);for(const m of e.exposedAttributes){const A=t.getAttribute(m);A!==null&&r.push(`${m}="${A}"`)}return Array.from(new Set(r))}function resolveA11yRole(t,e){return computeRole(t,ensureResolvedA11yConfig(e))}function resolveA11yInfo(t,e){const r=ensureResolvedA11yConfig(e);return{role:computeRole(t,r),tokens:computeStates(t,r)}}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] *)"],candidateSelector=candidateSelectors.join(","),NoElement=typeof Element>"u",matches=NoElement?function(){}:Element.prototype.matches||Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector,getRootNode=!NoElement&&Element.prototype.getRootNode?function(t){var e;return t==null||(e=t.getRootNode)===null||e===void 0?void 0:e.call(t)}:function(t){return t?.ownerDocument},isContentEditable=function t(e){var r,n=e==null||(r=e.getAttribute)===null||r===void 0?void 0:r.call(e,"contenteditable");return n===""||n==="true"},hasTabIndex=function t(e){return!isNaN(parseInt(e.getAttribute("tabindex"),10))},getTabIndex=function t(e){if(!e)throw new Error("No node provided");return e.tabIndex<0&&(/^(AUDIO|VIDEO|DETAILS)$/.test(e.tagName)||isContentEditable(e))&&!hasTabIndex(e)?0:e.tabIndex},isInput=function t(e){return e.tagName==="INPUT"},isHiddenInput=function t(e){return isInput(e)&&e.type==="hidden"},isDetailsWithSummary=function t(e){var r=e.tagName==="DETAILS"&&Array.prototype.slice.apply(e.children).some(function(n){return n.tagName==="SUMMARY"});return r},getCheckedRadio=function t(e,r){for(var n=0;n<e.length;n++)if(e[n].checked&&e[n].form===r)return e[n]},isTabbableRadio=function t(e){if(!e.name)return!0;var r=e.form||getRootNode(e),n=function(a){return r.querySelectorAll('input[type="radio"][name="'+a+'"]')},i;if(typeof window<"u"&&typeof window.CSS<"u"&&typeof window.CSS.escape=="function")i=n(window.CSS.escape(e.name));else try{i=n(e.name)}catch(s){return console.error("Looks like you have a radio button with a name attribute containing invalid CSS selector characters and need the CSS.escape polyfill: %s",s.message),!1}var o=getCheckedRadio(i,e.form);return!o||o===e},isRadio=function t(e){return isInput(e)&&e.type==="radio"},isNonTabbableRadio=function t(e){return isRadio(e)&&!isTabbableRadio(e)},isNodeAttached=function t(e){var r,n=e&&getRootNode(e),i=(r=n)===null||r===void 0?void 0:r.host,o=!1;if(n&&n!==e){var s,a,l;for(o=!!((s=i)!==null&&s!==void 0&&(a=s.ownerDocument)!==null&&a!==void 0&&a.contains(i)||e!=null&&(l=e.ownerDocument)!==null&&l!==void 0&&l.contains(e));!o&&i;){var c,u,h;n=getRootNode(i),i=(c=n)===null||c===void 0?void 0:c.host,o=!!((u=i)!==null&&u!==void 0&&(h=u.ownerDocument)!==null&&h!==void 0&&h.contains(i))}}return o},isZeroArea=function t(e){var r=e.getBoundingClientRect(),n=r.width,i=r.height;return n===0&&i===0},isHidden$2=function t(e,r){var n=r.displayCheck,i=r.getShadowRoot;if(n==="full-native"&&"checkVisibility"in e){var o=e.checkVisibility({checkOpacity:!1,opacityProperty:!1,contentVisibilityAuto:!0,visibilityProperty:!0,checkVisibilityCSS:!0});return!o}var s=getComputedStyle(e),a=s.visibility;if(a==="hidden"||a==="collapse")return!0;var l=matches.call(e,"details>summary:first-of-type"),c=l?e.parentElement:e;if(matches.call(c,"details:not([open]) *"))return!0;if(!n||n==="full"||n==="full-native"||n==="legacy-full"){if(typeof i=="function"){for(var u=e;e;){var h=e.parentElement,f=getRootNode(e);if(h&&!h.shadowRoot&&i(h)===!0)return isZeroArea(e);e.assignedSlot?e=e.assignedSlot:!h&&f!==e.ownerDocument?e=f.host:e=h}e=u}if(isNodeAttached(e))return!e.getClientRects().length;if(n!=="legacy-full")return!0}else if(n==="non-zero-area")return isZeroArea(e);return!1},isDisabledFromFieldset=function t(e){if(/^(INPUT|BUTTON|SELECT|TEXTAREA)$/.test(e.tagName))for(var r=e.parentElement;r;){if(r.tagName==="FIELDSET"&&r.disabled){for(var n=0;n<r.children.length;n++){var i=r.children.item(n);if(i.tagName==="LEGEND")return matches.call(r,"fieldset[disabled] *")?!0:!i.contains(e)}return!0}r=r.parentElement}return!1},isNodeMatchingSelectorFocusable=function t(e,r){return!(r.disabled||isHiddenInput(r)||isHidden$2(r,e)||isDetailsWithSummary(r)||isDisabledFromFieldset(r))},isNodeMatchingSelectorTabbable=function t(e,r){return!(isNonTabbableRadio(r)||getTabIndex(r)<0||!isNodeMatchingSelectorFocusable(e,r))},isTabbable=function t(e,r){if(r=r||{},!e)throw new Error("No node provided");return matches.call(e,candidateSelector)===!1?!1:isNodeMatchingSelectorTabbable(r,e)};const DEFAULT_PAGE_AGENT_TOOL_CONFIG={enableHighlight:!1,removeMaskAfterToolCall:!0,a11yConfig:DEFAULT_A11Y_CONFIG};function getPageAgentToolConfig(){return typeof window<"u"&&window.__webmcpcli_toolConfig?window.__webmcpcli_toolConfig:{enableHighlight:DEFAULT_PAGE_AGENT_TOOL_CONFIG.enableHighlight,removeMaskAfterToolCall:DEFAULT_PAGE_AGENT_TOOL_CONFIG.removeMaskAfterToolCall,a11yConfig:mergeA11yConfig()}}function resolvePatch(t,e){return{enableHighlight:t.enableHighlight??e.enableHighlight,removeMaskAfterToolCall:t.removeMaskAfterToolCall??e.removeMaskAfterToolCall,a11yConfig:mergeA11yConfigs(e.a11yConfig,t.a11yConfig??{})}}function setPageAgentToolConfig(t,e){const r=e?.mode??"merge",n=getPageAgentToolConfig(),i=typeof t=="function"?resolvePatch(t(n),DEFAULT_PAGE_AGENT_TOOL_CONFIG):resolvePatch(t,r==="replace"?DEFAULT_PAGE_AGENT_TOOL_CONFIG:n);return typeof window<"u"&&(window.__webmcpcli_toolConfig=i),i}function isInShadowDom(t){return t.getRootNode()instanceof ShadowRoot}function dispatchComposedEvents(t,...e){for(const r of e)t.dispatchEvent(new Event(r,{bubbles:!0,composed:!0}))}function deepQuerySelectorAll(t,e=document){const r=Array.from(e.querySelectorAll(t)),n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,null);let i=n.currentNode;for(;i;)i.shadowRoot&&r.push(...deepQuerySelectorAll(t,i.shadowRoot)),i=n.nextNode();return r}function waitForDomSettled(t=600,e=150){return new Promise(r=>{let n=!1,i;const o=()=>{n||(n=!0,s.disconnect(),i&&clearTimeout(i),r())},s=new MutationObserver(()=>{i&&clearTimeout(i),i=setTimeout(o,e)});i=setTimeout(o,e),setTimeout(o,t),s.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["class","style","hidden"]})})}function detectPageDialog(){const t=new Set,e=[],r=getPageAgentToolConfig().a11yConfig.dialogSelectors;for(const n of r)try{for(const i of deepQuerySelectorAll(n)){if(t.has(i)||i.id?.includes("page-agent-runtime")||i.closest("#page-agent-runtime_simulator-mask"))continue;const o=i.getBoundingClientRect();if(o.width<50||o.height<50)continue;const s=window.getComputedStyle(i);if(s.display==="none"||s.visibility==="hidden")continue;const a=s.position==="fixed"||s.position==="absolute",l=parseInt(s.zIndex||"0",10);if(!a||l<100)continue;const c=window.innerWidth,u=window.innerHeight;if(!(o.left<c*.6&&o.right>c*.4&&o.top<u*.6&&o.bottom>u*.4))continue;t.add(i);const f=(i.textContent||"").trim().replace(/\s+/g," ");if(f.length>5){const g=i.querySelectorAll('button, [role="button"], a'),b=Array.from(g).map(w=>(w.textContent||"").trim()).filter(w=>w.length>0&&w.length<20).slice(0,5),P=b.length?` [可操作按钮: ${b.join(" / ")}]`:"";e.push(`${f.substring(0,300)}${P}`)}}}catch{}return e.length===0?"":`
324
+ [页面弹窗检测] 检测到 ${e.length} 个模态弹窗,请优先处理:
325
+ ${e.map((n,i)=>`${i+1}. ${n}`).join(`
326
+ `)}
327
+ `}function detectValidationErrors(){const t=new Set,e=[],r=extractSelectors(getPageAgentToolConfig().a11yConfig.states.error);for(const n of r)try{for(const i of deepQuerySelectorAll(n)){if(t.has(i)||Array.from(t).some(l=>l.contains(i)))continue;const o=i.getBoundingClientRect();if(o.width<1||o.height<1)continue;const s=window.getComputedStyle(i);if(s.display==="none"||s.visibility==="hidden")continue;const a=(i.textContent||"").trim().replace(/\s+/g," ");a.length>2&&a.length<200&&(t.add(i),e.push(a))}}catch{}return e.length===0?"":`
328
+ [校验提示] 检测到 ${e.length} 个表单校验错误,请先修复后再继续:
329
+ ${e.map((n,i)=>`${i+1}. ${n}`).join(`
330
+ `)}
331
+ `}const NON_CONTENT_TAGS=new Set(["script","style","noscript","template","link","meta","head","title"]);function isNonContentElement(t){return NON_CONTENT_TAGS.has(t.tagName.toLowerCase())}function hasOwnPointerCursor(t){try{if(window.getComputedStyle(t).cursor!=="pointer")return!1;const e=t.parentElement;return e?window.getComputedStyle(e).cursor!=="pointer":!0}catch{return!1}}const INTERACTION_PSEUDO_RE=/:(hover|focus|focus-visible|focus-within|active)\b/gi;function collectInteractivePointerSelectors(t,e){for(const r of Array.from(t)){const n=r,i=r;if(!n.selectorText&&i.cssRules){collectInteractivePointerSelectors(i.cssRules,e);continue}const o=n.selectorText;if(!(!o||!n.style||n.style.cursor!=="pointer")&&/:(hover|focus|focus-visible|focus-within|active)\b/i.test(o))for(const s of o.split(",")){const a=s.replace(INTERACTION_PSEUDO_RE,"").trim();a&&a!=="*"&&e.add(a)}}}function collectHoverPointerElements(t){const e=new Set,r=new Set;try{for(const i of Array.from(document.styleSheets)){let o=null;try{o=i.cssRules}catch{continue}o&&collectInteractivePointerSelectors(o,r)}}catch{return e}if(r.size===0)return e;const n=Array.from(r);try{for(const i of deepQuerySelectorAll(n.join(", "),t))e.add(i);return e}catch{for(const i of n)try{for(const o of deepQuerySelectorAll(i,t))e.add(o)}catch{}}return e}function isHidden$1(t){if(isNonContentElement(t)||t.getAttribute("aria-hidden")==="true"||t.hidden)return!0;try{const e=window.getComputedStyle(t);if(e.display==="none"||e.visibility==="hidden"||e.opacity==="0")return!0;const r=e.overflowX!=="visible",n=e.overflowY!=="visible";if(parseFloat(e.width)===0&&r||parseFloat(e.height)===0&&n)return!0}catch{}return!1}function collectTitleLabel(t){const e=t.getAttribute("title")?.trim();if(e)return e;const n=t.querySelector("[title]")?.getAttribute("title")?.trim();return n||""}function collectDescendantText(t,e){let r="";const n=i=>{if(i.nodeType===Node.TEXT_NODE)r+=(i.textContent??"")+" ";else if(i.nodeType===Node.ELEMENT_NODE){const o=i;if(o!==t&&isNonContentElement(o)||isHidden$1(o)&&o!==t||o===t&&isNonContentElement(o))return;if(o!==t){const s=o.tagName.toLowerCase(),a=resolveA11yRole(o,e),l=["button","a","input","select","textarea","li","option"].includes(s),c=["button","link","checkbox","radio","textbox","listitem","option","combobox","listbox"].includes(a),u=isTabbable(o),h=hasOwnPointerCursor(o);if(u&&!(a==="generic"&&!h)||l||c)return}for(const s of Array.from(o.childNodes))n(s)}};return n(t),r.trim().replace(/\s+/g," ")}function getComposedChildren(t){const e=t.shadowRoot?t.shadowRoot.children:t.children,r=[];for(const n of Array.from(e))if(n instanceof HTMLSlotElement){const i=n.assignedElements({flatten:!0});r.push(...i.length>0?i:Array.from(n.children))}else r.push(n);return r}var toStr=Object.prototype.toString;function isCallable(t){return typeof t=="function"||toStr.call(t)==="[object Function]"}function toInteger(t){var e=Number(t);return isNaN(e)?0:e===0||!isFinite(e)?e:(e>0?1:-1)*Math.floor(Math.abs(e))}var maxSafeInteger=Math.pow(2,53)-1;function toLength(t){var e=toInteger(t);return Math.min(Math.max(e,0),maxSafeInteger)}function arrayFrom(t,e){var r=Array,n=Object(t);if(t==null)throw new TypeError("Array.from requires an array-like object - not null or undefined");for(var i=toLength(n.length),o=isCallable(r)?Object(new r(i)):new Array(i),s=0,a;s<i;)a=n[s],o[s]=a,s+=1;return o.length=i,o}function _typeof$1(t){"@babel/helpers - typeof";return _typeof$1=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$1(t)}function _classCallCheck(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function _defineProperties(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,_toPropertyKey(n.key),n)}}function _createClass(t,e,r){return e&&_defineProperties(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t}function _defineProperty(t,e,r){return e=_toPropertyKey(e),e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function _toPropertyKey(t){var e=_toPrimitive(t,"string");return _typeof$1(e)==="symbol"?e:String(e)}function _toPrimitive(t,e){if(_typeof$1(t)!=="object"||t===null)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e);if(_typeof$1(n)!=="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var SetLike=(function(){function t(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];_classCallCheck(this,t),_defineProperty(this,"items",void 0),this.items=e}return _createClass(t,[{key:"add",value:function(r){return this.has(r)===!1&&this.items.push(r),this}},{key:"clear",value:function(){this.items=[]}},{key:"delete",value:function(r){var n=this.items.length;return this.items=this.items.filter(function(i){return i!==r}),n!==this.items.length}},{key:"forEach",value:function(r){var n=this;this.items.forEach(function(i){r(i,i,n)})}},{key:"has",value:function(r){return this.items.indexOf(r)!==-1}},{key:"size",get:function(){return this.items.length}}]),t})();const SetLike$1=typeof Set>"u"?Set:SetLike;function getLocalName(t){var e;return(e=t.localName)!==null&&e!==void 0?e:t.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(t,e){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(r){var n;return t.hasAttribute(r)&&!((n=prohibitedAttributes[e])!==null&&n!==void 0&&n.has(r))})}function ignorePresentationalRole(t,e){return hasGlobalAriaAttributes(t,e)}function getRole(t){var e=getExplicitRole(t);if(e===null||presentationRoles.indexOf(e)!==-1){var r=getImplicitRole(t);if(presentationRoles.indexOf(e||"")===-1||ignorePresentationalRole(t,r||""))return r}return e}function getImplicitRole(t){var e=localNameToRoleMappings[getLocalName(t)];if(e!==void 0)return e;switch(getLocalName(t)){case"a":case"area":case"link":if(t.hasAttribute("href"))return"link";break;case"img":return t.getAttribute("alt")===""&&!ignorePresentationalRole(t,"img")?"presentation":"img";case"input":{var r=t,n=r.type;switch(n){case"button":case"image":case"reset":case"submit":return"button";case"checkbox":case"radio":return n;case"range":return"slider";case"email":case"tel":case"text":case"url":return t.hasAttribute("list")?"combobox":"textbox";case"search":return t.hasAttribute("list")?"combobox":"searchbox";case"number":return"spinbutton";default:return null}}case"select":return t.hasAttribute("multiple")||t.size>1?"listbox":"combobox"}return null}function getExplicitRole(t){var e=t.getAttribute("role");if(e!==null){var r=e.trim().split(" ")[0];if(r.length>0)return r}return null}var presentationRoles=["presentation","none"];function isElement(t){return t!==null&&t.nodeType===t.ELEMENT_NODE}function isHTMLTableCaptionElement(t){return isElement(t)&&getLocalName(t)==="caption"}function isHTMLInputElement(t){return isElement(t)&&getLocalName(t)==="input"}function isHTMLOptGroupElement(t){return isElement(t)&&getLocalName(t)==="optgroup"}function isHTMLSelectElement(t){return isElement(t)&&getLocalName(t)==="select"}function isHTMLTableElement(t){return isElement(t)&&getLocalName(t)==="table"}function isHTMLTextAreaElement(t){return isElement(t)&&getLocalName(t)==="textarea"}function safeWindow(t){var e=t.ownerDocument===null?t:t.ownerDocument,r=e.defaultView;if(r===null)throw new TypeError("no window available");return r}function isHTMLFieldSetElement(t){return isElement(t)&&getLocalName(t)==="fieldset"}function isHTMLLegendElement(t){return isElement(t)&&getLocalName(t)==="legend"}function isHTMLSlotElement(t){return isElement(t)&&getLocalName(t)==="slot"}function isSVGElement(t){return isElement(t)&&t.ownerSVGElement!==void 0}function isSVGSVGElement(t){return isElement(t)&&getLocalName(t)==="svg"}function isSVGTitleElement(t){return isSVGElement(t)&&getLocalName(t)==="title"}function queryIdRefs(t,e){if(isElement(t)&&t.hasAttribute(e)){var r=t.getAttribute(e).split(" "),n=t.getRootNode?t.getRootNode():t.ownerDocument;return r.map(function(i){return n.getElementById(i)}).filter(function(i){return i!==null})}return[]}function hasAnyConcreteRoles(t,e){return isElement(t)?e.indexOf(getRole(t))!==-1:!1}function asFlatString(t){return t.trim().replace(/\s\s+/g," ")}function isHidden(t,e){if(!isElement(t))return!1;if(t.hasAttribute("hidden")||t.getAttribute("aria-hidden")==="true")return!0;var r=e(t);return r.getPropertyValue("display")==="none"||r.getPropertyValue("visibility")==="hidden"}function isControl(t){return hasAnyConcreteRoles(t,["button","combobox","listbox","textbox"])||hasAbstractRole(t,"range")}function hasAbstractRole(t,e){if(!isElement(t))return!1;switch(e){case"range":return hasAnyConcreteRoles(t,["meter","progressbar","scrollbar","slider","spinbutton"]);default:throw new TypeError("No knowledge about abstract role '".concat(e,"'. This is likely a bug :("))}}function querySelectorAllSubtree(t,e){var r=arrayFrom(t.querySelectorAll(e));return queryIdRefs(t,"aria-owns").forEach(function(n){r.push.apply(r,arrayFrom(n.querySelectorAll(e)))}),r}function querySelectedOptions(t){return isHTMLSelectElement(t)?t.selectedOptions||querySelectorAllSubtree(t,"[selected]"):querySelectorAllSubtree(t,'[aria-selected="true"]')}function isMarkedPresentational(t){return hasAnyConcreteRoles(t,presentationRoles)}function isNativeHostLanguageTextAlternativeElement(t){return isHTMLTableCaptionElement(t)}function allowsNameFromContent(t){return hasAnyConcreteRoles(t,["button","cell","checkbox","columnheader","gridcell","heading","label","legend","link","menuitem","menuitemcheckbox","menuitemradio","option","radio","row","rowheader","switch","tab","tooltip","treeitem"])}function isDescendantOfNativeHostLanguageTextAlternativeElement(t){return!1}function getValueOfTextbox(t){return isHTMLInputElement(t)||isHTMLTextAreaElement(t)?t.value:t.textContent||""}function getTextualContent(t){var e=t.getPropertyValue("content");return/^["'].*["']$/.test(e)?e.slice(1,-1):""}function isLabelableElement(t){var e=getLocalName(t);return e==="button"||e==="input"&&t.getAttribute("type")!=="hidden"||e==="meter"||e==="output"||e==="progress"||e==="select"||e==="textarea"}function findLabelableElement(t){if(isLabelableElement(t))return t;var e=null;return t.childNodes.forEach(function(r){if(e===null&&isElement(r)){var n=findLabelableElement(r);n!==null&&(e=n)}}),e}function getControlOfLabel(t){if(t.control!==void 0)return t.control;var e=t.getAttribute("for");return e!==null?t.ownerDocument.getElementById(e):findLabelableElement(t)}function getLabels(t){var e=t.labels;if(e===null)return e;if(e!==void 0)return arrayFrom(e);if(!isLabelableElement(t))return null;var r=t.ownerDocument;return arrayFrom(r.querySelectorAll("label")).filter(function(n){return getControlOfLabel(n)===t})}function getSlotContents(t){var e=t.assignedNodes();return e.length===0?arrayFrom(t.childNodes):e}function computeTextAlternative(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=new SetLike$1,n=safeWindow(t),i=e.compute,o=i===void 0?"name":i,s=e.computedStyleSupportsPseudoElements,a=s===void 0?e.getComputedStyle!==void 0:s,l=e.getComputedStyle,c=l===void 0?n.getComputedStyle.bind(n):l,u=e.hidden,h=u===void 0?!1:u;function f(p,m){var A="";if(isElement(p)&&a){var T=c(p,"::before"),k=getTextualContent(T);A="".concat(k," ").concat(A)}var Z=isHTMLSlotElement(p)?getSlotContents(p):arrayFrom(p.childNodes).concat(queryIdRefs(p,"aria-owns"));if(Z.forEach(function(j){var H=w(j,{isEmbeddedInLabel:m.isEmbeddedInLabel,isReferenced:!1,recursion:!0}),B=isElement(j)?c(j).getPropertyValue("display"):"inline",G=B!=="inline"?" ":"";A+="".concat(G).concat(H).concat(G)}),isElement(p)&&a){var R=c(p,"::after"),V=getTextualContent(R);A="".concat(A," ").concat(V)}return A.trim()}function g(p,m){var A=p.getAttributeNode(m);return A!==null&&!r.has(A)&&A.value.trim()!==""?(r.add(A),A.value):null}function b(p){return isElement(p)?g(p,"title"):null}function P(p){if(!isElement(p))return null;if(isHTMLFieldSetElement(p)){r.add(p);for(var m=arrayFrom(p.childNodes),A=0;A<m.length;A+=1){var T=m[A];if(isHTMLLegendElement(T))return w(T,{isEmbeddedInLabel:!1,isReferenced:!1,recursion:!1})}}else if(isHTMLTableElement(p)){r.add(p);for(var k=arrayFrom(p.childNodes),Z=0;Z<k.length;Z+=1){var R=k[Z];if(isHTMLTableCaptionElement(R))return w(R,{isEmbeddedInLabel:!1,isReferenced:!1,recursion:!1})}}else if(isSVGSVGElement(p)){r.add(p);for(var V=arrayFrom(p.childNodes),j=0;j<V.length;j+=1){var H=V[j];if(isSVGTitleElement(H))return H.textContent}return null}else if(getLocalName(p)==="img"||getLocalName(p)==="area"){var B=g(p,"alt");if(B!==null)return B}else if(isHTMLOptGroupElement(p)){var G=g(p,"label");if(G!==null)return G}if(isHTMLInputElement(p)&&(p.type==="button"||p.type==="submit"||p.type==="reset")){var ie=g(p,"value");if(ie!==null)return ie;if(p.type==="submit")return"Submit";if(p.type==="reset")return"Reset"}var X=getLabels(p);if(X!==null&&X.length!==0)return r.add(p),arrayFrom(X).map(function(Q){return w(Q,{isEmbeddedInLabel:!0,isReferenced:!1,recursion:!0})}).filter(function(Q){return Q.length>0}).join(" ");if(isHTMLInputElement(p)&&p.type==="image"){var te=g(p,"alt");if(te!==null)return te;var oe=g(p,"title");return oe!==null?oe:"Submit Query"}if(hasAnyConcreteRoles(p,["button"])){var re=f(p,{isEmbeddedInLabel:!1});if(re!=="")return re}return null}function w(p,m){if(r.has(p))return"";if(!h&&isHidden(p,c)&&!m.isReferenced)return r.add(p),"";var A=isElement(p)?p.getAttributeNode("aria-labelledby"):null,T=A!==null&&!r.has(A)?queryIdRefs(p,"aria-labelledby"):[];if(o==="name"&&!m.isReferenced&&T.length>0)return r.add(A),T.map(function(B){return w(B,{isEmbeddedInLabel:m.isEmbeddedInLabel,isReferenced:!0,recursion:!1})}).join(" ");var k=m.recursion&&isControl(p)&&o==="name";if(!k){var Z=(isElement(p)&&p.getAttribute("aria-label")||"").trim();if(Z!==""&&o==="name")return r.add(p),Z;if(!isMarkedPresentational(p)){var R=P(p);if(R!==null)return r.add(p),R}}if(hasAnyConcreteRoles(p,["menu"]))return r.add(p),"";if(k||m.isEmbeddedInLabel||m.isReferenced){if(hasAnyConcreteRoles(p,["combobox","listbox"])){r.add(p);var V=querySelectedOptions(p);return V.length===0?isHTMLInputElement(p)?p.value:"":arrayFrom(V).map(function(B){return w(B,{isEmbeddedInLabel:m.isEmbeddedInLabel,isReferenced:!1,recursion:!0})}).join(" ")}if(hasAbstractRole(p,"range"))return r.add(p),p.hasAttribute("aria-valuetext")?p.getAttribute("aria-valuetext"):p.hasAttribute("aria-valuenow")?p.getAttribute("aria-valuenow"):p.getAttribute("value")||"";if(hasAnyConcreteRoles(p,["textbox"]))return r.add(p),getValueOfTextbox(p)}if(allowsNameFromContent(p)||isElement(p)&&m.isReferenced||isNativeHostLanguageTextAlternativeElement(p)||isDescendantOfNativeHostLanguageTextAlternativeElement()){var j=f(p,{isEmbeddedInLabel:m.isEmbeddedInLabel});if(j!=="")return r.add(p),j}if(p.nodeType===p.TEXT_NODE)return r.add(p),p.textContent||"";if(m.recursion)return r.add(p),f(p,{isEmbeddedInLabel:m.isEmbeddedInLabel});var H=b(p);return H!==null?(r.add(p),H):(r.add(p),"")}return asFlatString(w(t,{isEmbeddedInLabel:!1,isReferenced:o==="description",recursion:!1}))}function prohibitsNaming(t){return hasAnyConcreteRoles(t,["caption","code","deletion","emphasis","generic","insertion","none","paragraph","presentation","strong","subscript","superscript"])}function computeAccessibleName(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return prohibitsNaming(t)?"":computeTextAlternative(t,e)}const INTERACTIVE_ROLES=new Set(["button","link","textbox","searchbox","combobox","listbox","checkbox","radio","switch","slider","spinbutton","menuitem","menuitemcheckbox","menuitemradio","tab","treeitem"]);function buildVNode(t,e,r,n,i,o,s=new Set){if(isNonContentElement(t)||isHidden$1(t)||n.has(t))return null;const{role:a,tokens:l}=resolveA11yInfo(t,o);let c=computeAccessibleName(t);const u=isTabbable(t),h=l.includes("cursor=pointer"),f=hasOwnPointerCursor(t)||s.has(t),g=i.has(t),b=t.tagName.toLowerCase()==="label"&&t.hasAttribute("for");if(!c.trim()){const R=t.tagName.toLowerCase();if(!(R==="select"||a==="combobox"||a==="listbox")){const j=["button","a","input","textarea","li","label"].includes(R);(u||g||h||f||j||a==="listitem"||a==="option")&&(c=collectDescendantText(t,o))}}if(!c.trim()&&(u||g||h||f||a==="button")&&(c=collectTitleLabel(t)),!c.trim()&&["tab","menuitem","option","treeitem","button"].includes(a)&&(c=collectVisiblePlainText(t)),!c.trim()&&!(getComposedChildren(t).length>0)){const V=collectDescendantText(t,o);V&&(c=V)}const P=t.tagName.toLowerCase(),w=P==="a"&&t.hasAttribute("href")||["button","input","select","textarea"].includes(P)&&!t.hasAttribute("disabled"),p=u&&!(a==="generic"&&!f),m=l.includes("disabled"),A=!m&&p||g||b||w||!m&&INTERACTIVE_ROLES.has(a)||!m&&f;let T;A&&(T=e.value,r.set(T,t),e.value++);const k=[];for(const R of getComposedChildren(t)){const V=buildVNode(R,e,r,n,i,o,s);V&&k.push(V)}const Z={role:a,name:c,tokens:l,ref:T,el:t,children:k};return hasInteractiveDescendant(Z)&&(Z.name=getOwnDeclaredName(t)),Z}function getOwnDeclaredName(t){return t.hasAttribute("aria-label")||t.hasAttribute("aria-labelledby")?computeAccessibleName(t).trim():""}function isStaticBranch(t){return t.ref===void 0&&!hasInteractiveDescendant(t)}function collectVisiblePlainText(t){return collectDescendantText(t).replace(/\s+/g," ").trim()}function getStaticDisplayText(t){const e=t.children.length>0?t.children.map(getStaticDisplayText).filter(Boolean).join(" ").replace(/\s+/g," ").trim():"",r=t.children.length===0?collectVisiblePlainText(t.el):"",n=t.name.trim(),i=[];if(n&&!isNoiseAccessibleName(n)&&i.push(n),e&&!isNoiseAccessibleName(e)){const o=n.replace(/\s+/g," ").trim(),s=e.replace(/\s+/g," ").trim();(!o||s!==o&&!o.includes(s))&&i.push(e)}return i.length===0&&r&&!isNoiseAccessibleName(r)&&i.push(r),i.join(" ").replace(/\s+/g," ").trim()}function isNoiseAccessibleName(t){const e=t.trim();return e?!!(/@font-face\b/i.test(e)||/data:(?:font|application|image)\//i.test(e)||/base64,[A-Za-z0-9+/=]{80,}/.test(e)):!1}function canOmitStaticChild(t,e,r){const n=getStaticDisplayText(t);if(!n||!e.trim())return!1;const i=e.replace(/\s+/g," ").trim(),o=n.replace(/\s+/g," ").trim();return r?o===i:i.includes(o)}function hasValue(t){return t.ref!==void 0||t.name.trim()!==""?!0:t.children.some(hasValue)}function hasInteractiveDescendant(t){return t.children.some(e=>e.ref!==void 0||hasInteractiveDescendant(e))}function findSingleRefDescendant(t){const e=[],r=n=>{n.ref!==void 0&&e.push(n),!(e.length>1)&&n.children.forEach(r)};return t.children.forEach(r),e.length===1?e[0]:null}function shouldPassThrough(t,e){return!(!e.pruneUnnamed||e.preserveRoles.includes(t.role)||t.ref!==void 0||t.name.trim()!=="")}function formatNameAttr(t){const e=t.replace(/[\r\n]+/g," ").replace(/"/g,'\\"').trim();return e?` "${e}"`:""}function serializeVNode(t,e,r){const n=hasInteractiveDescendant(t),i=r.preserveRoles.includes(t.role),o=" ".repeat(e),s=t.ref!==void 0?` #${t.ref}`:"",a=t.tokens.map(m=>m.replace(/[\r\n]+/g," ").replace(/"/g,'\\"')),l=a.length>0?` [${a.join(" ")}]`:"";if(!n&&!i){if(shouldPassThrough(t,r))return t.children.filter(A=>hasValue(A)).flatMap(A=>serializeVNode(A,e,r));let m=t.name.trim();return!m&&t.children.length>0&&(m=collectVisiblePlainText(t.el)),isNoiseAccessibleName(m)&&(m=""),[`${o}- ${t.role}${s}${l}${formatNameAttr(m)}`]}if(!n&&i){const m=getOwnDeclaredName(t.el),A=`${o}- ${t.role}${s}${l}${formatNameAttr(m)}`,T=t.children.flatMap(k=>serializeVNode(k,e+1,r));return[A,...T]}const c=getOwnDeclaredName(t.el),u=c!=="",h=t.children.filter(isStaticBranch),f=h.map(getStaticDisplayText).filter(Boolean).join(" ").replace(/\s+/g," ").trim();let g=u?c:f;if(isNoiseAccessibleName(g)&&(g=""),!u&&isNoiseAccessibleName(t.name)&&(g=f&&!isNoiseAccessibleName(f)?f:""),!(t.ref!==void 0||g!==""||i||!r.pruneUnnamed))return t.children.filter(m=>hasValue(m)).flatMap(m=>serializeVNode(m,e,r));if(t.ref!==void 0){const m=findSingleRefDescendant(t);if(m&&m.role==="generic"&&!hasInteractiveDescendant(m)&&h.length===0){const A=g.trim()||m.name.trim(),T=m.ref!==void 0?` #${m.ref}`:s;return[`${o}- ${t.role}${T}${l}${formatNameAttr(A)}`]}}const P=t.children.filter(m=>isStaticBranch(m)?!canOmitStaticChild(m,g,u):!0),w=`${o}- ${t.role}${s}${l}${formatNameAttr(g)}`,p=P.flatMap(m=>serializeVNode(m,e+1,r));return[w,...p]}const HIGHLIGHT_CONTAINER_ID="webmcpcli-highlight-container",HIGHLIGHT_CONTAINER_STYLE_ID="webmcpcli-highlight-container-style",colors=["#FF0000","#00FF00","#0000FF","#FFA500","#800080","#008080","#FF69B4","#4B0082","#FF4500","#2E8B57","#DC143C","#4682B4"],opacity=Math.floor(.3*255).toString(16).padStart(2,"0"),injectStyles$1=`
324
332
  #${HIGHLIGHT_CONTAINER_ID} {
325
333
  position: fixed;
326
334
  pointer-events: none;
@@ -347,16 +355,16 @@ ${r.pixels_above>4&&n!==-1?`... ${r.pixels_above} pixels above (${r.pages_above.
347
355
  padding: 0 2px;
348
356
  border-radius: 4px;
349
357
  }
350
- `;function isElementViewport(t){const e=t.getBoundingClientRect();return e.top>=0&&e.left>=0&&e.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&e.right<=(window.innerWidth||document.documentElement.clientWidth)}const doHighlight=(t,e=null)=>{if(!document.head.querySelector(`#${HIGHLIGHT_CONTAINER_STYLE_ID}`)){const o=document.head.appendChild(document.createElement("style"));o.id=HIGHLIGHT_CONTAINER_STYLE_ID,o.textContent=injectStyles$1,document.head.appendChild(o)}let r=document.getElementById(HIGHLIGHT_CONTAINER_ID);r?r.innerHTML="":(r=document.createElement("div"),r.id=HIGHLIGHT_CONTAINER_ID,document.body.appendChild(r));let n={x:0,y:0};if(e){const o=e.getBoundingClientRect();n.x=o.left,n.y=o.top}const i=document.createDocumentFragment();for(const[o,s]of t.entries()){if(!isElementViewport(s))continue;const l=colors[o%colors.length]+opacity,d=s.getBoundingClientRect();if(d.width===0||d.height===0)continue;const u=document.createElement("div");u.style.border=`2px solid ${l}`;const f=d.top+n.y,p=d.left+n.x;u.style.top=`${f}px`,u.style.left=`${p}px`,u.style.width=`${d.width}px`,u.style.height=`${d.height}px`;const g=document.createElement("span");g.style.backgroundColor=l,g.style.height=`${d.height-4}px`,g.style.lineHeight=`${d.height-4}px`,g.textContent=o.toString(),u.appendChild(g),i.appendChild(u)}r.appendChild(i)},highlight=(t,e=null)=>{doHighlight(t,e);const i=((a,l)=>{let d=0;return(...u)=>{const f=performance.now();if(!(f-d<l))return d=f,a(...u)}})(()=>doHighlight(t,e),16);window.addEventListener("scroll",i,!0),window.addEventListener("resize",i);const o=()=>{window.removeEventListener("scroll",i,!0),window.removeEventListener("resize",i)},s=window;(s._highlightCleanupFunctions=s._highlightCleanupFunctions||[]).push(o)},unhighlight=()=>{document.getElementById(HIGHLIGHT_CONTAINER_ID)?.remove();const t=window._highlightCleanupFunctions||[];for(const e of t)typeof e=="function"&&e();window._highlightCleanupFunctions=[]},globalRemoveListener=()=>{if(window.__registerGlobalRemoveListener)return;window.__registerGlobalRemoveListener=!0,window.addEventListener("popstate",()=>{unhighlight()}),window.addEventListener("hashchange",()=>{unhighlight()}),window.addEventListener("beforeunload",()=>{unhighlight()});const t=window.navigation;if(t&&typeof t.addEventListener=="function")t.addEventListener("navigate",()=>{unhighlight()});else{let e=window.location.href;setInterval(()=>{window.location.href!==e&&(e=window.location.href,unhighlight())},500)}},DEFAULT_OPTIONS={pruneUnnamed:!0,preserveRoles:[],exposedAttributes:[],errorSelectors:DEFAULT_ERROR_SELECTORS$1,warningSelectors:DEFAULT_WARNING_SELECTORS};function buildA11yTree(t=document.body,e=[],r=[],n){const i={...DEFAULT_OPTIONS,...n},o={value:0},s=new Map,a=new Set(e),l=new Set(r),d=[];a.add(document.getElementById(HIGHLIGHT_CONTAINER_ID));for(const f of getComposedChildren(t)){const p=buildVNode(f,o,s,a,l,i.exposedAttributes,i.errorSelectors,i.warningSelectors);p&&d.push(...serializeVNode(p,0,i))}return{yaml:"```yaml\n"+d.join(`
351
- `)+"\n```",refMap:s,interactiveCount:s.size,lines:d}}function searchA11yTree(t,e=document.body,r=[],n=[],i){const{contextLines:o=2,caseInsensitive:s=!0,maxMatches:a=20,...l}=i??{},d=Math.max(0,o),u=Math.max(1,a),{lines:f,refMap:p,yaml:g}=buildA11yTree(e,r,n,l),y=s?t.toLowerCase():t,Z=f.length,h=/^#\d+$/.test(t)?new RegExp(`\\s${t}(?:\\s|[\\[]|$)`):null,S=[];for(let w=0;w<f.length;w++){let V=!1;h?V=h.test(f[w]):V=(s?f[w].toLowerCase():f[w]).includes(y),V&&S.push(w)}const I=[];let A=!1;for(const w of S){const V=Math.max(0,w-d),F=Math.min(Z-1,w+d),j=I[I.length-1];if(j&&V<=j.end+1)j.end=Math.max(j.end,F),j.hits.push(w);else{if(I.length>=u){A=!0;break}I.push({start:V,end:F,hits:[w]})}}const O=I.map(w=>({lineNumber:w.hits[0]+1,line:f[w.hits[0]],context:Array.from({length:w.end-w.start+1},(V,F)=>({lineNumber:w.start+F+1,line:f[w.start+F]}))})),C=[`无障碍树搜索结果 — 关键词: "${t}" | 总行数: ${Z} | 命中: ${S.length} 行 | 返回分组: ${O.length}`,""];return O.length===0?C.push("(未找到匹配项)"):(O.forEach((w,V)=>{const F=I[V];C.push(`── 分组 ${V+1}(第 ${F.start+1}–${F.end+1} 行)──`),w.context.forEach(({lineNumber:j,line:H})=>{const W=F.hits.includes(j-1),te=String(j).padStart(4);C.push(W?`>>>${te} | ${H}`:` ${te} | ${H}`)}),C.push("")}),A&&C.push(`⚠️ 命中过多,已截断至前 ${u} 个分组,建议缩小搜索范围`),C.push("提示:如需操作命中元素,使用其 #N 索引;如需查看完整树,请使用 browserState。")),{text:C.join(`
352
- `),matches:O,totalLines:Z,matchCount:S.length,refMap:p,yaml:g}}function Diff(){}Diff.prototype={diff:function t(e,r){var n,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},o=i.callback;typeof i=="function"&&(o=i,i={});var s=this;function a(A){return A=s.postProcess(A,i),o?(setTimeout(function(){o(A)},0),!0):A}e=this.castInput(e,i),r=this.castInput(r,i),e=this.removeEmpty(this.tokenize(e,i)),r=this.removeEmpty(this.tokenize(r,i));var l=r.length,d=e.length,u=1,f=l+d;i.maxEditLength!=null&&(f=Math.min(f,i.maxEditLength));var p=(n=i.timeout)!==null&&n!==void 0?n:1/0,g=Date.now()+p,y=[{oldPos:-1,lastComponent:void 0}],Z=this.extractCommon(y[0],r,e,0,i);if(y[0].oldPos+1>=d&&Z+1>=l)return a(buildValues(s,y[0].lastComponent,r,e,s.useLongestToken));var x=-1/0,h=1/0;function S(){for(var A=Math.max(x,-u);A<=Math.min(h,u);A+=2){var O=void 0,C=y[A-1],w=y[A+1];C&&(y[A-1]=void 0);var V=!1;if(w){var F=w.oldPos-A;V=w&&0<=F&&F<l}var j=C&&C.oldPos+1<d;if(!V&&!j){y[A]=void 0;continue}if(!j||V&&C.oldPos<w.oldPos?O=s.addToPath(w,!0,!1,0,i):O=s.addToPath(C,!1,!0,1,i),Z=s.extractCommon(O,r,e,A,i),O.oldPos+1>=d&&Z+1>=l)return a(buildValues(s,O.lastComponent,r,e,s.useLongestToken));y[A]=O,O.oldPos+1>=d&&(h=Math.min(h,A-1)),Z+1>=l&&(x=Math.max(x,A+1))}u++}if(o)(function A(){setTimeout(function(){if(u>f||Date.now()>g)return o();S()||A()},0)})();else for(;u<=f&&Date.now()<=g;){var I=S();if(I)return I}},addToPath:function t(e,r,n,i,o){var s=e.lastComponent;return s&&!o.oneChangePerToken&&s.added===r&&s.removed===n?{oldPos:e.oldPos+i,lastComponent:{count:s.count+1,added:r,removed:n,previousComponent:s.previousComponent}}:{oldPos:e.oldPos+i,lastComponent:{count:1,added:r,removed:n,previousComponent:s}}},extractCommon:function t(e,r,n,i,o){for(var s=r.length,a=n.length,l=e.oldPos,d=l-i,u=0;d+1<s&&l+1<a&&this.equals(n[l+1],r[d+1],o);)d++,l++,u++,o.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return u&&!o.oneChangePerToken&&(e.lastComponent={count:u,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=l,d},equals:function t(e,r,n){return n.comparator?n.comparator(e,r):e===r||n.ignoreCase&&e.toLowerCase()===r.toLowerCase()},removeEmpty:function t(e){for(var r=[],n=0;n<e.length;n++)e[n]&&r.push(e[n]);return r},castInput:function t(e){return e},tokenize:function t(e){return Array.from(e)},join:function t(e){return e.join("")},postProcess:function t(e){return e}};function buildValues(t,e,r,n,i){for(var o=[],s;e;)o.push(e),s=e.previousComponent,delete e.previousComponent,e=s;o.reverse();for(var a=0,l=o.length,d=0,u=0;a<l;a++){var f=o[a];if(f.removed)f.value=t.join(n.slice(u,u+f.count)),u+=f.count;else{if(!f.added&&i){var p=r.slice(d,d+f.count);p=p.map(function(g,y){var Z=n[u+y];return Z.length>g.length?Z:g}),f.value=t.join(p)}else f.value=t.join(r.slice(d,d+f.count));d+=f.count,f.added||(u+=f.count)}}return o}function longestCommonPrefix(t,e){var r;for(r=0;r<t.length&&r<e.length;r++)if(t[r]!=e[r])return t.slice(0,r);return t.slice(0,r)}function longestCommonSuffix(t,e){var r;if(!t||!e||t[t.length-1]!=e[e.length-1])return"";for(r=0;r<t.length&&r<e.length;r++)if(t[t.length-(r+1)]!=e[e.length-(r+1)])return t.slice(-r);return t.slice(-r)}function replacePrefix(t,e,r){if(t.slice(0,e.length)!=e)throw Error("string ".concat(JSON.stringify(t)," doesn't start with prefix ").concat(JSON.stringify(e),"; this is a bug"));return r+t.slice(e.length)}function replaceSuffix(t,e,r){if(!e)return t+r;if(t.slice(-e.length)!=e)throw Error("string ".concat(JSON.stringify(t)," doesn't end with suffix ").concat(JSON.stringify(e),"; this is a bug"));return t.slice(0,-e.length)+r}function removePrefix(t,e){return replacePrefix(t,e,"")}function removeSuffix(t,e){return replaceSuffix(t,e,"")}function maximumOverlap(t,e){return e.slice(0,overlapCount(t,e))}function overlapCount(t,e){var r=0;t.length>e.length&&(r=t.length-e.length);var n=e.length;t.length<e.length&&(n=t.length);var i=Array(n),o=0;i[0]=0;for(var s=1;s<n;s++){for(e[s]==e[o]?i[s]=i[o]:i[s]=o;o>0&&e[s]!=e[o];)o=i[o];e[s]==e[o]&&o++}o=0;for(var a=r;a<t.length;a++){for(;o>0&&t[a]!=e[o];)o=i[o];t[a]==e[o]&&o++}return o}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(t,e,r){return r.ignoreCase&&(t=t.toLowerCase(),e=e.toLowerCase()),t.trim()===e.trim()},wordDiff.tokenize=function(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r;if(e.intlSegmenter){if(e.intlSegmenter.resolvedOptions().granularity!="word")throw new Error('The segmenter passed must have a granularity of "word"');r=Array.from(e.intlSegmenter.segment(t),function(o){return o.segment})}else r=t.match(tokenizeIncludingWhitespace)||[];var n=[],i=null;return r.forEach(function(o){/\s/.test(o)?i==null?n.push(o):n.push(n.pop()+o):/\s/.test(i)?n[n.length-1]==i?n.push(n.pop()+o):n.push(i+o):n.push(o),i=o}),n},wordDiff.join=function(t){return t.map(function(e,r){return r==0?e:e.replace(/^\s+/,"")}).join("")},wordDiff.postProcess=function(t,e){if(!t||e.oneChangePerToken)return t;var r=null,n=null,i=null;return t.forEach(function(o){o.added?n=o:o.removed?i=o:((n||i)&&dedupeWhitespaceInChangeObjects(r,i,n,o),r=o,n=null,i=null)}),(n||i)&&dedupeWhitespaceInChangeObjects(r,i,n,null),t};function dedupeWhitespaceInChangeObjects(t,e,r,n){if(e&&r){var i=e.value.match(/^\s*/)[0],o=e.value.match(/\s*$/)[0],s=r.value.match(/^\s*/)[0],a=r.value.match(/\s*$/)[0];if(t){var l=longestCommonPrefix(i,s);t.value=replaceSuffix(t.value,s,l),e.value=removePrefix(e.value,l),r.value=removePrefix(r.value,l)}if(n){var d=longestCommonSuffix(o,a);n.value=replacePrefix(n.value,a,d),e.value=removeSuffix(e.value,d),r.value=removeSuffix(r.value,d)}}else if(r)t&&(r.value=r.value.replace(/^\s*/,"")),n&&(n.value=n.value.replace(/^\s*/,""));else if(t&&n){var u=n.value.match(/^\s*/)[0],f=e.value.match(/^\s*/)[0],p=e.value.match(/\s*$/)[0],g=longestCommonPrefix(u,f);e.value=removePrefix(e.value,g);var y=longestCommonSuffix(removePrefix(u,g),p);e.value=removeSuffix(e.value,y),n.value=replacePrefix(n.value,u,y),t.value=replaceSuffix(t.value,u,u.slice(0,u.length-y.length))}else if(n){var Z=n.value.match(/^\s*/)[0],x=e.value.match(/\s*$/)[0],h=maximumOverlap(x,Z);e.value=removeSuffix(e.value,h)}else if(t){var S=t.value.match(/\s*$/)[0],I=e.value.match(/^\s*/)[0],A=maximumOverlap(S,I);e.value=removePrefix(e.value,A)}}var wordWithSpaceDiff=new Diff;wordWithSpaceDiff.tokenize=function(t){var e=new RegExp("(\\r?\\n)|[".concat(extendedWordChars,"]+|[^\\S\\n\\r]+|[^").concat(extendedWordChars,"]"),"ug");return t.match(e)||[]};var lineDiff=new Diff;lineDiff.tokenize=function(t,e){e.stripTrailingCr&&(t=t.replace(/\r\n/g,`
358
+ `,MAX_ICON_FALLBACK_SIZE=48;function resolveHighlightRect(t){const e=t.getBoundingClientRect();if(e.width>0&&e.height>0)return{top:e.top,left:e.left,width:e.width,height:e.height};let r=t.parentElement;for(let n=0;n<3&&r;n++){const i=r.getBoundingClientRect();if(i.width>0&&i.height>0&&i.width<=MAX_ICON_FALLBACK_SIZE&&i.height<=MAX_ICON_FALLBACK_SIZE)return{top:i.top,left:i.left,width:i.width,height:i.height};r=r.parentElement}if(e.width>0||e.height>0)try{const n=parseFloat(getComputedStyle(t).fontSize)||16,i=e.width>0?e.width:n,o=e.height>0?e.height:n;return{top:e.height>0?e.top:e.top-(o-e.height)/2,left:e.width>0?e.left:e.left-(i-e.width)/2,width:i,height:o}}catch{}return null}function isRectInViewport(t){const e=window.innerHeight||document.documentElement.clientHeight,r=window.innerWidth||document.documentElement.clientWidth;return t.top<e&&t.top+t.height>0&&t.left<r&&t.left+t.width>0}const doHighlight=(t,e=null)=>{if(!document.head.querySelector(`#${HIGHLIGHT_CONTAINER_STYLE_ID}`)){const o=document.head.appendChild(document.createElement("style"));o.id=HIGHLIGHT_CONTAINER_STYLE_ID,o.textContent=injectStyles$1,document.head.appendChild(o)}let r=document.getElementById(HIGHLIGHT_CONTAINER_ID);r?r.innerHTML="":(r=document.createElement("div"),r.id=HIGHLIGHT_CONTAINER_ID,document.body.appendChild(r));let n={x:0,y:0};if(e){const o=e.getBoundingClientRect();n.x=o.left,n.y=o.top}const i=document.createDocumentFragment();for(const[o,s]of t.entries()){const a=resolveHighlightRect(s);if(!a)continue;const l=a.top+n.y,c=a.left+n.x,u={top:l,left:c,width:a.width,height:a.height};if(!isRectInViewport(u))continue;const f=colors[o%colors.length]+opacity,g=document.createElement("div");g.style.border=`2px solid ${f}`,g.dataset.refIndex=String(o),g.style.top=`${l}px`,g.style.left=`${c}px`,g.style.width=`${a.width}px`,g.style.height=`${a.height}px`;const b=document.createElement("span");b.style.backgroundColor=f,b.style.height=`${Math.max(a.height-4,0)}px`,b.style.lineHeight=`${Math.max(a.height-4,0)}px`,b.textContent=o.toString(),g.appendChild(b),i.appendChild(g)}r.appendChild(i)},highlight=(t,e=null)=>{doHighlight(t,e);const i=((a,l)=>{let c=0;return(...u)=>{const h=performance.now();if(!(h-c<l))return c=h,a(...u)}})(()=>doHighlight(t,e),16);window.addEventListener("scroll",i,!0),window.addEventListener("resize",i);const o=()=>{window.removeEventListener("scroll",i,!0),window.removeEventListener("resize",i)},s=window;(s._highlightCleanupFunctions=s._highlightCleanupFunctions||[]).push(o)},unhighlight=()=>{document.getElementById(HIGHLIGHT_CONTAINER_ID)?.remove();const t=window._highlightCleanupFunctions||[];for(const e of t)typeof e=="function"&&e();window._highlightCleanupFunctions=[]},globalRemoveListener=()=>{if(window.__registerGlobalRemoveListener)return;window.__registerGlobalRemoveListener=!0,window.addEventListener("popstate",()=>{unhighlight()}),window.addEventListener("hashchange",()=>{unhighlight()}),window.addEventListener("beforeunload",()=>{unhighlight()});const t=window.navigation;if(t&&typeof t.addEventListener=="function")t.addEventListener("navigate",()=>{unhighlight()});else{let e=window.location.href;setInterval(()=>{window.location.href!==e&&(e=window.location.href,unhighlight())},500)}};function resolveElementList(t,e){const r=new Set;for(const n of t)if(typeof n=="string")try{for(const i of deepQuerySelectorAll(n,e))r.add(i)}catch{}else n&&r.add(n);return r}function buildA11yTree(t=document.body,e){const{pruneUnnamed:r=!0,preserveRoles:n=[],...i}=e??{},o=ensureResolvedA11yConfig(i),s={pruneUnnamed:r,preserveRoles:n},a={value:0},l=new Map,c=resolveElementList(o.blacklist,t),u=resolveElementList(o.whitelist,t),h=[],f=document.getElementById(HIGHLIGHT_CONTAINER_ID);f&&c.add(f);const g=collectHoverPointerElements(t);for(const P of getComposedChildren(t)){const w=buildVNode(P,a,l,c,u,o,g);w&&h.push(...serializeVNode(w,0,s))}return{yaml:"```yaml\n"+h.join(`
359
+ `)+"\n```",refMap:l,interactiveCount:l.size,lines:h}}function searchA11yTree(t,e=document.body,r){const{contextLines:n=2,caseInsensitive:i=!0,maxMatches:o=20,...s}=r??{},a=Math.max(0,n),l=Math.max(1,o),{lines:c,refMap:u,yaml:h}=buildA11yTree(e,s),f=i?t.toLowerCase():t,g=c.length,P=/^#\d+$/.test(t)?new RegExp(`\\s${t}(?:\\s|[\\[]|$)`):null,w=[];for(let k=0;k<c.length;k++){let Z=!1;P?Z=P.test(c[k]):Z=(i?c[k].toLowerCase():c[k]).includes(f),Z&&w.push(k)}const p=[];let m=!1;for(const k of w){const Z=Math.max(0,k-a),R=Math.min(g-1,k+a),V=p[p.length-1];if(V&&Z<=V.end+1)V.end=Math.max(V.end,R),V.hits.push(k);else{if(p.length>=l){m=!0;break}p.push({start:Z,end:R,hits:[k]})}}const A=p.map(k=>({lineNumber:k.hits[0]+1,line:c[k.hits[0]],context:Array.from({length:k.end-k.start+1},(Z,R)=>({lineNumber:k.start+R+1,line:c[k.start+R]}))})),T=[`无障碍树搜索结果 — 关键词: "${t}" | 总行数: ${g} | 命中: ${w.length} 行 | 返回分组: ${A.length}`,""];return A.length===0?T.push("(未找到匹配项)"):(A.forEach((k,Z)=>{const R=p[Z];T.push(`── 分组 ${Z+1}(第 ${R.start+1}–${R.end+1} 行)──`),k.context.forEach(({lineNumber:V,line:j})=>{const H=R.hits.includes(V-1),B=String(V).padStart(4);T.push(H?`>>>${B} | ${j}`:` ${B} | ${j}`)}),T.push("")}),m&&T.push(`⚠️ 命中过多,已截断至前 ${l} 个分组,建议缩小搜索范围`),T.push("提示:如需操作命中元素,使用其 #N 索引;如需查看完整树,请使用 browserState。")),{text:T.join(`
360
+ `),matches:A,totalLines:g,matchCount:w.length,refMap:u,yaml:h}}function Diff(){}Diff.prototype={diff:function t(e,r){var n,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},o=i.callback;typeof i=="function"&&(o=i,i={});var s=this;function a(T){return T=s.postProcess(T,i),o?(setTimeout(function(){o(T)},0),!0):T}e=this.castInput(e,i),r=this.castInput(r,i),e=this.removeEmpty(this.tokenize(e,i)),r=this.removeEmpty(this.tokenize(r,i));var l=r.length,c=e.length,u=1,h=l+c;i.maxEditLength!=null&&(h=Math.min(h,i.maxEditLength));var f=(n=i.timeout)!==null&&n!==void 0?n:1/0,g=Date.now()+f,b=[{oldPos:-1,lastComponent:void 0}],P=this.extractCommon(b[0],r,e,0,i);if(b[0].oldPos+1>=c&&P+1>=l)return a(buildValues(s,b[0].lastComponent,r,e,s.useLongestToken));var w=-1/0,p=1/0;function m(){for(var T=Math.max(w,-u);T<=Math.min(p,u);T+=2){var k=void 0,Z=b[T-1],R=b[T+1];Z&&(b[T-1]=void 0);var V=!1;if(R){var j=R.oldPos-T;V=R&&0<=j&&j<l}var H=Z&&Z.oldPos+1<c;if(!V&&!H){b[T]=void 0;continue}if(!H||V&&Z.oldPos<R.oldPos?k=s.addToPath(R,!0,!1,0,i):k=s.addToPath(Z,!1,!0,1,i),P=s.extractCommon(k,r,e,T,i),k.oldPos+1>=c&&P+1>=l)return a(buildValues(s,k.lastComponent,r,e,s.useLongestToken));b[T]=k,k.oldPos+1>=c&&(p=Math.min(p,T-1)),P+1>=l&&(w=Math.max(w,T+1))}u++}if(o)(function T(){setTimeout(function(){if(u>h||Date.now()>g)return o();m()||T()},0)})();else for(;u<=h&&Date.now()<=g;){var A=m();if(A)return A}},addToPath:function t(e,r,n,i,o){var s=e.lastComponent;return s&&!o.oneChangePerToken&&s.added===r&&s.removed===n?{oldPos:e.oldPos+i,lastComponent:{count:s.count+1,added:r,removed:n,previousComponent:s.previousComponent}}:{oldPos:e.oldPos+i,lastComponent:{count:1,added:r,removed:n,previousComponent:s}}},extractCommon:function t(e,r,n,i,o){for(var s=r.length,a=n.length,l=e.oldPos,c=l-i,u=0;c+1<s&&l+1<a&&this.equals(n[l+1],r[c+1],o);)c++,l++,u++,o.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return u&&!o.oneChangePerToken&&(e.lastComponent={count:u,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=l,c},equals:function t(e,r,n){return n.comparator?n.comparator(e,r):e===r||n.ignoreCase&&e.toLowerCase()===r.toLowerCase()},removeEmpty:function t(e){for(var r=[],n=0;n<e.length;n++)e[n]&&r.push(e[n]);return r},castInput:function t(e){return e},tokenize:function t(e){return Array.from(e)},join:function t(e){return e.join("")},postProcess:function t(e){return e}};function buildValues(t,e,r,n,i){for(var o=[],s;e;)o.push(e),s=e.previousComponent,delete e.previousComponent,e=s;o.reverse();for(var a=0,l=o.length,c=0,u=0;a<l;a++){var h=o[a];if(h.removed)h.value=t.join(n.slice(u,u+h.count)),u+=h.count;else{if(!h.added&&i){var f=r.slice(c,c+h.count);f=f.map(function(g,b){var P=n[u+b];return P.length>g.length?P:g}),h.value=t.join(f)}else h.value=t.join(r.slice(c,c+h.count));c+=h.count,h.added||(u+=h.count)}}return o}function longestCommonPrefix(t,e){var r;for(r=0;r<t.length&&r<e.length;r++)if(t[r]!=e[r])return t.slice(0,r);return t.slice(0,r)}function longestCommonSuffix(t,e){var r;if(!t||!e||t[t.length-1]!=e[e.length-1])return"";for(r=0;r<t.length&&r<e.length;r++)if(t[t.length-(r+1)]!=e[e.length-(r+1)])return t.slice(-r);return t.slice(-r)}function replacePrefix(t,e,r){if(t.slice(0,e.length)!=e)throw Error("string ".concat(JSON.stringify(t)," doesn't start with prefix ").concat(JSON.stringify(e),"; this is a bug"));return r+t.slice(e.length)}function replaceSuffix(t,e,r){if(!e)return t+r;if(t.slice(-e.length)!=e)throw Error("string ".concat(JSON.stringify(t)," doesn't end with suffix ").concat(JSON.stringify(e),"; this is a bug"));return t.slice(0,-e.length)+r}function removePrefix(t,e){return replacePrefix(t,e,"")}function removeSuffix(t,e){return replaceSuffix(t,e,"")}function maximumOverlap(t,e){return e.slice(0,overlapCount(t,e))}function overlapCount(t,e){var r=0;t.length>e.length&&(r=t.length-e.length);var n=e.length;t.length<e.length&&(n=t.length);var i=Array(n),o=0;i[0]=0;for(var s=1;s<n;s++){for(e[s]==e[o]?i[s]=i[o]:i[s]=o;o>0&&e[s]!=e[o];)o=i[o];e[s]==e[o]&&o++}o=0;for(var a=r;a<t.length;a++){for(;o>0&&t[a]!=e[o];)o=i[o];t[a]==e[o]&&o++}return o}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(t,e,r){return r.ignoreCase&&(t=t.toLowerCase(),e=e.toLowerCase()),t.trim()===e.trim()},wordDiff.tokenize=function(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r;if(e.intlSegmenter){if(e.intlSegmenter.resolvedOptions().granularity!="word")throw new Error('The segmenter passed must have a granularity of "word"');r=Array.from(e.intlSegmenter.segment(t),function(o){return o.segment})}else r=t.match(tokenizeIncludingWhitespace)||[];var n=[],i=null;return r.forEach(function(o){/\s/.test(o)?i==null?n.push(o):n.push(n.pop()+o):/\s/.test(i)?n[n.length-1]==i?n.push(n.pop()+o):n.push(i+o):n.push(o),i=o}),n},wordDiff.join=function(t){return t.map(function(e,r){return r==0?e:e.replace(/^\s+/,"")}).join("")},wordDiff.postProcess=function(t,e){if(!t||e.oneChangePerToken)return t;var r=null,n=null,i=null;return t.forEach(function(o){o.added?n=o:o.removed?i=o:((n||i)&&dedupeWhitespaceInChangeObjects(r,i,n,o),r=o,n=null,i=null)}),(n||i)&&dedupeWhitespaceInChangeObjects(r,i,n,null),t};function dedupeWhitespaceInChangeObjects(t,e,r,n){if(e&&r){var i=e.value.match(/^\s*/)[0],o=e.value.match(/\s*$/)[0],s=r.value.match(/^\s*/)[0],a=r.value.match(/\s*$/)[0];if(t){var l=longestCommonPrefix(i,s);t.value=replaceSuffix(t.value,s,l),e.value=removePrefix(e.value,l),r.value=removePrefix(r.value,l)}if(n){var c=longestCommonSuffix(o,a);n.value=replacePrefix(n.value,a,c),e.value=removeSuffix(e.value,c),r.value=removeSuffix(r.value,c)}}else if(r)t&&(r.value=r.value.replace(/^\s*/,"")),n&&(n.value=n.value.replace(/^\s*/,""));else if(t&&n){var u=n.value.match(/^\s*/)[0],h=e.value.match(/^\s*/)[0],f=e.value.match(/\s*$/)[0],g=longestCommonPrefix(u,h);e.value=removePrefix(e.value,g);var b=longestCommonSuffix(removePrefix(u,g),f);e.value=removeSuffix(e.value,b),n.value=replacePrefix(n.value,u,b),t.value=replaceSuffix(t.value,u,u.slice(0,u.length-b.length))}else if(n){var P=n.value.match(/^\s*/)[0],w=e.value.match(/\s*$/)[0],p=maximumOverlap(w,P);e.value=removeSuffix(e.value,p)}else if(t){var m=t.value.match(/\s*$/)[0],A=e.value.match(/^\s*/)[0],T=maximumOverlap(m,A);e.value=removePrefix(e.value,T)}}var wordWithSpaceDiff=new Diff;wordWithSpaceDiff.tokenize=function(t){var e=new RegExp("(\\r?\\n)|[".concat(extendedWordChars,"]+|[^\\S\\n\\r]+|[^").concat(extendedWordChars,"]"),"ug");return t.match(e)||[]};var lineDiff=new Diff;lineDiff.tokenize=function(t,e){e.stripTrailingCr&&(t=t.replace(/\r\n/g,`
353
361
  `));var r=[],n=t.split(/(\n|\r\n)/);n[n.length-1]||n.pop();for(var i=0;i<n.length;i++){var o=n[i];i%2&&!e.newlineIsToken?r[r.length-1]+=o:r.push(o)}return r},lineDiff.equals=function(t,e,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
354
362
  `))&&(t=t.trim()),(!r.newlineIsToken||!e.includes(`
355
363
  `))&&(e=e.trim())):r.ignoreNewlineAtEof&&!r.newlineIsToken&&(t.endsWith(`
356
364
  `)&&(t=t.slice(0,-1)),e.endsWith(`
357
- `)&&(e=e.slice(0,-1))),Diff.prototype.equals.call(this,t,e,r)};function diffLines(t,e,r){return lineDiff.diff(t,e,r)}var sentenceDiff=new Diff;sentenceDiff.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};var cssDiff=new Diff;cssDiff.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};function _typeof(t){"@babel/helpers - typeof";return _typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof(t)}var jsonDiff=new Diff;jsonDiff.useLongestToken=!0,jsonDiff.tokenize=lineDiff.tokenize,jsonDiff.castInput=function(t,e){var r=e.undefinedReplacement,n=e.stringifyReplacer,i=n===void 0?function(o,s){return typeof s>"u"?r:s}:n;return typeof t=="string"?t:JSON.stringify(canonicalize(t,null,null,i),i," ")},jsonDiff.equals=function(t,e,r){return Diff.prototype.equals.call(jsonDiff,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"),r)};function canonicalize(t,e,r,n,i){e=e||[],r=r||[],n&&(t=n(i,t));var o;for(o=0;o<e.length;o+=1)if(e[o]===t)return r[o];var s;if(Object.prototype.toString.call(t)==="[object Array]"){for(e.push(t),s=new Array(t.length),r.push(s),o=0;o<t.length;o+=1)s[o]=canonicalize(t[o],e,r,n,i);return e.pop(),r.pop(),s}if(t&&t.toJSON&&(t=t.toJSON()),_typeof(t)==="object"&&t!==null){e.push(t),s={},r.push(s);var a=[],l;for(l in t)Object.prototype.hasOwnProperty.call(t,l)&&a.push(l);for(a.sort(),o=0;o<a.length;o+=1)l=a[o],s[l]=canonicalize(t[l],e,r,n,l);e.pop(),r.pop()}else s=t;return s}var arrayDiff=new Diff;arrayDiff.tokenize=function(t){return t.slice()},arrayDiff.join=arrayDiff.removeEmpty=function(t){return t};class PageStateCache{constructor(){this.prev=null}isFullRefresh(e){return!this.prev||this.prev.url!==e}update(e,r){const n=this.isFullRefresh(e),i=this.prev?.url??"";let o=0,s=0,a="";if(!n&&this.prev){const l=diffLines(this.prev.yaml,r),d=[];l.forEach(u=>{if(!u.added&&!u.removed)return;const f=u.value.split(`
358
- `).filter(Boolean);u.added?(o+=f.length,f.forEach(p=>d.push(`+ ${p}`))):(s+=f.length,f.forEach(p=>d.push(`- ${p}`)))}),a=d.join(`
359
- `)}return this.prev={url:e,yaml:r},{isFullRefresh:n,prevUrl:i,addedLines:o,removedLines:s,diffText:a}}invalidate(){this.prev=null}}function computeBorderGeometry(t,e,r,n){const i=Math.max(1,Math.min(t,e)),o=Math.min(r,20),a=Math.min(o+n,i),l=Math.min(a,Math.floor(t/2)),d=Math.min(a,Math.floor(e/2)),u=v=>v/t*2-1,f=v=>v/e*2-1,p=0,g=t,y=0,Z=e,x=l,h=t-l,S=d,I=e-d,A=u(p),O=u(g),C=f(y),w=f(Z),V=u(x),F=u(h),j=f(S),H=f(I),W=0,te=0,X=1,re=1,oe=l/t,ne=1-l/t,Q=d/e,K=1-d/e,de=new Float32Array([A,C,O,C,A,j,A,j,O,C,O,j,A,H,O,H,A,w,A,w,O,H,O,w,A,j,V,j,A,H,A,H,V,j,V,H,F,j,O,j,F,H,F,H,O,j,O,H]),c=new Float32Array([W,te,X,te,W,Q,W,Q,X,te,X,Q,W,K,X,K,W,re,W,re,X,K,X,re,W,Q,oe,Q,W,K,W,K,oe,Q,oe,K,ne,Q,X,Q,ne,K,ne,K,X,Q,X,K]);return{positions:de,uvs:c}}function compileShader(t,e,r){const n=t.createShader(e);if(!n)throw new Error("Failed to create shader");if(t.shaderSource(n,r),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS)){const i=t.getShaderInfoLog(n)||"Unknown shader error";throw t.deleteShader(n),new Error(i)}return n}function createProgram(t,e,r){const n=compileShader(t,t.VERTEX_SHADER,e),i=compileShader(t,t.FRAGMENT_SHADER,r),o=t.createProgram();if(!o)throw new Error("Failed to create program");if(t.attachShader(o,n),t.attachShader(o,i),t.linkProgram(o),!t.getProgramParameter(o,t.LINK_STATUS)){const s=t.getProgramInfoLog(o)||"Unknown link error";throw t.deleteProgram(o),t.deleteShader(n),t.deleteShader(i),new Error(s)}return t.deleteShader(n),t.deleteShader(i),o}const fragmentShaderSource=`#version 300 es
365
+ `)&&(e=e.slice(0,-1))),Diff.prototype.equals.call(this,t,e,r)};function diffLines(t,e,r){return lineDiff.diff(t,e,r)}var sentenceDiff=new Diff;sentenceDiff.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};var cssDiff=new Diff;cssDiff.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};function _typeof(t){"@babel/helpers - typeof";return _typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof(t)}var jsonDiff=new Diff;jsonDiff.useLongestToken=!0,jsonDiff.tokenize=lineDiff.tokenize,jsonDiff.castInput=function(t,e){var r=e.undefinedReplacement,n=e.stringifyReplacer,i=n===void 0?function(o,s){return typeof s>"u"?r:s}:n;return typeof t=="string"?t:JSON.stringify(canonicalize(t,null,null,i),i," ")},jsonDiff.equals=function(t,e,r){return Diff.prototype.equals.call(jsonDiff,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"),r)};function canonicalize(t,e,r,n,i){e=e||[],r=r||[],n&&(t=n(i,t));var o;for(o=0;o<e.length;o+=1)if(e[o]===t)return r[o];var s;if(Object.prototype.toString.call(t)==="[object Array]"){for(e.push(t),s=new Array(t.length),r.push(s),o=0;o<t.length;o+=1)s[o]=canonicalize(t[o],e,r,n,i);return e.pop(),r.pop(),s}if(t&&t.toJSON&&(t=t.toJSON()),_typeof(t)==="object"&&t!==null){e.push(t),s={},r.push(s);var a=[],l;for(l in t)Object.prototype.hasOwnProperty.call(t,l)&&a.push(l);for(a.sort(),o=0;o<a.length;o+=1)l=a[o],s[l]=canonicalize(t[l],e,r,n,l);e.pop(),r.pop()}else s=t;return s}var arrayDiff=new Diff;arrayDiff.tokenize=function(t){return t.slice()},arrayDiff.join=arrayDiff.removeEmpty=function(t){return t};class PageStateCache{constructor(){this.prev=null}isFullRefresh(e){return!this.prev||this.prev.url!==e}update(e,r){const n=this.isFullRefresh(e),i=this.prev?.url??"";let o=0,s=0,a="";if(!n&&this.prev){const l=diffLines(this.prev.yaml,r),c=[];l.forEach(u=>{if(!u.added&&!u.removed)return;const h=u.value.split(`
366
+ `).filter(Boolean);u.added?(o+=h.length,h.forEach(f=>c.push(`+ ${f}`))):(s+=h.length,h.forEach(f=>c.push(`- ${f}`)))}),a=c.join(`
367
+ `)}return this.prev={url:e,yaml:r},{isFullRefresh:n,prevUrl:i,addedLines:o,removedLines:s,diffText:a}}invalidate(){this.prev=null}}function computeBorderGeometry(t,e,r,n){const i=Math.max(1,Math.min(t,e)),o=Math.min(r,20),a=Math.min(o+n,i),l=Math.min(a,Math.floor(t/2)),c=Math.min(a,Math.floor(e/2)),u=x=>x/t*2-1,h=x=>x/e*2-1,f=0,g=t,b=0,P=e,w=l,p=t-l,m=c,A=e-c,T=u(f),k=u(g),Z=h(b),R=h(P),V=u(w),j=u(p),H=h(m),B=h(A),G=0,ie=0,X=1,te=1,oe=l/t,re=1-l/t,Q=c/e,K=1-c/e,ce=new Float32Array([T,Z,k,Z,T,H,T,H,k,Z,k,H,T,B,k,B,T,R,T,R,k,B,k,R,T,H,V,H,T,B,T,B,V,H,V,B,j,H,k,H,j,B,j,B,k,H,k,B]),d=new Float32Array([G,ie,X,ie,G,Q,G,Q,X,ie,X,Q,G,K,X,K,G,te,G,te,X,K,X,te,G,Q,oe,Q,G,K,G,K,oe,Q,oe,K,re,Q,X,Q,re,K,re,K,X,Q,X,K]);return{positions:ce,uvs:d}}function compileShader(t,e,r){const n=t.createShader(e);if(!n)throw new Error("Failed to create shader");if(t.shaderSource(n,r),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS)){const i=t.getShaderInfoLog(n)||"Unknown shader error";throw t.deleteShader(n),new Error(i)}return n}function createProgram(t,e,r){const n=compileShader(t,t.VERTEX_SHADER,e),i=compileShader(t,t.FRAGMENT_SHADER,r),o=t.createProgram();if(!o)throw new Error("Failed to create program");if(t.attachShader(o,n),t.attachShader(o,i),t.linkProgram(o),!t.getProgramParameter(o,t.LINK_STATUS)){const s=t.getProgramInfoLog(o)||"Unknown link error";throw t.deleteProgram(o),t.deleteShader(n),t.deleteShader(i),new Error(s)}return t.deleteShader(n),t.deleteShader(i),o}const fragmentShaderSource=`#version 300 es
360
368
  precision lowp float;
361
369
  in vec2 vUV;
362
370
  out vec4 outColor;
@@ -466,7 +474,7 @@ out vec2 vUV;
466
474
  void main() {
467
475
  vUV = aUV;
468
476
  gl_Position = vec4(aPosition, 0.0, 1.0);
469
- }`;const DEFAULT_COLORS=["rgb(57, 182, 255)","rgb(189, 69, 251)","rgb(255, 87, 51)","rgb(255, 214, 0)"];function parseColor(t){const e=t.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);if(!e)throw new Error(`Invalid color format: ${t}`);const[,r,n,i]=e;return[parseInt(r)/255,parseInt(n)/255,parseInt(i)/255]}class Motion{element;canvas;options;running=!1;disposed=!1;startTime=0;lastTime=0;rafId=null;glr;observer;constructor(e={}){this.options={width:e.width??600,height:e.height??600,ratio:e.ratio??window.devicePixelRatio??1,borderWidth:e.borderWidth??8,glowWidth:e.glowWidth??200,borderRadius:e.borderRadius??8,mode:e.mode??"light",...e},this.canvas=document.createElement("canvas"),this.options.classNames&&(this.canvas.className=this.options.classNames),this.options.styles&&Object.assign(this.canvas.style,this.options.styles),this.canvas.style.display="block",this.canvas.style.transformOrigin="center",this.canvas.style.pointerEvents="none",this.element=this.canvas,this.setupGL(),this.options.skipGreeting||this.greet()}start(){if(this.disposed)throw 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 e=()=>{if(!this.running||!this.glr)return;this.rafId=requestAnimationFrame(e);const r=performance.now();if(r-this.lastTime<1e3/32)return;this.lastTime=r;const i=(r-this.startTime)*.001;this.render(i)};this.rafId=requestAnimationFrame(e)}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:e,vao:r,positionBuffer:n,uvBuffer:i,program:o}=this.glr;r&&e.deleteVertexArray(r),n&&e.deleteBuffer(n),i&&e.deleteBuffer(i),e.deleteProgram(o),this.observer&&this.observer.disconnect(),this.canvas.remove()}resize(e,r,n){if(this.disposed)throw new Error("Motion instance has been disposed.");if(this.options.width=e,this.options.height=r,n&&(this.options.ratio=n),!this.running)return;const{gl:i,program:o,vao:s,positionBuffer:a,uvBuffer:l,uResolution:d}=this.glr,u=n??this.options.ratio??window.devicePixelRatio??1,f=Math.max(1,Math.floor(e*u)),p=Math.max(1,Math.floor(r*u));this.canvas.style.width=`${e}px`,this.canvas.style.height=`${r}px`,(this.canvas.width!==f||this.canvas.height!==p)&&(this.canvas.width=f,this.canvas.height=p),i.viewport(0,0,this.canvas.width,this.canvas.height),this.checkGLError(i,"resize: after viewport setup");const{positions:g,uvs:y}=computeBorderGeometry(this.canvas.width,this.canvas.height,this.options.borderWidth*u,this.options.glowWidth*u);i.bindVertexArray(s),i.bindBuffer(i.ARRAY_BUFFER,a),i.bufferData(i.ARRAY_BUFFER,g,i.STATIC_DRAW);const Z=i.getAttribLocation(o,"aPosition");i.enableVertexAttribArray(Z),i.vertexAttribPointer(Z,2,i.FLOAT,!1,0,0),this.checkGLError(i,"resize: after position buffer update"),i.bindBuffer(i.ARRAY_BUFFER,l),i.bufferData(i.ARRAY_BUFFER,y,i.STATIC_DRAW);const x=i.getAttribLocation(o,"aUV");i.enableVertexAttribArray(x),i.vertexAttribPointer(x,2,i.FLOAT,!1,0,0),this.checkGLError(i,"resize: after UV buffer update"),i.useProgram(o),i.uniform2f(d,this.canvas.width,this.canvas.height),i.uniform1f(this.glr.uBorderWidth,this.options.borderWidth*u),i.uniform1f(this.glr.uGlowWidth,this.options.glowWidth*u),i.uniform1f(this.glr.uBorderRadius,this.options.borderRadius*u),this.checkGLError(i,"resize: after uniform updates");const h=performance.now();this.lastTime=h;const S=(h-this.startTime)*.001;this.render(S)}autoResize(e){this.observer&&this.observer.disconnect(),this.observer=new ResizeObserver(()=>{const r=e.getBoundingClientRect();this.resize(r.width,r.height)}),this.observer.observe(e)}fadeIn(){if(this.disposed)throw new Error("Motion instance has been disposed.");return new Promise((e,r)=>{const n=this.canvas.animate([{opacity:0,transform:"scale(1.2)"},{opacity:1,transform:"scale(1)"}],{duration:300,easing:"ease-out",fill:"forwards"});n.onfinish=()=>e(),n.oncancel=()=>r("canceled")})}fadeOut(){if(this.disposed)throw new Error("Motion instance has been disposed.");return new Promise((e,r)=>{const n=this.canvas.animate([{opacity:1,transform:"scale(1)"},{opacity:0,transform:"scale(1.2)"}],{duration:300,easing:"ease-in",fill:"forwards"});n.onfinish=()=>e(),n.oncancel=()=>r("canceled")})}checkGLError(e,r){let n=e.getError();if(n!==e.NO_ERROR){for(console.group(`🔴 WebGL Error in ${r}`);n!==e.NO_ERROR;){const i=this.getGLErrorName(e,n);console.error(`${i} (0x${n.toString(16)})`),n=e.getError()}console.groupEnd()}}getGLErrorName(e,r){switch(r){case e.INVALID_ENUM:return"INVALID_ENUM";case e.INVALID_VALUE:return"INVALID_VALUE";case e.INVALID_OPERATION:return"INVALID_OPERATION";case e.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case e.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case e.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return"UNKNOWN_ERROR"}}setupGL(){const e=this.canvas.getContext("webgl2",{antialias:!1,alpha:!0});if(!e)throw new Error("WebGL2 is required but not available.");const r=createProgram(e,vertexShaderSource,fragmentShaderSource);this.checkGLError(e,"setupGL: after createProgram");const n=e.createVertexArray();e.bindVertexArray(n),this.checkGLError(e,"setupGL: after VAO creation");const i=this.canvas.width||2,o=this.canvas.height||2,{positions:s,uvs:a}=computeBorderGeometry(i,o,this.options.borderWidth,this.options.glowWidth),l=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,l),e.bufferData(e.ARRAY_BUFFER,s,e.STATIC_DRAW);const d=e.getAttribLocation(r,"aPosition");e.enableVertexAttribArray(d),e.vertexAttribPointer(d,2,e.FLOAT,!1,0,0),this.checkGLError(e,"setupGL: after position buffer setup");const u=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,u),e.bufferData(e.ARRAY_BUFFER,a,e.STATIC_DRAW);const f=e.getAttribLocation(r,"aUV");e.enableVertexAttribArray(f),e.vertexAttribPointer(f,2,e.FLOAT,!1,0,0),this.checkGLError(e,"setupGL: after UV buffer setup");const p=e.getUniformLocation(r,"uResolution"),g=e.getUniformLocation(r,"uTime"),y=e.getUniformLocation(r,"uBorderWidth"),Z=e.getUniformLocation(r,"uGlowWidth"),x=e.getUniformLocation(r,"uBorderRadius"),h=e.getUniformLocation(r,"uColors"),S=e.getUniformLocation(r,"uGlowExponent"),I=e.getUniformLocation(r,"uGlowFactor");e.useProgram(r),e.uniform1f(y,this.options.borderWidth),e.uniform1f(Z,this.options.glowWidth),e.uniform1f(x,this.options.borderRadius),this.options.mode==="dark"?(e.uniform1f(S,2),e.uniform1f(I,1.8)):(e.uniform1f(S,1),e.uniform1f(I,1));const A=(this.options.colors||DEFAULT_COLORS).map(parseColor);for(let O=0;O<A.length;O++)e.uniform3f(e.getUniformLocation(r,`uColors[${O}]`),...A[O]);this.checkGLError(e,"setupGL: after uniform setup"),e.bindVertexArray(null),e.bindBuffer(e.ARRAY_BUFFER,null),this.glr={gl:e,program:r,vao:n,positionBuffer:l,uvBuffer:u,uResolution:p,uTime:g,uBorderWidth:y,uGlowWidth:Z,uBorderRadius:x,uColors:h}}render(e){if(!this.glr)return;const{gl:r,program:n,vao:i,uTime:o}=this.glr;r.useProgram(n),r.bindVertexArray(i),r.uniform1f(o,e),r.disable(r.DEPTH_TEST),r.disable(r.CULL_FACE),r.disable(r.BLEND),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),r.drawArrays(r.TRIANGLES,0,24),this.checkGLError(r,"render: after draw call"),r.bindVertexArray(null)}greet(){console.log("%c🌈 ai-motion 0.4.8 🌈","background: linear-gradient(90deg, #39b6ff, #bd45fb, #ff5733, #ffd600); color: white; text-shadow: 0 0 2px rgba(0, 0, 0, 0.2); font-weight: bold; font-size: 1em; padding: 2px 12px; border-radius: 6px;")}}function isPageDark$1(){try{return!!(hasDarkModeClass$1()||hasDarkModeDataAttribute$1()||isColorSchemeDark$1()||isBackgroundDark$1()||isMainContentBackgroundDark$1()||isTextColorLight$1())}catch(t){return console.warn("Error determining if page is dark:",t),!1}}function hasDarkModeClass$1(){const t=["dark","dark-mode","theme-dark","night","night-mode"],e=document.documentElement,r=document.body||document.documentElement;for(const n of t)if(e.classList.contains(n)||r?.classList.contains(n))return!0;return!1}function hasDarkModeDataAttribute$1(){const t=document.documentElement,e=document.body||document.documentElement,r=["data-theme","data-color-mode","data-bs-theme","data-mui-color-scheme"];for(const n of r){const i=e?.getAttribute(n),o=t.getAttribute(n);if(i?.toLowerCase()==="dark"||o?.toLowerCase()==="dark")return!0}return!1}function isColorSchemeDark$1(){const e=document.querySelector('meta[name="color-scheme"]')?.content.toLowerCase();if(e==="dark"||e==="only dark")return!0;const n=window.getComputedStyle(document.documentElement).getPropertyValue("color-scheme").trim().toLowerCase();return n==="dark"||n==="only dark"}function isBackgroundDark$1(){const t=window.getComputedStyle(document.documentElement),e=window.getComputedStyle(document.body||document.documentElement),r=t.backgroundColor,n=e.backgroundColor;return isColorDark$1(n)?!0:n==="transparent"||n.startsWith("rgba(0, 0, 0, 0)")?isColorDark$1(r):!1}function isTextColorLight$1(){const e=window.getComputedStyle(document.body||document.documentElement),r=getLuminance$1(e.color);return r!==null&&r>200}function isMainContentBackgroundDark$1(){const{innerWidth:t,innerHeight:e}=window,r=t*e*.5,n=["#app","#root","#__next"];for(const i of n){const o=document.querySelector(i);if(!o)continue;const s=o.getBoundingClientRect();if(!(s.width*s.height<r)&&isColorDark$1(window.getComputedStyle(o).backgroundColor))return!0}return!1}function parseRgbColor$1(t){const e=/rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(t);return e?{r:parseInt(e[1]),g:parseInt(e[2]),b:parseInt(e[3])}:null}function getLuminance$1(t){if(!t||t==="transparent"||t.startsWith("rgba(0, 0, 0, 0)"))return null;const e=parseRgbColor$1(t);return e?.299*e.r+.587*e.g+.114*e.b:null}function isColorDark$1(t,e=128){const r=getLuminance$1(t);return r!==null&&r<e}const injectStyles=`
477
+ }`;const DEFAULT_COLORS=["rgb(57, 182, 255)","rgb(189, 69, 251)","rgb(255, 87, 51)","rgb(255, 214, 0)"];function parseColor(t){const e=t.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);if(!e)throw new Error(`Invalid color format: ${t}`);const[,r,n,i]=e;return[parseInt(r)/255,parseInt(n)/255,parseInt(i)/255]}class Motion{element;canvas;options;running=!1;disposed=!1;startTime=0;lastTime=0;rafId=null;glr;observer;constructor(e={}){this.options={width:e.width??600,height:e.height??600,ratio:e.ratio??window.devicePixelRatio??1,borderWidth:e.borderWidth??8,glowWidth:e.glowWidth??200,borderRadius:e.borderRadius??8,mode:e.mode??"light",...e},this.canvas=document.createElement("canvas"),this.options.classNames&&(this.canvas.className=this.options.classNames),this.options.styles&&Object.assign(this.canvas.style,this.options.styles),this.canvas.style.display="block",this.canvas.style.transformOrigin="center",this.canvas.style.pointerEvents="none",this.element=this.canvas,this.setupGL(),this.options.skipGreeting||this.greet()}start(){if(this.disposed)throw 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 e=()=>{if(!this.running||!this.glr)return;this.rafId=requestAnimationFrame(e);const r=performance.now();if(r-this.lastTime<1e3/32)return;this.lastTime=r;const i=(r-this.startTime)*.001;this.render(i)};this.rafId=requestAnimationFrame(e)}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:e,vao:r,positionBuffer:n,uvBuffer:i,program:o}=this.glr;r&&e.deleteVertexArray(r),n&&e.deleteBuffer(n),i&&e.deleteBuffer(i),e.deleteProgram(o),this.observer&&this.observer.disconnect(),this.canvas.remove()}resize(e,r,n){if(this.disposed)throw new Error("Motion instance has been disposed.");if(this.options.width=e,this.options.height=r,n&&(this.options.ratio=n),!this.running)return;const{gl:i,program:o,vao:s,positionBuffer:a,uvBuffer:l,uResolution:c}=this.glr,u=n??this.options.ratio??window.devicePixelRatio??1,h=Math.max(1,Math.floor(e*u)),f=Math.max(1,Math.floor(r*u));this.canvas.style.width=`${e}px`,this.canvas.style.height=`${r}px`,(this.canvas.width!==h||this.canvas.height!==f)&&(this.canvas.width=h,this.canvas.height=f),i.viewport(0,0,this.canvas.width,this.canvas.height),this.checkGLError(i,"resize: after viewport setup");const{positions:g,uvs:b}=computeBorderGeometry(this.canvas.width,this.canvas.height,this.options.borderWidth*u,this.options.glowWidth*u);i.bindVertexArray(s),i.bindBuffer(i.ARRAY_BUFFER,a),i.bufferData(i.ARRAY_BUFFER,g,i.STATIC_DRAW);const P=i.getAttribLocation(o,"aPosition");i.enableVertexAttribArray(P),i.vertexAttribPointer(P,2,i.FLOAT,!1,0,0),this.checkGLError(i,"resize: after position buffer update"),i.bindBuffer(i.ARRAY_BUFFER,l),i.bufferData(i.ARRAY_BUFFER,b,i.STATIC_DRAW);const w=i.getAttribLocation(o,"aUV");i.enableVertexAttribArray(w),i.vertexAttribPointer(w,2,i.FLOAT,!1,0,0),this.checkGLError(i,"resize: after UV buffer update"),i.useProgram(o),i.uniform2f(c,this.canvas.width,this.canvas.height),i.uniform1f(this.glr.uBorderWidth,this.options.borderWidth*u),i.uniform1f(this.glr.uGlowWidth,this.options.glowWidth*u),i.uniform1f(this.glr.uBorderRadius,this.options.borderRadius*u),this.checkGLError(i,"resize: after uniform updates");const p=performance.now();this.lastTime=p;const m=(p-this.startTime)*.001;this.render(m)}autoResize(e){this.observer&&this.observer.disconnect(),this.observer=new ResizeObserver(()=>{const r=e.getBoundingClientRect();this.resize(r.width,r.height)}),this.observer.observe(e)}fadeIn(){if(this.disposed)throw new Error("Motion instance has been disposed.");return new Promise((e,r)=>{const n=this.canvas.animate([{opacity:0,transform:"scale(1.2)"},{opacity:1,transform:"scale(1)"}],{duration:300,easing:"ease-out",fill:"forwards"});n.onfinish=()=>e(),n.oncancel=()=>r("canceled")})}fadeOut(){if(this.disposed)throw new Error("Motion instance has been disposed.");return new Promise((e,r)=>{const n=this.canvas.animate([{opacity:1,transform:"scale(1)"},{opacity:0,transform:"scale(1.2)"}],{duration:300,easing:"ease-in",fill:"forwards"});n.onfinish=()=>e(),n.oncancel=()=>r("canceled")})}checkGLError(e,r){let n=e.getError();if(n!==e.NO_ERROR){for(console.group(`🔴 WebGL Error in ${r}`);n!==e.NO_ERROR;){const i=this.getGLErrorName(e,n);console.error(`${i} (0x${n.toString(16)})`),n=e.getError()}console.groupEnd()}}getGLErrorName(e,r){switch(r){case e.INVALID_ENUM:return"INVALID_ENUM";case e.INVALID_VALUE:return"INVALID_VALUE";case e.INVALID_OPERATION:return"INVALID_OPERATION";case e.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case e.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case e.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return"UNKNOWN_ERROR"}}setupGL(){const e=this.canvas.getContext("webgl2",{antialias:!1,alpha:!0});if(!e)throw new Error("WebGL2 is required but not available.");const r=createProgram(e,vertexShaderSource,fragmentShaderSource);this.checkGLError(e,"setupGL: after createProgram");const n=e.createVertexArray();e.bindVertexArray(n),this.checkGLError(e,"setupGL: after VAO creation");const i=this.canvas.width||2,o=this.canvas.height||2,{positions:s,uvs:a}=computeBorderGeometry(i,o,this.options.borderWidth,this.options.glowWidth),l=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,l),e.bufferData(e.ARRAY_BUFFER,s,e.STATIC_DRAW);const c=e.getAttribLocation(r,"aPosition");e.enableVertexAttribArray(c),e.vertexAttribPointer(c,2,e.FLOAT,!1,0,0),this.checkGLError(e,"setupGL: after position buffer setup");const u=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,u),e.bufferData(e.ARRAY_BUFFER,a,e.STATIC_DRAW);const h=e.getAttribLocation(r,"aUV");e.enableVertexAttribArray(h),e.vertexAttribPointer(h,2,e.FLOAT,!1,0,0),this.checkGLError(e,"setupGL: after UV buffer setup");const f=e.getUniformLocation(r,"uResolution"),g=e.getUniformLocation(r,"uTime"),b=e.getUniformLocation(r,"uBorderWidth"),P=e.getUniformLocation(r,"uGlowWidth"),w=e.getUniformLocation(r,"uBorderRadius"),p=e.getUniformLocation(r,"uColors"),m=e.getUniformLocation(r,"uGlowExponent"),A=e.getUniformLocation(r,"uGlowFactor");e.useProgram(r),e.uniform1f(b,this.options.borderWidth),e.uniform1f(P,this.options.glowWidth),e.uniform1f(w,this.options.borderRadius),this.options.mode==="dark"?(e.uniform1f(m,2),e.uniform1f(A,1.8)):(e.uniform1f(m,1),e.uniform1f(A,1));const T=(this.options.colors||DEFAULT_COLORS).map(parseColor);for(let k=0;k<T.length;k++)e.uniform3f(e.getUniformLocation(r,`uColors[${k}]`),...T[k]);this.checkGLError(e,"setupGL: after uniform setup"),e.bindVertexArray(null),e.bindBuffer(e.ARRAY_BUFFER,null),this.glr={gl:e,program:r,vao:n,positionBuffer:l,uvBuffer:u,uResolution:f,uTime:g,uBorderWidth:b,uGlowWidth:P,uBorderRadius:w,uColors:p}}render(e){if(!this.glr)return;const{gl:r,program:n,vao:i,uTime:o}=this.glr;r.useProgram(n),r.bindVertexArray(i),r.uniform1f(o,e),r.disable(r.DEPTH_TEST),r.disable(r.CULL_FACE),r.disable(r.BLEND),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),r.drawArrays(r.TRIANGLES,0,24),this.checkGLError(r,"render: after draw call"),r.bindVertexArray(null)}greet(){console.log("%c🌈 ai-motion 0.4.8 🌈","background: linear-gradient(90deg, #39b6ff, #bd45fb, #ff5733, #ffd600); color: white; text-shadow: 0 0 2px rgba(0, 0, 0, 0.2); font-weight: bold; font-size: 1em; padding: 2px 12px; border-radius: 6px;")}}function isPageDark$1(){try{return!!(hasDarkModeClass$1()||hasDarkModeDataAttribute$1()||isColorSchemeDark$1()||isBackgroundDark$1()||isMainContentBackgroundDark$1()||isTextColorLight$1())}catch(t){return console.warn("Error determining if page is dark:",t),!1}}function hasDarkModeClass$1(){const t=["dark","dark-mode","theme-dark","night","night-mode"],e=document.documentElement,r=document.body||document.documentElement;for(const n of t)if(e.classList.contains(n)||r?.classList.contains(n))return!0;return!1}function hasDarkModeDataAttribute$1(){const t=document.documentElement,e=document.body||document.documentElement,r=["data-theme","data-color-mode","data-bs-theme","data-mui-color-scheme"];for(const n of r){const i=e?.getAttribute(n),o=t.getAttribute(n);if(i?.toLowerCase()==="dark"||o?.toLowerCase()==="dark")return!0}return!1}function isColorSchemeDark$1(){const e=document.querySelector('meta[name="color-scheme"]')?.content.toLowerCase();if(e==="dark"||e==="only dark")return!0;const n=window.getComputedStyle(document.documentElement).getPropertyValue("color-scheme").trim().toLowerCase();return n==="dark"||n==="only dark"}function isBackgroundDark$1(){const t=window.getComputedStyle(document.documentElement),e=window.getComputedStyle(document.body||document.documentElement),r=t.backgroundColor,n=e.backgroundColor;return isColorDark$1(n)?!0:n==="transparent"||n.startsWith("rgba(0, 0, 0, 0)")?isColorDark$1(r):!1}function isTextColorLight$1(){const e=window.getComputedStyle(document.body||document.documentElement),r=getLuminance$1(e.color);return r!==null&&r>200}function isMainContentBackgroundDark$1(){const{innerWidth:t,innerHeight:e}=window,r=t*e*.5,n=["#app","#root","#__next"];for(const i of n){const o=document.querySelector(i);if(!o)continue;const s=o.getBoundingClientRect();if(!(s.width*s.height<r)&&isColorDark$1(window.getComputedStyle(o).backgroundColor))return!0}return!1}function parseRgbColor$1(t){const e=/rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(t);return e?{r:parseInt(e[1]),g:parseInt(e[2]),b:parseInt(e[3])}:null}function getLuminance$1(t){if(!t||t==="transparent"||t.startsWith("rgba(0, 0, 0, 0)"))return null;const e=parseRgbColor$1(t);return e?.299*e.r+.587*e.g+.114*e.b:null}function isColorDark$1(t,e=128){const r=getLuminance$1(t);return r!==null&&r<e}const injectStyles=`
470
478
  .webmcp-page-agent-cursor {
471
479
  position: absolute;
472
480
  width: var(--cursor-size, 75px);
@@ -475,31 +483,15 @@ gl_Position = vec4(aPosition, 0.0, 1.0);
475
483
  z-index: 10000;
476
484
  }
477
485
 
478
- .webmcp-page-agent-cursorBorder {
479
- position: absolute;
480
- width: 100%;
481
- height: 100%;
482
- background: linear-gradient(45deg, rgb(57, 182, 255), rgb(189, 69, 251));
483
- 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");
484
- mask-size: 100% 100%;
485
- mask-repeat: no-repeat;
486
-
487
- transform-origin: center;
488
- transform: rotate(-90deg) scale(0.8);
489
- margin-left: -10px;
490
- margin-top: -18px;
491
- }
492
-
493
486
  .webmcp-page-agent-cursorFilling {
494
487
  position: absolute;
495
488
  width: 100%;
496
489
  height: 100%;
497
- 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");
498
- background-size: 100% 100%;
490
+ background: url("data:image/svg+xml,%3Csvg%20viewBox%3D%270%200%2079.0834%2079.4553%27%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%20%20width%3D%2779.083374%27%20height%3D%2779.455322%27%20fill%3D%27none%27%20%3E--%3Cdefs%3E%3Cfilter%20id%3D%27filter_0%27%20width%3D%2779.083374%27%20height%3D%2779.455322%27%20x%3D%270.000000%27%20y%3D%270.000000%27%20filterUnits%3D%27userSpaceOnUse%27%20%20color-interpolation-filters%3D%27sRGB%27%3E%3CfeFlood%20flood-opacity%3D%270%27%20result%3D%27BackgroundImageFix%27%20%2F%3E%3CfeOffset%20dx%3D%276.000000%27%20dy%3D%276.000000%27%20in%3D%27SourceAlpha%27%20%2F%3E%3CfeGaussianBlur%20stdDeviation%3D%276.66666651%27%20%2F%3E%3CfeColorMatrix%20type%3D%27matrix%27%20values%3D%270%200%200%200%200%200%200%200%200%200%200%200%200%200%200%200%200%200%200.18%200%20%27%20%2F%3E%3CfeBlend%20result%3D%27effect_dropShadow_1%27%20in2%3D%27BackgroundImageFix%27%20mode%3D%27normal%27%20%2F%3E%3CfeBlend%20result%3D%27shape%27%20in%3D%27SourceGraphic%27%20in2%3D%27effect_dropShadow_1%27%20mode%3D%27normal%27%20%2F%3E%3C%2Ffilter%3E%3ClinearGradient%20id%3D%27paint_linear_0%27%20x1%3D%2718.4743214%27%20x2%3D%2718.4213886%27%20y1%3D%27-1.86264515e-09%27%20y2%3D%2734.9221306%27%20gradientUnits%3D%27userSpaceOnUse%27%3E%3Cstop%20stop-color%3D%27rgb%28255%2C181%2C96%29%27%20offset%3D%270%27%20stop-opacity%3D%271%27%20%2F%3E%3Cstop%20stop-color%3D%27rgb%28255%2C120%2C114%29%27%20offset%3D%270.5%27%20stop-opacity%3D%271%27%20%2F%3E%3Cstop%20stop-color%3D%27rgb%28241%2C109%2C237%29%27%20offset%3D%271%27%20stop-opacity%3D%271%27%20%2F%3E%3C%2FlinearGradient%3E%3C%2Fdefs%3E%3Cg%20filter%3D%27url%28%23filter_0%29%27%3E%3Cpath%20d%3D%27M20.2632%203.57771L34.6257%2032.3027C35.4444%2033.9402%2033.8152%2035.7258%2032.1097%2035.0603L19.2014%2030.0229C18.7339%2029.8404%2018.2148%2029.8404%2017.7472%2030.0229L4.83891%2035.0603C3.13343%2035.7258%201.50423%2033.9402%202.32297%2032.3027L16.6855%203.57771C17.4225%202.10361%2019.5261%202.10361%2020.2632%203.57771Z%27%20fill%3D%27url%28%23paint_linear_0%29%27%20fill-rule%3D%27evenodd%27%20transform%3D%27matrix%280.719908%2C-0.69407%2C0.69407%2C0.719908%2C2.00256%2C28.0095%29%27%20%2F%3E%3Cpath%20d%3D%27M37.2169%2032.6848C37.1578%2032.189%2037.0096%2031.7039%2036.7723%2031.2294L22.4098%202.5044C22.1973%202.07946%2021.9328%201.70554%2021.6163%201.38261C21.3524%201.11342%2021.0524%200.879671%2020.7162%200.681366C20.3925%200.490407%2020.0558%200.34434%2019.7061%200.243163C19.312%200.129145%2018.9014%200.0721366%2018.4743%200.0721366C18.0472%200.0721366%2017.6367%200.129145%2017.2426%200.243163C16.8929%200.34434%2016.5562%200.490407%2016.2324%200.681366C15.8962%200.879671%2015.5962%201.11342%2015.3323%201.38261C15.0158%201.70553%2014.7513%202.07946%2014.5388%202.5044L0.176342%2031.2294C-0.0609121%2031.7039%20-0.209128%2032.189%20-0.268305%2032.6848C-0.316251%2033.0865%20-0.305747%2033.4951%20-0.236792%2033.9108C-0.171059%2034.307%20-0.0570567%2034.6809%200.105216%2035.0326C0.292784%2035.4391%200.544845%2035.8158%200.861397%2036.1627C1.17794%2036.5097%201.53001%2036.7951%201.91761%2037.0191C2.25297%2037.2128%202.61492%2037.3606%203.00348%2037.4623C3.41106%2037.5689%203.81704%2037.6168%204.22142%2037.6058C4.72053%2037.5922%205.21719%2037.4889%205.71141%2037.2961L18.4743%2032.3154L31.2372%2037.2961C31.7315%2037.4889%2032.2281%2037.5922%2032.7272%2037.6058C33.1316%2037.6168%2033.5376%2037.5689%2033.9452%2037.4623C34.3337%2037.3606%2034.6957%2037.2128%2035.0311%2037.0191C35.4187%2036.7951%2035.7707%2036.5097%2036.0873%2036.1627C36.4038%2035.8158%2036.6558%2035.4391%2036.8434%2035.0327C37.0057%2034.681%2037.1197%2034.307%2037.1854%2033.9108C37.2544%2033.4951%2037.2649%2033.0865%2037.2169%2032.6848ZM34.6257%2032.3027L20.2632%203.57771C19.5261%202.10361%2017.4225%202.10361%2016.6855%203.57771L2.32297%2032.3027C1.50423%2033.9402%203.13343%2035.7258%204.83891%2035.0603L17.7472%2030.0229C18.2148%2029.8404%2018.7339%2029.8404%2019.2014%2030.0229L32.1097%2035.0603C33.8152%2035.7258%2035.4444%2033.9402%2034.6257%2032.3027Z%27%20fill%3D%27rgb%28255%2C255%2C255%29%27%20fill-rule%3D%27evenodd%27%20transform%3D%27matrix%280.719908%2C-0.69407%2C0.69407%2C0.719908%2C2.00256%2C28.0095%29%27%20%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E");
491
+ background-size: 100% 100%;
499
492
  background-repeat: no-repeat;
500
493
 
501
494
  transform-origin: center;
502
- transform: rotate(-90deg) scale(0.8);
503
495
  margin-left: -10px;
504
496
  margin-top: -18px;
505
497
  }
@@ -552,7 +544,7 @@ gl_Position = vec4(aPosition, 0.0, 1.0);
552
544
  .webmcp-page-agent-wrapper.visible {
553
545
  display: block;
554
546
  }
555
- `;let SimulatorMask$1=class extends EventTarget{constructor(){super(),this.shown=!1,this.wrapper=document.createElement("div"),this.motion=null,this.#n=!1,this.#e=document.createElement("div"),this.#t=0,this.#r=0,this.#i=0,this.#o=0,document.head.appendChild(document.createElement("style")).textContent=injectStyles,this.wrapper.id="page-agent-runtime_simulator-mask",this.wrapper.className="webmcp-page-agent-wrapper",this.wrapper.setAttribute("data-browser-use-ignore","true"),this.wrapper.setAttribute("data-page-agent-ignore","true");try{const s=new Motion({mode:isPageDark$1()?"dark":"light",styles:{position:"absolute",inset:"0"}});this.motion=s,this.wrapper.appendChild(s.element),s.autoResize(this.wrapper)}catch(s){console.warn("[SimulatorMask] Motion overlay unavailable:",s)}const e=s=>{s.stopPropagation(),s.preventDefault()};["click","mousedown","mouseup","mousemove","wheel","keydown","keyup"].forEach(s=>this.wrapper.addEventListener(s,e)),this.#a(),document.body.appendChild(this.wrapper),this.#s();const r=s=>{const{x:a,y:l}=s.detail;this.setCursorPosition(a,l)},n=()=>{this.triggerClickAnimation()},i=()=>{this.wrapper.style.pointerEvents="none"},o=()=>{this.wrapper.style.pointerEvents="auto"};window.addEventListener("PageAgent::MovePointerTo",r),window.addEventListener("PageAgent::ClickPointer",n),window.addEventListener("PageAgent::EnablePassThrough",i),window.addEventListener("PageAgent::DisablePassThrough",o),this.addEventListener("dispose",()=>{window.removeEventListener("PageAgent::MovePointerTo",r),window.removeEventListener("PageAgent::ClickPointer",n),window.removeEventListener("PageAgent::EnablePassThrough",i),window.removeEventListener("PageAgent::DisablePassThrough",o)})}#n;#e;#t;#r;#i;#o;#a(){this.#e.className="webmcp-page-agent-cursor";const e=document.createElement("div");e.className="webmcp-page-agent-cursorRipple",this.#e.appendChild(e);const r=document.createElement("div");r.className="webmcp-page-agent-cursorFilling",this.#e.appendChild(r);const n=document.createElement("div");n.className="webmcp-page-agent-cursorBorder",this.#e.appendChild(n),this.wrapper.appendChild(this.#e)}#s(){if(this.#n)return;const e=this.#t+(this.#i-this.#t)*.2,r=this.#r+(this.#o-this.#r)*.2,n=Math.abs(e-this.#i);n>0&&(n<2?this.#t=this.#i:this.#t=e,this.#e.style.left=`${this.#t}px`);const i=Math.abs(r-this.#o);i>0&&(i<2?this.#r=this.#o:this.#r=r,this.#e.style.top=`${this.#r}px`),requestAnimationFrame(()=>this.#s())}setCursorPosition(e,r){this.#n||(this.#i=e,this.#o=r)}triggerClickAnimation(){this.#n||(this.#e.classList.remove("clicking"),this.#e.offsetHeight,this.#e.classList.add("clicking"))}show(){this.shown||this.#n||(this.shown=!0,this.motion?.start(),this.motion?.fadeIn(),this.wrapper.classList.add("visible"),this.#t=window.innerWidth/2,this.#r=window.innerHeight/2,this.#i=this.#t,this.#o=this.#r,this.#e.style.left=`${this.#t}px`,this.#e.style.top=`${this.#r}px`)}hide(){!this.shown||this.#n||(this.shown=!1,this.motion?.fadeOut(),this.motion?.pause(),this.#e.classList.remove("clicking"),setTimeout(()=>{this.wrapper.classList.remove("visible")},800))}dispose(){this.#n=!0,this.motion?.dispose(),this.wrapper.remove(),this.dispatchEvent(new Event("dispose"))}};const DEFAULT_ERROR_SELECTORS=['[role="alert"]','[aria-invalid="true"]',".ti3-unifyvalid-error",".ti3-error",".ti-error",".lego-text-error",".lego-error",".el-form-item__error",".ant-form-item-explain-error",".is-invalid",".invalid-feedback",".ng-invalid",".error-msg",".error-message",".error-text",".field-error",".form-error",".is-error",".has-error",".validate-error",".valid-error"],DEFAULT_DIALOG_SELECTORS=['[role="dialog"]','[role="alertdialog"]','[class*="ti3-modal"]','[class*="ti3-message-box"]','[class*="el-dialog"]','[class*="el-message-box"]','[class*="ant-modal"]','[class*="modal-content"]','[class*="v-dialog"]','[class*="n-modal"]'],inputSchema=objectType({action:enumType(["browserState","click","fill","select","scroll","executeJavascript","searchTree"]).describe(`执行的动作名称, 每一次执行 'click', 'fill', 'select'动作之前,**必须**要先调用 'browserState' 去获取页面的最新状态。
547
+ `;let SimulatorMask$1=class extends EventTarget{constructor(){super(),this.shown=!1,this.wrapper=document.createElement("div"),this.motion=null,this.#n=!1,this.#e=document.createElement("div"),this.#t=0,this.#r=0,this.#i=0,this.#o=0,document.head.appendChild(document.createElement("style")).textContent=injectStyles,this.wrapper.id="page-agent-runtime_simulator-mask",this.wrapper.className="webmcp-page-agent-wrapper",this.wrapper.setAttribute("data-browser-use-ignore","true"),this.wrapper.setAttribute("data-page-agent-ignore","true");try{const s=new Motion({mode:isPageDark$1()?"dark":"light",styles:{position:"absolute",inset:"0"},glowWidth:80,borderWidth:8,colors:["rgb(121, 216, 247)","rgb(171, 219, 110)","rgb(252, 188, 114)","rgb(235, 117, 231)"]});this.motion=s,this.wrapper.appendChild(s.element),s.autoResize(this.wrapper)}catch(s){console.warn("[SimulatorMask] Motion overlay unavailable:",s)}const e=s=>{s.stopPropagation(),s.preventDefault()};["click","mousedown","mouseup","mousemove","wheel","keydown","keyup"].forEach(s=>this.wrapper.addEventListener(s,e)),this.#a(),document.body.appendChild(this.wrapper),this.#s();const r=s=>{const{x:a,y:l}=s.detail;this.setCursorPosition(a,l)},n=()=>{this.triggerClickAnimation()},i=()=>{this.wrapper.style.pointerEvents="none"},o=()=>{this.wrapper.style.pointerEvents="auto"};window.addEventListener("PageAgent::MovePointerTo",r),window.addEventListener("PageAgent::ClickPointer",n),window.addEventListener("PageAgent::EnablePassThrough",i),window.addEventListener("PageAgent::DisablePassThrough",o),this.addEventListener("dispose",()=>{window.removeEventListener("PageAgent::MovePointerTo",r),window.removeEventListener("PageAgent::ClickPointer",n),window.removeEventListener("PageAgent::EnablePassThrough",i),window.removeEventListener("PageAgent::DisablePassThrough",o)})}#n;#e;#t;#r;#i;#o;#a(){this.#e.className="webmcp-page-agent-cursor";const e=document.createElement("div");e.className="webmcp-page-agent-cursorRipple",this.#e.appendChild(e);const r=document.createElement("div");r.className="webmcp-page-agent-cursorFilling",this.#e.appendChild(r),this.wrapper.appendChild(this.#e)}#s(){if(this.#n)return;const e=this.#t+(this.#i-this.#t)*.2,r=this.#r+(this.#o-this.#r)*.2,n=Math.abs(e-this.#i);n>0&&(n<2?this.#t=this.#i:this.#t=e,this.#e.style.left=`${this.#t}px`);const i=Math.abs(r-this.#o);i>0&&(i<2?this.#r=this.#o:this.#r=r,this.#e.style.top=`${this.#r}px`),requestAnimationFrame(()=>this.#s())}setCursorPosition(e,r){this.#n||(this.#i=e,this.#o=r)}triggerClickAnimation(){this.#n||(this.#e.classList.remove("clicking"),this.#e.offsetHeight,this.#e.classList.add("clicking"))}show(){this.shown||this.#n||(this.shown=!0,this.motion?.start(),this.motion?.fadeIn(),this.wrapper.classList.add("visible"),this.#t=window.innerWidth/2,this.#r=window.innerHeight/2,this.#i=this.#t,this.#o=this.#r,this.#e.style.left=`${this.#t}px`,this.#e.style.top=`${this.#r}px`)}hide(){!this.shown||this.#n||(this.shown=!1,this.motion?.fadeOut(),this.motion?.pause(),this.#e.classList.remove("clicking"),setTimeout(()=>{this.wrapper.classList.remove("visible")},800))}dispose(){this.#n=!0,this.motion?.dispose(),this.wrapper.remove(),this.dispatchEvent(new Event("dispose"))}borderElement(e){if(!e)return;this.wrapper.querySelector(".webmcp-page-agent-border")?.remove();const r=e.getBoundingClientRect(),n=2,i=2,o=n+i,s=document.createElement("div");s.className="webmcp-page-agent-border",s.style.position="absolute",s.style.left=`${r.left-o}px`,s.style.top=`${r.top-o}px`,s.style.width=`${r.width+o*2}px`,s.style.height=`${r.height+o*2}px`,s.style.boxSizing="border-box",s.style.pointerEvents="none",s.style.zIndex="10000",s.style.border=`${i}px solid transparent`,s.style.borderImageSource="linear-gradient(to bottom right, #79D8F7, #ABDB6E, #FCBC72, #FA8682, #EB75E7)",s.style.borderImageSlice="1",s.style.borderImageWidth=`${i}px`,this.wrapper.appendChild(s)}removeBorderElement(){this.wrapper.querySelector(".webmcp-page-agent-border")?.remove()}};const inputSchema=objectType({action:enumType(["browserState","click","fill","select","scroll","executeJavascript","searchTree"]).describe(`执行的动作名称, 每一次执行 'click', 'fill', 'select'动作之前,**必须**要先调用 'browserState' 去获取页面的最新状态。
556
548
  browserState: '查询整个页面的浏览器状态;返回页面的标题、URL、YAML格式的语义化页面树',
557
549
  click: '根据元素索引点击;',
558
550
  fill: '根据元素索引填写文本;';
@@ -560,24 +552,20 @@ gl_Position = vec4(aPosition, 0.0, 1.0);
560
552
  scroll: '滚动页面的动作,可以指定水平滚动还是上下滚动; 不带元素索引时:滚动整个文档。带元素索引时:滚动该索引处的容器(或其最近的可滚动祖先元素)'
561
553
  executeJavascript: '执行javascript代码'
562
554
  searchTree: '按关键词搜索无障碍树,返回带行号的匹配节点及上下文,无需获取全量树。适合快速定位特定元素(如所有按钮、特定名称的链接等),显著减少上下文消耗。必须提供 query 参数。'
563
- `),index:numberType().min(0).optional().describe("执行动作 of the element index, 动作为 click,fill,select时,必须提供元素索引"),text:stringType().optional().describe("执行动作的文本内容, 动作为 fill,select 时,必须提供文本内容"),down:booleanType().optional().describe("执行上下滚动时,必须提供down参数"),right:booleanType().optional().describe("执行水平滚动方向, 必须提供right参数"),numPages:numberType().optional().describe("执行动作的滚动页数, 动作为 scroll时,可以提供滚动页数,建议每次滚动0.1页,该值不要大于5."),pixels:numberType().int().min(0).optional().describe("执行动作的滚动像素数,动作为 scroll时,可以提供滚动像素数"),script:stringType().optional().describe("执行的javascript代码,动作为 executeJavascript时,必须提供script参数"),query:stringType().optional().describe("搜索关键词,动作为 searchTree 时必须提供。支持按 role(如 button、link)、节点名称、状态(如 checked)或 ref 索引(如 #3)搜索"),contextLines:numberType().int().min(0).max(10).default(2).describe("searchTree 时每个命中行前后保留的上下文行数,默认 2"),maxMatches:numberType().int().min(1).max(50).default(20).describe("searchTree 时最大返回分组数,默认 20"),responseMode:enumType(["full","diff","both"]).optional().default("diff").describe("返回浏览器状态的模式。full: 仅返回当前全量 A11y 树;diff: 仅返回与上一次状态的增量差异;both: 同时返回全量 A11y 树与增量差异。默认值为 diff。")});function isInShadowDom(t){return t.getRootNode()instanceof ShadowRoot}function dispatchComposedEvents(t,...e){for(const r of e)t.dispatchEvent(new Event(r,{bubbles:!0,composed:!0}))}function deepQuerySelectorAll(t,e=document){const r=Array.from(e.querySelectorAll(t)),n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,null);let i=n.currentNode;for(;i;)i.shadowRoot&&r.push(...deepQuerySelectorAll(t,i.shadowRoot)),i=n.nextNode();return r}function waitForDomSettled(t=600,e=150){return new Promise(r=>{let n=!1,i;const o=()=>{n||(n=!0,s.disconnect(),i&&clearTimeout(i),r())},s=new MutationObserver(()=>{i&&clearTimeout(i),i=setTimeout(o,e)});i=setTimeout(o,e),setTimeout(o,t),s.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["class","style","hidden"]})})}function detectPageDialog(){const t=new Set,e=[],r=window.__webmcpcli_dialogSelectors??DEFAULT_DIALOG_SELECTORS;for(const n of r)try{for(const i of deepQuerySelectorAll(n)){if(t.has(i)||i.id?.includes("page-agent-runtime")||i.closest("#page-agent-runtime_simulator-mask"))continue;const o=i.getBoundingClientRect();if(o.width<50||o.height<50)continue;const s=window.getComputedStyle(i);if(s.display==="none"||s.visibility==="hidden")continue;const a=s.position==="fixed"||s.position==="absolute",l=parseInt(s.zIndex||"0",10);if(!a||l<100)continue;const d=window.innerWidth,u=window.innerHeight;if(!(o.left<d*.6&&o.right>d*.4&&o.top<u*.6&&o.bottom>u*.4))continue;t.add(i);const p=(i.textContent||"").trim().replace(/\s+/g," ");if(p.length>5){const g=i.querySelectorAll('button, [role="button"], a'),y=Array.from(g).map(x=>(x.textContent||"").trim()).filter(x=>x.length>0&&x.length<20).slice(0,5),Z=y.length?` [可操作按钮: ${y.join(" / ")}]`:"";e.push(`${p.substring(0,300)}${Z}`)}}}catch{}return e.length===0?"":`
564
- [页面弹窗检测] 检测到 ${e.length} 个模态弹窗,请优先处理:
565
- ${e.map((n,i)=>`${i+1}. ${n}`).join(`
566
- `)}
567
- `}function detectValidationErrors(){const t=new Set,e=[],r=window.__webmcpcli_errorSelectors??DEFAULT_ERROR_SELECTORS;for(const n of r)try{for(const i of deepQuerySelectorAll(n)){if(t.has(i)||Array.from(t).some(l=>l.contains(i)))continue;const o=i.getBoundingClientRect();if(o.width<1||o.height<1)continue;const s=window.getComputedStyle(i);if(s.display==="none"||s.visibility==="hidden")continue;const a=(i.textContent||"").trim().replace(/\s+/g," ");a.length>2&&a.length<200&&(t.add(i),e.push(a))}}catch{}return e.length===0?"":`
568
- [校验提示] 检测到 ${e.length} 个表单校验错误,请先修复后再继续:
569
- ${e.map((n,i)=>`${i+1}. ${n}`).join(`
570
- `)}
571
- `}async function handleBrowserState(t,e){if(window.__webmcpcli_beforeGetBrowserState)try{window.__webmcpcli_beforeGetBrowserState()}catch(r){console.warn("__webmcpcli_beforeGetBrowserState error:",r)}return e.buildBrowserStateResponse(t.responseMode??"diff")}async function handleClick(t,e){const r=t.responseMode??"diff";if(t.index===void 0)return e.errContent("点击结果: 缺少元素索引");const n=e.getRefMap().get(t.index);if(!n)return e.refreshOnStaleRef("点击",t.index);let i=n;if(n.shadowRoot&&!(n instanceof HTMLButtonElement)&&!(n instanceof HTMLAnchorElement)){const o=n.shadowRoot.querySelector('button, a, [role="button"], [role="link"]');o&&(i=o)}return await clickElement(i),await waitForDomSettled(),e.buildBrowserStateResponse(r)}async function handleFill(t,e){const r=t.responseMode??"diff";if(t.index===void 0||typeof t.text!="string")return e.errContent("填写结果: 缺少元素索引或文本内容");const n=e.getRefMap().get(t.index);if(!n)return e.refreshOnStaleRef("填写",t.index);let i=n;if(!(i instanceof HTMLInputElement)&&!(i instanceof HTMLTextAreaElement)){const o=n.querySelector("input, textarea")??n.shadowRoot?.querySelector("input, textarea");o&&(i=o)}if(i instanceof HTMLInputElement&&i.readOnly)i.value=t.text,dispatchComposedEvents(i,"input","change","blur");else{let o=!1;try{await inputTextElement(i,t.text),o=!0}catch{const a=Object.getOwnPropertyDescriptor((i instanceof HTMLTextAreaElement?HTMLTextAreaElement:HTMLInputElement).prototype,"value")?.set;a&&(i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement)&&(a.call(i,t.text),i.dispatchEvent(new Event("focus",{bubbles:!0,composed:!0})),i.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),i.dispatchEvent(new Event("change",{bubbles:!0,composed:!0})),i.dispatchEvent(new Event("blur",{bubbles:!0,composed:!0})),o=!0)}if(!o)return e.errContent(`填写结果: 无法填写元素 ${t.index},元素不是 input、textarea 或 contenteditable`);isInShadowDom(i)&&dispatchComposedEvents(i,"input","change")}return await waitForDomSettled(),e.buildBrowserStateResponse(r)}async function handleSelect(t,e){const r=t.responseMode??"diff";if(t.index===void 0||typeof t.text!="string")return e.errContent("选择结果: 缺少元素索引或文本内容");let n=e.getRefMap().get(t.index);if(!n)return e.refreshOnStaleRef("选择",t.index);let i=null;if(n instanceof HTMLSelectElement)i=n;else{const o=n.querySelector("select")??n.shadowRoot?.querySelector("select");o&&(i=o)}return i?(await selectOptionElement(i,t.text),isInShadowDom(i)&&dispatchComposedEvents(i,"change"),await waitForDomSettled(),e.buildBrowserStateResponse(r)):e.errContent(`选择结果: 无法选择元素 ${t.index},未找到对应的 <select> 元素`)}function getScrollInfo(t=window){if(t===window){const e=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight),r=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth),n=window.scrollY,i=window.scrollX,o=Math.max(0,e-(window.innerHeight+n)),s=Math.max(0,r-(window.innerWidth+i));return{scrollY:n,scrollX:i,pixelsAbove:n,pixelsBelow:o,pixelsLeft:i,pixelsRight:s,pagesAbove:window.innerHeight>0?n/window.innerHeight:0,pagesBelow:window.innerHeight>0?o/window.innerHeight:0,atTop:n<=1,atBottom:o<=1,atLeft:i<=1,atRight:s<=1}}else{const e=t,r=e.scrollTop,n=e.scrollLeft,i=e.scrollHeight-e.clientHeight-r,o=e.scrollWidth-e.clientWidth-n;return{scrollY:r,scrollX:n,pixelsAbove:r,pixelsBelow:Math.max(0,i),pixelsLeft:n,pixelsRight:Math.max(0,o),pagesAbove:e.clientHeight>0?r/e.clientHeight:0,pagesBelow:e.clientHeight>0?Math.max(0,i)/e.clientHeight:0,atTop:r<=1,atBottom:i<=1,atLeft:n<=1,atRight:o<=1}}}function waitForScrollEnd(t,e=2e3){return new Promise(r=>{let n=!1;const i=t===window?document:t,o=()=>{n||(n=!0,i.removeEventListener("scrollend",s),clearTimeout(a),r())},s=()=>o(),a=setTimeout(o,e);i.addEventListener("scrollend",s,{once:!0})})}async function handleScroll(t,e){const r=t.responseMode??"diff";if(t.down===void 0&&t.right===void 0)return e.errContent("滚动结果: 缺少滚动方向参数");let n=window;if(t.index!==void 0){const g=e.getRefMap().get(t.index);if(!g)return e.refreshOnStaleRef("滚动",t.index);n=g}const i=getScrollInfo(n);if(t.right!==void 0){const g=t.pixels??300;n.scrollBy({left:t.right?g:-g,behavior:"smooth"})}else{const g=t.pixels??Math.round((t.numPages??1)*window.innerHeight);n.scrollBy({top:t.down?g:-g,behavior:"smooth"})}await waitForScrollEnd(n);const o=getScrollInfo(n),s=Math.round(o.scrollY-i.scrollY),a=Math.round(o.scrollX-i.scrollX),l=t.right!==void 0;let d;if(Math.abs(s)<1&&Math.abs(a)<1)l?d=t.right?"⚠️ 已到达右边界,无法继续向右滚动":"⚠️ 已到达左边界,无法继续向左滚动":d=t.down?"⚠️ 已到达底部,无法继续向下滚动":"⚠️ 已到达顶部,无法继续向上滚动";else{const g=l?`水平滚动 ${a}px`:`垂直滚动 ${s}px`;let y="";l?t.right&&o.atRight?y=",已到达右边界":!t.right&&o.atLeft&&(y=",已到达左边界"):t.down&&o.atBottom?y=",已到达底部":!t.down&&o.atTop&&(y=",已到达顶部"),d=`✅ ${g}${y}`}const u=t.right!==void 0?`当前水平滚动位置: scrollX=${Math.round(o.scrollX)}px,左侧 ${o.pagesAbove.toFixed(1)} 屏,右侧 ${o.pagesBelow.toFixed(1)} 屏`:`当前滚动位置: scrollY=${Math.round(o.scrollY)}px,上方 ${o.pagesAbove.toFixed(1)} 屏,下方 ${o.pagesBelow.toFixed(1)} 屏`,f=`[滚动结果] ${d}
572
- ${u}`,p=await e.buildBrowserStateResponse(r);return p.content[0].text=`${f}
555
+ `),index:numberType().min(0).optional().describe("执行动作 of the element index, 动作为 click,fill,select时,必须提供元素索引"),text:stringType().optional().describe("执行动作的文本内容, 动作为 fill,select 时,必须提供文本内容"),down:booleanType().optional().describe("执行上下滚动时,必须提供down参数"),right:booleanType().optional().describe("执行水平滚动方向, 必须提供right参数"),numPages:numberType().optional().describe("执行动作的滚动页数, 动作为 scroll时,可以提供滚动页数,建议每次滚动0.1页,该值不要大于5."),pixels:numberType().int().min(0).optional().describe("执行动作的滚动像素数,动作为 scroll时,可以提供滚动像素数"),script:stringType().optional().describe("执行的javascript代码,动作为 executeJavascript时,必须提供script参数"),query:stringType().optional().describe("搜索关键词,动作为 searchTree 时必须提供。支持按 role(如 button、link)、节点名称、状态(如 checked)或 ref 索引(如 #3)搜索"),contextLines:numberType().int().min(0).max(10).default(2).describe("searchTree 时每个命中行前后保留的上下文行数,默认 2"),maxMatches:numberType().int().min(1).max(50).default(20).describe("searchTree 时最大返回分组数,默认 20"),responseMode:enumType(["full","diff","both"]).optional().default("diff").describe("返回浏览器状态的模式。full: 仅返回当前全量 A11y 树;diff: 仅返回与上一次状态的增量差异;both: 同时返回全量 A11y 树与增量差异。默认值为 diff。")}),PAGE_AGENT_TOOL_CALL_EVENT="page-agent-tool-call",PAGE_AGENT_TOOL_RESULT_EVENT="page-agent-tool-result",PAGE_AGENT_CHAT_END_EVENT="page-agent-chat-end";function isPageAgentToolErrorResult(t){return typeof t=="object"&&t!==null&&"isError"in t&&t.isError===!0&&"error"in t&&typeof t.error=="string"}function dispatchPageAgentToolResult(t){window.dispatchEvent(new CustomEvent(PAGE_AGENT_TOOL_RESULT_EVENT,{detail:t}))}function setupPageAgentToolEventBridge(t,e){window.__nextSdkPageAgentToolEventCleanup?.();const r=async i=>{const o=i.detail,s=o?.requestId;if(!s){dispatchPageAgentToolResult({requestId:"",data:{success:!1,error:"缺少 requestId"}});return}try{const a=inputSchema.parse(o.data),l=await t(a);if(isPageAgentToolErrorResult(l)){dispatchPageAgentToolResult({requestId:s,data:{success:!1,error:l.error,result:l}});return}dispatchPageAgentToolResult({requestId:s,data:{success:!0,result:l}})}catch(a){dispatchPageAgentToolResult({requestId:s,data:{success:!1,error:a instanceof Error?a.message:String(a)}})}},n=async()=>{try{await e.hideMask()}catch{}};window.addEventListener(PAGE_AGENT_TOOL_CALL_EVENT,r),window.addEventListener(PAGE_AGENT_CHAT_END_EVENT,n),window.__nextSdkPageAgentToolEventCleanup=()=>{window.removeEventListener(PAGE_AGENT_TOOL_CALL_EVENT,r),window.removeEventListener(PAGE_AGENT_CHAT_END_EVENT,n),window.__nextSdkPageAgentToolEventCleanup=void 0}}async function createActionErrorResult(t,e){try{const r=await e("full");return{isError:!0,error:t,content:[{type:"text",text:`${t}
556
+
557
+ ${r.content[0].text}`}]}}catch(r){return{isError:!0,error:t,content:[{type:"text",text:`${t}
558
+
559
+ 获取最新浏览器状态失败: ${r instanceof Error?r.message:String(r)}`}]}}}async function handleBrowserState(t,e){if(window.__webmcpcli_beforeGetBrowserState)try{window.__webmcpcli_beforeGetBrowserState()}catch(r){console.warn("__webmcpcli_beforeGetBrowserState error:",r)}return e.buildBrowserStateResponse(t.responseMode??"diff")}async function handleClick(t,e){const r=t.responseMode??"diff";if(t.index===void 0)return e.actionError("点击结果: 缺少元素索引");const n=e.getRefMap().get(t.index);if(!n)return e.actionError(`点击失败: ref 索引 ${t.index} 已失效(页面可能已刷新),已自动重新加载页面状态,请使用新的 ref 索引重试。`);let i=n;if(n.shadowRoot&&!(n instanceof HTMLButtonElement)&&!(n instanceof HTMLAnchorElement)){const o=n.shadowRoot.querySelector('button, a, [role="button"], [role="link"]');o&&(i=o)}return await clickElement(i),await waitForDomSettled(),e.buildBrowserStateResponse(r)}async function handleFill(t,e){const r=t.responseMode??"diff";if(t.index===void 0||typeof t.text!="string")return e.actionError("填写结果: 缺少元素索引或文本内容");const n=e.getRefMap().get(t.index);if(!n)return e.actionError(`填写失败: ref 索引 ${t.index} 已失效(页面可能已刷新),已自动重新加载页面状态,请使用新的 ref 索引重试。`);let i=n;if(!(i instanceof HTMLInputElement)&&!(i instanceof HTMLTextAreaElement)){const o=n.querySelector("input, textarea")??n.shadowRoot?.querySelector("input, textarea");o&&(i=o)}if(i instanceof HTMLInputElement&&i.readOnly)i.value=t.text,dispatchComposedEvents(i,"input","change","blur");else{let o=!1;try{await inputTextElement(i,t.text),o=!0}catch{const a=Object.getOwnPropertyDescriptor((i instanceof HTMLTextAreaElement?HTMLTextAreaElement:HTMLInputElement).prototype,"value")?.set;a&&(i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement)&&(a.call(i,t.text),i.dispatchEvent(new Event("focus",{bubbles:!0,composed:!0})),i.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),i.dispatchEvent(new Event("change",{bubbles:!0,composed:!0})),i.dispatchEvent(new Event("blur",{bubbles:!0,composed:!0})),o=!0)}if(!o)return e.actionError(`填写结果: 无法填写元素 ${t.index},元素不是 input、textarea 或 contenteditable`);isInShadowDom(i)&&dispatchComposedEvents(i,"input","change")}return await waitForDomSettled(),e.buildBrowserStateResponse(r)}async function handleSelect(t,e){const r=t.responseMode??"diff";if(t.index===void 0||typeof t.text!="string")return e.actionError("选择结果: 缺少元素索引或文本内容");let n=e.getRefMap().get(t.index);if(!n)return e.actionError(`选择失败: ref 索引 ${t.index} 已失效(页面可能已刷新),已自动重新加载页面状态,请使用新的 ref 索引重试。`);let i=null;if(n instanceof HTMLSelectElement)i=n;else{const o=n.querySelector("select")??n.shadowRoot?.querySelector("select");o&&(i=o)}return i?(await selectOptionElement(i,t.text),isInShadowDom(i)&&dispatchComposedEvents(i,"change"),await waitForDomSettled(),e.buildBrowserStateResponse(r)):e.actionError(`选择结果: 无法选择元素 ${t.index},未找到对应的 <select> 元素`)}function getScrollInfo(t=window){if(t===window){const e=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight),r=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth),n=window.scrollY,i=window.scrollX,o=Math.max(0,e-(window.innerHeight+n)),s=Math.max(0,r-(window.innerWidth+i));return{scrollY:n,scrollX:i,pixelsAbove:n,pixelsBelow:o,pixelsLeft:i,pixelsRight:s,pagesAbove:window.innerHeight>0?n/window.innerHeight:0,pagesBelow:window.innerHeight>0?o/window.innerHeight:0,atTop:n<=1,atBottom:o<=1,atLeft:i<=1,atRight:s<=1}}else{const e=t,r=e.scrollTop,n=e.scrollLeft,i=e.scrollHeight-e.clientHeight-r,o=e.scrollWidth-e.clientWidth-n;return{scrollY:r,scrollX:n,pixelsAbove:r,pixelsBelow:Math.max(0,i),pixelsLeft:n,pixelsRight:Math.max(0,o),pagesAbove:e.clientHeight>0?r/e.clientHeight:0,pagesBelow:e.clientHeight>0?Math.max(0,i)/e.clientHeight:0,atTop:r<=1,atBottom:i<=1,atLeft:n<=1,atRight:o<=1}}}function waitForScrollEnd(t,e=2e3){return new Promise(r=>{let n=!1;const i=t===window?document:t,o=()=>{n||(n=!0,i.removeEventListener("scrollend",s),clearTimeout(a),r())},s=()=>o(),a=setTimeout(o,e);i.addEventListener("scrollend",s,{once:!0})})}async function handleScroll(t,e){const r=t.responseMode??"diff";if(t.down===void 0&&t.right===void 0)return e.errContent("滚动结果: 缺少滚动方向参数");let n=window;if(t.index!==void 0){const g=e.getRefMap().get(t.index);if(!g)return e.refreshOnStaleRef("滚动",t.index);n=g}const i=getScrollInfo(n);if(t.right!==void 0){const g=t.pixels??300;n.scrollBy({left:t.right?g:-g,behavior:"smooth"})}else{const g=t.pixels??Math.round((t.numPages??1)*window.innerHeight);n.scrollBy({top:t.down?g:-g,behavior:"smooth"})}await waitForScrollEnd(n);const o=getScrollInfo(n),s=Math.round(o.scrollY-i.scrollY),a=Math.round(o.scrollX-i.scrollX),l=t.right!==void 0;let c;if(Math.abs(s)<1&&Math.abs(a)<1)l?c=t.right?"⚠️ 已到达右边界,无法继续向右滚动":"⚠️ 已到达左边界,无法继续向左滚动":c=t.down?"⚠️ 已到达底部,无法继续向下滚动":"⚠️ 已到达顶部,无法继续向上滚动";else{const g=l?`水平滚动 ${a}px`:`垂直滚动 ${s}px`;let b="";l?t.right&&o.atRight?b=",已到达右边界":!t.right&&o.atLeft&&(b=",已到达左边界"):t.down&&o.atBottom?b=",已到达底部":!t.down&&o.atTop&&(b=",已到达顶部"),c=`✅ ${g}${b}`}const u=t.right!==void 0?`当前水平滚动位置: scrollX=${Math.round(o.scrollX)}px,左侧 ${o.pagesAbove.toFixed(1)} 屏,右侧 ${o.pagesBelow.toFixed(1)} 屏`:`当前滚动位置: scrollY=${Math.round(o.scrollY)}px,上方 ${o.pagesAbove.toFixed(1)} 屏,下方 ${o.pagesBelow.toFixed(1)} 屏`,h=`[滚动结果] ${c}
560
+ ${u}`,f=await e.buildBrowserStateResponse(r);return f.content[0].text=`${h}
573
561
 
574
- ${p.content[0].text}`,p}async function handleExecuteJavascript(t,e){if(!t.script)return e.errContent("脚本执行异常: 缺少javascript代码");let r=await new Function(`return (async () => { ${t.script} })()`)();if(r===void 0)try{r=await new Function(`return (async () => (${t.script}))()`)()}catch{}return await e.pageController.hideMask(),{content:[{type:"text",text:`脚本执行结果: ${JSON.stringify(r)}`}]}}async function handleSearchTree(t,e){if(!t.query)return e.errContent("搜索失败: 缺少 query 参数");const r=window.__webmcpcli_interactiveBlacklist??[],n=window.__webmcpcli_interactiveWhitelist??[],i=window.__webmcpcli_exposedAttributes??[],o=searchA11yTree(t.query,document.body,r,n,{contextLines:t.contextLines,maxMatches:t.maxMatches,exposedAttributes:i,errorSelectors:(window.__webmcpcli_errorSelectors??DEFAULT_ERROR_SELECTORS).join(", ")});e.setRefMap(o.refMap),e.stateCache.update(window.location.href,o.yaml),await e.pageController.hideMask();const s=detectPageDialog(),a=detectValidationErrors(),l=`${s}${a}`;return{content:[{type:"text",text:l?`${l}
575
- ${o.text}`:o.text}]}}function registerPageAgentTool(t={}){initializeBuiltinWebMCP(),typeof t.enableHighlight>"u"&&(t.enableHighlight=!0),window.__webmcpcli_interactiveWhitelist=window.__webmcpcli_interactiveWhitelist||[],window.__webmcpcli_interactiveBlacklist=window.__webmcpcli_interactiveBlacklist||[],window.__webmcpcli_exposedAttributes=window.__webmcpcli_exposedAttributes||t?.exposedAttributes||[],window.__webmcpcli_beforeGetBrowserState=window.__webmcpcli_beforeGetBrowserState||null,window.__webmcpcli_errorSelectors=window.__webmcpcli_errorSelectors||DEFAULT_ERROR_SELECTORS,window.__webmcpcli_dialogSelectors=window.__webmcpcli_dialogSelectors||DEFAULT_DIALOG_SELECTORS;const e=new PageController({enableMask:!1});e.maskReady=(async()=>{e.mask=new SimulatorMask$1})();const r=new PageStateCache;let n=new Map;async function i(l){return await e.hideMask(),{content:[{type:"text",text:l}]}}async function o(l,d){const u=await s("full");return{content:[{type:"text",text:`⚠️ ${l}失败: ref 索引 ${d} 已失效(页面可能已刷新),已自动重新加载页面状态,请使用新的 ref 索引重试。
576
- `+u.content[0].text}]}}async function s(l="diff"){const d=window.location.href,u=document.title,f=window.__webmcpcli_interactiveBlacklist??[],p=window.__webmcpcli_interactiveWhitelist??[],g=window.__webmcpcli_exposedAttributes??[],{yaml:y,refMap:Z}=buildA11yTree(document.body,f,p,{exposedAttributes:g,errorSelectors:(window.__webmcpcli_errorSelectors??DEFAULT_ERROR_SELECTORS).join(", ")});n=Z,t?.enableHighlight&&(highlight(Z),globalRemoveListener());const x=r.update(d,y);await e.hideMask();const h=detectPageDialog(),S=detectValidationErrors();let I="";return l==="full"?I=y:l==="diff"?I=x.isFullRefresh?y:x.diffText:l==="both"&&(I=`【全量页面树】:
577
- ${y}
562
+ ${f.content[0].text}`,f}async function handleExecuteJavascript(t,e){if(!t.script)return e.errContent("脚本执行异常: 缺少javascript代码");let r=await new Function(`return (async () => { ${t.script} })()`)();if(r===void 0)try{r=await new Function(`return (async () => (${t.script}))()`)()}catch{}return await e.pageController.hideMask(),{content:[{type:"text",text:`脚本执行结果: ${JSON.stringify(r)}`}]}}async function handleSearchTree(t,e){if(!t.query)return e.errContent("搜索失败: 缺少 query 参数");const r=searchA11yTree(t.query,document.body,{...getPageAgentToolConfig().a11yConfig,contextLines:t.contextLines,maxMatches:t.maxMatches});e.setRefMap(r.refMap),e.stateCache.update(window.location.href,r.yaml),await e.pageController.hideMask();const n=detectPageDialog(),i=detectValidationErrors(),o=`${n}${i}`;return{content:[{type:"text",text:o?`${o}
563
+ ${r.text}`:r.text}]}}function registerPageAgentTool(t={}){initializeBuiltinWebMCP(),setPageAgentToolConfig(t,{mode:"replace"}),window.__webmcpcli_beforeGetBrowserState=window.__webmcpcli_beforeGetBrowserState||null;const e=new PageController({enableMask:!1});e.maskReady=(async()=>{e.mask=new SimulatorMask$1})();const r=new PageStateCache;let n=new Map;async function i(u){return{content:[{type:"text",text:u}]}}async function o(u){const h=await createActionErrorResult(u,a);return t.removeMaskAfterToolCall&&await e.hideMask(),h}async function s(u,h){const f=await a("full");return{content:[{type:"text",text:`⚠️ ${u}失败: ref 索引 ${h} 已失效(页面可能已刷新),已自动重新加载页面状态,请使用新的 ref 索引重试。
564
+ `+f.content[0].text}]}}async function a(u="diff"){const h=window.location.href,f=document.title,{yaml:g,refMap:b}=buildA11yTree(document.body,getPageAgentToolConfig().a11yConfig);n=b,getPageAgentToolConfig().enableHighlight&&(highlight(b),globalRemoveListener());const P=r.update(h,g),w=detectPageDialog(),p=detectValidationErrors();let m="";return u==="full"?m=g:u==="diff"?m=P.isFullRefresh?g:P.diffText:u==="both"&&(m=`【全量页面树】:
565
+ ${g}
578
566
 
579
567
  【增量差异】:
580
- ${x.isFullRefresh?"(首次/刷新,无增量差异)":x.diffText}`),{content:[{type:"text",text:`浏览器状态: ${JSON.stringify({url:d,title:u,content:I})}${h}${S}`}]}}const a={pageController:e,stateCache:r,getRefMap:()=>n,setRefMap:l=>{n=l},buildBrowserStateResponse:s,refreshOnStaleRef:o,errContent:i};document.modelContext.registerTool({name:"page-agent-tool",description:pageAgentPrompt,inputSchema:zodToJsonSchema(inputSchema),async execute(l){await e.showMask();try{switch(l.action){case"browserState":return await handleBrowserState(l,a);case"click":return await handleClick(l,a);case"fill":return await handleFill(l,a);case"select":return await handleSelect(l,a);case"scroll":return await handleScroll(l,a);case"executeJavascript":return await handleExecuteJavascript(l,a);case"searchTree":return await handleSearchTree(l,a);default:return await e.hideMask(),{content:[{type:"text",text:`未知操作: ${l.action}`}]}}}catch(d){return await e.hideMask(),{content:[{type:"text",text:`异常: ${String(d)}`}]}}}})}typeof window<"u"&&(window.initializeBuiltinWebMCP=initializeBuiltinWebMCP,window.registerPageAgentTool=registerPageAgentTool,registerPageAgentTool()),(function(){try{if(typeof document<"u"){var t=document.createElement("style");t.appendChild(document.createTextNode(`._wrapper_1ooyb_1 {
568
+ ${P.isFullRefresh?"(首次/刷新,无增量差异)":P.diffText}`),{content:[{type:"text",text:`浏览器状态: ${JSON.stringify({url:h,title:f,content:m})}${w}${p}`}]}}const l={pageController:e,stateCache:r,getRefMap:()=>n,setRefMap:u=>{n=u},buildBrowserStateResponse:a,refreshOnStaleRef:s,errContent:i,actionError:o};async function c(u){try{let h;switch(u.action){case"browserState":h=await handleBrowserState(u,l);break;case"click":await e.showMask(),e.mask.borderElement(n.get(u.index)),h=await handleClick(u,l),e.mask.removeBorderElement(),t.removeMaskAfterToolCall&&await e.hideMask();break;case"fill":await e.showMask(),e.mask.borderElement(n.get(u.index)),h=await handleFill(u,l),e.mask.removeBorderElement(),t.removeMaskAfterToolCall&&await e.hideMask();break;case"select":await e.showMask(),e.mask.borderElement(n.get(u.index)),h=await handleSelect(u,l),e.mask.removeBorderElement(),t.removeMaskAfterToolCall&&await e.hideMask();break;case"scroll":await e.showMask(),h=await handleScroll(u,l),t.removeMaskAfterToolCall&&await e.hideMask();break;case"executeJavascript":h=await handleExecuteJavascript(u,l);break;case"searchTree":h=await handleSearchTree(u,l);break;default:h={content:[{type:"text",text:`未知操作: ${u.action}`}]}}return h}catch(h){const f={click:"点击",fill:"填写",select:"选择"};if(u.action in f)return o(`${f[u.action]}执行异常: ${h instanceof Error?h.message:String(h)}`);throw t.removeMaskAfterToolCall&&await e.hideMask(),h}}document.modelContext.registerTool({name:"page-agent-tool",description:pageAgentPrompt,inputSchema:zodToJsonSchema(inputSchema),async execute(u){try{return c(u)}catch(h){return{content:[{type:"text",text:`异常: ${String(h)}`}]}}}}),setupPageAgentToolEventBridge(c,e)}const consoleCloudPageAgentToolOptions={enableHighlight:!1,a11yConfig:{roles:[{role:"tablist",selector:"ul.ti3-tabs"},{role:"tab",selector:".ti3-tabs-text"},{role:"tabpanel",selector:["ti-tab.ti3-tab-pane",".ti3-tab-pane"]},{role:"combobox",selector:[".ti3-select-dominator-container",".selected-label",".sort-select",".service-select",".region-select",'[cf-uba="searchableRegion..open"]']},{role:"button",selector:[".modules-service-list-menu-service-icon-container",".ti3-btn-only-icon-noborder",".ti3-select-dominator-dropdown-btn",".modules-right-sidebar-icon-item-wrapper",".modules-right-sidebar-hide-state-plugin",".components-service-list-container-service-list-input-service-close",".modules-searchable-region-region-panel-close",".modules-searchable-region-region-panel-search-btn",'[cf-uba="rightSidebar..hideBtn"]',".ti-global-help-panel-header-icon","ti-icon[name]","tp-icon[name]","tp-icon.common-icon","ti-icon.common-icon","ti-icon.ti3-icon-full-screen","ti-icon.ti3-icon-close","tp-icon.ti3-icon-full-screen","tp-icon.ti3-icon-close"]},{role:"menuitem",selector:[".components-service-list-left-box-sidebar-visit-panel > li",".modules-menus-menu-item",".components-menu-wrapper-menu-text"]},{role:"option",selector:[".region-selector-item",".modules-searchable-region-project-item-region-item",".modules-searchable-region-region-panel-recent-region-item",".ti3-multiselect-box-cell"]}],states:{selected:[{selector:"li.ti3-tab-li.ti3-tab-active"},{selector:".ti3-btn-item-container.ti3-active"},{selector:".components-service-list-left-box-active"},{selector:[".modules-searchable-region-project-item-region-item-selected",".components-search-content-search-select-search-select-selected"]}],hasPopup:[{selector:[".ti3-select-dominator-container",".selected-label",".sort-select",".service-select",".region-select",'[cf-uba="searchableRegion..open"]','[cf-uba="serviceList..open"]','[cf-uba="userinfo"]']}],disabled:[{selector:".ti3-disabled"}],expanded:[{match:t=>{try{if(!t.matches(".modules-layout-module-sidebar-panel, .modules-searchable-region-region-panel, .ti3-dropdown-container"))return!1;const e=window.getComputedStyle(t);return e.display!=="none"&&e.visibility!=="hidden"&&e.opacity!=="0"}catch{return!1}}}]},exposedAttributes:["cf-uba","data-qa-id","name"],whitelist:[".modules-service-list-menu-service-icon-container",".ti3-tabs-text",'[cf-uba="cloudShell"]','[cf-uba="messageBox"]','[cf-uba="helpFeedback"]','[cf-uba="globalMessage"]','[cf-uba="rightSidebar..hideBtn"]',".ti-global-help-panel-header-icon","ti-icon[name]","tp-icon[name]","tp-icon.common-icon","ti-icon.common-icon","ti-icon.ti3-icon-full-screen"],blacklist:["noscript","pan-gu","#J_header"],dialogSelectors:['[class*="ti3-modal"]','[class*="ti3-message-box"]','[class*="drawer"]',".modules-layout-module-sidebar-panel"]}};function isConsoleCloudHost(t=typeof location<"u"?location.hostname:""){return/(^|\.)console\.huaweicloud\.com$/i.test(t)}const runtimeApi={initializeBuiltinWebMCP,registerPageAgentTool,getPageAgentToolConfig,setPageAgentToolConfig,defineA11yConfig,consoleCloudPageAgentToolOptions,isConsoleCloudHost};typeof window<"u"&&(Object.assign(window,runtimeApi),window.WebMCP||(window.WebMCP={}),Object.assign(window.WebMCP,runtimeApi)),(function(){try{if(typeof document<"u"){var t=document.createElement("style");t.appendChild(document.createTextNode(`._wrapper_1ooyb_1 {
581
569
  position: fixed;
582
570
  inset: 0;
583
571
  z-index: 2147483641; /* 确保在所有元素之上,除了 panel */
@@ -741,4 +729,4 @@ ${x.isFullRefresh?"(首次/刷新,无增量差异)":x.diffText}`),{content
741
729
  transform: scale(2);
742
730
  opacity: 0;
743
731
  }
744
- }`)),document.head.appendChild(t)}}catch(e){console.error("vite-plugin-css-injected-by-js",e)}})();function isPageDark(){try{return!!(hasDarkModeClass()||hasDarkModeDataAttribute()||isColorSchemeDark()||isBackgroundDark()||isMainContentBackgroundDark()||isTextColorLight())}catch(t){return console.warn("Error determining if page is dark:",t),!1}}function hasDarkModeClass(){const t=["dark","dark-mode","theme-dark","night","night-mode"],e=document.documentElement,r=document.body||document.documentElement;for(const n of t)if(e.classList.contains(n)||r?.classList.contains(n))return!0;return!1}function hasDarkModeDataAttribute(){const t=document.documentElement,e=document.body||document.documentElement;for(const r of["data-theme","data-color-mode","data-bs-theme","data-mui-color-scheme"]){const n=e?.getAttribute(r),i=t.getAttribute(r);if(n?.toLowerCase()==="dark"||i?.toLowerCase()==="dark")return!0}return!1}function isColorSchemeDark(){const t=document.querySelector('meta[name="color-scheme"]')?.content.toLowerCase();if(t==="dark"||t==="only dark")return!0;const e=window.getComputedStyle(document.documentElement).getPropertyValue("color-scheme").trim().toLowerCase();return e==="dark"||e==="only dark"}function isBackgroundDark(){const t=window.getComputedStyle(document.documentElement),e=window.getComputedStyle(document.body||document.documentElement),r=t.backgroundColor,n=e.backgroundColor;return isColorDark(n)?!0:n==="transparent"||n.startsWith("rgba(0, 0, 0, 0)")?isColorDark(r):!1}function isTextColorLight(){const e=getLuminance(window.getComputedStyle(document.body||document.documentElement).color);return e!==null&&e>200}function isMainContentBackgroundDark(){const{innerWidth:t,innerHeight:e}=window,r=t*e*.5;for(const n of["#app","#root","#__next"]){const i=document.querySelector(n);if(!i)continue;const o=i.getBoundingClientRect();if(!(o.width*o.height<r)&&isColorDark(window.getComputedStyle(i).backgroundColor))return!0}return!1}function parseRgbColor(t){const e=/rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(t);return e?{r:parseInt(e[1]),g:parseInt(e[2]),b:parseInt(e[3])}:null}function getLuminance(t){if(!t||t==="transparent"||t.startsWith("rgba(0, 0, 0, 0)"))return null;const e=parseRgbColor(t);return e?.299*e.r+.587*e.g+.114*e.b:null}function isColorDark(t,e=128){const r=getLuminance(t);return r!==null&&r<e}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;#n=!1;#e=document.createElement("div");#t=0;#r=0;#i=0;#o=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 i=new Motion({mode:isPageDark()?"dark":"light",styles:{position:"absolute",inset:"0"}});this.motion=i,this.wrapper.appendChild(i.element),i.autoResize(this.wrapper)}catch(i){console.warn("[SimulatorMask] Motion overlay unavailable:",i)}this.wrapper.addEventListener("click",i=>{i.stopPropagation(),i.preventDefault()}),this.wrapper.addEventListener("mousedown",i=>{i.stopPropagation(),i.preventDefault()}),this.wrapper.addEventListener("mouseup",i=>{i.stopPropagation(),i.preventDefault()}),this.wrapper.addEventListener("mousemove",i=>{i.stopPropagation(),i.preventDefault()}),this.wrapper.addEventListener("wheel",i=>{i.stopPropagation(),i.preventDefault()}),this.wrapper.addEventListener("keydown",i=>{i.stopPropagation(),i.preventDefault()}),this.wrapper.addEventListener("keyup",i=>{i.stopPropagation(),i.preventDefault()}),this.#a(),document.body.appendChild(this.wrapper),this.#s();const t=i=>{const{x:o,y:s}=i.detail;this.setCursorPosition(o,s)},e=()=>{this.triggerClickAnimation()},r=()=>{this.wrapper.style.pointerEvents="none"},n=()=>{this.wrapper.style.pointerEvents="auto"};window.addEventListener("PageAgent::MovePointerTo",t),window.addEventListener("PageAgent::ClickPointer",e),window.addEventListener("PageAgent::EnablePassThrough",r),window.addEventListener("PageAgent::DisablePassThrough",n),this.addEventListener("dispose",()=>{window.removeEventListener("PageAgent::MovePointerTo",t),window.removeEventListener("PageAgent::ClickPointer",e),window.removeEventListener("PageAgent::EnablePassThrough",r),window.removeEventListener("PageAgent::DisablePassThrough",n)})}#a(){this.#e.className=cursor_module_default.cursor;const t=document.createElement("div");t.className=cursor_module_default.cursorRipple,this.#e.appendChild(t);const e=document.createElement("div");e.className=cursor_module_default.cursorFilling,this.#e.appendChild(e);const r=document.createElement("div");r.className=cursor_module_default.cursorBorder,this.#e.appendChild(r),this.wrapper.appendChild(this.#e)}#s(){if(this.#n)return;const t=this.#t+(this.#i-this.#t)*.2,e=this.#r+(this.#o-this.#r)*.2,r=Math.abs(t-this.#i);r>0&&(r<2?this.#t=this.#i:this.#t=t,this.#e.style.left=`${this.#t}px`);const n=Math.abs(e-this.#o);n>0&&(n<2?this.#r=this.#o:this.#r=e,this.#e.style.top=`${this.#r}px`),requestAnimationFrame(()=>this.#s())}setCursorPosition(t,e){this.#n||(this.#i=t,this.#o=e)}triggerClickAnimation(){this.#n||(this.#e.classList.remove(cursor_module_default.clicking),this.#e.offsetHeight,this.#e.classList.add(cursor_module_default.clicking))}show(){this.shown||this.#n||(this.shown=!0,this.motion?.start(),this.motion?.fadeIn(),this.wrapper.classList.add(SimulatorMask_module_default.visible),this.#t=window.innerWidth/2,this.#r=window.innerHeight/2,this.#i=this.#t,this.#o=this.#r,this.#e.style.left=`${this.#t}px`,this.#e.style.top=`${this.#r}px`)}hide(){!this.shown||this.#n||(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.#n=!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"}));return exports.initializeBuiltinWebMCP=initializeBuiltinWebMCP,exports.registerPageAgentTool=registerPageAgentTool,Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"}),exports})({});
732
+ }`)),document.head.appendChild(t)}}catch(e){console.error("vite-plugin-css-injected-by-js",e)}})();function isPageDark(){try{return!!(hasDarkModeClass()||hasDarkModeDataAttribute()||isColorSchemeDark()||isBackgroundDark()||isMainContentBackgroundDark()||isTextColorLight())}catch(t){return console.warn("Error determining if page is dark:",t),!1}}function hasDarkModeClass(){const t=["dark","dark-mode","theme-dark","night","night-mode"],e=document.documentElement,r=document.body||document.documentElement;for(const n of t)if(e.classList.contains(n)||r?.classList.contains(n))return!0;return!1}function hasDarkModeDataAttribute(){const t=document.documentElement,e=document.body||document.documentElement;for(const r of["data-theme","data-color-mode","data-bs-theme","data-mui-color-scheme"]){const n=e?.getAttribute(r),i=t.getAttribute(r);if(n?.toLowerCase()==="dark"||i?.toLowerCase()==="dark")return!0}return!1}function isColorSchemeDark(){const t=document.querySelector('meta[name="color-scheme"]')?.content.toLowerCase();if(t==="dark"||t==="only dark")return!0;const e=window.getComputedStyle(document.documentElement).getPropertyValue("color-scheme").trim().toLowerCase();return e==="dark"||e==="only dark"}function isBackgroundDark(){const t=window.getComputedStyle(document.documentElement),e=window.getComputedStyle(document.body||document.documentElement),r=t.backgroundColor,n=e.backgroundColor;return isColorDark(n)?!0:n==="transparent"||n.startsWith("rgba(0, 0, 0, 0)")?isColorDark(r):!1}function isTextColorLight(){const e=getLuminance(window.getComputedStyle(document.body||document.documentElement).color);return e!==null&&e>200}function isMainContentBackgroundDark(){const{innerWidth:t,innerHeight:e}=window,r=t*e*.5;for(const n of["#app","#root","#__next"]){const i=document.querySelector(n);if(!i)continue;const o=i.getBoundingClientRect();if(!(o.width*o.height<r)&&isColorDark(window.getComputedStyle(i).backgroundColor))return!0}return!1}function parseRgbColor(t){const e=/rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(t);return e?{r:parseInt(e[1]),g:parseInt(e[2]),b:parseInt(e[3])}:null}function getLuminance(t){if(!t||t==="transparent"||t.startsWith("rgba(0, 0, 0, 0)"))return null;const e=parseRgbColor(t);return e?.299*e.r+.587*e.g+.114*e.b:null}function isColorDark(t,e=128){const r=getLuminance(t);return r!==null&&r<e}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;#n=!1;#e=document.createElement("div");#t=0;#r=0;#i=0;#o=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 i=new Motion({mode:isPageDark()?"dark":"light",styles:{position:"absolute",inset:"0"}});this.motion=i,this.wrapper.appendChild(i.element),i.autoResize(this.wrapper)}catch(i){console.warn("[SimulatorMask] Motion overlay unavailable:",i)}this.wrapper.addEventListener("click",i=>{i.stopPropagation(),i.preventDefault()}),this.wrapper.addEventListener("mousedown",i=>{i.stopPropagation(),i.preventDefault()}),this.wrapper.addEventListener("mouseup",i=>{i.stopPropagation(),i.preventDefault()}),this.wrapper.addEventListener("mousemove",i=>{i.stopPropagation(),i.preventDefault()}),this.wrapper.addEventListener("wheel",i=>{i.stopPropagation(),i.preventDefault()}),this.wrapper.addEventListener("keydown",i=>{i.stopPropagation(),i.preventDefault()}),this.wrapper.addEventListener("keyup",i=>{i.stopPropagation(),i.preventDefault()}),this.#a(),document.body.appendChild(this.wrapper),this.#s();const t=i=>{const{x:o,y:s}=i.detail;this.setCursorPosition(o,s)},e=()=>{this.triggerClickAnimation()},r=()=>{this.wrapper.style.pointerEvents="none"},n=()=>{this.wrapper.style.pointerEvents="auto"};window.addEventListener("PageAgent::MovePointerTo",t),window.addEventListener("PageAgent::ClickPointer",e),window.addEventListener("PageAgent::EnablePassThrough",r),window.addEventListener("PageAgent::DisablePassThrough",n),this.addEventListener("dispose",()=>{window.removeEventListener("PageAgent::MovePointerTo",t),window.removeEventListener("PageAgent::ClickPointer",e),window.removeEventListener("PageAgent::EnablePassThrough",r),window.removeEventListener("PageAgent::DisablePassThrough",n)})}#a(){this.#e.className=cursor_module_default.cursor;const t=document.createElement("div");t.className=cursor_module_default.cursorRipple,this.#e.appendChild(t);const e=document.createElement("div");e.className=cursor_module_default.cursorFilling,this.#e.appendChild(e);const r=document.createElement("div");r.className=cursor_module_default.cursorBorder,this.#e.appendChild(r),this.wrapper.appendChild(this.#e)}#s(){if(this.#n)return;const t=this.#t+(this.#i-this.#t)*.2,e=this.#r+(this.#o-this.#r)*.2,r=Math.abs(t-this.#i);r>0&&(r<2?this.#t=this.#i:this.#t=t,this.#e.style.left=`${this.#t}px`);const n=Math.abs(e-this.#o);n>0&&(n<2?this.#r=this.#o:this.#r=e,this.#e.style.top=`${this.#r}px`),requestAnimationFrame(()=>this.#s())}setCursorPosition(t,e){this.#n||(this.#i=t,this.#o=e)}triggerClickAnimation(){this.#n||(this.#e.classList.remove(cursor_module_default.clicking),this.#e.offsetHeight,this.#e.classList.add(cursor_module_default.clicking))}show(){this.shown||this.#n||(this.shown=!0,this.motion?.start(),this.motion?.fadeIn(),this.wrapper.classList.add(SimulatorMask_module_default.visible),this.#t=window.innerWidth/2,this.#r=window.innerHeight/2,this.#i=this.#t,this.#o=this.#r,this.#e.style.left=`${this.#t}px`,this.#e.style.top=`${this.#r}px`)}hide(){!this.shown||this.#n||(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.#n=!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"}));return exports.consoleCloudPageAgentToolOptions=consoleCloudPageAgentToolOptions,exports.defineA11yConfig=defineA11yConfig,exports.getPageAgentToolConfig=getPageAgentToolConfig,exports.initializeBuiltinWebMCP=initializeBuiltinWebMCP,exports.isConsoleCloudHost=isConsoleCloudHost,exports.registerPageAgentTool=registerPageAgentTool,exports.setPageAgentToolConfig=setPageAgentToolConfig,Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"}),exports})({});