1import{_ as lr}from"./PPVm8Dsz.js";class Ge extends Error{response;request;options;constructor(t,n,r){const o=t.status||t.status===0?t.status:"",i=t.statusText??"",s=`${o} ${i}`.trim(),a=s?`status code ${s}`:"an unknown error";super(`Request failed with ${a}: ${n.method} ${n.url}`),this.name="HTTPError",this.response=t,this.request=n,this.options=r}}class un extends Error{name="NonError";value;constructor(t){let n="Non-error value was thrown";try{typeof t=="string"?n=t:t&&typeof t=="object"&&"message"in t&&typeof t.message=="string"&&(n=t.message)}catch{}super(n),this.value=t}}class Ne extends Error{name="ForceRetryError";customDelay;code;customRequest;constructor(t){const n=t?.cause?t.cause instanceof Error?t.cause:new un(t.cause):void 0;super(t?.code?`Forced retry: ${t.code}`:"Forced retry",n?{cause:n}:void 0),this.customDelay=t?.delay,this.code=t?.code,this.customRequest=t?.request}}const wt=(()=>{let e=!1,t=!1;const n=typeof globalThis.ReadableStream=="function",r=typeof globalThis.Request=="function";if(n&&r)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(o){if(o instanceof Error&&o.message==="unsupported BodyInit type")return!1;throw o}return e&&!t})(),fr=typeof globalThis.AbortController=="function",ln=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",dr=typeof globalThis.ReadableStream=="function",hr=typeof globalThis.FormData=="function",fn=["get","post","put","patch","head","delete"],pr={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},xe=2147483647,mr=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,dn=Symbol("stop");class hn{options;constructor(t){this.options=t}}const gr=e=>new hn(e),yr={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0,context:!0},wr={next:!0},_r={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,duplex:!0},br=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(const[n,r]of e)t+=mr,t+=new TextEncoder().encode(`Content-Disposition: form-data; name="${n}"`).length,t+=typeof r=="string"?new TextEncoder().encode(r).length:r.size;return t}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if(typeof e=="string")return new TextEncoder().encode(e).length;if(e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).length;if("byteLength"in e)return e.byteLength;if(typeof e=="object"&&e!==null)try{const t=JSON.stringify(e);return new TextEncoder().encode(t).length}catch{return 0}return 0},pn=(e,t,n)=>{let r,o=0;return e.pipeThrough(new TransformStream({transform(i,s){if(s.enqueue(i),r){o+=r.byteLength;let a=t===0?0:o/t;a>=1&&(a=1-Number.EPSILON),n?.({percent:a,totalBytes:Math.max(t,o),transferredBytes:o},r)}r=i},flush(){r&&(o+=r.byteLength,n?.({percent:1,totalBytes:Math.max(t,o),transferredBytes:o},r))}}))},vr=(e,t)=>{if(!e.body)return e;if(e.status===204)return new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers});const n=Math.max(0,Number(e.headers.get("content-length"))||0);return new Response(pn(e.body,n,t),{status:e.status,statusText:e.statusText,headers:e.headers})},Tr=(e,t,n)=>{if(!e.body)return e;const r=br(n??e.body);return new Request(e,{duplex:"half",body:pn(e.body,r,t)})},q=e=>e!==null&&typeof e=="object",ge=(...e)=>{for(const t of e)if((!q(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return et({},...e)},mn=(e={},t={})=>{const n=new globalThis.Headers(e),r=t instanceof globalThis.Headers,o=new globalThis.Headers(t);for(const[i,s]of o.entries())r&&s==="undefined"||s===void 0?n.delete(i):n.set(i,s);return n};function ye(e,t,n){return Object.hasOwn(t,n)&&t[n]===void 0?[]:et(e[n]??[],t[n]??[])}const gn=(e={},t={})=>({beforeRequest:ye(e,t,"beforeRequest"),beforeRetry:ye(e,t,"beforeRetry"),afterResponse:ye(e,t,"afterResponse"),beforeError:ye(e,t,"beforeError")}),Er=(e,t)=>
1{const n=new URLSearchParams;for(const r of[e,t])if(r!==void 0)if(r instanceof URLSearchParams)for(const[o,i]of r.entries())n.append(o,i);else if(Array.isArray(r))for(const o of r){if(!Array.isArray(o)||o.length!==2)throw new TypeError("Array search parameters must be provided in [[key, value], ...] format");n.append(String(o[0]),String(o[1]))}else if(q(r))for(const[o,i]of Object.entries(r))i!==void 0&&n.append(o,String(i));else{const o=new URLSearchParams(r);for(const[i,s]of o.entries())n.append(i,s)}return n},et=(...e)=>{let t={},n={},r={},o;const i=[];for(const s of e)if(Array.isArray(s))Array.isArray(t)||(t=[]),t=[...t,...s];else if(q(s)){for(let[a,c]of Object.entries(s)){if(a==="signal"&&c instanceof globalThis.AbortSignal){i.push(c);continue}if(a==="context"){if(c!=null&&(!q(c)||Array.isArray(c)))throw new TypeError("The `context` option must be an object");t={...t,context:c==null?{}:{...t.context,...c}};continue}if(a==="searchParams"){c==null?o=void 0:o=o===void 0?c:Er(o,c);continue}q(c)&&a in t&&(c=et(t[a],c)),t={...t,[a]:c}}q(s.hooks)&&(r=gn(r,s.hooks),t.hooks=r),q(s.headers)&&(n=mn(n,s.headers),t.headers=n)}return o!==void 0&&(t.searchParams=o),i.length>0&&(i.length===1?t.signal=i[0]:ln?t.signal=AbortSignal.any(i):t.signal=i.at(-1)),t},Rr=e=>fn.includes(e)?e.toUpperCase():e,Sr=["get","put","head","delete","options","trace"],kr=[408,413,429,500,502,503,504],zr=[413,429,503],_t={limit:2,methods:Sr,statusCodes:kr,afterStatusCodes:zr,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3,jitter:void 0,retryOnTimeout:!1},Pr=(e={})=>{if(typeof e=="number")return{..._t,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.methods&&=e.methods.map(n=>n.toLowerCase()),e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");const t=Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0));return{..._t,...t}};class We extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}}async function $r(e,t,n,r){return new Promise((o,i)=>{const s=setTimeout(()=>{n&&n.abort(),i(new We(e))},r.timeout);r.fetch(e,t).then(o).catch(i).then(()=>{clearTimeout(s)})})}async function Ar(e,{signal:t}){return new Promise((n,r)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",o,{once:!0}));function o(){clearTimeout(i),r(t.reason)}const i=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e)})}const Or=(e,t)=>{const n={};for(const r in t)Object.hasOwn(t,r)&&!(r in _r)&&!(r in yr)&&(!(r in e)||r in wr)&&(n[r]=t[r]);return n},Ir=e=>e===void 0?!1:Array.isArray(e)?e.length>0:e instanceof URLSearchParams?e.size>0:typeof e=="object"?Object.keys(e).length>0:typeof e=="string"?e.trim().length>0:!!e;function Oe(e){return e instanceof Ge||e?.name===Ge.name}function Ve(e){return e instanceof We||e?.name===We.name}class ue{static create(t,n){const r=new ue(t,n),o=async()=>{if(typeof r.#e.timeout=="number"&&r.#e.timeout>xe)throw new RangeError(`The \`timeout\` option cannot be greater than ${xe}`);await Promise.resolve();let s=await r.#y();for(const a of r.#e.hooks.afterResponse){const c=r.#d(s.clone());let u;try{u=await a(r.request,r.#c(),c,{retryCount:r.#n})}catch(h){throw r.#s(c),r.#s(s),h}if(u instanceof hn)throw r.#s(c),r.#s(s),new Ne(u.options);const l=u instanceof globalThis.Response?u:s;c!==l&&r.#s(c),s!==l&&r.#s(s),s=l}if(r.#d(s),!s.ok&&(typeof r.#e.throwHttpErrors=="function"?r.#e.throwHttpErrors(s.status):r.#e.throwHttpErrors)){let a=new Ge(s,r.request,r.#c());for(const c of r.#e.hooks.beforeError)a=await c(a,{retryCount:r.#n});throw a}if(r.#e.onDownloadProgress){if(typeof r.#e.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!dr)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");const a=s.clone();return r.#s(s),vr(a,r.#e.onDownloadProgress)}return s},i=r.#h(o).finally(()=>{const s=r.#i;r.#l(s?.body??void 0),r.#l(r.request.body??void 0)});for(const[s,a]of Object.entries(pr))s==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(i[s]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||a);const c=await i;if(s==="json"){if(c.status===204)return"";const u=await c.text();return u===""?"":n.parseJson?n.parseJson(u):JSON.parse(u)}return c[s]()});return i}static#m(t){return t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof URLSearchParams)?Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0)):t}request;#r;#n=0;#t;#e;#i;#o;#a;constructor(t,n={}){if(this.#t=t,this.#e={...n,headers:mn(this.#t.headers,n.headers),hooks:gn({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},n.hooks),method:Rr(n.method??this.#t.method??"GET"),prefixUrl:String(n.prefixUrl||""),retry:Pr(n.retry),throwHttpErrors:n.throwHttpErrors??!0,timeout:n.timeout??1e4,fetch:n.fetch??globalThis.fetch.bind(globalThis),context:n.context??{}},typeof this.#t!="string"&&!(this.#t instanceof URL||this.#t instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");
1if(this.#e.prefixUrl&&typeof this.#t=="string"){if(this.#t.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this.#e.prefixUrl.endsWith("/")||(this.#e.prefixUrl+="/"),this.#t=this.#e.prefixUrl+this.#t}fr&&ln&&(this.#o=this.#e.signal??this.#t.signal,this.#r=new globalThis.AbortController,this.#e.signal=this.#o?AbortSignal.any([this.#o,this.#r.signal]):this.#r.signal),wt&&(this.#e.duplex="half"),this.#e.json!==void 0&&(this.#e.body=this.#e.stringifyJson?.(this.#e.json)??JSON.stringify(this.#e.json),this.#e.headers.set("content-type",this.#e.headers.get("content-type")??"application/json"));const r=n.headers&&new globalThis.Headers(n.headers).has("content-type");if(this.#t instanceof globalThis.Request&&(hr&&this.#e.body instanceof globalThis.FormData||this.#e.body instanceof URLSearchParams)&&!r&&this.#e.headers.delete("content-type"),this.request=new globalThis.Request(this.#t,this.#e),Ir(this.#e.searchParams)){const i="?"+(typeof this.#e.searchParams=="string"?this.#e.searchParams.replace(/^\?/,""):new URLSearchParams(ue.#m(this.#e.searchParams)).toString()),s=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,i);this.request=new globalThis.Request(s,this.#e)}if(this.#e.onUploadProgress){if(typeof this.#e.onUploadProgress!="function")throw new TypeError("The `onUploadProgress` option must be a function");if(!wt)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request=this.#p(this.request,this.#e.body??void 0)}}#u(){const t=this.#e.retry.delay(this.#n);let n=t;this.#e.retry.jitter===!0?n=Math.random()*t:typeof this.#e.retry.jitter=="function"&&(n=this.#e.retry.jitter(t),(!Number.isFinite(n)||n<0)&&(n=t));const r=this.#e.retry.backoffLimit??Number.POSITIVE_INFINITY;return Math.min(r,n)}async#g(t){if(this.#n++,this.#n>this.#e.retry.limit)throw t;const n=t instanceof Error?t:new un(t);if(n instanceof Ne)return n.customDelay??this.#u();if(!this.#e.retry.methods.includes(this.request.method.toLowerCase()))throw t;if(this.#e.retry.shouldRetry!==void 0){const r=await this.#e.retry.shouldRetry({error:n,retryCount:this.#n});if(r===!1)throw t;if(r===!0)return this.#u()}if(Ve(t)&&!this.#e.retry.retryOnTimeout)throw t;if(Oe(t)){if(!this.#e.retry.statusCodes.includes(t.response.status))throw t;const r=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Retry-After")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(r&&this.#e.retry.afterStatusCodes.includes(t.response.status)){let o=Number(r)*1e3;Number.isNaN(o)?o=Date.parse(r)-Date.now():o>=Date.parse("2024-01-01")&&(o-=Date.now());const i=this.#e.retry.maxRetryAfter??o;return o<i?o:i}if(t.response.status===413)throw t}return this.#u()}#d(t){return this.#e.parseJson&&(t.json=async()=>this.#e.parseJson(await t.text())),t}#l(t){t&&t.cancel().catch(()=>{})}#s(t){this.#l(t.body??void 0)}async#h(t){try{return await t()}catch(n){const r=Math.min(await this.#g(n),xe);if(this.#n<1)throw n;if(await Ar(r,this.#o?{signal:this.#o}:{}),n instanceof Ne&&n.customRequest){const o=this.#e.signal?new globalThis.Request(n.customRequest,{signal:this.#e.signal}):new globalThis.Request(n.customRequest);this.#f(o)}for(const o of this.#e.hooks.beforeRetry){const i=await o({request:this.request,options:this.#c(),error:n,retryCount:this.#n});if(i instanceof globalThis.Request){this.#f(i);break}if(i instanceof globalThis.Response)return i;if(i===dn)return}return this.#h(t)}}async#y(){this.#r?.signal.aborted&&(this.#r=new globalThis.AbortController,this.#e.signal=this.#o?AbortSignal.any([this.#o,this.#r.signal]):this.#r.signal,this.request=new globalThis.Request(this.request,{signal:this.#e.signal}));for(const n of this.#e.hooks.beforeRequest){const r=await n(this.request,this.#c(),{retryCount:this.#n});if(r instanceof Response)return r;if(r instanceof globalThis.Request){this.#f(r);break}}const t=Or(this.request,this.#e);return this.#i=this.request,this.request=this.#i.clone(),this.#e.timeout===!1?this.#e.fetch(this.#i,t):$r(this.#i,t,this.#r,this.#e)}#c(){if(!this.#a){const{hooks:t,...n}=this.#e;this.#a=Object.freeze(n)}return this.#a}#f(t){this.#a=void 0,this.request=this.#p(t)}#p(t,n){return!this.#e.onUploadProgress||!t.body?t:Tr(t,this.#e.onUploadProgress,n??this.#e.body??void 0)}}const qe=e=>{const t=(n,r)=>ue.create(n,ge(e,r));for(const n of fn)t[n]=(r,o)=>ue.create(r,ge(e,o,{method:n}));return t.create=n=>qe(ge(n)),t.extend=n=>(typeof n=="function"&&(n=n(e??{})),qe(ge(e,n))),t.stop=dn,t.retry=gr,t},he=qe();var bt;function f(e,t,n){function r(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,c);const u=s.prototype,l=Object.keys(u);for(let h=0;h<l.length;h++){const p=l[h];p in a||(a[p]=u[p].bind(a))}}
1const o=n?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function s(a){var c;const u=n?.Parent?new i:this;r(u,a),(c=u._zod).deferred??(c.deferred=[]);for(const l of u._zod.deferred)l();return u}return Object.defineProperty(s,"init",{value:r}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}class te extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class yn extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(bt=globalThis).__zod_globalConfig??(bt.__zod_globalConfig={});const tt=globalThis.__zod_globalConfig;function J(e){return tt}function wn(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,o])=>t.indexOf(+r)===-1).map(([r,o])=>o)}function He(e,t){return typeof t=="bigint"?t.toString():t}function nt(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function rt(e){return e==null}function ot(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Ur(e,t){const n=e/t,r=Math.round(n),o=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-r)<o?0:n-r}const vt=Symbol("evaluating");function w(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==vt)return r===void 0&&(r=vt,r=n()),r},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function K(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function G(...e){const t={};for(const n of e){const r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function Tt(e){return JSON.stringify(e)}function Lr(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const _n="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function ke(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Br=nt(()=>{if(tt.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function le(e){if(ke(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(ke(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function bn(e){return le(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const Nr=new Set(["string","number","symbol"]);function Ie(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function W(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function g(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function xr(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const Mr={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Zr(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const i=G(e._zod.def,{get shape(){const s={};for(const a in t){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&(s[a]=n.shape[a])}return K(this,"shape",s),s},checks:[]});
1return W(e,i)}function Dr(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const i=G(e._zod.def,{get shape(){const s={...e._zod.def.shape};for(const a in t){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&delete s[a]}return K(this,"shape",s),s},checks:[]});return W(e,i)}function Cr(e,t){if(!le(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const i=e._zod.def.shape;for(const s in t)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const o=G(e._zod.def,{get shape(){const i={...e._zod.def.shape,...t};return K(this,"shape",i),i}});return W(e,o)}function Fr(e,t){if(!le(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=G(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return K(this,"shape",r),r}});return W(e,n)}function jr(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n=G(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return K(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return W(e,n)}function Gr(e,t,n){const o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const s=G(t._zod.def,{get shape(){const a=t._zod.def.shape,c={...a};if(n)for(const u in n){if(!(u in a))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(c[u]=e?new e({type:"optional",innerType:a[u]}):a[u])}else for(const u in a)c[u]=e?new e({type:"optional",innerType:a[u]}):a[u];return K(this,"shape",c),c},checks:[]});return W(t,s)}function Wr(e,t,n){const r=G(t._zod.def,{get shape(){const o=t._zod.def.shape,i={...o};if(n)for(const s in n){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(i[s]=new e({type:"nonoptional",innerType:o[s]}))}else for(const s in o)i[s]=new e({type:"nonoptional",innerType:o[s]});return K(this,"shape",i),i}});return W(t,r)}function ee(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Vr(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function vn(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function we(e){return typeof e=="string"?e:e?.message}function Y(e,t,n){const r=e.message?e.message:we(e.inst?._zod.def?.error?.(e))??we(t?.error?.(e))??we(n.customError?.(e))??we(n.localeError?.(e))??"Invalid input",{inst:o,continue:i,input:s,...a}=e;return a.path??(a.path=[]),a.message=r,t?.reportInput&&(a.input=s),a}function st(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function fe(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const Tn=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,He,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},En=f("$ZodError",Tn),Rn=f("$ZodError",Tn,{Parent:Error});function qr(e,t=n=>n.message){const n={},r=[];for(const o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}function Hr(e,t=n=>n.message){const n={_errors:[]},r=(o,i=[])=>{for(const s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>r({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")r({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")r({issues:s.issues},[...i,...s.path]);else{const a=[...i,...s.path];if(a.length===0)n._errors.push(t(s));else{let c=n,u=0;for(;u<a.length;){const l=a[u];u===a.length-1?(c[l]=c[l]||{_errors:[]},c[l]._errors.push(t(s))):c[l]=c[l]||{_errors:[]},c=c[l],u++}}}};return r(e),n}const it=e=>(t,n,r,o)=>{const i=r?{...r,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw new te;if(s.issues.length){const a=new(o?.Err??e)(s.issues.map(c=>Y(c,i,J())));throw _n(a,o?.callee),a}return s.value},at=e=>async(t,n,r,o)=>{const i=r?{...r,async:!0}:{async:!0};let s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){const a=new(o?.Err??e)(s.issues.map(c=>Y(c,i,J())));throw _n(a,o?.callee),a}return s.value},Ue=e=>(t,n,r)=>{const o=r?{...r,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new te;return i.issues.length?{success:!1,error:new(e??En)(i.issues.map(s=>Y(s,o,J())))}:{success:!0,data:i.value}}
vendor: 2,768 bytes, line 1
1,Jr=Ue(Rn),Le=e=>async(t,n,r)=>{const o=r?{...r,async:!0}:{async:!0};let i=t._zod.run({value:n,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>Y(s,o,J())))}:{success:!0,data:i.value}},Yr=Le(Rn),Kr=e=>(t,n,r)=>{const o=r?{...r,direction:"backward"}:{direction:"backward"};return it(e)(t,n,o)},Xr=e=>(t,n,r)=>it(e)(t,n,r),Qr=e=>async(t,n,r)=>{const o=r?{...r,direction:"backward"}:{direction:"backward"};return at(e)(t,n,o)},eo=e=>async(t,n,r)=>at(e)(t,n,r),to=e=>(t,n,r)=>{const o=r?{...r,direction:"backward"}:{direction:"backward"};return Ue(e)(t,n,o)},no=e=>(t,n,r)=>Ue(e)(t,n,r),ro=e=>async(t,n,r)=>{const o=r?{...r,direction:"backward"}:{direction:"backward"};return Le(e)(t,n,o)},oo=e=>async(t,n,r)=>Le(e)(t,n,r),so=/^[cC][0-9a-z]{6,}$/,io=/^[0-9a-z]+$/,ao=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,co=/^[0-9a-vA-V]{20}$/,uo=/^[A-Za-z0-9]{27}$/,lo=/^[a-zA-Z0-9_-]{21}$/,fo=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,ho=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Et=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,po=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,mo="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function go(){return new RegExp(mo,"u")}const yo=/^(?:(?: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])$/,wo=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,_o=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,bo=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,vo=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Sn=/^[A-Za-z0-9_-]*$/,To=/^https?$/,Eo=/^\+[1-9]\d{6,14}$/,kn="(?:(?:\\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])))",Ro=new RegExp(`^${kn}
1$`);function zn(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function So(e){return new RegExp(`^${zn(e)}$`)}function ko(e){const t=zn({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${kn}T(?:${r})$`)}const zo=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Po=/^-?\d+$/,$o=/^-?\d+(?:\.\d+)?$/,Ao=/^(?:true|false)$/i,Oo=/^[^A-Z]*$/,Io=/^[^a-z]*$/,N=f("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Pn={number:"number",bigint:"bigint",object:"date"},$n=f("$ZodCheckLessThan",(e,t)=>{N.init(e,t);const n=Pn[typeof t.value];e._zod.onattach.push(r=>{const o=r._zod.bag,i=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),An=f("$ZodCheckGreaterThan",(e,t)=>{N.init(e,t);const n=Pn[typeof t.value];e._zod.onattach.push(r=>{const o=r._zod.bag,i=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Uo=f("$ZodCheckMultipleOf",(e,t)=>{N.init(e,t),e._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):Ur(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Lo=f("$ZodCheckNumberFormat",(e,t)=>{N.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[o,i]=Mr[t.format];e._zod.onattach.push(s=>{const a=s._zod.bag;a.format=t.format,a.minimum=o,a.maximum=i,n&&(a.pattern=Po)}),e._zod.check=s=>{const a=s.value;if(n){if(!Number.isInteger(a)){s.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}a<o&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),a>i&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),Bo=f("$ZodCheckMaxLength",(e,t)=>{var n;N.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!rt(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const o=r.value;if(o.length<=t.maximum)return;const s=st(o);r.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),No=f("$ZodCheckMinLength",(e,t)=>{var n;N.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!rt(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const o=r.value;if(o.length>=t.minimum)return;const s=st(o);r.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),xo=f("$ZodCheckLengthEquals",(e,t)=>{var n;N.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!rt(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=r=>{const o=r.value,i=o.length;if(i===t.length)return;const s=st(o),a=i>t.length;r.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),Be=f("$ZodCheckStringFormat",(e,t)=>{var n,r;N.init(e,t),e._zod.onattach.push(o=>{const i=o._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Mo=f("$ZodCheckRegex",(e,t)=>{Be.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Zo=f("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Oo),Be.init(e,t)}),Do=f("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Io),Be.init(e,t)}),Co=f("$ZodCheckIncludes",(e,t)=>{N.init(e,t);const n=Ie(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(o=>{const i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input
vendor: 20,327 bytes, lines 1-62
1:o.value,inst:e,continue:!t.abort})}}),Fo=f("$ZodCheckStartsWith",(e,t)=>{N.init(e,t);const n=new RegExp(`^${Ie(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),jo=f("$ZodCheckEndsWith",(e,t)=>{N.init(e,t);const n=new RegExp(`.*${Ie(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),Go=f("$ZodCheckOverwrite",(e,t)=>{N.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class Wo{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(` 2`).filter(s=>s),o=Math.min(...r.map(s=>s.length-s.trimStart().length)),i=r.map(s=>s.slice(o)).map(s=>" ".repeat(this.indent*2)+s);for(const s of i)this.content.push(s)}compile(){const t=Function,n=this?.args,o=[...(this?.content??[""]).map(i=>` ${i}`)];return new t(...n,o.join(` 3`))}}const Vo={major:4,minor:4,patch:3},S=f("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Vo;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const o of r)for(const i of o._zod.onattach)i(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=(s,a,c)=>{let u=ee(s),l;for(const h of a){if(h._zod.def.when){if(Vr(s)||!h._zod.def.when(s))continue}else if(u)continue;const p=s.issues.length,d=h._zod.check(s);if(d instanceof Promise&&c?.async===!1)throw new te;if(l||d instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await d,s.issues.length!==p&&(u||(u=ee(s,p)))});else{if(s.issues.length===p)continue;u||(u=ee(s,p))}}return l?l.then(()=>s):s},i=(s,a,c)=>{if(ee(s))return s.aborted=!0,s;const u=o(a,r,c);if(u instanceof Promise){if(c.async===!1)throw new te;return u.then(l=>e._zod.parse(l,c))}return e._zod.parse(u,c)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){const u=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return u instanceof Promise?u.then(l=>i(l,s,a)):i(u,s,a)}const c=e._zod.parse(s,a);if(c instanceof Promise){if(a.async===!1)throw new te;return c.then(u=>o(u,r,a))}return o(c,r,a)}}w(e,"~standard",()=>({validate:o=>{try{const i=Jr(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return Yr(e,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),ct=f("$ZodString",(e,t)=>{S.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??zo(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),_=f("$ZodStringFormat",(e,t)=>{Be.init(e,t),ct.init(e,t)}),qo=f("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=ho),_.init(e,t)}),Ho=f("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Et(r))}else t.pattern??(t.pattern=Et());_.init(e,t)}),Jo=f("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=po),_.init(e,t)}),Yo=f("$ZodURL",(e,t)=>{_.init(e,t),e._zod.check=n=>{try{const r=n.value.trim();if(!t.normalize&&t.protocol?.source===To.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}const o=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=o.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Ko=f("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=go()),_.init(e,t)}),Xo=f("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=lo),_.init(e,t)}),Qo=f("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=so),_.init(e,t)}),es=f("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=io),_.init(e,t)}),ts=f("$ZodULID",(e,t)=>{t.pattern??(t.pattern=ao),_.init(e,t)}),ns=f("$ZodXID",(e,t)=>{t.pattern??(t.pattern=co),_.init(e,t)}),rs=f("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=uo),_.init(e,t)}),os=f("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=ko(t)),_.init(e,t)}),ss=f("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Ro),_.init(e,t)}),is=f("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=So(t)),_.init(e,t)}),as=f("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=fo),_.init(e,t)}),cs=f("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=yo),_.init(e,t),e._zod.bag.format="ipv4"}),us=f("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=wo),_.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),ls=f("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=_o),_.init(e,t)}),fs=f("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=bo),_.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[o,i]=r;if(!i)throw new Error;const s=Number(i);if(`${s}`!==i)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${o}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function On(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const ds=f("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=vo),_.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{On(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function hs(e){if(!Sn.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return On(n)}const ps=f("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Sn),_.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{hs(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),ms=f("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Eo),_.init(e,t)});function gs(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const o=JSON.parse(atob(r));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const ys=f("$ZodJWT",(e,t)=>{_.init(e,t),e._zod.check=n=>{gs(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),In=f("$ZodNumber",(e,t)=>{S.init(e,t),e._zod.pattern=e._zod.bag.pattern??$o,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;const i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),n}}),ws=f("$ZodNumberFormat",(e,t)=>{Lo.init(e,t),In.init(e,t)}),_s=f("$ZodBoolean",(e,t)=>{S.init(e,t),e._zod.pattern=Ao,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}}),bs=f("$ZodUnknown",(e,t)=>{S.init(e,t),e._zod.parse=n=>n}),vs=f("$ZodNever",(e,t)=>{S.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Rt(e,t,n){e.issues.length&&t.issues.push(...vn(n,e.issues)),t.value[n]=e.value}const Ts=f("$ZodArray",(e,t)=>{S.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);const i=[];for(let s=0;s<o.length;s++){const a=o[s],c=t.element._zod.run({value:a,issues:[]},r);c instanceof Promise?i.push(c.then(u=>Rt(u,n,s))):Rt(c,n,s)}return i.length?Promise.all(i).then(()=>n):n}});function ze(e,t,n,r,o,i){const s=n in r;if(e.issues.length){if(o&&i&&!s)return;t.issues.push(...vn(n,e.issues))}if(!s&&!o){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?s&&(t.value[n]=void 0):t.value[n]=e.value}function Un(e){const t=Object.keys(e.shape);for(const r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const n=xr(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Ln(e,t,n,r,o,i){const s=[],a=o.keySet,c=o.catchall._zod,u=c.def.type,l=c.optin==="optional",h=c.optout==="optional";for(const p in t){if(p==="__proto__"||a.has(p))continue;if(u==="never"){s.push(p);continue}const d=c.run({value:t[p],issues:[]},r);d instanceof Promise?e.push(d.then(m=>ze(m,n,p,t,l,h))):ze(d,n,p,t,l,h)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i}),e.length?Promise.all(e).then(()=>n):n}const Es=f("$ZodObject",(e,t)=>{if(S.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const a=t.shape;Object.defineProperty(t,"shape",{get:()=>{const c={...a};return Object.defineProperty(t,"shape",{value:c}),c}})}const r=nt(()=>Un(t));w(e._zod,"propValues",()=>{const a=t.shape,c={};for(const u in a){const l=a[u]._zod;if(l.values){c[u]??(c[u]=new Set);for(const h of l.values)c[u].add(h)}}return c});const o=ke,i=t.catchall;let s;e._zod.parse=(a,c)=>{s??(s=r.value);const u=a.value;if(!o(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),a;a.value={};const l=[],h=s.shape;for(const p of s.keys){const d=h[p],m=d._zod.optin==="optional",I=d._zod.optout==="optional",y=d._zod.run({value:u[p],issues:[]},c);y instanceof Promise?l.push(y.then(C=>ze(C,a,p,u,m,I))):ze(y,a,p,u,m,I)}return i?Ln(l,u,a,c,r.value,e):l.length?Promise.all(l).then(()=>a):a}}),Rs=f("$ZodObjectJIT",(e,t)=>{Es.init(e,t);const n=e._zod.parse,r=nt(()=>Un(t)),o=p=>{const d=new Wo(["shape","payload","ctx"]),m=r.value,I=x=>{const T=Tt(x);return`shape[${T}]._zod.run({ value: input[${T}], issues: [] }, ctx)`};d.write("const input = payload.value;");const y=Object.create(null);let C=0;for(const x of m.keys)y[x]=`key_${C++}`;d.write("const newResult = {};");for(const x of m.keys){const T=y[x],P=Tt(x),gt=p[x],yt=gt?._zod?.optin==="optional",ur=gt?._zod?.optout==="optional";d.write(`const ${T} = ${I(x)};`),yt&&ur?d.write(` 4 if (${T}.issues.length) { 5 if (${P} in input) { 6 payload.issues = payload.issues.concat(${T}.issues.map(iss => ({ 7 ...iss, 8 path: iss.path ? [${P}, ...iss.path] : [${P}] 9 }))); 10 } 11 } 12 13 if (${T}.value === undefined) { 14 if (${P} in input) { 15 newResult[${P}] = undefined; 16 } 17 } else { 18 newResult[${P}] = ${T}.value; 19 } 20 21 `):yt?d.write(` 22 if (${T}.issues.length) { 23 payload.issues = payload.issues.concat(${T}.issues.map(iss => ({ 24 ...iss, 25 path: iss.path ? [${P}, ...iss.path] : [${P}] 26 }))); 27 } 28 29 if (${T}.value === undefined) { 30 if (${P} in input) { 31 newResult[${P}] = undefined; 32 } 33 } else { 34 newResult[${P}] = ${T}.value; 35 } 36 37 `):d.write(` 38 const ${T}_present = ${P} in input; 39 if (${T}.issues.length) { 40 payload.issues = payload.issues.concat(${T}.issues.map(iss => ({ 41 ...iss, 42 path: iss.path ? [${P}, ...iss.path] : [${P}] 43 }))); 44 } 45 if (!${T}_present && !${T}.issues.length) { 46 payload.issues.push({ 47 code: "invalid_type", 48 expected: "nonoptional", 49 input: undefined, 50 path: [${P}] 51 }); 52 } 53 54 if (${T}_present) { 55 if (${T}.value === undefined) { 56 newResult[${P}] = undefined; 57 } else { 58 newResult[${P}] = ${T}.value; 59 } 60 } 61 62 `)}d.write("payload.value = newResult;"),d.write("return payload;");const X=d.compile();return(x,T)=>X(p,x,T)};let i;const s=ke,a=!tt.jitless,u=a&&Br.value,l=t.catchall;let h;e._zod.parse=(p,d)=>{h??(h=r.value);const m=p.value;return s(m)?a&&u&&d?.async===!1&&d.jitless!==!0?(i||(i=o(t.shape)),p=i(p,d),l?Ln([],m,p,d,h,e):p):n(p,d):(p.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),p)}});function St(e,t,n,r){for(const i of e)if(i.issues.length===0)return t.value=i.value,t;const o=e.filter(i=>!ee(i));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(i=>i.issues.map(s=>Y(s,r,J())))}),t)}const Ss=f("$ZodUnion",(e,t)=>{S.init(e,t),w(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),w(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),w(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),w(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(o=>o._zod.pattern);return new RegExp(`^(${r.map(o=>ot(o.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,o)=>{if(n)return n(r,o);let i=!1;const s=[];for(const a of t.options){const c=a._zod.run({value:r.value,issues:[]},o);if(c instanceof Promise)s.push(c),i=!0;else{if(c.issues.length===0)return c;s.push(c)}}return i?Promise.all(s).then(a=>St(a,r,e,o)):St(s,r,e,o)}}),ks=f("$ZodIntersection",(e,t)=>{S.init(e,t),e._zod.parse=(n,r)=>{const o=n.value,i=t.left._zod.run({value:o,issues:[]},r),s=t.right._zod.run({value:o,issues:[]},r);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([c,u])=>kt(n,c,u)):kt(n,i,s)}});function Je(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(le(e)&&le(t)){const n=Object.keys(t),r=Object.keys(e).filter(i=>n.indexOf(i)!==-1),o={...e,...t};for(const i of r){const s=Je(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const o=e[r],i=t[r],s=Je(o,i);if(!s.valid)return{valid:!1,mergeErrorPath:[r,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function kt(e,t,n){const r=new Map;let o;for(const a of t.issues)if(a.code==="unrecognized_keys"){o??(o=a);for(const c of a.keys)r.has(c)||r.set(c,{}),r.get(c).l=!0}else e.issues.push(a);for(const a of n.issues)if(a.code==="unrecognized_keys")for(const c of a.keys)r.has(c)||r.set(c,{}),r.get(c).r=!0;else e.issues.push(a);const i=[...r].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(i.length&&o&&e.issues.push({...o,keys:i}),ee(e))return e;const s=Je(t.value,n.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}const zs=f("$ZodEnum",(e,t)=>{S.init(e,t);const n=wn(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(o=>Nr.has(typeof o)).map(o=>typeof o=="string"?Ie(o):o.toString()).join("|")})$`),e._zod.parse=(o,i)=>{const s=o.value;return r.has(s)||o.issues.push({code:"invalid_value",values:n,input:s,inst:e}),o}}),Ps=f("$ZodTransform",(e,t)=>{S.init(e,t),e._zod.optin="optional",e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new yn(e.constructor.name);const o=t.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(s=>(n.value=s,n.fallback=!0,n));if(o instanceof Promise)throw new te;return n.value=o,n.fallback=!0,n}});function zt(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const Bn=f("$ZodOptional",(e,t)=>{S.init(e,t),e._zod.optin="optional",e._zod.optout="optional",w(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),w(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${ot(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){const o=n.value,i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(s=>zt(s,o)):zt(i,o)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),$s=f("$ZodExactOptional",(e,t)=>{Bn.init(e,t),w(e._zod,"values",()=>t.innerType._zod.values),w(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),As=f("$ZodNullable",(e,t)=>{S.init(e,t),w(e._zod,"optin",()=>t.innerType._zod.optin),w(e._zod,"optout",()=>t.innerType._zod.optout),w(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${ot(n.source)}|null)$`):void 0}),w(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),Os=f("$ZodDefault",(e,t)=>{S.init(e,t),e._zod.optin="optional",w(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(i=>Pt(i,t)):Pt(o,t)}});function Pt(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Is=f("$ZodPrefault",(e,t)=>{S.init(e,t),e._zod.optin="optional",w(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),Us=f("$ZodNonOptional",(e,t)=>{S.init(e,t),w(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(i=>$t(i,e)):$t(o,e)}});function $t(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const Ls=f("$ZodCatch",(e,t)=>{S.init(e,t),e._zod.optin="optional",w(e._zod,"optout",()=>t.innerType._zod.optout),w(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(i=>(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(s=>Y(s,r,J()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(i=>Y(i,r,J()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),Bs=f("$ZodPipe",(e,t)=>{S.init(e,t),w(e._zod,"values",()=>t.in._zod.values),w(e._zod,"optin",()=>t.in._zod.optin),w(e._zod,"optout",()=>t.out._zod.optout),w(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){const i=t.out._zod.run(n,r);return i instanceof Promise?i.then(s=>_e(s,t.in,r)):_e(i,t.in,r)}const o=t.in._zod.run(n,r);return o instanceof Promise?o.then(i=>_e(i,t.out,r)):_e(o,t.out,r)}});function _e(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}const Ns=f("$ZodReadonly",(e,t)=>{S.init(e,t),w(e._zod,"propValues",()=>t.innerType._zod.propValues),w(e._zod,"values",()=>t.innerType._zod.values),w(e._zod,"optin",()=>t.innerType?._zod?.optin),w(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const o=t.innerType._zod.run(n,r);
vendor: 5,040 bytes, line 62
62return o instanceof Promise?o.then(At):At(o)}});function At(e){return e.value=Object.freeze(e.value),e}const xs=f("$ZodCustom",(e,t)=>{N.init(e,t),S.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then(i=>Ot(i,n,r,e));Ot(o,n,r,e)}});function Ot(e,t,n,r){if(!e){const o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),t.issues.push(fe(o))}}var It;class Ms{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};delete r.id;const o={...r,...this._map.get(t)};return Object.keys(o).length?o:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function Zs(){return new Ms}(It=globalThis).__zod_globalRegistry??(It.__zod_globalRegistry=Zs());const ae=globalThis.__zod_globalRegistry;function Ds(e,t){return new e({type:"string",...g(t)})}function Cs(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...g(t)})}function Ut(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...g(t)})}function Fs(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...g(t)})}function js(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...g(t)})}function Gs(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...g(t)})}function Ws(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...g(t)})}function Vs(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...g(t)})}function qs(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...g(t)})}function Hs(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...g(t)})}function Js(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...g(t)})}function Ys(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...g(t)})}function Ks(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...g(t)})}function Xs(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...g(t)})}function Qs(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...g(t)})}function ei(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...g(t)})}function ti(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...g(t)})}function ni(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...g(t)})}function ri(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...g(t)})}function oi(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...g(t)})}function si(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...g(t)})}function ii(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...g(t)})}function ai(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...g(t)})}function ci(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...g(t)})}function ui(e,t){return new e({type:"string",format:"date",check:"string_format",...g(t)})}function li(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...g(t)})}function fi(e,t){return new e({type:"string",format:"duration",check:"string_format",...g(t)})}function di(e,t){return new e({type:"number",checks:[],...g(t)})}function hi(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...g(t)})}function pi(e,t){return new e({type:"boolean",...g(t)})}function mi(e){return new e({type:"unknown"})}function gi(e,t){return new e({type:"never",...g(t)})}function Lt(e,t){return new $n({check:"less_than",...g(t),value:e,inclusive:!1})}function Me(e,t){return new $n({check:"less_than",...g(t),value:e,inclusive:!0})}function Bt(e,t){return new An({check:"greater_than",...g(t),value:e,inclusive:!1})}function Ze(e,t){return new An({check:"greater_than",...g(t),value:e,inclusive:!0})}function Nt(e,t){return new Uo({check:"multiple_of",...g(t),value:e})}function Nn(e,t){return new Bo({check:"max_length",...g(t),maximum:e})}function Pe(e,t){return new No({check:"min_length",...g(t),minimum:e})}function xn(e,t){return new xo({check:"length_equals",...g(t),length:e})}function yi(e,t){return new Mo({check:"string_format",format:"regex",...g(t),pattern:e})}function wi(e){return new Zo({check:"string_format",format:"lowercase",...g(e)})}
vendor: 4,915 bytes, lines 62-64
62function _i(e){return new Do({check:"string_format",format:"uppercase",...g(e)})}function bi(e,t){return new Co({check:"string_format",format:"includes",...g(t),includes:e})}function vi(e,t){return new Fo({check:"string_format",format:"starts_with",...g(t),prefix:e})}function Ti(e,t){return new jo({check:"string_format",format:"ends_with",...g(t),suffix:e})}function se(e){return new Go({check:"overwrite",tx:e})}function Ei(e){return se(t=>t.normalize(e))}function Ri(){return se(e=>e.trim())}function Si(){return se(e=>e.toLowerCase())}function ki(){return se(e=>e.toUpperCase())}function zi(){return se(e=>Lr(e))}function Pi(e,t,n){return new e({type:"array",element:t,...g(n)})}function $i(e,t,n){return new e({type:"custom",check:"custom",fn:t,...g(n)})}function Ai(e,t){const n=Oi(r=>(r.addIssue=o=>{if(typeof o=="string")r.issues.push(fe(o,r.value,n._zod.def));else{const i=o;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=n),i.continue??(i.continue=!n._zod.def.abort),r.issues.push(fe(i))}},e(r.value,r)),t);return n}function Oi(e,t){const n=new N({check:"custom",...g(t)});return n._zod.check=e,n}function Mn(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??ae,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function O(e,t,n={path:[],schemaPath:[]}){var r;const o=e._zod.def,i=t.seen.get(e);if(i)return i.count++,n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema;const s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s);const a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{const l={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,l);else{const p=s.schema,d=t.processors[o.type];if(!d)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);d(e,t,p,l)}const h=e._zod.parent;h&&(s.ref||(s.ref=h),O(h,t,l),t.seen.get(h).isParent=!0)}const c=t.metadataRegistry.get(e);return c&&Object.assign(s.schema,c),t.io==="input"&&L(e)&&(delete s.schema.examples,delete s.schema.default),t.io==="input"&&"_prefault"in s.schema&&((r=s.schema).default??(r.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}function Zn(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const s of e.seen.entries()){const a=e.metadataRegistry.get(s[0])?.id;if(a){const c=r.get(a);if(c&&c!==s[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(a,s[0])}}const o=s=>{const a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const h=e.external.registry.get(s[0])?.id,p=e.external.uri??(m=>m);if(h)return{ref:p(h)};const d=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=d,{defId:d,ref:`${p("__shared")}#/${a}/${d}`}}if(s[1]===n)return{ref:"#"};const u=`#/${a}/`,l=s[1].schema.id??`__schema${e.counter++}`;return{defId:l,ref:u+l}},i=s=>{if(s[1].schema.$ref)return;const a=s[1],{ref:c,defId:u}=o(s);a.def={...a.schema},u&&(a.defId=u);const l=a.schema;for(const h in l)delete l[h];l.$ref=c};if(e.cycles==="throw")for(const s of e.seen.entries()){const a=s[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root> 63 64Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const s of e.seen.entries()){const a=s[1];if(t===s[0]){i(s);continue}if(e.external){const u=e.external.registry.get(s[0])?.id;if(t!==s[0]&&u){i(s);continue}}if(e.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}if(a.count>1&&e.reused==="ref"){i(s);continue}}}function Dn(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=a=>{const c=e.seen.get(a);if(c.ref===null)return;const u=c.def??c.schema,l={...u},h=c.ref;if(c.ref=null,h){r(h);const d=e.seen.get(h),m=d.schema;if(m.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(m)):Object.assign(u,m),Object.assign(u,l),a._zod.parent===h)for(const y in u)y==="$ref"||y==="allOf"||y in l||delete u[y];if(m.$ref&&d.def)for(const y in u)y==="$ref"||y==="allOf"||y in d.def&&JSON.stringify(u[y])===JSON.stringify(d.def[y])&&delete u[y]}const p=a._zod.parent;if(p&&p!==h){r(p);const d=e.seen.get(p);if(d?.schema.$ref&&(u.$ref=d.schema.$ref,d.def))for(const m in u)m==="$ref"||m==="allOf"||m in d.def&&JSON.stringify(u[m])===JSON.stringify(d.def[m])&&delete u[m]}e.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};for(const a of[...e.seen.entries()].reverse())r(a[0]);const o={};
64if(e.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(a)}Object.assign(o,n.def??n.schema);const i=e.metadataRegistry.get(t)?.id;i!==void 0&&o.id===i&&delete o.id;const s=e.external?.defs??{};for(const a of e.seen.entries()){const c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,s[c.defId]=c.def)}e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?o.$defs=s:o.definitions=s);try{const a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:$e(t,"input",e.processors),output:$e(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function L(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return L(r.element,n);if(r.type==="set")return L(r.valueType,n);if(r.type==="lazy")return L(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return L(r.innerType,n);if(r.type==="intersection")return L(r.left,n)||L(r.right,n);if(r.type==="record"||r.type==="map")return L(r.keyType,n)||L(r.valueType,n);if(r.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:L(r.in,n)||L(r.out,n);if(r.type==="object"){for(const o in r.shape)if(L(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(const o of r.options)if(L(o,n))return!0;return!1}if(r.type==="tuple"){for(const o of r.items)if(L(o,n))return!0;return!!(r.rest&&L(r.rest,n))}return!1}const Ii=(e,t={})=>n=>{const r=Mn({...n,processors:t});return O(e,r),Zn(r,e),Dn(r,e)},$e=(e,t,n={})=>r=>{const{libraryOptions:o,target:i}=r??{},s=Mn({...o??{},target:i,io:t,processors:n});return O(e,s),Zn(s,e),Dn(s,e)},Ui={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Li=(e,t,n,r)=>{const o=n;o.type="string";const{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:u}=e._zod.bag;if(typeof i=="number"&&(o.minLength=i),typeof s=="number"&&(o.maxLength=s),a&&(o.format=Ui[a]??a,o.format===""&&delete o.format,a==="time"&&delete o.format),u&&(o.contentEncoding=u),c&&c.size>0){const l=[...c];l.length===1?o.pattern=l[0].source:l.length>1&&(o.allOf=[...l.map(h=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:h.source}))])}},Bi=(e,t,n,r)=>{const o=n,{minimum:i,maximum:s,format:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:l}=e._zod.bag;typeof a=="string"&&a.includes("int")?o.type="integer":o.type="number";const h=typeof l=="number"&&l>=(i??Number.NEGATIVE_INFINITY),p=typeof u=="number"&&u<=(s??Number.POSITIVE_INFINITY),d=t.target==="draft-04"||t.target==="openapi-3.0";h?d?(o.minimum=l,o.exclusiveMinimum=!0):o.exclusiveMinimum=l:typeof i=="number"&&(o.minimum=i),p?d?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u:typeof s=="number"&&(o.maximum=s),typeof c=="number"&&(o.multipleOf=c)},Ni=(e,t,n,r)=>{n.type="boolean"},xi=(e,t,n,r)=>{n.not={}},Mi=(e,t,n,r)=>{},Zi=(e,t,n,r)=>{const o=e._zod.def,i=wn(o.entries);i.every(s=>typeof s=="number")&&(n.type="number"),i.every(s=>typeof s=="string")&&(n.type="string"),n.enum=i},Di=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Ci=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Fi=(e,t,n,r)=>{const o=n,i=e._zod.def,{minimum:s,maximum:a}=e._zod.bag;typeof s=="number"&&(o.minItems=s),typeof a=="number"&&(o.maxItems=a),o.type="array",o.items=O(i.element,t,{...r,path:[...r.path,"items"]})},ji=(e,t,n,r)=>{const o=n,i=e._zod.def;o.type="object",o.properties={};const s=i.shape;for(const u in s)o.properties[u]=O(s[u],t,{...r,path:[...r.path,"properties",u]});const a=new Set(Object.keys(s)),c=new Set([...a].filter(u=>{const l=i.shape[u]._zod;return t.io==="input"?l.optin===void 0:l.optout===void 0}));c.size>0&&(o.required=Array.from(c)),i.catchall?._zod.def.type==="never"?o.additionalProperties=!1:i.catchall?i.catchall&&(o.additionalProperties=O(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},Gi=(e,t,n,r)=>{const o=e._zod.def,i=o.inclusive===!1,s=o.options.map((a,c)=>
vendor: 6,040 bytes, line 64
64O(a,t,{...r,path:[...r.path,i?"oneOf":"anyOf",c]}));i?n.oneOf=s:n.anyOf=s},Wi=(e,t,n,r)=>{const o=e._zod.def,i=O(o.left,t,{...r,path:[...r.path,"allOf",0]}),s=O(o.right,t,{...r,path:[...r.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];n.allOf=c},Vi=(e,t,n,r)=>{const o=e._zod.def,i=O(o.innerType,t,r),s=t.seen.get(e);t.target==="openapi-3.0"?(s.ref=o.innerType,n.nullable=!0):n.anyOf=[i,{type:"null"}]},qi=(e,t,n,r)=>{const o=e._zod.def;O(o.innerType,t,r);const i=t.seen.get(e);i.ref=o.innerType},Hi=(e,t,n,r)=>{const o=e._zod.def;O(o.innerType,t,r);const i=t.seen.get(e);i.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},Ji=(e,t,n,r)=>{const o=e._zod.def;O(o.innerType,t,r);const i=t.seen.get(e);i.ref=o.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},Yi=(e,t,n,r)=>{const o=e._zod.def;O(o.innerType,t,r);const i=t.seen.get(e);i.ref=o.innerType;let s;try{s=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=s},Ki=(e,t,n,r)=>{const o=e._zod.def,i=o.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?i?o.out:o.in:o.out;O(s,t,r);const a=t.seen.get(e);a.ref=s},Xi=(e,t,n,r)=>{const o=e._zod.def;O(o.innerType,t,r);const i=t.seen.get(e);i.ref=o.innerType,n.readOnly=!0},Cn=(e,t,n,r)=>{const o=e._zod.def;O(o.innerType,t,r);const i=t.seen.get(e);i.ref=o.innerType},Qi=f("ZodISODateTime",(e,t)=>{os.init(e,t),v.init(e,t)});function ea(e){return ci(Qi,e)}const ta=f("ZodISODate",(e,t)=>{ss.init(e,t),v.init(e,t)});function na(e){return ui(ta,e)}const ra=f("ZodISOTime",(e,t)=>{is.init(e,t),v.init(e,t)});function oa(e){return li(ra,e)}const sa=f("ZodISODuration",(e,t)=>{as.init(e,t),v.init(e,t)});function ia(e){return fi(sa,e)}const aa=(e,t)=>{En.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>Hr(e,n)},flatten:{value:n=>qr(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,He,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,He,2)}},isEmpty:{get(){return e.issues.length===0}}})},Z=f("ZodError",aa,{Parent:Error}),ca=it(Z),ua=at(Z),la=Ue(Z),fa=Le(Z),da=Kr(Z),ha=Xr(Z),pa=Qr(Z),ma=eo(Z),ga=to(Z),ya=no(Z),wa=ro(Z),_a=oo(Z),xt=new WeakMap;function pe(e,t,n){const r=Object.getPrototypeOf(e);let o=xt.get(r);if(o||(o=new Set,xt.set(r,o)),!o.has(t)){o.add(t);for(const i in n){const s=n[i];Object.defineProperty(r,i,{configurable:!0,enumerable:!1,get(){const a=s.bind(this);return Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}const k=f("ZodType",(e,t)=>(S.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:$e(e,"input"),output:$e(e,"output")}}),e.toJSONSchema=Ii(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,r)=>ca(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>la(e,n,r),e.parseAsync=async(n,r)=>ua(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>fa(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>da(e,n,r),e.decode=(n,r)=>ha(e,n,r),e.encodeAsync=async(n,r)=>pa(e,n,r),e.decodeAsync=async(n,r)=>ma(e,n,r),e.safeEncode=(n,r)=>ga(e,n,r),e.safeDecode=(n,r)=>ya(e,n,r),e.safeEncodeAsync=async(n,r)=>wa(e,n,r),e.safeDecodeAsync=async(n,r)=>_a(e,n,r),pe(e,"ZodType",{check(...n){const r=this.def;return this.clone(G(r,{checks:[...r.checks??[],...n.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return W(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(dc(n,r))},superRefine(n,r){return this.check(hc(n,r))},overwrite(n){return this.check(se(n))},optional(){return Dt(this)},exactOptional(){return Qa(this)},nullable(){return Ct(this)},nullish(){return Dt(Ct(this))},nonoptional(n){return sc(this,n)},array(){return ne(this)},or(n){return qa([this,n])},and(n){return Ja(this,n)},transform(n){return Ft(this,Ka(n))},default(n){return nc(this,n)},prefault(n){return oc(this,n)},catch(n){return ac(this,n)},pipe(n){return Ft(this,n)},readonly(){return lc(this)},describe(n){const r=this.clone();return ae.add(r,{description:n}),r},meta(...n){if(n.length===0)return ae.get(this);const r=this.clone();return ae.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return ae.get(e)?.description},configurable:!0}),e)),Fn=f("_ZodString",(e,t)=>{ct.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,o,i)=>Li(e,r,o);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,pe(e,"_ZodString",{regex(...r){return this.check(yi(...r))},includes(...r){return this.check(bi(...r))},startsWith(...r){return this.check(vi(...r))},endsWith(...r){return this.check(Ti(...r))},min(...r){return this.check(Pe(...r))},max(...r){return this.check(Nn(...r))},length(...r){return this.check(xn(...r))},nonempty(...r){return this.check(Pe(1,...r))},lowercase(r){return this.check(wi(r))},uppercase(r){return this.check(_i(r))},trim(){return this.check(Ri())},normalize(...r){return this.check(Ei(...r))},toLowerCase(){return this.check(Si())},toUpperCase(){return this.check(ki())},slugify(){return this.check(zi())}})}),ba=f("ZodString",(e,t)=>{ct.init(e,t),Fn.init(e,t),e.email=n=>e.check(Cs(va,n)),e.url=n=>e.check(Vs(Ta,n)),e.jwt=n=>e.check(ai(xa,n)),e.emoji=n=>e.check(qs(Ea,n)),e.guid=n=>e.check(Ut(Mt,n)),e.uuid=n=>e.check(Fs(be,n)),e.uuidv4=n=>e.check(js(be,n)),e.uuidv6=n=>e.check(Gs(be,n)),e.uuidv7=n=>e.check(Ws(be,n)),e.nanoid=n=>e.check(Hs(Ra,n)),e.guid=n=>e.check(Ut(Mt,n)),e.cuid=n=>e.check(Js(Sa,n)),e.cuid2=n=>e.check(Ys(ka,n)),e.ulid=n=>e.check(Ks(za,n)),e.base64=n=>e.check(oi(La,n)),e.base64url=n=>e.check(si(Ba,n)),e.xid=n=>e.check(Xs(Pa,n)),e.ksuid=n=>e.check(Qs($a,n)),e.ipv4=n=>
64e.check(ei(Aa,n)),e.ipv6=n=>e.check(ti(Oa,n)),e.cidrv4=n=>e.check(ni(Ia,n)),e.cidrv6=n=>e.check(ri(Ua,n)),e.e164=n=>e.check(ii(Na,n)),e.datetime=n=>e.check(ea(n)),e.date=n=>e.check(na(n)),e.time=n=>e.check(oa(n)),e.duration=n=>e.check(ia(n))});function $(e){return Ds(ba,e)}const v=f("ZodStringFormat",(e,t)=>{_.init(e,t),Fn.init(e,t)}),va=f("ZodEmail",(e,t)=>{Jo.init(e,t),v.init(e,t)}),Mt=f("ZodGUID",(e,t)=>{qo.init(e,t),v.init(e,t)}),be=f("ZodUUID",(e,t)=>{Ho.init(e,t),v.init(e,t)}),Ta=f("ZodURL",(e,t)=>{Yo.init(e,t),v.init(e,t)}),Ea=f("ZodEmoji",(e,t)=>{Ko.init(e,t),v.init(e,t)}),Ra=f("ZodNanoID",(e,t)=>{Xo.init(e,t),v.init(e,t)}),Sa=f("ZodCUID",(e,t)=>{Qo.init(e,t),v.init(e,t)}),ka=f("ZodCUID2",(e,t)=>{es.init(e,t),v.init(e,t)}),za=f("ZodULID",(e,t)=>{ts.init(e,t),v.init(e,t)}),Pa=f("ZodXID",(e,t)=>{ns.init(e,t),v.init(e,t)}),$a=f("ZodKSUID",(e,t)=>{rs.init(e,t),v.init(e,t)}),Aa=f("ZodIPv4",(e,t)=>{cs.init(e,t),v.init(e,t)}),Oa=f("ZodIPv6",(e,t)=>{us.init(e,t),v.init(e,t)}),Ia=f("ZodCIDRv4",(e,t)=>{ls.init(e,t),v.init(e,t)}),Ua=f("ZodCIDRv6",(e,t)=>{fs.init(e,t),v.init(e,t)}),La=f("ZodBase64",(e,t)=>{ds.init(e,t),v.init(e,t)}),Ba=f("ZodBase64URL",(e,t)=>{ps.init(e,t),v.init(e,t)}),Na=f("ZodE164",(e,t)=>{ms.init(e,t),v.init(e,t)}),xa=f("ZodJWT",(e,t)=>{ys.init(e,t),v.init(e,t)}),jn=f("ZodNumber",(e,t)=>{In.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,o,i)=>Bi(e,r,o),pe(e,"ZodNumber",{gt(r,o){return this.check(Bt(r,o))},gte(r,o){return this.check(Ze(r,o))},min(r,o){return this.check(Ze(r,o))},lt(r,o){return this.check(Lt(r,o))},lte(r,o){return this.check(Me(r,o))},max(r,o){return this.check(Me(r,o))},int(r){return this.check(Zt(r))},safe(r){return this.check(Zt(r))},positive(r){return this.check(Bt(0,r))},nonnegative(r){return this.check(Ze(0,r))},negative(r){return this.check(Lt(0,r))},nonpositive(r){return this.check(Me(0,r))},multipleOf(r,o){return this.check(Nt(r,o))},step(r,o){return this.check(Nt(r,o))},finite(){return this}});const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function Re(e){return di(jn,e)}const Ma=f("ZodNumberFormat",(e,t)=>{ws.init(e,t),jn.init(e,t)});function Zt(e){return hi(Ma,e)}const Za=f("ZodBoolean",(e,t)=>{_s.init(e,t),k.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ni(e,n,r)});function Da(e){return pi(Za,e)}const Ca=f("ZodUnknown",(e,t)=>{bs.init(e,t),k.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Mi()});function j(){return mi(Ca)}const Fa=f("ZodNever",(e,t)=>{vs.init(e,t),k.init(e,t),e._zod.processJSONSchema=(n,r,o)=>xi(e,n,r)});function ja(e){return gi(Fa,e)}const Ga=f("ZodArray",(e,t)=>{Ts.init(e,t),k.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Fi(e,n,r,o),e.element=t.element,pe(e,"ZodArray",{min(n,r){return this.check(Pe(n,r))},nonempty(n){return this.check(Pe(1,n))},max(n,r){return this.check(Nn(n,r))},length(n,r){return this.check(xn(n,r))},unwrap(){return this.element}})});function ne(e,t){return Pi(Ga,e,t)}const Wa=f("ZodObject",(e,t)=>{Rs.init(e,t),k.init(e,t),e._zod.processJSONSchema=(n,r,o)=>ji(e,n,r,o),w(e,"shape",()=>t.shape),pe(e,"ZodObject",{keyof(){return Gn(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:j()})},loose(){return this.clone({...this._zod.def,catchall:j()})},strict(){return this.clone({...this._zod.def,catchall:ja()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return Cr(this,n)},safeExtend(n){return Fr(this,n)},merge(n){return jr(this,n)},pick(n){return Zr(this,n)},omit(n){return Dr(this,n)},partial(...n){return Gr(Wn,this,n[0])},required(...n){return Wr(Vn,this,n[0])}})});function re(e,t){const n={type:"object",shape:e??{},...g(t)};return new Wa(n)}const Va=f("ZodUnion",(e,t)=>{Ss.init(e,t),k.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Gi(e,n,r,o),e.options=t.options});function qa(e,t){return new Va({type:"union",options:e,...g(t)})}const Ha=f("ZodIntersection",(e,t)=>{ks.init(e,t),k.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Wi(e,n,r,o)});function Ja(e,t){return new Ha({type:"intersection",left:e,right:t})}const Ye=f("ZodEnum",(e,t)=>{zs.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,o,i)=>Zi(e,r,o),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,o)=>{const i={};for(const s of r)if(n.has(s))i[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Ye({...t,checks:[],...g(o),entries:i})},e.exclude=(r,o)=>{const i={...t.entries};for(const s of r)if(n.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new Ye({...t,checks:[],...g(o),entries:i})}});function Gn(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new Ye({type:"enum",entries:n,...g(t)})}const Ya=f("ZodTransform",(e,t)=>{Ps.init(e,t),k.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ci(e,n),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new yn(e.constructor.name);n.addIssue=i=>{if(typeof i=="string")n.issues.push(fe(i,n.value,t));else{const s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=e),n.issues.push(fe(s))}};
vendor: 2,364 bytes, line 64
64const o=t.transform(n.value,n);return o instanceof Promise?o.then(i=>(n.value=i,n.fallback=!0,n)):(n.value=o,n.fallback=!0,n)}});function Ka(e){return new Ya({type:"transform",transform:e})}const Wn=f("ZodOptional",(e,t)=>{Bn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Cn(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function Dt(e){return new Wn({type:"optional",innerType:e})}const Xa=f("ZodExactOptional",(e,t)=>{$s.init(e,t),k.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Cn(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function Qa(e){return new Xa({type:"optional",innerType:e})}const ec=f("ZodNullable",(e,t)=>{As.init(e,t),k.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Vi(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function Ct(e){return new ec({type:"nullable",innerType:e})}const tc=f("ZodDefault",(e,t)=>{Os.init(e,t),k.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Hi(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function nc(e,t){return new tc({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():bn(t)}})}const rc=f("ZodPrefault",(e,t)=>{Is.init(e,t),k.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ji(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function oc(e,t){return new rc({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():bn(t)}})}const Vn=f("ZodNonOptional",(e,t)=>{Us.init(e,t),k.init(e,t),e._zod.processJSONSchema=(n,r,o)=>qi(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function sc(e,t){return new Vn({type:"nonoptional",innerType:e,...g(t)})}const ic=f("ZodCatch",(e,t)=>{Ls.init(e,t),k.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Yi(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function ac(e,t){return new ic({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const cc=f("ZodPipe",(e,t)=>{Bs.init(e,t),k.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ki(e,n,r,o),e.in=t.in,e.out=t.out});function Ft(e,t){return new cc({type:"pipe",in:e,out:t})}const uc=f("ZodReadonly",(e,t)=>{Ns.init(e,t),k.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Xi(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function lc(e){return new uc({type:"readonly",innerType:e})}const fc=f("ZodCustom",(e,t)=>{xs.init(e,t),k.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Di(e,n)});function dc(e,t={}){return $i(fc,e,t)}function hc(e,t){return Ai(e,t)}
64class pc extends Error{constructor(){super("LiteRT-LM is not initialized yet. Please call loadLiteRtLm() and wait for its promise to resolve to load the LiteRT-LM WASM module.")}}let Ke,ut;function qn(){if(!Ke)throw new pc;return Ke}function mc(e){Ke=e}function Hn(){return ut}function gc(){return!!ut}function jt(e){ut=e}class Jn{liteRtLmWasm;static DEFAULT_WASM_PATH="https://cdn.jsdelivr.net/npm/@litert-lm/[email protected]/wasm";constructor(t){this.liteRtLmWasm=t,this.liteRtLmWasm.setupLogging()}async setupDefaultWebGpuDevice(){this.liteRtLmWasm.preinitializedWebGPUDevice||(this.liteRtLmWasm.preinitializedWebGPUDevice=await wc())}delete(){}}const yc=["shader-f16","subgroups"];async function wc(){const e={powerPreference:"high-performance"},t=await navigator.gpu.requestAdapter(e);if(!t)throw new Error("No GPU adapter found.");const n={maxBufferSize:t.limits.maxBufferSize,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxStorageBuffersPerShaderStage:t.limits.maxStorageBuffersPerShaderStage,maxTextureDimension2D:t.limits.maxTextureDimension2D},r=[];for(const o of yc)t.features.has(o)&&r.push(o);return await t.requestDevice({requiredFeatures:r,requiredLimits:n})}async function _c(e){if(typeof importScripts=="function")importScripts(e.toString());else{const t=document.createElement("script");return t.src=e.toString(),t.crossOrigin="anonymous",new Promise((n,r)=>{t.addEventListener("load",()=>{n()},!1),t.addEventListener("error",o=>{r(o)},!1),document.body.appendChild(t)})}}var bc=async(e,t,n,r,o)=>{if(t&&await _c(t),!self.ModuleFactory)throw new Error("ModuleFactory not set.");const i=await self.ModuleFactory(self.Module||o);return self.ModuleFactory=self.Module=void 0,new e(i,r)};function vc(e,t){if(!e)return t;if(!t)return e;const n=e.endsWith("/")?e:e+"/",r=t.startsWith("/")?t.substring(1):t;return n+r}const Tc=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,15,1,13,0,65,1,253,15,65,2,253,15,253,128,2,11]),Ec=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]),D={relaxedSimd:void 0,threads:void 0,jspi:void 0};function Rc(){return"Suspending"in WebAssembly}async function Gt(e){try{return await WebAssembly.instantiate(e),{supported:!0}}catch(t){return{supported:!1,error:t}}}const Sc={relaxedSimd:()=>(D.relaxedSimd===void 0&&(D.relaxedSimd=Gt(Tc)),D.relaxedSimd),threads:()=>{if(D.threads===void 0)try{typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),D.threads=Gt(Ec)}catch(e){D.threads=Promise.resolve({supported:!1,error:e})}return D.threads},jspi:()=>{if(D.jspi===void 0)try{const e=Rc();D.jspi=Promise.resolve({supported:e,error:e?void 0:new Error("JSPI is not supported")})}catch(e){D.jspi=Promise.resolve({supported:!1,error:e})}return D.jspi}};async function Wt(e){const t=Sc[e]?.();if(!t)throw new Error(`Unknown feature: ${e}`);return(await t).supported}const kc="litertlm_wasm_internal.js",zc="litertlm_wasm_compat_internal.js",Pc="litertlm_wasm_asyncify_internal.js",$c="litertlm_wasm_compat_asyncify_internal.js";async function Ac(e,t){const n=e,r=await Wt("relaxedSimd"),o=await Wt("jspi");let i="";r?i=o?kc:Pc:i=o?zc:$c;let s=e;if(n.endsWith(".wasm"))throw new Error("Please load the `.js` file corresponding to the `.wasm` file, or load the directory containing it.");return n.endsWith(".js")||(s=vc(e,i)),bc(Jn,s)}let ve;function Oc(e,t){if(gc())throw new Error("LiteRT-LM is already loading / loaded.");return jt(Ac(e).then(async n=>(mc(n),n)).catch(n=>{throw jt(void 0),n})),Hn()}function Yn(e){const t=Hn();if(t){if(e&&ve!==e)throw new Error(`LiteRT-LM is already loading / loaded with a different path ${ve} but was requested to load ${e}. To reload with a different path, call unloadLiteRtLm() first.`);return t}return ve=e??Jn.DEFAULT_WASM_PATH,t??Oc(ve)}const B={UNSPECIFIED:0,CPU_ARTISAN:1,GPU_ARTISAN:2,CPU:3,GPU:4,GOOGLE_TENSOR_ARTISAN:5,NPU:6};function Ae(e){const t=new Array(e.size());for(let n=0;n<e.size();++n)t[n]=e.get(n);return e.delete(),t}function Kn(e,t){for(const n of e)t.push_back(n)}function Ic(e,t,n,r=qn().liteRtLmWasm){const o=e.getMutableMainExecutorSettings();if(o.setCacheDir(":nocache"),t.benchmarkEnabled&&e.enableBenchmark(),t.mainExecutorSettings){const i=t.mainExecutorSettings;if(i.maxNumTokens!==void 0&&o.setMaxNumTokens(i.maxNumTokens),i.samplerBackend!==void 0&&o.setSamplerBackend({value:i.samplerBackend}),i.backendConfig!==void 0){const s=i.backendConfig;if(n===B.CPU)o.setBackendConfigCpu(s);else if(n===B.GPU)o.setBackendConfigGpu(s);else if(n===B.GPU_ARTISAN){const a=s,c=new r.VectorUint32;Kn(a.supported_lora_ranks,c);const u={...a,supported_lora_ranks:c};o.setBackendConfigGpuArtisan(u),c.delete()}}if(i.advancedSettings!==void 0){const a={...o.getAdvancedSettings(),...i.advancedSettings};o.setAdvancedSettings(a)}}}function Uc(e){const t=e.getMutableMainExecutorSettings();let n,r;try{n=t.getBackendConfigCpu(),r=B.CPU}catch{try{n=t.getBackendConfigGpu(),r=B.GPU}catch{try{const s=t.getBackendConfigGpuArtisan();n={...s,supported_lora_ranks:Ae(s.supported_lora_ranks)},r=B.GPU_ARTISAN}catch{throw new Error("Unsupported backend config")}}}return{backend:r,mainExecutorSettings:{maxNumTokens:t.getMaxNumTokens(),samplerBackend:t.getSamplerBackend().value,backendConfig:n,advancedSettings:t.getAdvancedSettings()},benchmarkEnabled:!1}}class Lc{callbacks=new Set;add(t){return this.callbacks.add(t),()=>{this.callbacks.delete(t),t()}}
64run(){for(const t of this.callbacks)t();this.callbacks.clear()}}const Vt="Conversation is busy. A generation is already in progress.";class Bc{conversation;engine;mutexes;isBusy=!1;constructor(t,n,r){this.conversation=t,this.engine=n,this.mutexes=r}async sendMessage(t){if(this.isBusy)throw new Error(Vt);this.isBusy=!0;try{return await this.mutexes.executor.acquireAndRun(async()=>{const n=qt(t),r=await this.conversation.sendMessage(n);return JSON.parse(r)})}finally{this.isBusy=!1}}sendMessageStreaming(t){if(this.isBusy)throw new Error(Vt);this.isBusy=!0;let n=!1,r=!1;return new ReadableStream({start:o=>{const i=qt(t);(async()=>{await this.mutexes.executor.acquireAndRun(async()=>{await this.conversation.sendMessageAsync(i,(a,c,u)=>{if(!(n||r)){if(u){r=!0,this.isBusy=!1,o.error(new Error(u));return}if(a)try{const l=JSON.parse(a);o.enqueue(l)}catch(l){r=!0,this.isBusy=!1,o.error(l)}}}),await this.engine.waitUntilDone()}),!(n||r)&&(this.isBusy=!1,o.close())})().catch(a=>{n||r||(this.isBusy=!1,o.error(a))})},cancel:()=>{n=!0,this.isBusy=!1,this.cancel()}})}cancel(){this.conversation.cancelProcess()}async getHistory(){return this.mutexes.executor.acquireAndRun(()=>{const t=this.conversation.getHistory();return JSON.parse(t)})}async getTokenCount(){return this.mutexes.executor.acquireAndRun(()=>this.conversation.getTokenCount())}async getBenchmarkInfo(){return this.mutexes.executor.acquireAndRun(()=>this.conversation.getBenchmarkInfo())}async delete(){await this.mutexes.executor.acquireAndRun(()=>{this.conversation.delete()})}}function qt(e){let t;return Array.isArray(e)?t=e.map(Ht):t=Ht(e),JSON.stringify(t)}function Ht(e){return typeof e=="string"?{role:"user",content:e}:e}class Nc{mutexPromise=Promise.resolve();queueCount=0;get isLocked(){return this.queueCount>0}async acquireAndRun(t){this.queueCount++;const n=this.mutexPromise;let r;this.mutexPromise=new Promise(o=>{r=o});try{return await n,await t()}finally{this.queueCount--,r()}}}class xc{size;data;fullyDiscarded=!1;discardedRegions=[];constructor(t){this.size=t}discard(t,n){if(this.fullyDiscarded)return;if(this.discardedRegions.length===0){this.discardedRegions.push([t,n]),this.checkFullyDiscarded();return}this.discardedRegions.push([t,n]),this.discardedRegions.sort((o,i)=>o[0]-i[0]);const r=[];for(const o of this.discardedRegions){const i=r[r.length-1];!i||i[1]<o[0]?r.push(o):i[1]=Math.max(i[1],o[1])}this.discardedRegions=r,this.checkFullyDiscarded()}getDiscardedRegions(t=0,n=this.size){const r=[];for(const[o,i]of this.discardedRegions){if(o>=n)break;i<=t||r.push([o,i])}return r}checkFullyDiscarded(){this.discardedRegions.length===1&&this.discardedRegions[0][0]===0&&this.discardedRegions[0][1]===this.size&&(this.fullyDiscarded=!0,this.data=void 0)}}class Mc{stream;getWasmHeap;bytesPerSlice;slices=[];streamDone=!1;globalPosition=0;reader;leftoverData;isReading=!1;constructor(t,n,r=1e7){this.stream=t,this.getWasmHeap=n,this.bytesPerSlice=r;try{this.reader={byobReader:this.stream.getReader({mode:"byob"})}}catch{this.reader={defaultReader:this.stream.getReader()}}}*getViews(t,n){if(t>=n)return;let r,o,i=t;for(;i<n;){const s=Math.floor(i/this.bytesPerSlice),a=i%this.bytesPerSlice,c=s*this.bytesPerSlice;let u=this.slices[s];u||((!o||!o.fullyDiscarded)&&(r=new Uint8Array(this.bytesPerSlice)),u=new xc(this.bytesPerSlice),u.data=r,this.slices[s]=u);const l=Math.min(this.bytesPerSlice,n-c),h=()=>{u.discard(a,l)},p=l-a,d=y=>{u.data=new Uint8Array(y.buffer,0,y.buffer.byteLength),r=u.data},m=()=>{const y=u.getDiscardedRegions(a,l);if(y.length>0){const C=y.map(([X,x])=>`[${X+c}, ${x+c}]`);throw new Error(`Slice ${s} for data at ${i} overlaps discarded regions: [${C.join(", ")}]`)}if(!u.data)throw new Error(`No ArrayBuffer for slice ${s} at position ${i}`)};yield{getView:()=>(m(),new Uint8Array(u.data.buffer,u.data.byteOffset+a,u.data.byteOffset+p)),discardView:h,setView:d,checkReadable:m},o=u,i+=p}}async readInternal(t,n,r,o){if(this.isReading)throw new Error("Concurrent reads are not supported");this.isReading=!0;try{for(const{getView:a,setView:c,checkReadable:u}of this.getViews(this.globalPosition,n)){u();const l=await this.fillBufferFromStream(a());if(c(l),l.length===0)break}const i=Math.min(this.globalPosition,n+r);for(const{getView:a,discardView:c}of this.getViews(n,i)){const u=a();this.getWasmHeap().set(u,t),o&&c(),t+=u.length}const s=Math.max(i,n);
64for(const{getView:a,setView:c,discardView:u}of this.getViews(s,n+r)){if(this.streamDone&&this.globalPosition<=s)break;const l=await this.fillBufferFromStream(a());c(l),this.getWasmHeap().set(l,t),o&&u(),t+=l.length}}finally{this.isReading=!1}}async fillBufferFromStream(t){const n=t.byteLength;if(n===0)return t;const r=t.byteOffset;let o=0,i=t.buffer;for(;o<n;){if(this.streamDone&&(!this.leftoverData||this.leftoverData.length===0))throw new Error(`Read from stream returned early EOF at position ${this.globalPosition}. Expected ${n-o} more bytes.`);if(this.reader.byobReader){const a=new Uint8Array(i,r+o,n-o),c=await this.reader.byobReader.read(a);if(c.done&&(this.streamDone=!0),!c.value)throw new Error("Read from stream returned null value");this.globalPosition+=c.value.byteLength,o+=c.value.byteLength,i=c.value.buffer}else{let a;if(this.leftoverData&&this.leftoverData.length>0)a=this.leftoverData,this.leftoverData=void 0;else{const h=await this.reader.defaultReader.read();if(h.done&&(this.streamDone=!0,!h.value))continue;if(!h.value)throw new Error("Read from stream returned null value");a=h.value}const c=n-o,u=Math.min(a.length,c);new Uint8Array(i,r+o,u).set(a.subarray(0,u)),a.length>u&&(this.leftoverData=a.subarray(u)),this.globalPosition+=u,o+=u}}const s=new Uint8Array(i,r,o);if(s.length!==n)throw new Error(`Read from stream returned ${s.length} bytes, expected ${n}`);return s}doDiscard(t,n){for(const{discardView:r}of this.getViews(t,t+n))r()}async readAndDiscard(t,n,r){try{return await this.readInternal(t>>>0,Q(n),Q(r),!0),{}}catch(o){return{error:o}}}async readAndPreserve(t,n,r){try{return await this.readInternal(t>>>0,Q(n),Q(r),!1),{}}catch(o){return{error:o}}}async discard(t,n){try{return this.doDiscard(Q(t),Q(n)),{}}catch(r){return{error:r}}}}function Q(e){if(typeof e=="number")return e;if(e>Number.MAX_SAFE_INTEGER)throw new Error(`BigInt value ${e} too large to be represented as a number`);return Number(e)}function Jt(e,t=qn().liteRtLmWasm){const n=t.SessionConfig.createDefault();if(e.audioModalityEnabled!==void 0&&n.setAudioModalityEnabled(e.audioModalityEnabled),e.visionModalityEnabled!==void 0&&n.setVisionModalityEnabled(e.visionModalityEnabled),e.samplerParams!==void 0){const r=n.getMutableSamplerParams();e.samplerParams.type!==void 0&&r.setType({value:e.samplerParams.type}),e.samplerParams.k!==void 0&&r.setK(e.samplerParams.k),e.samplerParams.p!==void 0&&r.setP(e.samplerParams.p),e.samplerParams.temperature!==void 0&&r.setTemperature(e.samplerParams.temperature),e.samplerParams.seed!==void 0&&r.setSeed(e.samplerParams.seed)}if(e.startTokenId!==void 0&&n.setStartTokenId(e.startTokenId),e.numOutputCandidates!==void 0&&n.setNumOutputCandidates(e.numOutputCandidates),e.samplerBackend!==void 0&&n.setSamplerBackend({value:e.samplerBackend}),e.applyPromptTemplateInSession!==void 0&&n.setApplyPromptTemplateInSession(e.applyPromptTemplateInSession),e.useExternalSampler!==void 0&&n.setUseExternalSampler(e.useExternalSampler),e.maxOutputTokens!==void 0&&n.setMaxOutputTokens(e.maxOutputTokens),e.stopTokenIds!==void 0){const r=new t.VectorVectorInt;for(const o of e.stopTokenIds){const i=new t.VectorInt;Kn(o,i),r.push_back(i),i.delete()}n.setStopTokenIds(r),r.delete()}return n}function Zc(e){const t=e.getMutableSamplerParams();return{audioModalityEnabled:e.getAudioModalityEnabled(),visionModalityEnabled:e.getVisionModalityEnabled(),samplerParams:{type:t.type().value,k:t.k(),p:t.p(),temperature:t.temperature(),seed:t.seed()},stopTokenIds:Ae(e.getStopTokenIds()).map(Ae),startTokenId:e.getStartTokenId(),numOutputCandidates:e.getNumOutputCandidates(),samplerBackend:e.getSamplerBackend().value,applyPromptTemplateInSession:e.getApplyPromptTemplateInSession(),useExternalSampler:e.getUseExternalSampler(),maxOutputTokens:e.getMaxOutputTokens()}}const Yt="Session is busy. An operation is already in progress.";class Dc{session;mutexes;config;isBusy=!1;constructor(t,n){this.session=t,this.mutexes=n;const r=t.getSessionConfig();this.config=Zc(r),r.delete()}async runPrefill(t){if(this.isBusy)throw new Error(Yt);this.isBusy=!0;try{await this.mutexes.executor.acquireAndRun(async()=>{await this.session.runPrefill(t)})}finally{this.isBusy=!1}}async runDecode(){if(this.isBusy)throw new Error(Yt);this.isBusy=!0;try{return await this.mutexes.executor.acquireAndRun(async()=>{const t=await this.session.runDecode();return new Cc(t)})}finally{this.isBusy=!1}}cancel(){this.session.cancelProcess()}async delete(){await this.mutexes.executor.acquireAndRun(()=>{this.session.delete()})}}class Cc{responses;constructor(t){this.responses=t}getTexts(){const t=this.responses.getTexts();return Ae(t)}delete(){this.responses.delete()}}let Fc=0;class lt{wasm;engine;
64deleteCallback;settings;mutexes={executor:new Nc};constructor(t,n,r,o){this.wasm=t,this.engine=n,this.deleteCallback=o;const i=n.getEngineSettings(),s=Uc(i);this.settings={...s,model:r},i.delete()}static async create(t,n=""){const r=await Yn(),o=r.liteRtLmWasm,i=`/model_${Fc++}.litertlm`,s=t.backend??B.GPU_ARTISAN;t={...t,backend:s};const a=t.mainExecutorSettings?.samplerBackend;(s===B.GPU||s===B.GPU_ARTISAN||a===B.GPU||a===B.GPU_ARTISAN)&&await r.setupDefaultWebGpuDevice();const c=new Lc,u=await jc(t.model);let l;try{let h;const p=s===B.GPU_ARTISAN;if(p){const y=new Mc(u,()=>o.HEAPU8),C=o.ReadableStreamDataStream.create(y);c.add(()=>{C.delete()}),h=o.ModelAssets.createStreaming(C)}else await Gc(o,u,i),c.add(()=>{try{o.FS.unlink(i)}catch(y){console.error("Error removing file from VFS:",y)}}),h=o.ModelAssets.create(i);const d=c.add(()=>{h.delete()}),m=o.EngineSettings.createDefault(h,{value:s});d();const I=c.add(()=>{m.delete()});return Ic(m,t,s,o),m.setParallelFileSectionLoading(!1),m.setSingleThreadedExecution(!0),p?l=await o.Engine.createStreaming(m,n):l=await o.Engine.createEngine(m,n),I(),c.add(()=>{l.delete()}),new lt(o,l,t.model,()=>c.run())}catch(h){throw c.run(),h}}async createSession(t={}){return this.mutexes.executor.acquireAndRun(()=>{const n=Jt(t,this.wasm),r=this.engine.createSession(n);return n.delete(),new Dc(r,this.mutexes)})}async createConversation(t){return this.mutexes.executor.acquireAndRun(async()=>{let n,r;if(t){r=Jt(t.sessionConfig||{},this.wasm);const i=t.preface?JSON.stringify(t.preface):"";n=this.wasm.ConversationConfig.createCustom(this.engine,r,!!t.enableConstrainedDecoding,!!t.prefillPrefaceOnInit,!!t.filterChannelContentFromKvCache,i)}else n=this.wasm.ConversationConfig.createDefault(this.engine);const o=await this.wasm.Conversation.create(this.engine,n);return n.delete(),r&&r.delete(),new Bc(o,this.engine,this.mutexes)})}async delete(){await this.mutexes.executor.acquireAndRun(()=>{this.deleteCallback()})}}async function jc(e){if(e instanceof ReadableStream)return e;if(e instanceof Blob)return e.stream();const t=e,n=await fetch(t,{credentials:"same-origin"});if(!n.ok)throw new Error(`Failed to fetch model file from ${t}`);return n.body}async function Gc(e,t,n){let r;const o=t.getReader(),i=[];let s=0;for(;;){const{done:c,value:u}=await o.read();if(c)break;u&&(i.push(u),s+=u.length)}r=new Uint8Array(s);let a=0;for(const c of i)r.set(c,a),a+=c.length;try{e.FS.writeFile(n,r)}catch(c){throw console.error("Error writing file to VFS:",c),c}}var b={NONE:0,FLOAT32:1,INT32:2,UINT8:3,INT64:4,STRING:5,BOOL:6,INT16:7,COMPLEX64:8,INT8:9,FLOAT16:10,FLOAT64:11,COMPLEX128:12,UINT64:13,RESOURCE:14,VARIANT:15,UINT32:16,UINT16:17,INT4:18,BFLOAT16:19},Xn={[b.NONE]:"NONE",[b.FLOAT32]:"FLOAT32",[b.INT32]:"INT32",[b.UINT8]:"UINT8",[b.INT64]:"INT64",[b.STRING]:"STRING",[b.BOOL]:"BOOL",[b.INT16]:"INT16",[b.COMPLEX64]:"COMPLEX64",[b.INT8]:"INT8",[b.FLOAT16]:"FLOAT16",[b.FLOAT64]:"FLOAT64",[b.COMPLEX128]:"COMPLEX128",[b.UINT64]:"UINT64",[b.RESOURCE]:"RESOURCE",[b.VARIANT]:"VARIANT",[b.UINT32]:"UINT32",[b.UINT16]:"UINT16",[b.INT4]:"INT4",[b.BFLOAT16]:"BFLOAT16"},A={HOST_MEMORY:1,WEB_GPU_BUFFER:20,WEB_GPU_BUFFER_FP16:21,WEB_GPU_BUFFER_PACKED:26},V={[A.HOST_MEMORY]:"HOST_MEMORY",[A.WEB_GPU_BUFFER]:"WEB_GPU_BUFFER",[A.WEB_GPU_BUFFER_FP16]:"WEB_GPU_BUFFER_FP16",[A.WEB_GPU_BUFFER_PACKED]:"WEB_GPU_BUFFER_PACKED"},Wc=Object.freeze([{dtype:"float32",typedArrayConstructor:Float32Array,elementType:b.FLOAT32},{dtype:"int32",typedArrayConstructor:Int32Array,elementType:b.INT32},{dtype:"uint8",typedArrayConstructor:Uint8Array,elementType:b.UINT8}]);function ie(e){for(const t of Wc)if(t.dtype===e||t.typedArrayConstructor===e||e instanceof t.typedArrayConstructor||t.elementType===e)return t;throw typeof e=="string"?new Error(`DType ${e} is not supported.`):e instanceof Object?new Error(`Typed array ${"name"in e?e.name:e.constructor.name} is not supported.`):new Error(`Element type ${Xn[e]??e} is not supported.`)}var Vc=class extends Error{constructor(){super("LiteRT is not initialized yet. Please call loadLiteRt() and wait for its promise to resolve to load the LiteRT WASM module.")}};function M(){throw new Vc}var qc={webgpu:A.WEB_GPU_BUFFER_PACKED,wasm:A.HOST_MEMORY},Hc={[A.HOST_MEMORY]:"wasm",[A.WEB_GPU_BUFFER]:"webgpu",[A.WEB_GPU_BUFFER_FP16]:"webgpu",[A.WEB_GPU_BUFFER_PACKED]:"webgpu"},Jc=["shader-f16","subgroups"],Yc=class Qn{constructor(t){this.options=t,this.liteRtEnvironment=M().liteRtWasm.LiteRtEnvironment.create(t.webGpuDevice)}liteRtEnvironment;static async create(t={}){let n=null;if("webGpuDevice"in t)t.webGpuDevice&&(n=t.webGpuDevice);else try{n=await Kc()}catch(r){console.warn("Failed to create default WebGPU device:",r)}return new Qn({...t,webGpuDevice:n})}get webGpuDevice(){return this.options.webGpuDevice}delete(){this.liteRtEnvironment.delete()}};async function Kc(){const e={powerPreference:"high-performance"},t=await navigator.gpu.requestAdapter(e);if(!t)throw new Error("No GPU adapter found.");const n={maxBufferSize:t.limits.maxBufferSize,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxStorageBuffersPerShaderStage:t.limits.maxStorageBuffersPerShaderStage,maxTextureDimension2D:t.limits.maxTextureDimension2D},r=[];for(const o of Jc)t.features.has(o)&&r.push(o);return await t.requestDevice({requiredFeatures:r,requiredLimits:n}
64)}function Xc(e){const t=new Array(e.size());for(let n=0;n<e.size();++n)t[n]=e.get(n);return e.delete(),t}function er(e,t){for(const n of e)t.push_back(n)}function Qc(e){const t=e.shift(),n=M().liteRtWasm;if(t instanceof n.LiteRtTensorBuffer)return{liteRtTensorBuffer:t};if(ArrayBuffer.isView(t))return{typedArray:t};if(t instanceof GPUBuffer)return{gpuBuffer:t};throw new Error(`Unknown type (${t?.constructor.name??t}) provided to create a Tensor`)}function eu(e){return Array.isArray(e[0])||e[0]instanceof Int32Array?{shape:e.shift()}:{}}function ft(e){for(;e.length>0&&e[0]===void 0;)e.shift()}function tu(e){if(ft(e),typeof e[0]=="string"){const t=e.shift();return{dataType:ie(t).dtype}}else return{}}function nu(e){return ft(e),e[0]instanceof Yc?{environment:e.shift()}:{}}function ru(e){return ft(e),e[0]instanceof Function?{onDelete:e.shift()}:{}}function ou(e){return{...Qc(e),...eu(e),...tu(e),...nu(e),...ru(e)}}var de=class Xe{liteRtTensorBuffer;type;environment;deletedInternal=!1;onDelete;static copyFunctions=new Map;constructor(t,n,r,o,i){const{typedArray:s,gpuBuffer:a,liteRtTensorBuffer:c,shape:u,dataType:l,environment:h,onDelete:p}=ou([t,n,r,o,i]);if(this.onDelete=p,this.environment=h??M().getDefaultEnvironment(),c){if(u)throw new Error("A LiteRtTensorBuffer cannot be provided with a shape.");if(l)throw new Error("A LiteRtTensorBuffer cannot be provided with a data type.");this.liteRtTensorBuffer=c}else if(a){if(!u)throw new Error("A GPUBuffer must be provided with a shape.");if(!l)throw new Error("A GPUBuffer must be provided with a data type.");const[d,m]=iu(a,u,l,this.environment);this.liteRtTensorBuffer=d;const I=this.onDelete;this.onDelete=()=>{M().liteRtWasm.wgpuBufferRelease(m),I?.()}}else if(s)this.liteRtTensorBuffer=au(s,u,h);else throw new Error("No data provided to create a Tensor.");this.type=su(this.liteRtTensorBuffer)}static fromTypedArray(t,n,r){return new Xe(t,n,r)}ensureNotDeleted(){if(this.deleted)throw new Error("Tensor is deleted and cannot be used.")}async data(){if(this.ensureNotDeleted(),this.liteRtTensorBuffer.bufferType().value===A.HOST_MEMORY)return this.toTypedArray();const t=await this.copyTo("wasm"),n=await t.data();return t.delete(),n}toTypedArray(){this.ensureNotDeleted();const t=M().liteRtWasm;if(this.liteRtTensorBuffer.isWebGpuMemory())throw new Error("Cannot convert a Tensor with WebGPU memory to a TypedArray.");if(this.liteRtTensorBuffer.bufferType().value!==t.LiteRtTensorBufferType.HOST_MEMORY.value)throw new Error("Cannot convert a Tensor with non-host memory to a TypedArray.");if(this.liteRtTensorBuffer.size()!==this.liteRtTensorBuffer.packedSize()||this.liteRtTensorBuffer.offset()!==0)throw new Error("Tensors with strides or padding are not yet supported.");const n=this.liteRtTensorBuffer.tensorType(),r=n.elementType(),o=t.liteRtGetByteWidth(r);n.delete();const i=ie(r.value).typedArrayConstructor;if(i.BYTES_PER_ELEMENT!==o)throw new Error(`Byte width ${o} of the tensor's element type ${Xn[r.value]} does not match the expected byte width ${i.BYTES_PER_ELEMENT} of the ${i.name}.`);const s=this.liteRtTensorBuffer.lock(M().liteRtWasm.LiteRtTensorBufferLockMode.READ);try{const a=t.HEAPU8.slice(s,s+this.liteRtTensorBuffer.packedSize());return new i(a.buffer,a.byteOffset,a.byteLength/o)}finally{this.liteRtTensorBuffer.unlock()}}getBufferType(){return this.ensureNotDeleted(),this.liteRtTensorBuffer.bufferType().value}toGpuBuffer(){this.ensureNotDeleted();const t=M().liteRtWasm;if(!this.liteRtTensorBuffer.isWebGpuMemory())throw new Error("Cannot convert a Tensor with non-WebGPU memory to a GPUBuffer.");const n=this.liteRtTensorBuffer.bufferType().value;if(n!==t.LiteRtTensorBufferType.WEB_GPU_BUFFER.value&&n!==t.LiteRtTensorBufferType.WEB_GPU_BUFFER_FP16.value&&n!==t.LiteRtTensorBufferType.WEB_GPU_BUFFER_PACKED.value)throw new Error("Cannot convert a Tensor with host memory to a GPUBuffer.");if(this.liteRtTensorBuffer.size()!==this.liteRtTensorBuffer.packedSize()||this.liteRtTensorBuffer.offset()!==0)throw new Error("Tensors with strides or padding are not yet supported.");const r=this.liteRtTensorBuffer.getWebGpuBuffer();return t.WebGPU.getJsObject(r)}getCopyFunctionSet(t){this.ensureNotDeleted();const n=this.getBufferType(),r=Xe.copyFunctions.get(n);if(!r)throw new Error(`TensorBufferType ${V[n]??n} does not support copying or moving`);const o=typeof t=="string"?qc[t]:t;
64if(o==null)throw new Error(`Unknown destination '${t}' for copying or moving.`);const i=r.get(o);if(!i){const s=[...r].map(([a])=>V[a]??a);throw new Error(`TensorBufferType ${V[n]} does not support copying or moving to ${V[o]}. It supports the following TensorBufferTypes: [${s.join(", ")}].`)}return[i,o]}async copyTo(t,n){const[r,o]=this.getCopyFunctionSet(t);if(!r.copyTo)throw new Error(`Copying to ${V[o]} is not supported by this tensor.`);return r.copyTo(this,n)}async moveTo(t,n){const[r,o]=this.getCopyFunctionSet(t);if(!r.moveTo)throw new Error(`Moving to ${V[o]} is not supported by this tensor.`);return r.moveTo(this,n)}get bufferType(){return this.liteRtTensorBuffer.bufferType().value}get accelerator(){const t=Hc[this.bufferType];if(t===void 0)throw new Error(`TensorBufferType ${V[this.bufferType]} has an unknown accelerator type.`);return t}get deleted(){return this.deletedInternal}delete(){this.deletedInternal||(this.deletedInternal=!0,this.liteRtTensorBuffer.delete(),this.onDelete?.())}};function su(e){const t=e.tensorType(),n=t.elementType(),r=t.layout(),o=r.dimensions();return r.delete(),t.delete(),{dtype:ie(n.value).dtype,layout:{dimensions:Xc(o)}}}function iu(e,t,n,r){const i=M().liteRtWasm,s=new i.VectorInt32;er(t,s);const a=i.LiteRtLayout.create(s);s.delete();const c=i.LiteRtRankedTensorType.create({value:ie(n).elementType},a);a.delete();const u=i.WebGPU.importJsBuffer(e),l=i.LiteRtTensorBuffer.createFromWebGpuBuffer(r.liteRtEnvironment,c,i.LiteRtTensorBufferType.WEB_GPU_BUFFER_PACKED,u,e.size);return c.delete(),[l,u]}function au(e,t,n){const r=M(),o=r.liteRtWasm;n=n??r.getDefaultEnvironment();const i=ie(e).elementType,s=new o.VectorInt32;er(t??[e.length],s);const a=o.LiteRtLayout.create(s);s.delete();const c=a.numElements();if(e.length!==c)throw a.delete(),new Error(`Number of elements ${e.length} of the provided TypedArray does not match the expected number of elements ${c}.`);const u=o.LiteRtRankedTensorType.create({value:i},a);a.delete();const h=e.constructor.BYTES_PER_ELEMENT*e.length,p=u.bytes();if(h!==p)throw u.delete(),new Error(`Byte length ${h} of the provided TypedArray does not match the expected buffer size ${p}.`);const d=o.LiteRtTensorBuffer.createManaged(n.liteRtEnvironment,o.LiteRtTensorBufferType.HOST_MEMORY,u,h);u.delete();const m=d.lock(o.LiteRtTensorBufferLockMode.WRITE);try{const I=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);o.HEAPU8.set(I,m)}finally{d.unlock()}return d}async function Kt(e,t={}){const n=t.environment??e.environment,r=M().liteRtWasm,o=e.liteRtTensorBuffer;if(o.bufferType().value!==A.HOST_MEMORY)throw new Error("Source tensor is not in host memory. Cannot copy to host memory.");const s=o.lock(r.LiteRtTensorBufferLockMode.READ);let a;try{a=r.LiteRtTensorBuffer.createManaged(n.liteRtEnvironment,r.LiteRtTensorBufferType.HOST_MEMORY,o.tensorType(),o.size());const c=a.lock(r.LiteRtTensorBufferLockMode.WRITE);try{const u=new Uint8Array(r.HEAPU8.buffer,s,o.size());r.HEAPU8.set(u,c)}finally{a.unlock()}}finally{o.unlock()}if(!a)throw new Error("Failed to create destination tensor buffer.");return new de(a,n)}async function Xt(e,t={}){const n=t.environment??e.environment,r=n.webGpuDevice;if(!r)throw new Error("No WebGPU device is available. Did you forget to pass a destination environment that has a WebGPU device?");const o=M().liteRtWasm,s=e.liteRtTensorBuffer.size()+3&-4,a=r.createBuffer({size:s,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC,mappedAtCreation:!0}),c=await a.getMappedRange(),u=new Uint8Array(c),l=e.liteRtTensorBuffer.lock(o.LiteRtTensorBufferLockMode.READ);try{const d=new Uint8Array(o.HEAPU8.buffer,l,e.liteRtTensorBuffer.size());u.set(d)}finally{e.liteRtTensorBuffer.unlock()}a.unmap();const h=r.createBuffer({size:s,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST|GPUBufferUsage.STORAGE}),p=r.createCommandEncoder();return p.copyBufferToBuffer(a,0,h,0,s),r.queue.submit([p.finish()]),a.destroy(),new de(h,e.type.layout.dimensions,e.type.dtype,n,()=>{h.destroy()})}async function Qt(e,t={}){const n=t.environment??e.environment,r=e.environment.webGpuDevice;if(!r)throw new Error("No WebGPU device is available. Does the source tensor have a WebGPU device?");const o=M().liteRtWasm,i=e.liteRtTensorBuffer,s=i.bufferType();if(s!==o.LiteRtTensorBufferType.WEB_GPU_BUFFER_PACKED)throw new Error(`Cannot convert a tensor with a non-WebGPU buffer type ${s} to a CPU tensor.`);const a=o.WebGPU.getJsObject(i.getWebGpuBuffer()),c=i.offset(),u=i.tensorType(),l=u.layout(),h=l.numElements(),p=ie(u.elementType().value).typedArrayConstructor;l.delete(),u.delete();let d=a,m=()=>{};if(!(a.usage&GPUBufferUsage.MAP_READ)){d=r.createBuffer({size:a.size,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),m=()=>{d.destroy()};const X=r.createCommandEncoder();X.copyBufferToBuffer(a,0,d,0,a.size),r.queue.submit([X.finish()])}await d.mapAsync(GPUMapMode.READ);const I=d.getMappedRange(),y=new p(I,c,h),C=new de(y,e.type.layout.dimensions,n);
64return d.unmap(),m(),C}function De(e){return async(t,n)=>{const r=await e(t,n);return t.delete(),r}}function cu(){de.copyFunctions.set(A.HOST_MEMORY,new Map([[A.HOST_MEMORY,{copyTo:Kt,moveTo:De(Kt)}],[A.WEB_GPU_BUFFER_PACKED,{copyTo:Xt,moveTo:De(Xt)}]])),de.copyFunctions.set(A.WEB_GPU_BUFFER_PACKED,new Map([[A.HOST_MEMORY,{copyTo:Qt,moveTo:De(Qt)}]]))}cu();var U=class extends Error{causeValue;constructor(e,t,n=void 0){super(t),this.code=e,this.name="XybridError",this.causeValue=n}},F=class extends U{constructor(e,t=void 0){super("invalid_metadata",e,t),this.name="InvalidMetadataError"}},R=class extends U{constructor(e,t=void 0){super("registry",e,t),this.name="RegistryError"}},z=class extends U{constructor(e,t=void 0){super("huggingface",e,t),this.name="HuggingFaceError"}},Ce=class extends U{constructor(e,t=void 0){super("integrity",e,t),this.name="IntegrityError"}},tr=class extends U{constructor(e,t="TfLite"){super("unsupported_template",`Browser preview supports ${t} metadata, received ${e}.`),this.name="UnsupportedTemplateError"}},Te=class extends U{constructor(e){super("unsupported_feature",`Browser preview does not support ${e}.`),this.name="UnsupportedFeatureError"}},E=class extends U{constructor(e="LiteRT is already initialized with a different configuration."){super("runtime_configuration",e),this.name="RuntimeConfigurationError"}},oe=class extends U{constructor(e){super("runtime_initialization","LiteRT initialization or compilation failed.",e),this.name="RuntimeInitializationError"}},Qe=class extends U{constructor(e){super("input_validation",e),this.name="InputValidationError"}},uu=class extends U{constructor(e){super("inference","LiteRT inference failed.",e),this.name="InferenceError"}},en=class extends U{constructor(){super("concurrent_run","This model already has an in-flight run."),this.name="ConcurrentRunError"}},tn=class extends U{constructor(){super("disposed","This model has been disposed or disposal was requested."),this.name="DisposedError"}};const nn=32768,lu=re({model_id:$(),version:$(),execution_template:re({type:$(),model_file:$().optional(),context_length:j().optional()}).loose(),files:ne($()),preprocessing:ne(j()).default([]),postprocessing:ne(j()).default([]),voices:j().optional(),vision_encoder:j().optional()}).loose(),dt=e=>{const t=lu.safeParse(e);if(!t.success)throw new F("Model metadata does not match the Xybrid metadata contract.",t.error);return{modelId:t.data.model_id,version:t.data.version,template:{type:t.data.execution_template.type,modelFile:t.data.execution_template.model_file,contextLength:t.data.execution_template.context_length},files:t.data.files,preprocessing:t.data.preprocessing,postprocessing:t.data.postprocessing,voices:t.data.voices,visionEncoder:t.data.vision_encoder}},nr=(e,t)=>
64{if(e.preprocessing.length>0)throw new Te("metadata preprocessing");if(e.postprocessing.length>0)throw new Te("metadata postprocessing");if(e.voices!==void 0&&e.voices!==null)throw new Te("metadata voices");if(e.visionEncoder!==void 0&&e.visionEncoder!==null)throw new Te("metadata vision_encoder");if(e.template.modelFile===void 0)throw new F(`${t} metadata requires execution_template.model_file.`);return e.template.modelFile},rr=e=>{if(e.template.type!=="TfLite")throw new tr(e.template.type,"TfLite");return nr(e,"TfLite")},me=e=>{if(e.template.type!=="LiteRtLm")throw new tr(e.template.type,"LiteRtLm");const t=nr(e,"LiteRtLm"),n=e.template.contextLength;if(n===void 0)return{modelFile:t,contextLength:void 0};if(typeof n!="number"||!Number.isSafeInteger(n)||n<=0||n>nn)throw new F(`LiteRtLm metadata context_length must be a positive safe integer no greater than ${nn}.`);return{modelFile:t,contextLength:n}},fu=(e,t,n)=>{if(t.length===0||t==="."||t===".."||t.includes("/")||t.includes("\\")||t.includes(":")||t.includes("%")||t.includes("?")||t.includes("#")||t.trim()!==t||!/^[A-Za-z0-9._-]+$/.test(t))throw new F("model_file must be a bare filename in the metadata directory.");if(!n.includes(t))throw new F("model_file must be present in metadata files.");try{return new URL(t,e)}catch(r){throw new F("model_file could not be resolved beside the metadata.",r)}},ht=async(e,t,n,r,o,i)=>{if(i?.aborted)throw i.reason??new DOMException("The operation was aborted.","AbortError");const s=Number(e.headers.get("content-length")),a=Number.isFinite(s)&&s>0?s:void 0;if(a!==void 0&&a>t)throw new Error(n);if(e.body===null){const d=new Uint8Array(await e.arrayBuffer());if(d.byteLength>t)throw new Error(n);return o?.(d),r?.(d.byteLength,a??d.byteLength),[d]}const c=e.body.getReader(),u=[];let l=0,h=!1;const p=()=>{h=!0,c.cancel(i?.reason).catch(()=>{})};i?.addEventListener("abort",p,{once:!0});try{for(;;){const{done:d,value:m}=await c.read();if(h||i?.aborted)throw i?.reason??new DOMException("The operation was aborted.","AbortError");if(d)break;if(l+=m.byteLength,l>t)throw new Error(n);o?.(m),u.push(m),r?.(l,a)}}catch(d){throw await c.cancel(d instanceof Error?d.message:String(d)).catch(()=>{}),d}finally{i?.removeEventListener("abort",p),c.releaseLock()}return u},du=async(e,t,n,r)=>{const o=await ht(e,t,n,r),i=o.reduce((c,u)=>c+u.byteLength,0),s=new Uint8Array(i);let a=0;for(const c of o)s.set(c,a),a+=c.byteLength;return s};var ce=class extends Error{};const hu=(e,t)=>{try{const n=e instanceof URL?e:t===void 0?new URL(e):new URL(e,t);if(n.protocol!=="http:"&&n.protocol!=="https:")throw new F("metadataUrl must use HTTP(S).");return n}catch(n){throw n instanceof F?n:new F("metadataUrl must be a valid absolute or browser-relative URL.",n)}},pu=(e,t)=>{if(t===void 0)throw new E("wasmPath requires a browser location.");try{const n=new URL(t),r=new URL(e,n);if(r.protocol!=="http:"&&r.protocol!=="https:"||r.origin!==n.origin)throw new E("wasmPath must use the page's HTTP(S) origin.");return r}catch(n){throw n instanceof E?n:new E("wasmPath is not a valid browser URL.")}},mu=1024*1024,pt=(e,t,n)=>{if(typeof e!="object"||e===null)throw new E("load options must be an object.");const r=e,o=r.accelerator??"auto";wu(o);const i=r.wasmPath??n;if(typeof i!="string"&&!(i instanceof URL))throw new E("wasmPath must be a string or URL.");return{accelerator:o,wasmPath:pu(i,t)}},gu=(e,t,n)=>{const r=pt(e===void 0?{}:e,t,n),o=e===void 0?{}:e,i=o.onDownloadProgress;if(i!==void 0&&typeof i!="function")throw new E("onDownloadProgress must be a function.");const s=o.registryUrl;let a;if(s!==void 0){if(typeof s!="string"&&!(s instanceof URL))throw new E("registryUrl must be a string or URL.");try{if(a=new URL(s),a.protocol!=="https:")throw new E("registryUrl must use HTTPS.")}catch(l){throw l instanceof E?l:new E("registryUrl must be a valid HTTPS URL.")}}const c=o.version;if(c!==void 0&&typeof c!="string")throw new E("version must be a string.");const u=o.signal;if(u!==void 0&&(typeof u!="object"||u===null||typeof u.aborted!="boolean"))throw new E("signal must be an AbortSignal.");return{accelerator:r.accelerator,wasmPath:r.wasmPath,registryUrl:a,version:c,onDownloadProgress:i,signal:u}},yu=(e,t,n)=>{const r=pt(e===void 0?{}:e,t,n),o=e===void 0?{}:e,i=o.revision;
64if(i!==void 0&&typeof i!="string")throw new E("revision must be a string.");const s=o.file;if(s!==void 0&&typeof s!="string")throw new E("file must be a string.");const a=o.onDownloadProgress;if(a!==void 0&&typeof a!="function")throw new E("onDownloadProgress must be a function.");const c=o.signal;if(c!==void 0&&(typeof c!="object"||c===null||typeof c.aborted!="boolean"))throw new E("signal must be an AbortSignal.");return{accelerator:r.accelerator,wasmPath:r.wasmPath,revision:i,file:s,onDownloadProgress:a,signal:c}},or=(e,t,n,r,o)=>{const i=Promise.resolve().then(()=>e instanceof URL?r(e):e).catch(a=>{throw a instanceof U?a:new F("Failed to load model metadata.",a)});let s;try{s=o.initialize(n,{wasmPath:t,threads:!1,jspi:!1})}catch(a){s=Promise.reject(a)}return Promise.allSettled([s]),{metadata:i,initialization:s}},wu=e=>{if(e!=="auto"&&e!=="wasm"&&e!=="webgpu")throw new E("accelerator must be auto, wasm, or webgpu.")},sr=async e=>{const t=await du(await he.get(e),mu,"Model metadata exceeds the 1 MiB browser limit."),n=new TextDecoder().decode(t);return dt(JSON.parse(n))},ir=async(e,t)=>{const n=async o=>{try{return await t(o)}catch(i){throw i instanceof U||i instanceof ce?i:new oe(i)}},r=async o=>{try{return{value:await n(o),accelerator:o}}catch(i){throw i instanceof ce?new oe(i):i}};if(e==="wasm")return r("wasm");if(e==="webgpu")return r("webgpu");try{return{value:await n("webgpu"),accelerator:"webgpu"}}catch{return{value:await n("wasm"),accelerator:"wasm"}}},ar="https://huggingface.co",_u=3e4,rn=512*1024*1024,bu="main",vu=re({type:Gn(["file","directory"]),oid:$().optional(),size:Re().optional(),path:$(),lfs:re({oid:$(),size:Re(),pointerSize:Re()}).loose().optional(),xetHash:$().optional()}).loose(),Tu=ne(vu),H=e=>encodeURIComponent(e),Eu=e=>{if(typeof e!="string")throw new z("HuggingFace repo must be in the form org/name.");const t=e.split("/");if(t.length!==2||t.some(o=>o==="."||o===".."||!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(o)))throw new z(`Invalid HuggingFace repo ${e}; expected a single org/name pair with safe segments.`);const n=t[0],r=t[1];if(n===void 0||r===void 0)throw new z("HuggingFace repo must be in the form org/name.");return{organization:n,name:r}},Ru=(e=bu)=>{if(typeof e!="string"||e.length===0||e==="."||e===".."||/[\\/?#%\s]/.test(e))throw new z("HuggingFace revision must be a non-empty, single path-safe segment.");return e},Su=(e,t)=>new URL(`${ar}/api/models/${H(e.organization)}/${H(e.name)}/tree/${H(t)}`),on=(e,t,n)=>new URL(`${ar}/${H(e.organization)}/${H(e.name)}/resolve/${H(t)}/${H(n)}`),ku=async(e,t,n,r)=>{let o;try{o=await he.get(Su(t,n),{retry:0,timeout:_u,...r===void 0?{}:{signal:r}})}catch(a){throw Oe(a)?a.response.status===404?new z(`HuggingFace repo ${e} was not found at revision ${n}.`,a):new z(`HuggingFace tree request failed with HTTP ${a.response.status} for repo ${e} at revision ${n}.`,a):a}let i;try{i=await o.json()}catch(a){throw new z("HuggingFace tree response was not valid JSON.",a)}const s=Tu.safeParse(i);if(!s.success)throw new z("HuggingFace tree response did not contain valid file entries.",s.error);return s.data},zu=e=>e.filter(t=>t.type==="file"&&!t.path.includes("/")),Pu=(e,t,n,r)=>{const o=t.filter(s=>s.path.endsWith(n));if(r!==void 0){if(!r.endsWith(n))throw new z(`HuggingFace options.file ${r} must end with ${n}.`);if(!o.some(s=>s.path===r))throw new z(`HuggingFace options.file ${r} was not found in repo ${e}.`);return r}if(o.length===0)throw new z(`HuggingFace repo ${e} has no ${n} file in repo.`);if(o.length>1)throw new z(`HuggingFace repo ${e} contains multiple ${n} files: ${o.map(s=>s.path).join(", ")}. Pass options.file to select one.`);const i=o[0];if(i===void 0)throw new z(`HuggingFace repo ${e} has no ${n} file in repo.`);return i.path},$u=e=>e.toLowerCase().replace(/[^a-z0-9.-]/g,"-"),Au=(e,t,n,r)=>{const o=dt({model_id:$u(e),version:t,execution_template:{type:"LiteRtLm",model_file:n},files:[n],preprocessing:[],postprocessing:[]});return me(o),o},Ou=(e,t)=>t==="litertlm"?me(e).modelFile:rr(e),Iu=(e,t,n)=>{const r=n.lfs?.size??n.size;if(typeof r!="number"||!Number.isSafeInteger(r)||r<=0||r>rn)throw new z(`HuggingFace model ${t} in repo ${e} must be a positive safe integer no greater than ${rn} bytes.`);return r},Uu=async(e,t,n={})=>{const r=Eu(e),o=Ru(n.revision),i=`${r.organization}/${r.name}`,s=zu(await ku(i,r,o,n.signal)),a=".litertlm";if(n.file!==void 0&&!n.file.endsWith(a))throw new z(`HuggingFace options.file ${n.file} must end with ${a}.`);const c=s.find(m=>m.path==="model_metadata.json");let u,l;if(c!==void 0){if(u=await sr(on(r,o,c.path)),l=Ou(u,t),!s.some(m=>m.path===l))throw new z(`HuggingFace metadata model_file ${l} was not found in the repo ${i} tree.`);if(n.file!==void 0&&n.file!==l)throw new z(`HuggingFace options.file ${n.file} conflicts with metadata model_file ${l}.`)}else l=Pu(i,s,a,n.file),u=Au(r.name,o,l);const h=s.find(m=>m.path===l);if(h===void 0)throw new z(`HuggingFace model file ${l} was not found in repo ${i}.`);const p=Iu(i,l,h),d=h.lfs?.oid!==void 0&&/^[0-9a-f]{64}$/.test(h.lfs.oid)?h.lfs.oid:void 0;return{modelUrl:on(r,o,l),metadata:u,sizeBytes:p,sha256:d}},Lu=(e,t)=>e.wasmPath.toString()===t.wasmPath.toString()&&e.threads===t.threads&&e.jspi===t.jspi;var Bu=class{config;promise;initialize(e,t){return this.config!==void 0&&!Lu(this.config,t)?Promise.reject(new E):this.promise!==void 0?this.promise:(this.config=t,this.promise=e.initialize(t).catch(n=>{throw this.config=void 0,this.promise=void 0,new oe(n)}),this.promise)}};const Fe=new Bu,Nu=512*1024*1024,xu="Model exceeds the 512 MiB browser limit.",Mu=6e5,Zu=async(e,t,n)=>{try{return await t(await he.get(e,{timeout:Mu}),Nu,xu,n===void 0?void 0:(r,o)=>n({loadedBytes:r,totalBytes:o}))}catch(r){throw new oe(r)}},Du=(e,t)=>Zu(e,ht,t),Cu=e=>{const t=e.content;if(typeof t=="string")return t;if(!Array.isArray(t))return"";let n="";for(const r of t)typeof r=="object"&&r!==null&&"type"in r&&r.type==="text"&&"text"in r&&typeof r.text=="string"&&(n+=r.text);return n},Fu=async()=>{const e=navigator.gpu;if(e===void 0||typeof e.requestAdapter!="function")throw new ce("WebGPU is unavailable.");let t;try{t=await e.requestAdapter()}catch(n){throw new ce(`WebGPU adapter request failed: ${String(n)}`)}if(t==null)throw new ce("WebGPU reported no compatible adapter.")},ju=async(e,t,n)=>{const r=await e.createConversation(n.maxOutputTokens===void 0?void 0:{sessionConfig:{maxOutputTokens:n.maxOutputTokens}});let o,i=!1,s;const a=async()=>
64{if(i){s!==void 0&&await s;return}i=!0,s=(async()=>{o!==void 0&&await o.cancel().catch(()=>{}),await r.delete().catch(()=>{})})(),await s};try{o=r.sendMessageStreaming(t).getReader()}catch(u){throw await a(),u}const c=o;if(c===void 0)throw await a(),new oe("LiteRT-LM did not return a stream reader.");return{stream:(async function*(){try{for(;;){const{done:u,value:l}=await c.read();if(u)return;const h=Cu(l);h.length>0&&(yield h)}}finally{await a()}})(),cancel:()=>{a()},dispose:a}},je={initialize:async e=>{await Yn(e.wasmPath.toString())},fetchModel:async(e,t)=>Du(e,t).then(n=>new Blob(n)),modelFromChunks:async e=>{const t=e.map(n=>{const r=new Uint8Array(new ArrayBuffer(n.byteLength));return r.set(n),r});return new Blob(t)},createEngine:async(e,t,n)=>{t==="webgpu"&&await Fu();const r=await lt.create({model:e,backend:t==="webgpu"?B.GPU:B.CPU,...n===void 0?{}:{mainExecutorSettings:{maxNumTokens:n}}});return{generate:(o,i)=>ju(r,o,i),delete:()=>r.delete()}}},Gu=["https://registry.xybrid.dev","https://r2.xybrid.dev"],Wu=3e4,sn=512*1024*1024,Vu=re({hf_repo:$(),file:$(),download_url:$(),format:$(),quantization:$(),size_bytes:Re(),sha256:$(),passthrough:Da(),model_metadata:j().optional(),artifacts:ne(j()).optional()}).loose(),qu=re({mask:$(),platform:$(),resolved:Vu}).loose(),Hu=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},Ju=e=>{if(typeof e!="string"||e.length===0||/[/?#%\\]/.test(e)||/\s/.test(e))throw new R("Model id must be a non-empty path-safe string without slashes, URL delimiters, percent signs, or whitespace.");return e},Yu=(e,t,n,r)=>{const o=new URL(e),i=new URL(`${o.toString().replace(/\/+$/,"")}/v1/models/${encodeURIComponent(t)}/resolve`);return i.searchParams.set("platform","web"),i.searchParams.set("format",n),r!==void 0&&i.searchParams.set("version",r),i},Ku=e=>{try{const t=new URL(e);if(t.protocol!=="https:")throw new R("registryUrl must use HTTPS.");return t}catch(t){throw t instanceof R?t:new R("registryUrl must be a valid HTTPS URL.",t)}},Xu=e=>Oe(e)||e instanceof R||Ve(e)?Ve(e):e instanceof DOMException?e.name==="NetworkError":e instanceof TypeError,Qu=(e,t)=>{const n=qu.safeParse(e);if(!n.success)throw new R("Registry response does not contain a valid resolved model.",n.error);const r=n.data.resolved;if(r.format!==t)throw new R(`Registry resolved format ${r.format} instead of the required ${t}.`);if(!Number.isSafeInteger(r.size_bytes)||r.size_bytes<=0||r.size_bytes>sn)throw new R(`Registry resolved size_bytes must be a positive safe integer no greater than ${sn}.`);if(!/^[0-9a-f]{64}$/.test(r.sha256))throw new R("Registry resolved sha256 must be a 64-character lowercase hex string.");if(r.passthrough!==!0)throw new R("Registry resolved model must have passthrough=true.");if(r.artifacts!==void 0&&r.artifacts.length>0)throw new R("Registry resolved model must not include artifacts.");if(!Hu(r.model_metadata))throw new R("Registry resolved model_metadata must be a present plain object.");let o;try{o=new URL(r.download_url)}catch(i){throw new R("Registry resolved download_url must be a valid HTTPS URL.",i)}if(o.protocol!=="https:")throw new R("Registry resolved download_url must use HTTPS.");try{const i=dt(r.model_metadata),s=t==="litertlm"?me(i).modelFile:rr(i);if(r.file!==s)throw new R(`Registry resolved file ${r.file} does not match execution_template.model_file ${s}.`);return{modelUrl:o,metadata:i,sizeBytes:r.size_bytes,sha256:r.sha256}}catch(i){throw i instanceof R?i:new R("Registry model metadata is not browser-compatible.",i)}},el=async(e,t,n,r)=>{let o;try{o=await he.get(e,{retry:0,timeout:Wu,...r===void 0?{}:{signal:r}})}catch(s){throw Oe(s)?s.response.status===404?new R(`No browser-compatible variant exists for model id ${t} in ${n} format.`,s):new R(`Registry resolve failed with HTTP ${s.response.status} for model id ${t}.`,s):s}let i;try{i=await o.json()}catch(s){throw new R("Registry resolve response was not valid JSON.",s)}return Qu(i,n)},tl=async(e,t,n={})=>{const r=Ju(e),o=n.registryUrl===void 0?Gu:[Ku(n.registryUrl)];let i;for(const s of o)try{return await el(Yu(s,r,t,n.version),r,t,n.signal)}catch(a){if(!Xu(a))throw a;i=a}throw new R(`Registry network resolution failed for model id ${r}.`,i)},nl=6e5,rl=async(e,t)=>{try{const n=await he.get(e,{retry:0,timeout:nl,...t.signal===void 0?{}:{signal:t.signal}}),r=t.sha256===void 0?void 0:await(async()=>{const{createSHA256:s}=await lr(async()=>{const{createSHA256:c}=await import("./C-W79GWb.js");return{createSHA256:c}},[],import.meta.url),a=await s();return a.init(),a})();let o=0;const i=await ht(n,Number.MAX_SAFE_INTEGER,"Verified model exceeds the declared size.",s=>{t.onProgress?.({loadedBytes:s,totalBytes:t.sizeBytes})},s=>{if(o+=s.byteLength,o>t.sizeBytes)throw new Ce(`Verified model exceeds the declared size of ${t.sizeBytes} bytes (received ${o}).`);r?.update(s)},t.signal);if(o!==t.sizeBytes)throw new Ce(`Verified model size mismatch: expected ${t.sizeBytes} bytes, received ${o}.`);if(t.sha256!==void 0&&r!==void 0){const s=r.digest("hex");
64if(s!==t.sha256)throw new Ce(`Verified model SHA-256 mismatch: expected ${t.sha256}, received ${s}.`)}return i}catch(n){throw n instanceof U?n:new oe(n)}},Ee=Symbol("XybridLlm construction"),mt="/xybrid/llm-runtime",ol=(e,t)=>{const n=pt(e,t,mt),r=e.onDownloadProgress;if(r!==void 0&&typeof r!="function")throw new E("onDownloadProgress must be a function.");const o={...n};return r===void 0?o:{...o,onDownloadProgress:r}},sl=(e,t)=>gu(e,t,mt),il=(e,t)=>yu(e,t,mt),al=e=>{if(typeof e!="string"||e.length===0)throw new Qe("prompt must be a non-empty string.");return e},cl=e=>{if(e===void 0)return{};if(typeof e!="object"||e===null)throw new Qe("generate options must be an object.");const t=e.maxOutputTokens;if(t===void 0)return{};if(!Number.isSafeInteger(t)||t<=0)throw new Qe("maxOutputTokens must be a positive integer.");return{maxOutputTokens:t}},an=e=>e instanceof U?e:new uu(e);var cr=class{running;activeGeneration;disposePromise;constructor(e,t){this.engine=e,this.accelerator=t}generateStream(e,t){const n=al(e),r=cl(t);if(this.assertRunnable(),this.running!==void 0)throw new en;const o=this;return(async function*(){if(o.assertRunnable(),o.running!==void 0)throw new en;let i=()=>{};o.running=new Promise(s=>{i=s});try{let s;try{s=await o.engine.generate(n,r)}catch(a){throw an(a)}if(o.activeGeneration=s,o.disposePromise!==void 0)throw s.cancel(),await s.dispose(),new tn;try{yield*s.stream}catch(a){throw an(a)}}finally{o.activeGeneration?.cancel(),o.activeGeneration=void 0,o.running=void 0,i()}})()}async generate(e,t){let n="";for await(const r of this.generateStream(e,t))n+=r;return n}async dispose(){return this.disposePromise!==void 0?this.disposePromise:(this.disposePromise=this.finishDisposal(),this.disposePromise)}async finishDisposal(){const e=this.activeGeneration;e?.cancel(),this.running!==void 0&&await Promise.allSettled([this.running]),await e?.dispose(),await this.engine.delete()}assertRunnable(){if(this.disposePromise!==void 0)throw new tn}},fl=class Se{constructor(t,n){if(this.session=t,n!==Ee)throw new E("XybridLlm instances must be created with load().")}static async load(t,n){const r=typeof location>"u"?void 0:location.href;return new Se(await ul(hu(t,r),ol(n,r),je,sr,Fe),Ee)}static async fromRegistry(t,n){const r=sl(n,typeof location>"u"?void 0:location.href);return new Se(await cn(await tl(t,"litertlm",{registryUrl:r.registryUrl,signal:r.signal,version:r.version}),r,je,Fe),Ee)}static async fromHuggingFace(t,n){const r=il(n,typeof location>"u"?void 0:location.href);return new Se(await cn(await Uu(t,"litertlm",{file:r.file,revision:r.revision,signal:r.signal}),r,je,Fe),Ee)}get accelerator(){return this.session.accelerator}generate(t,n){return this.session.generate(t,n)}generateStream(t,n){return this.session.generateStream(t,n)}dispose(){return this.session.dispose()}};const ul=async(e,t,n,r,o)=>{const i=t.wasmPath;if(i===void 0)throw new E("wasmPath must be provided to the internal LLM loader.");const s=or(e,i,n,r,o),a=await s.metadata,{modelFile:c,contextLength:u}=me(a),l=fu(e,c,a.files),h=n.fetchModel(l,t.onDownloadProgress),[,p]=await Promise.all([s.initialization,h]),{value:d,accelerator:m}=await ir(t.accelerator??"auto",I=>n.createEngine(p,I,u));return new cr(d,m)},cn=async(e,t,n,r)=>{const o=or(e.metadata,t.wasmPath,n,async()=>e.metadata,r),i=rl(e.modelUrl,{onProgress:t.onDownloadProgress,sha256:e.sha256,signal:t.signal,sizeBytes:e.sizeBytes}),[,s]=await Promise.all([o.initialization,i]),a=await n.modelFromChunks(s),{value:c,accelerator:u}=await ir(t.accelerator,l=>n.createEngine(a,l,me(e.metadata).contextLength));return new cr(c,u)};export{en as ConcurrentRunError,tn as DisposedError,z as HuggingFaceError,uu as InferenceError,Qe as InputValidationError,Ce as IntegrityError,F as InvalidMetadataError,R as RegistryError,E as RuntimeConfigurationError,oe as RuntimeInitializationError,Te as UnsupportedFeatureError,tr as UnsupportedTemplateError,U as XybridError,fl as XybridLlm};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.