@aprovan/mcp-app-server 0.1.0-dev.4d82df8

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 (53) hide show
  1. package/.turbo/turbo-build.log +23 -0
  2. package/E2E_TESTING.md +224 -0
  3. package/LICENSE +373 -0
  4. package/README.md +164 -0
  5. package/dist/index.d.ts +128 -0
  6. package/dist/index.js +990 -0
  7. package/dist/index.js.map +1 -0
  8. package/dist/runtime/assets/__vite-browser-external-BIHI7g3E.js +1 -0
  9. package/dist/runtime/assets/index-tRNuU9ap.js +1059 -0
  10. package/dist/runtime/index.html +38 -0
  11. package/dist/server.d.ts +6 -0
  12. package/dist/server.js +1511 -0
  13. package/dist/server.js.map +1 -0
  14. package/dist/shell/shell.js +67 -0
  15. package/docs/widget-preview.png +0 -0
  16. package/e2e/__snapshots__/.gitkeep +0 -0
  17. package/e2e/global-setup.ts +114 -0
  18. package/e2e/global-teardown.ts +15 -0
  19. package/e2e/visual-regression.test.ts +86 -0
  20. package/e2e/widget-smoke.test.ts +109 -0
  21. package/index.html +32 -0
  22. package/package.json +51 -0
  23. package/playwright.config.ts +43 -0
  24. package/src/__tests__/live-update.test.ts +158 -0
  25. package/src/__tests__/local-backend.test.ts +100 -0
  26. package/src/__tests__/memory-backend.ts +144 -0
  27. package/src/__tests__/registry-backend.test.ts +256 -0
  28. package/src/__tests__/services.test.ts +153 -0
  29. package/src/__tests__/shim.test.ts +60 -0
  30. package/src/__tests__/widget-store.test.ts +188 -0
  31. package/src/e2e-visual.ts +148 -0
  32. package/src/index.ts +608 -0
  33. package/src/live-update.ts +150 -0
  34. package/src/logger.ts +44 -0
  35. package/src/reference-widgets/live-dashboard.ts +162 -0
  36. package/src/registry-backend.ts +306 -0
  37. package/src/runtime/index.html +38 -0
  38. package/src/runtime/main.ts +164 -0
  39. package/src/scripts/export-artifacts.ts +51 -0
  40. package/src/server.ts +398 -0
  41. package/src/services.ts +307 -0
  42. package/src/shell/main.ts +172 -0
  43. package/src/shim.ts +106 -0
  44. package/src/tunnel.ts +123 -0
  45. package/src/widget-store/index.ts +10 -0
  46. package/src/widget-store/local-backend.ts +77 -0
  47. package/src/widget-store/store.ts +242 -0
  48. package/src/widget-store/types.ts +53 -0
  49. package/tsconfig.json +10 -0
  50. package/tsup.config.ts +14 -0
  51. package/vite.runtime.config.ts +28 -0
  52. package/vite.shell.config.ts +30 -0
  53. package/vitest.config.ts +7 -0
@@ -0,0 +1,1059 @@
1
+ var jr=Object.defineProperty;var Cr=(n,e,t)=>e in n?jr(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var ze=(n,e,t)=>Cr(n,typeof e!="symbol"?e+"":e,t);const Tr=(function(){const e=typeof document<"u"&&document.createElement("link").relList;return e&&e.supports&&e.supports("modulepreload")?"modulepreload":"preload"})(),Or=function(n,e){return new URL(n,e).href},yn={},Dt=function(e,t,r){let s=Promise.resolve();if(t&&t.length>0){let c=function(A){return Promise.all(A.map(G=>Promise.resolve(G).then(ce=>({status:"fulfilled",value:ce}),ce=>({status:"rejected",reason:ce}))))};const d=document.getElementsByTagName("link"),w=document.querySelector("meta[property=csp-nonce]"),C=(w==null?void 0:w.nonce)||(w==null?void 0:w.getAttribute("nonce"));s=c(t.map(A=>{if(A=Or(A,r),A in yn)return;yn[A]=!0;const G=A.endsWith(".css"),ce=G?'[rel="stylesheet"]':"";if(!!r)for(let fe=d.length-1;fe>=0;fe--){const xe=d[fe];if(xe.href===A&&(!G||xe.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${A}"]${ce}`))return;const K=document.createElement("link");if(K.rel=G?"stylesheet":Tr,G||(K.as="script"),K.crossOrigin="",K.href=A,C&&K.setAttribute("nonce",C),document.head.appendChild(K),G)return new Promise((fe,xe)=>{K.addEventListener("load",fe),K.addEventListener("error",()=>xe(new Error(`Unable to preload CSS for ${A}`)))})}))}function i(c){const d=new Event("vite:preloadError",{cancelable:!0});if(d.payload=c,window.dispatchEvent(d),!d.defaultPrevented)throw c}return s.then(c=>{for(const d of c||[])d.status==="rejected"&&i(d.reason);return e().catch(i)})};var Ft={exports:{}},vn;function $r(){return vn||(vn=1,(function(n){(e=>{var t=Object.defineProperty,r=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,c=(a,o)=>{for(var u in o)t(a,u,{get:o[u],enumerable:!0})},d=(a,o,u,p)=>{if(o&&typeof o=="object"||typeof o=="function")for(let k of s(o))!i.call(a,k)&&k!==u&&t(a,k,{get:()=>o[k],enumerable:!(p=r(o,k))||p.enumerable});return a},w=a=>d(t({},"__esModule",{value:!0}),a),C=(a,o,u)=>new Promise((p,k)=>{var E=m=>{try{$(u.next(m))}catch(O){k(O)}},_=m=>{try{$(u.throw(m))}catch(O){k(O)}},$=m=>m.done?p(m.value):Promise.resolve(m.value).then(E,_);$((u=u.apply(a,o)).next())}),A={};c(A,{analyzeMetafile:()=>pr,analyzeMetafileSync:()=>wr,build:()=>dr,buildSync:()=>gr,context:()=>fr,default:()=>kr,formatMessages:()=>mr,formatMessagesSync:()=>vr,initialize:()=>br,stop:()=>_r,transform:()=>hr,transformSync:()=>yr,version:()=>ur}),e.exports=w(A);function G(a){let o=p=>{if(p===null)u.write8(0);else if(typeof p=="boolean")u.write8(1),u.write8(+p);else if(typeof p=="number")u.write8(2),u.write32(p|0);else if(typeof p=="string")u.write8(3),u.write(K(p));else if(p instanceof Uint8Array)u.write8(4),u.write(p);else if(p instanceof Array){u.write8(5),u.write32(p.length);for(let k of p)o(k)}else{let k=Object.keys(p);u.write8(6),u.write32(k.length);for(let E of k)u.write(K(E)),o(p[E])}},u=new ue;return u.write32(0),u.write32(a.id<<1|+!a.isRequest),o(a.value),Ne(u.buf,u.len-4,0),u.buf.subarray(0,u.len)}function ce(a){let o=()=>{switch(u.read8()){case 0:return null;case 1:return!!u.read8();case 2:return u.read32();case 3:return fe(u.read());case 4:return u.read();case 5:{let _=u.read32(),$=[];for(let m=0;m<_;m++)$.push(o());return $}case 6:{let _=u.read32(),$={};for(let m=0;m<_;m++)$[fe(u.read())]=o();return $}default:throw new Error("Invalid packet")}},u=new ue(a),p=u.read32(),k=(p&1)===0;p>>>=1;let E=o();if(u.ptr!==a.length)throw new Error("Invalid packet");return{id:p,isRequest:k,value:E}}var ue=class{constructor(a=new Uint8Array(1024)){this.buf=a,this.len=0,this.ptr=0}_write(a){if(this.len+a>this.buf.length){let o=new Uint8Array((this.len+a)*2);o.set(this.buf),this.buf=o}return this.len+=a,this.len-a}write8(a){let o=this._write(1);this.buf[o]=a}write32(a){let o=this._write(4);Ne(this.buf,a,o)}write(a){let o=this._write(4+a.length);Ne(this.buf,a.length,o),this.buf.set(a,o+4)}_read(a){if(this.ptr+a>this.buf.length)throw new Error("Invalid packet");return this.ptr+=a,this.ptr-a}read8(){return this.buf[this._read(1)]}read32(){return Oe(this.buf,this._read(4))}read(){let a=this.read32(),o=new Uint8Array(a),u=this._read(o.length);return o.set(this.buf.subarray(u,u+a)),o}},K,fe,xe;if(typeof TextEncoder<"u"&&typeof TextDecoder<"u"){let a=new TextEncoder,o=new TextDecoder;K=u=>a.encode(u),fe=u=>o.decode(u),xe='new TextEncoder().encode("")'}else if(typeof Buffer<"u")K=a=>Buffer.from(a),fe=a=>{let{buffer:o,byteOffset:u,byteLength:p}=a;return Buffer.from(o,u,p).toString()},xe='Buffer.from("")';else throw new Error("No UTF-8 codec found");if(!(K("")instanceof Uint8Array))throw new Error(`Invariant violation: "${xe} instanceof Uint8Array" is incorrectly false
2
+
3
+ This indicates that your JavaScript environment is broken. You cannot use
4
+ esbuild in this environment because esbuild relies on this invariant. This
5
+ is not a problem with esbuild. You need to fix your environment instead.
6
+ `);function Oe(a,o){return(a[o++]|a[o++]<<8|a[o++]<<16|a[o++]<<24)>>>0}function Ne(a,o,u){a[u++]=o,a[u++]=o>>8,a[u++]=o>>16,a[u++]=o>>24}var Ee=String.fromCharCode;function he(a,o,u){const p=a[o];let k=1,E=0;for(let _=0;_<o;_++)a[_]===10?(k++,E=0):E++;throw new SyntaxError(u||(o===a.length?"Unexpected end of input while parsing JSON":p>=32&&p<=126?`Unexpected character ${Ee(p)} in JSON at position ${o} (line ${k}, column ${E})`:`Unexpected byte 0x${p.toString(16)} in JSON at position ${o} (line ${k}, column ${E})`))}function Ue(a){if(!(a instanceof Uint8Array))throw new Error("JSON input must be a Uint8Array");const o=[],u=[],p=[],k=a.length;let E=null,_=0,$,m=0;for(;m<k;){let O=a[m++];if(O<=32)continue;let N;switch(_===2&&E===null&&O!==34&&O!==125&&he(a,--m),O){case 116:{(a[m++]!==114||a[m++]!==117||a[m++]!==101)&&he(a,--m),N=!0;break}case 102:{(a[m++]!==97||a[m++]!==108||a[m++]!==115||a[m++]!==101)&&he(a,--m),N=!1;break}case 110:{(a[m++]!==117||a[m++]!==108||a[m++]!==108)&&he(a,--m),N=null;break}case 45:case 46:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:{let V=m;for(N=Ee(O),O=a[m];;){switch(O){case 43:case 45:case 46:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 101:case 69:{N+=Ee(O),O=a[++m];continue}}break}N=+N,isNaN(N)&&he(a,--V,"Invalid number");break}case 34:{for(N="";m>=k&&he(a,k),O=a[m++],O!==34;)if(O===92)switch(a[m++]){case 34:N+='"';break;case 47:N+="/";break;case 92:N+="\\";break;case 98:N+="\b";break;case 102:N+="\f";break;case 110:N+=`
7
+ `;break;case 114:N+="\r";break;case 116:N+=" ";break;case 117:{let V=0;for(let ne=0;ne<4;ne++)O=a[m++],V<<=4,O>=48&&O<=57?V|=O-48:O>=97&&O<=102?V|=O+-87:O>=65&&O<=70?V|=O+-55:he(a,--m);N+=Ee(V);break}default:he(a,--m);break}else if(O<=127)N+=Ee(O);else if((O&224)===192)N+=Ee((O&31)<<6|a[m++]&63);else if((O&240)===224)N+=Ee((O&15)<<12|(a[m++]&63)<<6|a[m++]&63);else if((O&248)==240){let V=(O&7)<<18|(a[m++]&63)<<12|(a[m++]&63)<<6|a[m++]&63;V>65535&&(V-=65536,N+=Ee(V>>10&1023|55296),V=56320|V&1023),N+=Ee(V)}N[0];break}case 91:{N=[],o.push(E),u.push($),p.push(_),E=null,$=N,_=1;continue}case 123:{N={},o.push(E),u.push($),p.push(_),E=null,$=N,_=2;continue}case 93:{_!==1&&he(a,--m),N=$,E=o.pop(),$=u.pop(),_=p.pop();break}case 125:{_!==2&&he(a,--m),N=$,E=o.pop(),$=u.pop(),_=p.pop();break}default:he(a,--m)}for(O=a[m];O<=32;)O=a[++m];switch(_){case 0:{if(m===k)return N;break}case 1:{if($.push(N),O===44){m++;continue}if(O===93)continue;break}case 2:{if(E===null){if(E=N,O===58){m++;continue}}else{if($[E]=N,E=null,O===44){m++;continue}if(O===125)continue}break}}break}he(a,m)}var ge=JSON.stringify,Ge="warning",me="silent";function we(a,o){const u=[];for(const p of a){if(Ce(p,o),p.indexOf(",")>=0)throw new Error(`Invalid ${o}: ${p}`);u.push(p)}return u.join(",")}var Ie=()=>null,le=a=>typeof a=="boolean"?null:"a boolean",L=a=>typeof a=="string"?null:"a string",Et=a=>a instanceof RegExp?null:"a RegExp object",Ke=a=>typeof a=="number"&&a===(a|0)?null:"an integer",Yn=a=>typeof a=="number"&&a===(a|0)&&a>=0&&a<=65535?null:"a valid port number",on=a=>typeof a=="function"?null:"a function",Fe=a=>Array.isArray(a)?null:"an array",je=a=>Array.isArray(a)&&a.every(o=>typeof o=="string")?null:"an array of strings",$e=a=>typeof a=="object"&&a!==null&&!Array.isArray(a)?null:"an object",Xn=a=>typeof a=="object"&&a!==null?null:"an array or an object",Kn=a=>a instanceof WebAssembly.Module?null:"a WebAssembly.Module",ln=a=>typeof a=="object"&&!Array.isArray(a)?null:"an object or null",cn=a=>typeof a=="string"||typeof a=="boolean"?null:"a string or a boolean",Qn=a=>typeof a=="string"||typeof a=="object"&&a!==null&&!Array.isArray(a)?null:"a string or an object",un=a=>typeof a=="string"||Array.isArray(a)&&a.every(o=>typeof o=="string")?null:"a string or an array of strings",dn=a=>typeof a=="string"||a instanceof Uint8Array?null:"a string or a Uint8Array",er=a=>typeof a=="string"||a instanceof URL?null:"a string or a URL";function h(a,o,u,p){let k=a[u];if(o[u+""]=!0,k===void 0)return;let E=p(k);if(E!==null)throw new Error(`${ge(u)} must be ${E}`);return k}function _e(a,o,u){for(let p in a)if(!(p in o))throw new Error(`Invalid option ${u}: ${ge(p)}`)}function tr(a){let o=Object.create(null),u=h(a,o,"wasmURL",er),p=h(a,o,"wasmModule",Kn),k=h(a,o,"worker",le);return _e(a,o,"in initialize() call"),{wasmURL:u,wasmModule:p,worker:k}}function fn(a){let o;if(a!==void 0){o=Object.create(null);for(let u in a){let p=a[u];if(typeof p=="string"||p===!1)o[u]=p;else throw new Error(`Expected ${ge(u)} in mangle cache to map to either a string or false`)}}return o}function St(a,o,u,p,k){let E=h(o,u,"color",le),_=h(o,u,"logLevel",L),$=h(o,u,"logLimit",Ke);E!==void 0?a.push(`--color=${E}`):p&&a.push("--color=true"),a.push(`--log-level=${_||k}`),a.push(`--log-limit=${$||0}`)}function Ce(a,o,u){if(typeof a!="string")throw new Error(`Expected value for ${o}${u!==void 0?" "+ge(u):""} to be a string, got ${typeof a} instead`);return a}function hn(a,o,u){let p=h(o,u,"legalComments",L),k=h(o,u,"sourceRoot",L),E=h(o,u,"sourcesContent",le),_=h(o,u,"target",un),$=h(o,u,"format",L),m=h(o,u,"globalName",L),O=h(o,u,"mangleProps",Et),N=h(o,u,"reserveProps",Et),V=h(o,u,"mangleQuoted",le),ne=h(o,u,"minify",le),Q=h(o,u,"minifySyntax",le),se=h(o,u,"minifyWhitespace",le),ie=h(o,u,"minifyIdentifiers",le),z=h(o,u,"lineLimit",Ke),ye=h(o,u,"drop",je),W=h(o,u,"dropLabels",je),B=h(o,u,"charset",L),T=h(o,u,"treeShaking",le),b=h(o,u,"ignoreAnnotations",le),f=h(o,u,"jsx",L),y=h(o,u,"jsxFactory",L),x=h(o,u,"jsxFragment",L),I=h(o,u,"jsxImportSource",L),D=h(o,u,"jsxDev",le),v=h(o,u,"jsxSideEffects",le),S=h(o,u,"define",$e),U=h(o,u,"logOverride",$e),l=h(o,u,"supported",$e),g=h(o,u,"pure",je),P=h(o,u,"keepNames",le),R=h(o,u,"platform",L),H=h(o,u,"tsconfigRaw",Qn),pe=h(o,u,"absPaths",je);if(p&&a.push(`--legal-comments=${p}`),k!==void 0&&a.push(`--source-root=${k}`),E!==void 0&&a.push(`--sources-content=${E}`),_&&a.push(`--target=${we(Array.isArray(_)?_:[_],"target")}`),$&&a.push(`--format=${$}`),m&&a.push(`--global-name=${m}`),R&&a.push(`--platform=${R}`),H&&a.push(`--tsconfig-raw=${typeof H=="string"?H:JSON.stringify(H)}`),ne&&a.push("--minify"),Q&&a.push("--minify-syntax"),se&&a.push("--minify-whitespace"),ie&&a.push("--minify-identifiers"),z&&a.push(`--line-limit=${z}`),B&&a.push(`--charset=${B}`),T!==void 0&&a.push(`--tree-shaking=${T}`),b&&a.push("--ignore-annotations"),ye)for(let F of ye)a.push(`--drop:${Ce(F,"drop")}`);if(W&&a.push(`--drop-labels=${we(W,"drop label")}`),pe&&a.push(`--abs-paths=${we(pe,"abs paths")}`),O&&a.push(`--mangle-props=${Tt(O)}`),N&&a.push(`--reserve-props=${Tt(N)}`),V!==void 0&&a.push(`--mangle-quoted=${V}`),f&&a.push(`--jsx=${f}`),y&&a.push(`--jsx-factory=${y}`),x&&a.push(`--jsx-fragment=${x}`),I&&a.push(`--jsx-import-source=${I}`),D&&a.push("--jsx-dev"),v&&a.push("--jsx-side-effects"),S)for(let F in S){if(F.indexOf("=")>=0)throw new Error(`Invalid define: ${F}`);a.push(`--define:${F}=${Ce(S[F],"define",F)}`)}if(U)for(let F in U){if(F.indexOf("=")>=0)throw new Error(`Invalid log override: ${F}`);a.push(`--log-override:${F}=${Ce(U[F],"log override",F)}`)}if(l)for(let F in l){if(F.indexOf("=")>=0)throw new Error(`Invalid supported: ${F}`);const ae=l[F];if(typeof ae!="boolean")throw new Error(`Expected value for supported ${ge(F)} to be a boolean, got ${typeof ae} instead`);a.push(`--supported:${F}=${ae}`)}if(g)for(let F of g)a.push(`--pure:${Ce(F,"pure")}`);P&&a.push("--keep-names")}function nr(a,o,u,p,k){var E;let _=[],$=[],m=Object.create(null),O=null,N=null;St(_,o,m,u,p),hn(_,o,m);let V=h(o,m,"sourcemap",cn),ne=h(o,m,"bundle",le),Q=h(o,m,"splitting",le),se=h(o,m,"preserveSymlinks",le),ie=h(o,m,"metafile",le),z=h(o,m,"outfile",L),ye=h(o,m,"outdir",L),W=h(o,m,"outbase",L),B=h(o,m,"tsconfig",L),T=h(o,m,"resolveExtensions",je),b=h(o,m,"nodePaths",je),f=h(o,m,"mainFields",je),y=h(o,m,"conditions",je),x=h(o,m,"external",je),I=h(o,m,"packages",L),D=h(o,m,"alias",$e),v=h(o,m,"loader",$e),S=h(o,m,"outExtension",$e),U=h(o,m,"publicPath",L),l=h(o,m,"entryNames",L),g=h(o,m,"chunkNames",L),P=h(o,m,"assetNames",L),R=h(o,m,"inject",je),H=h(o,m,"banner",$e),pe=h(o,m,"footer",$e),F=h(o,m,"entryPoints",Xn),ae=h(o,m,"absWorkingDir",L),re=h(o,m,"stdin",$e),te=(E=h(o,m,"write",le))!=null?E:k,Te=h(o,m,"allowOverwrite",le),be=h(o,m,"mangleCache",$e);if(m.plugins=!0,_e(o,m,`in ${a}() call`),V&&_.push(`--sourcemap${V===!0?"":`=${V}`}`),ne&&_.push("--bundle"),Te&&_.push("--allow-overwrite"),Q&&_.push("--splitting"),se&&_.push("--preserve-symlinks"),ie&&_.push("--metafile"),z&&_.push(`--outfile=${z}`),ye&&_.push(`--outdir=${ye}`),W&&_.push(`--outbase=${W}`),B&&_.push(`--tsconfig=${B}`),I&&_.push(`--packages=${I}`),T&&_.push(`--resolve-extensions=${we(T,"resolve extension")}`),U&&_.push(`--public-path=${U}`),l&&_.push(`--entry-names=${l}`),g&&_.push(`--chunk-names=${g}`),P&&_.push(`--asset-names=${P}`),f&&_.push(`--main-fields=${we(f,"main field")}`),y&&_.push(`--conditions=${we(y,"condition")}`),x)for(let J of x)_.push(`--external:${Ce(J,"external")}`);if(D)for(let J in D){if(J.indexOf("=")>=0)throw new Error(`Invalid package name in alias: ${J}`);_.push(`--alias:${J}=${Ce(D[J],"alias",J)}`)}if(H)for(let J in H){if(J.indexOf("=")>=0)throw new Error(`Invalid banner file type: ${J}`);_.push(`--banner:${J}=${Ce(H[J],"banner",J)}`)}if(pe)for(let J in pe){if(J.indexOf("=")>=0)throw new Error(`Invalid footer file type: ${J}`);_.push(`--footer:${J}=${Ce(pe[J],"footer",J)}`)}if(R)for(let J of R)_.push(`--inject:${Ce(J,"inject")}`);if(v)for(let J in v){if(J.indexOf("=")>=0)throw new Error(`Invalid loader extension: ${J}`);_.push(`--loader:${J}=${Ce(v[J],"loader",J)}`)}if(S)for(let J in S){if(J.indexOf("=")>=0)throw new Error(`Invalid out extension: ${J}`);_.push(`--out-extension:${J}=${Ce(S[J],"out extension",J)}`)}if(F)if(Array.isArray(F))for(let J=0,Ze=F.length;J<Ze;J++){let Re=F[J];if(typeof Re=="object"&&Re!==null){let Me=Object.create(null),We=h(Re,Me,"in",L),Ae=h(Re,Me,"out",L);if(_e(Re,Me,"in entry point at index "+J),We===void 0)throw new Error('Missing property "in" for entry point at index '+J);if(Ae===void 0)throw new Error('Missing property "out" for entry point at index '+J);$.push([Ae,We])}else $.push(["",Ce(Re,"entry point at index "+J)])}else for(let J in F)$.push([J,Ce(F[J],"entry point",J)]);if(re){let J=Object.create(null),Ze=h(re,J,"contents",dn),Re=h(re,J,"resolveDir",L),Me=h(re,J,"sourcefile",L),We=h(re,J,"loader",L);_e(re,J,'in "stdin" object'),Me&&_.push(`--sourcefile=${Me}`),We&&_.push(`--loader=${We}`),Re&&(N=Re),typeof Ze=="string"?O=K(Ze):Ze instanceof Uint8Array&&(O=Ze)}let Be=[];if(b)for(let J of b)J+="",Be.push(J);return{entries:$,flags:_,write:te,stdinContents:O,stdinResolveDir:N,absWorkingDir:ae,nodePaths:Be,mangleCache:fn(be)}}function rr(a,o,u,p){let k=[],E=Object.create(null);St(k,o,E,u,p),hn(k,o,E);let _=h(o,E,"sourcemap",cn),$=h(o,E,"sourcefile",L),m=h(o,E,"loader",L),O=h(o,E,"banner",L),N=h(o,E,"footer",L),V=h(o,E,"mangleCache",$e);return _e(o,E,`in ${a}() call`),_&&k.push(`--sourcemap=${_===!0?"external":_}`),$&&k.push(`--sourcefile=${$}`),m&&k.push(`--loader=${m}`),O&&k.push(`--banner=${O}`),N&&k.push(`--footer=${N}`),{flags:k,mangleCache:fn(V)}}function sr(a){const o={},u={didClose:!1,reason:""};let p={},k=0,E=0,_=new Uint8Array(16*1024),$=0,m=B=>{let T=$+B.length;if(T>_.length){let f=new Uint8Array(T*2);f.set(_),_=f}_.set(B,$),$+=B.length;let b=0;for(;b+4<=$;){let f=Oe(_,b);if(b+4+f>$)break;b+=4,se(_.subarray(b,b+f)),b+=f}b>0&&(_.copyWithin(0,b,$),$-=b)},O=B=>{u.didClose=!0,B&&(u.reason=": "+(B.message||B));const T="The service was stopped"+u.reason;for(let b in p)p[b](T,null);p={}},N=(B,T,b)=>{if(u.didClose)return b("The service is no longer running"+u.reason,null);let f=k++;p[f]=(y,x)=>{try{b(y,x)}finally{B&&B.unref()}},B&&B.ref(),a.writeToStdin(G({id:f,isRequest:!0,value:T}))},V=(B,T)=>{if(u.didClose)throw new Error("The service is no longer running"+u.reason);a.writeToStdin(G({id:B,isRequest:!1,value:T}))},ne=(B,T)=>C(null,null,function*(){try{if(T.command==="ping"){V(B,{});return}if(typeof T.key=="number"){const b=o[T.key];if(!b)return;const f=b[T.command];if(f){yield f(B,T);return}}throw new Error("Invalid command: "+T.command)}catch(b){const f=[Qe(b,a,null,void 0,"")];try{V(B,{errors:f})}catch{}}}),Q=!0,se=B=>{if(Q){Q=!1;let b=String.fromCharCode(...B);if(b!=="0.27.7")throw new Error(`Cannot start service: Host version "0.27.7" does not match binary version ${ge(b)}`);return}let T=ce(B);if(T.isRequest)ne(T.id,T.value);else{let b=p[T.id];delete p[T.id],T.value.error?b(T.value.error,{}):b(null,T.value)}};return{readFromStdout:m,afterClose:O,service:{buildOrContext:({callName:B,refs:T,options:b,isTTY:f,defaultWD:y,callback:x})=>{let I=0;const D=E++,v={},S={ref(){++I===1&&T&&T.ref()},unref(){--I===0&&(delete o[D],T&&T.unref())}};o[D]=v,S.ref(),ir(B,D,N,V,S,a,v,b,f,y,(U,l)=>{try{x(U,l)}finally{S.unref()}})},transform:({callName:B,refs:T,input:b,options:f,isTTY:y,fs:x,callback:I})=>{const D=mn();let v=S=>{try{if(typeof b!="string"&&!(b instanceof Uint8Array))throw new Error('The input to "transform" must be a string or a Uint8Array');let{flags:U,mangleCache:l}=rr(B,f,y,me),g={command:"transform",flags:U,inputFS:S!==null,input:S!==null?K(S):typeof b=="string"?K(b):b};l&&(g.mangleCache=l),N(T,g,(P,R)=>{if(P)return I(new Error(P),null);let H=st(R.errors,D),pe=st(R.warnings,D),F=1,ae=()=>{if(--F===0){let re={warnings:pe,code:R.code,map:R.map,mangleCache:void 0,legalComments:void 0};"legalComments"in R&&(re.legalComments=R==null?void 0:R.legalComments),R.mangleCache&&(re.mangleCache=R==null?void 0:R.mangleCache),I(null,re)}};if(H.length>0)return I(ft("Transform failed",H,pe),null);R.codeFS&&(F++,x.readFile(R.code,(re,te)=>{re!==null?I(re,null):(R.code=te,ae())})),R.mapFS&&(F++,x.readFile(R.map,(re,te)=>{re!==null?I(re,null):(R.map=te,ae())})),ae()})}catch(U){let l=[];try{St(l,f,{},y,me)}catch{}const g=Qe(U,a,D,void 0,"");N(T,{command:"error",flags:l,error:g},()=>{g.detail=D.load(g.detail),I(ft("Transform failed",[g],[]),null)})}};if((typeof b=="string"||b instanceof Uint8Array)&&b.length>1024*1024){let S=v;v=()=>x.writeFile(b,S)}v(null)},formatMessages:({callName:B,refs:T,messages:b,options:f,callback:y})=>{if(!f)throw new Error(`Missing second argument in ${B}() call`);let x={},I=h(f,x,"kind",L),D=h(f,x,"color",le),v=h(f,x,"terminalWidth",Ke);if(_e(f,x,`in ${B}() call`),I===void 0)throw new Error(`Missing "kind" in ${B}() call`);if(I!=="error"&&I!=="warning")throw new Error(`Expected "kind" to be "error" or "warning" in ${B}() call`);let S={command:"format-msgs",messages:Ve(b,"messages",null,"",v),isWarning:I==="warning"};D!==void 0&&(S.color=D),v!==void 0&&(S.terminalWidth=v),N(T,S,(U,l)=>{if(U)return y(new Error(U),null);y(null,l.messages)})},analyzeMetafile:({callName:B,refs:T,metafile:b,options:f,callback:y})=>{f===void 0&&(f={});let x={},I=h(f,x,"color",le),D=h(f,x,"verbose",le);_e(f,x,`in ${B}() call`);let v={command:"analyze-metafile",metafile:b};I!==void 0&&(v.color=I),D!==void 0&&(v.verbose=D),N(T,v,(S,U)=>{if(S)return y(new Error(S),null);y(null,U.result)})}}}}function ir(a,o,u,p,k,E,_,$,m,O,N){const V=mn(),ne=a==="context",Q=(z,ye)=>{const W=[];try{St(W,$,{},m,Ge)}catch{}const B=Qe(z,E,V,void 0,ye);u(k,{command:"error",flags:W,error:B},()=>{B.detail=V.load(B.detail),N(ft(ne?"Context failed":"Build failed",[B],[]),null)})};let se;if(typeof $=="object"){const z=$.plugins;if(z!==void 0){if(!Array.isArray(z))return Q(new Error('"plugins" must be an array'),"");se=z}}if(se&&se.length>0){if(E.isSync)return Q(new Error("Cannot use plugins in synchronous API calls"),"");ar(o,u,p,k,E,_,$,se,V).then(z=>{if(!z.ok)return Q(z.error,z.pluginName);try{ie(z.requestPlugins,z.runOnEndCallbacks,z.scheduleOnDisposeCallbacks)}catch(ye){Q(ye,"")}},z=>Q(z,""));return}try{ie(null,(z,ye)=>ye([],[]),()=>{})}catch(z){Q(z,"")}function ie(z,ye,W){const B=E.hasFS,{entries:T,flags:b,write:f,stdinContents:y,stdinResolveDir:x,absWorkingDir:I,nodePaths:D,mangleCache:v}=nr(a,$,m,Ge,B);if(f&&!E.hasFS)throw new Error('The "write" option is unavailable in this environment');const S={command:"build",key:o,entries:T,flags:b,write:f,stdinContents:y,stdinResolveDir:x,absWorkingDir:I||O,nodePaths:D,context:ne};z&&(S.plugins=z),v&&(S.mangleCache=v);const U=(P,R)=>{const H={errors:st(P.errors,V),warnings:st(P.warnings,V),outputFiles:void 0,metafile:void 0,mangleCache:void 0},pe=H.errors.slice(),F=H.warnings.slice();P.outputFiles&&(H.outputFiles=P.outputFiles.map(lr)),P.metafile&&P.metafile.length&&(H.metafile=cr(P.metafile)),P.mangleCache&&(H.mangleCache=P.mangleCache),P.writeToStdout!==void 0&&console.log(fe(P.writeToStdout).replace(/\n$/,"")),ye(H,(ae,re)=>{if(pe.length>0||ae.length>0){const te=ft("Build failed",pe.concat(ae),F.concat(re));return R(te,null,ae,re)}R(null,H,ae,re)})};let l,g;ne&&(_["on-end"]=(P,R)=>new Promise(H=>{U(R,(pe,F,ae,re)=>{const te={errors:ae,warnings:re};g&&g(pe,F),l=void 0,g=void 0,p(P,te),H()})})),u(k,S,(P,R)=>{if(P)return N(new Error(P),null);if(!ne)return U(R,(F,ae)=>(W(),N(F,ae)));if(R.errors.length>0)return N(ft("Context failed",R.errors,R.warnings),null);let H=!1;const pe={rebuild:()=>(l||(l=new Promise((F,ae)=>{let re;g=(Te,be)=>{re||(re=()=>Te?ae(Te):F(be))};const te=()=>{u(k,{command:"rebuild",key:o},(be,Be)=>{be?ae(new Error(be)):re?re():te()})};te()})),l),watch:(F={})=>new Promise((ae,re)=>{if(!E.hasFS)throw new Error('Cannot use the "watch" API in this environment');const te={},Te=h(F,te,"delay",Ke);_e(F,te,"in watch() call");const be={command:"watch",key:o};Te&&(be.delay=Te),u(k,be,Be=>{Be?re(new Error(Be)):ae(void 0)})}),serve:(F={})=>new Promise((ae,re)=>{if(!E.hasFS)throw new Error('Cannot use the "serve" API in this environment');const te={},Te=h(F,te,"port",Yn),be=h(F,te,"host",L),Be=h(F,te,"servedir",L),J=h(F,te,"keyfile",L),Ze=h(F,te,"certfile",L),Re=h(F,te,"fallback",L),Me=h(F,te,"cors",$e),We=h(F,te,"onRequest",on);_e(F,te,"in serve() call");const Ae={command:"serve",key:o,onRequest:!!We};if(Te!==void 0&&(Ae.port=Te),be!==void 0&&(Ae.host=be),Be!==void 0&&(Ae.servedir=Be),J!==void 0&&(Ae.keyfile=J),Ze!==void 0&&(Ae.certfile=Ze),Re!==void 0&&(Ae.fallback=Re),Me){const mt={},it=h(Me,mt,"origin",un);_e(Me,mt,'on "cors" object'),Array.isArray(it)?Ae.corsOrigin=it:it!==void 0&&(Ae.corsOrigin=[it])}u(k,Ae,(mt,it)=>{if(mt)return re(new Error(mt));We&&(_["serve-request"]=(Er,Sr)=>{We(Sr.args),p(Er,{})}),ae(it)})}),cancel:()=>new Promise(F=>{if(H)return F();u(k,{command:"cancel",key:o},()=>{F()})}),dispose:()=>new Promise(F=>{if(H)return F();H=!0,u(k,{command:"dispose",key:o},()=>{F(),W(),k.unref()})})};k.ref(),N(null,pe)})}}var ar=(a,o,u,p,k,E,_,$,m)=>C(null,null,function*(){let O=[],N=[],V={},ne={},Q=[],se=0,ie=0,z=[],ye=!1;$=[...$];for(let T of $){let b={};if(typeof T!="object")throw new Error(`Plugin at index ${ie} must be an object`);const f=h(T,b,"name",L);if(typeof f!="string"||f==="")throw new Error(`Plugin at index ${ie} is missing a name`);try{let y=h(T,b,"setup",on);if(typeof y!="function")throw new Error("Plugin is missing a setup function");_e(T,b,`on plugin ${ge(f)}`);let x={name:f,onStart:!1,onEnd:!1,onResolve:[],onLoad:[]};ie++;let D=y({initialOptions:_,resolve:(v,S={})=>{if(!ye)throw new Error('Cannot call "resolve" before plugin setup has completed');if(typeof v!="string")throw new Error("The path to resolve must be a string");let U=Object.create(null),l=h(S,U,"pluginName",L),g=h(S,U,"importer",L),P=h(S,U,"namespace",L),R=h(S,U,"resolveDir",L),H=h(S,U,"kind",L),pe=h(S,U,"pluginData",Ie),F=h(S,U,"with",$e);return _e(S,U,"in resolve() call"),new Promise((ae,re)=>{const te={command:"resolve",path:v,key:a,pluginName:f};if(l!=null&&(te.pluginName=l),g!=null&&(te.importer=g),P!=null&&(te.namespace=P),R!=null&&(te.resolveDir=R),H!=null)te.kind=H;else throw new Error('Must specify "kind" when calling "resolve"');pe!=null&&(te.pluginData=m.store(pe)),F!=null&&(te.with=or(F,"with")),o(p,te,(Te,be)=>{Te!==null?re(new Error(Te)):ae({errors:st(be.errors,m),warnings:st(be.warnings,m),path:be.path,external:be.external,sideEffects:be.sideEffects,namespace:be.namespace,suffix:be.suffix,pluginData:m.load(be.pluginData)})})})},onStart(v){let S='This error came from the "onStart" callback registered here:',U=jt(new Error(S),k,"onStart");O.push({name:f,callback:v,note:U}),x.onStart=!0},onEnd(v){let S='This error came from the "onEnd" callback registered here:',U=jt(new Error(S),k,"onEnd");N.push({name:f,callback:v,note:U}),x.onEnd=!0},onResolve(v,S){let U='This error came from the "onResolve" callback registered here:',l=jt(new Error(U),k,"onResolve"),g={},P=h(v,g,"filter",Et),R=h(v,g,"namespace",L);if(_e(v,g,`in onResolve() call for plugin ${ge(f)}`),P==null)throw new Error("onResolve() call is missing a filter");let H=se++;V[H]={name:f,callback:S,note:l},x.onResolve.push({id:H,filter:Tt(P),namespace:R||""})},onLoad(v,S){let U='This error came from the "onLoad" callback registered here:',l=jt(new Error(U),k,"onLoad"),g={},P=h(v,g,"filter",Et),R=h(v,g,"namespace",L);if(_e(v,g,`in onLoad() call for plugin ${ge(f)}`),P==null)throw new Error("onLoad() call is missing a filter");let H=se++;ne[H]={name:f,callback:S,note:l},x.onLoad.push({id:H,filter:Tt(P),namespace:R||""})},onDispose(v){Q.push(v)},esbuild:k.esbuild});D&&(yield D),z.push(x)}catch(y){return{ok:!1,error:y,pluginName:f}}}E["on-start"]=(T,b)=>C(null,null,function*(){m.clear();let f={errors:[],warnings:[]};yield Promise.all(O.map(y=>C(null,[y],function*({name:x,callback:I,note:D}){try{let v=yield I();if(v!=null){if(typeof v!="object")throw new Error(`Expected onStart() callback in plugin ${ge(x)} to return an object`);let S={},U=h(v,S,"errors",Fe),l=h(v,S,"warnings",Fe);_e(v,S,`from onStart() callback in plugin ${ge(x)}`),U!=null&&f.errors.push(...Ve(U,"errors",m,x,void 0)),l!=null&&f.warnings.push(...Ve(l,"warnings",m,x,void 0))}}catch(v){f.errors.push(Qe(v,k,m,D&&D(),x))}}))),u(T,f)}),E["on-resolve"]=(T,b)=>C(null,null,function*(){let f={},y="",x,I;for(let D of b.ids)try{({name:y,callback:x,note:I}=V[D]);let v=yield x({path:b.path,importer:b.importer,namespace:b.namespace,resolveDir:b.resolveDir,kind:b.kind,pluginData:m.load(b.pluginData),with:b.with});if(v!=null){if(typeof v!="object")throw new Error(`Expected onResolve() callback in plugin ${ge(y)} to return an object`);let S={},U=h(v,S,"pluginName",L),l=h(v,S,"path",L),g=h(v,S,"namespace",L),P=h(v,S,"suffix",L),R=h(v,S,"external",le),H=h(v,S,"sideEffects",le),pe=h(v,S,"pluginData",Ie),F=h(v,S,"errors",Fe),ae=h(v,S,"warnings",Fe),re=h(v,S,"watchFiles",je),te=h(v,S,"watchDirs",je);_e(v,S,`from onResolve() callback in plugin ${ge(y)}`),f.id=D,U!=null&&(f.pluginName=U),l!=null&&(f.path=l),g!=null&&(f.namespace=g),P!=null&&(f.suffix=P),R!=null&&(f.external=R),H!=null&&(f.sideEffects=H),pe!=null&&(f.pluginData=m.store(pe)),F!=null&&(f.errors=Ve(F,"errors",m,y,void 0)),ae!=null&&(f.warnings=Ve(ae,"warnings",m,y,void 0)),re!=null&&(f.watchFiles=Ct(re,"watchFiles")),te!=null&&(f.watchDirs=Ct(te,"watchDirs"));break}}catch(v){f={id:D,errors:[Qe(v,k,m,I&&I(),y)]};break}u(T,f)}),E["on-load"]=(T,b)=>C(null,null,function*(){let f={},y="",x,I;for(let D of b.ids)try{({name:y,callback:x,note:I}=ne[D]);let v=yield x({path:b.path,namespace:b.namespace,suffix:b.suffix,pluginData:m.load(b.pluginData),with:b.with});if(v!=null){if(typeof v!="object")throw new Error(`Expected onLoad() callback in plugin ${ge(y)} to return an object`);let S={},U=h(v,S,"pluginName",L),l=h(v,S,"contents",dn),g=h(v,S,"resolveDir",L),P=h(v,S,"pluginData",Ie),R=h(v,S,"loader",L),H=h(v,S,"errors",Fe),pe=h(v,S,"warnings",Fe),F=h(v,S,"watchFiles",je),ae=h(v,S,"watchDirs",je);_e(v,S,`from onLoad() callback in plugin ${ge(y)}`),f.id=D,U!=null&&(f.pluginName=U),l instanceof Uint8Array?f.contents=l:l!=null&&(f.contents=K(l)),g!=null&&(f.resolveDir=g),P!=null&&(f.pluginData=m.store(P)),R!=null&&(f.loader=R),H!=null&&(f.errors=Ve(H,"errors",m,y,void 0)),pe!=null&&(f.warnings=Ve(pe,"warnings",m,y,void 0)),F!=null&&(f.watchFiles=Ct(F,"watchFiles")),ae!=null&&(f.watchDirs=Ct(ae,"watchDirs"));break}}catch(v){f={id:D,errors:[Qe(v,k,m,I&&I(),y)]};break}u(T,f)});let W=(T,b)=>b([],[]);N.length>0&&(W=(T,b)=>{C(null,null,function*(){const f=[],y=[];for(const{name:x,callback:I,note:D}of N){let v,S;try{const U=yield I(T);if(U!=null){if(typeof U!="object")throw new Error(`Expected onEnd() callback in plugin ${ge(x)} to return an object`);let l={},g=h(U,l,"errors",Fe),P=h(U,l,"warnings",Fe);_e(U,l,`from onEnd() callback in plugin ${ge(x)}`),g!=null&&(v=Ve(g,"errors",m,x,void 0)),P!=null&&(S=Ve(P,"warnings",m,x,void 0))}}catch(U){v=[Qe(U,k,m,D&&D(),x)]}if(v){f.push(...v);try{T.errors.push(...v)}catch{}}if(S){y.push(...S);try{T.warnings.push(...S)}catch{}}}b(f,y)})});let B=()=>{for(const T of Q)setTimeout(()=>T(),0)};return ye=!0,{ok:!0,requestPlugins:z,runOnEndCallbacks:W,scheduleOnDisposeCallbacks:B}});function mn(){const a=new Map;let o=0;return{clear(){a.clear()},load(u){return a.get(u)},store(u){if(u===void 0)return-1;const p=o++;return a.set(p,u),p}}}function jt(a,o,u){let p,k=!1;return()=>{if(k)return p;k=!0;try{let E=(a.stack+"").split(`
8
+ `);E.splice(1,1);let _=pn(o,E,u);if(_)return p={text:a.message,location:_},p}catch{}}}function Qe(a,o,u,p,k){let E="Internal error",_=null;try{E=(a&&a.message||a)+""}catch{}try{_=pn(o,(a.stack+"").split(`
9
+ `),"")}catch{}return{id:"",pluginName:k,text:E,location:_,notes:p?[p]:[],detail:u?u.store(a):-1}}function pn(a,o,u){let p=" at ";if(a.readFileSync&&!o[0].startsWith(p)&&o[1].startsWith(p))for(let k=1;k<o.length;k++){let E=o[k];if(E.startsWith(p))for(E=E.slice(p.length);;){let _=/^(?:new |async )?\S+ \((.*)\)$/.exec(E);if(_){E=_[1];continue}if(_=/^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(E),_){E=_[1];continue}if(_=/^(\S+):(\d+):(\d+)$/.exec(E),_){let $;try{$=a.readFileSync(_[1],"utf8")}catch{break}let m=$.split(/\r\n|\r|\n|\u2028|\u2029/)[+_[2]-1]||"",O=+_[3]-1,N=m.slice(O,O+u.length)===u?u.length:0;return{file:_[1],namespace:"file",line:+_[2],column:K(m.slice(0,O)).length,length:K(m.slice(O,O+N)).length,lineText:m+`
10
+ `+o.slice(1).join(`
11
+ `),suggestion:""}}break}}return null}function ft(a,o,u){let p=5;a+=o.length<1?"":` with ${o.length} error${o.length<2?"":"s"}:`+o.slice(0,p+1).map((E,_)=>{if(_===p)return`
12
+ ...`;if(!E.location)return`
13
+ error: ${E.text}`;let{file:$,line:m,column:O}=E.location,N=E.pluginName?`[plugin: ${E.pluginName}] `:"";return`
14
+ ${$}:${m}:${O}: ERROR: ${N}${E.text}`}).join("");let k=new Error(a);for(const[E,_]of[["errors",o],["warnings",u]])Object.defineProperty(k,E,{configurable:!0,enumerable:!0,get:()=>_,set:$=>Object.defineProperty(k,E,{configurable:!0,enumerable:!0,value:$})});return k}function st(a,o){for(const u of a)u.detail=o.load(u.detail);return a}function gn(a,o,u){if(a==null)return null;let p={},k=h(a,p,"file",L),E=h(a,p,"namespace",L),_=h(a,p,"line",Ke),$=h(a,p,"column",Ke),m=h(a,p,"length",Ke),O=h(a,p,"lineText",L),N=h(a,p,"suggestion",L);if(_e(a,p,o),O){const V=O.slice(0,($&&$>0?$:0)+(m&&m>0?m:0)+(u&&u>0?u:80));!/[\x7F-\uFFFF]/.test(V)&&!/\n/.test(O)&&(O=V)}return{file:k||"",namespace:E||"",line:_||0,column:$||0,length:m||0,lineText:O||"",suggestion:N||""}}function Ve(a,o,u,p,k){let E=[],_=0;for(const $ of a){let m={},O=h($,m,"id",L),N=h($,m,"pluginName",L),V=h($,m,"text",L),ne=h($,m,"location",ln),Q=h($,m,"notes",Fe),se=h($,m,"detail",Ie),ie=`in element ${_} of "${o}"`;_e($,m,ie);let z=[];if(Q)for(const ye of Q){let W={},B=h(ye,W,"text",L),T=h(ye,W,"location",ln);_e(ye,W,ie),z.push({text:B||"",location:gn(T,ie,k)})}E.push({id:O||"",pluginName:N||p,text:V||"",location:gn(ne,ie,k),notes:z,detail:u?u.store(se):-1}),_++}return E}function Ct(a,o){const u=[];for(const p of a){if(typeof p!="string")throw new Error(`${ge(o)} must be an array of strings`);u.push(p)}return u}function or(a,o){const u=Object.create(null);for(const p in a){const k=a[p];if(typeof k!="string")throw new Error(`key ${ge(p)} in object ${ge(o)} must be a string`);u[p]=k}return u}function lr({path:a,contents:o,hash:u}){let p=null;return{path:a,contents:o,hash:u,get text(){const k=this.contents;return(p===null||k!==o)&&(o=k,p=fe(k)),p}}}function Tt(a){let o=a.source;return a.flags&&(o=`(?${a.flags})${o}`),o}function cr(a){let o;try{o=fe(a)}catch{return Ue(a)}return JSON.parse(o)}var ur="0.27.7",dr=a=>ht().build(a),fr=a=>ht().context(a),hr=(a,o)=>ht().transform(a,o),mr=(a,o)=>ht().formatMessages(a,o),pr=(a,o)=>ht().analyzeMetafile(a,o),gr=()=>{throw new Error('The "buildSync" API only works in node')},yr=()=>{throw new Error('The "transformSync" API only works in node')},vr=()=>{throw new Error('The "formatMessagesSync" API only works in node')},wr=()=>{throw new Error('The "analyzeMetafileSync" API only works in node')},_r=()=>(Ot&&Ot(),Promise.resolve()),et,Ot,$t,ht=()=>{if($t)return $t;throw et?new Error('You need to wait for the promise returned from "initialize" to be resolved before calling this'):new Error('You need to call "initialize" before calling this')},br=a=>{a=tr(a||{});let o=a.wasmURL,u=a.wasmModule,p=a.worker!==!1;if(!o&&!u)throw new Error('Must provide either the "wasmURL" option or the "wasmModule" option');if(et)throw new Error('Cannot call "initialize" more than once');return et=xr(o||"",u,p),et.catch(()=>{et=void 0}),et},xr=(a,o,u)=>C(null,null,function*(){let p,k;const E=new Promise(V=>k=V);if(u){let V=new Blob([`onmessage=((postMessage) => {
15
+ // Copyright 2018 The Go Authors. All rights reserved.
16
+ // Use of this source code is governed by a BSD-style
17
+ // license that can be found in the LICENSE file.
18
+ var __async = (__this, __arguments, generator) => {
19
+ return new Promise((resolve, reject) => {
20
+ var fulfilled = (value) => {
21
+ try {
22
+ step(generator.next(value));
23
+ } catch (e) {
24
+ reject(e);
25
+ }
26
+ };
27
+ var rejected = (value) => {
28
+ try {
29
+ step(generator.throw(value));
30
+ } catch (e) {
31
+ reject(e);
32
+ }
33
+ };
34
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
35
+ step((generator = generator.apply(__this, __arguments)).next());
36
+ });
37
+ };
38
+ let onmessage;
39
+ let globalThis = {};
40
+ for (let o = self; o; o = Object.getPrototypeOf(o))
41
+ for (let k of Object.getOwnPropertyNames(o))
42
+ if (!(k in globalThis))
43
+ Object.defineProperty(globalThis, k, { get: () => self[k] });
44
+ "use strict";
45
+ (() => {
46
+ const enosys = () => {
47
+ const err = new Error("not implemented");
48
+ err.code = "ENOSYS";
49
+ return err;
50
+ };
51
+ if (!globalThis.fs) {
52
+ let outputBuf = "";
53
+ globalThis.fs = {
54
+ constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1, O_DIRECTORY: -1 },
55
+ // unused
56
+ writeSync(fd, buf) {
57
+ outputBuf += decoder.decode(buf);
58
+ const nl = outputBuf.lastIndexOf("\\n");
59
+ if (nl != -1) {
60
+ console.log(outputBuf.substring(0, nl));
61
+ outputBuf = outputBuf.substring(nl + 1);
62
+ }
63
+ return buf.length;
64
+ },
65
+ write(fd, buf, offset, length, position, callback) {
66
+ if (offset !== 0 || length !== buf.length || position !== null) {
67
+ callback(enosys());
68
+ return;
69
+ }
70
+ const n = this.writeSync(fd, buf);
71
+ callback(null, n);
72
+ },
73
+ chmod(path, mode, callback) {
74
+ callback(enosys());
75
+ },
76
+ chown(path, uid, gid, callback) {
77
+ callback(enosys());
78
+ },
79
+ close(fd, callback) {
80
+ callback(enosys());
81
+ },
82
+ fchmod(fd, mode, callback) {
83
+ callback(enosys());
84
+ },
85
+ fchown(fd, uid, gid, callback) {
86
+ callback(enosys());
87
+ },
88
+ fstat(fd, callback) {
89
+ callback(enosys());
90
+ },
91
+ fsync(fd, callback) {
92
+ callback(null);
93
+ },
94
+ ftruncate(fd, length, callback) {
95
+ callback(enosys());
96
+ },
97
+ lchown(path, uid, gid, callback) {
98
+ callback(enosys());
99
+ },
100
+ link(path, link, callback) {
101
+ callback(enosys());
102
+ },
103
+ lstat(path, callback) {
104
+ callback(enosys());
105
+ },
106
+ mkdir(path, perm, callback) {
107
+ callback(enosys());
108
+ },
109
+ open(path, flags, mode, callback) {
110
+ callback(enosys());
111
+ },
112
+ read(fd, buffer, offset, length, position, callback) {
113
+ callback(enosys());
114
+ },
115
+ readdir(path, callback) {
116
+ callback(enosys());
117
+ },
118
+ readlink(path, callback) {
119
+ callback(enosys());
120
+ },
121
+ rename(from, to, callback) {
122
+ callback(enosys());
123
+ },
124
+ rmdir(path, callback) {
125
+ callback(enosys());
126
+ },
127
+ stat(path, callback) {
128
+ callback(enosys());
129
+ },
130
+ symlink(path, link, callback) {
131
+ callback(enosys());
132
+ },
133
+ truncate(path, length, callback) {
134
+ callback(enosys());
135
+ },
136
+ unlink(path, callback) {
137
+ callback(enosys());
138
+ },
139
+ utimes(path, atime, mtime, callback) {
140
+ callback(enosys());
141
+ }
142
+ };
143
+ }
144
+ if (!globalThis.process) {
145
+ globalThis.process = {
146
+ getuid() {
147
+ return -1;
148
+ },
149
+ getgid() {
150
+ return -1;
151
+ },
152
+ geteuid() {
153
+ return -1;
154
+ },
155
+ getegid() {
156
+ return -1;
157
+ },
158
+ getgroups() {
159
+ throw enosys();
160
+ },
161
+ pid: -1,
162
+ ppid: -1,
163
+ umask() {
164
+ throw enosys();
165
+ },
166
+ cwd() {
167
+ throw enosys();
168
+ },
169
+ chdir() {
170
+ throw enosys();
171
+ }
172
+ };
173
+ }
174
+ if (!globalThis.path) {
175
+ globalThis.path = {
176
+ resolve(...pathSegments) {
177
+ return pathSegments.join("/");
178
+ }
179
+ };
180
+ }
181
+ if (!globalThis.crypto) {
182
+ throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)");
183
+ }
184
+ if (!globalThis.performance) {
185
+ throw new Error("globalThis.performance is not available, polyfill required (performance.now only)");
186
+ }
187
+ if (!globalThis.TextEncoder) {
188
+ throw new Error("globalThis.TextEncoder is not available, polyfill required");
189
+ }
190
+ if (!globalThis.TextDecoder) {
191
+ throw new Error("globalThis.TextDecoder is not available, polyfill required");
192
+ }
193
+ const encoder = new TextEncoder("utf-8");
194
+ const decoder = new TextDecoder("utf-8");
195
+ globalThis.Go = class {
196
+ constructor() {
197
+ this.argv = ["js"];
198
+ this.env = {};
199
+ this.exit = (code) => {
200
+ if (code !== 0) {
201
+ console.warn("exit code:", code);
202
+ }
203
+ };
204
+ this._exitPromise = new Promise((resolve) => {
205
+ this._resolveExitPromise = resolve;
206
+ });
207
+ this._pendingEvent = null;
208
+ this._scheduledTimeouts = /* @__PURE__ */ new Map();
209
+ this._nextCallbackTimeoutID = 1;
210
+ const setInt64 = (addr, v) => {
211
+ this.mem.setUint32(addr + 0, v, true);
212
+ this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true);
213
+ };
214
+ const setInt32 = (addr, v) => {
215
+ this.mem.setUint32(addr + 0, v, true);
216
+ };
217
+ const getInt64 = (addr) => {
218
+ const low = this.mem.getUint32(addr + 0, true);
219
+ const high = this.mem.getInt32(addr + 4, true);
220
+ return low + high * 4294967296;
221
+ };
222
+ const loadValue = (addr) => {
223
+ const f = this.mem.getFloat64(addr, true);
224
+ if (f === 0) {
225
+ return void 0;
226
+ }
227
+ if (!isNaN(f)) {
228
+ return f;
229
+ }
230
+ const id = this.mem.getUint32(addr, true);
231
+ return this._values[id];
232
+ };
233
+ const storeValue = (addr, v) => {
234
+ const nanHead = 2146959360;
235
+ if (typeof v === "number" && v !== 0) {
236
+ if (isNaN(v)) {
237
+ this.mem.setUint32(addr + 4, nanHead, true);
238
+ this.mem.setUint32(addr, 0, true);
239
+ return;
240
+ }
241
+ this.mem.setFloat64(addr, v, true);
242
+ return;
243
+ }
244
+ if (v === void 0) {
245
+ this.mem.setFloat64(addr, 0, true);
246
+ return;
247
+ }
248
+ let id = this._ids.get(v);
249
+ if (id === void 0) {
250
+ id = this._idPool.pop();
251
+ if (id === void 0) {
252
+ id = this._values.length;
253
+ }
254
+ this._values[id] = v;
255
+ this._goRefCounts[id] = 0;
256
+ this._ids.set(v, id);
257
+ }
258
+ this._goRefCounts[id]++;
259
+ let typeFlag = 0;
260
+ switch (typeof v) {
261
+ case "object":
262
+ if (v !== null) {
263
+ typeFlag = 1;
264
+ }
265
+ break;
266
+ case "string":
267
+ typeFlag = 2;
268
+ break;
269
+ case "symbol":
270
+ typeFlag = 3;
271
+ break;
272
+ case "function":
273
+ typeFlag = 4;
274
+ break;
275
+ }
276
+ this.mem.setUint32(addr + 4, nanHead | typeFlag, true);
277
+ this.mem.setUint32(addr, id, true);
278
+ };
279
+ const loadSlice = (addr) => {
280
+ const array = getInt64(addr + 0);
281
+ const len = getInt64(addr + 8);
282
+ return new Uint8Array(this._inst.exports.mem.buffer, array, len);
283
+ };
284
+ const loadSliceOfValues = (addr) => {
285
+ const array = getInt64(addr + 0);
286
+ const len = getInt64(addr + 8);
287
+ const a = new Array(len);
288
+ for (let i = 0; i < len; i++) {
289
+ a[i] = loadValue(array + i * 8);
290
+ }
291
+ return a;
292
+ };
293
+ const loadString = (addr) => {
294
+ const saddr = getInt64(addr + 0);
295
+ const len = getInt64(addr + 8);
296
+ return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len));
297
+ };
298
+ const testCallExport = (a, b) => {
299
+ this._inst.exports.testExport0();
300
+ return this._inst.exports.testExport(a, b);
301
+ };
302
+ const timeOrigin = Date.now() - performance.now();
303
+ this.importObject = {
304
+ _gotest: {
305
+ add: (a, b) => a + b,
306
+ callExport: testCallExport
307
+ },
308
+ gojs: {
309
+ // Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters)
310
+ // may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported
311
+ // function. A goroutine can switch to a new stack if the current stack is too small (see morestack function).
312
+ // This changes the SP, thus we have to update the SP used by the imported function.
313
+ // func wasmExit(code int32)
314
+ "runtime.wasmExit": (sp) => {
315
+ sp >>>= 0;
316
+ const code = this.mem.getInt32(sp + 8, true);
317
+ this.exited = true;
318
+ delete this._inst;
319
+ delete this._values;
320
+ delete this._goRefCounts;
321
+ delete this._ids;
322
+ delete this._idPool;
323
+ this.exit(code);
324
+ },
325
+ // func wasmWrite(fd uintptr, p unsafe.Pointer, n int32)
326
+ "runtime.wasmWrite": (sp) => {
327
+ sp >>>= 0;
328
+ const fd = getInt64(sp + 8);
329
+ const p = getInt64(sp + 16);
330
+ const n = this.mem.getInt32(sp + 24, true);
331
+ globalThis.fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n));
332
+ },
333
+ // func resetMemoryDataView()
334
+ "runtime.resetMemoryDataView": (sp) => {
335
+ sp >>>= 0;
336
+ this.mem = new DataView(this._inst.exports.mem.buffer);
337
+ },
338
+ // func nanotime1() int64
339
+ "runtime.nanotime1": (sp) => {
340
+ sp >>>= 0;
341
+ setInt64(sp + 8, (timeOrigin + performance.now()) * 1e6);
342
+ },
343
+ // func walltime() (sec int64, nsec int32)
344
+ "runtime.walltime": (sp) => {
345
+ sp >>>= 0;
346
+ const msec = (/* @__PURE__ */ new Date()).getTime();
347
+ setInt64(sp + 8, msec / 1e3);
348
+ this.mem.setInt32(sp + 16, msec % 1e3 * 1e6, true);
349
+ },
350
+ // func scheduleTimeoutEvent(delay int64) int32
351
+ "runtime.scheduleTimeoutEvent": (sp) => {
352
+ sp >>>= 0;
353
+ const id = this._nextCallbackTimeoutID;
354
+ this._nextCallbackTimeoutID++;
355
+ this._scheduledTimeouts.set(id, setTimeout(
356
+ () => {
357
+ this._resume();
358
+ while (this._scheduledTimeouts.has(id)) {
359
+ console.warn("scheduleTimeoutEvent: missed timeout event");
360
+ this._resume();
361
+ }
362
+ },
363
+ getInt64(sp + 8)
364
+ ));
365
+ this.mem.setInt32(sp + 16, id, true);
366
+ },
367
+ // func clearTimeoutEvent(id int32)
368
+ "runtime.clearTimeoutEvent": (sp) => {
369
+ sp >>>= 0;
370
+ const id = this.mem.getInt32(sp + 8, true);
371
+ clearTimeout(this._scheduledTimeouts.get(id));
372
+ this._scheduledTimeouts.delete(id);
373
+ },
374
+ // func getRandomData(r []byte)
375
+ "runtime.getRandomData": (sp) => {
376
+ sp >>>= 0;
377
+ crypto.getRandomValues(loadSlice(sp + 8));
378
+ },
379
+ // func finalizeRef(v ref)
380
+ "syscall/js.finalizeRef": (sp) => {
381
+ sp >>>= 0;
382
+ const id = this.mem.getUint32(sp + 8, true);
383
+ this._goRefCounts[id]--;
384
+ if (this._goRefCounts[id] === 0) {
385
+ const v = this._values[id];
386
+ this._values[id] = null;
387
+ this._ids.delete(v);
388
+ this._idPool.push(id);
389
+ }
390
+ },
391
+ // func stringVal(value string) ref
392
+ "syscall/js.stringVal": (sp) => {
393
+ sp >>>= 0;
394
+ storeValue(sp + 24, loadString(sp + 8));
395
+ },
396
+ // func valueGet(v ref, p string) ref
397
+ "syscall/js.valueGet": (sp) => {
398
+ sp >>>= 0;
399
+ const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16));
400
+ sp = this._inst.exports.getsp() >>> 0;
401
+ storeValue(sp + 32, result);
402
+ },
403
+ // func valueSet(v ref, p string, x ref)
404
+ "syscall/js.valueSet": (sp) => {
405
+ sp >>>= 0;
406
+ Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32));
407
+ },
408
+ // func valueDelete(v ref, p string)
409
+ "syscall/js.valueDelete": (sp) => {
410
+ sp >>>= 0;
411
+ Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16));
412
+ },
413
+ // func valueIndex(v ref, i int) ref
414
+ "syscall/js.valueIndex": (sp) => {
415
+ sp >>>= 0;
416
+ storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16)));
417
+ },
418
+ // valueSetIndex(v ref, i int, x ref)
419
+ "syscall/js.valueSetIndex": (sp) => {
420
+ sp >>>= 0;
421
+ Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24));
422
+ },
423
+ // func valueCall(v ref, m string, args []ref) (ref, bool)
424
+ "syscall/js.valueCall": (sp) => {
425
+ sp >>>= 0;
426
+ try {
427
+ const v = loadValue(sp + 8);
428
+ const m = Reflect.get(v, loadString(sp + 16));
429
+ const args = loadSliceOfValues(sp + 32);
430
+ const result = Reflect.apply(m, v, args);
431
+ sp = this._inst.exports.getsp() >>> 0;
432
+ storeValue(sp + 56, result);
433
+ this.mem.setUint8(sp + 64, 1);
434
+ } catch (err) {
435
+ sp = this._inst.exports.getsp() >>> 0;
436
+ storeValue(sp + 56, err);
437
+ this.mem.setUint8(sp + 64, 0);
438
+ }
439
+ },
440
+ // func valueInvoke(v ref, args []ref) (ref, bool)
441
+ "syscall/js.valueInvoke": (sp) => {
442
+ sp >>>= 0;
443
+ try {
444
+ const v = loadValue(sp + 8);
445
+ const args = loadSliceOfValues(sp + 16);
446
+ const result = Reflect.apply(v, void 0, args);
447
+ sp = this._inst.exports.getsp() >>> 0;
448
+ storeValue(sp + 40, result);
449
+ this.mem.setUint8(sp + 48, 1);
450
+ } catch (err) {
451
+ sp = this._inst.exports.getsp() >>> 0;
452
+ storeValue(sp + 40, err);
453
+ this.mem.setUint8(sp + 48, 0);
454
+ }
455
+ },
456
+ // func valueNew(v ref, args []ref) (ref, bool)
457
+ "syscall/js.valueNew": (sp) => {
458
+ sp >>>= 0;
459
+ try {
460
+ const v = loadValue(sp + 8);
461
+ const args = loadSliceOfValues(sp + 16);
462
+ const result = Reflect.construct(v, args);
463
+ sp = this._inst.exports.getsp() >>> 0;
464
+ storeValue(sp + 40, result);
465
+ this.mem.setUint8(sp + 48, 1);
466
+ } catch (err) {
467
+ sp = this._inst.exports.getsp() >>> 0;
468
+ storeValue(sp + 40, err);
469
+ this.mem.setUint8(sp + 48, 0);
470
+ }
471
+ },
472
+ // func valueLength(v ref) int
473
+ "syscall/js.valueLength": (sp) => {
474
+ sp >>>= 0;
475
+ setInt64(sp + 16, parseInt(loadValue(sp + 8).length));
476
+ },
477
+ // valuePrepareString(v ref) (ref, int)
478
+ "syscall/js.valuePrepareString": (sp) => {
479
+ sp >>>= 0;
480
+ const str = encoder.encode(String(loadValue(sp + 8)));
481
+ storeValue(sp + 16, str);
482
+ setInt64(sp + 24, str.length);
483
+ },
484
+ // valueLoadString(v ref, b []byte)
485
+ "syscall/js.valueLoadString": (sp) => {
486
+ sp >>>= 0;
487
+ const str = loadValue(sp + 8);
488
+ loadSlice(sp + 16).set(str);
489
+ },
490
+ // func valueInstanceOf(v ref, t ref) bool
491
+ "syscall/js.valueInstanceOf": (sp) => {
492
+ sp >>>= 0;
493
+ this.mem.setUint8(sp + 24, loadValue(sp + 8) instanceof loadValue(sp + 16) ? 1 : 0);
494
+ },
495
+ // func copyBytesToGo(dst []byte, src ref) (int, bool)
496
+ "syscall/js.copyBytesToGo": (sp) => {
497
+ sp >>>= 0;
498
+ const dst = loadSlice(sp + 8);
499
+ const src = loadValue(sp + 32);
500
+ if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) {
501
+ this.mem.setUint8(sp + 48, 0);
502
+ return;
503
+ }
504
+ const toCopy = src.subarray(0, dst.length);
505
+ dst.set(toCopy);
506
+ setInt64(sp + 40, toCopy.length);
507
+ this.mem.setUint8(sp + 48, 1);
508
+ },
509
+ // func copyBytesToJS(dst ref, src []byte) (int, bool)
510
+ "syscall/js.copyBytesToJS": (sp) => {
511
+ sp >>>= 0;
512
+ const dst = loadValue(sp + 8);
513
+ const src = loadSlice(sp + 16);
514
+ if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) {
515
+ this.mem.setUint8(sp + 48, 0);
516
+ return;
517
+ }
518
+ const toCopy = src.subarray(0, dst.length);
519
+ dst.set(toCopy);
520
+ setInt64(sp + 40, toCopy.length);
521
+ this.mem.setUint8(sp + 48, 1);
522
+ },
523
+ "debug": (value) => {
524
+ console.log(value);
525
+ }
526
+ }
527
+ };
528
+ }
529
+ run(instance) {
530
+ return __async(this, null, function* () {
531
+ if (!(instance instanceof WebAssembly.Instance)) {
532
+ throw new Error("Go.run: WebAssembly.Instance expected");
533
+ }
534
+ this._inst = instance;
535
+ this.mem = new DataView(this._inst.exports.mem.buffer);
536
+ this._values = [
537
+ // JS values that Go currently has references to, indexed by reference id
538
+ NaN,
539
+ 0,
540
+ null,
541
+ true,
542
+ false,
543
+ globalThis,
544
+ this
545
+ ];
546
+ this._goRefCounts = new Array(this._values.length).fill(Infinity);
547
+ this._ids = /* @__PURE__ */ new Map([
548
+ // mapping from JS values to reference ids
549
+ [0, 1],
550
+ [null, 2],
551
+ [true, 3],
552
+ [false, 4],
553
+ [globalThis, 5],
554
+ [this, 6]
555
+ ]);
556
+ this._idPool = [];
557
+ this.exited = false;
558
+ let offset = 4096;
559
+ const strPtr = (str) => {
560
+ const ptr = offset;
561
+ const bytes = encoder.encode(str + "\\0");
562
+ new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes);
563
+ offset += bytes.length;
564
+ if (offset % 8 !== 0) {
565
+ offset += 8 - offset % 8;
566
+ }
567
+ return ptr;
568
+ };
569
+ const argc = this.argv.length;
570
+ const argvPtrs = [];
571
+ this.argv.forEach((arg) => {
572
+ argvPtrs.push(strPtr(arg));
573
+ });
574
+ argvPtrs.push(0);
575
+ const keys = Object.keys(this.env).sort();
576
+ keys.forEach((key) => {
577
+ argvPtrs.push(strPtr(\`\${key}=\${this.env[key]}\`));
578
+ });
579
+ argvPtrs.push(0);
580
+ const argv = offset;
581
+ argvPtrs.forEach((ptr) => {
582
+ this.mem.setUint32(offset, ptr, true);
583
+ this.mem.setUint32(offset + 4, 0, true);
584
+ offset += 8;
585
+ });
586
+ const wasmMinDataAddr = 4096 + 8192;
587
+ if (offset >= wasmMinDataAddr) {
588
+ throw new Error("total length of command line and environment variables exceeds limit");
589
+ }
590
+ this._inst.exports.run(argc, argv);
591
+ if (this.exited) {
592
+ this._resolveExitPromise();
593
+ }
594
+ yield this._exitPromise;
595
+ });
596
+ }
597
+ _resume() {
598
+ if (this.exited) {
599
+ throw new Error("Go program has already exited");
600
+ }
601
+ this._inst.exports.resume();
602
+ if (this.exited) {
603
+ this._resolveExitPromise();
604
+ }
605
+ }
606
+ _makeFuncWrapper(id) {
607
+ const go = this;
608
+ return function() {
609
+ const event = { id, this: this, args: arguments };
610
+ go._pendingEvent = event;
611
+ go._resume();
612
+ return event.result;
613
+ };
614
+ }
615
+ };
616
+ })();
617
+ onmessage = ({ data: wasm }) => {
618
+ let decoder = new TextDecoder();
619
+ let fs = globalThis.fs;
620
+ let stderr = "";
621
+ fs.writeSync = (fd, buffer) => {
622
+ if (fd === 1) {
623
+ postMessage(buffer);
624
+ } else if (fd === 2) {
625
+ stderr += decoder.decode(buffer);
626
+ let parts = stderr.split("\\n");
627
+ if (parts.length > 1) console.log(parts.slice(0, -1).join("\\n"));
628
+ stderr = parts[parts.length - 1];
629
+ } else {
630
+ throw new Error("Bad write");
631
+ }
632
+ return buffer.length;
633
+ };
634
+ let stdin = [];
635
+ let resumeStdin;
636
+ let stdinPos = 0;
637
+ onmessage = ({ data }) => {
638
+ if (data.length > 0) {
639
+ stdin.push(data);
640
+ if (resumeStdin) resumeStdin();
641
+ }
642
+ return go;
643
+ };
644
+ fs.read = (fd, buffer, offset, length, position, callback) => {
645
+ if (fd !== 0 || offset !== 0 || length !== buffer.length || position !== null) {
646
+ throw new Error("Bad read");
647
+ }
648
+ if (stdin.length === 0) {
649
+ resumeStdin = () => fs.read(fd, buffer, offset, length, position, callback);
650
+ return;
651
+ }
652
+ let first = stdin[0];
653
+ let count = Math.max(0, Math.min(length, first.length - stdinPos));
654
+ buffer.set(first.subarray(stdinPos, stdinPos + count), offset);
655
+ stdinPos += count;
656
+ if (stdinPos === first.length) {
657
+ stdin.shift();
658
+ stdinPos = 0;
659
+ }
660
+ callback(null, count);
661
+ };
662
+ let go = new globalThis.Go();
663
+ go.argv = ["", \`--service=\${"0.27.7"}\`];
664
+ tryToInstantiateModule(wasm, go).then(
665
+ (instance) => {
666
+ postMessage(null);
667
+ go.run(instance);
668
+ },
669
+ (error) => {
670
+ postMessage(error);
671
+ }
672
+ );
673
+ return go;
674
+ };
675
+ function tryToInstantiateModule(wasm, go) {
676
+ return __async(this, null, function* () {
677
+ if (wasm instanceof WebAssembly.Module) {
678
+ return WebAssembly.instantiate(wasm, go.importObject);
679
+ }
680
+ const res = yield fetch(wasm);
681
+ if (!res.ok) throw new Error(\`Failed to download \${JSON.stringify(wasm)}\`);
682
+ if ("instantiateStreaming" in WebAssembly && /^application\\/wasm($|;)/i.test(res.headers.get("Content-Type") || "")) {
683
+ const result2 = yield WebAssembly.instantiateStreaming(res, go.importObject);
684
+ return result2.instance;
685
+ }
686
+ const bytes = yield res.arrayBuffer();
687
+ const result = yield WebAssembly.instantiate(bytes, go.importObject);
688
+ return result.instance;
689
+ });
690
+ }
691
+ return (m) => onmessage(m);
692
+ })(postMessage)`],{type:"text/javascript"});p=new Worker(URL.createObjectURL(V))}else{let V=(Q=>{var se=(W,B,T)=>new Promise((b,f)=>{var y=D=>{try{I(T.next(D))}catch(v){f(v)}},x=D=>{try{I(T.throw(D))}catch(v){f(v)}},I=D=>D.done?b(D.value):Promise.resolve(D.value).then(y,x);I((T=T.apply(W,B)).next())});let ie,z={};for(let W=self;W;W=Object.getPrototypeOf(W))for(let B of Object.getOwnPropertyNames(W))B in z||Object.defineProperty(z,B,{get:()=>self[B]});(()=>{const W=()=>{const b=new Error("not implemented");return b.code="ENOSYS",b};if(!z.fs){let b="";z.fs={constants:{O_WRONLY:-1,O_RDWR:-1,O_CREAT:-1,O_TRUNC:-1,O_APPEND:-1,O_EXCL:-1,O_DIRECTORY:-1},writeSync(f,y){b+=T.decode(y);const x=b.lastIndexOf(`
693
+ `);return x!=-1&&(console.log(b.substring(0,x)),b=b.substring(x+1)),y.length},write(f,y,x,I,D,v){if(x!==0||I!==y.length||D!==null){v(W());return}const S=this.writeSync(f,y);v(null,S)},chmod(f,y,x){x(W())},chown(f,y,x,I){I(W())},close(f,y){y(W())},fchmod(f,y,x){x(W())},fchown(f,y,x,I){I(W())},fstat(f,y){y(W())},fsync(f,y){y(null)},ftruncate(f,y,x){x(W())},lchown(f,y,x,I){I(W())},link(f,y,x){x(W())},lstat(f,y){y(W())},mkdir(f,y,x){x(W())},open(f,y,x,I){I(W())},read(f,y,x,I,D,v){v(W())},readdir(f,y){y(W())},readlink(f,y){y(W())},rename(f,y,x){x(W())},rmdir(f,y){y(W())},stat(f,y){y(W())},symlink(f,y,x){x(W())},truncate(f,y,x){x(W())},unlink(f,y){y(W())},utimes(f,y,x,I){I(W())}}}if(z.process||(z.process={getuid(){return-1},getgid(){return-1},geteuid(){return-1},getegid(){return-1},getgroups(){throw W()},pid:-1,ppid:-1,umask(){throw W()},cwd(){throw W()},chdir(){throw W()}}),z.path||(z.path={resolve(...b){return b.join("/")}}),!z.crypto)throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)");if(!z.performance)throw new Error("globalThis.performance is not available, polyfill required (performance.now only)");if(!z.TextEncoder)throw new Error("globalThis.TextEncoder is not available, polyfill required");if(!z.TextDecoder)throw new Error("globalThis.TextDecoder is not available, polyfill required");const B=new TextEncoder("utf-8"),T=new TextDecoder("utf-8");z.Go=class{constructor(){this.argv=["js"],this.env={},this.exit=l=>{l!==0&&console.warn("exit code:",l)},this._exitPromise=new Promise(l=>{this._resolveExitPromise=l}),this._pendingEvent=null,this._scheduledTimeouts=new Map,this._nextCallbackTimeoutID=1;const b=(l,g)=>{this.mem.setUint32(l+0,g,!0),this.mem.setUint32(l+4,Math.floor(g/4294967296),!0)},f=l=>{const g=this.mem.getUint32(l+0,!0),P=this.mem.getInt32(l+4,!0);return g+P*4294967296},y=l=>{const g=this.mem.getFloat64(l,!0);if(g===0)return;if(!isNaN(g))return g;const P=this.mem.getUint32(l,!0);return this._values[P]},x=(l,g)=>{if(typeof g=="number"&&g!==0){if(isNaN(g)){this.mem.setUint32(l+4,2146959360,!0),this.mem.setUint32(l,0,!0);return}this.mem.setFloat64(l,g,!0);return}if(g===void 0){this.mem.setFloat64(l,0,!0);return}let R=this._ids.get(g);R===void 0&&(R=this._idPool.pop(),R===void 0&&(R=this._values.length),this._values[R]=g,this._goRefCounts[R]=0,this._ids.set(g,R)),this._goRefCounts[R]++;let H=0;switch(typeof g){case"object":g!==null&&(H=1);break;case"string":H=2;break;case"symbol":H=3;break;case"function":H=4;break}this.mem.setUint32(l+4,2146959360|H,!0),this.mem.setUint32(l,R,!0)},I=l=>{const g=f(l+0),P=f(l+8);return new Uint8Array(this._inst.exports.mem.buffer,g,P)},D=l=>{const g=f(l+0),P=f(l+8),R=new Array(P);for(let H=0;H<P;H++)R[H]=y(g+H*8);return R},v=l=>{const g=f(l+0),P=f(l+8);return T.decode(new DataView(this._inst.exports.mem.buffer,g,P))},S=(l,g)=>(this._inst.exports.testExport0(),this._inst.exports.testExport(l,g)),U=Date.now()-performance.now();this.importObject={_gotest:{add:(l,g)=>l+g,callExport:S},gojs:{"runtime.wasmExit":l=>{l>>>=0;const g=this.mem.getInt32(l+8,!0);this.exited=!0,delete this._inst,delete this._values,delete this._goRefCounts,delete this._ids,delete this._idPool,this.exit(g)},"runtime.wasmWrite":l=>{l>>>=0;const g=f(l+8),P=f(l+16),R=this.mem.getInt32(l+24,!0);z.fs.writeSync(g,new Uint8Array(this._inst.exports.mem.buffer,P,R))},"runtime.resetMemoryDataView":l=>{this.mem=new DataView(this._inst.exports.mem.buffer)},"runtime.nanotime1":l=>{l>>>=0,b(l+8,(U+performance.now())*1e6)},"runtime.walltime":l=>{l>>>=0;const g=new Date().getTime();b(l+8,g/1e3),this.mem.setInt32(l+16,g%1e3*1e6,!0)},"runtime.scheduleTimeoutEvent":l=>{l>>>=0;const g=this._nextCallbackTimeoutID;this._nextCallbackTimeoutID++,this._scheduledTimeouts.set(g,setTimeout(()=>{for(this._resume();this._scheduledTimeouts.has(g);)console.warn("scheduleTimeoutEvent: missed timeout event"),this._resume()},f(l+8))),this.mem.setInt32(l+16,g,!0)},"runtime.clearTimeoutEvent":l=>{l>>>=0;const g=this.mem.getInt32(l+8,!0);clearTimeout(this._scheduledTimeouts.get(g)),this._scheduledTimeouts.delete(g)},"runtime.getRandomData":l=>{l>>>=0,crypto.getRandomValues(I(l+8))},"syscall/js.finalizeRef":l=>{l>>>=0;const g=this.mem.getUint32(l+8,!0);if(this._goRefCounts[g]--,this._goRefCounts[g]===0){const P=this._values[g];this._values[g]=null,this._ids.delete(P),this._idPool.push(g)}},"syscall/js.stringVal":l=>{l>>>=0,x(l+24,v(l+8))},"syscall/js.valueGet":l=>{l>>>=0;const g=Reflect.get(y(l+8),v(l+16));l=this._inst.exports.getsp()>>>0,x(l+32,g)},"syscall/js.valueSet":l=>{l>>>=0,Reflect.set(y(l+8),v(l+16),y(l+32))},"syscall/js.valueDelete":l=>{l>>>=0,Reflect.deleteProperty(y(l+8),v(l+16))},"syscall/js.valueIndex":l=>{l>>>=0,x(l+24,Reflect.get(y(l+8),f(l+16)))},"syscall/js.valueSetIndex":l=>{l>>>=0,Reflect.set(y(l+8),f(l+16),y(l+24))},"syscall/js.valueCall":l=>{l>>>=0;try{const g=y(l+8),P=Reflect.get(g,v(l+16)),R=D(l+32),H=Reflect.apply(P,g,R);l=this._inst.exports.getsp()>>>0,x(l+56,H),this.mem.setUint8(l+64,1)}catch(g){l=this._inst.exports.getsp()>>>0,x(l+56,g),this.mem.setUint8(l+64,0)}},"syscall/js.valueInvoke":l=>{l>>>=0;try{const g=y(l+8),P=D(l+16),R=Reflect.apply(g,void 0,P);l=this._inst.exports.getsp()>>>0,x(l+40,R),this.mem.setUint8(l+48,1)}catch(g){l=this._inst.exports.getsp()>>>0,x(l+40,g),this.mem.setUint8(l+48,0)}},"syscall/js.valueNew":l=>{l>>>=0;try{const g=y(l+8),P=D(l+16),R=Reflect.construct(g,P);l=this._inst.exports.getsp()>>>0,x(l+40,R),this.mem.setUint8(l+48,1)}catch(g){l=this._inst.exports.getsp()>>>0,x(l+40,g),this.mem.setUint8(l+48,0)}},"syscall/js.valueLength":l=>{l>>>=0,b(l+16,parseInt(y(l+8).length))},"syscall/js.valuePrepareString":l=>{l>>>=0;const g=B.encode(String(y(l+8)));x(l+16,g),b(l+24,g.length)},"syscall/js.valueLoadString":l=>{l>>>=0;const g=y(l+8);I(l+16).set(g)},"syscall/js.valueInstanceOf":l=>{l>>>=0,this.mem.setUint8(l+24,y(l+8)instanceof y(l+16)?1:0)},"syscall/js.copyBytesToGo":l=>{l>>>=0;const g=I(l+8),P=y(l+32);if(!(P instanceof Uint8Array||P instanceof Uint8ClampedArray)){this.mem.setUint8(l+48,0);return}const R=P.subarray(0,g.length);g.set(R),b(l+40,R.length),this.mem.setUint8(l+48,1)},"syscall/js.copyBytesToJS":l=>{l>>>=0;const g=y(l+8),P=I(l+16);if(!(g instanceof Uint8Array||g instanceof Uint8ClampedArray)){this.mem.setUint8(l+48,0);return}const R=P.subarray(0,g.length);g.set(R),b(l+40,R.length),this.mem.setUint8(l+48,1)},debug:l=>{console.log(l)}}}}run(b){return se(this,null,function*(){if(!(b instanceof WebAssembly.Instance))throw new Error("Go.run: WebAssembly.Instance expected");this._inst=b,this.mem=new DataView(this._inst.exports.mem.buffer),this._values=[NaN,0,null,!0,!1,z,this],this._goRefCounts=new Array(this._values.length).fill(1/0),this._ids=new Map([[0,1],[null,2],[!0,3],[!1,4],[z,5],[this,6]]),this._idPool=[],this.exited=!1;let f=4096;const y=U=>{const l=f,g=B.encode(U+"\0");return new Uint8Array(this.mem.buffer,f,g.length).set(g),f+=g.length,f%8!==0&&(f+=8-f%8),l},x=this.argv.length,I=[];this.argv.forEach(U=>{I.push(y(U))}),I.push(0),Object.keys(this.env).sort().forEach(U=>{I.push(y(`${U}=${this.env[U]}`))}),I.push(0);const v=f;if(I.forEach(U=>{this.mem.setUint32(f,U,!0),this.mem.setUint32(f+4,0,!0),f+=8}),f>=12288)throw new Error("total length of command line and environment variables exceeds limit");this._inst.exports.run(x,v),this.exited&&this._resolveExitPromise(),yield this._exitPromise})}_resume(){if(this.exited)throw new Error("Go program has already exited");this._inst.exports.resume(),this.exited&&this._resolveExitPromise()}_makeFuncWrapper(b){const f=this;return function(){const y={id:b,this:this,args:arguments};return f._pendingEvent=y,f._resume(),y.result}}}})(),ie=({data:W})=>{let B=new TextDecoder,T=z.fs,b="";T.writeSync=(D,v)=>{if(D===1)Q(v);else if(D===2){b+=B.decode(v);let S=b.split(`
694
+ `);S.length>1&&console.log(S.slice(0,-1).join(`
695
+ `)),b=S[S.length-1]}else throw new Error("Bad write");return v.length};let f=[],y,x=0;ie=({data:D})=>(D.length>0&&(f.push(D),y&&y()),I),T.read=(D,v,S,U,l,g)=>{if(D!==0||S!==0||U!==v.length||l!==null)throw new Error("Bad read");if(f.length===0){y=()=>T.read(D,v,S,U,l,g);return}let P=f[0],R=Math.max(0,Math.min(U,P.length-x));v.set(P.subarray(x,x+R),S),x+=R,x===P.length&&(f.shift(),x=0),g(null,R)};let I=new z.Go;return I.argv=["","--service=0.27.7"],ye(W,I).then(D=>{Q(null),I.run(D)},D=>{Q(D)}),I};function ye(W,B){return se(this,null,function*(){if(W instanceof WebAssembly.Module)return WebAssembly.instantiate(W,B.importObject);const T=yield fetch(W);if(!T.ok)throw new Error(`Failed to download ${JSON.stringify(W)}`);if("instantiateStreaming"in WebAssembly&&/^application\/wasm($|;)/i.test(T.headers.get("Content-Type")||""))return(yield WebAssembly.instantiateStreaming(T,B.importObject)).instance;const b=yield T.arrayBuffer();return(yield WebAssembly.instantiate(b,B.importObject)).instance})}return W=>ie(W)})(Q=>p.onmessage({data:Q})),ne;p={onmessage:null,postMessage:Q=>setTimeout(()=>{try{ne=V({data:Q})}catch(se){k(se)}}),terminate(){if(ne)for(let Q of ne._scheduledTimeouts.values())clearTimeout(Q)}}}let _,$;const m=new Promise((V,ne)=>{_=V,$=ne});p.onmessage=({data:V})=>{p.onmessage=({data:ne})=>O(ne),V?$(V):_()},p.postMessage(o||new URL(a,location.href).toString());let{readFromStdout:O,service:N}=sr({writeToStdin(V){p.postMessage(V)},isSync:!1,hasFS:!1,esbuild:A});yield m,Ot=()=>{p.terminate(),et=void 0,Ot=void 0,$t=void 0},$t={build:V=>new Promise((ne,Q)=>{E.then(Q),N.buildOrContext({callName:"build",refs:null,options:V,isTTY:!1,defaultWD:"/",callback:(se,ie)=>se?Q(se):ne(ie)})}),context:V=>new Promise((ne,Q)=>{E.then(Q),N.buildOrContext({callName:"context",refs:null,options:V,isTTY:!1,defaultWD:"/",callback:(se,ie)=>se?Q(se):ne(ie)})}),transform:(V,ne)=>new Promise((Q,se)=>{E.then(se),N.transform({callName:"transform",refs:null,input:V,options:ne||{},isTTY:!1,fs:{readFile(ie,z){z(new Error("Internal error"),null)},writeFile(ie,z){z(null)}},callback:(ie,z)=>ie?se(ie):Q(z)})}),formatMessages:(V,ne)=>new Promise((Q,se)=>{E.then(se),N.formatMessages({callName:"formatMessages",refs:null,messages:V,options:ne,callback:(ie,z)=>ie?se(ie):Q(z)})}),analyzeMetafile:(V,ne)=>new Promise((Q,se)=>{E.then(se),N.analyzeMetafile({callName:"analyzeMetafile",refs:null,metafile:typeof V=="string"?V:JSON.stringify(V),options:ne,callback:(ie,z)=>ie?se(ie):Q(z)})})}}),kr=A})(n)})(Ft)),Ft.exports}var tn=$r(),de;(function(n){n.assertEqual=s=>{};function e(s){}n.assertIs=e;function t(s){throw new Error}n.assertNever=t,n.arrayToEnum=s=>{const i={};for(const c of s)i[c]=c;return i},n.getValidEnumValues=s=>{const i=n.objectKeys(s).filter(d=>typeof s[s[d]]!="number"),c={};for(const d of i)c[d]=s[d];return n.objectValues(c)},n.objectValues=s=>n.objectKeys(s).map(function(i){return s[i]}),n.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const i=[];for(const c in s)Object.prototype.hasOwnProperty.call(s,c)&&i.push(c);return i},n.find=(s,i)=>{for(const c of s)if(i(c))return c},n.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(c=>typeof c=="string"?`'${c}'`:c).join(i)}n.joinValues=r,n.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(de||(de={}));var wn;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(wn||(wn={}));const Z=de.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),He=n=>{switch(typeof n){case"undefined":return Z.undefined;case"string":return Z.string;case"number":return Number.isNaN(n)?Z.nan:Z.number;case"boolean":return Z.boolean;case"function":return Z.function;case"bigint":return Z.bigint;case"symbol":return Z.symbol;case"object":return Array.isArray(n)?Z.array:n===null?Z.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?Z.promise:typeof Map<"u"&&n instanceof Map?Z.map:typeof Set<"u"&&n instanceof Set?Z.set:typeof Date<"u"&&n instanceof Date?Z.date:Z.object;default:return Z.unknown}},j=de.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 Je extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(i){return i.message},r={_errors:[]},s=i=>{for(const c of i.issues)if(c.code==="invalid_union")c.unionErrors.map(s);else if(c.code==="invalid_return_type")s(c.returnTypeError);else if(c.code==="invalid_arguments")s(c.argumentsError);else if(c.path.length===0)r._errors.push(t(c));else{let d=r,w=0;for(;w<c.path.length;){const C=c.path[w];w===c.path.length-1?(d[C]=d[C]||{_errors:[]},d[C]._errors.push(t(c))):d[C]=d[C]||{_errors:[]},d=d[C],w++}}};return s(this),r}static assert(e){if(!(e instanceof Je))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,de.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},r=[];for(const s of this.issues)if(s.path.length>0){const i=s.path[0];t[i]=t[i]||[],t[i].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}Je.create=n=>new Je(n);const Gt=(n,e)=>{let t;switch(n.code){case j.invalid_type:n.received===Z.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case j.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,de.jsonStringifyReplacer)}`;break;case j.unrecognized_keys:t=`Unrecognized key(s) in object: ${de.joinValues(n.keys,", ")}`;break;case j.invalid_union:t="Invalid input";break;case j.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${de.joinValues(n.options)}`;break;case j.invalid_enum_value:t=`Invalid enum value. Expected ${de.joinValues(n.options)}, received '${n.received}'`;break;case j.invalid_arguments:t="Invalid function arguments";break;case j.invalid_return_type:t="Invalid function return type";break;case j.invalid_date:t="Invalid date";break;case j.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:de.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case j.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case j.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case j.custom:t="Invalid input";break;case j.invalid_intersection_types:t="Intersection results could not be merged";break;case j.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case j.not_finite:t="Number must be finite";break;default:t=e.defaultError,de.assertNever(n)}return{message:t}};let Rr=Gt;function Ar(){return Rr}const Pr=n=>{const{data:e,path:t,errorMaps:r,issueData:s}=n,i=[...t,...s.path||[]],c={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let d="";const w=r.filter(C=>!!C).slice().reverse();for(const C of w)d=C(c,{data:e,defaultError:d}).message;return{...s,path:i,message:d}};function M(n,e){const t=Ar(),r=Pr({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===Gt?void 0:Gt].filter(s=>!!s)});n.common.issues.push(r)}class Se{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const s of t){if(s.status==="aborted")return X;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const s of t){const i=await s.key,c=await s.value;r.push({key:i,value:c})}return Se.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const s of t){const{key:i,value:c}=s;if(i.status==="aborted"||c.status==="aborted")return X;i.status==="dirty"&&e.dirty(),c.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof c.value<"u"||s.alwaysSet)&&(r[i.value]=c.value)}return{status:e.value,value:r}}}const X=Object.freeze({status:"aborted"}),gt=n=>({status:"dirty",value:n}),Pe=n=>({status:"valid",value:n}),_n=n=>n.status==="aborted",bn=n=>n.status==="dirty",lt=n=>n.status==="valid",Pt=n=>typeof Promise<"u"&&n instanceof Promise;var q;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(q||(q={}));class De{constructor(e,t,r,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=s}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 xn=(n,e)=>{if(lt(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new Je(n.common.issues);return this._error=t,this._error}}};function ee(n){if(!n)return{};const{errorMap:e,invalid_type_error:t,required_error:r,description:s}=n;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(c,d)=>{const{message:w}=n;return c.code==="invalid_enum_value"?{message:w??d.defaultError}:typeof d.data>"u"?{message:w??r??d.defaultError}:c.code!=="invalid_type"?{message:d.defaultError}:{message:w??t??d.defaultError}},description:s}}class oe{get description(){return this._def.description}_getType(e){return He(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:He(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Se,ctx:{common:e.parent.common,data:e.data,parsedType:He(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(Pt(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:(t==null?void 0:t.async)??!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:He(e)},s=this._parseSync({data:e,path:r.path,parent:r});return xn(r,s)}"~validate"(e){var r,s;const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:He(e)};if(!this["~standard"].async)try{const i=this._parseSync({data:e,path:[],parent:t});return lt(i)?{value:i.value}:{issues:t.common.issues}}catch(i){(s=(r=i==null?void 0:i.message)==null?void 0:r.toLowerCase())!=null&&s.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(i=>lt(i)?{value:i.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:He(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(Pt(s)?s:Promise.resolve(s));return xn(r,i)}refine(e,t){const r=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{const c=e(s),d=()=>i.addIssue({code:j.custom,...r(s)});return typeof Promise<"u"&&c instanceof Promise?c.then(w=>w?!0:(d(),!1)):c?!0:(d(),!1)})}refinement(e,t){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof t=="function"?t(r,s):t),!1))}_refinement(e){return new ut({schema:this,typeName:Y.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:t=>this["~validate"](t)}}optional(){return Ye.create(this,this._def)}nullable(){return dt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Le.create(this)}promise(){return Lt.create(this,this._def)}or(e){return It.create([this,e],this._def)}and(e){return Ut.create(this,e,this._def)}transform(e){return new ut({...ee(this._def),schema:this,typeName:Y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Kt({...ee(this._def),innerType:this,defaultValue:t,typeName:Y.ZodDefault})}brand(){return new ns({typeName:Y.ZodBranded,type:this,...ee(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Qt({...ee(this._def),innerType:this,catchValue:t,typeName:Y.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return nn.create(this,e)}readonly(){return en.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Nr=/^c[^\s-]{8,}$/i,Ir=/^[0-9a-z]+$/,Ur=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Mr=/^[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,Lr=/^[a-z0-9_-]{21}$/i,Dr=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Fr=/^[-+]?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)?)??$/,Vr=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Br="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Vt;const Zr=/^(?:(?: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])$/,Wr=/^(?:(?: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])$/,zr=/^(([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]))$/,qr=/^(([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])$/,Jr=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Gr=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ln="((\\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])))",Hr=new RegExp(`^${Ln}$`);function Dn(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);const t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Yr(n){return new RegExp(`^${Dn(n)}$`)}function Xr(n){let e=`${Ln}T${Dn(n)}`;const t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Kr(n,e){return!!((e==="v4"||!e)&&Zr.test(n)||(e==="v6"||!e)&&zr.test(n))}function Qr(n,e){if(!Dr.test(n))return!1;try{const[t]=n.split(".");if(!t)return!1;const r=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&(s==null?void 0:s.typ)!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function es(n,e){return!!((e==="v4"||!e)&&Wr.test(n)||(e==="v6"||!e)&&qr.test(n))}class qe extends oe{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Z.string){const i=this._getOrReturnCtx(e);return M(i,{code:j.invalid_type,expected:Z.string,received:i.parsedType}),X}const r=new Se;let s;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),M(s,{code:j.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),M(s,{code:j.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const c=e.data.length>i.value,d=e.data.length<i.value;(c||d)&&(s=this._getOrReturnCtx(e,s),c?M(s,{code:j.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):d&&M(s,{code:j.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")Vr.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"email",code:j.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Vt||(Vt=new RegExp(Br,"u")),Vt.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"emoji",code:j.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")Mr.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"uuid",code:j.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Lr.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"nanoid",code:j.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Nr.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"cuid",code:j.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")Ir.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"cuid2",code:j.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Ur.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"ulid",code:j.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),M(s,{validation:"url",code:j.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"regex",code:j.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),M(s,{code:j.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),M(s,{code:j.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),M(s,{code:j.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Xr(i).test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{code:j.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Hr.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{code:j.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Yr(i).test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{code:j.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?Fr.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"duration",code:j.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?Kr(e.data,i.version)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"ip",code:j.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?Qr(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"jwt",code:j.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?es(e.data,i.version)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"cidr",code:j.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?Jr.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"base64",code:j.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?Gr.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"base64url",code:j.invalid_string,message:i.message}),r.dirty()):de.assertNever(i);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(s=>e.test(s),{validation:t,code:j.invalid_string,...q.errToObj(r)})}_addCheck(e){return new qe({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...q.errToObj(e)})}url(e){return this._addCheck({kind:"url",...q.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...q.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...q.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...q.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...q.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...q.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...q.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...q.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...q.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...q.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...q.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...q.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==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(e==null?void 0:e.offset)??!1,local:(e==null?void 0:e.local)??!1,...q.errToObj(e==null?void 0: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==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...q.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...q.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...q.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...q.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...q.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...q.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...q.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...q.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...q.errToObj(t)})}nonempty(e){return this.min(1,q.errToObj(e))}trim(){return new qe({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new qe({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new qe({...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 t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}qe.create=n=>new qe({checks:[],typeName:Y.ZodString,coerce:(n==null?void 0:n.coerce)??!1,...ee(n)});function ts(n,e){const t=(n.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=t>r?t:r,i=Number.parseInt(n.toFixed(s).replace(".","")),c=Number.parseInt(e.toFixed(s).replace(".",""));return i%c/10**s}class vt extends oe{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)!==Z.number){const i=this._getOrReturnCtx(e);return M(i,{code:j.invalid_type,expected:Z.number,received:i.parsedType}),X}let r;const s=new Se;for(const i of this._def.checks)i.kind==="int"?de.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),M(r,{code:j.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),M(r,{code:j.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),M(r,{code:j.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?ts(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),M(r,{code:j.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),M(r,{code:j.not_finite,message:i.message}),s.dirty()):de.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,q.toString(t))}gt(e,t){return this.setLimit("min",e,!1,q.toString(t))}lte(e,t){return this.setLimit("max",e,!0,q.toString(t))}lt(e,t){return this.setLimit("max",e,!1,q.toString(t))}setLimit(e,t,r,s){return new vt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:q.toString(s)}]})}_addCheck(e){return new vt({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:q.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:q.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:q.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:q.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:q.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:q.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:q.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:q.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:q.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&de.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}vt.create=n=>new vt({checks:[],typeName:Y.ZodNumber,coerce:(n==null?void 0:n.coerce)||!1,...ee(n)});class wt extends oe{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)!==Z.bigint)return this._getInvalidInput(e);let r;const s=new Se;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),M(r,{code:j.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),M(r,{code:j.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),M(r,{code:j.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):de.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return M(t,{code:j.invalid_type,expected:Z.bigint,received:t.parsedType}),X}gte(e,t){return this.setLimit("min",e,!0,q.toString(t))}gt(e,t){return this.setLimit("min",e,!1,q.toString(t))}lte(e,t){return this.setLimit("max",e,!0,q.toString(t))}lt(e,t){return this.setLimit("max",e,!1,q.toString(t))}setLimit(e,t,r,s){return new wt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:q.toString(s)}]})}_addCheck(e){return new wt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:q.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:q.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:q.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:q.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:q.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}wt.create=n=>new wt({checks:[],typeName:Y.ZodBigInt,coerce:(n==null?void 0:n.coerce)??!1,...ee(n)});class Ht extends oe{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==Z.boolean){const r=this._getOrReturnCtx(e);return M(r,{code:j.invalid_type,expected:Z.boolean,received:r.parsedType}),X}return Pe(e.data)}}Ht.create=n=>new Ht({typeName:Y.ZodBoolean,coerce:(n==null?void 0:n.coerce)||!1,...ee(n)});class Nt extends oe{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Z.date){const i=this._getOrReturnCtx(e);return M(i,{code:j.invalid_type,expected:Z.date,received:i.parsedType}),X}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return M(i,{code:j.invalid_date}),X}const r=new Se;let s;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),M(s,{code:j.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),M(s,{code:j.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):de.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Nt({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:q.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:q.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}Nt.create=n=>new Nt({checks:[],coerce:(n==null?void 0:n.coerce)||!1,typeName:Y.ZodDate,...ee(n)});class kn extends oe{_parse(e){if(this._getType(e)!==Z.symbol){const r=this._getOrReturnCtx(e);return M(r,{code:j.invalid_type,expected:Z.symbol,received:r.parsedType}),X}return Pe(e.data)}}kn.create=n=>new kn({typeName:Y.ZodSymbol,...ee(n)});class En extends oe{_parse(e){if(this._getType(e)!==Z.undefined){const r=this._getOrReturnCtx(e);return M(r,{code:j.invalid_type,expected:Z.undefined,received:r.parsedType}),X}return Pe(e.data)}}En.create=n=>new En({typeName:Y.ZodUndefined,...ee(n)});class Sn extends oe{_parse(e){if(this._getType(e)!==Z.null){const r=this._getOrReturnCtx(e);return M(r,{code:j.invalid_type,expected:Z.null,received:r.parsedType}),X}return Pe(e.data)}}Sn.create=n=>new Sn({typeName:Y.ZodNull,...ee(n)});class _t extends oe{constructor(){super(...arguments),this._any=!0}_parse(e){return Pe(e.data)}}_t.create=n=>new _t({typeName:Y.ZodAny,...ee(n)});class Yt extends oe{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Pe(e.data)}}Yt.create=n=>new Yt({typeName:Y.ZodUnknown,...ee(n)});class Xe extends oe{_parse(e){const t=this._getOrReturnCtx(e);return M(t,{code:j.invalid_type,expected:Z.never,received:t.parsedType}),X}}Xe.create=n=>new Xe({typeName:Y.ZodNever,...ee(n)});class jn extends oe{_parse(e){if(this._getType(e)!==Z.undefined){const r=this._getOrReturnCtx(e);return M(r,{code:j.invalid_type,expected:Z.void,received:r.parsedType}),X}return Pe(e.data)}}jn.create=n=>new jn({typeName:Y.ZodVoid,...ee(n)});class Le extends oe{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==Z.array)return M(t,{code:j.invalid_type,expected:Z.array,received:t.parsedType}),X;if(s.exactLength!==null){const c=t.data.length>s.exactLength.value,d=t.data.length<s.exactLength.value;(c||d)&&(M(t,{code:c?j.too_big:j.too_small,minimum:d?s.exactLength.value:void 0,maximum:c?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(M(t,{code:j.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(M(t,{code:j.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((c,d)=>s.type._parseAsync(new De(t,c,t.path,d)))).then(c=>Se.mergeArray(r,c));const i=[...t.data].map((c,d)=>s.type._parseSync(new De(t,c,t.path,d)));return Se.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new Le({...this._def,minLength:{value:e,message:q.toString(t)}})}max(e,t){return new Le({...this._def,maxLength:{value:e,message:q.toString(t)}})}length(e,t){return new Le({...this._def,exactLength:{value:e,message:q.toString(t)}})}nonempty(e){return this.min(1,e)}}Le.create=(n,e)=>new Le({type:n,minLength:null,maxLength:null,exactLength:null,typeName:Y.ZodArray,...ee(e)});function at(n){if(n instanceof ke){const e={};for(const t in n.shape){const r=n.shape[t];e[t]=Ye.create(at(r))}return new ke({...n._def,shape:()=>e})}else return n instanceof Le?new Le({...n._def,type:at(n.element)}):n instanceof Ye?Ye.create(at(n.unwrap())):n instanceof dt?dt.create(at(n.unwrap())):n instanceof tt?tt.create(n.items.map(e=>at(e))):n}class ke extends oe{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(),t=de.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==Z.object){const C=this._getOrReturnCtx(e);return M(C,{code:j.invalid_type,expected:Z.object,received:C.parsedType}),X}const{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:c}=this._getCached(),d=[];if(!(this._def.catchall instanceof Xe&&this._def.unknownKeys==="strip"))for(const C in s.data)c.includes(C)||d.push(C);const w=[];for(const C of c){const A=i[C],G=s.data[C];w.push({key:{status:"valid",value:C},value:A._parse(new De(s,G,s.path,C)),alwaysSet:C in s.data})}if(this._def.catchall instanceof Xe){const C=this._def.unknownKeys;if(C==="passthrough")for(const A of d)w.push({key:{status:"valid",value:A},value:{status:"valid",value:s.data[A]}});else if(C==="strict")d.length>0&&(M(s,{code:j.unrecognized_keys,keys:d}),r.dirty());else if(C!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const C=this._def.catchall;for(const A of d){const G=s.data[A];w.push({key:{status:"valid",value:A},value:C._parse(new De(s,G,s.path,A)),alwaysSet:A in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const C=[];for(const A of w){const G=await A.key,ce=await A.value;C.push({key:G,value:ce,alwaysSet:A.alwaysSet})}return C}).then(C=>Se.mergeObjectSync(r,C)):Se.mergeObjectSync(r,w)}get shape(){return this._def.shape()}strict(e){return q.errToObj,new ke({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{var i,c;const s=((c=(i=this._def).errorMap)==null?void 0:c.call(i,t,r).message)??r.defaultError;return t.code==="unrecognized_keys"?{message:q.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new ke({...this._def,unknownKeys:"strip"})}passthrough(){return new ke({...this._def,unknownKeys:"passthrough"})}extend(e){return new ke({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ke({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Y.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ke({...this._def,catchall:e})}pick(e){const t={};for(const r of de.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new ke({...this._def,shape:()=>t})}omit(e){const t={};for(const r of de.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new ke({...this._def,shape:()=>t})}deepPartial(){return at(this)}partial(e){const t={};for(const r of de.objectKeys(this.shape)){const s=this.shape[r];e&&!e[r]?t[r]=s:t[r]=s.optional()}return new ke({...this._def,shape:()=>t})}required(e){const t={};for(const r of de.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Ye;)i=i._def.innerType;t[r]=i}return new ke({...this._def,shape:()=>t})}keyof(){return Fn(de.objectKeys(this.shape))}}ke.create=(n,e)=>new ke({shape:()=>n,unknownKeys:"strip",catchall:Xe.create(),typeName:Y.ZodObject,...ee(e)});ke.strictCreate=(n,e)=>new ke({shape:()=>n,unknownKeys:"strict",catchall:Xe.create(),typeName:Y.ZodObject,...ee(e)});ke.lazycreate=(n,e)=>new ke({shape:n,unknownKeys:"strip",catchall:Xe.create(),typeName:Y.ZodObject,...ee(e)});class It extends oe{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;function s(i){for(const d of i)if(d.result.status==="valid")return d.result;for(const d of i)if(d.result.status==="dirty")return t.common.issues.push(...d.ctx.common.issues),d.result;const c=i.map(d=>new Je(d.ctx.common.issues));return M(t,{code:j.invalid_union,unionErrors:c}),X}if(t.common.async)return Promise.all(r.map(async i=>{const c={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:c}),ctx:c}})).then(s);{let i;const c=[];for(const w of r){const C={...t,common:{...t.common,issues:[]},parent:null},A=w._parseSync({data:t.data,path:t.path,parent:C});if(A.status==="valid")return A;A.status==="dirty"&&!i&&(i={result:A,ctx:C}),C.common.issues.length&&c.push(C.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;const d=c.map(w=>new Je(w));return M(t,{code:j.invalid_union,unionErrors:d}),X}}get options(){return this._def.options}}It.create=(n,e)=>new It({options:n,typeName:Y.ZodUnion,...ee(e)});function Xt(n,e){const t=He(n),r=He(e);if(n===e)return{valid:!0,data:n};if(t===Z.object&&r===Z.object){const s=de.objectKeys(e),i=de.objectKeys(n).filter(d=>s.indexOf(d)!==-1),c={...n,...e};for(const d of i){const w=Xt(n[d],e[d]);if(!w.valid)return{valid:!1};c[d]=w.data}return{valid:!0,data:c}}else if(t===Z.array&&r===Z.array){if(n.length!==e.length)return{valid:!1};const s=[];for(let i=0;i<n.length;i++){const c=n[i],d=e[i],w=Xt(c,d);if(!w.valid)return{valid:!1};s.push(w.data)}return{valid:!0,data:s}}else return t===Z.date&&r===Z.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}class Ut extends oe{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=(i,c)=>{if(_n(i)||_n(c))return X;const d=Xt(i.value,c.value);return d.valid?((bn(i)||bn(c))&&t.dirty(),{status:t.value,value:d.data}):(M(r,{code:j.invalid_intersection_types}),X)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,c])=>s(i,c)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}Ut.create=(n,e,t)=>new Ut({left:n,right:e,typeName:Y.ZodIntersection,...ee(t)});class tt extends oe{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Z.array)return M(r,{code:j.invalid_type,expected:Z.array,received:r.parsedType}),X;if(r.data.length<this._def.items.length)return M(r,{code:j.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),X;!this._def.rest&&r.data.length>this._def.items.length&&(M(r,{code:j.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const i=[...r.data].map((c,d)=>{const w=this._def.items[d]||this._def.rest;return w?w._parse(new De(r,c,r.path,d)):null}).filter(c=>!!c);return r.common.async?Promise.all(i).then(c=>Se.mergeArray(t,c)):Se.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new tt({...this._def,rest:e})}}tt.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new tt({items:n,typeName:Y.ZodTuple,rest:null,...ee(e)})};class Mt extends oe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Z.object)return M(r,{code:j.invalid_type,expected:Z.object,received:r.parsedType}),X;const s=[],i=this._def.keyType,c=this._def.valueType;for(const d in r.data)s.push({key:i._parse(new De(r,d,r.path,d)),value:c._parse(new De(r,r.data[d],r.path,d)),alwaysSet:d in r.data});return r.common.async?Se.mergeObjectAsync(t,s):Se.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,r){return t instanceof oe?new Mt({keyType:e,valueType:t,typeName:Y.ZodRecord,...ee(r)}):new Mt({keyType:qe.create(),valueType:e,typeName:Y.ZodRecord,...ee(t)})}}class Cn extends oe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Z.map)return M(r,{code:j.invalid_type,expected:Z.map,received:r.parsedType}),X;const s=this._def.keyType,i=this._def.valueType,c=[...r.data.entries()].map(([d,w],C)=>({key:s._parse(new De(r,d,r.path,[C,"key"])),value:i._parse(new De(r,w,r.path,[C,"value"]))}));if(r.common.async){const d=new Map;return Promise.resolve().then(async()=>{for(const w of c){const C=await w.key,A=await w.value;if(C.status==="aborted"||A.status==="aborted")return X;(C.status==="dirty"||A.status==="dirty")&&t.dirty(),d.set(C.value,A.value)}return{status:t.value,value:d}})}else{const d=new Map;for(const w of c){const C=w.key,A=w.value;if(C.status==="aborted"||A.status==="aborted")return X;(C.status==="dirty"||A.status==="dirty")&&t.dirty(),d.set(C.value,A.value)}return{status:t.value,value:d}}}}Cn.create=(n,e,t)=>new Cn({valueType:e,keyType:n,typeName:Y.ZodMap,...ee(t)});class bt extends oe{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Z.set)return M(r,{code:j.invalid_type,expected:Z.set,received:r.parsedType}),X;const s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(M(r,{code:j.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(M(r,{code:j.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const i=this._def.valueType;function c(w){const C=new Set;for(const A of w){if(A.status==="aborted")return X;A.status==="dirty"&&t.dirty(),C.add(A.value)}return{status:t.value,value:C}}const d=[...r.data.values()].map((w,C)=>i._parse(new De(r,w,r.path,C)));return r.common.async?Promise.all(d).then(w=>c(w)):c(d)}min(e,t){return new bt({...this._def,minSize:{value:e,message:q.toString(t)}})}max(e,t){return new bt({...this._def,maxSize:{value:e,message:q.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}bt.create=(n,e)=>new bt({valueType:n,minSize:null,maxSize:null,typeName:Y.ZodSet,...ee(e)});class Tn extends oe{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Tn.create=(n,e)=>new Tn({getter:n,typeName:Y.ZodLazy,...ee(e)});class On extends oe{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return M(t,{received:t.data,code:j.invalid_literal,expected:this._def.value}),X}return{status:"valid",value:e.data}}get value(){return this._def.value}}On.create=(n,e)=>new On({value:n,typeName:Y.ZodLiteral,...ee(e)});function Fn(n,e){return new ct({values:n,typeName:Y.ZodEnum,...ee(e)})}class ct extends oe{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),r=this._def.values;return M(t,{expected:de.joinValues(r),received:t.parsedType,code:j.invalid_type}),X}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return M(t,{received:t.data,code:j.invalid_enum_value,options:r}),X}return Pe(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ct.create(e,{...this._def,...t})}exclude(e,t=this._def){return ct.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}}ct.create=Fn;class $n extends oe{_parse(e){const t=de.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==Z.string&&r.parsedType!==Z.number){const s=de.objectValues(t);return M(r,{expected:de.joinValues(s),received:r.parsedType,code:j.invalid_type}),X}if(this._cache||(this._cache=new Set(de.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=de.objectValues(t);return M(r,{received:r.data,code:j.invalid_enum_value,options:s}),X}return Pe(e.data)}get enum(){return this._def.values}}$n.create=(n,e)=>new $n({values:n,typeName:Y.ZodNativeEnum,...ee(e)});class Lt extends oe{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==Z.promise&&t.common.async===!1)return M(t,{code:j.invalid_type,expected:Z.promise,received:t.parsedType}),X;const r=t.parsedType===Z.promise?t.data:Promise.resolve(t.data);return Pe(r.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Lt.create=(n,e)=>new Lt({type:n,typeName:Y.ZodPromise,...ee(e)});class ut extends oe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:c=>{M(r,c),c.fatal?t.abort():t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){const c=s.transform(r.data,i);if(r.common.async)return Promise.resolve(c).then(async d=>{if(t.value==="aborted")return X;const w=await this._def.schema._parseAsync({data:d,path:r.path,parent:r});return w.status==="aborted"?X:w.status==="dirty"||t.value==="dirty"?gt(w.value):w});{if(t.value==="aborted")return X;const d=this._def.schema._parseSync({data:c,path:r.path,parent:r});return d.status==="aborted"?X:d.status==="dirty"||t.value==="dirty"?gt(d.value):d}}if(s.type==="refinement"){const c=d=>{const w=s.refinement(d,i);if(r.common.async)return Promise.resolve(w);if(w instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return d};if(r.common.async===!1){const d=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return d.status==="aborted"?X:(d.status==="dirty"&&t.dirty(),c(d.value),{status:t.value,value:d.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(d=>d.status==="aborted"?X:(d.status==="dirty"&&t.dirty(),c(d.value).then(()=>({status:t.value,value:d.value}))))}if(s.type==="transform")if(r.common.async===!1){const c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!lt(c))return X;const d=s.transform(c.value,i);if(d instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:d}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>lt(c)?Promise.resolve(s.transform(c.value,i)).then(d=>({status:t.value,value:d})):X);de.assertNever(s)}}ut.create=(n,e,t)=>new ut({schema:n,typeName:Y.ZodEffects,effect:e,...ee(t)});ut.createWithPreprocess=(n,e,t)=>new ut({schema:e,effect:{type:"preprocess",transform:n},typeName:Y.ZodEffects,...ee(t)});class Ye extends oe{_parse(e){return this._getType(e)===Z.undefined?Pe(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ye.create=(n,e)=>new Ye({innerType:n,typeName:Y.ZodOptional,...ee(e)});class dt extends oe{_parse(e){return this._getType(e)===Z.null?Pe(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}dt.create=(n,e)=>new dt({innerType:n,typeName:Y.ZodNullable,...ee(e)});class Kt extends oe{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===Z.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Kt.create=(n,e)=>new Kt({innerType:n,typeName:Y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ee(e)});class Qt extends oe{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Pt(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Je(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Je(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Qt.create=(n,e)=>new Qt({innerType:n,typeName:Y.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ee(e)});class Rn extends oe{_parse(e){if(this._getType(e)!==Z.nan){const r=this._getOrReturnCtx(e);return M(r,{code:j.invalid_type,expected:Z.nan,received:r.parsedType}),X}return{status:"valid",value:e.data}}}Rn.create=n=>new Rn({typeName:Y.ZodNaN,...ee(n)});class ns extends oe{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class nn extends oe{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?X:i.status==="dirty"?(t.dirty(),gt(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?X:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,t){return new nn({in:e,out:t,typeName:Y.ZodPipeline})}}class en extends oe{_parse(e){const t=this._def.innerType._parse(e),r=s=>(lt(s)&&(s.value=Object.freeze(s.value)),s);return Pt(t)?t.then(s=>r(s)):r(t)}unwrap(){return this._def.innerType}}en.create=(n,e)=>new en({innerType:n,typeName:Y.ZodReadonly,...ee(e)});function An(n,e){const t=typeof n=="function"?n(e):typeof n=="string"?{message:n}:n;return typeof t=="string"?{message:t}:t}function rs(n,e={},t){return n?_t.create().superRefine((r,s)=>{const i=n(r);if(i instanceof Promise)return i.then(c=>{if(!c){const d=An(e,r),w=d.fatal??t??!0;s.addIssue({code:"custom",...d,fatal:w})}});if(!i){const c=An(e,r),d=c.fatal??t??!0;s.addIssue({code:"custom",...c,fatal:d})}}):_t.create()}var Y;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(Y||(Y={}));const ve=qe.create,Vn=Ht.create;_t.create;const Bn=Yt.create;Xe.create;const rn=Le.create,rt=ke.create;It.create;Ut.create;tt.create;const nt=Mt.create,xt=ct.create;Lt.create;Ye.create;dt.create;var Zn=xt(["browser","cli"]),ss=rt({target:ve().optional(),format:xt(["esm","cjs","iife"]).optional(),jsx:xt(["automatic","transform","preserve"]).optional(),jsxFactory:ve().optional(),jsxFragment:ve().optional()}).strict().optional(),is=rt({globals:nt(ve(),ve()).optional(),preload:rn(ve()).optional(),deps:nt(ve(),ve()).optional()}).strict().optional(),as=nt(ve(),ve()).optional(),os=nt(ve(),ve()).optional(),ls=rt({platform:Zn,dependencies:os,esbuild:ss,framework:is,aliases:as}).strict(),cs=rt({type:xt(["string","number","boolean","object","array"]),default:Bn().optional(),required:Vn().optional(),description:ve().optional()});rt({name:ve(),version:ve(),description:ve().optional(),platform:Zn,image:ve(),inputs:nt(ve(),cs).optional(),services:rn(ve()).optional(),packages:nt(ve(),ve()).optional()});rt({typescript:Vn().optional()}).strict().optional();var us=xt(["embedded","iframe"]);rt({target:rs(n=>n instanceof HTMLElement,{message:"Expected HTMLElement"}),mode:us,sandbox:rn(ve()).optional(),inputs:nt(ve(),Bn()).optional()});function Wn(n){const e=ls.safeParse(n);return e.success?e.data:null}var zn={platform:"browser",esbuild:{target:"es2020",format:"esm",jsx:"automatic"},framework:{}},ds="https://esm.sh",sn=ds;function Bt(n){sn=n}function qn(){return sn}function kt(n,e,t,r){let s=`${sn}/${n}`;if(e&&(s+=`@${e}`),t&&(s+=`/${t}`),r&&Object.keys(r).length>0){const i=Object.entries(r).map(([c,d])=>`${c}@${d}`).join(",");s+=`?deps=${i}`}return s}function Pn(n){return!(n.startsWith(".")||n.startsWith("/")||n.startsWith("http://")||n.startsWith("https://"))}function fs(n){if(n.startsWith("@")){const t=n.split("/");if(t.length>=2){const r=t[0],s=t.slice(1).join("/"),i=s.lastIndexOf("@");return i>0?{name:`${r}/${s.slice(0,i)}`,version:s.slice(i+1)}:{name:`${r}/${s}`}}}const e=n.lastIndexOf("@");return e>0?{name:n.slice(0,e),version:n.slice(e+1)}:{name:n}}function Rt(n){if(n.startsWith("@")){const s=n.split("/");if(s.length>=2){const i=`${s[0]}/${s[1]}`,c=s.slice(2).join("/");return{packageName:i,subpath:c||void 0}}}const e=n.split("/"),t=e[0],r=e.slice(1).join("/");return{packageName:t,subpath:r||void 0}}function hs(n,e){for(const[t,r]of Object.entries(e)){if(t.endsWith("/*")){const s=t.slice(0,-2);if(n===s||n.startsWith(s+"/"))return r}if(n===t)return r}return null}var ms={react:["useState","useEffect","useCallback","useMemo","useRef","useContext","useReducer","useLayoutEffect","useId","createContext","createElement","cloneElement","createRef","forwardRef","lazy","memo","Fragment","Suspense","StrictMode","Component","PureComponent","Children","isValidElement"],"react-dom":["createPortal","flushSync","render","hydrate","unmountComponentAtNode"]};function Nn(n){return ms[n]??[]}function yt(n){return fs(n)}async function ps(n,e){const t=qn(),r=e?`@${e}`:"",s=`${t}/${n}${r}/package.json`,i=await fetch(s);if(!i.ok)throw new Error(`Failed to fetch package.json for ${n}: ${i.statusText}`);return i.json()}async function gs(n){if(typeof globalThis.require>"u"&&typeof process>"u")return null;try{const{createRequire:e}=await Dt(async()=>{const{createRequire:ue}=await import("./__vite-browser-external-BIHI7g3E.js");return{createRequire:ue}},[],import.meta.url),{readFile:t}=await Dt(async()=>{const{readFile:ue}=await import("./__vite-browser-external-BIHI7g3E.js");return{readFile:ue}},[],import.meta.url),{dirname:r,join:s}=await Dt(async()=>{const{dirname:ue,join:K}=await import("./__vite-browser-external-BIHI7g3E.js");return{dirname:ue,join:K}},[],import.meta.url),i=e(import.meta.url);let c;try{c=i.resolve(`${n}/package.json`)}catch{return null}const d=await t(c,"utf-8"),w=JSON.parse(d),C=Wn(w.patchwork)||zn;let A,G;const ce=r(c);if(w.main)try{const K=await import(s(ce,w.main));typeof K.setup=="function"&&(A=K.setup),typeof K.mount=="function"&&(G=K.mount)}catch{}return{name:w.name,version:w.version,config:C,dependencies:w.dependencies||{},setup:A,mount:G}}catch{return null}}async function ys(n){const{name:e,version:t}=yt(n),r=await gs(e);if(r)return r;const s=await ps(e,t),i=Wn(s.patchwork)||zn;let c,d,w;if(s.main&&typeof window<"u")try{const C=qn(),A=t?`@${t}`:"",G=s.main.startsWith("./")?s.main.slice(2):s.main,ce=`${C}/${e}${A}/${G}`;w=ce;const ue=await import(ce);typeof ue.setup=="function"&&(c=ue.setup),typeof ue.mount=="function"&&(d=ue.mount)}catch(C){console.error("[patchwork-compiler] Failed to load image module:",C)}return{name:s.name,version:s.version,moduleUrl:w,config:i,dependencies:s.dependencies||{},setup:c,mount:d}}var vs=class{constructor(){ze(this,"images",new Map);ze(this,"loading",new Map)}get(n){const{name:e}=yt(n);return this.images.get(e)}has(n){const{name:e}=yt(n);return this.images.has(e)}async load(n){const{name:e}=yt(n),t=this.images.get(e);if(t)return t;const r=this.loading.get(e);if(r)return r;const s=ys(n).then(i=>(this.images.set(e,i),this.loading.delete(e),i));return this.loading.set(e,s),s}async preload(n){await this.load(n)}clear(n){const{name:e}=yt(n);this.images.delete(e),this.loading.delete(e)}clearAll(){this.images.clear(),this.loading.clear()}getLoadedNames(){return Array.from(this.images.keys())}},Zt=null;function ws(){return Zt||(Zt=new vs),Zt}function _s(n){return{async call(e,t,r){const s=`${n}/${e}/${t}`,i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({args:r[0]??{}})});if(!i.ok)throw new Error(`Service call failed: ${i.status} ${i.statusText}`);return await i.json()}}}function bs(n,e){function t(r){const s=(...i)=>e(n,r,...i);return new Proxy(s,{get(i,c){if(typeof c=="symbol")return;const d=r?`${r}.${c}`:c;return t(d)}})}return new Proxy({},{get(r,s){if(typeof s!="symbol")return t(s)}})}function xs(n,e){const t={},r=an(n);for(const s of r)t[s]=bs(s,(i,c,...d)=>e.call(i,c,d));return t}function ks(n,e){for(const[t,r]of Object.entries(e))n[t]=r}function Es(n,e){for(const t of e)delete n[t]}function an(n){const e=new Set;for(const t of n){const r=t.split(".");r[0]&&e.add(r[0])}return Array.from(e)}var Ss=class{constructor(n){ze(this,"proxy");ze(this,"pendingCalls",new Map);ze(this,"iframes",new Set);ze(this,"messageHandler");this.proxy=n,this.messageHandler=this.handleMessage.bind(this),typeof window<"u"&&window.addEventListener("message",this.messageHandler)}registerIframe(n){this.iframes.add(n)}unregisterIframe(n){this.iframes.delete(n)}async handleMessage(n){var r,s;const e=Array.from(this.iframes).find(i=>i.contentWindow===n.source);if(!e)return;const t=n.data;if(!(!t||typeof t!="object")&&t.type==="service-call"){const i=t.payload;try{const c=await this.proxy.call(i.namespace,i.procedure,i.args),d={type:"service-result",id:t.id,payload:{result:c}};(r=e.contentWindow)==null||r.postMessage(d,"*")}catch(c){const d={type:"service-result",id:t.id,payload:{error:c instanceof Error?c.message:String(c)}};(s=e.contentWindow)==null||s.postMessage(d,"*")}}}dispose(){typeof window<"u"&&window.removeEventListener("message",this.messageHandler),this.iframes.clear(),this.pendingCalls.clear()}};function js(n){return`
696
+ (function() {
697
+ const pendingCalls = new Map();
698
+
699
+ window.addEventListener('message', function(event) {
700
+ const message = event.data;
701
+ if (!message || typeof message !== 'object') return;
702
+
703
+ if (message.type === 'service-result') {
704
+ const pending = pendingCalls.get(message.id);
705
+ if (pending) {
706
+ pendingCalls.delete(message.id);
707
+ if (message.payload.error) {
708
+ pending.reject(new Error(message.payload.error));
709
+ } else {
710
+ pending.resolve(message.payload.result);
711
+ }
712
+ }
713
+ }
714
+ });
715
+
716
+ function proxyCall(namespace, procedure, args) {
717
+ return new Promise(function(resolve, reject) {
718
+ const id = Date.now() + '-' + Math.random().toString(36).slice(2, 11);
719
+ pendingCalls.set(id, { resolve: resolve, reject: reject });
720
+
721
+ window.parent.postMessage({
722
+ type: 'service-call',
723
+ id: id,
724
+ payload: { namespace: namespace, procedure: procedure, args: args }
725
+ }, '*');
726
+
727
+ setTimeout(function() {
728
+ if (pendingCalls.has(id)) {
729
+ pendingCalls.delete(id);
730
+ reject(new Error('Service call timeout: ' + namespace + '.' + procedure));
731
+ }
732
+ }, 30000);
733
+ });
734
+ }
735
+
736
+ // Create a dynamic proxy for a namespace that supports arbitrary nested method calls
737
+ function createNamespaceProxy(namespace) {
738
+ function createNestedProxy(path) {
739
+ var fn = function() {
740
+ return proxyCall(namespace, path, Array.prototype.slice.call(arguments));
741
+ };
742
+
743
+ return new Proxy(fn, {
744
+ get: function(_, nestedName) {
745
+ if (typeof nestedName === 'symbol') return undefined;
746
+ var newPath = path ? path + '.' + nestedName : nestedName;
747
+ return createNestedProxy(newPath);
748
+ }
749
+ });
750
+ }
751
+
752
+ return new Proxy({}, {
753
+ get: function(_, fieldName) {
754
+ if (typeof fieldName === 'symbol') return undefined;
755
+ return createNestedProxy(fieldName);
756
+ }
757
+ });
758
+ }
759
+
760
+ ${an(n).map(r=>`window.${r} = createNamespaceProxy('${r}');`).join(`
761
+ `)}
762
+ })();
763
+ `}var Cs=0,Wt=!1;function Ts(n,e,t){if(Wt)return;if(document.querySelector('script[type="importmap"]')){Wt=!0;return}const s={};Object.keys(n).forEach((d,w)=>{e[w]?s[d]=e[w]:t!=null&&t[d]?s[d]=kt(d,t[d]):s[d]=kt(d)}),s["react-dom"]&&(s["react-dom/client"]=s["react-dom"]);const c=document.createElement("script");c.type="importmap",c.textContent=JSON.stringify({imports:s},null,2),document.head.insertBefore(c,document.head.firstChild),Wt=!0}function Os(){return`pw-mount-${Date.now()}-${++Cs}`}function $s(n){for(const e of n){const t=e==null?void 0:e.createElement;if(typeof t=="function")return t;const r=e==null?void 0:e.default;if(r&&typeof r.createElement=="function")return r.createElement}return null}function Rs(n){for(const e of n){if(e&&typeof e.createRoot=="function")return{kind:"root",createRoot:e.createRoot};if(e&&typeof e.render=="function")return{kind:"render",render:e.render};const t=e==null?void 0:e.default;if(t&&typeof t.createRoot=="function")return{kind:"root",createRoot:t.createRoot};if(t&&typeof t.render=="function")return{kind:"render",render:t.render}}return null}async function Jn(n,e,t,r){var Ge;const{target:s,inputs:i={}}=e,c=Os(),d=document.createElement("div");if(d.id=c,d.className="patchwork-widget patchwork-embedded",s.appendChild(d),t!=null&&t.setup&&await t.setup(d),t!=null&&t.css){const me=document.createElement("style");me.id=`${c}-style`,me.textContent=t.css,document.head.appendChild(me)}const w=n.manifest.services||[],C=an(w),A=xs(w,r);ks(window,A);const G=((Ge=t==null?void 0:t.config)==null?void 0:Ge.framework)||{},ce=G.preload||[],ue=G.globals||{},K=G.deps||{};Ts(ue,ce,K);const fe=await Promise.all(ce.map(me=>import(me))),xe=window,Oe=Object.values(ue);fe.forEach((me,we)=>{if(Oe[we]){const Ie=Oe[we];xe[Ie]=me}});const Ne=new Blob([n.code],{type:"application/javascript"}),Ee=URL.createObjectURL(Ne);let he;const Ue=Oe.map(me=>xe[me]).filter(Boolean);try{const me=await import(Ee);if(t!=null&&t.mount){const we=await t.mount(me,d,i);typeof we=="function"&&(he=we)}else if(typeof me.mount=="function"){const we=await me.mount(d,i);typeof we=="function"&&(he=we)}else if(typeof me.render=="function"){const we=await me.render(d,i);typeof we=="function"&&(he=we)}else if(typeof me.default=="function"){const we=me.default,Ie=$s(Ue),le=Rs(Ue);if(Ie&&(le==null?void 0:le.kind)==="root"){const L=le.createRoot(d);L.render(Ie(we,i)),typeof L.unmount=="function"&&(he=()=>L.unmount())}else if(Ie&&(le==null?void 0:le.kind)==="render")le.render(Ie(we,i),d);else{const L=we(i);L instanceof HTMLElement?d.appendChild(L):typeof L=="string"&&(d.innerHTML=L)}}}finally{URL.revokeObjectURL(Ee)}return{id:c,widget:n,mode:"embedded",target:s,inputs:i,unmount:()=>{he&&he(),Es(window,C);const me=document.getElementById(`${c}-style`);me&&me.remove(),d.remove()}}}async function As(n,e,t,r){return n.unmount(),Jn(e,{target:n.target,inputs:n.inputs},t,r)}var Ps=new Set(["react","react-dom","ink"]),Ns=new Set(["assert","buffer","child_process","cluster","crypto","dgram","dns","events","fs","http","http2","https","net","os","path","perf_hooks","process","querystring","readline","stream","string_decoder","timers","tls","tty","url","util","v8","vm","worker_threads","zlib"]);function Is(n={}){const{packages:e={},external:t=[],bundle:r=!1,globals:s={},deps:i={},aliases:c={}}=n,d=new Set([...Ps,...t]),w=new Set(Object.keys(s));return{name:"cdn-transform",setup(C){C.onResolve({filter:/.*/},A=>{const G=hs(A.path,c);if(G){const{packageName:ce,subpath:ue}=Rt(G);if(w.has(ce))return{path:G,namespace:"global-inject"};const K=e[ce];let fe=kt(ce,K,ue,Object.keys(i).length>0?i:void 0);return r&&(fe+=fe.includes("?")?"&bundle":"?bundle"),{path:fe,external:!0}}return null}),C.onResolve({filter:/.*/},A=>{if(!Pn(A.path))return null;const{packageName:G}=Rt(A.path);return w.has(G)?{path:A.path,namespace:"global-inject"}:null}),C.onLoad({filter:/.*/,namespace:"global-inject"},A=>{const{packageName:G,subpath:ce}=Rt(A.path),ue=s[G];return ue?ce?{contents:`export * from '${G}'; export { default } from '${G}';`,loader:"js"}:{contents:`
764
+ const mod = window.${ue};
765
+ export default mod;
766
+ // Re-export all properties as named exports
767
+ const { ${Nn(G).join(", ")} } = mod;
768
+ export { ${Nn(G).join(", ")} };
769
+ `,loader:"js"}:null}),C.onResolve({filter:/.*/},A=>{if(!Pn(A.path))return null;if(Ns.has(A.path))return{external:!0};const{packageName:G,subpath:ce}=Rt(A.path);if(w.has(G))return null;if(d.has(G))return{external:!0};const ue=e[G];let K=kt(G,ue,ce,Object.keys(i).length>0?i:void 0);return r&&(K+=K.includes("?")?"&bundle":"?bundle"),{path:K,external:!0}})}}}function Us(n){const e={};for(const[t,r]of Object.entries(n))e[t]=kt(t,r);return e}var Ms=0,zt=null;function Ls(n){return zt||(zt=new Ss(n)),zt}function Ds(){return`pw-iframe-${Date.now()}-${++Ms}`}var Fs=["allow-scripts"];function Vs(n,e,t,r){var K;const s=js(t),i={...(n==null?void 0:n.dependencies)||{}},c=Us(i),d=(n==null?void 0:n.css)||"",w=((K=n==null?void 0:n.config)==null?void 0:K.framework)||{},C=w.preload||[],A=w.globals||{},G=Object.values(A),ce=(n==null?void 0:n.moduleUrl)||"",ue=`
770
+ // Run image setup inside the iframe (styling/runtime)
771
+ const imageModuleUrl = ${JSON.stringify(ce)};
772
+
773
+ // Preload framework modules declared by the image (if any)
774
+ const preloadUrls = ${JSON.stringify(C)};
775
+ const globalNames = ${JSON.stringify(G)};
776
+ for (let i = 0; i < preloadUrls.length; i++) {
777
+ const url = preloadUrls[i];
778
+ const name = globalNames[i];
779
+ if (!url || !name) continue;
780
+ try {
781
+ const mod = await import(/* webpackIgnore: true */ url);
782
+ window[name] = mod;
783
+ } catch (e) {
784
+ console.error('[patchwork-iframe] Failed to preload:', url, e);
785
+ }
786
+ }
787
+
788
+ const root = document.getElementById('root');
789
+ const inputs = window.__PATCHWORK_INPUTS__ || {};
790
+
791
+ if (imageModuleUrl && root) {
792
+ try {
793
+ const img = await import(/* webpackIgnore: true */ imageModuleUrl);
794
+ if (typeof img?.setup === 'function') {
795
+ await img.setup(root);
796
+ }
797
+ } catch (e) {
798
+ console.error('[patchwork-iframe] Failed to run image setup:', e);
799
+ }
800
+ }
801
+
802
+ function pickCreateElement(globals) {
803
+ for (const obj of globals) {
804
+ if (obj && typeof obj.createElement === 'function') return obj.createElement.bind(obj);
805
+ if (obj?.default && typeof obj.default.createElement === 'function') return obj.default.createElement.bind(obj.default);
806
+ }
807
+ return null;
808
+ }
809
+
810
+ function pickRenderer(globals) {
811
+ for (const obj of globals) {
812
+ if (obj && typeof obj.createRoot === 'function') {
813
+ return {
814
+ kind: 'root',
815
+ createRoot: obj.createRoot.bind(obj),
816
+ };
817
+ }
818
+ if (obj && typeof obj.render === 'function') {
819
+ return {
820
+ kind: 'render',
821
+ render: obj.render.bind(obj),
822
+ };
823
+ }
824
+ if (obj?.default && typeof obj.default.createRoot === 'function') {
825
+ return {
826
+ kind: 'root',
827
+ createRoot: obj.default.createRoot.bind(obj.default),
828
+ };
829
+ }
830
+ if (obj?.default && typeof obj.default.render === 'function') {
831
+ return {
832
+ kind: 'render',
833
+ render: obj.default.render.bind(obj.default),
834
+ };
835
+ }
836
+ }
837
+ return null;
838
+ }
839
+
840
+ function getGlobalsFromConfig() {
841
+ const names = ${JSON.stringify(G)};
842
+ return names.map((n) => window[n]).filter(Boolean);
843
+ }
844
+
845
+ async function mountModule(mod) {
846
+ if (!root) throw new Error('No #root element');
847
+
848
+ if (typeof mod?.mount === 'function') {
849
+ const cleanup = await mod.mount(root, inputs);
850
+ if (typeof cleanup === 'function') window.__PATCHWORK_CLEANUP__ = cleanup;
851
+ return;
852
+ }
853
+
854
+ if (typeof mod?.render === 'function') {
855
+ const cleanup = await mod.render(root, inputs);
856
+ if (typeof cleanup === 'function') window.__PATCHWORK_CLEANUP__ = cleanup;
857
+ return;
858
+ }
859
+
860
+ const Component = mod?.default;
861
+ if (typeof Component !== 'function') {
862
+ root.textContent = 'Widget did not export a default component.';
863
+ return;
864
+ }
865
+
866
+ const globals = getGlobalsFromConfig();
867
+ const createElement = pickCreateElement(globals);
868
+ const renderer = pickRenderer(globals);
869
+
870
+ if (createElement && renderer?.kind === 'root') {
871
+ const r = renderer.createRoot(root);
872
+ r.render(createElement(Component, inputs));
873
+ if (typeof r.unmount === 'function') window.__PATCHWORK_CLEANUP__ = () => r.unmount();
874
+ return;
875
+ }
876
+
877
+ if (createElement && renderer?.kind === 'render') {
878
+ renderer.render(createElement(Component, inputs), root);
879
+ return;
880
+ }
881
+
882
+ const result = Component(inputs);
883
+ if (result instanceof HTMLElement) {
884
+ root.appendChild(result);
885
+ return;
886
+ }
887
+ if (typeof result === 'string') {
888
+ root.innerHTML = result;
889
+ return;
890
+ }
891
+
892
+ root.textContent = 'No framework renderer available for this widget.';
893
+ }
894
+
895
+ // Wait for widget code via postMessage (more efficient than inline in srcdoc)
896
+ // We convert relative URLs to absolute so they work inside blob URL context
897
+ window.addEventListener('message', async function handleWidgetCode(event) {
898
+ if (!event.data || event.data.type !== 'widget-code') return;
899
+ window.removeEventListener('message', handleWidgetCode);
900
+
901
+ const widgetCode = event.data.code;
902
+ const origin = event.data.origin || ''; // Parent sends the origin
903
+
904
+ // Convert relative URLs (starting with /) to absolute URLs
905
+ // This is necessary because blob: URLs can't resolve relative imports
906
+ // and srcdoc iframes have null origin
907
+ const absoluteCode = widgetCode.replace(
908
+ /from\\s*["'](\\/[^"']+)["']/g,
909
+ (_, path) => 'from "' + origin + path + '"'
910
+ ).replace(
911
+ /import\\s*["'](\\/[^"']+)["']/g,
912
+ (_, path) => 'import "' + origin + path + '"'
913
+ );
914
+
915
+ const blob = new Blob([absoluteCode], { type: 'application/javascript' });
916
+ const url = URL.createObjectURL(blob);
917
+
918
+ try {
919
+ const mod = await import(/* webpackIgnore: true */ url);
920
+ await mountModule(mod);
921
+ window.parent.postMessage({ type: 'widget-mounted' }, '*');
922
+ } catch (e) {
923
+ console.error('[patchwork-iframe] Failed to mount widget:', e);
924
+ window.parent.postMessage({ type: 'widget-error', error: e.message }, '*');
925
+ } finally {
926
+ URL.revokeObjectURL(url);
927
+ }
928
+ });
929
+
930
+ // Signal ready to receive widget code
931
+ window.parent.postMessage({ type: 'widget-ready' }, '*');
932
+
933
+ // Set up ResizeObserver to report body size changes to parent
934
+ const resizeObserver = new ResizeObserver((entries) => {
935
+ for (const entry of entries) {
936
+ const { width, height } = entry.contentRect;
937
+ window.parent.postMessage({
938
+ type: 'widget-resize',
939
+ width: Math.ceil(width),
940
+ height: Math.ceil(height)
941
+ }, '*');
942
+ }
943
+ });
944
+ resizeObserver.observe(document.body);
945
+ `;return`<!DOCTYPE html>
946
+ <html>
947
+ <head>
948
+ <base href="${r}">
949
+ <meta charset="UTF-8">
950
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
951
+ <style>
952
+ * { box-sizing: border-box; margin: 0; padding: 0; }
953
+ body { font-family: system-ui, -apple-system, sans-serif; }
954
+ ${d}
955
+ </style>
956
+ <script type="importmap">
957
+ ${JSON.stringify({imports:c},null,2)}
958
+ <\/script>
959
+ </head>
960
+ <body>
961
+ <div id="root"></div>
962
+
963
+ <!-- Service Bridge -->
964
+ <script>
965
+ ${s}
966
+ <\/script>
967
+
968
+ <!-- Widget Inputs -->
969
+ <script>
970
+ window.__PATCHWORK_INPUTS__ = ${JSON.stringify(e)};
971
+ <\/script>
972
+
973
+ <script type="module">
974
+ ${ue}
975
+ <\/script>
976
+ </body>
977
+ </html>`}async function Gn(n,e,t,r){const{target:s,sandbox:i=Fs,inputs:c={}}=e,d=Ds(),w=document.createElement("iframe");w.id=d,w.className="patchwork-widget patchwork-iframe",w.style.cssText="width: 100%; border: none; overflow: hidden;",w.sandbox.add(...i);const C=Ls(r);C.registerIframe(w);const A=n.manifest.services||[],G=typeof window<"u"?window.location.origin:"",ce=Vs(t,c,A,G);w.srcdoc=ce,s.appendChild(w);const ue=fe=>{var xe;if(fe.source===w.contentWindow&&((xe=fe.data)==null?void 0:xe.type)==="widget-resize"){const{height:Oe}=fe.data;typeof Oe=="number"&&Oe>0&&(w.style.height=`${Oe}px`)}};return window.addEventListener("message",ue),await new Promise((fe,xe)=>{const Oe=setTimeout(()=>{Ee(),xe(new Error("Iframe mount timeout"))},3e4),Ne=he=>{var Ue,ge,Ge,me;he.source===w.contentWindow&&(((Ue=he.data)==null?void 0:Ue.type)==="widget-ready"?(ge=w.contentWindow)==null||ge.postMessage({type:"widget-code",code:n.code,origin:G},"*"):((Ge=he.data)==null?void 0:Ge.type)==="widget-mounted"?(Ee(),fe()):((me=he.data)==null?void 0:me.type)==="widget-error"&&(Ee(),xe(new Error(he.data.error||"Widget mount failed"))))},Ee=()=>{clearTimeout(Oe),window.removeEventListener("message",Ne)};window.addEventListener("message",Ne)}),{id:d,widget:n,mode:"iframe",target:s,iframe:w,inputs:c,sandbox:i,unmount:()=>{window.removeEventListener("message",ue),C.unregisterIframe(w),w.remove()}}}async function Bs(n,e,t,r){return n.unmount(),Gn(e,{target:n.target,sandbox:n.sandbox,inputs:n.inputs},t,r)}function Zs(n){const e=n.lastIndexOf("/");return e===-1?".":n.slice(0,e)||"."}function Ws(n){const e=[];for(const t of n.split("/"))t===".."?e.pop():t&&t!=="."&&e.push(t);return e.join("/")}function zs(n,e){if(e)switch(e){case"typescript":case"ts":return"ts";case"tsx":return"tsx";case"javascript":case"js":return"js";case"jsx":return"jsx";case"json":return"json";case"css":return"css"}switch(n.split(".").pop()){case"ts":return"ts";case"tsx":return"tsx";case"js":return"js";case"jsx":return"jsx";case"json":return"json";case"css":return"css";default:return"tsx"}}function Hn(n){return n.startsWith("@/")?n.slice(2):n}function qs(n,e){const t=Zs(Hn(n)),r=t==="."?e:`${t}/${e}`;return Ws(r)}function Js(n,e){if(!e)return null;for(const[t,r]of Object.entries(e)){if(t.endsWith("/*")){const s=t.slice(0,-2);if(n===s||n.startsWith(s+"/"))return r}if(n===t)return r}return null}function Gs(n,e){if(n.files.has(e))return e;const t=[".tsx",".ts",".jsx",".js",".json"];for(const r of t)if(n.files.has(e+r))return e+r;for(const r of t){const s=`${e}/index${r}`;if(n.files.has(s))return s}return null}function Hs(n,e={}){return{name:"patchwork-vfs",setup(t){t.onResolve({filter:/^@\//},r=>Js(r.path,e.aliases)?null:{path:r.path,namespace:"vfs"}),t.onResolve({filter:/^\./},r=>{const s=r.namespace!=="vfs"&&r.importer===n.entry;return r.namespace!=="vfs"&&!s?null:{path:qs(r.importer,r.path),namespace:"vfs"}}),t.onLoad({filter:/.*/,namespace:"vfs"},r=>{const s=Hn(r.path),i=Gs(n,s);if(!i)throw new Error(`File not found in VFS: ${r.path}`);const c=n.files.get(i);return{contents:c.content,loader:zs(i,c.language)}})}}}function Ys(n,e=crypto.randomUUID()){const t=new Map;for(const r of n)t.set(r.path,r);return{id:e,entry:Xs(t),files:t}}function Xs(n){const e=Array.from(n.keys()),t=e.find(i=>/\bmain\.(tsx?|jsx?)$/.test(i));if(t)return t;const r=e.find(i=>/\bindex\.(tsx?|jsx?)$/.test(i));if(r)return r;const s=e.find(i=>/\.(tsx|jsx)$/.test(i));return s||e[0]||"main.tsx"}function Ks(n,e="main.tsx",t="inline"){return{id:t,entry:e,files:new Map([[e,{path:e,content:n}]])}}var qt=!1,At=null,Qs=`https://unpkg.com/esbuild-wasm@${tn.version}/esbuild.wasm`;async function ei(n){if(qt)return;if(At)return At;const e=(n==null?void 0:n["esbuild-wasm/esbuild.wasm"])||Qs;return At=(async()=>{try{await tn.initialize({wasmURL:e}),qt=!0}catch(t){if(t instanceof Error&&t.message.includes("initialize"))qt=!0;else throw t}})(),At}function ti(n){const t=new TextEncoder().encode(n);let r=0;for(let s=0;s<t.length;s++)r=(r<<5)-r+(t[s]??0)|0;return Math.abs(r).toString(16).padStart(8,"0")}async function ni(n){await ei(n.urlOverrides);const{image:e,proxyUrl:t,cdnBaseUrl:r,widgetCdnBaseUrl:s}=n;r&&Bt(r),s?Bt(s):r&&Bt(r);const i=ws();await i.preload(e);const c=_s(t);return new ri(c,i)}var ri=class{constructor(n,e){ze(this,"proxy");ze(this,"registry");this.proxy=n,this.registry=e}async preloadImage(n){await this.registry.preload(n)}isImageLoaded(n){return this.registry.has(n)}async compile(n,e,t={}){var he,Ue;const r=typeof n=="string"?Ks(n):n,s=r.entry.split(".").pop(),i=s==="ts"||s==="tsx"?"tsx":"jsx",c=this.registry.get(e.image)||null,d=(c==null?void 0:c.config.esbuild)||{},w=(c==null?void 0:c.config.framework)||{},C=d.target||"es2020",A=d.format||"esm",G=d.jsx??"automatic",ce={...(c==null?void 0:c.dependencies)||{},...e.packages||{}},ue=w.globals||{},K=w.deps||{},fe=(c==null?void 0:c.config.aliases)||{},xe=r.files.get(r.entry);if(!xe)throw new Error(`Entry file not found: ${r.entry}`);const Ne=((Ue=(he=(await tn.build({stdin:{contents:xe.content,loader:i,sourcefile:r.entry},bundle:!0,format:A,target:C,platform:e.platform==="cli"?"node":"browser",jsx:G,...d.jsxFactory?{jsxFactory:d.jsxFactory}:{},...d.jsxFragment?{jsxFragment:d.jsxFragment}:{},write:!1,sourcemap:"inline",plugins:[Hs(r,{aliases:fe}),Is({packages:ce,globals:ue,deps:K,aliases:fe})]})).outputFiles)==null?void 0:he[0])==null?void 0:Ue.text)||"",Ee=ti(Ne);return{code:Ne,hash:Ee,manifest:e}}async mount(n,e){const t=this.registry.get(n.manifest.image)||null;return e.mode==="iframe"?Gn(n,e,t,this.proxy):Jn(n,e,t,this.proxy)}unmount(n){n.unmount()}async reload(n,e,t){const r=await this.compile(e,t),s=this.registry.get(r.manifest.image)||null;n.mode==="iframe"?await Bs(n,r,s,this.proxy):await As(n,r,s,this.proxy)}};function si(n){return`
978
+ (function () {
979
+ if (window.patchwork) return; // guard against double-injection
980
+
981
+ var __pending = {};
982
+ var __seq = 0;
983
+ var __streams = {};
984
+
985
+ function __post(msg) {
986
+ msg.source = 'patchwork';
987
+ window.parent.postMessage(msg, '*');
988
+ }
989
+
990
+ function __request(payload) {
991
+ return new Promise(function (resolve, reject) {
992
+ var id = 'r' + (++__seq);
993
+ __pending[id] = { resolve: resolve, reject: reject };
994
+ payload.id = id;
995
+ __post(payload);
996
+ });
997
+ }
998
+
999
+ window.addEventListener('message', function (e) {
1000
+ var m = e.data;
1001
+ if (!m || m.source !== 'patchwork-host') return;
1002
+ if (m.kind === 'result' && m.id && __pending[m.id]) {
1003
+ var p = __pending[m.id];
1004
+ delete __pending[m.id];
1005
+ if (m.ok) p.resolve(m.value);
1006
+ else p.reject(new Error(m.error || 'Service call failed'));
1007
+ } else if (m.kind === 'stream-event') {
1008
+ var cbs = __streams[m.stream];
1009
+ if (cbs) {
1010
+ for (var i = 0; i < cbs.length; i++) {
1011
+ try { cbs[i](m.data, m.seq, m.stream); }
1012
+ catch (err) { console.error('[patchwork] subscribe callback error:', err); }
1013
+ }
1014
+ }
1015
+ }
1016
+ });
1017
+
1018
+ window.patchwork = {
1019
+ /** Subscribe to a named server data stream. Returns an unsubscribe fn. */
1020
+ subscribe: function (stream, cb) {
1021
+ if (!__streams[stream]) {
1022
+ __streams[stream] = [];
1023
+ __post({ kind: 'subscribe', stream: stream });
1024
+ }
1025
+ __streams[stream].push(cb);
1026
+ return function () {
1027
+ var a = __streams[stream];
1028
+ if (!a) return;
1029
+ var i = a.indexOf(cb);
1030
+ if (i !== -1) a.splice(i, 1);
1031
+ };
1032
+ },
1033
+ /** Push widget state into the conversation context. */
1034
+ updateContext: function (content) {
1035
+ __post({ kind: 'context', content: content });
1036
+ return Promise.resolve();
1037
+ },
1038
+ /** Fire a client event as an MCP tool call and await its result. */
1039
+ fireEvent: function (toolName, args) {
1040
+ return __request({ kind: 'fire', toolName: toolName, args: args || {} });
1041
+ }
1042
+ };
1043
+
1044
+ var __namespaces = ${JSON.stringify(n.namespaces??[])};
1045
+ for (var __i = 0; __i < __namespaces.length; __i++) {
1046
+ (function (ns) {
1047
+ window[ns] = new Proxy({}, {
1048
+ get: function (target, prop) {
1049
+ if (typeof prop !== 'string') return undefined;
1050
+ return function (args) {
1051
+ return __request({ kind: 'service', namespace: ns, procedure: prop, args: args || {} });
1052
+ };
1053
+ }
1054
+ });
1055
+ })(__namespaces[__i]);
1056
+ }
1057
+ })();
1058
+ `}const In="https://esm.sh",pt=document.getElementById("pw-status");function ot(n,e=!1){pt&&(pt.textContent=n,e?pt.setAttribute("data-error","true"):pt.removeAttribute("data-error"),pt.style.display=n?"block":"none")}async function ii(n){if(!n.trim())return;const e=new Blob([n],{type:"application/javascript"}),t=URL.createObjectURL(e);try{await import(t)}catch(r){console.warn("[patchwork-runtime] bridge shim failed to load:",r)}finally{URL.revokeObjectURL(t)}}function Un(){const n=Math.ceil(document.documentElement.getBoundingClientRect().height);window.parent.postMessage({source:"patchwork",kind:"size",height:n},"*")}let Jt=!1;const Mn=new Map;function ai(n){let e=Mn.get(n);return e||(e=ni({image:n,proxyUrl:"",cdnBaseUrl:In,widgetCdnBaseUrl:In}),Mn.set(n,e)),e}async function oi(n,e){if(!Jt){Jt=!0;try{ot("Loading widget source…");const t=await fetch(`/widget/${encodeURIComponent(n.name)}/${encodeURIComponent(n.hash)}/files`);if(!t.ok)throw new Error(`Failed to load widget files (${t.status})`);const{files:r,entry:s,manifest:i}=await t.json(),c=i.services??[];await ii(si({namespaces:c})),ot("Compiling widget…");const d=await ai(i.image),w=Ys(r,n.name);s&&(w.entry=s);const C={...i,services:void 0},A=await d.compile(w,C),G=document.getElementById("root");if(!G)throw new Error("Missing #root element");ot(""),await d.mount(A,{target:G,mode:"embedded",inputs:e}),Un(),new ResizeObserver(()=>Un()).observe(document.body)}catch(t){Jt=!1,console.error("[patchwork-runtime] render failed",t);const r=t instanceof Error?t.message:String(t);ot(`Failed to render widget:
1059
+ ${r}`,!0),window.parent.postMessage({source:"patchwork",kind:"error",error:r},"*")}}}function li(){const n=new URLSearchParams(window.location.search),e=n.get("widget");if(!e){ot("No widget specified.",!0);return}const[t,r]=e.split("/");if(!t||!r){ot("Invalid widget reference.",!0);return}let s={};const i=n.get("inputs");if(i)try{s=JSON.parse(i)}catch{}oi({name:t,hash:r},s)}li();