@aprovan/patchwork-mcp 0.1.0-dev.5e426ca → 0.1.0-dev.78e095c

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