PageSourceSearch

https://reforeai.cn/_nuxt/6vagJksp.js

js reforeai.cn collected 2026-09-24 13:30:18 UTC 384,503 bytes, 230 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./D6B7PRGu.js","./DWQRx4os.js","./entry.CkBvUIfC.css","./B-pQ2ZuD.js","./DSx64CIE.js","./C0afyVFu.js","./4eCrLmse.js","./ydN-EymE.js","./CjN2hqkz.js","./C9H-ASir.js","./CwFC1dsF.js","./BsXi9iKz.js","./IHOOn322.js","./DtNbtGvo.js","./C7aAIYbN.js"])))=>i.map(i=>d[i]);
2import{d5 as kp,d6 as Ii,d7 as Sp,d8 as Ip,d9 as Tp,g as Ne,bQ as ie,L as D,a6 as bo,y as Qn,da as wo,db as Ep,dc as Ap,K as ur,J as z,dd as Ar,an as Ze,de as Lt,ao as we,aM as Gl,df as ge,dg as Xe,dh as Va,di as Zl,dj as Cp,dk as Rp,dl as Ve,bj as Pp,dm as gn,dn as dt,dp as Wl,dq as Qe,p as At,a4 as nn,a5 as wn,bp as Qr,dr as _n,bC as Hl,bm as Op,aE as _o,b1 as Xs,aD as Sn,b2 as Jl,ds as Mp,dt as Np,be as Ql,P as ns,du as jp,dv as $p,dw as Dp,dx as Ti,dy as Fp,dz as qp,dA as vt,x as Wr,dB as Lp,ar as Ei,dC as Bp,bo as vn,dD as Up,dE as Vp,dF as Kp,dG as zp,bx as Gp,ca as Zn,dH as Zp,ai as Ai,bw as Wp,by as Hp,b5 as Jp,N as Qp,dI as Yp,bk as Xp,dJ as ef,dK as Yl,s as tf,S as eo,dL as Xl,dM as rf,E as nf,ac as eu}from"./DWQRx4os.js";import{u as Zt}from"./DSx64CIE.js";import{a as af}from"./C0afyVFu.js";import{a as Ci,u as sf}from"./4eCrLmse.js";import{m as xo,b as of,h as tu,g as lf,s as uf,c as Rr}from"./ydN-EymE.js";import{u as ru}from"./C9H-ASir.js";import{u as la}from"./CwFC1dsF.js";import{u as cf}from"./BsXi9iKz.js";var df=class extends kp{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){super.setOptions({...e,behavior:Ii()})}getOptimisticResult(e){return e.behavior=Ii(),super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){const{state:r}=e,n=super.createResult(e,t),{isFetching:s,isRefetching:o,isError:l,isRefetchError:u}=n,d=r.fetchMeta?.fetchMore?.direction,f=l&&d==="forward",m=s&&d==="forward",b=l&&d==="backward",v=s&&d==="backward";return{...n,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Ip(t,r.data),hasPreviousPage:Sp(t,r.data),isFetchNextPageError:f,isFetchingNextPage:m,isFetchPreviousPageError:b,isFetchingPreviousPage:v,isRefetchError:u&&!f&&!b,isRefetching:o&&!m&&!v}}};function pf(e,t){return Tp(df,e)}var nu=(e=>(e.Project="Project",e.Snapshot="Snapshot",e))(nu||{}),St=(e=>(e.Draft="Draft",e.Pending="Pending",e.Ready="Ready",e.Error="Error",e))(St||{});const au="​";class G0{constructor(t=new Set){this.existing=t}create(t){const r=t.trim().slice(0,20);let n=r,s=1;for(;this.existing.has(n);)s++,n=`${r}(${s})`;return this.existing.add(n),n}}function ko(e){return["cloud","virtual-file-content",wo(e,["id","shareKey","hash"])]}function ff(e){return["cloud","virtual-file-content",()=>{const t=ie(e);return t?wo(t,["id","shareKey","hash"]):void 0}]}const Z0="highlight-file-selector";function hf(e,t){return bo(()=>{Qn(t,r=>{const n=e.value;!r?.length||r.find(s=>s.filename===n)||(e.value=r[0].filename)},{immediate:!0})}),Ne(()=>{const r=e.value;return t.value?.find(n=>n.filename===r)})}function Yn(e){return e?e.map((r,n)=>({...r,order:typeof r.order=="number"?r.order:n})).sort((r,n)=>r.order!==n.order?(r.order??0)-(n.order??0):r.createdAt&&n.createdAt&&r.createdAt!==n.createdAt?r.createdAt.localeCompare(n.createdAt):r.filename.localeCompare(n.filename)):e??void 0}function mf(){const{t:e}=la();return function(r,n){return r.displayName||r.filename||e("project.page",{index:n+1})}}function W0(e,t){const r=mf();return Ne(()=>{const n=ie(t);if(!n)return null;const s=ie(e),o=n.findIndex(u=>u.filename===s);if(o===-1)return null;const l=n[o];return r(l,o)})}function H0(){const{t:e}=la();return D({error:""}).min(1,e("chat.rename-file.error.empty"))}function su(e,t){const r=[],n=new Map(t.map(o=>[o.version,o]));let s=n.get(e);for(;s&&(r.push(s),!!s.parent);)s=n.get(s.parent);return r}var ou="vercel.ai.error",gf=Symbol.for(ou),iu,vf=class lu extends Error{constructor({name:t,message:r,cause:n}){super(r),this[iu]=!0,this.name=t,this.cause=n}static isInstance(t){return lu.hasMarker(t,ou)}static hasMarker(t,r){const n=Symbol.for(r);return t!=null&&typeof t=="object"&&n in t&&typeof t[n]=="boolean"&&t[n]===!0}};iu=gf;var be=vf,uu="AI_APICallError",cu=`vercel.ai.error.${uu}`,yf=Symbol.for(cu),du,ft=class extends be{constructor({message:e,url:t,requestBodyValues:r,statusCode:n,responseHeaders:s,responseBody:o,cause:l,isRetryable:u=n!=null&&(n===408||n===409||n===429||n>=500),data:d}){super({name:uu,message:e,cause:l}),this[du]=!0,this.url=t,this.requestBodyValues=r,this.statusCode=n,this.responseHeaders=s,this.responseBody=o,this.isRetryable=u,this.data=d}static isInstance(e){return be.hasMarker(e,cu)}};du=yf;var pu="AI_EmptyResponseBodyError",fu=`vercel.ai.error.${pu}`,bf=Symbol.for(fu),hu,wf=class extends be{constructor({message:e="Empty response body"}={}){super({name:pu,message:e}),this[hu]=!0}static isInstance(e){return be.hasMarker(e,fu)}};hu=bf;function In(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var mu="AI_InvalidArgumentError",gu=`vercel.ai.error.${mu}`,_f=Symbol.for(gu),vu,yu=class extends be{constructor({message:t,cause:r,argument:n}){super({name:mu,message:t,cause:r}),this[vu]=!0,this.argument=n}static isInstance(t){return be.hasMarker(t,gu)}};vu=_f;var bu="AI_InvalidPromptError",wu=`vercel.ai.error.${bu}`,xf=Symbol.for(wu),_u,Gr=class extends be{constructor({prompt:e,message:t,cause:r}){super({name:bu,message:`Invalid prompt: ${t}`,cause:r}),this[_u]=!0,this.prompt=e}static isInstance(e){return be.hasMarker(e,wu)}};_u=xf;var xu="AI_InvalidResponseDataError",ku=`vercel.ai.error.${xu}`,kf=Symbol.for(ku),Su,Ri=class extends be{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:xu,message:t}),this[Su]=!0,this.data=e}static isInstance(e){return be.hasMarker(e,ku)}};Su=kf;var Iu="AI_JSONParseError",Tu=`vercel.ai.error.${Iu}`,Sf=Symbol.for(Tu),Eu,Ka=class extends be{constructor({text:e,cause:t}){super({name:Iu,message:`JSON parsing failed: Text: ${e}.
3Error message: ${In(t)}`,cause:t}),this[Eu]=!0,this.text=e}static isInstance(e){return be.hasMarker(e,Tu)}};Eu=Sf;var Au="AI_LoadAPIKeyError",Cu=`vercel.ai.error.${Au}`,If=Symbol.for(Cu),Ru,Oa=class extends be{constructor({message:e}){super({name:Au,message:e}),this[Ru]=!0}static isInstance(e){return be.hasMarker(e,Cu)}};Ru=If;
3var Pu="AI_NoSuchModelError",Ou=`vercel.ai.error.${Pu}`,Tf=Symbol.for(Ou),Mu,Ef=class extends be{constructor({errorName:e=Pu,modelId:t,modelType:r,message:n=`No such ${r}: ${t}`}){super({name:e,message:n}),this[Mu]=!0,this.modelId=t,this.modelType=r}static isInstance(e){return be.hasMarker(e,Ou)}};Mu=Tf;var Nu="AI_TooManyEmbeddingValuesForCallError",ju=`vercel.ai.error.${Nu}`,Af=Symbol.for(ju),$u,Cf=class extends be{constructor(e){super({name:Nu,message:`Too many values for a single embedding call. The ${e.provider} model "${e.modelId}" can only embed up to ${e.maxEmbeddingsPerCall} values per call, but ${e.values.length} values were provided.`}),this[$u]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return be.hasMarker(e,ju)}};$u=Af;var Du="AI_TypeValidationError",Fu=`vercel.ai.error.${Du}`,Rf=Symbol.for(Fu),qu,Pf=class to extends be{constructor({value:t,cause:r}){super({name:Du,message:`Type validation failed: Value: ${JSON.stringify(t)}.
4Error message: ${In(r)}`,cause:r}),this[qu]=!0,this.value=t}static isInstance(t){return be.hasMarker(t,Fu)}static wrap({value:t,cause:r}){return to.isInstance(r)&&r.value===t?r:new to({value:t,cause:r})}};qu=Rf;var Xn=Pf,Lu="AI_UnsupportedFunctionalityError",Bu=`vercel.ai.error.${Lu}`,Of=Symbol.for(Bu),Uu,za=class extends be{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:Lu,message:t}),this[Uu]=!0,this.functionality=e}static isInstance(e){return be.hasMarker(e,Bu)}};Uu=Of;class Pi extends Error{constructor(t,r){super(t),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}function qs(e){}function Mf(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=qs,onError:r=qs,onRetry:n=qs,onComment:s}=e;let o="",l=!0,u,d="",f="";function m(S){const M=l?S.replace(/^\xEF\xBB\xBF/,""):S,[R,B]=Nf(`${o}${M}`);for(const V of R)b(V);o=B,l=!1}function b(S){if(S===""){y();return}if(S.startsWith(":")){s&&s(S.slice(S.startsWith(": ")?2:1));return}const M=S.indexOf(":");if(M!==-1){const R=S.slice(0,M),B=S[M+1]===" "?2:1,V=S.slice(M+B);v(R,V,S);return}v(S,"",S)}function v(S,M,R){switch(S){case"event":f=M;break;case"data":d=`${d}${M}
5`;break;case"id":u=M.includes("\0")?void 0:M;break;case"retry":/^\d+$/.test(M)?n(parseInt(M,10)):r(new Pi(`Invalid \`retry\` value: "${M}"`,{type:"invalid-retry",value:M,line:R}));break;default:r(new Pi(`Unknown field "${S.length>20?`${S.slice(0,20)}…`:S}"`,{type:"unknown-field",field:S,value:M,line:R}));break}}function y(){d.length>0&&t({id:u,event:f||void 0,data:d.endsWith(`
6`)?d.slice(0,-1):d}),u=void 0,d="",f=""}function x(S={}){o&&S.consume&&b(o),l=!0,u=void 0,d="",f="",o=""}return{feed:m,reset:x}}function Nf(e){const t=[];let r="",n=0;for(;n<e.length;){const s=e.indexOf("\r",n),o=e.indexOf(`
7`,n);let l=-1;if(s!==-1&&o!==-1?l=Math.min(s,o):s!==-1?s===e.length-1?l=-1:l=s:o!==-1&&(l=o),l===-1){r=e.slice(n);break}else{const u=e.slice(n,l);t.push(u),n=l+1,e[n-1]==="\r"&&e[n]===`
8`&&n++}}return[t,r]}class jf extends TransformStream{constructor({onError:t,onRetry:r,onComment:n}={}){let s;super({start(o){s=Mf({onEvent:l=>{o.enqueue(l)},onError(l){t==="terminate"?o.error(l):typeof t=="function"&&t(l)},onRetry:r,onComment:n})},transform(o){s.feed(o)}})}}var Se;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(Se||(Se={}));var Vu={};function pr(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}async function $f(e,t){if(e==null)return Promise.resolve();const r=t?.abortSignal;return new Promise((n,s)=>{if(r?.aborted){s(Oi());return}const o=setTimeout(()=>{l(),n()},e),l=()=>{clearTimeout(o),r?.removeEventListener("abort",u)},u=()=>{l(),s(Oi())};r?.addEventListener("abort",u)})}function Oi(){return new DOMException("Delay was aborted","AbortError")}function Tn(e){return Object.fromEntries([...e.headers])}var ua=({prefix:e,size:t=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const s=()=>{const o=r.length,l=new Array(t);for(let u=0;u<t;u++)l[u]=r[Math.random()*o|0];return l.join("")};if(e==null)return s;if(r.includes(n))throw new yu({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${s()}`},yn=ua();function Ku(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function Yr(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var Df=["fetch failed","failed to fetch"];function zu({error:e,url:t,requestBodyValues:r}){if(Yr(e))return e;if(e instanceof TypeError&&Df.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new ft({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return e}function ea(e=globalThis){var t,r,n;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(n=(r=e.process)==null?void 0:r.versions)!=null&&n.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function Ff(e){return Object.fromEntries(Object.entries(e).filter(([t,r])=>r!=null))}function Xr(e,...t){const r=Ff(e??{}),n=new Headers(r),s=n.get("user-agent")||"";
8return n.set("user-agent",[s,...t].filter(Boolean).join(" ")),Object.fromEntries(n)}var Gu="3.0.12",qf=()=>globalThis.fetch,Mi=async({url:e,headers:t={},successfulResponseHandler:r,failedResponseHandler:n,abortSignal:s,fetch:o=qf()})=>{try{const l=await o(e,{method:"GET",headers:Xr(t,`ai-sdk/provider-utils/${Gu}`,ea()),signal:s}),u=Tn(l);if(!l.ok){let d;try{d=await n({response:l,url:e,requestBodyValues:{}})}catch(f){throw Yr(f)||ft.isInstance(f)?f:new ft({message:"Failed to process error response",cause:f,statusCode:l.status,url:e,responseHeaders:u,requestBodyValues:{}})}throw d.value}try{return await r({response:l,url:e,requestBodyValues:{}})}catch(d){throw d instanceof Error&&(Yr(d)||ft.isInstance(d))?d:new ft({message:"Failed to process successful response",cause:d,statusCode:l.status,url:e,responseHeaders:u,requestBodyValues:{}})}}catch(l){throw zu({error:l,url:e,requestBodyValues:{}})}};function Lf({mediaType:e,url:t,supportedUrls:r}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(r).map(([n,s])=>{const o=n.toLowerCase();return o==="*"||o==="*/*"?{mediaTypePrefix:"",regexes:s}:{mediaTypePrefix:o.replace(/\*/,""),regexes:s}}).filter(({mediaTypePrefix:n})=>e.startsWith(n)).flatMap(({regexes:n})=>n).some(n=>n.test(t))}function Q0({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new Oa({message:`${n} API key must be a string.`});if(typeof process>"u")throw new Oa({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(e=Vu[t],e==null)throw new Oa({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new Oa({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function qa({settingValue:e,environmentVariableName:t}){if(typeof e=="string")return e;if(!(e!=null||typeof process>"u")&&(e=Vu[t],!(e==null||typeof e!="string")))return e}function Y0(e){var t;const[r,n=""]=e.toLowerCase().split("/");return(t={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[n])!=null?t:n}var Bf=/"__proto__"\s*:/,Uf=/"constructor"\s*:/;function Vf(e){const t=JSON.parse(e);return t===null||typeof t!="object"||Bf.test(e)===!1&&Uf.test(e)===!1?t:Kf(t)}function Kf(e){let t=[e];for(;t.length;){const r=t;t=[];for(const n of r){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const s in n){const o=n[s];o&&typeof o=="object"&&t.push(o)}}}return e}function So(e){const{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return Vf(e)}finally{Error.stackTraceLimit=t}}var Ga=Symbol.for("vercel.ai.validator");function zf(e){return{[Ga]:!0,validate:e}}function Gf(e){return typeof e=="object"&&e!==null&&Ga in e&&e[Ga]===!0&&"validate"in e}function an(e){let t;return()=>(t==null&&(t=e()),t)}function Zf(e){return Gf(e)?e:typeof e=="function"?e():Wf(e)}function Wf(e){return zf(async t=>{const r=await e["~standard"].validate(t);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new Xn({value:t,cause:r.issues})}})}async function ro({value:e,schema:t}){const r=await fr({value:e,schema:t});if(!r.success)throw Xn.wrap({value:e,cause:r.error});return r.value}async function fr({value:e,schema:t}){const r=Zf(t);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};const n=await r.validate(e);return n.success?{success:!0,value:n.value,rawValue:e}:{success:!1,error:Xn.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:Xn.wrap({value:e,cause:n}),rawValue:e}}}async function Hf({text:e,schema:t}){try{const r=So(e);return t==null?r:ro({value:r,schema:t})}catch(r){throw Ka.isInstance(r)||Xn.isInstance(r)?r:new Ka({text:e,cause:r})}}async function en({text:e,schema:t}){try{const r=So(e);return t==null?{success:!0,value:r,rawValue:r}:await fr({value:r,schema:t})}catch(r){return{success:!1,error:Ka.isInstance(r)?r:new Ka({text:e,cause:r}),rawValue:void 0}}}function Ni(e){try{return So(e),!0}catch{return!1}}
8function Zu({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new jf).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await en({text:r,schema:t}))}}))}async function ta({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await fr({value:t[e],schema:r});if(!n.success)throw new yu({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var Jf=()=>globalThis.fetch,hr=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:l})=>Wu({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:l}),X0=async({url:e,headers:t,formData:r,failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:l})=>Wu({url:e,headers:t,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:l}),Wu=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:s,abortSignal:o,fetch:l=Jf()})=>{try{const u=await l(e,{method:"POST",headers:Xr(t,`ai-sdk/provider-utils/${Gu}`,ea()),body:r.content,signal:o}),d=Tn(u);if(!u.ok){let f;try{f=await s({response:u,url:e,requestBodyValues:r.values})}catch(m){throw Yr(m)||ft.isInstance(m)?m:new ft({message:"Failed to process error response",cause:m,statusCode:u.status,url:e,responseHeaders:d,requestBodyValues:r.values})}throw f.value}try{return await n({response:u,url:e,requestBodyValues:r.values})}catch(f){throw f instanceof Error&&(Yr(f)||ft.isInstance(f))?f:new ft({message:"Failed to process successful response",cause:f,statusCode:u.status,url:e,responseHeaders:d,requestBodyValues:r.values})}}catch(u){throw zu({error:u,url:e,requestBodyValues:r.values})}};function e_(e){return e}function t_({id:e,name:t,inputSchema:r}){return({execute:n,outputSchema:s,toModelOutput:o,onInputStart:l,onInputDelta:u,onInputAvailable:d,...f})=>({type:"provider-defined",id:e,name:t,args:f,inputSchema:r,outputSchema:s,execute:n,toModelOutput:o,onInputStart:l,onInputDelta:u,onInputAvailable:d})}function r_({id:e,name:t,inputSchema:r,outputSchema:n}){return({execute:s,toModelOutput:o,onInputStart:l,onInputDelta:u,onInputAvailable:d,...f})=>({type:"provider-defined",id:e,name:t,args:f,inputSchema:r,outputSchema:n,execute:s,toModelOutput:o,onInputStart:l,onInputDelta:u,onInputAvailable:d})}async function Et(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}var mr=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:s,requestBodyValues:o})=>{const l=await n.text(),u=Tn(n);if(l.trim()==="")return{responseHeaders:u,value:new ft({message:n.statusText,url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:u,responseBody:l,isRetryable:r?.(n)})};try{const d=await Hf({text:l,schema:e});return{responseHeaders:u,value:new ft({message:t(d),url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:u,responseBody:l,data:d,isRetryable:r?.(n,d)})}}catch{return{responseHeaders:u,value:new ft({message:n.statusText,url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:u,responseBody:l,isRetryable:r?.(n)})}}},Io=e=>async({response:t})=>{const r=Tn(t);if(t.body==null)throw new wf({});return{responseHeaders:r,value:Zu({stream:t.body,schema:e})}},Cr=e=>async({response:t,url:r,requestBodyValues:n})=>{const s=await t.text(),o=await en({text:s,schema:e}),l=Tn(t);if(!o.success)throw new ft({message:"Invalid JSON response",cause:o.error,statusCode:t.status,responseHeaders:l,responseBody:s,url:r,requestBodyValues:n});return{responseHeaders:l,value:o.value,rawValue:o.rawValue}},n_=()=>async({response:e,url:t,requestBodyValues:r})=>{const n=Tn(e);if(!e.body)throw new ft({message:"Response body is empty",url:t,requestBodyValues:r,statusCode:e.status,responseHeaders:n,responseBody:void 0});try{const s=await e.arrayBuffer();return{responseHeaders:n,value:new Uint8Array(s)}}catch(s){throw new ft({message:"Failed to read response as array buffer",url:t,requestBodyValues:r,statusCode:e.status,responseHeaders:n,responseBody:void 0,cause:s})}},Qf=(e,t)=>
8{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")},Yf=Symbol("Let zodToJsonSchema decide on which parser to use"),ji={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},Xf=e=>typeof e=="string"?{...ji,name:e}:{...ji,...e};function Mt(){return{}}function eh(e,t){var r,n,s;const o={type:"array"};return(r=e.type)!=null&&r._def&&((s=(n=e.type)==null?void 0:n._def)==null?void 0:s.typeName)!==Se.ZodAny&&(o.items=Ke(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(o.minItems=e.minLength.value),e.maxLength&&(o.maxItems=e.maxLength.value),e.exactLength&&(o.minItems=e.exactLength.value,o.maxItems=e.exactLength.value),o}function th(e){const t={type:"integer",format:"int64"};if(!e.checks)return t;for(const r of e.checks)switch(r.kind){case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value;break}return t}function rh(){return{type:"boolean"}}function Hu(e,t){return Ke(e.type._def,t)}var nh=(e,t)=>Ke(e.innerType._def,t);function Ju(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>Ju(e,t,s))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return ah(e)}}var ah=e=>{const t={type:"integer",format:"unix-time"};for(const r of e.checks)switch(r.kind){case"min":t.minimum=r.value;break;case"max":t.maximum=r.value;break}return t};function sh(e,t){return{...Ke(e.innerType._def,t),default:e.defaultValue()}}function oh(e,t){return t.effectStrategy==="input"?Ke(e.schema._def,t):Mt()}function ih(e){return{type:"string",enum:Array.from(e.values)}}var lh=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function uh(e,t){const r=[Ke(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Ke(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(s=>!!s),n=[];return r.forEach(s=>{if(lh(s))n.push(...s.allOf);else{let o=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:l,...u}=s;o=u}n.push(o)}}),n.length?{allOf:n}:void 0}function ch(e){const t=typeof e.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(e.value)?"array":"object"}:{type:t==="bigint"?"integer":t,const:e.value}}var Ls=void 0,Vt={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Ls===void 0&&(Ls=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ls),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Qu(e,t){const r={type:"string"};if(e.checks)for(const n of e.checks)switch(n.kind){case"min":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value;break;case"max":r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"email":switch(t.emailStrategy){case"format:email":Kt(r,"email",n.message,t);break;case"format:idn-email":Kt(r,"idn-email",n.message,t);break;case"pattern:zod":xt(r,Vt.email,n.message,t);break}break;case"url":Kt(r,"uri",n.message,t);break;case"uuid":Kt(r,"uuid",n.message,t);break;case"regex":xt(r,n.regex,n.message,t);break;case"cuid":xt(r,Vt.cuid,n.message,t);break;case"cuid2":xt(r,Vt.cuid2,n.message,t);break;case"startsWith":xt(r,RegExp(`^${Bs(n.value,t)}`),n.message,t);break;case"endsWith":xt(r,RegExp(`${Bs(n.value,t)}$`),n.message,t);break;case"datetime":Kt(r,"date-time",n.message,t);break;case"date":Kt(r,"date",n.message,t);break;case"time":Kt(r,"time",n.message,t);break;case"duration":Kt(r,"duration",n.message,t);break;case"length":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"includes":{xt(r,RegExp(Bs(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&Kt(r,"ipv4",n.message,t),n.version!=="v4"&&Kt(r,"ipv6",n.message,t);break}case"base64url":xt(r,Vt.base64url,n.message,t);break;case"jwt":xt(r,Vt.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&xt(r,Vt.ipv4Cidr,n.message,t),n.version!=="v4"&&xt(r,Vt.ipv6Cidr,n.message,t);break}
8case"emoji":xt(r,Vt.emoji(),n.message,t);break;case"ulid":{xt(r,Vt.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Kt(r,"binary",n.message,t);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{xt(r,Vt.base64,n.message,t);break}}break}case"nanoid":xt(r,Vt.nanoid,n.message,t)}return r}function Bs(e,t){return t.patternStrategy==="escape"?ph(e):e}var dh=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function ph(e){let t="";for(let r=0;r<e.length;r++)dh.has(e[r])||(t+="\\"),t+=e[r];return t}function Kt(e,t,r,n){var s;e.format||(s=e.anyOf)!=null&&s.some(o=>o.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):e.format=t}function xt(e,t,r,n){var s;e.pattern||(s=e.allOf)!=null&&s.some(o=>o.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:$i(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):e.pattern=$i(t,n)}function $i(e,t){var r;if(!t.applyRegexFlags||!e.flags)return e.source;const n={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},s=n.i?e.source.toLowerCase():e.source;let o="",l=!1,u=!1,d=!1;for(let f=0;f<s.length;f++){if(l){o+=s[f],l=!1;continue}if(n.i){if(u){if(s[f].match(/[a-z]/)){d?(o+=s[f],o+=`${s[f-2]}-${s[f]}`.toUpperCase(),d=!1):s[f+1]==="-"&&((r=s[f+2])!=null&&r.match(/[a-z]/))?(o+=s[f],d=!0):o+=`${s[f]}${s[f].toUpperCase()}`;continue}}else if(s[f].match(/[a-z]/)){o+=`[${s[f]}${s[f].toUpperCase()}]`;continue}}if(n.m){if(s[f]==="^"){o+=`(^|(?<=[\r
9]))`;continue}else if(s[f]==="$"){o+=`($|(?=[\r
10]))`;continue}}if(n.s&&s[f]==="."){o+=u?`${s[f]}\r
11`:`[${s[f]}\r
12]`;continue}o+=s[f],s[f]==="\\"?l=!0:u&&s[f]==="]"?u=!1:!u&&s[f]==="["&&(u=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return o}function Yu(e,t){var r,n,s,o,l,u;const d={type:"object",additionalProperties:(r=Ke(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?r:t.allowedAdditionalProperties};if(((n=e.keyType)==null?void 0:n._def.typeName)===Se.ZodString&&((s=e.keyType._def.checks)!=null&&s.length)){const{type:f,...m}=Qu(e.keyType._def,t);return{...d,propertyNames:m}}else{if(((o=e.keyType)==null?void 0:o._def.typeName)===Se.ZodEnum)return{...d,propertyNames:{enum:e.keyType._def.values}};if(((l=e.keyType)==null?void 0:l._def.typeName)===Se.ZodBranded&&e.keyType._def.type._def.typeName===Se.ZodString&&((u=e.keyType._def.type._def.checks)!=null&&u.length)){const{type:f,...m}=Hu(e.keyType._def,t);return{...d,propertyNames:m}}}return d}function fh(e,t){if(t.mapStrategy==="record")return Yu(e,t);const r=Ke(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Mt(),n=Ke(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Mt();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function hh(e){const t=e.values,n=Object.keys(e.values).filter(o=>typeof t[t[o]]!="number").map(o=>t[o]),s=Array.from(new Set(n.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}function mh(){return{not:Mt()}}function gh(){return{type:"null"}}var no={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function vh(e,t){const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in no&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((s,o)=>{const l=no[o._def.typeName];return l&&!s.includes(l)?[...s,l]:s},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((s,o)=>{const l=typeof o._def.value;switch(l){case"string":case"number":case"boolean":return[...s,l];case"bigint":return[...s,"integer"];case"object":if(o._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(n.length===r.length){const s=n.filter((o,l,u)=>u.indexOf(o)===l);return{type:s.length>1?s:s[0],enum:r.reduce((o,l)=>o.includes(l._def.value)?o:[...o,l._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(o=>!n.includes(o))],[])};return yh(e,t)}var yh=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,s)=>Ke(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function bh(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[no[e.innerType._def.typeName],"null"]};const r=Ke(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function wh(e){const t={type:"number"};if(!e.checks)return t;for(const r of e.checks)switch(r.kind){case"int":t.type="integer";break;case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value;break}return t}function _h(e,t){const r={type:"object",properties:{}},n=[],s=e.shape();for(const l in s){let u=s[l];if(u===void 0||u._def===void 0)continue;const d=kh(u),f=Ke(u._def,{...t,currentPath:[...t.currentPath,"properties",l],propertyPath:[...t.currentPath,"properties",l]});f!==void 0&&(r.properties[l]=f,d||n.push(l))}n.length&&(r.required=n);const o=xh(e,t);return o!==void 0&&(r.additionalProperties=o),r}function xh(e,t){if(e.catchall._def.typeName!=="ZodNever")return Ke(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;
12case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function kh(e){try{return e.isOptional()}catch{return!0}}var Sh=(e,t)=>{var r;if(t.currentPath.toString()===((r=t.propertyPath)==null?void 0:r.toString()))return Ke(e.innerType._def,t);const n=Ke(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:Mt()},n]}:Mt()},Ih=(e,t)=>{if(t.pipeStrategy==="input")return Ke(e.in._def,t);if(t.pipeStrategy==="output")return Ke(e.out._def,t);const r=Ke(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=Ke(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}};function Th(e,t){return Ke(e.type._def,t)}function Eh(e,t){const n={type:"array",uniqueItems:!0,items:Ke(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(n.minItems=e.minSize.value),e.maxSize&&(n.maxItems=e.maxSize.value),n}function Ah(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>Ke(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Ke(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>Ke(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Ch(){return{not:Mt()}}function Rh(){return Mt()}var Ph=(e,t)=>Ke(e.innerType._def,t),Oh=(e,t,r)=>{switch(t){case Se.ZodString:return Qu(e,r);case Se.ZodNumber:return wh(e);case Se.ZodObject:return _h(e,r);case Se.ZodBigInt:return th(e);case Se.ZodBoolean:return rh();case Se.ZodDate:return Ju(e,r);case Se.ZodUndefined:return Ch();case Se.ZodNull:return gh();case Se.ZodArray:return eh(e,r);case Se.ZodUnion:case Se.ZodDiscriminatedUnion:return vh(e,r);case Se.ZodIntersection:return uh(e,r);case Se.ZodTuple:return Ah(e,r);case Se.ZodRecord:return Yu(e,r);case Se.ZodLiteral:return ch(e);case Se.ZodEnum:return ih(e);case Se.ZodNativeEnum:return hh(e);case Se.ZodNullable:return bh(e,r);case Se.ZodOptional:return Sh(e,r);case Se.ZodMap:return fh(e,r);case Se.ZodSet:return Eh(e,r);case Se.ZodLazy:return()=>e.getter()._def;case Se.ZodPromise:return Th(e,r);case Se.ZodNaN:case Se.ZodNever:return mh();case Se.ZodEffects:return oh(e,r);case Se.ZodAny:return Mt();case Se.ZodUnknown:return Rh();case Se.ZodDefault:return sh(e,r);case Se.ZodBranded:return Hu(e,r);case Se.ZodReadonly:return Ph(e,r);case Se.ZodCatch:return nh(e,r);case Se.ZodPipeline:return Ih(e,r);case Se.ZodFunction:case Se.ZodVoid:case Se.ZodSymbol:return;default:return(n=>{})()}};function Ke(e,t,r=!1){var n;const s=t.seen.get(e);if(t.override){const d=(n=t.override)==null?void 0:n.call(t,e,t,s,r);if(d!==Yf)return d}if(s&&!r){const d=Mh(s,t);if(d!==void 0)return d}const o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);const l=Oh(e,e.typeName,t),u=typeof l=="function"?Ke(l(),t):l;if(u&&Nh(e,t,u),t.postProcess){const d=t.postProcess(u,e,t);return o.jsonSchema=u,d}return o.jsonSchema=u,u}var Mh=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Qf(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Mt()):t.$refStrategy==="seen"?Mt():void 0}},Nh=(e,t,r)=>(e.description&&(r.description=e.description),r),jh=e=>{const t=Xf(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,s])=>[s._def,{def:s._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}},$h=(e,t)=>{var r;const n=jh(t);let s=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((f,[m,b])=>{var v;return{...f,[m]:(v=Ke(b._def,{...n,currentPath:[...n.basePath,n.definitionPath,m]},!0))!=null?v:Mt()}},{}):void 0;const o=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,l=(r=Ke(e._def,o===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,o]}
12,!1))!=null?r:Mt(),u=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;u!==void 0&&(l.title=u);const d=o===void 0?s?{...l,[n.definitionPath]:s}:l:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,o].join("/"),[n.definitionPath]:{...s,[o]:l}};return d.$schema="http://json-schema.org/draft-07/schema#",d},Dh=$h;function Fh(e,t){var r;const n=(r=void 0)!=null?r:!1;return To(()=>Dh(e,{$refStrategy:n?"root":"none"}),{validate:async s=>{const o=await e.safeParseAsync(s);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function qh(e,t){var r;const n=(r=void 0)!=null?r:!1;return To(()=>Ap(e,{target:"draft-7",io:"output",reused:n?"ref":"inline"}),{validate:async s=>{const o=await Ep(e,s);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function Lh(e){return"_zod"in e}function Pr(e,t){return Lh(e)?qh(e):Fh(e)}var ao=Symbol.for("vercel.ai.schema");function a_(e){let t;return()=>(t==null&&(t=e()),t)}function To(e,{validate:t}={}){return{[ao]:!0,_type:void 0,[Ga]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function Bh(e){return typeof e=="object"&&e!==null&&ao in e&&e[ao]===!0&&"jsonSchema"in e&&"validate"in e}function kn(e){return e==null?To({properties:{},additionalProperties:!1}):Bh(e)?e:typeof e=="function"?e():Pr(e)}var{btoa:Uh,atob:Vh}=globalThis;function Eo(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=Vh(t);return Uint8Array.from(r,n=>n.codePointAt(0))}function Za(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return Uh(t)}function Kh(e){return e instanceof Uint8Array?Za(e):e}function Xu(e){return e?.replace(/\/$/,"")}function zh(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*Gh({execute:e,input:t,options:r}){const n=e(t,r);if(zh(n)){let s;for await(const o of n)s=o,yield{type:"preliminary",output:o};yield{type:"final",output:s}}else yield{type:"final",output:await n}}var Us,Di;function Zh(){if(Di)return Us;Di=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,s=(m,b)=>{for(var v in b)e(m,v,{get:b[v],enumerable:!0})},o=(m,b,v,y)=>{if(b&&typeof b=="object"||typeof b=="function")for(let x of r(b))!n.call(m,x)&&x!==v&&e(m,x,{get:()=>b[x],enumerable:!(y=t(b,x))||y.enumerable});return m},l=m=>o(e({},"__esModule",{value:!0}),m),u={};s(u,{SYMBOL_FOR_REQ_CONTEXT:()=>d,getContext:()=>f}),Us=l(u);const d=Symbol.for("@vercel/request-context");function f(){return globalThis[d]?.get?.()??{}}return Us}var Vs,Fi;function Wh(){if(Fi)return Vs;Fi=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,s=(b,v)=>{for(var y in v)e(b,y,{get:v[y],enumerable:!0})},o=(b,v,y,x)=>{if(v&&typeof v=="object"||typeof v=="function")for(let S of r(v))!n.call(b,S)&&S!==y&&e(b,S,{get:()=>v[S],enumerable:!(x=t(v,S))||x.enumerable});return b},l=b=>o(e({},"__esModule",{value:!0}),b),u={};s(u,{getContext:()=>d.getContext,getVercelOidcToken:()=>f,getVercelOidcTokenSync:()=>m}),Vs=l(u);var d=Zh();async function f(){return""}function m(){return""}return Vs}var ec=Wh(),Hh="vercel.ai.gateway.error",Ks=Symbol.for(Hh),qi,Li,Nt=class tc extends(Li=Error,qi=Ks,Li){constructor({message:t,statusCode:r=500,cause:n}){super(t),this[qi]=!0,this.statusCode=r,this.cause=n}static isInstance(t){return tc.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&Ks in t&&t[Ks]===!0}},rc="GatewayAuthenticationError",Jh=`vercel.ai.gateway.error.${rc}`,Bi=Symbol.for(Jh),Ui,Vi,Ao=class nc extends(Vi=Nt,Ui=Bi,Vi){constructor({message:t="Authentication failed",statusCode:r=401,cause:n}={}){super({message:t,statusCode:r,cause:n}),this[Ui]=!0,this.name=rc,this.type="authentication_error"}static isInstance(t){return Nt.hasMarker(t)&&Bi in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:r,message:n="Authentication failed",statusCode:s=401,cause:o}){let l;return t?l=`AI Gateway authentication failed: Invalid API key.
13
14Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
15
16Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:r?l=`AI Gateway authentication failed: Invalid OIDC token.
17
18Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.
19
20Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`:l=`AI Gateway authentication failed: No authentication provided.
21
22Option 1 - API key:
23Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
24Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
25
26Option 2 - OIDC token:
27Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new nc({message:l,statusCode:s,cause:o})}},ac="GatewayInvalidRequestError",Qh=`vercel.ai.gateway.error.${ac}
27`,Ki=Symbol.for(Qh),zi,Gi,Yh=class extends(Gi=Nt,zi=Ki,Gi){constructor({message:e="Invalid request",statusCode:t=400,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[zi]=!0,this.name=ac,this.type="invalid_request_error"}static isInstance(e){return Nt.hasMarker(e)&&Ki in e}},sc="GatewayRateLimitError",Xh=`vercel.ai.gateway.error.${sc}`,Zi=Symbol.for(Xh),Wi,Hi,em=class extends(Hi=Nt,Wi=Zi,Hi){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[Wi]=!0,this.name=sc,this.type="rate_limit_exceeded"}static isInstance(e){return Nt.hasMarker(e)&&Zi in e}},oc="GatewayModelNotFoundError",tm=`vercel.ai.gateway.error.${oc}`,Ji=Symbol.for(tm),rm=an(()=>Pr(z({modelId:D()}))),Qi,Yi,ic=class extends(Yi=Nt,Qi=Ji,Yi){constructor({message:e="Model not found",statusCode:t=404,modelId:r,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[Qi]=!0,this.name=oc,this.type="model_not_found",this.modelId=r}static isInstance(e){return Nt.hasMarker(e)&&Ji in e}},lc="GatewayInternalServerError",nm=`vercel.ai.gateway.error.${lc}`,Xi=Symbol.for(nm),el,tl,rl=class extends(tl=Nt,el=Xi,tl){constructor({message:e="Internal server error",statusCode:t=500,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[el]=!0,this.name=lc,this.type="internal_server_error"}static isInstance(e){return Nt.hasMarker(e)&&Xi in e}},uc="GatewayResponseError",am=`vercel.ai.gateway.error.${uc}`,nl=Symbol.for(am),al,sl,sm=class extends(sl=Nt,al=nl,sl){constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:r,validationError:n,cause:s}={}){super({message:e,statusCode:t,cause:s}),this[al]=!0,this.name=uc,this.type="response_error",this.response=r,this.validationError=n}static isInstance(e){return Nt.hasMarker(e)&&nl in e}};async function ol({response:e,statusCode:t,defaultMessage:r="Gateway request failed",cause:n,authMethod:s}){const o=await fr({value:e,schema:om});if(!o.success)return new sm({message:`Invalid error response format: ${r}`,statusCode:t,response:e,validationError:o.error,cause:n});const l=o.value,u=l.error.type,d=l.error.message;switch(u){case"authentication_error":return Ao.createContextualError({apiKeyProvided:s==="api-key",oidcTokenProvided:s==="oidc",statusCode:t,cause:n});case"invalid_request_error":return new Yh({message:d,statusCode:t,cause:n});case"rate_limit_exceeded":return new em({message:d,statusCode:t,cause:n});case"model_not_found":{const f=await fr({value:l.error.param,schema:rm});return new ic({message:d,statusCode:t,modelId:f.success?f.value.modelId:void 0,cause:n})}case"internal_server_error":return new rl({message:d,statusCode:t,cause:n});default:return new rl({message:d,statusCode:t,cause:n})}}var om=an(()=>Pr(z({error:z({message:D(),type:D().nullish(),param:Lt().nullish(),code:Xe([D(),we()]).nullish()})})));function tn(e,t){var r;return Nt.isInstance(e)?e:ft.isInstance(e)?ol({response:im(e),statusCode:(r=e.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):ol({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}function im(e){if(e.data!==void 0)return e.data;if(e.responseBody!=null)try{return JSON.parse(e.responseBody)}catch{return e.responseBody}return{}}var cc="ai-gateway-auth-method";async function ra(e){const t=await fr({value:e[cc],schema:lm});return t.success?t.value:void 0}var lm=an(()=>Pr(Xe([ge("api-key"),ge("oidc")]))),il=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await Mi({url:`${this.config.baseURL}/config`,headers:await Et(this.config.headers()),successfulResponseHandler:Cr(um),failedResponseHandler:mr({errorSchema:ur(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw await tn(e)}}async getCredits(){try{const e=new URL(this.config.baseURL),{value:t}=await Mi({url:`${e.origin}/v1/credits`,headers:await Et(this.config.headers()),successfulResponseHandler:Cr(cm),failedResponseHandler:mr({errorSchema:ur(),errorToMessage:r=>r}),fetch:this.config.fetch});return t}catch(e){throw await tn(e)}}},um=an(()=>Pr(z({models:Ze(z({id:D(),name:D(),description:D().nullish(),pricing:z({input:D(),output:D(),input_cache_read:D().nullish(),input_cache_write:D().nullish()}).transform(({input:e,output:t,input_cache_read:r,input_cache_write:n})=>({input:e,output:t,...r?{cachedInputTokens:r}:{},...n?{cacheCreationInputTokens:n}:{}})).nullish(),specification:z({specificationVersion:ge("v2"),provider:D(),modelId:D()}),modelType:Gl(["language","embedding","image"]).nullish()}))}))),cm=an(()=>Pr(z({balance:D(),total_used:D()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),dm=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}
27async getArgs(e){const{abortSignal:t,...r}=e;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,s=await Et(this.config.headers());try{const{responseHeaders:o,value:l,rawValue:u}=await hr({url:this.getUrl(),headers:pr(s,e.headers,this.getModelConfigHeaders(this.modelId,!1),await Et(this.config.o11yHeaders)),body:t,successfulResponseHandler:Cr(ur()),failedResponseHandler:mr({errorSchema:ur(),errorToMessage:d=>d}),...n&&{abortSignal:n},fetch:this.config.fetch});return{...l,request:{body:t},response:{headers:o,body:u},warnings:r}}catch(o){throw await tn(o,await ra(s))}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,s=await Et(this.config.headers());try{const{value:o,responseHeaders:l}=await hr({url:this.getUrl(),headers:pr(s,e.headers,this.getModelConfigHeaders(this.modelId,!0),await Et(this.config.o11yHeaders)),body:t,successfulResponseHandler:Io(ur()),failedResponseHandler:mr({errorSchema:ur(),errorToMessage:u=>u}),...n&&{abortSignal:n},fetch:this.config.fetch});return{stream:o.pipeThrough(new TransformStream({start(u){r.length>0&&u.enqueue({type:"stream-start",warnings:r})},transform(u,d){if(u.success){const f=u.value;if(f.type==="raw"&&!e.includeRawChunks)return;f.type==="response-metadata"&&f.timestamp&&typeof f.timestamp=="string"&&(f.timestamp=new Date(f.timestamp)),d.enqueue(f)}else d.error(u.error)}})),request:{body:t},response:{headers:l}}}catch(o){throw await tn(o,await ra(s))}}isFilePart(e){return e&&typeof e=="object"&&"type"in e&&e.type==="file"}maybeEncodeFileParts(e){for(const t of e.prompt)for(const r of t.content)if(this.isFilePart(r)){const n=r;if(n.data instanceof Uint8Array){const s=Uint8Array.from(n.data),o=Buffer.from(s).toString("base64");n.data=new URL(`data:${n.mediaType||"application/octet-stream"};base64,${o}`)}}return e}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(e,t){return{"ai-language-model-specification-version":"2","ai-language-model-id":e,"ai-language-model-streaming":String(t)}}},pm=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:r,providerOptions:n}){var s;const o=await Et(this.config.headers());try{const{responseHeaders:l,value:u,rawValue:d}=await hr({url:this.getUrl(),headers:pr(o,t??{},this.getModelConfigHeaders(),await Et(this.config.o11yHeaders)),body:{input:e.length===1?e[0]:e,...n?{providerOptions:n}:{}},successfulResponseHandler:Cr(fm),failedResponseHandler:mr({errorSchema:ur(),errorToMessage:f=>f}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:u.embeddings,usage:(s=u.usage)!=null?s:void 0,providerMetadata:u.providerMetadata,response:{headers:l,body:d}}}catch(l){throw await tn(l,await ra(o))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"2","ai-model-id":this.modelId}}},fm=an(()=>Pr(z({embeddings:Ze(Ze(we())),usage:z({tokens:we()}).nullish(),providerMetadata:Ar(D(),Ar(D(),Lt())).optional()})));async function hm(){var e;return(e=ec.getContext().headers)==null?void 0:e["x-vercel-id"]}var mm="2.0.0",gm="0.0.1";function vm(e={}){var t,r;let n=null,s=null;const o=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5;let l=0;const u=(r=Xu(e.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v1/ai",d=async()=>{const x=await bm(e);
27if(x)return Xr({Authorization:`Bearer ${x.token}`,"ai-gateway-protocol-version":gm,[cc]:x.authMethod,...e.headers},`ai-sdk/gateway/${mm}`);throw Ao.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},f=()=>{const x=qa({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),S=qa({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),M=qa({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const R=await hm();return{...x&&{"ai-o11y-deployment-id":x},...S&&{"ai-o11y-environment":S},...M&&{"ai-o11y-region":M},...R&&{"ai-o11y-request-id":R}}}},m=x=>new dm(x,{provider:"gateway",baseURL:u,headers:d,fetch:e.fetch,o11yHeaders:f()}),b=async()=>{var x,S,M;const R=(M=(S=(x=e._internal)==null?void 0:x.currentDate)==null?void 0:S.call(x).getTime())!=null?M:Date.now();return(!n||R-l>o)&&(l=R,n=new il({baseURL:u,headers:d,fetch:e.fetch}).getAvailableModels().then(B=>(s=B,B)).catch(async B=>{throw await tn(B,await ra(await d()))})),s?Promise.resolve(s):n},v=async()=>new il({baseURL:u,headers:d,fetch:e.fetch}).getCredits().catch(async x=>{throw await tn(x,await ra(await d()))}),y=function(x){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return m(x)};return y.getAvailableModels=b,y.getCredits=v,y.imageModel=x=>{throw new Ef({modelId:x,modelType:"imageModel"})},y.languageModel=m,y.textEmbeddingModel=x=>new pm(x,{provider:"gateway",baseURL:u,headers:d,fetch:e.fetch,o11yHeaders:f()}),y}var ym=vm();async function bm(e){const t=qa({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(t)return{token:t,authMethod:"api-key"};try{return{token:await ec.getVercelOidcToken(),authMethod:"oidc"}}catch{return null}}var wm=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},Hr="1.9.0",ll=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function _m(e){var t=new Set([e]),r=new Set,n=e.match(ll);if(!n)return function(){return!1};var s={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(s.prerelease!=null)return function(d){return d===e};function o(u){return r.add(u),!1}function l(u){return t.add(u),!0}return function(d){if(t.has(d))return!0;if(r.has(d))return!1;var f=d.match(ll);if(!f)return o(d);var m={major:+f[1],minor:+f[2],patch:+f[3],prerelease:f[4]};return m.prerelease!=null||s.major!==m.major?o(d):s.major===0?s.minor===m.minor&&s.patch<=m.patch?l(d):o(d):s.minor<=m.minor?l(d):o(d)}}var xm=_m(Hr),km=Hr.split(".")[0],na=Symbol.for("opentelemetry.js.api."+km),aa=wm;function Co(e,t,r,n){var s;n===void 0&&(n=!1);var o=aa[na]=(s=aa[na])!==null&&s!==void 0?s:{version:Hr};if(!n&&o[e]){var l=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return r.error(l.stack||l.message),!1}if(o.version!==Hr){var l=new Error("@opentelemetry/api: Registration of version v"+o.version+" for "+e+" does not match previously registered API v"+Hr);return r.error(l.stack||l.message),!1}return o[e]=t,r.debug("@opentelemetry/api: Registered a global for "+e+" v"+Hr+"."),!0}function sa(e){var t,r,n=(t=aa[na])===null||t===void 0?void 0:t.version;if(!(!n||!xm(n)))return(r=aa[na])===null||r===void 0?void 0:r[e]}function Ro(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+Hr+".");var r=aa[na];r&&delete r[e]}var Sm=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),s,o=[],l;try{for(;(t===void 0||t-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(u){l={error:u}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(l)throw l.error}}return o},Im=function(e,t,r){if(r||arguments.length===2)for(var n=0,s=t.length,o;n<s;n++)(o||!(n in t))&&(o||(o=Array.prototype.slice.call(t,0,n)),o[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))},Tm=(function(){function e(t){this._namespace=t.namespace||"DiagComponentLogger"}return e.prototype.debug=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Dn("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Dn("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Dn("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Dn("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Dn("verbose",this._namespace,t)},e})();function Dn(e,t,r){var n=sa("diag");if(n)return r.unshift(t),n[e].apply(n,Im([],Sm(r),!1))}var Ot;
vendor: 1,741 bytes, line 27
27(function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"})(Ot||(Ot={}));function Em(e,t){e<Ot.NONE?e=Ot.NONE:e>Ot.ALL&&(e=Ot.ALL),t=t||{};function r(n,s){var o=t[n];return typeof o=="function"&&e>=s?o.bind(t):function(){}}return{error:r("error",Ot.ERROR),warn:r("warn",Ot.WARN),info:r("info",Ot.INFO),debug:r("debug",Ot.DEBUG),verbose:r("verbose",Ot.VERBOSE)}}var Am=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),s,o=[],l;try{for(;(t===void 0||t-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(u){l={error:u}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(l)throw l.error}}return o},Cm=function(e,t,r){if(r||arguments.length===2)for(var n=0,s=t.length,o;n<s;n++)(o||!(n in t))&&(o||(o=Array.prototype.slice.call(t,0,n)),o[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))},Rm="diag",Wa=(function(){function e(){function t(s){return function(){for(var o=[],l=0;l<arguments.length;l++)o[l]=arguments[l];var u=sa("diag");if(u)return u[s].apply(u,Cm([],Am(o),!1))}}var r=this,n=function(s,o){var l,u,d;if(o===void 0&&(o={logLevel:Ot.INFO}),s===r){var f=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((l=f.stack)!==null&&l!==void 0?l:f.message),!1}typeof o=="number"&&(o={logLevel:o});var m=sa("diag"),b=Em((u=o.logLevel)!==null&&u!==void 0?u:Ot.INFO,s);if(m&&!o.suppressOverrideMessage){var v=(d=new Error().stack)!==null&&d!==void 0?d:"<failed to generate stacktrace>";m.warn("Current logger will be overwritten from "+v),b.warn("Current logger will over
27write one already registered from "+v)}return Co("diag",b,r,!0)};r.setLogger=n,r.disable=function(){Ro(Rm,r)},r.createComponentLogger=function(s){return new Tm(s)},r.verbose=t("verbose"),r.debug=t("debug"),r.info=t("info"),r.warn=t("warn"),r.error=t("error")}return e.instance=function(){return this._instance||(this._instance=new e),this._instance},e})();function Pm(e){return Symbol.for(e)}var Om=(function(){function e(t){var r=this;r._currentContext=t?new Map(t):new Map,r.getValue=function(n){return r._currentContext.get(n)},r.setValue=function(n,s){var o=new e(r._currentContext);return o._currentContext.set(n,s),o},r.deleteValue=function(n){var s=new e(r._currentContext);return s._currentContext.delete(n),s}}return e})(),Mm=new Om,Nm=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),s,o=[],l;try{for(;(t===void 0||t-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(u){l={error:u}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(l)throw l.error}}return o},jm=function(e,t,r){if(r||arguments.length===2)for(var n=0,s=t.length,o;n<s;n++)(o||!(n in t))&&(o||(o=Array.prototype.slice.call(t,0,n)),o[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))},$m=(function(){function e(){}return e.prototype.active=function(){return Mm},e.prototype.with=function(t,r,n){for(var s=[],o=3;o<arguments.length;o++)s[o-3]=arguments[o];return r.call.apply(r,jm([n],Nm(s),!1))},e.prototype.bind=function(t,r){return r},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),Dm=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),s,o=[],l;try{for(;(t===void 0||t-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(u){l={error:u}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(l)throw l.error}}return o},Fm=function(e,t,r){if(r||arguments.length===2)for(var n=0,s=t.length,o;n<s;n++)(o||!(n in t))&&(o||(o=Array.prototype.slice.call(t,0,n)),o[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))},zs="context",qm=new $m,dc=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return Co(zs,t,Wa.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(t,r,n){for(var s,o=[],l=3;l<arguments.length;l++)o[l-3]=arguments[l];return(s=this._getContextManager()).with.apply(s,Fm([t,r,n],Dm(o),!1))},e.prototype.bind=function(t,r){return this._getContextManager().bind(t,r)},e.prototype._getContextManager=function(){return sa(zs)||qm},e.prototype.disable=function(){this._getContextManager().disable(),Ro(zs,Wa.instance())},e})(),so;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(so||(so={}));var pc="0000000000000000",fc="00000000000000000000000000000000",Lm={traceId:fc,spanId:pc,traceFlags:so.NONE},Wn=(function(){function e(t){t===void 0&&(t=Lm),this._spanContext=t}return e.prototype.spanContext=function(){return this._spanContext},e.prototype.setAttribute=function(t,r){return this},e.prototype.setAttributes=function(t){return this},e.prototype.addEvent=function(t,r){return this},e.prototype.addLink=function(t){return this},e.prototype.addLinks=function(t){return this},e.prototype.setStatus=function(t){return this},e.prototype.updateName=function(t){return this},e.prototype.end=function(t){},e.prototype.isRecording=function(){return!1},e.prototype.recordException=function(t,r){},e})(),Po=Pm("OpenTelemetry Context Key SPAN");function Oo(e){return e.getValue(Po)||void 0}function Bm(){return Oo(dc.getInstance().active())}function Mo(e,t){return e.setValue(Po,t)}function Um(e){return e.deleteValue(Po)}function Vm(e,t){return Mo(e,new Wn(t))}function hc(e){var t;return(t=Oo(e))===null||t===void 0?void 0:t.spanContext()}var Km=/^([0-9a-f]{32})$/i,zm=/^[0-9a-f]{16}$/i;function Gm(e){return Km.test(e)&&e!==fc}function Zm(e){return zm.test(e)&&e!==pc}function mc(e){return Gm(e.traceId)&&Zm(e.spanId)}function Wm(e){return new Wn(e)}var Gs=dc.getInstance(),gc=(function(){function e(){}return e.prototype.startSpan=function(t,r,n){n===void 0&&(n=Gs.active());var s=!!r?.root;if(s)return new Wn;var o=n&&hc(n);return Hm(o)&&mc(o)?new Wn(o):new Wn},e.prototype.startActiveSpan=function(t,r,n,s){var o,l,u;if(!(arguments.length<2)){arguments.length===2?u=r:arguments.length===3?(o=r,u=n):(o=r,l=n,u=s);var d=l??Gs.active(),f=this.startSpan(t,o,d),m=Mo(d,f);return Gs.with(m,u,void 0,f)}},e})();function Hm(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var Jm=new gc,Qm=(function(){function e(t,r,n,s){this._provider=t,this.name=r,this.version=n,this.options=s}return e.prototype.startSpan=function(t,r,n){return this._getTracer().startSpan(t,r,n)},e.prototype.startActiveSpan=function(t,r,n,s){var o=this._getTracer();return Reflect.apply(o.startActiveSpan,o,arguments)},e.prototype._getTracer=function(){if(this._delegate)return this._delegate;var t=this._provider.getDelegateTracer(this.name,this.version,this.options);return t?(this._delegate=t,this._delegate):Jm},e})(),Ym=(function(){function e(){}return e.prototype.getTracer=function(t,r,n){return new gc},e})(),Xm=new Ym,ul=(function(){function e(){}return e.prototype.getTracer=function(t,r,n){var s;return(s=this.getDelegateTracer(t,r,n))!==null&&s!==void 0?s:new Qm(this,t,r,n)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:Xm},e.prototype.setDelegate=function(t){this._delegate=t},e.prototype.getDelegateTracer=function(t,r,n){var s;return(s=this._delegate)===null||s===void 0?void 0:s.getTracer(t,r,n)},e})(),Ha;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(Ha||(Ha={}));var Zs="trace",eg=(function(){function e(){this._proxyTracerProvider=new ul,this.wrapSpanContext=Wm,this.isSpanContextValid=mc,this.deleteSpan=Um,this.get
27Span=Oo,this.getActiveSpan=Bm,this.getSpanContext=hc,this.setSpan=Mo,this.setSpanContext=Vm}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var r=Co(Zs,this._proxyTracerProvider,Wa.instance());return r&&this._proxyTracerProvider.setDelegate(t),r},e.prototype.getTracerProvider=function(){return sa(Zs)||this._proxyTracerProvider},e.prototype.getTracer=function(t,r){return this.getTracerProvider().getTracer(t,r)},e.prototype.disable=function(){Ro(Zs,Wa.instance()),this._proxyTracerProvider=new ul},e})(),tg=eg.getInstance(),rg=Object.defineProperty,ng=(e,t)=>{for(var r in t)rg(e,r,{get:t[r],enumerable:!0})},vc="AI_NoOutputSpecifiedError",yc=`vercel.ai.error.${vc}`,ag=Symbol.for(yc),bc,sg=class extends be{constructor({message:e="No output specified."}={}){super({name:vc,message:e}),this[bc]=!0}static isInstance(e){return be.hasMarker(e,yc)}};bc=ag;function og(e){const t="AI SDK Warning:";switch(e.type){case"unsupported-setting":{let r=`${t} The "${e.setting}" setting is not supported by this model`;return e.details&&(r+=` - ${e.details}`),r}case"unsupported-tool":{const r="name"in e.tool?e.tool.name:"unknown tool";let n=`${t} The tool "${r}" is not supported by this model`;return e.details&&(n+=` - ${e.details}`),n}case"other":return`${t} ${e.message}`;default:return`${t} ${JSON.stringify(e,null,2)}`}}var ig="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",cl=!1,lg=e=>{if(e.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}cl||(cl=!0,console.info(ig));for(const r of e)console.warn(og(r))}},wc="AI_InvalidArgumentError",_c=`vercel.ai.error.${wc}`,ug=Symbol.for(_c),xc,tr=class extends be{constructor({parameter:e,value:t,message:r}){super({name:wc,message:`Invalid argument for parameter ${e}: ${r}`}),this[xc]=!0,this.parameter=e,this.value=t}static isInstance(e){return be.hasMarker(e,_c)}};xc=ug;var kc="AI_InvalidToolInputError",Sc=`vercel.ai.error.${kc}`,cg=Symbol.for(Sc),Ic,Tc=class extends be{constructor({toolInput:e,toolName:t,cause:r,message:n=`Invalid input for tool ${t}: ${In(r)}`}){super({name:kc,message:n,cause:r}),this[Ic]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return be.hasMarker(e,Sc)}};Ic=cg;var Ec="AI_NoObjectGeneratedError",Ac=`vercel.ai.error.${Ec}`,dg=Symbol.for(Ac),Cc,dl=class extends be{constructor({message:e="No object generated.",cause:t,text:r,response:n,usage:s,finishReason:o}){super({name:Ec,message:e,cause:t}),this[Cc]=!0,this.text=r,this.response=n,this.usage=s,this.finishReason=o}static isInstance(e){return be.hasMarker(e,Ac)}};Cc=dg;var Rc="AI_NoOutputGeneratedError",Pc=`vercel.ai.error.${Rc}`,pg=Symbol.for(Pc),Oc,fg=class extends be{constructor({message:e="No output generated.",cause:t}={}){super({name:Rc,message:e,cause:t}),this[Oc]=!0}static isInstance(e){return be.hasMarker(e,Pc)}};Oc=pg;var Mc="AI_NoSuchToolError",Nc=`vercel.ai.error.${Mc}`,hg=Symbol.for(Nc),jc,oo=class extends be{constructor({toolName:e,availableTools:t=void 0,message:r=`Model tried to call unavailable tool '${e}'. ${t===void 0?"No tools are available.":`Available tools: ${t.join(", ")}.`}`}){super({name:Mc,message:r}),this[jc]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return be.hasMarker(e,Nc)}};jc=hg;var $c="AI_ToolCallRepairError",Dc=`vercel.ai.error.${$c}`,mg=Symbol.for(Dc),Fc,gg=class extends be{constructor({cause:e,originalError:t,message:r=`Error repairing tool call: ${In(e)}`}){super({name:$c,message:r,cause:e}),this[Fc]=!0,this.originalError=t}static isInstance(e){return be.hasMarker(e,Dc)}};Fc=mg;var vg=class extends be{constructor(e){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${e.version} for provider "${e.provider}" and model "${e.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=e.version,this.provider=e.provider,this.modelId=e.modelId}},qc="AI_InvalidMessageRoleError",Lc=`vercel.ai.error.${qc}`,yg=Symbol.for(Lc),Bc,bg=class extends be{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:qc,message:t}),this[Bc]=!0,this.role=e}static isInstance(e){return be.hasMarker(e,Lc)}};Bc=yg;var Uc="AI_MessageConversionError",Vc=`vercel.ai.error.${Uc}`,wg=Symbol.for(Vc),Kc,_g=class extends be{constructor({originalMessage:e,message:t}){super({name:Uc,message:t}),this[Kc]=!0,this.originalMessage=e}static isInstance(e){return be.hasMarker(e,Vc)}};Kc=wg;var zc="AI_DownloadError",Gc=`vercel.ai.error.${zc}`,xg=Symbol.for(Gc),Zc,Ws=class extends be{constructor({url:e,statusCode:t,statusText:r,cause:n,message:s=n==null?`Failed to download ${e}: ${t} ${r}`:`Failed to download ${e}: ${n}`}){super({name:zc,message:s,cause:n}),this[Zc]=!0,this.url=e,this.statusCode=t,this.statusText=r}static isInstance(e){return be.hasMarker(e,Gc)}};Zc=xg;var Wc="AI_RetryError",Hc=`vercel.ai.error.${Wc}`,kg=Symbol.for(Hc),Jc,pl=class extends be{constructor({message:e,reason:t,errors:r}){super({name:Wc,message:e}),this[Jc]=!0,this.reason=t,this.errors=r,this.lastError=r[r.length-1]}static isInstance(e){return be.hasMarker(e,Hc)}};Jc=kg;function Qc(e){if(typeof e!="string"){if(e.specificationVersion!=="v2")throw new vg({version:e.specificationVersion,provider:e.provider,modelId:e.modelId});return e}return Sg().languageModel(e)}function Sg(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:ym}var Ig=[{mediaType:"image/gif",bytesPrefix:[71,73,70]},{mediaType:"image/png",bytesPrefix:[137,80,78,71]},{mediaType:"image/jpeg",bytesPrefix:[255,216]}
27,{mediaType:"image/webp",bytesPrefix:[82,73,70,70,null,null,null,null,87,69,66,80]},{mediaType:"image/bmp",bytesPrefix:[66,77]},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0]},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42]},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102]},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99]}],Tg=e=>{const t=typeof e=="string"?Eo(e):e,r=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(r+10)};function Eg(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?Tg(e):e}function Ag({data:e,signatures:t}){const r=Eg(e),n=typeof r=="string"?Eo(r.substring(0,Math.min(r.length,24))):r;for(const s of t)if(n.length>=s.bytesPrefix.length&&s.bytesPrefix.every((o,l)=>o===null||n[l]===o))return s.mediaType}var io="5.0.76",Cg=async({url:e})=>{var t;const r=e.toString();try{const n=await fetch(r,{headers:Xr({},`ai-sdk/${io}`,ea())});if(!n.ok)throw new Ws({url:r,statusCode:n.status,statusText:n.statusText});return{data:new Uint8Array(await n.arrayBuffer()),mediaType:(t=n.headers.get("content-type"))!=null?t:void 0}}catch(n){throw Ws.isInstance(n)?n:new Ws({url:r,cause:n})}},Rg=(e=Cg)=>t=>Promise.all(t.map(async r=>r.isUrlSupportedByModel?null:e(r)));function Pg(e){try{const[t,r]=e.split(",");return{mediaType:t.split(";")[0].split(":")[1],base64Content:r}}catch{return{mediaType:void 0,base64Content:void 0}}}var Yc=Xe([D(),Va(Uint8Array),Va(ArrayBuffer),Zl(e=>{var t,r;return(r=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?r:!1},{message:"Must be a Buffer"})]);function Xc(e){if(e instanceof Uint8Array)return{data:e,mediaType:void 0};if(e instanceof ArrayBuffer)return{data:new Uint8Array(e),mediaType:void 0};if(typeof e=="string")try{e=new URL(e)}catch{}if(e instanceof URL&&e.protocol==="data:"){const{mediaType:t,base64Content:r}=Pg(e.toString());if(t==null||r==null)throw new be({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:r,mediaType:t}}return{data:e,mediaType:void 0}}function Og(e){return typeof e=="string"?e:e instanceof ArrayBuffer?Za(new Uint8Array(e)):Za(e)}async function Mg({prompt:e,supportedUrls:t,download:r=Rg()}){const n=await jg(e.messages,r,t);return[...e.system!=null?[{role:"system",content:e.system}]:[],...e.messages.map(s=>Ng({message:s,downloadedAssets:n}))]}function Ng({message:e,downloadedAssets:t}){const r=e.role;switch(r){case"system":return{role:"system",content:e.content,providerOptions:e.providerOptions};case"user":return typeof e.content=="string"?{role:"user",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"user",content:e.content.map(n=>$g(n,t)).filter(n=>n.type!=="text"||n.text!==""),providerOptions:e.providerOptions};case"assistant":return typeof e.content=="string"?{role:"assistant",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"assistant",content:e.content.filter(n=>n.type!=="text"||n.text!==""||n.providerOptions!=null).map(n=>{const s=n.providerOptions;switch(n.type){case"file":{const{data:o,mediaType:l}=Xc(n.data);return{type:"file",data:o,filename:n.filename,mediaType:l??n.mediaType,providerOptions:s}}case"reasoning":return{type:"reasoning",text:n.text,providerOptions:s};case"text":return{type:"text",text:n.text,providerOptions:s};case"tool-call":return{type:"tool-call",toolCallId:n.toolCallId,toolName:n.toolName,input:n.input,providerExecuted:n.providerExecuted,providerOptions:s};case"tool-result":return{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:n.output,providerOptions:s}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.map(n=>({type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:n.output,providerOptions:n.providerOptions})),providerOptions:e.providerOptions};default:{const n=r;throw new bg({role:n})}}}async function jg(e,t,r){const n=e.filter(o=>o.role==="user").map(o=>o.content).filter(o=>Array.isArray(o)).flat().filter(o=>o.type==="image"||o.type==="file").map(o=>{var l;const u=(l=o.mediaType)!=null?l:o.type==="image"?"image/*":void 0;let d=o.type==="image"?o.image:o.data;
27if(typeof d=="string")try{d=new URL(d)}catch{}return{mediaType:u,data:d}}).filter(o=>o.data instanceof URL).map(o=>({url:o.data,isUrlSupportedByModel:o.mediaType!=null&&Lf({url:o.data.toString(),mediaType:o.mediaType,supportedUrls:r})})),s=await t(n);return Object.fromEntries(s.map((o,l)=>o==null?null:[n[l].url.toString(),{data:o.data,mediaType:o.mediaType}]).filter(o=>o!=null))}function $g(e,t){var r;if(e.type==="text")return{type:"text",text:e.text,providerOptions:e.providerOptions};let n;const s=e.type;switch(s){case"image":n=e.image;break;case"file":n=e.data;break;default:throw new Error(`Unsupported part type: ${s}`)}const{data:o,mediaType:l}=Xc(n);let u=l??e.mediaType,d=o;if(d instanceof URL){const f=t[d.toString()];f&&(d=f.data,u??(u=f.mediaType))}switch(s){case"image":return(d instanceof Uint8Array||typeof d=="string")&&(u=(r=Ag({data:d,signatures:Ig}))!=null?r:u),{type:"file",mediaType:u??"image/*",filename:void 0,data:d,providerOptions:e.providerOptions};case"file":{if(u==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:u,filename:e.filename,data:d,providerOptions:e.providerOptions}}}}function Dg({maxOutputTokens:e,temperature:t,topP:r,topK:n,presencePenalty:s,frequencyPenalty:o,seed:l,stopSequences:u}){if(e!=null){if(!Number.isInteger(e))throw new tr({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new tr({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new tr({parameter:"temperature",value:t,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new tr({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new tr({parameter:"topK",value:n,message:"topK must be a number"});if(s!=null&&typeof s!="number")throw new tr({parameter:"presencePenalty",value:s,message:"presencePenalty must be a number"});if(o!=null&&typeof o!="number")throw new tr({parameter:"frequencyPenalty",value:o,message:"frequencyPenalty must be a number"});if(l!=null&&!Number.isInteger(l))throw new tr({parameter:"seed",value:l,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:r,topK:n,presencePenalty:s,frequencyPenalty:o,stopSequences:u,seed:l}}function Fg(e){return e!=null&&Object.keys(e).length>0}function qg({tools:e,toolChoice:t,activeTools:r}){return Fg(e)?{tools:(r!=null?Object.entries(e).filter(([s])=>r.includes(s)):Object.entries(e)).map(([s,o])=>{const l=o.type;switch(l){case void 0:case"dynamic":case"function":return{type:"function",name:s,description:o.description,inputSchema:kn(o.inputSchema).jsonSchema,providerOptions:o.providerOptions};case"provider-defined":return{type:"provider-defined",name:s,id:o.id,args:o.args};default:{const u=l;throw new Error(`Unsupported tool type: ${u}`)}}}),toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}:{tools:void 0,toolChoice:void 0}}var oa=Cp(()=>Xe([Rp(),D(),we(),Ve(),Ar(D(),oa),Ze(oa)])),at=Ar(D(),Ar(D(),oa)),ed=z({type:ge("text"),text:D(),providerOptions:at.optional()}),Lg=z({type:ge("image"),image:Xe([Yc,Va(URL)]),mediaType:D().optional(),providerOptions:at.optional()}),td=z({type:ge("file"),data:Xe([Yc,Va(URL)]),filename:D().optional(),mediaType:D(),providerOptions:at.optional()}),Bg=z({type:ge("reasoning"),text:D(),providerOptions:at.optional()}),Ug=z({type:ge("tool-call"),toolCallId:D(),toolName:D(),input:Lt(),providerOptions:at.optional(),providerExecuted:Ve().optional()}),Vg=Pp("type",[z({type:ge("text"),value:D()}),z({type:ge("json"),value:oa}),z({type:ge("error-text"),value:D()}),z({type:ge("error-json"),value:oa}),z({type:ge("content"),value:Ze(Xe([z({type:ge("text"),text:D()}),z({type:ge("media"),data:D(),mediaType:D()})]))})]),rd=z({type:ge("tool-result"),toolCallId:D(),toolName:D(),output:Vg,providerOptions:at.optional()}),Kg=z({role:ge("system"),content:D(),providerOptions:at.optional()}),zg=z({role:ge("user"),content:Xe([D(),Ze(Xe([ed,Lg,td]))]),providerOptions:at.optional()}),Gg=z({role:ge("assistant"),content:Xe([D(),Ze(Xe([ed,td,Bg,Ug,rd]))]),providerOptions:at.optional()}),Zg=z({role:ge("tool"),content:Ze(rd),providerOptions:at.optional()}),Wg=Xe([Kg,zg,Gg,Zg]);async function Hg(e){if(e.prompt==null&&e.messages==null)throw new Gr({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new Gr({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string")throw new Gr({prompt:e,message:"system must be a string"});let t;if(e.prompt!=null&&typeof e.prompt=="string")t=[{role:"user",content:e.prompt}];else if(e.prompt!=null&&Array.isArray(e.prompt))t=e.prompt;else if(e.messages!=null)t=e.messages;else throw new Gr({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new Gr({prompt:e,message:"messages must not be empty"});const r=await fr({value:t,schema:Ze(Wg)});if(!r.success)throw new Gr({prompt:e,message:"The messages must be a ModelMessage[]. If you have passed a UIMessage[], you can use convertToModelMessages to convert them.",cause:r.error});return{messages:t,system:e.system}}function Jg(e){return Ao.isInstance(e)||ic.isInstance(e)?new be({name:"GatewayError",message:"Vercel AI Gateway access failed. If you want to use AI SDK providers directly, use the providers, e.g. @ai-sdk/openai, or register a different global default provider.",cause:e}):e}function lo({operationId:e,telemetry:t}){return{"operation.name":`${e}${t?.functionId!=null?` ${t.functionId}`:""}`,"resource.name":t?.functionId,"ai.operationId":e,"ai.telemetry.functionId":t?.functionId}}function Qg({model:e,settings:t,telemetry:r,headers:n}){var s;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((o,[l,u])=>(o[`ai.settings.${l}`]=u,o),{}),...Object.entries((s=r?.metadata)!=null?s:{}).reduce((o,[l,u])=>(o[`ai.telemetry.metadata.${l}`]=u,o),{}),...Object.entries(n??{}).reduce((o,[l,u])=>(u!==void 0&&(o[`ai.request.headers.${l}`]=u),o),{})}}var Yg={startSpan(){return Ma},startActiveSpan(e,t,r,n){if(typeof t=="function")return t(Ma);if(typeof r=="function")return r(Ma);if(typeof n=="function")return n(Ma)}},Ma={spanContext(){return Xg},setAttribute(){return this},setAttributes(){return this},addEvent(){return this},addLink(){return this},addLinks(){return this},setStatus(){return this},updateName(){return this},end(){return this},isRecording(){return!1},recordException(){return this}},Xg={traceId:"",spanId:"",traceFlags:0};function ev({isEnabled:e=!1,tracer:t}={}){return e?t||tg.getTracer("ai"):Yg}function uo({name:e,tracer:t,attributes:r,fn:n,endWhenDone:s=!0}){return t.startActiveSpan(e,{attributes:r},async o=>{try{const l=await n(o);return s&&o.end(),l}catch(l){try{nd(o,l)}finally{o.end()}throw l}})}
27function nd(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:Ha.ERROR,message:t.message})):e.setStatus({code:Ha.ERROR})}function bn({telemetry:e,attributes:t}){return e?.isEnabled!==!0?{}:Object.entries(t).reduce((r,[n,s])=>{if(s==null)return r;if(typeof s=="object"&&"input"in s&&typeof s.input=="function"){if(e?.recordInputs===!1)return r;const o=s.input();return o==null?r:{...r,[n]:o}}if(typeof s=="object"&&"output"in s&&typeof s.output=="function"){if(e?.recordOutputs===!1)return r;const o=s.output();return o==null?r:{...r,[n]:o}}return{...r,[n]:s}},{})}function tv(e){return JSON.stringify(e.map(t=>({...t,content:typeof t.content=="string"?t.content:t.content.map(r=>r.type==="file"?{...r,data:r.data instanceof Uint8Array?Og(r.data):r.data}:r)})))}function rv(e,t){return{inputTokens:Fn(e.inputTokens,t.inputTokens),outputTokens:Fn(e.outputTokens,t.outputTokens),totalTokens:Fn(e.totalTokens,t.totalTokens),reasoningTokens:Fn(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:Fn(e.cachedInputTokens,t.cachedInputTokens)}}function Fn(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function fl(e){return e===void 0?[]:Array.isArray(e)?e:[e]}function nv({error:e,exponentialBackoffDelay:t}){const r=e.responseHeaders;if(!r)return t;let n;const s=r["retry-after-ms"];if(s){const l=parseFloat(s);Number.isNaN(l)||(n=l)}const o=r["retry-after"];if(o&&n===void 0){const l=parseFloat(o);Number.isNaN(l)?n=Date.parse(o)-Date.now():n=l*1e3}return n!=null&&!Number.isNaN(n)&&0<=n&&(n<60*1e3||n<t)?n:t}var av=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:r=2,abortSignal:n}={})=>async s=>ad(s,{maxRetries:e,delayInMs:t,backoffFactor:r,abortSignal:n});async function ad(e,{maxRetries:t,delayInMs:r,backoffFactor:n,abort
27Signal:s},o=[]){try{return await e()}catch(l){if(Yr(l)||t===0)throw l;const u=Ku(l),d=[...o,l],f=d.length;if(f>t)throw new pl({message:`Failed after ${f} attempts. Last error: ${u}`,reason:"maxRetriesExceeded",errors:d});if(l instanceof Error&&ft.isInstance(l)&&l.isRetryable===!0&&f<=t)return await $f(nv({error:l,exponentialBackoffDelay:r}),{abortSignal:s}),ad(e,{maxRetries:t,delayInMs:n*r,backoffFactor:n,abortSignal:s},d);throw f===1?l:new pl({message:`Failed after ${f} attempts with non-retryable error: '${u}'`,reason:"errorNotRetryable",errors:d})}}function sv({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new tr({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new tr({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const r=e??2;return{maxRetries:r,retry:av({maxRetries:r,abortSignal:t})}}var ov=class{constructor({data:e,mediaType:t}){const r=e instanceof Uint8Array;this.base64Data=r?void 0:e,this.uint8ArrayData=r?e:void 0,this.mediaType=t}get base64(){return this.base64Data==null&&(this.base64Data=Za(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Eo(this.base64Data)),this.uint8ArrayData}},iv=class extends ov{constructor(e){super(e),this.type="file"}};async function lv({toolCall:e,tools:t,repairToolCall:r,system:n,messages:s}){try{if(t==null)throw new oo({toolName:e.toolName});try{return await hl({toolCall:e,tools:t})}catch(o){if(r==null||!(oo.isInstance(o)||Tc.isInstance(o)))throw o;let l=null;try{l=await r({toolCall:e,tools:t,inputSchema:({toolName:u})=>{const{inputSchema:d}=t[u];return kn(d).jsonSchema},system:n,messages:s,error:o})}catch(u){throw new gg({cause:u,originalError:o})}if(l==null)throw o;return await hl({toolCall:l,tools:t})}}catch(o){const l=await en({text:e.input}),u=l.success?l.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:u,dynamic:!0,invalid:!0,error:o}}}async function hl({toolCall:e,tools:t}){const r=e.toolName,n=t[r];if(n==null)throw new oo({toolName:e.toolName,availableTools:Object.keys(t)});const s=kn(n.inputSchema),o=e.input.trim()===""?await fr({value:{},schema:s}):await en({text:e.input,schema:s});if(o.success===!1)throw new Tc({toolName:r,toolInput:e.input,cause:o.error});return n.type==="dynamic"?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:o.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,dynamic:!0}:{type:"tool-call",toolCallId:e.toolCallId,toolName:r,input:o.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}var uv=class{constructor({content:e,finishReason:t,usage:r,warnings:n,request:s,response:o,providerMetadata:l}){this.content=e,this.finishReason=t,this.usage=r,this.warnings=n,this.request=s,this.response=o,this.providerMetadata=l}get text(){return this.content.filter(e=>e.type==="text").map(e=>e.text).join("")}get reasoning(){return this.content.filter(e=>e.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(e=>e.text).join("")}get files(){return this.content.filter(e=>e.type==="file").map(e=>e.file)}get sources(){return this.content.filter(e=>e.type==="source")}get toolCalls(){return this.content.filter(e=>e.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(e=>e.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(e=>e.dynamic===!0)}get toolResults(){return this.content.filter(e=>e.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(e=>e.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(e=>e.dynamic===!0)}};function cv(e){return({steps:t})=>t.length===e}async function dv({stopConditions:e,steps:t}){return(await Promise.all(e.map(r=>r({steps:t})))).some(r=>r)}function Hn({output:e,tool:t,errorMode:r}){return r==="text"?{type:"error-text",value:In(e)}:r==="json"?{type:"error-json",value:ml(e)}:t?.toModelOutput?t.toModelOutput(e):typeof e=="string"?{type:"text",value:e}:{type:"json",value:ml(e)}}function ml(e){return e===void 0?null:e}function gl({content:e,tools:t}){const r=[],n=e.filter(o=>o.type!=="source").filter(o=>(o.type!=="tool-result"||o.providerExecuted)&&(o.type!=="tool-error"||o.providerExecuted)).filter(o=>o.type!=="text"||o.text.length>0).map(o=>{switch(o.type){case"text":return{type:"text",text:o.text,providerOptions:o.providerMetadata};case"reasoning":return{type:"reasoning",text:o.text,providerOptions:o.providerMetadata};case"file":return{type:"file",data:o.file.base64,mediaType:o.file.mediaType,providerOptions:o.providerMetadata};case"tool-call":return{type:"tool-call",toolCallId:o.toolCallId,toolName:o.toolName,input:o.input,providerExecuted:o.providerExecuted,providerOptions:o.providerMetadata};case"tool-result":return{type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:Hn({tool:t?.[o.toolName],output:o.output,errorMode:"none"}),providerExecuted:!0,providerOptions:o.providerMetadata};case"tool-error":return{type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:Hn({tool:t?.[o.toolName],output:o.error,errorMode:"json"}),providerOptions:o.providerMetadata}}});n.length>0&&r.push({role:"assistant",content:n});const s=e.filter(o=>o.type==="tool-result"||o.type==="tool-error").filter(o=>!o.providerExecuted).map(o=>({type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:Hn({tool:t?.[o.toolName],output:o.type==="tool-result"?o.output:o.error,errorMode:o.type==="tool-error"?"text":"none"})}));return s.length>0&&r.push({role:"tool",content:s}),r}ua({prefix:"aitxt",size:24});function as(e,t){const r=new Headers(e??{});for(const[n,s]of Object.entries(t))r.has(n)||r.set(n,s);return r}function pv({status:e,statusText:t,headers:r,textStream:n}
27){return new Response(n.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:as(r,{"content-type":"text/plain; charset=utf-8"})})}function sd({response:e,status:t,statusText:r,headers:n,stream:s}){e.writeHead(t??200,r,n);const o=s.getReader();(async()=>{try{for(;;){const{done:u,value:d}=await o.read();if(u)break;e.write(d)||await new Promise(m=>{e.once("drain",m)})}}catch(u){throw u}finally{e.end()}})()}function fv({response:e,status:t,statusText:r,headers:n,textStream:s}){sd({response:e,status:t,statusText:r,headers:Object.fromEntries(as(n,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:s.pipeThrough(new TextEncoderStream)})}var od=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
28
29`)},flush(e){e.enqueue(`data: [DONE]
30
31`)}})}},id={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function hv({status:e,statusText:t,headers:r,stream:n,consumeSseStream:s}){let o=n.pipeThrough(new od);if(s){const[l,u]=o.tee();o=l,s({stream:u})}return new Response(o.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:as(r,id)})}function mv({originalMessages:e,responseMessageId:t}){if(e==null)return;const r=e[e.length-1];return r?.role==="assistant"?r.id:typeof t=="function"?t():t}var gv=an(()=>Pr(Xe([Qe({type:ge("text-start"),id:D(),providerMetadata:at.optional()}),Qe({type:ge("text-delta"),id:D(),delta:D(),providerMetadata:at.optional()}),Qe({type:ge("text-end"),id:D(),providerMetadata:at.optional()}),Qe({type:ge("error"),errorText:D()}),Qe({type:ge("tool-input-start"),toolCallId:D(),toolName:D(),providerExecuted:Ve().optional(),dynamic:Ve().optional()}),Qe({type:ge("tool-input-delta"),toolCallId:D(),inputTextDelta:D()}),Qe({type:ge("tool-input-available"),toolCallId:D(),toolName:D(),input:Lt(),providerExecuted:Ve().optional(),providerMetadata:at.optional(),dynamic:Ve().optional()}),Qe({type:ge("tool-input-error"),toolCallId:D(),toolName:D(),input:Lt(),providerExecuted:Ve().optional(),providerMetadata:at.optional(),dynamic:Ve().optional(),errorText:D()}),Qe({type:ge("tool-output-available"),toolCallId:D(),output:Lt(),providerExecuted:Ve().optional(),dynamic:Ve().optional(),preliminary:Ve().optional()}),Qe({type:ge("tool-output-error"),toolCallId:D(),errorText:D(),providerExecuted:Ve().optional(),dynamic:Ve().optional()}),Qe({type:ge("reasoning-start"),id:D(),providerMetadata:at.optional()}),Qe({type:ge("reasoning-delta"),id:D(),delta:D(),providerMetadata:at.optional()}),Qe({type:ge("reasoning-end"),id:D(),providerMetadata:at.optional()}),Qe({type:ge("source-url"),sourceId:D(),url:D(),title:D().optional(),providerMetadata:at.optional()}),Qe({type:ge("source-document"),sourceId:D(),mediaType:D(),title:D(),filename:D().optional(),providerMetadata:at.optional()}),Qe({type:ge("file"),url:D(),mediaType:D(),providerMetadata:at.optional()}),Qe({type:Zl(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:D().optional(),data:Lt(),transient:Ve().optional()}),Qe({type:ge("start-step")}),Qe({type:ge("finish-step")}),Qe({type:ge("start"),messageId:D().optional(),messageMetadata:Lt().optional()}),Qe({type:ge("finish"),messageMetadata:Lt().optional()}),Qe({type:ge("abort")}),Qe({type:ge("message-metadata"),messageMetadata:Lt()})])));function vv(e){return e.type.startsWith("data-")}function ld(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const r={...e};for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const s=t[n];if(s===void 0)continue;const o=n in e?e[n]:void 0,l=s!==null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp),u=o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);l&&u?r[n]=ld(o,s):r[n]=s}return r}function yv(e){const t=["ROOT"];let r=-1,n=null;function s(d,f,m){switch(d){case'"':{r=f,t.pop(),t.push(m),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=f,n=f,t.pop(),t.push(m),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(m),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=f,t.pop(),t.push(m),t.push("INSIDE_NUMBER");break}case"{":{r=f,t.pop(),t.push(m),t.push("INSIDE_OBJECT_START");break}case"[":{r=f,t.pop(),t.push(m),t.push("INSIDE_ARRAY_START");break}}}function o(d,f){switch(d){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=f,t.pop();break}}}function l(d,f){switch(d){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=f,t.pop();break}}}for(let d=0;d<e.length;d++){const f=e[d];switch(t[t.length-1]){case"ROOT":s(f,d,"FINISH");break;case"INSIDE_OBJECT_START":{switch(f){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{r=d,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(f){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(f){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(f){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(f,d,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(f,d);break}case"INSIDE_STRING":{switch(f){case'"':{t.pop(),r=d;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:r=d}break}case"INSIDE_ARRAY_START":{switch(f){case"]":{r=d,t.pop();break}default:{r=d,s(f,d,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(f){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=d,t.pop();break}default:{r=d;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(f,d,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),r=d;break}case"INSIDE_NUMBER":{switch(f){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=d;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&l(f,d),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(f,d);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(f,d);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&l(f,d);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const b=e.substring(n,d+1);!"false".startsWith(b)&&!"true".startsWith(b)&&!"null".startsWith(b)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(f,d):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&l(f,d)):r=d;break}}}let u=e.slice(0,r+1);for(let d=t.length-1;d>=0;d--)switch(t[d]){case"INSIDE_STRING":{u+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{u+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{u+="]";break}case"INSIDE_LITERAL":{const m=e.substring(n,e.length);"true".startsWith(m)?u+="true".slice(m.length):"false".startsWith(m)?u+="false".slice(m.length):"null".startsWith(m)&&(u+="null".slice(m.length))}}return u}async function ud(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await en({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await en({text:yv(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Gt(e){return e.type.startsWith("tool-")}function bv(e){return e.type==="dynamic-tool"}function Ja(e){return Gt(e)||bv(e)}function Qa(e){return e.type.split("-").slice(1).join("-")}function cd({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function dd({stream:e,messageMetadataSchema:t,dataPartSchemas:r,runUpdateMessageJob:n,onError:s,onToolCall:o,onData:l}){return e.pipeThrough(new TransformStream({async transform(u,d){await n(async({state:f,write:m})=>{var b,v,y,x;function S(E){const U=f.message.parts.filter(Gt).find(K=>K.toolCallId===E);if(U==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return U}function M(E){const U=f.message.parts.filter(K=>K.type==="dynamic-tool").find(K=>K.toolCallId===E);if(U==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return U}function R(E){var te;const U=f.message.parts.find(me=>Gt(me)&&me.toolCallId===E.toolCallId),K=E,ce=U;U!=null?(U.state=E.state,ce.input=K.input,ce.output=K.output,ce.errorText=K.errorText,ce.rawInput=K.rawInput,ce.preliminary=K.preliminary,ce.providerExecuted=(te=K.providerExecuted)!=null?te:U.providerExecuted,K.providerMetadata!=null&&U.state==="input-available"&&(U.callProviderMetadata=K.providerMetadata)):f.message.parts.push({type:`tool-${E.toolName}`,toolCallId:E.toolCallId,state:E.state,input:K.input,output:K.output,rawInput:K.rawInput,errorText:K.errorText,providerExecuted:K.providerExecuted,preliminary:K.preliminary,...K.providerMetadata!=null?{callProviderMetadata:K.providerMetadata}:{}})}function B(E){var te;const U=f.message.parts.find(me=>me.type==="dynamic-tool"&&me.toolCallId===E.toolCallId),K=E,ce=U;U!=null?(U.state=E.state,ce.toolName=E.toolName,ce.input=K.input,ce.output=K.output,ce.errorText=K.errorText,ce.rawInput=(te=K.rawInput)!=null?te:ce.rawInput,ce.preliminary=K.preliminary,K.providerMetadata!=null&&U.state==="input-available"&&(U.callProviderMetadata=K.providerMetadata)):f.message.parts.push({type:"dynamic-tool",toolName:E.toolName,toolCallId:E.toolCallId,state:E.state,input:K.input,output:K.output,errorText:K.errorText,preliminary:K.preliminary,...K.providerMetadata!=null?{callProviderMetadata:K.providerMetadata}:{}})}async function V(E){if(E!=null){const te=f.message.metadata!=null?ld(f.message.metadata,E):E;t!=null&&await ro({value:te,schema:t}),f.message.metadata=te}}switch(u.type){case"text-start":{const E={type:"text",text:"",providerMetadata:u.providerMetadata,state:"streaming"};
31f.activeTextParts[u.id]=E,f.message.parts.push(E),m();break}case"text-delta":{const E=f.activeTextParts[u.id];E.text+=u.delta,E.providerMetadata=(b=u.providerMetadata)!=null?b:E.providerMetadata,m();break}case"text-end":{const E=f.activeTextParts[u.id];E.state="done",E.providerMetadata=(v=u.providerMetadata)!=null?v:E.providerMetadata,delete f.activeTextParts[u.id],m();break}case"reasoning-start":{const E={type:"reasoning",text:"",providerMetadata:u.providerMetadata,state:"streaming"};f.activeReasoningParts[u.id]=E,f.message.parts.push(E),m();break}case"reasoning-delta":{const E=f.activeReasoningParts[u.id];E.text+=u.delta,E.providerMetadata=(y=u.providerMetadata)!=null?y:E.providerMetadata,m();break}case"reasoning-end":{const E=f.activeReasoningParts[u.id];E.providerMetadata=(x=u.providerMetadata)!=null?x:E.providerMetadata,E.state="done",delete f.activeReasoningParts[u.id],m();break}case"file":{f.message.parts.push({type:"file",mediaType:u.mediaType,url:u.url}),m();break}case"source-url":{f.message.parts.push({type:"source-url",sourceId:u.sourceId,url:u.url,title:u.title,providerMetadata:u.providerMetadata}),m();break}case"source-document":{f.message.parts.push({type:"source-document",sourceId:u.sourceId,mediaType:u.mediaType,title:u.title,filename:u.filename,providerMetadata:u.providerMetadata}),m();break}case"tool-input-start":{const E=f.message.parts.filter(Gt);f.partialToolCalls[u.toolCallId]={text:"",toolName:u.toolName,index:E.length,dynamic:u.dynamic},u.dynamic?B({toolCallId:u.toolCallId,toolName:u.toolName,state:"input-streaming",input:void 0}):R({toolCallId:u.toolCallId,toolName:u.toolName,state:"input-streaming",input:void 0,providerExecuted:u.providerExecuted}),m();break}case"tool-input-delta":{const E=f.partialToolCalls[u.toolCallId];E.text+=u.inputTextDelta;const{value:te}=await ud(E.text);E.dynamic?B({toolCallId:u.toolCallId,toolName:E.toolName,state:"input-streaming",input:te}):R({toolCallId:u.toolCallId,toolName:E.toolName,state:"input-streaming",input:te}),m();break}case"tool-input-available":{u.dynamic?B({toolCallId:u.toolCallId,toolName:u.toolName,state:"input-available",input:u.input,providerMetadata:u.providerMetadata}):R({toolCallId:u.toolCallId,toolName:u.toolName,state:"input-available",input:u.input,providerExecuted:u.providerExecuted,providerMetadata:u.providerMetadata}),m(),o&&!u.providerExecuted&&await o({toolCall:u});break}case"tool-input-error":{u.dynamic?B({toolCallId:u.toolCallId,toolName:u.toolName,state:"output-error",input:u.input,errorText:u.errorText,providerMetadata:u.providerMetadata}):R({toolCallId:u.toolCallId,toolName:u.toolName,state:"output-error",input:void 0,rawInput:u.input,errorText:u.errorText,providerExecuted:u.providerExecuted,providerMetadata:u.providerMetadata}),m();break}case"tool-output-available":{if(u.dynamic){const E=M(u.toolCallId);B({toolCallId:u.toolCallId,toolName:E.toolName,state:"output-available",input:E.input,output:u.output,preliminary:u.preliminary})}else{const E=S(u.toolCallId);R({toolCallId:u.toolCallId,toolName:Qa(E),state:"output-available",input:E.input,output:u.output,providerExecuted:u.providerExecuted,preliminary:u.preliminary})}m();break}case"tool-output-error":{if(u.dynamic){const E=M(u.toolCallId);B({toolCallId:u.toolCallId,toolName:E.toolName,state:"output-error",input:E.input,errorText:u.errorText})}else{const E=S(u.toolCallId);R({toolCallId:u.toolCallId,toolName:Qa(E),state:"output-error",input:E.input,rawInput:E.rawInput,errorText:u.errorText})}m();break}case"start-step":{f.message.parts.push({type:"step-start"});break}case"finish-step":{f.activeTextParts={},f.activeReasoningParts={};break}case"start":{u.messageId!=null&&(f.message.id=u.messageId),await V(u.messageMetadata),(u.messageId!=null||u.messageMetadata!=null)&&m();break}case"finish":{await V(u.messageMetadata),u.messageMetadata!=null&&m();break}case"message-metadata":{await V(u.messageMetadata),u.messageMetadata!=null&&m();break}case"error":{s?.(new Error(u.errorText));break}default:if(vv(u)){r?.[u.type]!=null&&await ro({value:u.data,schema:r[u.type]});const E=u;if(E.transient){l?.(E);break}const te=E.id!=null?f.message.parts.find(U=>E.type===U.type&&E.id===U.id):void 0;te!=null?te.data=E.data:f.message.parts.push(E),l?.(E),m()}}d.enqueue(u)})}}))}function wv({messageId:e,originalMessages:t=[],onFinish:r,onError:n,stream:s}){let o=t?.[t.length-1];o?.role!=="assistant"?o=void 0:e=o.id;let l=!1;const u=s.pipeThrough(new TransformStream({transform(v,y){if(v.type==="start"){const x=v;x.messageId==null&&e!=null&&(x.messageId=e)}v.type==="abort"&&(l=!0),y.enqueue(v)}}));if(r==null)return u;const d=cd({lastMessage:o?structuredClone(o):void 0,messageId:e??""}),f=async v=>{await v({state:d,write:()=>{}})};let m=!1;const b=async()=>
31{if(m||!r)return;m=!0;const v=d.message.id===o?.id;await r({isAborted:l,isContinuation:v,responseMessage:d.message,messages:[...v?t.slice(0,-1):t,d.message]})};return dd({stream:u,runUpdateMessageJob:f,onError:n}).pipeThrough(new TransformStream({transform(v,y){y.enqueue(v)},async cancel(){await b()},async flush(){await b()}}))}function _v({response:e,status:t,statusText:r,headers:n,stream:s,consumeSseStream:o}){let l=s.pipeThrough(new od);if(o){const[u,d]=l.tee();l=u,o({stream:d})}sd({response:e,status:t,statusText:r,headers:Object.fromEntries(as(n,id).entries()),stream:l.pipeThrough(new TextEncoderStream)})}function Na(e){const t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){const r=this.getReader();let n=!1;async function s(o){var l;n=!0;try{o&&await((l=r.cancel)==null?void 0:l.call(r))}finally{try{r.releaseLock()}catch{}}}return{async next(){if(n)return{done:!0,value:void 0};const{done:o,value:l}=await r.read();return o?(await s(!0),{done:!0,value:void 0}):{done:!1,value:l}},async return(){return await s(!0),{done:!0,value:void 0}},async throw(o){throw await s(!0),o}}},t}async function pd({stream:e,onError:t}){const r=e.getReader();try{for(;;){const{done:n}=await r.read();if(n)break}}catch(n){t?.(n)}finally{r.releaseLock()}}function vl(){let e,t;return{promise:new Promise((n,s)=>{e=n,t=s}),resolve:e,reject:t}}function xv(){let e=[],t=null,r=!1,n=vl();const s=()=>{r=!0,n.resolve(),e.forEach(l=>l.cancel()),e=[],t?.close()},o=async()=>{if(r&&e.length===0){t?.close();return}if(e.length===0)return n=vl(),await n.promise,o();try{const{value:l,done:u}=await e[0].read();u?(e.shift(),e.length>0?await o():r&&t?.close()):t?.enqueue(l)}catch(l){t?.error(l),e.shift(),s()}};return{stream:new ReadableStream({start(l){t=l},pull:o,async cancel(){for(const l of e)await l.cancel();e=[],r=!0}}),addStream:l=>{if(r)throw new Error("Cannot add inner stream: outer stream is closed");e.push(l.getReader()),n.resolve()},close:()=>{r=!0,n.resolve(),e.length===0&&t?.close()},terminate:s}}var ja=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(this._promise=new Promise((e,t)=>{this.status.type==="resolved"?e(this.status.value):this.status.type==="rejected"&&t(this.status.error),this._resolve=e,this._reject=t}),this._promise)}resolve(e){var t;this.status={type:"resolved",value:e},this._promise&&((t=this._resolve)==null||t.call(this,e))}reject(e){var t;this.status={type:"rejected",error:e},this._promise&&((t=this._reject)==null||t.call(this,e))}};function kv(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}function Sv({tools:e,generatorStream:t,tracer:r,telemetry:n,system:s,messages:o,abortSignal:l,repairToolCall:u,experimental_context:d}){let f=null;const m=new ReadableStream({start(R){f=R}}),b=new Set,v=new Map;let y=!1,x;function S(){y&&b.size===0&&(x!=null&&f.enqueue(x),f.close())}const M=new TransformStream({async transform(R,B){const V=R.type;switch(V){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":{B.enqueue(R);break}case"file":{B.enqueue({type:"file",file:new iv({data:R.data,mediaType:R.mediaType})});break}case"finish":{x={type:"finish",finishReason:R.finishReason,usage:R.usage,providerMetadata:R.providerMetadata};break}case"tool-call":{try{const E=await lv({toolCall:R,tools:e,repairToolCall:u,system:s,messages:o});if(B.enqueue(E),E.invalid){f.enqueue({type:"tool-error",toolCallId:E.toolCallId,toolName:E.toolName,input:E.input,error:Ku(E.error),dynamic:!0});break}const te=e[E.toolName];if(v.set(E.toolCallId,E.input),te.onInputAvailable!=null&&await te.onInputAvailable({input:E.input,toolCallId:E.toolCallId,messages:o,abortSignal:l,experimental_context:d}),te.execute!=null&&E.providerExecuted!==!0){const U=yn();b.add(U),uo({name:"ai.toolCall",attributes:bn({telemetry:n,attributes:{...lo({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":E.toolName,"ai.toolCall.id":E.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(E.input)}}}),tracer:r,fn:async K=>{let ce;try{const me=Gh({execute:te.execute.bind(te),input:E.input,options:{toolCallId:E.toolCallId,messages:o,abortSignal:l,experimental_context:d}});for await(const de of me)f.enqueue({...E,type:"tool-result",output:de.output,...de.type==="preliminary"&&{preliminary:!0}}),de.type==="final"&&(ce=de.output)}catch(me){nd(K,me),f.enqueue({...E,type:"tool-error",error:me}),b.delete(U),S();return}b.delete(U),S();try{K.setAttributes(bn({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(ce)}}}))}catch{}}})}}catch(E){f.enqueue({type:"error",error:E})}break}case"tool-result":{const E=R.toolName;R.isError?f.enqueue({type:"tool-error",toolCallId:R.toolCallId,toolName:E,input:v.get(R.toolCallId),providerExecuted:R.providerExecuted,error:R.result}):B.enqueue({type:"tool-result",toolCallId:R.toolCallId,toolName:E,input:v.get(R.toolCallId),output:R.result,providerExecuted:R.providerExecuted});break}default:{const E=V;throw new Error(`Unhandled chunk type: ${E}`)}}},flush(){y=!0,S()}});return new ReadableStream({async start(R){return Promise.all([t.pipeThrough(M).pipeTo(new WritableStream({write(B){R.enqueue(B)},close(){}})),m.pipeTo(new WritableStream({write(B){R.enqueue(B)},close(){R.close()}}))])}})}var Iv=ua({prefix:"aitxt",size:24});function Tv({model:e,tools:t,toolChoice:r,system:n,prompt:s,messages:o,maxRetries:l,abortSignal:u,headers:d,stopWhen:f=cv(1),experimental_output:m,experimental_telemetry:b,prepareStep:v,providerOptions:y,experimental_activeTools:x,activeTools:S=x,experimental_repairToolCall:M,experimental_transform:R,experimental_download:B,includeRawChunks:V=!1,onChunk:E,onError:te=({error:Ce})=>{console.error(Ce)},onFinish:U,onAbort:K,onStepFinish:ce,experimental_context:me,_internal:{now:de=kv,generateId:he=Iv,currentDate:ve=()=>new Date}={},...ke}){return new Av({model:Qc(e),telemetry:b,headers:d,settings:ke,maxRetries:l,abortSignal:u,system:n,prompt:s,messages:o,tools:t,toolChoice:r,transforms:fl(R),activeTools:S,repairToolCall:M,stopConditions:fl(f),output:m,providerOptions:y,prepareStep:v,includeRawChunks:V,onChunk:E,onError:te,onFinish:U,onAbort:K,onStepFinish:ce,now:de,currentDate:ve,generateId:he,experimental_context:me,download:B})}function Ev(e){if(!e)return new TransformStream({transform(l,u){u.enqueue({part:l,partialOutput:void 0})}});let t,r="",n="",s="";function o({controller:l,partialOutput:u=void 0}){l.enqueue({part:{type:"text-delta",id:t,text:n},partialOutput:u}),n=""}return new TransformStream({async transform(l,u){if(l.type==="finish-step"&&n.length>0&&o({controller:u}),l.type!=="text-delta"&&l.type!=="text-start"&&l.type!=="text-end"){u.enqueue({part:l,partialOutput:void 0});return}if(t==null)t=l.id;else if(l.id!==t){u.enqueue({part:l,partialOutput:void 0});return}if(l.type==="text-start"){u.enqueue({part:l,partialOutput:void 0});return}if(l.type==="text-end"){n.length>0&&o({controller:u}),u.enqueue({part:l,partialOutput:void 0});return}r+=l.text,n+=l.text;const d=await e.parsePartial({text:r});if(d!=null){const f=JSON.stringify(d.partial);f!==s&&(o({controller:u,partialOutput:d.partial}),s=f)}}})}var Av=class{constructor({model:e,telemetry:t,headers:r,settings:n,maxRetries:s,abortSignal:o,system:l,prompt:u,messages:d,tools:f,toolChoice:m,transforms:b,activeTools:v,repairToolCall:y,stopConditions:x,output:S,providerOptions:M,prepareStep:R,includeRawChunks:B,now:V,currentDate:E,generateId:te,onChunk:U,onError:K,onFinish:ce,onAbort:me,onStepFinish:de,experimental_context:he,download:ve}){this._totalUsage=new ja,this._finishReason=new ja,this._steps=new ja,this.output=S,this.includeRawChunks=B,this.tools=f;let ke,Ce=[];const pt=[];let lt,Ct,H={},pe=[];const ne=[];let je,qe={},et={};const Le=new TransformStream({async transform(Ge,De){var Pe,Ae,bt,jt;De.enqueue(Ge);const{part:se}=Ge;if((se.type==="text-delta"||se.type==="reasoning-delta"||se.type==="source"||se.type==="tool-call"||se.type==="tool-result"||se.type==="tool-input-start"||se.type==="tool-input-delta"||se.type==="raw")&&await U?.({chunk:se}),se.type==="error"&&await K({error:Jg(se.error)}),se.type==="text-start"&&(qe[se.id]={type:"text",text:"",providerMetadata:se.providerMetadata},Ce.push(qe[se.id])),se.type==="text-delta"){const Ee=qe[se.id];if(Ee==null){De.enqueue({part:{type:"error",error:`text part ${se.id} not found`},partialOutput:void 0});return}Ee.text+=se.text,Ee.providerMetadata=(Pe=se.providerMetadata)!=null?Pe:Ee.providerMetadata}if(se.type==="text-end"){const Ee=qe[se.id];if(Ee==null){De.enqueue({part:{type:"error",error:`text part ${se.id} not found`},partialOutput:void 0});return}Ee.providerMetadata=(Ae=se.providerMetadata)!=null?Ae:Ee.providerMetadata,delete qe[se.id]}if(se.type==="reasoning-start"&&(et[se.id]={type:"reasoning",text:"",providerMetadata:se.providerMetadata},Ce.push(et[se.id])),se.type==="reasoning-delta"){const Ee=et[se.id];if(Ee==null){De.enqueue({part:{type:"error",error:`reasoning part ${se.id} not found`},partialOutput:void 0});return}Ee.text+=se.text,Ee.providerMetadata=(bt=se.providerMetadata)!=null?bt:Ee.providerMetadata}if(se.type==="reasoning-end"){const Ee=et[se.id];if(Ee==null){De.enqueue({part:{type:"error",error:`reasoning part ${se.id} not found`},partialOutput:void 0});return}Ee.providerMetadata=(jt=se.providerMetadata)!=null?jt:Ee.providerMetadata,delete et[se.id]}if(se.type==="file"&&Ce.push({type:"file",file:se.file}),se.type==="source"&&Ce.push(se),se.type==="tool-call"&&Ce.push(se),se.type==="tool-result"&&!se.preliminary&&Ce.push(se),se.type==="tool-error"&&Ce.push(se),se.type==="start-step"&&(H=se.request,pe=se.w
31arnings),se.type==="finish-step"){const Ee=gl({content:Ce,tools:f}),gr=new uv({content:Ce,finishReason:se.finishReason,usage:se.usage,warnings:pe,request:H,response:{...se.response,messages:[...pt,...Ee]},providerMetadata:se.providerMetadata});await de?.(gr),lg(pe),ne.push(gr),Ce=[],et={},qe={},pt.push(...Ee),ke.resolve()}se.type==="finish"&&(Ct=se.totalUsage,lt=se.finishReason)},async flush(Ge){try{if(ne.length===0){const bt=new fg({message:"No output generated. Check the stream for errors."});Re._finishReason.reject(bt),Re._totalUsage.reject(bt),Re._steps.reject(bt);return}const De=lt??"unknown",Pe=Ct??{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};Re._finishReason.resolve(De),Re._totalUsage.resolve(Pe),Re._steps.resolve(ne);const Ae=ne[ne.length-1];await ce?.({finishReason:De,totalUsage:Pe,usage:Ae.usage,content:Ae.content,text:Ae.text,reasoningText:Ae.reasoningText,reasoning:Ae.reasoning,files:Ae.files,sources:Ae.sources,toolCalls:Ae.toolCalls,staticToolCalls:Ae.staticToolCalls,dynamicToolCalls:Ae.dynamicToolCalls,toolResults:Ae.toolResults,staticToolResults:Ae.staticToolResults,dynamicToolResults:Ae.dynamicToolResults,request:Ae.request,response:Ae.response,warnings:Ae.warnings,providerMetadata:Ae.providerMetadata,steps:ne}),je.setAttributes(bn({telemetry:t,attributes:{"ai.response.finishReason":De,"ai.response.text":{output:()=>Ae.text},"ai.response.toolCalls":{output:()=>{var bt;return(bt=Ae.toolCalls)!=null&&bt.length?JSON.stringify(Ae.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(Ae.providerMetadata),"ai.usage.inputTokens":Pe.inputTokens,"ai.usage.outputTokens":Pe.outputTokens,"ai.usage.totalTokens":Pe.totalTokens,"ai.usage.reasoningTokens":Pe.reasoningTokens,"ai.usage.cachedInputTokens":Pe.cachedInputTokens}}))}catch(De){Ge.error(De)}finally{je.end()}}}),Y=xv();this.addStream=Y.addStream,this.closeStream=Y.close;const le=Y.stream.getReader();let Ie=new ReadableStream({async start(Ge){Ge.enqueue({type:"start"})},async pull(Ge){function De(){me?.({steps:ne}),Ge.enqueue({type:"abort"}),Ge.close()}try{const{done:Pe,value:Ae}=await le.read();if(Pe){Ge.close();return}if(o?.aborted){De();return}Ge.enqueue(Ae)}catch(Pe){Yr(Pe)&&o?.aborted?De():Ge.error(Pe)}},cancel(Ge){return Y.stream.cancel(Ge)}});for(const Ge of b)Ie=Ie.pipeThrough(Ge({tools:f,stopStream(){Y.terminate()}}));this.baseStream=Ie.pipeThrough(Ev(S)).pipeThrough(Le);const{maxRetries:$e,retry:Q}=sv({maxRetries:s,abortSignal:o}),We=ev(t),st=Dg(n),ye=Qg({model:e,telemetry:t,headers:r,settings:{...st,maxRetries:$e}}),Re=this;uo({name:"ai.streamText",attributes:bn({telemetry:t,attributes:{...lo({operationId:"ai.streamText",telemetry:t}),...ye,"ai.prompt":{input:()=>JSON.stringify({system:l,prompt:u,messages:d})}}}),tracer:We,endWhenDone:!1,fn:async Ge=>{je=Ge;async function De({currentStep:Pe,responseMessages:Ae,usage:bt}){var jt,se,Ee,gr,vr;const En=Re.includeRawChunks;ke=new ja;const yr=await Hg({system:l,prompt:u,messages:d}),Rt=[...yr.messages,...Ae],ut=await R?.({model:e,steps:ne,stepNumber:ne.length,messages:Rt}),Wt=Qc((jt=ut?.model)!=null?jt:e),br=await Mg({prompt:{system:(se=ut?.system)!=null?se:yr.system,messages:(Ee=ut?.messages)!=null?Ee:Rt},supportedUrls:await Wt.supportedUrls,download:ve}),{toolChoice:Mr,tools:wr}=qg({tools:f,toolChoice:(gr=ut?.toolChoice)!=null?gr:m,activeTools:(vr=ut?.activeTools)!=null?vr:v}),{result:{stream:rr,response:Nr,request:on},doStreamSpan:wt,startTimestampMs:ue}=await Q(()=>uo({name:"ai.streamText.doStream",attributes:bn({telemetry:t,attributes:{...lo({operationId:"ai.streamText.doStream",telemetry:t}),...ye,"ai.model.provider":Wt.provider,"ai.model.id":Wt.modelId,"ai.prompt.messages":{input:()=>tv(br)},"ai.prompt.tools":{input:()=>wr?.map(fe=>JSON.stringify(fe))},"ai.prompt.toolChoice":{input:()=>Mr!=null?JSON.stringify(Mr):void 0},"gen_ai.system":Wt.provider,"gen_ai.request.model":Wt.modelId,"gen_ai.request.frequency_penalty":st.frequencyPenalty,"gen_ai.request.max_tokens":st.maxOutputTokens,"gen_ai.request.presence_penalty":st.presencePenalty,"gen_ai.request.stop_sequences":st.stopSequences,"gen_ai.request.temperature":st.temperature,"gen_ai.request.top_k":st.topK,"gen_ai.request.top_p":st.topP}}),tracer:We,endWhenDone:!1,fn:async fe=>({startTimestampMs:V(),doStreamSpan:fe,result:await Wt.doStream({...st,tools:wr,toolChoice:Mr,responseFormat:S?.responseFormat,prompt:br,providerOptions:M,abortSignal:o,headers:r,includeRawChunks:En})})})),jr=Sv({tools:f,generatorStream:rr,tracer:We,telemetry:t,system:l,messages:Rt,repairToolCall:y,abort
31Signal:o,experimental_context:he}),nr=on??{},ar=[],X=[];let $r;const ln={};let Ht="unknown",Tt={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},Dr,pa=!0,$t={id:te(),timestamp:E(),modelId:e.modelId},sr="";Re.addStream(jr.pipeThrough(new TransformStream({async transform(fe,tt){var Jt,Be,Je,Ut;if(fe.type==="stream-start"){$r=fe.warnings;return}if(pa){const ot=V()-ue;pa=!1,wt.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":ot}),wt.setAttributes({"ai.response.msToFirstChunk":ot}),tt.enqueue({type:"start-step",request:nr,warnings:$r??[]})}const Fr=fe.type;switch(Fr){case"text-start":case"text-end":{tt.enqueue(fe);break}case"text-delta":{fe.delta.length>0&&(tt.enqueue({type:"text-delta",id:fe.id,text:fe.delta,providerMetadata:fe.providerMetadata}),sr+=fe.delta);break}case"reasoning-start":case"reasoning-end":{tt.enqueue(fe);break}case"reasoning-delta":{tt.enqueue({type:"reasoning-delta",id:fe.id,text:fe.delta,providerMetadata:fe.providerMetadata});break}case"tool-call":{tt.enqueue(fe),ar.push(fe);break}case"tool-result":{tt.enqueue(fe),fe.preliminary||X.push(fe);break}case"tool-error":{tt.enqueue(fe),X.push(fe);break}case"response-metadata":{$t={id:(Jt=fe.id)!=null?Jt:$t.id,timestamp:(Be=fe.timestamp)!=null?Be:$t.timestamp,modelId:(Je=fe.modelId)!=null?Je:$t.modelId};break}case"finish":{Tt=fe.usage,Ht=fe.finishReason,Dr=fe.providerMetadata;const ot=V()-ue;wt.addEvent("ai.stream.finish"),wt.setAttributes({"ai.response.msToFinish":ot,"ai.response.avgOutputTokensPerSecond":1e3*((Ut=Tt.outputTokens)!=null?Ut:0)/ot});break}case"file":{tt.enqueue(fe);break}case"source":{tt.enqueue(fe);break}case"tool-input-start":{ln[fe.id]=fe.toolName;const ot=f?.[fe.toolName];ot?.onInputStart!=null&&await ot.onInputStart({toolCallId:fe.id,messages:Rt,abortSignal:o,experimental_context:he}),tt.enqueue({...fe,dynamic:ot?.type==="dynamic"});break}case"tool-input-end":{delete ln[fe.id],tt.enqueue(fe);break}case"tool-input-delta":{const ot=ln[fe.id],_r=f?.[ot];_r?.onInputDelta!=null&&await _r.onInputDelta({inputTextDelta:fe.delta,toolCallId:fe.id,messages:Rt,abortSignal:o,experimental_context:he}),tt.enqueue(fe);break}case"error":{tt.enqueue(fe),Ht="error";break}case"raw":{En&&tt.enqueue(fe);break}default:{const ot=Fr;throw new Error(`Unknown chunk type: ${ot}`)}}},async flush(fe){const tt=ar.length>0?JSON.stringify(ar):void 0;try{wt.setAttributes(bn({telemetry:t,attributes:{"ai.response.finishReason":Ht,"ai.response.text":{output:()=>sr},"ai.response.toolCalls":{output:()=>tt},"ai.response.id":$t.id,"ai.response.model":$t.modelId,"ai.response.timestamp":$t.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Dr),"ai.usage.inputTokens":Tt.inputTokens,"ai.usage.outputTokens":Tt.outputTokens,"ai.usage.totalTokens":Tt.totalTokens,"ai.usage.reasoningTokens":Tt.reasoningTokens,"ai.usage.cachedInputTokens":Tt.cachedInputTokens,"gen_ai.response.finish_reasons":[Ht],"gen_ai.response.id":$t.id,"gen_ai.response.model":$t.modelId,"gen_ai.usage.input_tokens":Tt.inputTokens,"gen_ai.usage.output_tokens":Tt.outputTokens}}))}catch{}finally{wt.end()}fe.enqueue({type:"finish-step",finishReason:Ht,usage:Tt,providerMetadata:Dr,response:{...$t,headers:Nr?.headers}});const Jt=rv(bt,Tt);await ke.promise;const Be=ar.filter(Ut=>Ut.providerExecuted!==!0),Je=X.filter(Ut=>Ut.providerExecuted!==!0);if(Be.length>0&&Je.length===Be.length&&!await dv({stopConditions:x,steps:ne})){Ae.push(...gl({content:ne[ne.length-1].content,tools:f}));try{await De({currentStep:Pe+1,responseMessages:Ae,usage:Jt})}catch(Ut){fe.enqueue({type:"error",error:Ut}),Re.closeStream()}}else fe.enqueue({type:"finish",finishReason:Ht,totalUsage:Jt}),Re.closeStream()}})))}await De({currentStep:0,responseMessages:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0}})}}).catch(Ge=>{Re.addStream(new ReadableStream({start(De){De.enqueue({type:"error",error:Ge}),De.close()}})),Re.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(e=>e[e.length-1])}get content(){return this.finalStep.then(e=>e.content)}get warnings(){return this.finalStep.then(e=>e.warnings)}get providerMetadata(){return this.finalStep.then(e=>e.providerMetadata)}get text(){return this.finalStep.then(e=>e.text)}get reasoningText(){return this.finalStep.then(e=>e.reasoningText)}get reasoning(){return this.finalStep.then(e=>e.reasoning)}get sources(){return this.finalStep.then(e=>e.sources)}get files(){return this.finalStep.then(e=>e.files)}get toolCalls(){return this.finalStep.then(e=>e.toolCalls)}get staticToolCalls(){return this.finalStep.then(e=>e.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(e=>e.dynamicToolCalls)}get toolResults(){return this.finalStep.then(e=>e.toolResults)}get staticToolResults(){return this.finalStep.then(e=>e.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(e=>e.dynamicToolResults)}get usage(){return this.finalStep.then(e=>e.usage)}get request(){return this.finalStep.then(e=>e.request)}get response(){return this.finalStep.then(e=>e.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}teeStream(){const[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return Na(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}}
31)))}get fullStream(){return Na(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await pd({stream:this.fullStream,onError:e?.onError})}catch(r){(t=e?.onError)==null||t.call(e,r)}}get experimental_partialOutputStream(){if(this.output==null)throw new sg;return Na(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){e!=null&&t.enqueue(e)}})))}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:s=!0,sendSources:o=!1,sendStart:l=!0,sendFinish:u=!0,onError:d=In}={}){const f=t!=null?mv({originalMessages:e,responseMessageId:t}):void 0,m={},b=y=>{var x,S;const M=m[y];return((S=(x=this.tools)==null?void 0:x[M])==null?void 0:S.type)==="dynamic"?!0:void 0},v=this.fullStream.pipeThrough(new TransformStream({transform:async(y,x)=>{const S=n?.({part:y}),M=y.type;switch(M){case"text-start":{x.enqueue({type:"text-start",id:y.id,...y.providerMetadata!=null?{providerMetadata:y.providerMetadata}:{}});break}case"text-delta":{x.enqueue({type:"text-delta",id:y.id,delta:y.text,...y.providerMetadata!=null?{providerMetadata:y.providerMetadata}:{}});break}case"text-end":{x.enqueue({type:"text-end",id:y.id,...y.providerMetadata!=null?{providerMetadata:y.providerMetadata}:{}});break}case"reasoning-start":{x.enqueue({type:"reasoning-start",id:y.id,...y.providerMetadata!=null?{providerMetadata:y.providerMetadata}:{}});break}case"reasoning-delta":{s&&x.enqueue({type:"reasoning-delta",id:y.id,delta:y.text,...y.providerMetadata!=null?{providerMetadata:y.providerMetadata}:{}});break}case"reasoning-end":{x.enqueue({type:"reasoning-end",id:y.id,...y.providerMetadata!=null?{providerMetadata:y.providerMetadata}:{}});break}case"file":{x.enqueue({type:"file",mediaType:y.file.mediaType,url:`data:${y.file.mediaType};base64,${y.file.base64}`});break}case"source":{o&&y.sourceType==="url"&&x.enqueue({type:"source-url",sourceId:y.id,url:y.url,title:y.title,...y.providerMetadata!=null?{providerMetadata:y.providerMetadata}:{}}),o&&y.sourceType==="document"&&x.enqueue({type:"source-document",sourceId:y.id,mediaType:y.mediaType,title:y.title,filename:y.filename,...y.providerMetadata!=null?{providerMetadata:y.providerMetadata}:{}});break}case"tool-input-start":{m[y.id]=y.toolName;const R=b(y.id);x.enqueue({type:"tool-input-start",toolCallId:y.id,toolName:y.toolName,...y.providerExecuted!=null?{providerExecuted:y.providerExecuted}:{},...R!=null?{dynamic:R}:{}});break}case"tool-input-delta":{x.enqueue({type:"tool-input-delta",toolCallId:y.id,inputTextDelta:y.delta});break}case"tool-call":{m[y.toolCallId]=y.toolName;const R=b(y.toolCallId);y.invalid?x.enqueue({type:"tool-input-error",toolCallId:y.toolCallId,toolName:y.toolName,input:y.input,...y.providerExecuted!=null?{providerExecuted:y.providerExecuted}:{},...y.providerMetadata!=null?{providerMetadata:y.providerMetadata}:{},...R!=null?{dynamic:R}:{},errorText:d(y.error)}):x.enqueue({type:"tool-input-available",toolCallId:y.toolCallId,toolName:y.toolName,input:y.input,...y.providerExecuted!=null?{providerExecuted:y.providerExecuted}:{},...y.providerMetadata!=null?{providerMetadata:y.providerMetadata}:{},...R!=null?{dynamic:R}:{}});break}case"tool-result":{const R=b(y.toolCallId);x.enqueue({type:"tool-output-available",toolCallId:y.toolCallId,output:y.output,...y.providerExecuted!=null?{providerExecuted:y.providerExecuted}:{},...y.preliminary!=null?{preliminary:y.preliminary}:{},...R!=null?{dynamic:R}:{}});break}case"tool-error":{const R=b(y.toolCallId);x.enqueue({type:"tool-output-error",toolCallId:y.toolCallId,errorText:d(y.error),...y.providerExecuted!=null?{providerExecuted:y.providerExecuted}:{},...R!=null?{dynamic:R}:{}});break}case"error":{x.enqueue({type:"error",errorText:d(y.error)});break}case"start-step":{x.enqueue({type:"start-step"});break}case"finish-step":{x.enqueue({type:"finish-step"});break}case"start":{l&&x.enqueue({type:"start",...S!=null?{messageMetadata:S}:{},...f!=null?{messageId:f}:{}});break}case"finish":{u&&x.enqueue({type:"finish",...S!=null?{messageMetadata:S}:{}});break}case"abort":{x.enqueue(y);break}case"tool-input-end":break;case"raw":break;default:{const R=M;throw new Error(`Unknown chunk type: ${R}`)}}S!=null&&M!=="start"&&M!=="finish"&&x.enqueue({type:"message-metadata",messageMetadata:S})}}));
31return Na(wv({stream:v,messageId:f??t?.(),originalMessages:e,onFinish:r,onError:d}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:s,sendReasoning:o,sendSources:l,sendFinish:u,sendStart:d,onError:f,...m}={}){_v({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:s,sendReasoning:o,sendSources:l,sendFinish:u,sendStart:d,onError:f}),...m})}pipeTextStreamToResponse(e,t){fv({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:s,sendSources:o,sendFinish:l,sendStart:u,onError:d,...f}={}){return hv({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:s,sendSources:o,sendFinish:l,sendStart:u,onError:d}),...f})}toTextStreamResponse(e){return pv({textStream:this.textStream,...e})}};function Cv(e,t){const r=[];t?.ignoreIncompleteToolCalls&&(e=e.map(n=>({...n,parts:n.parts.filter(s=>!Ja(s)||s.state!=="input-streaming"&&s.state!=="input-available")})));for(const n of e)switch(n.role){case"system":{const s=n.parts.filter(l=>l.type==="text"),o=s.reduce((l,u)=>u.providerMetadata!=null?{...l,...u.providerMetadata}:l,{});r.push({role:"system",content:s.map(l=>l.text).join(""),...Object.keys(o).length>0?{providerOptions:o}:{}});break}case"user":{r.push({role:"user",content:n.parts.filter(s=>s.type==="text"||s.type==="file").map(s=>{switch(s.type){case"text":return{type:"text",text:s.text,...s.providerMetadata!=null?{providerOptions:s.providerMetadata}:{}};case"file":return{type:"file",mediaType:s.mediaType,filename:s.filename,data:s.url,...s.providerMetadata!=null?{providerOptions:s.providerMetadata}:{}};default:return s}})});break}case"assistant":{if(n.parts!=null){let s=function(){var l,u;if(o.length===0)return;const d=[];for(const m of o)if(m.type==="text")d.push({type:"text",text:m.text,...m.providerMetadata!=null?{providerOptions:m.providerMetadata}:{}});else if(m.type==="file")d.push({type:"file",mediaType:m.mediaType,filename:m.filename,data:m.url});else if(m.type==="reasoning")d.push({type:"reasoning",text:m.text,providerOptions:m.providerMetadata});else if(m.type==="dynamic-tool"){const b=m.toolName;m.state!=="input-streaming"&&d.push({type:"tool-call",toolCallId:m.toolCallId,toolName:b,input:m.input,...m.callProviderMetadata!=null?{providerOptions:m.callProviderMetadata}:{}})}else if(Gt(m)){const b=Qa(m);m.state!=="input-streaming"&&(d.push({type:"tool-call",toolCallId:m.toolCallId,toolName:b,input:m.state==="output-error"?(l=m.input)!=null?l:m.rawInput:m.input,providerExecuted:m.providerExecuted,...m.callProviderMetadata!=null?{providerOptions:m.callProviderMetadata}:{}}),m.providerExecuted===!0&&(m.state==="output-available"||m.state==="output-error")&&d.push({type:"tool-result",toolCallId:m.toolCallId,toolName:b,output:Hn({output:m.state==="output-error"?m.errorText:m.output,tool:(u=t?.tools)==null?void 0:u[b],errorMode:m.state==="output-error"?"json":"none"})}))}else{const b=m;throw new Error(`Unsupported part: ${b}`)}r.push({role:"assistant",content:d});const f=o.filter(m=>Gt(m)&&m.providerExecuted!==!0||m.type==="dynamic-tool");f.length>0&&r.push({role:"tool",content:f.map(m=>{var b;switch(m.state){case"output-error":case"output-available":{const v=m.type==="dynamic-tool"?m.toolName:Qa(m);return{type:"tool-result",toolCallId:m.toolCallId,toolName:v,output:Hn({output:m.state==="output-error"?m.errorText:m.output,tool:(b=t?.tools)==null?void 0:b[v],errorMode:m.state==="output-error"?"text":"none"})}}default:return null}}).filter(m=>m!=null)}),o=[]},o=[];for(const l of n.parts)l.type==="text"||l.type==="reasoning"||l.type==="file"||l.type==="dynamic-tool"||Gt(l)?o.push(l):l.type==="step-start"&&s();s();break}break}default:{const s=n.role;throw new _g({originalMessage:n,message:`Unsupported role: ${s}`})}}return r}ua({prefix:"aiobj",size:24});var Rv=class{constructor(){this.queue=[],this.isProcessing=!1}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;)await this.queue[0](),this.queue.shift();this.isProcessing=!1}}async run(e){return new Promise((t,r)=>{this.queue.push(async()=>{try{await e(),t()}catch(n){r(n)}}),this.processQueue()})}};ua({prefix:"aiobj",size:24});var Pv={};ng(Pv,{object:()=>Mv,text:()=>Ov});var Ov=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),Mv=({schema:e})=>{const t=kn(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:r}){const n=await ud(r);switch(n.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:n.value};default:{const s=n.state;throw new Error(`Unsupported parse state: ${s}`)}}},async parseOutput({text:r},n){const s=await en({text:r});if(!s.success)throw new dl({message:"No object generated: could not parse the response.",cause:s.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});const o=await fr({value:s.value,schema:t});if(!o.success)throw new dl({message:"No object generated: response did not match sc
31hema.",cause:o.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});return o.value}}},Nv=gn({name:D(),version:D()}),No=gn({_meta:dt(z({}).loose())}),ia=No,jv=z({method:D(),params:dt(No)}),$v=gn({experimental:dt(z({}).loose()),logging:dt(z({}).loose()),prompts:dt(gn({listChanged:dt(Ve())})),resources:dt(gn({subscribe:dt(Ve()),listChanged:dt(Ve())})),tools:dt(gn({listChanged:dt(Ve())}))});ia.extend({protocolVersion:D(),capabilities:$v,serverInfo:Nv,instructions:dt(D())});var Dv=ia.extend({nextCursor:dt(D())}),Fv=z({name:D(),description:dt(D()),inputSchema:z({type:ge("object"),properties:dt(z({}).loose())}).loose()}).loose();Dv.extend({tools:Ze(Fv)});var qv=z({type:ge("text"),text:D()}).loose(),Lv=z({type:ge("image"),data:Wl(),mimeType:D()}).loose(),fd=z({uri:D(),mimeType:dt(D())}).loose(),Bv=fd.extend({text:D()}),Uv=fd.extend({blob:Wl()}),Vv=z({type:ge("resource"),resource:Xe([Bv,Uv])}).loose();ia.extend({content:Ze(Xe([qv,Lv,Vv])),isError:Ve().default(!1).optional()}).or(ia.extend({toolResult:Lt()}));var ss="2.0",Kv=z({jsonrpc:ge(ss),id:Xe([D(),we().int()])}).merge(jv).strict(),zv=z({jsonrpc:ge(ss),id:Xe([D(),we().int()]),result:ia}).strict(),Gv=z({jsonrpc:ge(ss),id:Xe([D(),we().int()]),error:z({code:we().int(),message:D(),data:dt(Lt())})}).strict(),Zv=z({jsonrpc:ge(ss)}).merge(z({method:D(),params:dt(No)})).strict();Xe([Kv,Zv,zv,Gv]);async function Wv(e){if(e==null)return[];if(!globalThis.FileList||!(e instanceof globalThis.FileList))throw new Error("FileList is not supported in the current environment");return Promise.all(Array.from(e).map(async t=>{const{name:r,type:n}=t,s=await new Promise((o,l)=>{const u=new FileReader;u.onload=d=>{var f;o((f=d.target)==null?void 0:f.result)},u.onerror=d=>l(d),u.readAsDataURL(t)});return{type:"file",mediaType:n,filename:r,url:s}}))}var Hv=class{constructor({api:e="/api/chat",credentials:t,headers:r,body:n,fetch:s,prepareSendMessagesRequest:o,prepareReconnectToStreamRequest:l}){this.api=e,this.credentials=t,this.headers=r,this.body=n,this.fetch=s,this.prepareSendMessagesRequest=o,this.prepareReconnectToStreamRequest=l}async sendMessages({abortSignal:e,...t}){var r,n,s,o,l;const u=await Et(this.body),d=await Et(this.headers),f=await Et(this.credentials),m=await((r=this.prepareSendMessagesRequest)==null?void 0:r.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...u,...t.body},headers:{...d,...t.headers},credentials:f,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),b=(n=m?.api)!=null?n:this.api,v=m?.headers!==void 0?m.headers:{...d,...t.headers},y=m?.body!==void 0?m.body:{...u,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},x=(s=m?.credentials)!=null?s:f,M=await((o=this.fetch)!=null?o:globalThis.fetch)(b,{method:"POST",headers:Xr({"Content-Type":"application/json",...v},`ai-sdk/${io}`,ea()),body:JSON.stringify(y),credentials:x,signal:e});if(!M.ok)throw new Error((l=await M.text())!=null?l:"Failed to fetch the chat response.");if(!M.body)throw new Error("The response body is empty.");return this.processResponseStream(M.body)}async reconnectToStream(e){var t,r,n,s,o;const l=await Et(this.body),u=await Et(this.headers),d=await Et(this.credentials),f=await((t=this.prepareReconnectToStreamRequest)==null?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...l,...e.body},headers:{...u,...e.headers},credentials:d,requestMetadata:e.metadata})),m=(r=f?.api)!=null?r:`${this.api}/${e.chatId}/stream`,b=f?.headers!==void 0?f.headers:{...u,...e.headers},v=(n=f?.credentials)!=null?n:d,x=await((s=this.fetch)!=null?s:globalThis.fetch)(m,{method:"GET",headers:Xr(b,`ai-sdk/${io}`,ea()),credentials:v});if(x.status===204)return null;if(!x.ok)throw new Error((o=await x.text())!=null?o:"Failed to fetch the chat response.");if(!x.body)throw new Error("The response body is empty.");return this.processResponseStream(x.body)}},hd=class extends Hv{constructor(e={}){super(e)}processResponseStream(e){return Zu({stream:e,schema:gv}).pipeThrough(new TransformStream({async transform(t,r){if(!t.success)throw t.error;r.enqueue(t.value)}}))}},Jv=class{constructor({generateId:e=yn,id:t=e(),transport:r=new hd,messageMetadataSchema:n,dataPartSchemas:s,state:o,onError:l,onToolCall:u,onFinish:d,onData:f,sendAutomaticallyWhen:m}){this.activeResponse=void 0,this.jobExecutor=new Rv,this.sendMessage=async(b,v)=>{var y,x,S,M;
31if(b==null){await this.makeRequest({trigger:"submit-message",messageId:(y=this.lastMessage)==null?void 0:y.id,...v});return}let R;if("text"in b||"files"in b?R={parts:[...Array.isArray(b.files)?b.files:await Wv(b.files),..."text"in b&&b.text!=null?[{type:"text",text:b.text}]:[]]}:R=b,b.messageId!=null){const B=this.state.messages.findIndex(V=>V.id===b.messageId);if(B===-1)throw new Error(`message with id ${b.messageId} not found`);if(this.state.messages[B].role!=="user")throw new Error(`message with id ${b.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,B+1),this.state.replaceMessage(B,{...R,id:b.messageId,role:(x=R.role)!=null?x:"user",metadata:b.metadata})}else this.state.pushMessage({...R,id:(S=R.id)!=null?S:this.generateId(),role:(M=R.role)!=null?M:"user",metadata:b.metadata});await this.makeRequest({trigger:"submit-message",messageId:b.messageId,...v})},this.regenerate=async({messageId:b,...v}={})=>{const y=b==null?this.state.messages.length-1:this.state.messages.findIndex(x=>x.id===b);if(y===-1)throw new Error(`message ${b} not found`);this.state.messages=this.state.messages.slice(0,this.messages[y].role==="assistant"?y:y+1),await this.makeRequest({trigger:"regenerate-message",messageId:b,...v})},this.resumeStream=async(b={})=>{await this.makeRequest({trigger:"resume-stream",...b})},this.clearError=()=>{this.status==="error"&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolResult=async({state:b="output-available",tool:v,toolCallId:y,output:x,errorText:S})=>this.jobExecutor.run(async()=>{var M,R;const B=this.state.messages,V=B[B.length-1];this.state.replaceMessage(B.length-1,{...V,parts:V.parts.map(E=>Ja(E)&&E.toolCallId===y?{...E,state:b,output:x,errorText:S}:E)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(E=>Ja(E)&&E.toolCallId===y?{...E,state:b,output:x,errorText:S}:E)),this.status!=="streaming"&&this.status!=="submitted"&&((M=this.sendAutomaticallyWhen)!=null&&M.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(R=this.lastMessage)==null?void 0:R.id})}),this.stop=async()=>{var b;this.status!=="streaming"&&this.status!=="submitted"||(b=this.activeResponse)!=null&&b.abortController&&this.activeResponse.abortController.abort()},this.id=t,this.transport=r,this.generateId=e,this.messageMetadataSchema=n,this.dataPartSchemas=s,this.state=o,this.onError=l,this.onToolCall=u,this.onFinish=d,this.onData=f,this.sendAutomaticallyWhen=m}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async makeRequest({trigger:e,metadata:t,headers:r,body:n,messageId:s}){var o,l,u;this.setStatus({status:"submitted",error:void 0});const d=this.lastMessage;let f=!1,m=!1,b=!1;try{const v={state:cd({lastMessage:this.state.snapshot(d),messageId:this.generateId()}),abortController:new AbortController};v.abortController.signal.addEventListener("abort",()=>{f=!0}),this.activeResponse=v;let y;if(e==="resume-stream"){const S=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:r,body:n});if(S==null){this.setStatus({status:"ready"});return}y=S}else y=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:v.abortController.signal,metadata:t,headers:r,body:n,trigger:e,messageId:s});const x=S=>this.jobExecutor.run(()=>S({state:v.state,write:()=>{var M;this.setStatus({status:"streaming"}),v.state.message.id===((M=this.lastMessage)==null?void 0:M.id)?this.state.replaceMessage(this.state.messages.length-1,v.state.message):this.state.pushMessage(v.state.message)}}));await pd({stream:dd({stream:y,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:x,onError:S=>{throw S}}),onError:S=>{throw S}}),this.setStatus({status:"ready"})}catch(v){if(f||v.name==="AbortError")return f=!0,this.setStatus({status:"ready"}),null;b=!0,v instanceof TypeError&&(v.message.toLowerCase().includes("fetch")||v.message.toLowerCase().includes("network"))&&(m=!0),this.onError&&v instanceof Error&&this.onError(v),this.setStatus({status:"error",error:v})}finally{try{(o=this.onFinish)==null||o.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:f,isDisconnect:m,isError:b})}catch(v){console.error(v)}this.activeResponse=void 0}(l=this.sendAutomaticallyWhen)!=null&&l.call(this,{messages:this.state.messages}
31)&&!b&&await this.makeRequest({trigger:"submit-message",messageId:(u=this.lastMessage)==null?void 0:u.id,metadata:t,headers:r,body:n})}};function Qv({messages:e}){const t=e[e.length-1];if(!t||t.role!=="assistant")return!1;const r=t.parts.reduce((s,o,l)=>o.type==="step-start"?l:s,-1),n=t.parts.slice(r+1).filter(Ja);return n.length>0&&n.every(s=>s.state==="output-available"||s.state==="output-error")}const Yv=z({version:we().optional(),projectId:D().optional(),createdAt:D(),order:we().optional().describe("用于排序,编号大的在后面,只需要保证顺序正确,不需要保证严格自增"),isFinished:Ve().optional(),isPersisted:Ve().optional(),fileId:D().optional(),startTime:D().optional(),endTime:D().optional(),isHidden:Ve().optional()});function Xv(e){return["input-available","input-streaming"].includes(e?.state)}function s_(e){return Ne(()=>{const t=[],r=ie(e);let n;for(const s of r)Gt(s)?n=s:s.type!=="step-start"&&(n&&(t.push(n),n=void 0),s.type==="text"&&t.push(s));return n&&t.push(n),t})}function xn(e,t){if(e.metadata)return e.metadata;const r=e;e.metadata={...wo(r,Yv.keyof().options),createdAt:r.createdAt||new Date().toISOString(),version:r.version||t};const{metadata:n}=e;return n}function ey(e){const t=At(),{data:r}=wn({queryKey:["project",e],queryFn:()=>t("/api/ai-design/project",{query:{id:ie(e)},onResponseError(){}})});return{project:r}}function md(e){const t=At(),r=nn();return Zt({async mutationFn(n){const s=ie(e);await t("/api/ai-design/project",{method:"PATCH",body:{...n,projectId:s}})},onSuccess(n,s){const o=ie(e);r.setQueryData(["project",o],_n(l=>{l&&xo(l,s)})),r.invalidateQueries({queryKey:["/api/ai-design/projects"]})}})}function o_(e){const t=At(),r=nn();return Zt({async mutationFn(){const n=ie(e);n&&await t("/api/ai-design/project",{method:"DELETE",query:{id:n}})},onSuccess(){ie(e)&&r.invalidateQueries({queryKey:["/api/ai-design/projects"]})}})}function i_(e){const t=At(),r=nn(),n=vd(),s=bd();function o(M){const{data:R}=wn({queryKey:["project","files",e,M],queryFn:()=>t("/api/ai-design/project-files",{query:{projectId:ie(e),projectVersion:ie(M)}}),enabled:()=>!!ie(M)});return Ne(()=>Yn(R.value))}const{data:l}=wn({queryKey:["project","rules",e],queryFn:()=>t("/api/ai-design/project-rules",{query:{projectId:ie(e)}})}),{mutateAsync:u}=Zt({mutationKey:["project",e,"rule","enable"],mutationFn:M=>t("/api/ai-design/project-rule",{method:"PUT",body:{projectId:ie(e),ruleId:M}}),onSuccess(M,R){r.setQueryData(["project","rules",ie(e)],_n(B=>{B.push(R)}))}}),{mutateAsync:d}=Zt({mutationKey:["project",e,"rule","disable"],mutationFn:M=>t("/api/ai-design/project-rule",{method:"DELETE",body:{projectId:ie(e),ruleId:M}}),onSuccess(M,R){r.setQueryData(["project","rules",ie(e)],B=>B.filter(V=>V!==R))}});function f(){return t("/api/ai-design/project/versions",{query:{projectId:ie(e)}})}function m(){const{data:M}=wn({queryKey:["project","versions",e],queryFn:()=>f()});return M}async function b(M){await t("/api/ai-design/project/version",{method:"PATCH",body:{...M,projectId:ie(e)}}),r.setQueryData(["project","versions",ie(e)],_n(R=>{if(!R)return;const B=R.find(V=>V.version===M.version);B&&xo(B,M)}))}async function v(M){const{messages:R,parentVersion:B}=M,V=ie(e),{id:E,version:te,credentialData:U,virtualFile:K}=await t("/api/ai-design/project/messages",{method:"POST",body:{projectId:V,version:M.version,parentVersion:B,state:St.Pending}}),ce={messages:R.map(ve=>{const ke=xn(ve,te);return Object.assign(ke,{version:te,createdAt:new Date().toISOString()}),Hl(ve)})},me=JSON.stringify(ce),de=new Blob([me]),{hash:he}=await n(K,de,U);return await b({version:te,hash:he}),r.setQueryData(["project","versions",V],_n(ve=>{const ke=ve.find(Ce=>Ce.version===te);ke?ke.virtualFile.hash=he:ve.unshift({id:E,projectId:V,version:te,parent:B,state:M.state,virtualFile:{...K,hash:he}})})),r.setQueryData(ko(K),()=>({...K,hash:he,content:me})),te}async function y({version:M}){const R=await r.fetchQuery({queryKey:["project","versions",e],queryFn:()=>f()}),B=su(M,R);return(await Promise.all(B.map(({virtualFile:E})=>E.hash?s(E):null))).flatMap(E=>ty(E?.content)?.messages).filter(E=>!!E)}const{mutateAsync:x}=md(e);async function S(M,R){R=Qr(R,["id","projectId","version","filename"]),await t("/api/ai-design/project-file",{method:"PATCH",body:{...R,projectId:M.projectId,version:M.version,filename:M.filename}}),r.setQueryData(["project","files",M.projectId,M.version],B=>{if(!B)return B;const V=B.map(E=>E.id===M.id?{...E,...R}:E);return R.order!==void 0?Yn(V):V})}return{useProjectFiles:o,persistMessages:v,restoreMessages:y,projectRules:l,enableRule:u,disableRule:d,useProjectVersions:m,useFileContent:sy,patchProject:x,patchVersion:b,patchFile:S}}function ty(e){if(!e)return null;try{return JSON.parse(e)}catch(t){return window.reportError(t),null}}function co(e){if(!e)return null;try{return new DOMParser().parseFromString(e,"text/html")}catch(t){return console.warn(t),null}}function ry(e){return co(e)?.title}function ny(e,t){const r=new Set(t.map(s=>s.filename)),n=e.find(s=>
31r.has(s.filename));if(n)throw new Error(`file ${n.filename} already exists`)}const po=12;async function ay(e,t){const r=new CompressionStream("gzip"),n=e.stream().pipeThrough(r),s=await new Response(n).arrayBuffer(),o=tu(t),l=await lf(po),u=await crypto.subtle.importKey("raw",o,"aes-gcm",!1,["encrypt","decrypt"]),d=await crypto.subtle.encrypt({name:"aes-gcm",iv:l},u,s);return new Blob([l,d],{type:"application/octet-stream"})}async function gd(e,t){const r=tu(e),n=await t.arrayBuffer(),s=await crypto.subtle.importKey("raw",r,"aes-gcm",!1,["encrypt","decrypt"]),o=n.slice(0,po),l=n.slice(po),u=await crypto.subtle.decrypt({name:"aes-gcm",iv:o},s,l),d=new DecompressionStream("gzip"),m=new Blob([u]).stream().pipeThrough(d);return new Response(m)}function vd(){const{uploadFile:e}=ru(),t=_o();return async function(n,s,o){const l=await ay(s,n.shareKey);await e(Xs.VirtualFile,{type:Jl.Other,key:Sn(t,n.id,"file"),body:l,contentType:"application/octet-stream",force:!0},{credentialData:o,middleware:Mp(Np(Xs.VirtualFile),jp)});const u=await crypto.subtle.digest("SHA-256",await s.arrayBuffer());return{hash:of(u)}}}function sy(e){const t=_o(),{data:r}=wn({queryKey:ff(()=>ie(e)?.virtualFile),queryFn:async()=>{const n=ie(e);if(!n)return null;const{filename:s,virtualFile:o}=n;if(!o.hash)return null;const{id:l,hash:u,shareKey:d}=o,f=await Ql(ns(Sn("virtual-file",t,l,"file")),{responseType:"blob",query:{hash:u}}),b=await(await gd(d,f)).text();return{filename:s,content:b}}});return r}function yd(){const e=At(),t=vd();return async function(n,s,o,l){const u=new Map;return await Op(5,o.filter(d=>!!d.content).map(({filename:d,content:f},m)=>({...l[m],blob:new Blob([f]),filename:d})),async({virtualFile:d,blob:f,credentialData:m,filename:b})=>{if(m)try{const{hash:v}=await t(d,f,m);await e("/api/ai-design/project-file",{method:"PATCH",body:{filename:b,projectId:n,version:s,hash:v}}),u.set(b,v)}catch(v){throw console.error(v),v}}),{hashes:u}}}function bd(){const e=nn(),t=_o();return async function(n){return e.fetchQuery({queryKey:ko(n),queryFn:async()=>{const s=await Ql(ns(Sn("virtual-file",t,n.id,"file")),{responseType:"blob",query:{hash:n.hash}}),l=await(await gd(n.shareKey,s)).text();return{...n,content:l}}})}}function l_(e,t){const r=nn(),n=At(),s=Ne(()=>ie(e)),o=Ne(()=>ie(t)),{getVersionParams:l}=ep(()=>s.value.id,o),u=bd(),d=yd(),{mutate:f}=md(()=>s.value.id);function m(V){const E=s.value.id;return r.fetchQuery({queryKey:["project","files",E,V],queryFn:()=>n("/api/ai-design/project-files",{query:{projectId:E,projectVersion:V}}).then(te=>Yn(te)??[])})}async function b(V,E){const U=(await m(E)).find(K=>K.filename===V);if(U?.virtualFile.hash)return u(U.virtualFile)}async function v(V){const{content:E}=V,te=s.value.id,{version:U,credentialData:K,virtualFile:ce,filename:me}=await n("/api/ai-design/project-file",{method:"POST",body:{...await l(V.source),projectId:te,filename:V.filename}}),de=co(E);!ie(s).name&&de?.title&&f({name:de.title});const{hashes:he}=await d(te,U,[{filename:me,content:V.content,displayName:de?.title??void 0}],[{filename:me,credentialData:K,virtualFile:ce}]),ve=he.get(me)??"";return{projectId:te,version:U,files:[{filename:me,virtualFile:{...ce,hash:ve},credentialData:K}],contents:new Map([[me,E]])}}function y(V){if(!V)return;const{projectId:E,version:te,files:U,contents:K}=V;if(!(!U||!K)){for(const ce of U){const{virtualFile:me,filename:de}=ce,he=K.get(de);he&&r.setQueryData(ko(me),()=>({...me,content:he}))}r.invalidateQueries({queryKey:["project","versions",E]}),r.setQueryData(["project","files",E,te],ce=>{if(!ce)return;const me=_n(ce,de=>{const he=new Map(U.map(ve=>[ve.filename,ve]));for(const ve of de){const ke=he.get(ve.filename);ke&&(ve.virtualFile=ke.virtualFile,he.delete(ve.filename))}de.push(...Array.from(he.values()).filter(ve=>!!ve.projectFile).map(({projectFile:ve,virtualFile:ke})=>({...ve,virtualFile:ke})))});return Yn(me)??me})}}async function x(V){if(!o.value)throw new Error;const E=V.projectId||s.value.id,te=await m(o.value);ny(V.files,te);let U=!1;const{version:K,files:ce}=await n("/api/ai-design/project-file",{method:"PUT",body:{...await l(V.source),projectId:E,files:V.files.map(he=>{const ve={filename:he.filename};if(he.displayName)ve.displayName=he.displayName;
31else{const ke=co(he.content);ke?.title&&(ve.displayName=ke.title)}return ve.displayName&&!ie(s).name&&!U&&(U=!0,f({name:ve.displayName})),ve})}}),{hashes:me}=await d(E,K,V.files,ce),de=new Map(V.files.filter(he=>!!he.content).map(({filename:he,content:ve})=>[he,ve]));return{projectId:E,version:K,files:ce.map(he=>({...he,virtualFile:{...he.virtualFile,hash:me.get(he.filename)??""}})),contents:de}}function S(V,E,te){return R({source:V,files:[{filename:E,content:te}]})}const{mutateAsync:M}=Zt({mutationFn:v,onSuccess(V){y(V)}}),{mutateAsync:R}=Zt({mutationFn:x,onSuccess(V){y(V)}});async function B(V,E){const{version:te}=await n("/api/ai-design/project-file",{method:"DELETE",body:{...await l(V),projectId:s.value.id,filename:E}});return r.setQueryData(["project","files",s.value.id,te],U=>U?.filter(K=>K.filename!==E)),{version:te}}return{listFiles:m,readFile:b,writeFile:M,createFiles:R,createFile:S,deleteFile:B}}var La={exports:{}},oy=La.exports,yl;function iy(){return yl||(yl=1,(function(e,t){(function(r,n){e.exports=n()})(oy,function(){var r=function(a,i){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(c,p){c.__proto__=p}||function(c,p){for(var h in p)Object.prototype.hasOwnProperty.call(p,h)&&(c[h]=p[h])})(a,i)},n=function(){return(n=Object.assign||function(a){for(var i,c=1,p=arguments.length;c<p;c++)for(var h in i=arguments[c])Object.prototype.hasOwnProperty.call(i,h)&&(a[h]=i[h]);return a}).apply(this,arguments)};function s(a,i,c){for(var p,h=0,g=i.length;h<g;h++)!p&&h in i||((p=p||Array.prototype.slice.call(i,0,h))[h]=i[h]);return a.concat(p||Array.prototype.slice.call(i))}var o=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:$p,l=Object.keys,u=Array.isArray;function d(a,i){return typeof i!="object"||l(i).forEach(function(c){a[c]=i[c]}),a}typeof Promise>"u"||o.Promise||(o.Promise=Promise);var f=Object.getPrototypeOf,m={}.hasOwnProperty;function b(a,i){return m.call(a,i)}function v(a,i){typeof i=="function"&&(i=i(f(a))),(typeof Reflect>"u"?l:Reflect.ownKeys)(i).forEach(function(c){x(a,c,i[c])})}var y=Object.defineProperty;function x(a,i,c,p){y(a,i,d(c&&b(c,"get")&&typeof c.get=="function"?{get:c.get,set:c.set,configurable:!0}:{value:c,configurable:!0,writable:!0},p))}function S(a){return{from:function(i){return a.prototype=Object.create(i.prototype),x(a.prototype,"constructor",a),{extend:v.bind(null,a.prototype)}}}}var M=Object.getOwnPropertyDescriptor,R=[].slice;function B(a,i,c){return R.call(a,i,c)}function V(a,i){return i(a)}function E(a){if(!a)throw new Error("Assertion Failed")}function te(a){o.setImmediate?setImmediate(a):setTimeout(a,0)}function U(a,i){if(typeof i=="string"&&b(a,i))return a[i];if(!i)return a;if(typeof i!="string"){for(var c=[],p=0,h=i.length;p<h;++p){var g=U(a,i[p]);c.push(g)}return c}var w=i.indexOf(".");if(w!==-1){var _=a[i.substr(0,w)];return _==null?void 0:U(_,i.substr(w+1))}}function K(a,i,c){if(a&&i!==void 0&&!("isFrozen"in Object&&Object.isFrozen(a)))if(typeof i!="string"&&"length"in i){E(typeof c!="string"&&"length"in c);for(var p=0,h=i.length;p<h;++p)K(a,i[p],c[p])}else{var g,w,_=i.indexOf(".");_!==-1?(g=i.substr(0,_),(w=i.substr(_+1))===""?c===void 0?u(a)&&!isNaN(parseInt(g))?a.splice(g,1):delete a[g]:a[g]=c:K(_=!(_=a[g])||!b(a,g)?a[g]={}:_,w,c)):c===void 0?u(a)&&!isNaN(parseInt(i))?a.splice(i,1):delete a[i]:a[i]=c}}function ce(a){var i,c={};for(i in a)b(a,i)&&(c[i]=a[i]);return c}var me=[].concat;function de(a){return me.apply([],a)}var Rt="BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey".split(",").concat(de([8,16,32,64].map(function(a){return["Int","Uint","Float"].map(function(i){return i+a+"Array"})}))).filter(function(a){return o[a]}),he=new Set(Rt.map(function(a){return o[a]})),ve=null;function ke(a){return ve=new WeakMap,a=(function i(c){if(!c||typeof c!="object")return c;var p=ve.get(c);if(p)return p;if(u(c)){p=[],ve.set(c,p);for(var h=0,g=c.length;h<g;++h)p.push(i(c[h]))}else if(he.has(c.constructor))p=c;else{var w,_=f(c);for(w in p=_===Object.prototype?{}:Object.create(_),ve.set(c,p),c)b(c,w)&&(p[w]=i(c[w]))}return p})(a),ve=null,a}var Ce={}.toString;function pt(a){return Ce.call(a).slice(8,-1)}var lt=typeof Symbol<"u"?Symbol.iterator:"@@iterator",Ct=typeof lt=="symbol"?function(a){var i;return a!=null&&(i=a[lt])&&i.apply(a)}:function(){return null};function H(a,i){return i=a.indexOf(i),0<=i&&a.splice(i,1),0<=i}var pe={};function ne(a){var i,c,p,h;if(arguments.length===1){if(u(a))return a.slice();
31if(this===pe&&typeof a=="string")return[a];if(h=Ct(a)){for(c=[];!(p=h.next()).done;)c.push(p.value);return c}if(a==null)return[a];if(typeof(i=a.length)!="number")return[a];for(c=new Array(i);i--;)c[i]=a[i];return c}for(i=arguments.length,c=new Array(i);i--;)c[i]=arguments[i];return c}var je=typeof Symbol<"u"?function(a){return a[Symbol.toStringTag]==="AsyncFunction"}:function(){return!1},yr=["Unknown","Constraint","Data","TransactionInactive","ReadOnly","Version","NotFound","InvalidState","InvalidAccess","Abort","Timeout","QuotaExceeded","Syntax","DataClone"],Dt=["Modify","Bulk","OpenFailed","VersionChange","Schema","Upgrade","InvalidTable","MissingAPI","NoSuchDatabase","InvalidArgument","SubTransaction","Unsupported","Internal","DatabaseClosed","PrematureCommit","ForeignAwait"].concat(yr),qe={VersionChanged:"Database version changed by other database connection",DatabaseClosed:"Database has been closed",Abort:"Transaction aborted",TransactionInactive:"Transaction has already completed or failed",MissingAPI:"IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb"};function et(a,i){this.name=a,this.message=i}function Le(a,i){return a+". Errors: "+Object.keys(i).map(function(c){return i[c].toString()}).filter(function(c,p,h){return h.indexOf(c)===p}).join(`
32`)}function Y(a,i,c,p){this.failures=i,this.failedKeys=p,this.successCount=c,this.message=Le(a,i)}function le(a,i){this.name="BulkError",this.failures=Object.keys(i).map(function(c){return i[c]}),this.failuresByPos=i,this.message=Le(a,this.failures)}S(et).from(Error).extend({toString:function(){return this.name+": "+this.message}}),S(Y).from(et),S(le).from(et);var Ie=Dt.reduce(function(a,i){return a[i]=i+"Error",a},{}),$e=et,Q=Dt.reduce(function(a,i){var c=i+"Error";function p(h,g){this.name=c,h?typeof h=="string"?(this.message="".concat(h).concat(g?`
33 `+g:""),this.inner=g||null):typeof h=="object"&&(this.message="".concat(h.name," ").concat(h.message),this.inner=h):(this.message=qe[i]||c,this.inner=null)}return S(p).from($e),a[i]=p,a},{});Q.Syntax=SyntaxError,Q.Type=TypeError,Q.Range=RangeError;var We=yr.reduce(function(a,i){return a[i+"Error"]=Q[i],a},{}),st=Dt.reduce(function(a,i){return["Syntax","Type","Range"].indexOf(i)===-1&&(a[i+"Error"]=Q[i]),a},{});function ye(){}function Re(a){return a}function Ge(a,i){return a==null||a===Re?i:function(c){return i(a(c))}}function De(a,i){return function(){a.apply(this,arguments),i.apply(this,arguments)}}function Pe(a,i){return a===ye?i:function(){var c=a.apply(this,arguments);c!==void 0&&(arguments[0]=c);var p=this.onsuccess,h=this.onerror;this.onsuccess=null,this.onerror=null;var g=i.apply(this,arguments);return p&&(this.onsuccess=this.onsuccess?De(p,this.onsuccess):p),h&&(this.onerror=this.onerror?De(h,this.onerror):h),g!==void 0?g:c}}function Ae(a,i){return a===ye?i:function(){a.apply(this,arguments);var c=this.onsuccess,p=this.onerror;this.onsuccess=this.onerror=null,i.apply(this,arguments),c&&(this.onsuccess=this.onsuccess?De(c,this.onsuccess):c),p&&(this.onerror=this.onerror?De(p,this.onerror):p)}}function bt(a,i){return a===ye?i:function(c){var p=a.apply(this,arguments);d(c,p);var h=this.onsuccess,g=this.onerror;return this.onsuccess=null,this.onerror=null,c=i.apply(this,arguments),h&&(this.onsuccess=this.onsuccess?De(h,this.onsuccess):h),g&&(this.onerror=this.onerror?De(g,this.onerror):g),p===void 0?c===void 0?void 0:c:d(p,c)}}function jt(a,i){return a===ye?i:function(){return i.apply(this,arguments)!==!1&&a.apply(this,arguments)}}function se(a,i){return a===ye?i:function(){var c=a.apply(this,arguments);if(c&&typeof c.then=="function"){for(var p=this,h=arguments.length,g=new Array(h);h--;)g[h]=arguments[h];return c.then(function(){return i.apply(p,g)})}return i.apply(this,arguments)}}st.ModifyError=Y,st.DexieError=et,st.BulkError=le;var Ee=typeof location<"u"&&/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);function gr(a){Ee=a}var vr={},En=100,Rt=typeof Promise>"u"?[]:(function(){var a=Promise.resolve();if(typeof crypto>"u"||!crypto.subtle)return[a,f(a),a];var i=crypto.subtle.digest("SHA-512",new Uint8Array([0]));return[i,f(i),a]})(),yr=Rt[0],Dt=Rt[1],Rt=Rt[2],Dt=Dt&&Dt.then,ut=yr&&yr.constructor,Wt=!!Rt,br=function(a,i){jr.push([a,i]),wr&&(queueMicrotask($t),wr=!1)},Mr=!0,wr=!0,rr=[],Nr=[],on=Re,wt={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:ye,pgp:!1,env:{},finalize:ye},ue=wt,jr=[],nr=0,ar=[];function X(a){if(typeof this!="object")throw new TypeError("Promises must be constructed via new");this._listeners=[],this._lib=!1;var i=this._PSD=ue;if(typeof a!="function"){if(a!==vr)throw new TypeError("Not a function");return this._state=arguments[1],this._value=arguments[2],void(this._state===!1&&Ht(this,this._value))}this._state=null,this._value=null,++i.ref,(function c(p,h){try{h(function(g){if(p._state===null){if(g===p)throw new TypeError("A promise cannot be resolved with itself.");var w=p._lib&&sr();g&&typeof g.then=="function"?c(p,function(_,I){g instanceof X?g._then(_,I):g.then(_,I)}):(p._state=!0,p._value=g,Tt(p)),w&&fe()}},Ht.bind(null,p))}catch(g){Ht(p,g)}})(this,a)}var $r={get:function(){var a=ue,i=_r;function c(p,h){var g=this,w=!a.global&&(a!==ue||i!==_r),_=w&&!kr(),I=new X(function(A,P){Dr(g,new ln(Jo(p,a,w,_),Jo(h,a,w,_),A,P,a))});return this._consoleTask&&(I._consoleTask=this._consoleTask),I}return c.prototype=vr,c},set:function(a){x(this,"then",a&&a.prototype===vr?$r:{get:function(){return a}
33,set:$r.set})}};function ln(a,i,c,p,h){this.onFulfilled=typeof a=="function"?a:null,this.onRejected=typeof i=="function"?i:null,this.resolve=c,this.reject=p,this.psd=h}function Ht(a,i){var c,p;Nr.push(i),a._state===null&&(c=a._lib&&sr(),i=on(i),a._state=!1,a._value=i,p=a,rr.some(function(h){return h._value===p._value})||rr.push(p),Tt(a),c&&fe())}function Tt(a){var i=a._listeners;a._listeners=[];for(var c=0,p=i.length;c<p;++c)Dr(a,i[c]);var h=a._PSD;--h.ref||h.finalize(),nr===0&&(++nr,br(function(){--nr==0&&tt()},[]))}function Dr(a,i){if(a._state!==null){var c=a._state?i.onFulfilled:i.onRejected;if(c===null)return(a._state?i.resolve:i.reject)(a._value);++i.psd.ref,++nr,br(pa,[c,a,i])}else a._listeners.push(i)}function pa(a,i,c){try{var p,h=i._value;!i._state&&Nr.length&&(Nr=[]),p=Ee&&i._consoleTask?i._consoleTask.run(function(){return a(h)}):a(h),i._state||Nr.indexOf(h)!==-1||(function(g){for(var w=rr.length;w;)if(rr[--w]._value===g._value)return rr.splice(w,1)})(i),c.resolve(p)}catch(g){c.reject(g)}finally{--nr==0&&tt(),--c.psd.ref||c.psd.finalize()}}function $t(){qr(wt,function(){sr()&&fe()})}function sr(){var a=Mr;return wr=Mr=!1,a}function fe(){var a,i,c;do for(;0<jr.length;)for(a=jr,jr=[],c=a.length,i=0;i<c;++i){var p=a[i];p[0].apply(null,p[1])}while(0<jr.length);wr=Mr=!0}function tt(){var a=rr;rr=[],a.forEach(function(p){p._PSD.onunhandled.call(null,p._value,p)});for(var i=ar.slice(0),c=i.length;c;)i[--c]()}function Jt(a){return new X(vr,!1,a)}function Be(a,i){var c=ue;return function(){var p=sr(),h=ue;try{return Sr(c,!0),a.apply(this,arguments)}catch(g){i&&i(g)}finally{Sr(h,!1),p&&fe()}}}v(X.prototype,{then:$r,_then:function(a,i){Dr(this,new ln(null,null,a,i,ue))},catch:function(a){if(arguments.length===1)return this.then(null,a);var i=a,c=arguments[1];return typeof i=="function"?this.then(null,function(p){return(p instanceof i?c:Jt)(p)}):this.then(null,function(p){return(p&&p.name===i?c:Jt)(p)})},finally:function(a){return this.then(function(i){return X.resolve(a()).then(function(){return i})},function(i){return X.resolve(a()).then(function(){return Jt(i)})})},timeout:function(a,i){var c=this;return a<1/0?new X(function(p,h){var g=setTimeout(function(){return h(new Q.Timeout(i))},a);c.then(p,h).finally(clearTimeout.bind(null,g))}):this}}),typeof Symbol<"u"&&Symbol.toStringTag&&x(X.prototype,Symbol.toStringTag,"Dexie.Promise"),wt.env=Ho(),v(X,{all:function(){var a=ne.apply(null,arguments).map(fa);return new X(function(i,c){a.length===0&&i([]);var p=a.length;a.forEach(function(h,g){return X.resolve(h).then(function(w){a[g]=w,--p||i(a)},c)})})},resolve:function(a){return a instanceof X?a:a&&typeof a.then=="function"?new X(function(i,c){a.then(i,c)}):new X(vr,!0,a)},reject:Jt,race:function(){var a=ne.apply(null,arguments).map(fa);return new X(function(i,c){a.map(function(p){return X.resolve(p).then(i,c)})})},PSD:{get:function(){return ue},set:function(a){return ue=a}},totalEchoes:{get:function(){return _r}},newPSD:xr,usePSD:qr,scheduler:{get:function(){return br},set:function(a){br=a}},rejectionMapper:{get:function(){return on},set:function(a){on=a}},follow:function(a,i){return new X(function(c,p){return xr(function(h,g){var w=ue;w.unhandleds=[],w.onunhandled=g,w.finalize=De(function(){var _,I=this;_=function(){I.unhandleds.length===0?h():g(I.unhandleds[0])},ar.push(function A(){_(),ar.splice(ar.indexOf(A),1)}),++nr,br(function(){--nr==0&&tt()},[])},w.finalize),a()},i,c,p)})}}),ut&&(ut.allSettled&&x(X,"allSettled",function(){var a=ne.apply(null,arguments).map(fa);return new X(function(i){a.length===0&&i([]);var c=a.length,p=new Array(c);a.forEach(function(h,g){return X.resolve(h).then(function(w){return p[g]={status:"fulfilled",value:w}},function(w){return p[g]={status:"rejected",reason:w}}).then(function(){return--c||i(p)})})})}),ut.any&&typeof AggregateError<"u"&&x(X,"any",function(){var a=ne.apply(null,arguments).map(fa);return new X(function(i,c){a.length===0&&c(new AggregateError([]));var p=a.length,h=new Array(p);a.forEach(function(g,w){return X.resolve(g).then(function(_){return i(_)},function(_){h[w]=_,--p||c(new AggregateError(h))})})})}),ut.withResolvers&&(X.withResolvers=ut.withResolvers));var Je={awaits:0,echoes:0,id:0},Ut=0,Fr=[],ot=0,_r=0,tp=0;function xr(a,i,c,p){var h=ue,g=Object.create(h);return g.parent=h,g.ref=0,g.global=!1,g.id=++tp,wt.env,g.env=Wt?{Promise:X,PromiseProp:{value:X,configurable:!0,writable:!0},all:X.all,race:X.race,allSettled:X.allSettled,any:X.any,resolve:X.resolve,reject:X.reject}:{},i&&d(g,i),++h.ref,g.finalize=function(){--this.parent.ref||this.parent.finalize()},p=qr(g,a,c,p),g.ref===0&&g.finalize(),p}function un(){return Je.id||(Je.id=++Ut),++Je.awaits,Je.echoes+=En,Je.id}function kr(){return!!Je.awaits&&(--Je.awaits==0&&(Je.id=0),Je.echoes=Je.awaits*En,!0)}function fa(a){return Je.echoes&&a&&a.constructor===ut?(un(),a.then(function(i){return kr(),i},function(i){return kr(),rt(i)})):a}function rp(){var a=Fr[Fr.length-1];Fr.pop(),Sr(a,!1)}function Sr(a,i){var c,p=ue;(i?!Je.echoes||ot++&&a===ue:!ot||--ot&&a===ue)||queueMicrotask(i?(function(h){++_r,Je.echoes&&--Je.echoes!=0||(Je.echoes=Je.awaits=Je.id=0),Fr.push(ue),Sr(h,!0)}).bind(null,a):rp),a!==ue&&(ue=a,p===wt&&(wt.env=Ho()),Wt&&(c=wt.env.Promise,i=a.env,(p.global||a.global)&&(Object.defineProperty(o,"Promise",i.PromiseProp),c.all=i.all,c.race=i.race,c.resolve=i.resolve,c.reject=i.reject,i.allSettled&&(c.allSettled=i.allSettled),i.any&&(c.any=i.any))))}function Ho(){var a=o.Promise;return Wt?{Promise:a,PromiseProp:Object.getOwnPropertyDescriptor(o,"Promise"),all:a.all,race:a.race,allSettled:a.allSettled,any:a.any,resolve:a.resolve,reject:a.reject}:{}}function qr(a,i,c,p,h){var g=ue;
33try{return Sr(a,!0),i(c,p,h)}finally{Sr(g,!1)}}function Jo(a,i,c,p){return typeof a!="function"?a:function(){var h=ue;c&&un(),Sr(i,!0);try{return a.apply(this,arguments)}finally{Sr(h,!1),p&&queueMicrotask(kr)}}}function ps(a){Promise===ut&&Je.echoes===0?ot===0?a():enqueueNativeMicroTask(a):setTimeout(a,0)}(""+Dt).indexOf("[native code]")===-1&&(un=kr=ye);var rt=X.reject,Lr="ï¿¿",or="Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.",Qo="String expected.",cn=[],ha="__dbnames",fs="readonly",hs="readwrite";function Br(a,i){return a?i?function(){return a.apply(this,arguments)&&i.apply(this,arguments)}:a:i}var Yo={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function ma(a){return typeof a!="string"||/\./.test(a)?function(i){return i}:function(i){return i[a]===void 0&&a in i&&delete(i=ke(i))[a],i}}function Xo(){throw Q.Type("Entity instances must never be new:ed. Instances are generated by the framework bypassing the constructor.")}function Oe(a,i){try{var c=ei(a),p=ei(i);if(c!==p)return c==="Array"?1:p==="Array"?-1:c==="binary"?1:p==="binary"?-1:c==="string"?1:p==="string"?-1:c==="Date"?1:p!=="Date"?NaN:-1;switch(c){case"number":case"Date":case"string":return i<a?1:a<i?-1:0;case"binary":return(function(h,g){for(var w=h.length,_=g.length,I=w<_?w:_,A=0;A<I;++A)if(h[A]!==g[A])return h[A]<g[A]?-1:1;return w===_?0:w<_?-1:1})(ti(a),ti(i));case"Array":return(function(h,g){for(var w=h.length,_=g.length,I=w<_?w:_,A=0;A<I;++A){var P=Oe(h[A],g[A]);if(P!==0)return P}return w===_?0:w<_?-1:1})(a,i)}}catch{}return NaN}function ei(a){var i=typeof a;return i!="object"?i:ArrayBuffer.isView(a)?"binary":(a=pt(a),a==="ArrayBuffer"?"binary":a)}function ti(a){return a instanceof Uint8Array?a:ArrayBuffer.isView(a)?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):new Uint8Array(a)}function ga(a,i,c){var p=a.schema.yProps;return p?(i&&0<c.numFailures&&(i=i.filter(function(h,g){return!c.failures[g]})),Promise.all(p.map(function(h){return h=h.updatesTable,i?a.db.table(h).where("k").anyOf(i).delete():a.db.table(h).clear()})).then(function(){return c})):c}var ri=(He.prototype._trans=function(a,i,c){var p=this._tx||ue.trans,h=this.name,g=Ee&&typeof console<"u"&&console.createTask&&console.createTask("Dexie: ".concat(a==="readonly"?"read":"write"," ").concat(this.name));function w(A,P,k){if(!k.schema[h])throw new Q.NotFound("Table "+h+" not part of transaction");return i(k.idbtrans,k)}var _=sr();try{var I=p&&p.db._novip===this.db._novip?p===ue.trans?p._promise(a,w,c):xr(function(){return p._promise(a,w,c)},{trans:p,transless:ue.transless||ue}):(function A(P,k,j,T){if(P.idbdb&&(P._state.openComplete||ue.letThrough||P._vip)){var C=P._createTransaction(k,j,P._dbSchema);try{C.create(),P._state.PR1398_maxLoop=3}catch(N){return N.name===Ie.InvalidState&&P.isOpen()&&0<--P._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),P.close({disableAutoOpen:!1}),P.open().then(function(){return A(P,k,j,T)})):rt(N)}return C._promise(k,function(N,O){return xr(function(){return ue.trans=C,T(N,O,C)})}).then(function(N){if(k==="readwrite")try{C.idbtrans.commit()}catch{}return k==="readonly"?N:C._completion.then(function(){return N})})}if(P._state.openComplete)return rt(new Q.DatabaseClosed(P._state.dbOpenError));if(!P._state.isBeingOpened){if(!P._state.autoOpen)return rt(new Q.DatabaseClosed);P.open().catch(ye)}return P._state.dbReadyPromise.then(function(){return A(P,k,j,T)})})(this.db,a,[this.name],w);return g&&(I._consoleTask=g,I=I.catch(function(A){return console.trace(A),rt(A)})),I}finally{_&&fe()}},He.prototype.get=function(a,i){var c=this;return a&&a.constructor===Object?this.where(a).first(i):a==null?rt(new Q.Type("Invalid argument to Table.get()")):this._trans("readonly",function(p){return c.core.get({trans:p,key:a}).then(function(h){return c.hook.reading.fire(h)})}).then(i)},He.prototype.where=function(a){if(typeof a=="string")return new this.db.WhereClause(this,a);if(u(a))return new this.db.WhereClause(this,"[".concat(a.join("+"),"]"));var i=l(a);if(i.length===1)return this.where(i[0]).equals(a[i[0]]);var c=this.schema.indexes.concat(this.schema.primKey).filter(function(_){if(_.compound&&i.every(function(A){return 0<=_.keyPath.indexOf(A)}
33)){for(var I=0;I<i.length;++I)if(i.indexOf(_.keyPath[I])===-1)return!1;return!0}return!1}).sort(function(_,I){return _.keyPath.length-I.keyPath.length})[0];if(c&&this.db._maxKey!==Lr){var g=c.keyPath.slice(0,i.length);return this.where(g).equals(g.map(function(I){return a[I]}))}!c&&Ee&&console.warn("The query ".concat(JSON.stringify(a)," on ").concat(this.name," would benefit from a ")+"compound index [".concat(i.join("+"),"]"));var p=this.schema.idxByName;function h(_,I){return Oe(_,I)===0}var w=i.reduce(function(k,I){var A=k[0],P=k[1],k=p[I],j=a[I];return[A||k,A||!k?Br(P,k&&k.multi?function(T){return T=U(T,I),u(T)&&T.some(function(C){return h(j,C)})}:function(T){return h(j,U(T,I))}):P]},[null,null]),g=w[0],w=w[1];return g?this.where(g.name).equals(a[g.keyPath]).filter(w):c?this.filter(w):this.where(i).equals("")},He.prototype.filter=function(a){return this.toCollection().and(a)},He.prototype.count=function(a){return this.toCollection().count(a)},He.prototype.offset=function(a){return this.toCollection().offset(a)},He.prototype.limit=function(a){return this.toCollection().limit(a)},He.prototype.each=function(a){return this.toCollection().each(a)},He.prototype.toArray=function(a){return this.toCollection().toArray(a)},He.prototype.toCollection=function(){return new this.db.Collection(new this.db.WhereClause(this))},He.prototype.orderBy=function(a){return new this.db.Collection(new this.db.WhereClause(this,u(a)?"[".concat(a.join("+"),"]"):a))},He.prototype.reverse=function(){return this.toCollection().reverse()},He.prototype.mapToClass=function(a){var i,c=this.db,p=this.name;function h(){return i!==null&&i.apply(this,arguments)||this}(this.schema.mappedClass=a).prototype instanceof Xo&&((function(I,A){if(typeof A!="function"&&A!==null)throw new TypeError("Class extends value "+String(A)+" is not a constructor or null");function P(){this.constructor=I}r(I,A),I.prototype=A===null?Object.create(A):(P.prototype=A.prototype,new P)})(h,i=a),Object.defineProperty(h.prototype,"db",{get:function(){return c},enumerable:!1,configurable:!0}),h.prototype.table=function(){return p},a=h);for(var g=new Set,w=a.prototype;w;w=f(w))Object.getOwnPropertyNames(w).forEach(function(I){return g.add(I)});function _(I){if(!I)return I;var A,P=Object.create(a.prototype);for(A in I)if(!g.has(A))try{P[A]=I[A]}catch{}return P}return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=_,this.hook("reading",_),a},He.prototype.defineClass=function(){return this.mapToClass(function(a){d(this,a)})},He.prototype.add=function(a,i){var c=this,p=this.schema.primKey,h=p.auto,g=p.keyPath,w=a;return g&&h&&(w=ma(g)(a)),this._trans("readwrite",function(_){return c.core.mutate({trans:_,type:"add",keys:i!=null?[i]:null,values:[w]})}).then(function(_){return _.numFailures?X.reject(_.failures[0]):_.lastResult}).then(function(_){if(g)try{K(a,g,_)}catch{}return _})},He.prototype.update=function(a,i){return typeof a!="object"||u(a)?this.where(":id").equals(a).modify(i):(a=U(a,this.schema.primKey.keyPath),a===void 0?rt(new Q.InvalidArgument("Given object does not contain its primary key")):this.where(":id").equals(a).modify(i))},He.prototype.put=function(a,i){var c=this,p=this.schema.primKey,h=p.auto,g=p.keyPath,w=a;return g&&h&&(w=ma(g)(a)),this._trans("readwrite",function(_){return c.core.mutate({trans:_,type:"put",values:[w],keys:i!=null?[i]:null})}).then(function(_){return _.numFailures?X.reject(_.failures[0]):_.lastResult}).then(function(_){if(g)try{K(a,g,_)}catch{}return _})},He.prototype.delete=function(a){var i=this;return this._trans("readwrite",function(c){return i.core.mutate({trans:c,type:"delete",keys:[a]}).then(function(p){return ga(i,[a],p)}).then(function(p){return p.numFailures?X.reject(p.failures[0]):void 0})})},He.prototype.clear=function(){var a=this;return this._trans("readwrite",function(i){return a.core.mutate({trans:i,type:"deleteRange",range:Yo}).then(function(c){return ga(a,null,c)})}).then(function(i){return i.numFailures?X.reject(i.failures[0]):void 0})},He.prototype.bulkGet=function(a){var i=this;return this._trans("readonly",function(c){return i.core.getMany({keys:a,trans:c}).then(function(p){return p.map(function(h){return i.hook.reading.fire(h)})})})},He.prototype.bulkAdd=function(a,i,c){var p=this,h=Array.isArray(i)?i:void 0,g=(c=c||(h?void 0:i))?c.allKeys:void 0;return this._trans("readwrite",function(w){var A=p.schema.primKey,_=A.auto,A=A.keyPath;if(A&&h)throw new Q.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbou
33nd keys");if(h&&h.length!==a.length)throw new Q.InvalidArgument("Arguments objects and keys must have the same length");var I=a.length,A=A&&_?a.map(ma(A)):a;return p.core.mutate({trans:w,type:"add",keys:h,values:A,wantResults:g}).then(function(C){var k=C.numFailures,j=C.results,T=C.lastResult,C=C.failures;if(k===0)return g?j:T;throw new le("".concat(p.name,".bulkAdd(): ").concat(k," of ").concat(I," operations failed"),C)})})},He.prototype.bulkPut=function(a,i,c){var p=this,h=Array.isArray(i)?i:void 0,g=(c=c||(h?void 0:i))?c.allKeys:void 0;return this._trans("readwrite",function(w){var A=p.schema.primKey,_=A.auto,A=A.keyPath;if(A&&h)throw new Q.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(h&&h.length!==a.length)throw new Q.InvalidArgument("Arguments objects and keys must have the same length");var I=a.length,A=A&&_?a.map(ma(A)):a;return p.core.mutate({trans:w,type:"put",keys:h,values:A,wantResults:g}).then(function(C){var k=C.numFailures,j=C.results,T=C.lastResult,C=C.failures;if(k===0)return g?j:T;throw new le("".concat(p.name,".bulkPut(): ").concat(k," of ").concat(I," operations failed"),C)})})},He.prototype.bulkUpdate=function(a){var i=this,c=this.core,p=a.map(function(w){return w.key}),h=a.map(function(w){return w.changes}),g=[];return this._trans("readwrite",function(w){return c.getMany({trans:w,keys:p,cache:"clone"}).then(function(_){var I=[],A=[];a.forEach(function(k,j){var T=k.key,C=k.changes,N=_[j];if(N){for(var O=0,$=Object.keys(C);O<$.length;O++){var F=$[O],q=C[F];if(F===i.schema.primKey.keyPath){if(Oe(q,T)!==0)throw new Q.Constraint("Cannot update primary key in bulkUpdate()")}else K(N,F,q)}g.push(j),I.push(T),A.push(N)}});var P=I.length;return c.mutate({trans:w,type:"put",keys:I,values:A,updates:{keys:p,changeSpecs:h}}).then(function(k){var j=k.numFailures,T=k.failures;if(j===0)return P;for(var C=0,N=Object.keys(T);C<N.length;C++){var O,$=N[C],F=g[Number($)];F!=null&&(O=T[$],delete T[$],T[F]=O)}throw new le("".concat(i.name,".bulkUpdate(): ").concat(j," of ").concat(P," operations failed"),T)})})})},He.prototype.bulkDelete=function(a){var i=this,c=a.length;return this._trans("readwrite",function(p){return i.core.mutate({trans:p,type:"delete",keys:a}).then(function(h){return ga(i,a,h)})}).then(function(w){var h=w.numFailures,g=w.lastResult,w=w.failures;if(h===0)return g;throw new le("".concat(i.name,".bulkDelete(): ").concat(h," of ").concat(c," operations failed"),w)})},He);function He(){}function An(a){function i(w,_){if(_){for(var I=arguments.length,A=new Array(I-1);--I;)A[I-1]=arguments[I];return c[w].subscribe.apply(null,A),a}if(typeof w=="string")return c[w]}var c={};i.addEventType=g;for(var p=1,h=arguments.length;p<h;++p)g(arguments[p]);return i;function g(w,_,I){if(typeof w!="object"){var A;_=_||jt;var P={subscribers:[],fire:I=I||ye,subscribe:function(k){P.subscribers.indexOf(k)===-1&&(P.subscribers.push(k),P.fire=_(P.fire,k))},unsubscribe:function(k){P.subscribers=P.subscribers.filter(function(j){return j!==k}),P.fire=P.subscribers.reduce(_,I)}};return c[w]=i[w]=P}l(A=w).forEach(function(k){var j=A[k];if(u(j))g(k,A[k][0],A[k][1]);else{if(j!=="asap")throw new Q.InvalidArgument("Invalid event config");var T=g(k,Re,function(){for(var C=arguments.length,N=new Array(C);C--;)N[C]=arguments[C];T.subscribers.forEach(function(O){te(function(){O.apply(null,N)})})})}})}}function Cn(a,i){return S(i).from({prototype:a}),i}function dn(a,i){return!(a.filter||a.algorithm||a.or)&&(i?a.justLimit:!a.replayFilter)}function ms(a,i){a.filter=Br(a.filter,i)}function gs(a,i,c){var p=a.replayFilter;a.replayFilter=p?function(){return Br(p(),i())}:i,a.justLimit=c&&!p}function va(a,i){if(a.isPrimKey)return i.primaryKey;var c=i.getIndexByKeyPath(a.index);if(!c)throw new Q.Schema("KeyPath "+a.index+" on object store "+i.name+" is not indexed");return c}function ni(a,i,c){var p=va(a,i.schema);return i.openCursor({trans:c,values:!a.keysOnly,reverse:a.dir==="prev",unique:!!a.unique,query:{index:p,range:a.range}})}function ya(a,i,c,p){var h=a.replayFilter?Br(a.filter,a.replayFilter()):a.filter;if(a.or){var g={},w=function(_,I,A){var P,k;h&&!h(I,A,function(j){return I.stop(j)},function(j){return I.fail(j)})||((k=""+(P=I.primaryKey))=="[object ArrayBuffer]"&&(k=""+new Uint8Array(P)),b(g,k)||
33(g[k]=!0,i(_,I,A)))};return Promise.all([a.or._iterate(w,c),ai(ni(a,p,c),a.algorithm,w,!a.keysOnly&&a.valueMapper)])}return ai(ni(a,p,c),Br(a.algorithm,h),i,!a.keysOnly&&a.valueMapper)}function ai(a,i,c,p){var h=Be(p?function(g,w,_){return c(p(g),w,_)}:c);return a.then(function(g){if(g)return g.start(function(){var w=function(){return g.continue()};i&&!i(g,function(_){return w=_},function(_){g.stop(_),w=ye},function(_){g.fail(_),w=ye})||h(g.value,g,function(_){return w=_}),w()})})}var Rn=(si.prototype.execute=function(a){var i=this["@@propmod"];if(i.add!==void 0){var c=i.add;if(u(c))return s(s([],u(a)?a:[],!0),c).sort();if(typeof c=="number")return(Number(a)||0)+c;if(typeof c=="bigint")try{return BigInt(a)+c}catch{return BigInt(0)+c}throw new TypeError("Invalid term ".concat(c))}if(i.remove!==void 0){var p=i.remove;if(u(p))return u(a)?a.filter(function(h){return!p.includes(h)}).sort():[];if(typeof p=="number")return Number(a)-p;if(typeof p=="bigint")try{return BigInt(a)-p}catch{return BigInt(0)-p}throw new TypeError("Invalid subtrahend ".concat(p))}return c=(c=i.replacePrefix)===null||c===void 0?void 0:c[0],c&&typeof a=="string"&&a.startsWith(c)?i.replacePrefix[1]+a.substring(c.length):a},si);function si(a){this["@@propmod"]=a}var np=(Fe.prototype._read=function(a,i){var c=this._ctx;return c.error?c.table._trans(null,rt.bind(null,c.error)):c.table._trans("readonly",a).then(i)},Fe.prototype._write=function(a){var i=this._ctx;return i.error?i.table._trans(null,rt.bind(null,i.error)):i.table._trans("readwrite",a,"locked")},Fe.prototype._addAlgorithm=function(a){var i=this._ctx;i.algorithm=Br(i.algorithm,a)},Fe.prototype._iterate=function(a,i){return ya(this._ctx,a,i,this._ctx.table.core)},Fe.prototype.clone=function(a){var i=Object.create(this.constructor.prototype),c=Object.create(this._ctx);return a&&d(c,a),i._ctx=c,i},Fe.prototype.raw=function(){return this._ctx.valueMapper=null,this},Fe.prototype.each=function(a){var i=this._ctx;return this._read(function(c){return ya(i,a,c,i.table.core)})},Fe.prototype.count=function(a){var i=this;return this._read(function(c){var p=i._ctx,h=p.table.core;if(dn(p,!0))return h.count({trans:c,query:{index:va(p,h.schema),range:p.range}}).then(function(w){return Math.min(w,p.limit)});var g=0;return ya(p,function(){return++g,!1},c,h).then(function(){return g})}).then(a)},Fe.prototype.sortBy=function(a,i){var c=a.split(".").reverse(),p=c[0],h=c.length-1;function g(I,A){return A?g(I[c[A]],A-1):I[p]}var w=this._ctx.dir==="next"?1:-1;function _(I,A){return Oe(g(I,h),g(A,h))*w}return this.toArray(function(I){return I.sort(_)}).then(i)},Fe.prototype.toArray=function(a){var i=this;return this._read(function(c){var p=i._ctx;if(p.dir==="next"&&dn(p,!0)&&0<p.limit){var h=p.valueMapper,g=va(p,p.table.core.schema);return p.table.core.query({trans:c,limit:p.limit,values:!0,query:{index:g,range:p.range}}).then(function(_){return _=_.result,h?_.map(h):_})}var w=[];return ya(p,function(_){return w.push(_)},c,p.table.core).then(function(){return w})},a)},Fe.prototype.offset=function(a){var i=this._ctx;return a<=0||(i.offset+=a,dn(i)?gs(i,function(){var c=a;return function(p,h){return c===0||(c===1?--c:h(function(){p.advance(c),c=0}),!1)}}):gs(i,function(){var c=a;return function(){return--c<0}})),this},Fe.prototype.limit=function(a){return this._ctx.limit=Math.min(this._ctx.limit,a),gs(this._ctx,function(){var i=a;return function(c,p,h){return--i<=0&&p(h),0<=i}},!0),this},Fe.prototype.until=function(a,i){return ms(this._ctx,function(c,p,h){return!a(c.value)||(p(h),i)}),this},Fe.prototype.first=function(a){return this.limit(1).toArray(function(i){return i[0]}).then(a)},Fe.prototype.last=function(a){return this.reverse().first(a)},Fe.prototype.filter=function(a){var i;return ms(this._ctx,function(c){return a(c.value)}),(i=this._ctx).isMatch=Br(i.isMatch,a),this},Fe.prototype.and=function(a){return this.filter(a)},Fe.prototype.or=function(a){return new this.db.WhereClause(this._ctx.table,a,this)},Fe.prototype.reverse=function(){return this._ctx.dir=this._ctx.dir==="prev"?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this},Fe.prototype.desc=function(){return this.reverse()},Fe.prototype.eachKey=function(a){var i=this._ctx;return i.keysOnly=!i.isMatch,this.each(function(c,p){a(p.key,p)})},Fe.prototype.eachUniqueKey=function(a){return this._ctx.unique="unique",this.eachKey(a)},Fe.prototype.eachPrimaryKey=function(a){var i=this._ctx;return i.keysOnly=!i.isMatch,this.each(function(c,p){a(p.primaryKey,p)})},Fe.prototype.keys=function(a){var i=this._ctx;i.keysOnly=!i.isMatch;var c=[];return this.each(function(p,h){c.push(h.key)}).then(function(){return c}).then(a)},Fe.prototype.primaryKeys=function(a){var i=this._ctx;if(i.dir==="next"&&dn(i,!0)&&0<i.limit)return this._read(function(p){var h=va(i,i.table.core.schema);return i.table.core.query({trans:p,values:!1,limit:i.limit,query:{index:h,range:i.range}})}).then(function(p){return p.result}).then(a);i.keysOnly=!i.isMatch;var c=[];return this.each(function(p,h){c.push(h.primaryKey)}).then(function(){return c}).then(a)},Fe.prototype.uniqueKeys=function(a){return this._ctx.unique="unique",this.keys(a)},Fe.prototype.firstKey=function(a){return this.limit(1).keys(function(i){return i[0]}).then(a)},Fe.prototype.lastKey=function(a){return this.reverse().firstKey(a)},Fe.prototype.distinct=function(){var a=this._ctx,a=a.index&&a.table.schema.idxByName[a.index];if(!a||!a.multi)return this;var i={};return ms(this._ctx,function(h){var p=h.primaryKey.toString(),h=b(i,p);return i[p]=!0,!h}),this},Fe.prototype.modify=function(a){var i=this,c=this._ctx;return this._write(function(p){var h,g,w;w=typeof a=="function"?a:(h=l(a),g=h.length,function($){for(var F=!1,q=0;q<g;++q){var L=h[q],G=a[L],J=U($,L);G instanceof Rn?(K($,L,G.execute(J)),F=!0):J!==G&&(K($,L,G),F=!0)}return F});
33var _=c.table.core,k=_.schema.primaryKey,I=k.outbound,A=k.extractKey,P=200,k=i.db._options.modifyChunkSize;k&&(P=typeof k=="object"?k[_.name]||k["*"]||200:k);function j($,L){var q=L.failures,L=L.numFailures;C+=$-L;for(var G=0,J=l(q);G<J.length;G++){var Z=J[G];T.push(q[Z])}}var T=[],C=0,N=[],O=a===oi;return i.clone().primaryKeys().then(function($){function F(L){var G=Math.min(P,$.length-L),J=$.slice(L,L+G);return(O?Promise.resolve([]):_.getMany({trans:p,keys:J,cache:"immutable"})).then(function(Z){var W=[],re=[],ee=I?[]:null,ae=O?J:[];if(!O)for(var Te=0;Te<G;++Te){var Me=Z[Te],xe={value:ke(Me),primKey:$[L+Te]};w.call(xe,xe.value,xe)!==!1&&(xe.value==null?ae.push($[L+Te]):I||Oe(A(Me),A(xe.value))===0?(re.push(xe.value),I&&ee.push($[L+Te])):(ae.push($[L+Te]),W.push(xe.value)))}return Promise.resolve(0<W.length&&_.mutate({trans:p,type:"add",values:W}).then(function(Ye){for(var _e in Ye.failures)ae.splice(parseInt(_e),1);j(W.length,Ye)})).then(function(){return(0<re.length||q&&typeof a=="object")&&_.mutate({trans:p,type:"put",keys:ee,values:re,criteria:q,changeSpec:typeof a!="function"&&a,isAdditionalChunk:0<L}).then(function(Ye){return j(re.length,Ye)})}).then(function(){return(0<ae.length||q&&O)&&_.mutate({trans:p,type:"delete",keys:ae,criteria:q,isAdditionalChunk:0<L}).then(function(Ye){return ga(c.table,ae,Ye)}).then(function(Ye){return j(ae.length,Ye)})}).then(function(){return $.length>L+G&&F(L+P)})})}var q=dn(c)&&c.limit===1/0&&(typeof a!="function"||O)&&{index:c.index,range:c.range};return F(0).then(function(){if(0<T.length)throw new Y("Error modifying one or more objects",T,C,N);return $.length})})})},Fe.prototype.delete=function(){var a=this._ctx,i=a.range;return!dn(a)||a.table.schema.yProps||!a.isPrimKey&&i.type!==3?this.modify(oi):this._write(function(c){var p=a.table.core.schema.primaryKey,h=i;return a.table.core.count({trans:c,query:{index:p,range:h}}).then(function(g){return a.table.core.mutate({trans:c,type:"deleteRange",range:h}).then(function(I){var _=I.failures,I=I.numFailures;if(I)throw new Y("Could not delete some values",Object.keys(_).map(function(A){return _[A]}),g-I);return g-I})})})},Fe);function Fe(){}var oi=function(a,i){return i.value=null};function ap(a,i){return a<i?-1:a===i?0:1}function sp(a,i){return i<a?-1:a===i?0:1}function Pt(a,i,c){return a=a instanceof li?new a.Collection(a):a,a._ctx.error=new(c||TypeError)(i),a}function pn(a){return new a.Collection(a,function(){return ii("")}).limit(0)}function ba(a,i,c,p){var h,g,w,_,I,A,P,k=c.length;if(!c.every(function(C){return typeof C=="string"}))return Pt(a,Qo);function j(C){h=C==="next"?function(O){return O.toUpperCase()}:function(O){return O.toLowerCase()},g=C==="next"?function(O){return O.toLowerCase()}:function(O){return O.toUpperCase()},w=C==="next"?ap:sp;var N=c.map(function(O){return{lower:g(O),upper:h(O)}}).sort(function(O,$){return w(O.lower,$.lower)});_=N.map(function(O){return O.upper}),I=N.map(function(O){return O.lower}),P=(A=C)==="next"?"":p}j("next"),a=new a.Collection(a,function(){return Ir(_[0],I[k-1]+p)}),a._ondirectionchange=function(C){j(C)};var T=0;return a._addAlgorithm(function(C,N,O){var $=C.key;if(typeof $!="string")return!1;var F=g($);if(i(F,I,T))return!0;for(var q=null,L=T;L<k;++L){var G=(function(J,Z,W,re,ee,ae){for(var Te=Math.min(J.length,re.length),Me=-1,xe=0;xe<Te;++xe){var Ye=Z[xe];if(Ye!==re[xe])return ee(J[xe],W[xe])<0?J.substr(0,xe)+W[xe]+W.substr(xe+1):ee(J[xe],re[xe])<0?J.substr(0,xe)+re[xe]+W.substr(xe+1):0<=Me?J.substr(0,Me)+Z[Me]+W.substr(Me+1):null;ee(J[xe],Ye)<0&&(Me=xe)}return Te<re.length&&ae==="next"?J+W.substr(J.length):Te<J.length&&ae==="prev"?J.substr(0,W.length):Me<0?null:J.substr(0,Me)+re[Me]+W.substr(Me+1)})($,F,_[L],I[L],w,A);G===null&&q===null?T=L+1:(q===null||0<w(q,G))&&(q=G)}return N(q!==null?function(){C.continue(q+P)}:O),!1}),a}function Ir(a,i,c,p){return{type:2,lower:a,upper:i,lowerOpen:c,upperOpen:p}}function ii(a){return{type:1,lower:a,upper:a}}var li=(Object.defineProperty(ct.prototype,"Collection",{get:function(){return this._ctx.table.db.Collection},enumerable:!1,configurable:!0}),ct.prototype.between=function(a,i,c,p){c=c!==!1,p=p===!0;try{return 0<this._cmp(a,i)||this._cmp(a,i)===0&&(c||p)&&(!c||!p)?pn(this):new this.Collection(this,function(){return Ir(a,i,!c,!p)})}catch{return Pt(this,or)}},ct.prototype.equals=function(a){return a==null?Pt(this,or):new this.Collection(this,function(){return ii(a)})},ct.prototype.above=function(a){return a==null?Pt(this,or):new this.Collection(this,function(){return Ir(a,void 0,!0)})},ct.prototype.aboveOrEqual=function(a){return a==null?Pt(this,or):new this.Collection(this,function(){return Ir(a,void 0,!1)})},ct.prototype.below=function(a){return a==null?Pt(this,or):new this.Collection(this,function(){return Ir(void 0,a,!1,!0)})},ct.prototype.belowOrEqual=function(a){return a==null?Pt(this,or):new this.Collection(this,function(){return Ir(void 0,a)})},ct.prototype.startsWith=function(a){return typeof a!="string"?Pt(this,Qo):this.between(a,a+Lr,!0,!0)},ct.prototype.startsWithIgnoreCase=function(a){return a===""?this.startsWith(a):ba(this,function(i,c){return i.indexOf(c[0])===0},[a],Lr)},ct.prototype.equalsIgnoreCase=function(a){return ba(this,function(i,c){return i===c[0]},[a],"")},ct.prototype.anyOfIgnoreCase=function(){var a=ne.apply(pe,arguments);return a.length===0?pn(this):ba(this,function(i,c){return c.indexOf(i)!==-1},a,"")},ct.prototype.startsWithAnyOfIgnoreCase=function(){var a=ne.apply(pe,arguments);return a.length===0?pn(this):ba(this,function(i,c){return c.some(function(p){return i.indexOf(p)===0})},a,Lr)},ct.prototype.anyOf=function(){var a=this,i=ne.apply(pe,arguments),c=this._cmp;try{i.sort(c)}catch{return Pt(this,or)}if(i.length===0)return pn(this);var p=new this.Collection(this,function(){return Ir(i[0],i[i.length-1])});p._ondirectionchange=function(g){c=g==="next"?a._ascending:a._descending,i.sort(c)};var h=0;return p._addAlgorithm(function(g,w,_){for(var I=g.key;0<c(I,i[h]);
33)if(++h===i.length)return w(_),!1;return c(I,i[h])===0||(w(function(){g.continue(i[h])}),!1)}),p},ct.prototype.notEqual=function(a){return this.inAnyRange([[-1/0,a],[a,this.db._maxKey]],{includeLowers:!1,includeUppers:!1})},ct.prototype.noneOf=function(){var a=ne.apply(pe,arguments);if(a.length===0)return new this.Collection(this);try{a.sort(this._ascending)}catch{return Pt(this,or)}var i=a.reduce(function(c,p){return c?c.concat([[c[c.length-1][1],p]]):[[-1/0,p]]},null);return i.push([a[a.length-1],this.db._maxKey]),this.inAnyRange(i,{includeLowers:!1,includeUppers:!1})},ct.prototype.inAnyRange=function($,i){var c=this,p=this._cmp,h=this._ascending,g=this._descending,w=this._min,_=this._max;if($.length===0)return pn(this);if(!$.every(function(F){return F[0]!==void 0&&F[1]!==void 0&&h(F[0],F[1])<=0}))return Pt(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",Q.InvalidArgument);var I=!i||i.includeLowers!==!1,A=i&&i.includeUppers===!0,P,k=h;function j(F,q){return k(F[0],q[0])}try{(P=$.reduce(function(F,q){for(var L=0,G=F.length;L<G;++L){var J=F[L];if(p(q[0],J[1])<0&&0<p(q[1],J[0])){J[0]=w(J[0],q[0]),J[1]=_(J[1],q[1]);break}}return L===G&&F.push(q),F},[])).sort(j)}catch{return Pt(this,or)}var T=0,C=A?function(F){return 0<h(F,P[T][1])}:function(F){return 0<=h(F,P[T][1])},N=I?function(F){return 0<g(F,P[T][0])}:function(F){return 0<=g(F,P[T][0])},O=C,$=new this.Collection(this,function(){return Ir(P[0][0],P[P.length-1][1],!I,!A)});return $._ondirectionchange=function(F){k=F==="next"?(O=C,h):(O=N,g),P.sort(j)},$._addAlgorithm(function(F,q,L){for(var G,J=F.key;O(J);)if(++T===P.length)return q(L),!1;return!C(G=J)&&!N(G)||(c._cmp(J,P[T][1])===0||c._cmp(J,P[T][0])===0||q(function(){k===h?F.continue(P[T][0]):F.continue(P[T][1])}),!1)}),$},ct.prototype.startsWithAnyOf=function(){var a=ne.apply(pe,arguments);return a.every(function(i){return typeof i=="string"})?a.length===0?pn(this):this.inAnyRange(a.map(function(i){return[i,i+Lr]})):Pt(this,"startsWithAnyOf() only works with strings")},ct);function ct(){}function Qt(a){return Be(function(i){return Pn(i),a(i.target.error),!1})}function Pn(a){a.stopPropagation&&a.stopPropagation(),a.preventDefault&&a.preventDefault()}var On="storagemutated",vs="x-storagemutated-1",Tr=An(null,On),op=(Yt.prototype._lock=function(){return E(!ue.global),++this._reculock,this._reculock!==1||ue.global||(ue.lockOwnerFor=this),this},Yt.prototype._unlock=function(){if(E(!ue.global),--this._reculock==0)for(ue.global||(ue.lockOwnerFor=null);0<this._blockedFuncs.length&&!this._locked();){var a=this._blockedFuncs.shift();try{qr(a[1],a[0])}catch{}}return this},Yt.prototype._locked=function(){return this._reculock&&ue.lockOwnerFor!==this},Yt.prototype.create=function(a){var i=this;if(!this.mode)return this;var c=this.db.idbdb,p=this.db._state.dbOpenError;if(E(!this.idbtrans),!a&&!c)switch(p&&p.name){case"DatabaseClosedError":throw new Q.DatabaseClosed(p);case"MissingAPIError":throw new Q.MissingAPI(p.message,p);default:throw new Q.OpenFailed(p)}if(!this.active)throw new Q.TransactionInactive;return E(this._completion._state===null),(a=this.idbtrans=a||(this.db.core||c).transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability})).onerror=Be(function(h){Pn(h),i._reject(a.error)}),a.onabort=Be(function(h){Pn(h),i.active&&i._reject(new Q.Abort(a.error)),i.active=!1,i.on("abort").fire(h)}),a.oncomplete=Be(function(){i.active=!1,i._resolve(),"mutatedParts"in a&&Tr.storagemutated.fire(a.mutatedParts)}),this},Yt.prototype._promise=function(a,i,c){var p=this;if(a==="readwrite"&&this.mode!=="readwrite")return rt(new Q.ReadOnly("Transaction is readonly"));if(!this.active)return rt(new Q.TransactionInactive);if(this._locked())return new X(function(g,w){p._blockedFuncs.push([function(){p._promise(a,i,c).then(g,w)},ue])});if(c)return xr(function(){var g=new X(function(w,_){p._lock();var I=i(w,_,p);I&&I.then&&I.then(w,_)});return g.finally(function(){return p._unlock()}),g._lib=!0,g});var h=new X(function(g,w){var _=i(g,w,p);_&&_.then&&_.then(g,w)});return h._lib=!0,h},Yt.prototype._root=function(){return this.parent?this.parent._root():this},Yt.prototype.waitFor=function(a){var i,c=this._root(),p=X.resolve(a);c._waitingFor?c._waitingFor=c._waitingFor.then(function(){return p}):(c._waitingFor=p,c._waitingQueue=[],i=c.idbtrans.objectStore(c.storeNames[0]),(function g(){for(++c._spinCount;c._waitingQueue.length;)c._waitingQueue.shift()();c._waitingFor&&(i.get(-1/0).onsuccess=g)})());var h=c._waitingFor;return new X(function(g,w){p.then(function(_){return c._waitingQueue.push(Be(g.bind(null,_)))},function(_){return c._waitingQueue.push(Be(w.bind(null,_)))}
33).finally(function(){c._waitingFor===h&&(c._waitingFor=null)})})},Yt.prototype.abort=function(){this.active&&(this.active=!1,this.idbtrans&&this.idbtrans.abort(),this._reject(new Q.Abort))},Yt.prototype.table=function(a){var i=this._memoizedTables||(this._memoizedTables={});if(b(i,a))return i[a];var c=this.schema[a];if(!c)throw new Q.NotFound("Table "+a+" not part of transaction");return c=new this.db.Table(a,c,this),c.core=this.db.core.table(a),i[a]=c},Yt);function Yt(){}function ys(a,i,c,p,h,g,w,_){return{name:a,keyPath:i,unique:c,multi:p,auto:h,compound:g,src:(c&&!w?"&":"")+(p?"*":"")+(h?"++":"")+ui(i),type:_}}function ui(a){return typeof a=="string"?a:a?"["+[].join.call(a,"+")+"]":""}function bs(a,i,c){return{name:a,primKey:i,indexes:c,mappedClass:null,idxByName:(p=function(h){return[h.name,h]},c.reduce(function(h,g,w){return w=p(g,w),w&&(h[w[0]]=w[1]),h},{}))};var p}var Mn=function(a){try{return a.only([[]]),Mn=function(){return[[]]},[[]]}catch{return Mn=function(){return Lr},Lr}};function ws(a){return a==null?function(){}:typeof a=="string"?(i=a).split(".").length===1?function(c){return c[i]}:function(c){return U(c,i)}:function(c){return U(c,a)};var i}function ci(a){return[].slice.call(a)}var ip=0;function Nn(a){return a==null?":id":typeof a=="string"?a:"[".concat(a.join("+"),"]")}function lp(a,i,I){function p(O){if(O.type===3)return null;if(O.type===4)throw new Error("Cannot convert never type to IDBKeyRange");var T=O.lower,C=O.upper,N=O.lowerOpen,O=O.upperOpen;return T===void 0?C===void 0?null:i.upperBound(C,!!O):C===void 0?i.lowerBound(T,!!N):i.bound(T,C,!!N,!!O)}function h(j){var T,C=j.name;return{name:C,schema:j,mutate:function(N){var O=N.trans,$=N.type,F=N.keys,q=N.values,L=N.range;return new Promise(function(G,J){G=Be(G);var Z=O.objectStore(C),W=Z.keyPath==null,re=$==="put"||$==="add";if(!re&&$!=="delete"&&$!=="deleteRange")throw new Error("Invalid operation type: "+$);var ee,ae=(F||q||{length:1}).length;if(F&&q&&F.length!==q.length)throw new Error("Given keys array must have same length as given values array.");if(ae===0)return G({numFailures:0,failures:{},results:[],lastResult:void 0});function Te(_t){++Ye,Pn(_t)}var Me=[],xe=[],Ye=0;if($==="deleteRange"){if(L.type===4)return G({numFailures:Ye,failures:xe,results:[],lastResult:void 0});L.type===3?Me.push(ee=Z.clear()):Me.push(ee=Z.delete(p(L)))}else{var W=re?W?[q,F]:[q,null]:[F,null],_e=W[0],mt=W[1];if(re)for(var gt=0;gt<ae;++gt)Me.push(ee=mt&&mt[gt]!==void 0?Z[$](_e[gt],mt[gt]):Z[$](_e[gt])),ee.onerror=Te;else for(gt=0;gt<ae;++gt)Me.push(ee=Z[$](_e[gt])),ee.onerror=Te}function Pa(_t){_t=_t.target.result,Me.forEach(function(Kr,Fs){return Kr.error!=null&&(xe[Fs]=Kr.error)}),G({numFailures:Ye,failures:xe,results:$==="delete"?F:Me.map(function(Kr){return Kr.result}),lastResult:_t})}ee.onerror=function(_t){Te(_t),Pa(_t)},ee.onsuccess=Pa})},getMany:function(N){var O=N.trans,$=N.keys;return new Promise(function(F,q){F=Be(F);for(var L,G=O.objectStore(C),J=$.length,Z=new Array(J),W=0,re=0,ee=function(Me){Me=Me.target,Z[Me._pos]=Me.result,++re===W&&F(Z)},ae=Qt(q),Te=0;Te<J;++Te)$[Te]!=null&&((L=G.get($[Te]))._pos=Te,L.onsuccess=ee,L.onerror=ae,++W);W===0&&F(Z)})},get:function(N){var O=N.trans,$=N.key;return new Promise(function(F,q){F=Be(F);var L=O.objectStore(C).get($);L.onsuccess=function(G){return F(G.target.result)},L.onerror=Qt(q)})},query:(T=A,function(N){return new Promise(function(O,$){O=Be(O);var F,q,L,W=N.trans,G=N.values,J=N.limit,ee=N.query,Z=J===1/0?void 0:J,re=ee.index,ee=ee.range,W=W.objectStore(C),re=re.isPrimaryKey?W:W.index(re.name),ee=p(ee);if(J===0)return O({result:[]});T?((Z=G?re.getAll(ee,Z):re.getAllKeys(ee,Z)).onsuccess=function(ae){return O({result:ae.target.result})},Z.onerror=Qt($)):(F=0,q=!G&&"openKeyCursor"in re?re.openKeyCursor(ee):re.openCursor(ee),L=[],q.onsuccess=function(ae){var Te=q.result;return Te?(L.push(G?Te.value:Te.primaryKey),++F===J?O({result:L}):void Te.continue()):O({result:L})},q.onerror=Qt($))})}),openCursor:function(N){var O=N.trans,$=N.values,F=N.query,q=N.reverse,L=N.unique;return new Promise(function(G,J){G=Be(G);var re=F.index,Z=F.range,W=O.objectStore(C),W=re.isPrimaryKey?W:W.index(re.name),re=q?L?"prevunique":"prev":L?"nextunique":"next",ee=!$&&"openKeyCursor"in W?W.openKeyCursor(p(Z),re):W.openCursor(p(Z),re);ee.onerror=Qt(J),ee.onsuccess=Be(function(ae){var Te,Me,xe,Ye,_e=ee.result;_e?(_e.___id=++ip,_e.done=!1,Te=_e.continue.bind(_e),Me=(Me=_e.continuePrimaryKey)&&Me.bind(_e),xe=_e.advance.b
33ind(_e),Ye=function(){throw new Error("Cursor not stopped")},_e.trans=O,_e.stop=_e.continue=_e.continuePrimaryKey=_e.advance=function(){throw new Error("Cursor not started")},_e.fail=Be(J),_e.next=function(){var mt=this,gt=1;return this.start(function(){return gt--?mt.continue():mt.stop()}).then(function(){return mt})},_e.start=function(mt){function gt(){if(ee.result)try{mt()}catch(_t){_e.fail(_t)}else _e.done=!0,_e.start=function(){throw new Error("Cursor behind last entry")},_e.stop()}var Pa=new Promise(function(_t,Kr){_t=Be(_t),ee.onerror=Qt(Kr),_e.fail=Kr,_e.stop=function(Fs){_e.stop=_e.continue=_e.continuePrimaryKey=_e.advance=Ye,_t(Fs)}});return ee.onsuccess=Be(function(_t){ee.onsuccess=gt,gt()}),_e.continue=Te,_e.continuePrimaryKey=Me,_e.advance=xe,gt(),Pa},G(_e)):G(null)},J)})},count:function(N){var O=N.query,$=N.trans,F=O.index,q=O.range;return new Promise(function(L,G){var J=$.objectStore(C),Z=F.isPrimaryKey?J:J.index(F.name),J=p(q),Z=J?Z.count(J):Z.count();Z.onsuccess=Be(function(W){return L(W.target.result)}),Z.onerror=Qt(G)})}}}var g,w,_,P=(w=I,_=ci((g=a).objectStoreNames),{schema:{name:g.name,tables:_.map(function(j){return w.objectStore(j)}).map(function(j){var T=j.keyPath,O=j.autoIncrement,C=u(T),N={},O={name:j.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:T==null,compound:C,keyPath:T,autoIncrement:O,unique:!0,extractKey:ws(T)},indexes:ci(j.indexNames).map(function($){return j.index($)}).map(function(L){var F=L.name,q=L.unique,G=L.multiEntry,L=L.keyPath,G={name:F,compound:u(L),keyPath:L,unique:q,multiEntry:G,extractKey:ws(L)};return N[Nn(L)]=G}),getIndexByKeyPath:function($){return N[Nn($)]}};return N[":id"]=O.primaryKey,T!=null&&(N[Nn(T)]=O.primaryKey),O})},hasGetAll:0<_.length&&"getAll"in w.objectStore(_[0])&&!(typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604)}),I=P.schema,A=P.hasGetAll,P=I.tables.map(h),k={};return P.forEach(function(j){return k[j.name]=j}),{stack:"dbcore",transaction:a.transaction.bind(a),table:function(j){if(!k[j])throw new Error("Table '".concat(j,"' not found"));return k[j]},MIN_KEY:-1/0,MAX_KEY:Mn(i),schema:I}}function up(a,i,c,p){var h=c.IDBKeyRange;return c.indexedDB,{dbcore:(p=lp(i,h,p),a.dbcore.reduce(function(g,w){return w=w.create,n(n({},g),w(g))},p))}}function wa(a,p){var c=p.db,p=up(a._middlewares,c,a._deps,p);a.core=p.dbcore,a.tables.forEach(function(h){var g=h.name;a.core.schema.tables.some(function(w){return w.name===g})&&(h.core=a.core.table(g),a[g]instanceof a.Table&&(a[g].core=h.core))})}
33function _a(a,i,c,p){c.forEach(function(h){var g=p[h];i.forEach(function(w){var _=(function I(A,P){return M(A,P)||(A=f(A))&&I(A,P)})(w,h);(!_||"value"in _&&_.value===void 0)&&(w===a.Transaction.prototype||w instanceof a.Transaction?x(w,h,{get:function(){return this.table(h)},set:function(I){y(this,h,{value:I,writable:!0,configurable:!0,enumerable:!0})}}):w[h]=new a.Table(h,g))})})}function _s(a,i){i.forEach(function(c){for(var p in c)c[p]instanceof a.Table&&delete c[p]})}function cp(a,i){return a._cfg.version-i._cfg.version}function dp(a,i,c,p){var h=a._dbSchema;c.objectStoreNames.contains("$meta")&&!h.$meta&&(h.$meta=bs("$meta",pi("")[0],[]),a._storeNames.push("$meta"));var g=a._createTransaction("readwrite",a._storeNames,h);g.create(c),g._completion.catch(p);var w=g._reject.bind(g),_=ue.transless||ue;xr(function(){return ue.trans=g,ue.transless=_,i!==0?(wa(a,c),A=i,((I=g).storeNames.includes("$meta")?I.table("$meta").get("version").then(function(P){return P??A}):X.resolve(A)).then(function(P){return j=P,T=g,C=c,N=[],P=(k=a)._versions,O=k._dbSchema=ka(0,k.idbdb,C),(P=P.filter(function($){return $._cfg.version>=j})).length!==0?(P.forEach(function($){N.push(function(){var F=O,q=$._cfg.dbschema;Sa(k,F,C),Sa(k,q,C),O=k._dbSchema=q;var L=xs(F,q);L.add.forEach(function(re){ks(C,re[0],re[1].primKey,re[1].indexes)}),L.change.forEach(function(re){if(re.recreate)throw new Q.Upgrade("Not yet support for changing primary key");var ee=C.objectStore(re.name);re.add.forEach(function(ae){return xa(ee,ae)}),re.change.forEach(function(ae){ee.deleteIndex(ae.name),xa(ee,ae)}),re.del.forEach(function(ae){return ee.deleteIndex(ae)})});var G=$._cfg.contentUpgrade;if(G&&$._cfg.version>j){wa(k,C),T._memoizedTables={};var J=ce(q);L.del.forEach(function(re){J[re]=F[re]}),_s(k,[k.Transaction.prototype]),_a(k,[k.Transaction.prototype],l(J),J),T.schema=J;var Z,W=je(G);return W&&un(),L=X.follow(function(){var re;(Z=G(T))&&W&&(re=kr.bind(null,null),Z.then(re,re))}),Z&&typeof Z.then=="function"?X.resolve(Z):L.then(function(){return Z})}}),N.push(function(F){var q,L,G=$._cfg.dbschema;q=G,L=F,[].slice.call(L.db.objectStoreNames).forEach(function(J){return q[J]==null&&L.db.deleteObjectStore(J)}),_s(k,[k.Transaction.prototype]),_a(k,[k.Transaction.prototype],k._storeNames,k._dbSchema),T.schema=k._dbSchema}),N.push(function(F){k.idbdb.objectStoreNames.contains("$meta")&&(Math.ceil(k.idbdb.version/10)===$._cfg.version?(k.idbdb.deleteObjectStore("$meta"),delete k._dbSchema.$meta,k._storeNames=k._storeNames.filter(function(q){return q!=="$meta"})):F.objectStore("$meta").put($._cfg.version,"version"))})}),(function $(){return N.length?X.resolve(N.shift()(T.idbtrans)).then($):X.resolve()})().then(function(){di(O,C)})):X.resolve();var k,j,T,C,N,O}).catch(w)):(l(h).forEach(function(P){ks(c,P,h[P].primKey,h[P].indexes)}),wa(a,c),void X.follow(function(){return a.on.populate.fire(g)}).catch(w));var I,A})}function pp(a,i){di(a._dbSchema,i),i.db.version%10!=0||i.objectStoreNames.contains("$meta")||i.db.createObjectStore("$meta").add(Math.ceil(i.db.version/10-1),"version");var c=ka(0,a.idbdb,i);Sa(a,a._dbSchema,i);for(var p=0,h=xs(c,a._dbSchema).change;p<h.length;p++){var g=(function(w){if(w.change.length||w.recreate)return console.warn("Unable to patch indexes of table ".concat(w.name," because it has changes on the type of index or primary key.")),{value:void 0};var _=i.objectStore(w.name);w.add.forEach(function(I){Ee&&console.debug("Dexie upgrade patch: Creating missing index ".concat(w.name,".").concat(I.src)),xa(_,I)})})(h[p]);if(typeof g=="object")return g.value}}function xs(a,i){var c,p={del:[],add:[],change:[]};for(c in a)i[c]||p.del.push(c);for(c in i){var h=a[c],g=i[c];if(h){var w={name:c,def:g,recreate:!1,del:[],add:[],change:[]};if(""+(h.primKey.keyPath||"")!=""+(g.primKey.keyPath||"")||h.primKey.auto!==g.primKey.auto)w.recreate=!0,p.change.push(w);else{var _=h.idxByName,I=g.idxByName,A=void 0;for(A in _)I[A]||w.del.push(A);for(A in I){var P=_[A],k=I[A];P?P.src!==k.src&&w.change.push(k):w.add.push(k)}(0<w.del.length||0<w.add.length||0<w.change.length)&&p.change.push(w)}}else p.add.push([c,g])}return p}function ks(a,i,c,p){var h=a.db.createObjectStore(i,c.keyPath?{keyPath:c.keyPath,autoIncrement:c.auto}:{autoIncrement:c.auto});return p.forEach(function(g){return xa(h,g)}),h}
33function di(a,i){l(a).forEach(function(c){i.db.objectStoreNames.contains(c)||(Ee&&console.debug("Dexie: Creating missing table",c),ks(i,c,a[c].primKey,a[c].indexes))})}function xa(a,i){a.createIndex(i.name,i.keyPath,{unique:i.unique,multiEntry:i.multi})}function ka(a,i,c){var p={};return B(i.objectStoreNames,0).forEach(function(h){for(var g=c.objectStore(h),w=ys(ui(A=g.keyPath),A||"",!0,!1,!!g.autoIncrement,A&&typeof A!="string",!0),_=[],I=0;I<g.indexNames.length;++I){var P=g.index(g.indexNames[I]),A=P.keyPath,P=ys(P.name,A,!!P.unique,!!P.multiEntry,!1,A&&typeof A!="string",!1);_.push(P)}p[h]=bs(h,w,_)}),p}function Sa(a,i,c){for(var p=c.db.objectStoreNames,h=0;h<p.length;++h){var g=p[h],w=c.objectStore(g);a._hasGetAll="getAll"in w;for(var _=0;_<w.indexNames.length;++_){var I=w.indexNames[_],A=w.index(I).keyPath,P=typeof A=="string"?A:"["+B(A).join("+")+"]";!i[g]||(A=i[g].idxByName[P])&&(A.name=I,delete i[g].idxByName[P],i[g].idxByName[I]=A)}}typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&o.WorkerGlobalScope&&o instanceof o.WorkerGlobalScope&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604&&(a._hasGetAll=!1)}function pi(a){return a.split(",").map(function(i,c){var g=i.split(":"),p=(h=g[1])===null||h===void 0?void 0:h.trim(),h=(i=g[0].trim()).replace(/([&*]|\+\+)/g,""),g=/^\[/.test(h)?h.match(/^\[(.*)\]$/)[1].split("+"):h;return ys(h,g||null,/\&/.test(i),/\*/.test(i),/\+\+/.test(i),u(g),c===0,p)})}var fp=(fn.prototype._createTableSchema=bs,fn.prototype._parseIndexSyntax=pi,fn.prototype._parseStoresSpec=function(a,i){var c=this;l(a).forEach(function(p){if(a[p]!==null){var h=c._parseIndexSyntax(a[p]),g=h.shift();if(!g)throw new Q.Schema("Invalid schema for table "+p+": "+a[p]);if(g.unique=!0,g.multi)throw new Q.Schema("Primary key cannot be multiEntry*");h.forEach(function(w){if(w.auto)throw new Q.Schema("Only primary key can be marked as autoIncrement (++)");if(!w.keyPath)throw new Q.Schema("Index must have a name and cannot be an empty string")}),h=c._createTableSchema(p,g,h),i[p]=h}})},fn.prototype.stores=function(c){var i=this.db;this._cfg.storesSource=this._cfg.storesSource?d(this._cfg.storesSource,c):c;var c=i._versions,p={},h={};return c.forEach(function(g){d(p,g._cfg.storesSource),h=g._cfg.dbschema={},g._parseStoresSpec(p,h)}),i._dbSchema=h,_s(i,[i._allTables,i,i.Transaction.prototype]),_a(i,[i._allTables,i,i.Transaction.prototype,this._cfg.tables],l(h),h),i._storeNames=l(h),this},fn.prototype.upgrade=function(a){return this._cfg.contentUpgrade=se(this._cfg.contentUpgrade||ye,a),this},fn);function fn(){}function Ss(a,i){var c=a._dbNamesDB;return c||(c=a._dbNamesDB=new ir(ha,{addons:[],indexedDB:a,IDBKeyRange:i})).version(1).stores({dbnames:"name"}),c.table("dbnames")}function Is(a){return a&&typeof a.databases=="function"}function Ts(a){return xr(function(){return ue.letThrough=!0,a()})}function Es(a){return!("from"in a)}var ht=function(a,i){if(!this){var c=new ht;return a&&"d"in a&&d(c,a),c}d(this,arguments.length?{d:1,from:a,to:1<arguments.length?i:a}:{d:0})};function jn(a,i,c){var p=Oe(i,c);if(!isNaN(p)){if(0<p)throw RangeError();if(Es(a))return d(a,{from:i,to:c,d:1});var h=a.l,p=a.r;if(Oe(c,a.from)<0)return h?jn(h,i,c):a.l={from:i,to:c,d:1,l:null,r:null},hi(a);if(0<Oe(i,a.to))return p?jn(p,i,c):a.r={from:i,to:c,d:1,l:null,r:null},hi(a);Oe(i,a.from)<0&&(a.from=i,a.l=null,a.d=p?p.d+1:1),0<Oe(c,a.to)&&(a.to=c,a.r=null,a.d=a.l?a.l.d+1:1),c=!a.r,h&&!a.l&&$n(a,h),p&&c&&$n(a,p)}}function $n(a,i){Es(i)||(function c(p,I){var g=I.from,w=I.to,_=I.l,I=I.r;jn(p,g,w),_&&c(p,_),I&&c(p,I)})(a,i)}function fi(a,i){var c=Ia(i),p=c.next();if(p.done)return!1;for(var h=p.value,g=Ia(a),w=g.next(h.from),_=w.value;!p.done&&!w.done;){if(Oe(_.from,h.to)<=0&&0<=Oe(_.to,h.from))return!0;Oe(h.from,_.from)<0?h=(p=c.next(_.from)).value:_=(w=g.next(h.from)).value}return!1}function Ia(a){var i=Es(a)?null:{s:0,n:a};return{next:function(c){for(var p=0<arguments.length;i;)switch(i.s){case 0:if(i.s=1,p)for(;i.n.l&&Oe(c,i.n.from)<0;)i={up:i,n:i.n.l,s:1};else for(;i.n.l;)i={up:i,n:i.n.l,s:1};case 1:if(i.s=2,!p||Oe(c,i.n.to)<=0)return{value:i.n,done:!1};case 2:if(i.n.r){i.s=3,i={up:i,n:i.n.r,s:0};continue}case 3:i=i.up}return{done:!0}}}}function hi(a){var i,c,p=(((i=a.r)===null||i===void 0?void 0:i.d)||0)-(((c=a.l)===null||c===void 0?void 0:c.d)||0),h=1<p?"r":p<-1?"l":"";h&&(i=h=="r"?"l":"r",c=n({},a),p=a[h],a.from=p.from,a.to=p.to,a[h]=p[h],c[h]=p[i],(a[i]=c).d=mi(c)),a.d=mi(a)}function mi(c){var i=c.r,c=c.l;return(i?c?Math.max(i.d,c.d):i.d:c?c.d:0)+1}
33function Ta(a,i){return l(i).forEach(function(c){a[c]?$n(a[c],i[c]):a[c]=(function p(h){var g,w,_={};for(g in h)b(h,g)&&(w=h[g],_[g]=!w||typeof w!="object"||he.has(w.constructor)?w:p(w));return _})(i[c])}),a}function As(a,i){return a.all||i.all||Object.keys(a).some(function(c){return i[c]&&fi(i[c],a[c])})}v(ht.prototype,((Dt={add:function(a){return $n(this,a),this},addKey:function(a){return jn(this,a,a),this},addKeys:function(a){var i=this;return a.forEach(function(c){return jn(i,c,c)}),this},hasKey:function(a){var i=Ia(this).next(a).value;return i&&Oe(i.from,a)<=0&&0<=Oe(i.to,a)}})[lt]=function(){return Ia(this)},Dt));var Ur={},Cs={},Rs=!1;function Ea(a){Ta(Cs,a),Rs||(Rs=!0,setTimeout(function(){Rs=!1,Ps(Cs,!(Cs={}))},0))}function Ps(a,i){i===void 0&&(i=!1);var c=new Set;if(a.all)for(var p=0,h=Object.values(Ur);p<h.length;p++)gi(w=h[p],a,c,i);else for(var g in a){var w,_=/^idb\:\/\/(.*)\/(.*)\//.exec(g);_&&(g=_[1],_=_[2],(w=Ur["idb://".concat(g,"/").concat(_)])&&gi(w,a,c,i))}c.forEach(function(I){return I()})}function gi(a,i,c,p){for(var h=[],g=0,w=Object.entries(a.queries.query);g<w.length;g++){for(var _=w[g],I=_[0],A=[],P=0,k=_[1];P<k.length;P++){var j=k[P];As(i,j.obsSet)?j.subscribers.forEach(function(O){return c.add(O)}):p&&A.push(j)}p&&h.push([I,A])}if(p)for(var T=0,C=h;T<C.length;T++){var N=C[T],I=N[0],A=N[1];a.queries.query[I]=A}}function hp(a){var i=a._state,c=a._deps.indexedDB;if(i.isBeingOpened||a.idbdb)return i.dbReadyPromise.then(function(){return i.dbOpenError?rt(i.dbOpenError):a});i.isBeingOpened=!0,i.dbOpenError=null,i.openComplete=!1;var p=i.openCanceller,h=Math.round(10*a.verno),g=!1;function w(){if(i.openCanceller!==p)throw new Q.DatabaseClosed("db.open() was cancelled")}function _(){return new X(function(j,T){if(w(),!c)throw new Q.MissingAPI;var C=a.name,N=i.autoSchema||!h?c.open(C):c.open(C,h);if(!N)throw new Q.MissingAPI;N.onerror=Qt(T),N.onblocked=Be(a._fireOnBlocked),N.onupgradeneeded=Be(function(O){var $;P=N.transaction,i.autoSchema&&!a._options.allowEmptyDB?(N.onerror=Pn,P.abort(),N.result.close(),($=c.deleteDatabase(C)).onsuccess=$.onerror=Be(function(){T(new Q.NoSuchDatabase("Database ".concat(C," doesnt exist")))})):(P.onerror=Qt(T),O=O.oldVersion>Math.pow(2,62)?0:O.oldVersion,k=O<1,a.idbdb=N.result,g&&pp(a,P),dp(a,O/10,P,T))},T),N.onsuccess=Be(function(){P=null;var O,$,F,q,L,G=a.idbdb=N.result,J=B(G.objectStoreNames);if(0<J.length)try{var Z=G.transaction((q=J).length===1?q[0]:q,"readonly");if(i.autoSchema)$=G,F=Z,(O=a).verno=$.version/10,F=O._dbSchema=ka(0,$,F),O._storeNames=B($.objectStoreNames,0),_a(O,[O._allTables],l(F),F);else if(Sa(a,a._dbSchema,Z),((L=xs(ka(0,(L=a).idbdb,Z),L._dbSchema)).add.length||L.change.some(function(W){return W.add.length||W.change.length}))&&!g)return console.warn("Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Dexie will add missing parts and increment native version number to workaround this."),G.close(),h=G.version+1,g=!0,j(_());wa(a,Z)}catch{}cn.push(a),G.onversionchange=Be(function(W){i.vcFired=!0,a.on("versionchange").fire(W)}),G.onclose=Be(function(W){a.on("close").fire(W)}),k&&(L=a._deps,Z=C,G=L.indexedDB,L=L.IDBKeyRange,Is(G)||Z===ha||Ss(G,L).put({name:Z}).catch(ye)),j()},T)}).catch(function(j){switch(j?.name){case"UnknownError":if(0<i.PR1398_maxLoop)return i.PR1398_maxLoop--,console.warn("Dexie: Workaround for Chrome UnknownError on open()"),_();break;case"VersionError":if(0<h)return h=0,_()}return X.reject(j)})}var I,A=i.dbReadyResolve,P=null,k=!1;return X.race([p,(typeof navigator>"u"?X.resolve():!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise(function(j){function T(){return indexedDB.databases().finally(j)}I=setInterval(T,100),T()}).finally(function(){return clearInterval(I)}):Promise.resolve()).then(_)]).then(function(){return w(),i.onReadyBeingFired=[],X.resolve(Ts(function(){return a.on.ready.fire(a.vip)})).then(function j(){if(0<i.onReadyBeingFired.length){var T=i.onReadyBeingFired.reduce(se,ye);return i.onReadyBeingFired=[],X.resolve(Ts(function(){return T(a.vip)})).then(j)}})}).finally(function(){i.openCanceller===p&&(i.onReadyBeingFired=null,i.isBeingOpened=!1)}).catch(function(j){i.dbOpenError=j;try{P&&P.abort()}catch{}return p===i.openCanceller&&a._close(),rt(j)}).finally(function(){i.openComplete=!0,A()}).then(function(){var j;return k&&(j={}
33,a.tables.forEach(function(T){T.schema.indexes.forEach(function(C){C.name&&(j["idb://".concat(a.name,"/").concat(T.name,"/").concat(C.name)]=new ht(-1/0,[[[]]]))}),j["idb://".concat(a.name,"/").concat(T.name,"/")]=j["idb://".concat(a.name,"/").concat(T.name,"/:dels")]=new ht(-1/0,[[[]]])}),Tr(On).fire(j),Ps(j,!0)),a})}function Os(a){function i(g){return a.next(g)}var c=h(i),p=h(function(g){return a.throw(g)});function h(g){return function(I){var _=g(I),I=_.value;return _.done?I:I&&typeof I.then=="function"?I.then(c,p):u(I)?Promise.all(I).then(c,p):c(I)}}return h(i)()}function Aa(a,i,c){for(var p=u(a)?a.slice():[a],h=0;h<c;++h)p.push(i);return p}var mp={stack:"dbcore",name:"VirtualIndexMiddleware",level:1,create:function(a){return n(n({},a),{table:function(i){var c=a.table(i),p=c.schema,h={},g=[];function w(k,j,T){var C=Nn(k),N=h[C]=h[C]||[],O=k==null?0:typeof k=="string"?1:k.length,$=0<j,$=n(n({},T),{name:$?"".concat(C,"(virtual-from:").concat(T.name,")"):T.name,lowLevelIndex:T,isVirtual:$,keyTail:j,keyLength:O,extractKey:ws(k),unique:!$&&T.unique});return N.push($),$.isPrimaryKey||g.push($),1<O&&w(O===2?k[0]:k.slice(0,O-1),j+1,T),N.sort(function(F,q){return F.keyTail-q.keyTail}),$}i=w(p.primaryKey.keyPath,0,p.primaryKey),h[":id"]=[i];for(var _=0,I=p.indexes;_<I.length;_++){var A=I[_];w(A.keyPath,0,A)}function P(k){var j,T=k.query.index;return T.isVirtual?n(n({},k),{query:{index:T.lowLevelIndex,range:(j=k.query.range,T=T.keyTail,{type:j.type===1?2:j.type,lower:Aa(j.lower,j.lowerOpen?a.MAX_KEY:a.MIN_KEY,T),lowerOpen:!0,upper:Aa(j.upper,j.upperOpen?a.MIN_KEY:a.MAX_KEY,T),upperOpen:!0})}}):k}return n(n({},c),{schema:n(n({},p),{primaryKey:i,indexes:g,getIndexByKeyPath:function(k){return(k=h[Nn(k)])&&k[0]}}),count:function(k){return c.count(P(k))},query:function(k){return c.query(P(k))},openCursor:function(k){var j=k.query.index,T=j.keyTail,C=j.isVirtual,N=j.keyLength;return C?c.openCursor(P(k)).then(function($){return $&&O($)}):c.openCursor(k);function O($){return Object.create($,{continue:{value:function(F){F!=null?$.continue(Aa(F,k.reverse?a.MAX_KEY:a.MIN_KEY,T)):k.unique?$.continue($.key.slice(0,N).concat(k.reverse?a.MIN_KEY:a.MAX_KEY,T)):$.continue()}},continuePrimaryKey:{value:function(F,q){$.continuePrimaryKey(Aa(F,a.MAX_KEY,T),q)}},primaryKey:{get:function(){return $.primaryKey}},key:{get:function(){var F=$.key;return N===1?F[0]:F.slice(0,N)}},value:{get:function(){return $.value}}})}}})}})}};function Ms(a,i,c,p){return c=c||{},p=p||"",l(a).forEach(function(h){var g,w,_;b(i,h)?(g=a[h],w=i[h],typeof g=="object"&&typeof w=="object"&&g&&w?(_=pt(g))!==pt(w)?c[p+h]=i[h]:_==="Object"?Ms(g,w,c,p+h+"."):g!==w&&(c[p+h]=i[h]):g!==w&&(c[p+h]=i[h])):c[p+h]=void 0}),l(i).forEach(function(h){b(a,h)||(c[p+h]=i[h])}),c}function Ns(a,i){return i.type==="delete"?i.keys:i.keys||i.values.map(a.extractKey)}var gp={stack:"dbcore",name:"HooksMiddleware",level:2,create:function(a){return n(n({},a),{table:function(i){var c=a.table(i),p=c.schema.primaryKey;return n(n({},c),{mutate:function(h){var g=ue.trans,w=g.table(i).hook,_=w.deleting,I=w.creating,A=w.updating;switch(h.type){case"add":if(I.fire===ye)break;return g._promise("readwrite",function(){return P(h)},!0);case"put":if(I.fire===ye&&A.fire===ye)break;return g._promise("readwrite",function(){return P(h)},!0);case"delete":if(_.fire===ye)break;return g._promise("readwrite",function(){return P(h)},!0);case"deleteRange":if(_.fire===ye)break;return g._promise("readwrite",function(){return(function k(j,T,C){return c.query({trans:j,values:!1,query:{index:p,range:T},limit:C}).then(function(N){var O=N.result;return P({type:"delete",keys:O,trans:j}).then(function($){return 0<$.numFailures?Promise.reject($.failures[0]):O.length<C?{failures:[],numFailures:0,lastResult:void 0}:k(j,n(n({},T),{lower:O[O.length-1],lowerOpen:!0}),C)})})})(h.trans,h.range,1e4)},!0)}return c.mutate(h);function P(k){var j,T,C,N=ue.trans,O=k.keys||Ns(p,k);if(!O)throw new Error("Keys missing");return(k=k.type==="add"||k.type==="put"?n(n({},k),{keys:O}):n({},k)).type!=="delete"&&(k.values=s([],k.values)),k.keys&&(k.keys=s([],k.keys)),j=c,C=O,((T=k).type==="add"?Promise.resolve([]):j.getMany({trans:T.trans,keys:C,cache:"immutable"})).then(function($){var F=O.map(function(q,L){var G,J,Z,W=$[L],re={onerror:null,onsuccess:null};return k.type==="delete"?_.fire.call(re,q,W,N):k.type==="add"||W===void 0?(G=I.fire.call(re,q,k.values[L],N),q==null&&G!=null&&(k.keys[L]=q=G,p.outbound||K(k.values[L],p.keyPath,q))):(G=Ms(W,k.values[L]),(J=A.fire.call(re,G,q,W,N))&&(Z=k.values[L],Object.keys(J).forEach(function(ee){b(Z,ee)?Z[ee]=J[ee]:K(Z,ee,J[ee])}))),re});return c.mutate(k).then(function(q){for(var L=q.failures,G=q.results,J=q.numFailures,q=q.lastResult,Z=0;Z<O.length;++Z){var W=(G||O)[Z],re=F[Z];W==null?re.onerror&&re.onerror(L[Z]):re.onsuccess&&re.onsuccess(k.type==="put"&&$[Z]?k.values[Z]:W)}return{failures:L,results:G,numFailures:J,lastResult:q}}
33).catch(function(q){return F.forEach(function(L){return L.onerror&&L.onerror(q)}),Promise.reject(q)})})}}})}})}};function vi(a,i,c){try{if(!i||i.keys.length<a.length)return null;for(var p=[],h=0,g=0;h<i.keys.length&&g<a.length;++h)Oe(i.keys[h],a[g])===0&&(p.push(c?ke(i.values[h]):i.values[h]),++g);return p.length===a.length?p:null}catch{return null}}var vp={stack:"dbcore",level:-1,create:function(a){return{table:function(i){var c=a.table(i);return n(n({},c),{getMany:function(p){if(!p.cache)return c.getMany(p);var h=vi(p.keys,p.trans._cache,p.cache==="clone");return h?X.resolve(h):c.getMany(p).then(function(g){return p.trans._cache={keys:p.keys,values:p.cache==="clone"?ke(g):g},g})},mutate:function(p){return p.type!=="add"&&(p.trans._cache=null),c.mutate(p)}})}}}};function yi(a,i){return a.trans.mode==="readonly"&&!!a.subscr&&!a.trans.explicit&&a.trans.db._options.cache!=="disabled"&&!i.schema.primaryKey.outbound}function bi(a,i){switch(a){case"query":return i.values&&!i.unique;case"get":case"getMany":case"count":case"openCursor":return!1}}var yp={stack:"dbcore",level:0,name:"Observability",create:function(a){var i=a.schema.name,c=new ht(a.MIN_KEY,a.MAX_KEY);return n(n({},a),{transaction:function(p,h,g){if(ue.subscr&&h!=="readonly")throw new Q.ReadOnly("Readwrite transaction in liveQuery context. Querier source: ".concat(ue.querier));return a.transaction(p,h,g)},table:function(p){var h=a.table(p),g=h.schema,w=g.primaryKey,k=g.indexes,_=w.extractKey,I=w.outbound,A=w.autoIncrement&&k.filter(function(T){return T.compound&&T.keyPath.includes(w.keyPath)}),P=n(n({},h),{mutate:function(T){function C(ee){return ee="idb://".concat(i,"/").concat(p,"/").concat(ee),q[ee]||(q[ee]=new ht)}var N,O,$,F=T.trans,q=T.mutatedParts||(T.mutatedParts={}),L=C(""),G=C(":dels"),J=T.type,re=T.type==="deleteRange"?[T.range]:T.type==="delete"?[T.keys]:T.values.length<50?[Ns(w,T).filter(function(ee){return ee}),T.values]:[],Z=re[0],W=re[1],re=T.trans._cache;return u(Z)?(L.addKeys(Z),(re=J==="delete"||Z.length===W.length?vi(Z,re):null)||G.addKeys(Z),(re||W)&&(N=C,O=re,$=W,g.indexes.forEach(function(ee){var ae=N(ee.name||"");function Te(xe){return xe!=null?ee.extractKey(xe):null}function Me(xe){return ee.multiEntry&&u(xe)?xe.forEach(function(Ye){return ae.addKey(Ye)}):ae.addKey(xe)}(O||$).forEach(function(xe,mt){var _e=O&&Te(O[mt]),mt=$&&Te($[mt]);Oe(_e,mt)!==0&&(_e!=null&&Me(_e),mt!=null&&Me(mt))})}))):Z?(W={from:(W=Z.lower)!==null&&W!==void 0?W:a.MIN_KEY,to:(W=Z.upper)!==null&&W!==void 0?W:a.MAX_KEY},G.add(W),L.add(W)):(L.add(c),G.add(c),g.indexes.forEach(function(ee){return C(ee.name).add(c)})),h.mutate(T).then(function(ee){return!Z||T.type!=="add"&&T.type!=="put"||(L.addKeys(ee.results),A&&A.forEach(function(ae){for(var Te=T.values.map(function(_e){return ae.extractKey(_e)}),Me=ae.keyPath.findIndex(function(_e){return _e===w.keyPath}),xe=0,Ye=ee.results.length;xe<Ye;++xe)Te[xe][Me]=ee.results[xe];C(ae.name).addKeys(Te)})),F.mutatedParts=Ta(F.mutatedParts||{},q),ee})}}),k=function(C){var N=C.query,C=N.index,N=N.range;return[C,new ht((C=N.lower)!==null&&C!==void 0?C:a.MIN_KEY,(N=N.upper)!==null&&N!==void 0?N:a.MAX_KEY)]},j={get:function(T){return[w,new ht(T.key)]},getMany:function(T){return[w,new ht().addKeys(T.keys)]},count:k,query:k,openCursor:k};return l(j).forEach(function(T){P[T]=function(C){var N=ue.subscr,O=!!N,$=yi(ue,h)&&bi(T,C)?C.obsSet={}:N;if(O){var F=function(W){return W="idb://".concat(i,"/").concat(p,"/").concat(W),$[W]||($[W]=new ht)},q=F(""),L=F(":dels"),N=j[T](C),O=N[0],N=N[1];if((T==="query"&&O.isPrimaryKey&&!C.values?L:F(O.name||"")).add(N),!O.isPrimaryKey){if(T!=="count"){var G=T==="query"&&I&&C.values&&h.query(n(n({},C),{values:!1}));return h[T].apply(this,arguments).then(function(W){if(T==="query"){if(I&&C.values)return G.then(function(Te){return Te=Te.result,q.addKeys(Te),W});var re=C.values?W.result.map(_):W.result;(C.values?q:L).addKeys(re)}else if(T==="openCursor"){var ee=W,ae=C.values;return ee&&Object.create(ee,{key:{get:function(){return L.addKey(ee.primaryKey),ee.key}},primaryKey:{get:function(){var Te=ee.primaryKey;return L.addKey(Te),Te}},value:{get:function(){return ae&&q.addKey(ee.primaryKey),ee.value}}})}return W})}L.add(c)}}return h[T].apply(this,arguments)}}),P}})}};function wi(a,i,c){if(c.numFailures===0)return i;if(i.type==="deleteRange")return null;var p=i.keys?i.keys.length:"values"in i&&i.values?i.values.length:1;return c.numFailures===p?null:(i=n({},i),u(i.keys)&&(i.keys=i.keys.filter(function(h,g){return!(g in c.failures)})),"values"in i&&u(i.values)&&(i.values=i.values.filter(function(h,g){return!(g in c.failures)})),i)}function js(a,i){return c=a,((p=i).lower===void 0||(p.lowerOpen?0<Oe(c,p.lower):0<=Oe(c,p.lower)))&&(a=a,(i=i).upper===void 0||(i.upperOpen?Oe(a,i.upper)<0:Oe(a,i.upper)<=0));var c,p}function _i(a,i,j,p,h,g){if(!j||j.length===0)return a;var w=i.query.index,_=w.multiEntry,I=i.query.range,A=p.schema.primaryKey.extractKey,P=w.extractKey,k=(w.lowLevelIndex||w).extractKey,j=j.reduce(function(T,C){var N=T,O=[];if(C.type==="add"||C.type==="put")for(var $=new ht,F=C.values.length-1;0<=F;--F){var q,L=C.values[F],G=A(L);$.hasKey(G)||(q=P(L),(_&&u(q)?q.some(function(ee){return js(ee,I)}):js(q,I))&&($.addKey(G),O.push(L)))}switch(C.type){case"add":var J=new ht().addKeys(i.values?T.map(function(ae){return A(ae)}):T),N=T.concat(i.values?O.filter(function(ae){return ae=A(ae),!J.hasKey(ae)&&(J.addKey(ae),!0)}):O.map(function(ae){return A(ae)}).filter(function(ae){return!J.hasKey(ae)&&(J.addKey(ae),!0)}));break;case"put":var Z=new ht().addKeys(C.values.map(function(ae){return A(ae)}));N=T.filter(function(ae){return!Z.hasKey(i.values?A(ae):ae)}).concat(i.values?O:O.map(function(ae){return A(ae)}));break;case"delete":var W=new ht().addKeys(C.keys);N=T.filter(function(ae){return!W.hasKey(i.values?A(ae):ae)});break;case"deleteRange":var re=C.range;N=T.filter(function(ae){return!js(A(ae),re)})}return N},a);return j===a?a:(j.sort(function(T,C){return Oe(k(T),k(C))||Oe(A(T),A(C))}),i.limit&&i.limit<1/0&&(j.length>i.limit?j.length=i.limit:a.length===i.limit&&j.length<i.limit&&(h.dirty=!0)),g?Object.freeze(j):j)}function xi(a,i){return Oe(a.lower,i.lower)===0&&Oe(a.upper,i.upper)===0&&!!a.lowerOpen==!!i.lowerOpen&&!!a.upperOpen==!!i.upperOpen}function bp(a,i){return(function(c,p,h,g){if(c===void 0)return p!==void 0?-1:0;if(p===void 0)return 1;if((p=Oe(c,p))===0){if(h&&g)return 0;if(h)return 1;if(g)return-1}return p})(a.lower,i.lower,a.lowerOpen,i.lowerOpen)<=0&&0<=(function(c,p,h,g){if(c===void 0)return p!==void 0?1:0;if(p===void 0)return-1;if((p=Oe(c,p))===0){if(h&&g)return 0;if(h)return-1;if(g)return 1}return p})(a.upper,i.upper,a.upperOpen,i.upperOpen)}function wp(a,i,c,p){a.subscribers.add(c),p.addEventListener("abort",function(){var h,g;a.subscribers.delete(c),a.subscribers.size===0&&(h=a,g=i,setTimeout(function(){h.subscribers.size===0&&H(g,h)},3e3))})}var _p={stack:"dbcore",level:0,name:"Cache",create:function(a){var i=a.schema.name;return n(n({},a),{transaction:function(c,p,h){var g,w,_=a.transaction(c,p,h);return p==="readwrite"&&(w=(g=new AbortController).signal,h=function(I){return function(){if(g.abort(),p==="readwrite"){for(var A=new Set,P=0,k=c;P<k.length;P++){var j=k[P],T=Ur["idb://".concat(i,"/").concat(j)];if(T){var C=a.table(j),N=T.optimisticOps.filter(function(ae){return ae.trans===_});if(_._explicit&&I&&_.mutatedParts)for(var O=0,$=Object.values(T.queries.query
33);O<$.length;O++)for(var F=0,q=(J=$[O]).slice();F<q.length;F++)As((Z=q[F]).obsSet,_.mutatedParts)&&(H(J,Z),Z.subscribers.forEach(function(ae){return A.add(ae)}));else if(0<N.length){T.optimisticOps=T.optimisticOps.filter(function(ae){return ae.trans!==_});for(var L=0,G=Object.values(T.queries.query);L<G.length;L++)for(var J,Z,W,re=0,ee=(J=G[L]).slice();re<ee.length;re++)(Z=ee[re]).res!=null&&_.mutatedParts&&(I&&!Z.dirty?(W=Object.isFrozen(Z.res),W=_i(Z.res,Z.req,N,C,Z,W),Z.dirty?(H(J,Z),Z.subscribers.forEach(function(ae){return A.add(ae)})):W!==Z.res&&(Z.res=W,Z.promise=X.resolve({result:W}))):(Z.dirty&&H(J,Z),Z.subscribers.forEach(function(ae){return A.add(ae)})))}}}A.forEach(function(ae){return ae()})}}},_.addEventListener("abort",h(!1),{signal:w}),_.addEventListener("error",h(!1),{signal:w}),_.addEventListener("complete",h(!0),{signal:w})),_},table:function(c){var p=a.table(c),h=p.schema.primaryKey;return n(n({},p),{mutate:function(g){var w=ue.trans;if(h.outbound||w.db._options.cache==="disabled"||w.explicit||w.idbtrans.mode!=="readwrite")return p.mutate(g);var _=Ur["idb://".concat(i,"/").concat(c)];return _?(w=p.mutate(g),g.type!=="add"&&g.type!=="put"||!(50<=g.values.length||Ns(h,g).some(function(I){return I==null}))?(_.optimisticOps.push(g),g.mutatedParts&&Ea(g.mutatedParts),w.then(function(I){0<I.numFailures&&(H(_.optimisticOps,g),(I=wi(0,g,I))&&_.optimisticOps.push(I),g.mutatedParts&&Ea(g.mutatedParts))}),w.catch(function(){H(_.optimisticOps,g),g.mutatedParts&&Ea(g.mutatedParts)})):w.then(function(I){var A=wi(0,n(n({},g),{values:g.values.map(function(P,k){var j;return I.failures[k]?P:(P=(j=h.keyPath)!==null&&j!==void 0&&j.includes(".")?ke(P):n({},P),K(P,h.keyPath,I.results[k]),P)})}),I);_.optimisticOps.push(A),queueMicrotask(function(){return g.mutatedParts&&Ea(g.mutatedParts)})}),w):p.mutate(g)},query:function(g){if(!yi(ue,p)||!bi("query",g))return p.query(g);var w=((A=ue.trans)===null||A===void 0?void 0:A.db._options.cache)==="immutable",k=ue,_=k.requery,I=k.signal,A=(function(C,N,O,$){var F=Ur["idb://".concat(C,"/").concat(N)];if(!F)return[];if(!(N=F.queries[O]))return[null,!1,F,null];var q=N[($.query?$.query.index.name:null)||""];if(!q)return[null,!1,F,null];switch(O){case"query":var L=q.find(function(G){return G.req.limit===$.limit&&G.req.values===$.values&&xi(G.req.query.range,$.query.range)});return L?[L,!0,F,q]:[q.find(function(G){return("limit"in G.req?G.req.limit:1/0)>=$.limit&&(!$.values||G.req.values)&&bp(G.req.query.range,$.query.range)}),!1,F,q];case"count":return L=q.find(function(G){return xi(G.req.query.range,$.query.range)}),[L,!!L,F,q]}})(i,c,"query",g),P=A[0],k=A[1],j=A[2],T=A[3];return P&&k?P.obsSet=g.obsSet:(k=p.query(g).then(function(C){var N=C.result;if(P&&(P.res=N),w){for(var O=0,$=N.length;O<$;++O)Object.freeze(N[O]);Object.freeze(N)}else C.result=ke(N);return C}).catch(function(C){return T&&P&&H(T,P),Promise.reject(C)}),P={obsSet:g.obsSet,promise:k,subscribers:new Set,type:"query",req:g,dirty:!1},T?T.push(P):(T=[P],(j=j||(Ur["idb://".concat(i,"/").concat(c)]={queries:{query:{},count:{}},objs:new Map,optimisticOps:[],unsignaledParts:{}})).queries.query[g.query.index.name||""]=T)),wp(P,T,_,I),P.promise.then(function(C){return{result:_i(C.result,g,j?.optimisticOps,p,P,w)}})}})}})}};function Ca(a,i){return new Proxy(a,{get:function(c,p,h){return p==="db"?i:Reflect.get(c,p,h)}})}var ir=(nt.prototype.version=function(a){if(isNaN(a)||a<.1)throw new Q.Type("Given version is not a positive number");if(a=Math.round(10*a)/10,this.idbdb||this._state.isBeingOpened)throw new Q.Schema("Cannot add version when database is open");this.verno=Math.max(this.verno,a);var i=this._versions,c=i.filter(function(p){return p._cfg.version===a})[0];return c||(c=new this.Version(a),i.push(c),i.sort(cp),c.stores({}),this._state.autoSchema=!1,c)},nt.prototype._whenReady=function(a){var i=this;return this.idbdb&&(this._state.openComplete||ue.letThrough||this._vip)?a():new X(function(c,p){if(i._state.openComplete)return p(new Q.DatabaseClosed(i._state.dbOpenError));if(!i._state.isBeingOpened){if(!i._state.autoOpen)return void p(new Q.DatabaseClosed);i.open().catch(ye)}i._state.dbReadyPromise.then(c,p)}).then(a)},nt.prototype.use=function(a){var i=a.stack,c=a.create,p=a.level,h=a.name;return h&&this.unuse({stack:i,name:h}),a=this._middlewares[i]||(this._middlewares[i]=[]),a.push({stack:i,create:c,level:p??10,name:h}),a.sort(function(g,w){return g.level-w.level}),this},nt.prototype.unuse=function(a){var i=a.stack,c=a.name,p=a.create;return i&&this._middlewares[i]&&(this._middlewares[i]=this._middlewares[i].filter(function(h){return p?h.create!==p:!!c&&h.name!==c})),this},nt.prototype.open=function(){var a=this;return qr(wt,function(){return hp(a)})},nt.prototype._close=function(){this.on.close.fire(new CustomEvent("close"));var a=this._state,i=cn.indexOf(this);if(0<=i&&cn.splice(i,1),this.idbdb){try{this.idbdb.close()}catch{}this.idbdb=null}a.isBeingOpened||(a.dbReadyPromise=new X(function(c){a.dbReadyResolve=c}),a.openCanceller=new X(function(c,p){a.cancelOpen=p}))},nt.prototype.close=function(c){var i=(c===void 0?{disableAutoOpen:!0}:c).disableAutoOpen,c=this._state;i?(c.isBeingOpened&&c.cancelOpen(new Q.DatabaseClosed),this._close(),c.autoOpen=!1,c.dbOpenError=ne
33w Q.DatabaseClosed):(this._close(),c.autoOpen=this._options.autoOpen||c.isBeingOpened,c.openComplete=!1,c.dbOpenError=null)},nt.prototype.delete=function(a){var i=this;a===void 0&&(a={disableAutoOpen:!0});var c=0<arguments.length&&typeof arguments[0]!="object",p=this._state;return new X(function(h,g){function w(){i.close(a);var _=i._deps.indexedDB.deleteDatabase(i.name);_.onsuccess=Be(function(){var I,A,P;I=i._deps,A=i.name,P=I.indexedDB,I=I.IDBKeyRange,Is(P)||A===ha||Ss(P,I).delete(A).catch(ye),h()}),_.onerror=Qt(g),_.onblocked=i._fireOnBlocked}if(c)throw new Q.InvalidArgument("Invalid closeOptions argument to db.delete()");p.isBeingOpened?p.dbReadyPromise.then(w):w()})},nt.prototype.backendDB=function(){return this.idbdb},nt.prototype.isOpen=function(){return this.idbdb!==null},nt.prototype.hasBeenClosed=function(){var a=this._state.dbOpenError;return a&&a.name==="DatabaseClosed"},nt.prototype.hasFailed=function(){return this._state.dbOpenError!==null},nt.prototype.dynamicallyOpened=function(){return this._state.autoSchema},Object.defineProperty(nt.prototype,"tables",{get:function(){var a=this;return l(this._allTables).map(function(i){return a._allTables[i]})},enumerable:!1,configurable:!0}),nt.prototype.transaction=function(){var a=(function(i,c,p){var h=arguments.length;if(h<2)throw new Q.InvalidArgument("Too few arguments");for(var g=new Array(h-1);--h;)g[h-1]=arguments[h];return p=g.pop(),[i,de(g),p]}).apply(this,arguments);return this._transaction.apply(this,a)},nt.prototype._transaction=function(a,i,c){var p=this,h=ue.trans;h&&h.db===this&&a.indexOf("!")===-1||(h=null);var g,w,_=a.indexOf("?")!==-1;a=a.replace("!","").replace("?","");try{if(w=i.map(function(A){if(A=A instanceof p.Table?A.name:A,typeof A!="string")throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return A}),a=="r"||a===fs)g=fs;else{if(a!="rw"&&a!=hs)throw new Q.InvalidArgument("Invalid transaction mode: "+a);g=hs}if(h){if(h.mode===fs&&g===hs){if(!_)throw new Q.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");h=null}h&&w.forEach(function(A){if(h&&h.storeNames.indexOf(A)===-1){if(!_)throw new Q.SubTransaction("Table "+A+" not included in parent transaction.");h=null}}),_&&h&&!h.active&&(h=null)}}catch(A){return h?h._promise(null,function(P,k){k(A)}):rt(A)}var I=(function A(P,k,j,T,C){return X.resolve().then(function(){var N=ue.transless||ue,O=P._createTransaction(k,j,P._dbSchema,T);if(O.explicit=!0,N={trans:O,transless:N},T)O.idbtrans=T.idbtrans;else try{O.create(),O.idbtrans._explicit=!0,P._state.PR1398_maxLoop=3}catch(q){return q.name===Ie.InvalidState&&P.isOpen()&&0<--P._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),P.close({disableAutoOpen:!1}),P.open().then(function(){return A(P,k,j,null,C)})):rt(q)}var $,F=je(C);return F&&un(),N=X.follow(function(){var q;($=C.call(O,O))&&(F?(q=kr.bind(null,null),$.then(q,q)):typeof $.next=="function"&&typeof $.throw=="function"&&($=Os($)))},N),($&&typeof $.then=="function"?X.resolve($).then(function(q){return O.active?q:rt(new Q.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn"))}):N.then(function(){return $})).then(function(q){return T&&O._resolve(),O._completion.then(function(){return q})}).catch(function(q){return O._reject(q),rt(q)})})}).bind(null,this,g,w,h,c);return h?h._promise(g,I,"lock"):ue.trans?qr(ue.transless,function(){return p._whenReady(I)}):this._whenReady(I)},nt.prototype.table=function(a){if(!b(this._allTables,a))throw new Q.InvalidTable("Table ".concat(a," does not exist"));return this._allTables[a]},nt);function nt(a,i){var c=this;this._middlewares={},this.verno=0;var p=nt.dependencies;this._options=i=n({addons:nt.addons,autoOpen:!0,indexedDB:p.indexedDB,IDBKeyRange:p.IDBKeyRange,cache:"cloned"},i),this._deps={indexedDB:i.indexedDB,IDBKeyRange:i.IDBKeyRange},p=i.addons,this._dbSchema={},this._versions=[],this._storeNames=[],this._allTables={},this.idbdb=null,this._novip=this;var h,g,w,_,I,A={dbOpenError:null,isBeingOpened:!1,onReadyBeingFired:null,openComplete:!1,dbReadyResolve:ye,dbReadyPromise:null,cancelOpen:ye,openCanceller:null,autoSchema:!0,PR1398_maxLoop:3,autoOpen:i.autoOpen};A.dbReadyPromise=new X(function(k){A.dbReadyResolve=k}),A.openCanceller=new X(function(k,j){A.cancelOpen=j}),this._state=A,this.name=a,this.on=An(this,"populate","blocked","versionchange","close",{ready:[se,ye]}),this.once=function(k,j){var T=function(){for(var C=[],N=0;N<arguments.length;N++)C[N]=arguments[N];c.on(k).unsubscribe(T),j.apply(c,C)};return c.on(k,T)},this.on.ready.subscribe=V(this.on.ready.subscribe,function(k){return function(j,T){nt.vip(function(){var C,N=c._state;N.openComplete?(N.dbOpenError||X.resolve().then(j),T&&k(j)):N.onReadyBeingFired?(N.onReadyBeingFired.push(j),T&&k(j)):(k(j),C=c,T||k(function O(){C.on.ready.unsubscribe(j),C.on.ready.unsubscribe(O)}))})}}),this.Collection=(h=this,Cn(np.prototype,function($,O){this.db=h;var T=Yo,C=null;if(O)try{T=O()}catch(F){C=F}var N=$._ctx,O=N.table,$=O.hook.reading.fire;this._ctx={table:O,index:N.index,isPrimKey:!N.index||O.schema.primKey.keyPath&&N.index===O.schema.primKey.name,range:T,keysOnly:!1,dir:"next",unique:"",algorithm:null,filter:null,replayFilter:null,justLimit:!0,isMatch:null,offset:0,limit:1/0,error:C,or:N.or,valueMapper:$!==Re?$:null}})),this.Table=(g=this,Cn(ri.prototype,function(k,j,T){this.db=g,this._tx=T,this.name=k,this.schema=j,this.hook=g._allTables[k]?g._allTables[k].hook:An(null,{creating:[Pe,ye],reading:[Ge,Re],updating:[bt,ye],deleting:[Ae,ye]})}
33)),this.Transaction=(w=this,Cn(op.prototype,function(k,j,T,C,N){var O=this;k!=="readonly"&&j.forEach(function($){$=($=T[$])===null||$===void 0?void 0:$.yProps,$&&(j=j.concat($.map(function(F){return F.updatesTable})))}),this.db=w,this.mode=k,this.storeNames=j,this.schema=T,this.chromeTransactionDurability=C,this.idbtrans=null,this.on=An(this,"complete","error","abort"),this.parent=N||null,this.active=!0,this._reculock=0,this._blockedFuncs=[],this._resolve=null,this._reject=null,this._waitingFor=null,this._waitingQueue=null,this._spinCount=0,this._completion=new X(function($,F){O._resolve=$,O._reject=F}),this._completion.then(function(){O.active=!1,O.on.complete.fire()},function($){var F=O.active;return O.active=!1,O.on.error.fire($),O.parent?O.parent._reject($):F&&O.idbtrans&&O.idbtrans.abort(),rt($)})})),this.Version=(_=this,Cn(fp.prototype,function(k){this.db=_,this._cfg={version:k,storesSource:null,dbschema:{},tables:{},contentUpgrade:null}})),this.WhereClause=(I=this,Cn(li.prototype,function(k,j,T){if(this.db=I,this._ctx={table:k,index:j===":id"?null:j,or:T},this._cmp=this._ascending=Oe,this._descending=function(C,N){return Oe(N,C)},this._max=function(C,N){return 0<Oe(C,N)?C:N},this._min=function(C,N){return Oe(C,N)<0?C:N},this._IDBKeyRange=I._deps.IDBKeyRange,!this._IDBKeyRange)throw new Q.MissingAPI})),this.on("versionchange",function(k){0<k.newVersion?console.warn("Another connection wants to upgrade database '".concat(c.name,"'. Closing db now to resume the upgrade.")):console.warn("Another connection wants to delete database '".concat(c.name,"'. Closing db now to resume the delete request.")),c.close({disableAutoOpen:!1})}),this.on("blocked",function(k){!k.newVersion||k.newVersion<k.oldVersion?console.warn("Dexie.delete('".concat(c.name,"') was blocked")):console.warn("Upgrade '".concat(c.name,"' blocked by other connection holding version ").concat(k.oldVersion/10))}),this._maxKey=Mn(i.IDBKeyRange),this._createTransaction=function(k,j,T,C){return new c.Transaction(k,j,T,c._options.chromeTransactionDurability,C)},this._fireOnBlocked=function(k){c.on("blocked").fire(k),cn.filter(function(j){return j.name===c.name&&j!==c&&!j._state.vcFired}).map(function(j){return j.on("versionchange").fire(k)})},this.use(vp),this.use(_p),this.use(yp),this.use(mp),this.use(gp);var P=new Proxy(this,{get:function(k,j,T){if(j==="_vip")return!0;if(j==="table")return function(N){return Ca(c.table(N),P)};var C=Reflect.get(k,j,T);return C instanceof ri?Ca(C,P):j==="tables"?C.map(function(N){return Ca(N,P)}):j==="_createTransaction"?function(){return Ca(C.apply(this,arguments),P)}:C}});this.vip=P,p.forEach(function(k){return k(c)})}var Ra,Dt=typeof Symbol<"u"&&"observable"in Symbol?Symbol.observable:"@@observable",xp=($s.prototype.subscribe=function(a,i,c){return this._subscribe(a&&typeof a!="function"?a:{next:a,error:i,complete:c})},$s.prototype[Dt]=function(){return this},$s);function $s(a){this._subscribe=a}try{Ra={indexedDB:o.indexedDB||o.mozIndexedDB||o.webkitIndexedDB||o.msIndexedDB,IDBKeyRange:o.IDBKeyRange||o.webkitIDBKeyRange}}catch{Ra={indexedDB:null,IDBKeyRange:null}}function ki(a){var i,c=!1,p=new xp(function(h){var g=je(a),w,_=!1,I={},A={},P={get closed(){return _},unsubscribe:function(){_||(_=!0,w&&w.abort(),k&&Tr.storagemutated.unsubscribe(T))}};h.start&&h.start(P);var k=!1,j=function(){return ps(C)},T=function(N){Ta(I,N),As(A,I)&&j()},C=function(){var N,O,$;!_&&Ra.indexedDB&&(I={},N={},w&&w.abort(),w=new AbortController,$=(function(F){var q=sr();try{g&&un();var L=xr(a,F);return L=g?L.finally(kr):L}finally{q&&fe()}})(O={subscr:N,signal:w.signal,requery:j,querier:a,trans:null}),Promise.resolve($).then(function(F){c=!0,i=F,_||O.signal.aborted||(I={},(function(q){for(var L in q)if(b(q,L))return;return 1})(A=N)||k||(Tr(On,T),k=!0),ps(function(){return!_&&h.next&&h.next(F)}))},function(F){c=!1,["DatabaseClosedError","AbortError"].includes(F?.name)||_||ps(function(){_||h.error&&h.error(F)})}))};return setTimeout(j,0),P});return p.hasValue=function(){return c},p.getValue=function(){return i},p}var Vr=ir;function Ds(a){var i=Er;try{Er=!0,Tr.storagemutated.fire(a),Ps(a,!0)}finally{Er=i}}v(Vr,n(n({},st),{delete:function(a){return new Vr(a,{addons:[]}).delete()},exists:function(a){return new Vr(a,{addons:[]}).open().then(function(i){return i.close(),!0}).catch("NoSuchDatabaseError",function(){return!1})},getDatabaseNames:function(a){try{return i=Vr.dependencies,c=i.indexedDB,i=i.IDBKeyRange,(Is(c)?Promise.resolve(c.databases()).then(function(p){return p.map(function(h){return h.name}).filter(function(h){return h!==ha})}):Ss(c,i).toCollection().primaryKeys()).then(a)}catch{return rt(new Q.MissingAPI)}var i,c},defineClass:function(){return function(a){d(this,a)}},ignoreTransaction:function(a){return ue.trans?qr(ue.transless,a):a()},vip:Ts,async:function(a){return function(){try{var i=Os(a.apply(this,arguments));return i&&typeof i.then=="function"?i:X.resolve(i)}catch(c){return rt(c)}}},spawn:function(a,i,c){try{var p=Os(a.apply(c,i||[]));return p&&typeof p.then=="function"?p:X.resolve(p)}catch(h){return rt(h)}},currentTransaction:{get:function(){return ue.trans||null}},waitFor:function(a,i){return i=X.resolve(typeof a=="function"?Vr.ignoreTransaction(a):a).timeout(i||6e4),ue.trans?ue.trans.waitFor(i):i},Promise:X,debug:{get:function(){return Ee},set:function(a){gr(a)}},derive:S,extend:d,props:v,override:V,Events:An,on:Tr,liveQuery:ki,extendObservabilitySet:Ta,getByKeyPath:U,setByKeyPath:K,delByKeyPath:function(a,i){typeof i=="string"?K(a,i,void 0):"length"in i&&[].map.call(i,function(c){K(a,c,void 0)})},shallowClone:ce,deepClone:ke,getObjectDiff:Ms,cmp:Oe,asap:te,minKey:-1/0,addons:[],connections:cn,errnames:Ie,dependencies:Ra,cache:Ur,semVer:"4.2.0",version:"4.2.0".split(".").map(function(a){return parseInt(a)}).reduce(function(a,i,c){return a+i/Math.pow(10,2*c)})})),Vr.maxKey=Mn(Vr.dependencies.IDBKeyRange),typeof dispatchEvent<"u"&&typeof addEventListener<"u"&&(Tr(On,function(a){Er||(a=new CustomEvent(vs,{detail:a}),Er=!0,dispatchEvent(a),Er=!1)}),addEventListener(vs,function(a){a=a.detail,Er||Ds(a)}));var hn,Er=!1,Si=function(){};return typeof BroadcastChannel<"u"&&((Si=function(){(hn=new BroadcastChannel(vs)).onmessage=function(a){return a.data&&Ds(a.data)}})(),typeof hn.unref=="function"&&hn.unref(),Tr(On,function(a){Er||hn.postMessage(
33a)})),typeof addEventListener<"u"&&(addEventListener("pagehide",function(a){if(!ir.disableBfCache&&a.persisted){Ee&&console.debug("Dexie: handling persisted pagehide"),hn?.close();for(var i=0,c=cn;i<c.length;i++)c[i].close({disableAutoOpen:!1})}}),addEventListener("pageshow",function(a){!ir.disableBfCache&&a.persisted&&(Ee&&console.debug("Dexie: handling persisted pageshow"),Si(),Ds({all:new ht(-1/0,[[]])}))})),X.rejectionMapper=function(a,i){return!a||a instanceof et||a instanceof TypeError||a instanceof SyntaxError||!a.name||!We[a.name]?a:(i=new We[a.name](i||a.message,a),"stack"in a&&x(i,"stack",{get:function(){return this.inner.stack}}),i)},gr(Ee),n(ir,Object.freeze({__proto__:null,Dexie:ir,liveQuery:ki,Entity:Xo,cmp:Oe,PropModification:Rn,replacePrefix:function(a,i){return new Rn({replacePrefix:[a,i]})},add:function(a){return new Rn({add:a})},remove:function(a){return new Rn({remove:a})},default:ir,RangeSet:ht,mergeRanges:$n,rangesOverlap:fi}),{default:ir}),ir})})(La)),La.exports}var ly=iy();const fo=Dp(ly),bl=Symbol.for("Dexie"),Ya=globalThis[bl]||(globalThis[bl]=fo);if(fo.semVer!==Ya.semVer)throw new Error(`Two different versions of Dexie loaded in the same app: ${fo.semVer} and ${Ya.semVer}`);const{liveQuery:uy,mergeRanges:u_,rangesOverlap:c_,RangeSet:d_,cmp:p_,Entity:f_,PropModification:h_,replacePrefix:m_,add:g_,remove:v_,DexieYProvider:y_}=Ya,oe=new Ya("ReforeAI");oe.version(2).stores({messages:"id,projectId",models:"id,createdAt",rules:"id",projects:"id,parent,source",projectRules:"id,[projectId+ruleId],ruleId,projectId",projectVersions:"id,[projectId+version],parent",projectFiles:"id,[projectId+version],fileId",files:"id"});oe.version(10).stores({projectModel:"id,projectId"});oe.version(11).stores({messages:"id,projectId,[projectId+version]",projectFiles:"id,[projectId+version],[projectId+filename+version],fileId"});oe.version(12).stores({projectVersions:"id,[projectId+version]"});function Jr(e,t,r){const n=Ti(Ne(()=>ie(t)),{immediate:!0});return Fp(n.pipe(uf(s=>Ti(uy(()=>e(s))))),{initialValue:r})}function cy(){const e=Jr(()=>oe.rules.toArray()),t=Ne(()=>!e.value);async function r(o){const l=vt.createId(),u={...o,id:l,createdAt:new Date().toISOString(),isLocal:!0};return await oe.rules.add(u),u}async function n(o){await oe.rules.update(o.id,Qr(o,["id"]))}async function s(o){await oe.transaction("rw","projectRules","rules",()=>oe.rules.delete(o).then(()=>oe.projectRules.where("ruleId").equals(o).delete()))}return{list:e,isLoading:t,add:r,update:n,remove:s,refresh:qp}}function dy(e){return oe.projectVersions.where({projectId:e}).reverse().sortBy("version")}function wd(e,t){return t.version?Promise.resolve(t.version):dy(e).then(r=>(r.at(0)?.version??0)+1).then(r=>oe.projectVersions.add({id:vt.createId(),version:r,projectId:e,state:t.state,parent:t.parentVersion}).then(()=>{if(t.parentVersion)return oe.projectFiles.where({projectId:e,version:t.parentVersion}).toArray().then(n=>n.map(s=>({...s,id:vt.createId(),version:r,isOwned:!1}))).then(n=>oe.projectFiles.bulkAdd(n))}).then(()=>r))}function py(e,t,r){const n=t.map(({content:s})=>({id:vt.createId(),content:s??""}));return oe.transaction("rw","projectVersions",oe.projectFiles,oe.files,()=>wd(e,r).then(s=>oe.files.bulkAdd(n).then(()=>oe.projectFiles.bulkAdd(n.map((o,l)=>({id:vt.createId(),filename:`index_${l+1}.html`,displayName:ry(o.content??"")??"",projectId:e,version:s,fileId:o.id,createdAt:new Date().toISOString()})))).then(()=>s)))}function fy(e){return{project:Jr(r=>r?oe.projects.get(r):void 0,e)}}function hy(e){const{files:t,rules:r,createId:n=vt.createId}=e,s=e.name||"",o=e.id,l={id:o,name:s,parent:e.parent||"",createdAt:new Date().toISOString(),source:e.source||"",isLocal:!0,data:e.data};return oe.projects.add(l).then(()=>oe.projectRules.bulkPut(r.map(u=>({id:n(),projectId:o,ruleId:u})))).then(()=>{if(t.length)return py(o,t,{state:St.Draft})}).then(()=>l)}function b_(e){return Zt({async mutationFn(t){const r=t.id??ie(e);await oe.projects.where({id:r}).modify(Qr(t,["data"])),t.data&&await oe.transaction("rw","project",()=>oe.projects.get(r).then(n=>n?oe.projects.where({id:r}).modify({data:xo(n.data,t.data)}):null))}})}function w_(e){return Zt({async mutationFn(){const t=ie(e);t&&await Promise.allSettled([oe.projects.delete(t),oe.projectVersions.where({projectId:t}).delete(),oe.projectFiles.where({projectId:t}).delete(),oe.projectVersions.where({projectId:t}).delete()])}})}function my(){return async function(t){return hy(t)}}function __(e){function t(v){const y=Jr(({projectId:x,version:S})=>{if(S)return oe.projectFiles.where({projectId:x,version:S}).toArray().then(M=>Promise.all(M.map(R=>oe.files.get(R.fileId).then(B=>
33{if(!B)throw new Error;return{...R,virtualFile:{...B,shareKey:"",hash:""}}}))))},Ne(()=>({projectId:ie(e),version:ie(v)})));return Ne(()=>Yn(y.value))}const r=Jr(v=>oe.projectRules.where({projectId:v}).toArray().then(y=>y.map(x=>x.ruleId)),e);async function n(v){await oe.projectRules.put({id:vt.createId(),projectId:ie(e),ruleId:v})}async function s(v){await oe.projectRules.where({projectId:ie(e),ruleId:v}).delete()}function o(v){return Jr(y=>oe.projectVersions.where({projectId:y}).reverse().sortBy("version").then(x=>x.map(S=>S.state?S:{...S,state:S.isDraft?St.Draft:St.Ready})),v)}function l(v){const{version:y,...x}=v;return oe.projectVersions.where({projectId:ie(e),version:y}).modify(x)}async function u(v){const{messages:y,parentVersion:x,state:S}=v,M=ie(e);return wd(M,{parentVersion:x,version:v.version,state:S}).then(R=>oe.messages.where({projectId:M,version:R}).delete().then(()=>oe.messages.bulkPut(y.map(B=>{const V=xn(B,R);return Object.assign(V,{version:R,createdAt:new Date().toISOString()}),Object.assign(B,V),JSON.parse(JSON.stringify(B))}))).then(()=>R,B=>(console.warn(B),R)))}function d({version:v}){const y=ie(e);return oe.projectVersions.where({projectId:y}).toArray().then(x=>{const S=su(v,x),M=new Set(S.map(R=>R.version));return oe.messages.where({projectId:y}).toArray().then(R=>R.filter(B=>{const V=xn(B,void 0);return M.has(V.version)}))})}function f(v){return Ne(()=>{const y=ie(v);return y?{filename:y.filename,content:y.virtualFile.content}:null})}async function m(v){await oe.projects.where({id:v.id||ie(e)}).modify(Qr(v,["id"]))}async function b(v,y){y=Qr(y,["id","projectId","version","filename"]),await oe.projectFiles.update(v.id,y)}return{projectRules:r,useProjectFiles:t,enableRule:n,disableRule:s,useProjectVersions:o,persistMessages:u,restoreMessages:d,useFileContent:f,patchProject:m,patchVersion:l,patchFile:b}}async function gy(e,t){const r=await oe.projects.get(e.projectId);if(!r)throw new Error("project not exist");const n=await oe.projectVersions.where({projectId:e.projectId,version:e.version}).toArray(),s=await oe.projectFiles.where({projectId:e.projectId,version:e.version}).toArray(),o=await oe.projectRules.where({projectId:e.projectId}).toArray(),l=t(),u=[],d=new Set,f=n.map(b=>(b.state!==St.Ready&&d.add(1),{...b,id:vt.createId(),state:St.Draft,version:1,projectId:l})),m=await Promise.all(s.map(async b=>{let v=b.fileId;if(d.has(b.version)){v=vt.createId();const x=await oe.files.get(b.fileId),S={id:v,content:x?.content??""};u.push(S)}return{...b,projectId:l,id:vt.createId(),version:1,fileId:v}}));return await Promise.all([oe.projects.add({...r,id:l}),oe.files.bulkAdd(u),oe.projectVersions.bulkAdd(f),oe.projectFiles.bulkAdd(m),oe.projectRules.bulkAdd(o.map(b=>({...b,projectId:l})))]),{projectId:l}}var vy=class{constructor(e){this.statusRef=Wr("ready"),this.errorRef=Wr(void 0),this.pushMessage=t=>{this.messagesRef.value=[...this.messagesRef.value,t]},this.popMessage=()=>{this.messagesRef.value=this.messagesRef.value.slice(0,-1)},this.replaceMessage=(t,r)=>{this.messagesRef.value[t]={...r}},this.snapshot=t=>t,this.messagesRef=Wr(e??[])}get messages(){return this.messagesRef.value}set messages(e){this.messagesRef.value=e}get status(){return this.statusRef.value}set status(e){this.statusRef.value=e}get error(){return this.errorRef.value}set error(e){this.errorRef.value=e}},yy=class extends Jv{constructor({messages:e,...t}){super({...t,state:new vy(e)})}};function jo(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var sn=jo();function _d(e){sn=e}var Jn={exec:()=>null};function Ue(e,t=""){let r=typeof e=="string"?e:e.source,n={replace:(s,o)=>{let l=typeof o=="string"?o:o.source;return l=l.replace(It.caret,"$1"),r=r.replace(s,l),n},getRegex:()=>new RegExp(r,t)};return n}var It={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine
vendor: 12,595 bytes, lines 33-40
33:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[	 ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ 	][^\\n]*)?(?:\\n|$))`),hrRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,"i")},by=/^(?:[ \t]*(?:\n|$))+/,wy=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,_y=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,ca=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,xy=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,$o=/(?:[*+-]|\d{1,9}[.)])/,xd=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,kd=Ue(xd).replace(/bull/g,$o).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),ky=Ue(xd).replace(/bull/g,$o).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Do=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Sy=/^[^\n]+/,Fo=/(?!\s*\])(?:\\.|[^\[\]\\])+/,Iy=Ue(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Fo).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Ty=Ue(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,$o).getRegex(),os="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",qo=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Ey=Ue("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ 	]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ 	]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ 	]*)+\\n|$))","i").replace("comment",qo).replace("tag",os).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Sd=Ue(Do).replace("hr",ca).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",os).getRegex(),Ay=Ue(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Sd).getRegex(),Lo={blockquote:Ay,code:wy,def:Iy,fences:_y,heading:xy,hr:ca,html:Ey,lheading:kd,list:Ty,newline:by,paragraph:Sd,table:Jn,text:Sy},wl=Ue("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",ca).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3}	)[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",os).getRegex(),Cy={...Lo,lheading:ky,table:wl,paragraph:Ue(Do).replace("hr",ca).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",wl).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",os).getRegex()},Ry={...Lo,html:Ue(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",qo).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Jn,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Ue(Do).replace("hr",ca).replace("heading",` *#{1,6} *[^
34]`).replace("lheading",kd).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Py=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Oy=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Id=/^( {2,}|\\)\n(?!\s*$)/,My=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,is=/[\p{P}\p{S}]/u,Bo=/[\s\p{P}\p{S}]/u,Td=/[^\s\p{P}\p{S}]/u,Ny=Ue(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Bo).getRegex(),Ed=/(?!~)[\p{P}\p{S}]/u,jy=/(?!~)[\s\p{P}\p{S}]/u,$y=/(?:[^\s\p{P}\p{S}]|~)/u,Dy=/\[[^[\]]*?\]\((?:\\.|[^\\\(\)]|\((?:\\.|[^\\\(\)])*\))*\)|`[^`]*?`|<(?! )[^<>]*?>/g,Ad=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,Fy=Ue(Ad,"u").replace(/punct/g,is).getRegex(),qy=Ue(Ad,"u").replace(/punct/g,Ed).getRegex(),Cd="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Ly=Ue(Cd,"gu").replace(/notPunctSpace/g,Td).replace(/punctSpace/g,Bo).replace(/punct/g,is).getRegex(),By=Ue(Cd,"gu").replace(/notPunctSpace/g,$y).replace(/punctSpace/g,jy).replace(/punct/g,Ed).getRegex(),Uy=Ue("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Td).replace(/punctSpace/g,Bo).replace(/punct/g,is).getRegex(),Vy=Ue(/\\(punct)/,"gu").replace(/punct/g,is).getRegex(),Ky=Ue(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),zy=Ue(qo).replace("(?:-->|$)","-->").getRegex(),Gy=Ue("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",zy).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Xa=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,Zy=Ue(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",Xa).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Rd=Ue(/^!?\[(label)\]\[(ref)\]/).replace("label",Xa).replace("ref",Fo).getRegex(),Pd=Ue(/^!?\[(ref)\](?:\[\])?/).replace("ref",Fo).getRegex(),Wy=Ue("reflink|nolink(?!\\()","g").replace("reflink",Rd).replace("nolink",Pd).getRegex(),Uo={_backpedal:Jn,anyPunctuation:Vy,autolink:Ky,blockSkip:Dy,br:Id,code:Oy,del:Jn,emStrongLDelim:Fy,emStrongRDelimAst:Ly,emStrongRDelimUnd:Uy,escape:Py,link:Zy,nolink:Pd,punctuation:Ny,reflink:Rd,reflinkSearch:Wy,tag:Gy,text:My,url:Jn},Hy={...Uo,link:Ue(/^!?\[(label)\]\((.*?)\)/).replace("label",Xa).getRegex(),reflink:Ue(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Xa).getRegex()},ho={...Uo,emStrongRDelimAst:By,emStrongLDelim:qy,url:Ue(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},Jy={...ho,br:Ue(Id).replace("{2,}","*").getRegex(),text:Ue(ho.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},$a={normal:Lo,gfm:Cy,pedantic:Ry},qn={normal:Uo,gfm:ho,breaks:Jy,pedantic:Hy},Qy={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},_l=e=>Qy[e];function er(e,t){if(t){if(It.escapeTest.test(e))return e.replace(It.escapeReplace,_l)}else if(It.escapeTestNoEncode.test(e))return e.replace(It.escapeReplaceNoEncode,_l);return e}function xl(e){try{e=encodeURI(e).replace(It.percentDecode,"%")}catch{return null}return e}function kl(e,t){let r=e.replace(It.findPipe,(o,l,u)=>{let d=!1,f=l;for(;--f>=0&&u[f]==="\\";)d=!d;return d?"|":" |"}),n=r.split(It.splitPipe),s=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push("");for(;s<n.length;s++)n[s]=n[s].trim().replace(It.slashPipe,"|");return n}function Ln(e,t,r){let n=e.length;if(n===0)return"";let s=0;for(;s<n&&e.charAt(n-s-1)===t;)s++;return e.slice(0,n-s)}function Yy(e,t){if(e.indexOf(t[1])===-1)return-1;let r=0;for(let n=0;n<e.length;n++)if(e[n]==="\\")n++;else if(e[n]===t[0])r++;else if(e[n]===t[1]&&(r--,r<0))return n;return r>0?-2:-1}function Sl(e,t,r,n,s){let o=t.href,l=t.title||null,u=e[1].replace(s.other.outputLinkReplace,"$1");n.state.inLink=!0;let d={type:e[0].charAt(0)==="!"?"image":"link",raw:r,href:o,title:l,text:u,tokens:n.inlineTokens(u)};return n.state.inLink=!1,d}function Xy(e,t,r){let n=e.match(r.other.indentCodeCompensation);if(n===null)return t;let s=n[1];return t.split(`
35`).map(o=>{let l=o.match(r.other.beginningSpace);if(l===null)return o;let[u]=l;return u.length>=s.length?o.slice(s.length):o}).join(`
36`)}var es=class{options;rules;lexer;constructor(e){this.options=e||sn}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let r=t[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?r:Ln(r,`
37`)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let r=t[0],n=Xy(r,t[3]||"",this.rules);return{type:"code",raw:r,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:n}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let r=t[2].trim();if(this.rules.other.endingHash.test(r)){let n=Ln(r,"#");(this.options.pedantic||!n||this.rules.other.endingSpaceChar.test(n))&&(r=n.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:r,tokens:this.lexer.inline(r)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:Ln(t[0],`
38`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let r=Ln(t[0],`
39`).split(`
40`),n="",s="",o=[];for(;r.length>0;){let l=!1,u=[],d;for(d=0;d<r.length;
vendor: 26,726 bytes, lines 40-114
40d++)if(this.rules.other.blockquoteStart.test(r[d]))u.push(r[d]),l=!0;else if(!l)u.push(r[d]);else break;r=r.slice(d);let f=u.join(`
41`),m=f.replace(this.rules.other.blockquoteSetextReplace,`
42    $1`).replace(this.rules.other.blockquoteSetextReplace2,"");n=n?`${n}
43${f}`:f,s=s?`${s}
44${m}`:m;let b=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(m,o,!0),this.lexer.state.top=b,r.length===0)break;let v=o.at(-1);if(v?.type==="code")break;if(v?.type==="blockquote"){let y=v,x=y.raw+`
45`+r.join(`
46`),S=this.blockquote(x);o[o.length-1]=S,n=n.substring(0,n.length-y.raw.length)+S.raw,s=s.substring(0,s.length-y.text.length)+S.text;break}else if(v?.type==="list"){let y=v,x=y.raw+`
47`+r.join(`
48`),S=this.list(x);o[o.length-1]=S,n=n.substring(0,n.length-v.raw.length)+S.raw,s=s.substring(0,s.length-y.raw.length)+S.raw,r=x.substring(o.at(-1).raw.length).split(`
49`);continue}}return{type:"blockquote",raw:n,tokens:o,text:s}}}list(e){let t=this.rules.block.list.exec(e);if(t){let r=t[1].trim(),n=r.length>1,s={type:"list",raw:"",ordered:n,start:n?+r.slice(0,-1):"",loose:!1,items:[]};r=n?`\\d{1,9}\\${r.slice(-1)}`:`\\${r}`,this.options.pedantic&&(r=n?r:"[*+-]");let o=this.rules.other.listItemRegex(r),l=!1;for(;e;){let d=!1,f="",m="";if(!(t=o.exec(e))||this.rules.block.hr.test(e))break;f=t[0],e=e.substring(f.length);let b=t[2].split(`
50`,1)[0].replace(this.rules.other.listReplaceTabs,R=>" ".repeat(3*R.length)),v=e.split(`
51`,1)[0],y=!b.trim(),x=0;if(this.options.pedantic?(x=2,m=b.trimStart()):y?x=t[1].length+1:(x=t[2].search(this.rules.other.nonSpaceChar),x=x>4?1:x,m=b.slice(x),x+=t[1].length),y&&this.rules.other.blankLine.test(v)&&(f+=v+`
52`,e=e.substring(v.length+1),d=!0),!d){let R=this.rules.other.nextBulletRegex(x),B=this.rules.other.hrRegex(x),V=this.rules.other.fencesBeginRegex(x),E=this.rules.other.headingBeginRegex(x),te=this.rules.other.htmlBeginRegex(x);for(;e;){let U=e.split(`
53`,1)[0],K;if(v=U,this.options.pedantic?(v=v.replace(this.rules.other.listReplaceNesting,"  "),K=v):K=v.replace(this.rules.other.tabCharGlobal,"    "),V.test(v)||E.test(v)||te.test(v)||R.test(v)||B.test(v))break;if(K.search(this.rules.other.nonSpaceChar)>=x||!v.trim())m+=`
54`+K.slice(x);else{if(y||b.replace(this.rules.other.tabCharGlobal,"    ").search(this.rules.other.nonSpaceChar)>=4||V.test(b)||E.test(b)||B.test(b))break;m+=`
55`+v}!y&&!v.trim()&&(y=!0),f+=U+`
56`,e=e.substring(U.length+1),b=K.slice(x)}}s.loose||(l?s.loose=!0:this.rules.other.doubleBlankLine.test(f)&&(l=!0));let S=null,M;this.options.gfm&&(S=this.rules.other.listIsTask.exec(m),S&&(M=S[0]!=="[ ] ",m=m.replace(this.rules.other.listReplaceTask,""))),s.items.push({type:"list_item",raw:f,task:!!S,checked:M,loose:!1,text:m,tokens:[]}),s.raw+=f}let u=s.items.at(-1);if(u)u.raw=u.raw.trimEnd(),u.text=u.text.trimEnd();else return;s.raw=s.raw.trimEnd();for(let d=0;d<s.items.length;d++)if(this.lexer.state.top=!1,s.items[d].tokens=this.lexer.blockTokens(s.items[d].text,[]),!s.loose){let f=s.items[d].tokens.filter(b=>b.type==="space"),m=f.length>0&&f.some(b=>this.rules.other.anyLine.test(b.raw));s.loose=m}if(s.loose)for(let d=0;d<s.items.length;d++)s.items[d].loose=!0;return s}}html(e){let t=this.rules.block.html.exec(e);if(t)return{type:"html",block:!0,raw:t[0],pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:t[0]}}def(e){let t=this.rules.block.def.exec(e);if(t){let r=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),n=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",s=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:r,raw:t[0],href:n,title:s}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let r=kl(t[1]),n=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),s=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
57`):[],o={type:"table",raw:t[0],header:[],align:[],rows:[]};if(r.length===n.length){for(let l of n)this.rules.other.tableAlignRight.test(l)?o.align.push("right"):this.rules.other.tableAlignCenter.test(l)?o.align.push("center"):this.rules.other.tableAlignLeft.test(l)?o.align.push("left"):o.align.push(null);for(let l=0;l<r.length;l++)o.header.push({text:r[l],tokens:this.lexer.inline(r[l]),header:!0,align:o.align[l]});for(let l of s)o.rows.push(kl(l,o.header.length).map((u,d)=>({text:u,tokens:this.lexer.inline(u),header:!1,align:o.align[d]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:t[2].charAt(0)==="="?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let r=t[1].charAt(t[1].length-1)===`
58`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:r,tokens:this.lexer.inline(r)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let r=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(r)){if(!this.rules.other.endAngleBracket.test(r))return;let o=Ln(r.slice(0,-1),"\\");if((r.length-o.length)%2===0)return}else{let o=Yy(t[2],"()");if(o===-2)return;if(o>-1){let l=(t[0].indexOf("!")===0?5:4)+t[1].length+o;t[2]=t[2].substring(0,o),t[0]=t[0].substring(0,l).trim(),t[3]=""}}let n=t[2],s="";if(this.options.pedantic){let o=this.rules.other.pedanticHrefTitle.exec(n);o&&(n=o[1],s=o[3])}else s=t[3]?t[3].slice(1,-1):"";return n=n.trim(),this.rules.other.startAngleBracket.test(n)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(r)?n=n.slice(1):n=n.slice(1,-1)),Sl(t,{href:n&&n.replace(this.rules.inline.anyPunctuation,"$1"),title:s&&s.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let r;if((r=this.rules.inline.reflink.exec(e))||(r=this.rules.inline.nolink.exec(e))){let n=(r[2]||r[1]).replace(this.rules.other.multipleSpaceGlobal," "),s=t[n.toLowerCase()];if(!s){let o=r[0].charAt(0);return{type:"text",raw:o,text:o}}return Sl(r,s,r[0],this.lexer,this.rules)}}emStrong(e,t,r=""){let n=this.rules.inline.emStrongLDelim.exec(e);if(!(!n||n[3]&&r.match(this.rules.other.unicodeAlphaNumeric))&&(!(n[1]||n[2])||!r||this.rules.inline.punctuation.exec(r))){let s=[...n[0]].length-1,o,l,u=s,d=0,f=n[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(f.lastIndex=0,t=t.slice(-1*e.length+s);(n=f.exec(t))!=null;){if(o=n[1]||n[2]||n[3]||n[4]||n[5]||n[6],!o)continue;if(l=[...o].length,n[3]||n[4]){u+=l;continue}else if((n[5]||n[6])&&s%3&&!((s+l)%3)){d+=l;continue}if(u-=l,u>0)continue;l=Math.min(l,l+u+d);let m=[...n[0]][0].length,b=e.slice(0,s+n.index+m+l);if(Math.min(s,l)%2){let y=b.slice(1,-1);return{type:"em",raw:b,text:y,tokens:this.lexer.inlineTokens(y)}}let v=b.slice(2,-2);return{type:"strong",raw:b,text:v,tokens:this.lexer.inlineTokens(v)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let r=t[2].replace(this.rules.other.newLineCharGlobal," "),n=this.rules.other.nonSpaceChar.test(r),s=this.rules.other.startingSpaceChar.test(r)&&this.rules.other.endingSpaceChar.test(r);return n&&s&&(r=r.substring(1,r.length-1)),{type:"codespan",raw:t[0],text:r}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){let t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let r,n;return t[2]==="@"?(r=t[1],n="mailto:"+r):(r=t[1],n=r),{type:"link",raw:t[0],text:r,href:n,tokens:[{type:"text",raw:r,text:r}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let r,n;if(t[2]==="@")r=t[0],n="mailto:"+r;else{let s;do s=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(s!==t[0]);r=t[0],t[1]==="www."?n="http://"+t[0]:n=t[0]}return{type:"link",raw:t[0],text:r,href:n,tokens:[{type:"text",raw:r,text:r}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let r=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:r}}}},cr=class mo{tokens;options;state;tokenizer;inlineQueue;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||sn,this.options.tokenizer=this.options.tokenizer||new es,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let r={other:It,block:$a.normal,inline:qn.normal};this.options.pedantic?(r.block=$a.pedantic,r.inline=qn.pedantic):this.options.gfm&&(r.block=$a.gfm,this.options.breaks?r.inline=qn.breaks:r.inline=qn.gfm),this.tokenizer.rules=r}static get rules(){return{block:$a,inline:qn}}static lex(t,r){return new mo(r).lex(t)}static lexInline(t,r){return new mo(r).inlineTokens(t)}lex(t){t=t.replace(It.carriageReturn,`
59`),this.blockTokens(t,this.tokens);for(let r=0;r<this.inlineQueue.length;r++){let n=this.inlineQueue[r];this.inlineTokens(n.src,n.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,r=[],n=!1){for(this.options.pedantic&&(t=t.replace(It.tabCharGlobal,"    ").replace(It.spaceLine,""));t;){let s;if(this.options.extensions?.block?.some(l=>(s=l.call({lexer:this},t,r))?(t=t.substring(s.raw.length),r.push(s),!0):!1))continue;if(s=this.tokenizer.space(t)){t=t.substring(s.raw.length);let l=r.at(-1);s.raw.length===1&&l!==void 0?l.raw+=`
60`:r.push(s);continue}if(s=this.tokenizer.code(t)){t=t.substring(s.raw.length);let l=r.at(-1);l?.type==="paragraph"||l?.type==="text"?(l.raw+=(l.raw.endsWith(`
61`)?"":`
62`)+s.raw,l.text+=`
63`+s.text,this.inlineQueue.at(-1).src=l.text):r.push(s);continue}if(s=this.tokenizer.fences(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.heading(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.hr(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.blockquote(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.list(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.html(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.def(t)){t=t.substring(s.raw.length);let l=r.at(-1);l?.type==="paragraph"||l?.type==="text"?(l.raw+=(l.raw.endsWith(`
64`)?"":`
65`)+s.raw,l.text+=`
66`+s.raw,this.inlineQueue.at(-1).src=l.text):this.tokens.links[s.tag]||(this.tokens.links[s.tag]={href:s.href,title:s.title},r.push(s));continue}if(s=this.tokenizer.table(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.lheading(t)){t=t.substring(s.raw.length),r.push(s);continue}let o=t;if(this.options.extensions?.startBlock){let l=1/0,u=t.slice(1),d;this.options.extensions.startBlock.forEach(f=>{d=f.call({lexer:this},u),typeof d=="number"&&d>=0&&(l=Math.min(l,d))}),l<1/0&&l>=0&&(o=t.substring(0,l+1))}if(this.state.top&&(s=this.tokenizer.paragraph(o))){let l=r.at(-1);n&&l?.type==="paragraph"?(l.raw+=(l.raw.endsWith(`
67`)?"":`
68`)+s.raw,l.text+=`
69`+s.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=l.text):r.push(s),n=o.length!==t.length,t=t.substring(s.raw.length);continue}if(s=this.tokenizer.text(t)){t=t.substring(s.raw.length);let l=r.at(-1);l?.type==="text"?(l.raw+=(l.raw.endsWith(`
70`)?"":`
71`)+s.raw,l.text+=`
72`+s.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=l.text):r.push(s);continue}if(t){let l="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(l);break}else throw new Error(l)}}return this.state.top=!0,r}inline(t,r=[]){return this.inlineQueue.push({src:t,tokens:r}),r}inlineTokens(t,r=[]){let n=t,s=null;if(this.tokens.links){let u=Object.keys(this.tokens.links);if(u.length>0)for(;(s=this.tokenizer.rules.inline.reflinkSearch.exec(n))!=null;)u.includes(s[0].slice(s[0].lastIndexOf("[")+1,-1))&&(n=n.slice(0,s.index)+"["+"a".repeat(s[0].length-2)+"]"+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(s=this.tokenizer.rules.inline.anyPunctuation.exec(n))!=null;)n=n.slice(0,s.index)+"++"+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;(s=this.tokenizer.rules.inline.blockSkip.exec(n))!=null;)n=n.slice(0,s.index)+"["+"a".repeat(s[0].length-2)+"]"+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);let o=!1,l="";for(;t;){o||(l=""),o=!1;let u;if(this.options.extensions?.inline?.some(f=>(u=f.call({lexer:this},t,r))?(t=t.substring(u.raw.length),r.push(u),!0):!1))continue;if(u=this.tokenizer.escape(t)){t=t.substring(u.raw.length),r.push(u);continue}if(u=this.tokenizer.tag(t)){t=t.substring(u.raw.length),r.push(u);continue}if(u=this.tokenizer.link(t)){t=t.substring(u.raw.length),r.push(u);continue}if(u=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(u.raw.length);let f=r.at(-1);u.type==="text"&&f?.type==="text"?(f.raw+=u.raw,f.text+=u.text):r.push(u);continue}if(u=this.tokenizer.emStrong(t,n,l)){t=t.substring(u.raw.length),r.push(u);continue}if(u=this.tokenizer.codespan(t)){t=t.substring(u.raw.length),r.push(u);continue}if(u=this.tokenizer.br(t)){t=t.substring(u.raw.length),r.push(u);continue}if(u=this.tokenizer.del(t)){t=t.substring(u.raw.length),r.push(u);continue}if(u=this.tokenizer.autolink(t)){t=t.substring(u.raw.length),r.push(u);continue}if(!this.state.inLink&&(u=this.tokenizer.url(t))){t=t.substring(u.raw.length),r.push(u);continue}let d=t;if(this.options.extensions?.startInline){let f=1/0,m=t.slice(1),b;this.options.extensions.startInline.forEach(v=>{b=v.call({lexer:this},m),typeof b=="number"&&b>=0&&(f=Math.min(f,b))}),f<1/0&&f>=0&&(d=t.substring(0,f+1))}if(u=this.tokenizer.inlineText(d)){t=t.substring(u.raw.length),u.raw.slice(-1)!=="_"&&(l=u.raw.slice(-1)),o=!0;let f=r.at(-1);f?.type==="text"?(f.raw+=u.raw,f.text+=u.text):r.push(u);continue}if(t){let f="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(f);break}else throw new Error(f)}}return r}},ts=class{options;parser;constructor(e){this.options=e||sn}space(e){return""}code({text:e,lang:t,escaped:r}){let n=(t||"").match(It.notSpaceStart)?.[0],s=e.replace(It.endingNewline,"")+`
73`;return n?'<pre><code class="language-'+er(n)+'">'+(r?s:er(s,!0))+`</code></pre>
74`:"<pre><code>"+(r?s:er(s,!0))+`</code></pre>
75`}blockquote({tokens:e}){return`<blockquote>
76${this.parser.parse(e)}</blockquote>
77`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
78`}hr(e){return`<hr>
79`}list(e){let t=e.ordered,r=e.start,n="";for(let l=0;l<e.items.length;l++){let u=e.items[l];n+=this.listitem(u)}let s=t?"ol":"ul",o=t&&r!==1?' start="'+r+'"':"";return"<"+s+o+`>
80`+n+"</"+s+`>
81`}listitem(e){let t="";if(e.task){let r=this.checkbox({checked:!!e.checked});e.loose?e.tokens[0]?.type==="paragraph"?(e.tokens[0].text=r+" "+e.tokens[0].text,e.tokens[0].tokens&&e.tokens[0].tokens.length>0&&e.tokens[0].tokens[0].type==="text"&&(e.tokens[0].tokens[0].text=r+" "+er(e.tokens[0].tokens[0].text),e.tokens[0].tokens[0].escaped=!0)):e.tokens.unshift({type:"text",raw:r+" ",text:r+" ",escaped:!0}):t+=r+" "}return t+=this.parser.parse(e.tokens,!!e.loose),`<li>${t}</li>
82`}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox">'}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
83`}table(e){let t="",r="";for(let s=0;s<e.header.length;s++)r+=this.tablecell(e.header[s]);t+=this.tablerow({text:r});let n="";for(let s=0;s<e.rows.length;s++){let o=e.rows[s];r="";for(let l=0;l<o.length;l++)r+=this.tablecell(o[l]);n+=this.tablerow({text:r})}return n&&(n=`<tbody>${n}</tbody>`),`<table>
84<thead>
85`+t+`</thead>
86`+n+`</table>
87`}tablerow({text:e}){return`<tr>
88${e}</tr>
89`}tablecell(e){let t=this.parser.parseInline(e.tokens),r=e.header?"th":"td";return(e.align?`<${r} align="${e.align}">`:`<${r}>`)+t+`</${r}>
90`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${er(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:r}){let n=this.parser.parseInline(r),s=xl(e);if(s===null)return n;e=s;let o='<a href="'+e+'"';return t&&(o+=' title="'+er(t)+'"'),o+=">"+n+"</a>",o}image({href:e,title:t,text:r,tokens:n}){n&&(r=this.parser.parseInline(n,this.parser.textRenderer));let s=xl(e);if(s===null)return er(r);e=s;let o=`<img src="${e}" alt="${r}"`;return t&&(o+=` title="${er(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:er(e.text)}},Vo=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}},dr=class go{options;renderer;textRenderer;constructor(t){this.options=t||sn,this.options.renderer=this.options.renderer||new ts,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Vo}static parse(t,r){return new go(r).parse(t)}static parseInline(t,r){return new go(r).parseInline(t)}parse(t,r=!0){let n="";for(let s=0;s<t.length;s++){let o=t[s];if(this.options.extensions?.renderers?.[o.type]){let u=o,d=this.options.extensions.renderers[u.type].call({parser:this},u);if(d!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(u.type)){n+=d||"";continue}}let l=o;switch(l.type){case"space":{n+=this.renderer.space(l);continue}case"hr":{n+=this.renderer.hr(l);continue}case"heading":{n+=this.renderer.heading(l);continue}case"code":{n+=this.renderer.code(l);continue}case"table":{n+=this.renderer.table(l);continue}case"blockquote":{n+=this.renderer.blockquote(l);continue}case"list":{n+=this.renderer.list(l);continue}case"html":{n+=this.renderer.html(l);continue}case"def":{n+=this.renderer.def(l);continue}case"paragraph":{n+=this.renderer.paragraph(l);continue}case"text":{let u=l,d=this.renderer.text(u);for(;s+1<t.length&&t[s+1].type==="text";)u=t[++s],d+=`
91`+this.renderer.text(u);r?n+=this.renderer.paragraph({type:"paragraph",raw:d,text:d,tokens:[{type:"text",raw:d,text:d,escaped:!0}]}):n+=d;continue}default:{let u='Token with "'+l.type+'" type was not found.';if(this.options.silent)return console.error(u),"";throw new Error(u)}}}return n}parseInline(t,r=this.renderer){let n="";for(let s=0;s<t.length;s++){let o=t[s];if(this.options.extensions?.renderers?.[o.type]){let u=this.options.extensions.renderers[o.type].call({parser:this},o);if(u!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(o.type)){n+=u||"";continue}}let l=o;switch(l.type){case"escape":{n+=r.text(l);break}case"html":{n+=r.html(l);break}case"link":{n+=r.link(l);break}case"image":{n+=r.image(l);break}case"strong":{n+=r.strong(l);break}case"em":{n+=r.em(l);break}case"codespan":{n+=r.codespan(l);break}case"br":{n+=r.br(l);break}case"del":{n+=r.del(l);break}case"text":{n+=r.text(l);break}default:{let u='Token with "'+l.type+'" type was not found.';if(this.options.silent)return console.error(u),"";throw new Error(u)}}}return n}},Ba=class{options;block;constructor(e){this.options=e||sn}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}provideLexer(){return this.block?cr.lex:cr.lexInline}provideParser(){return this.block?dr.parse:dr.parseInline}},eb=class{defaults=jo();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=dr;Renderer=ts;TextRenderer=Vo;Lexer=cr;Tokenizer=es;Hooks=Ba;constructor(...e){this.use(...e)}walkTokens(e,t){let r=[];for(let n of e)switch(r=r.concat(t.call(this,n)),n.type){case"table":{let s=n;for(let o of s.header)r=r.concat(this.walkTokens(o.tokens,t));for(let o of s.rows)for(let l of o)r=r.concat(this.walkTokens(l.tokens,t));break}case"list":{let s=n;r=r.concat(this.walkTokens(s.items,t));break}default:{let s=n;this.defaults.extensions?.childTokens?.[s.type]?this.defaults.extensions.childTokens[s.type].forEach(o=>{let l=s[o].flat(1/0);r=r.concat(this.walkTokens(l,t))}):s.tokens&&(r=r.concat(this.walkTokens(s.tokens,t)))}}return r}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(r=>{let n={...r};if(n.async=this.defaults.async||n.async||!1,r.extensions&&(r.extensions.forEach(s=>{if(!s.name)throw new Error("extension name required");if("renderer"in s){let o=t.renderers[s.name];o?t.renderers[s.name]=function(...l){let u=s.renderer.apply(this,l);return u===!1&&(u=o.apply(this,l)),u}:t.renderers[s.name]=s.renderer}if("tokenizer"in s){if(!s.level||s.level!=="block"&&s.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=t[s.level];o?o.unshift(s.tokenizer):t[s.level]=[s.tokenizer],s.start&&(s.level==="block"?t.startBlock?t.startBlock.push(s.start):t.startBlock=[s.start]:s.level==="inline"&&(t.startInline?t.startInline.push(s.start):t.startInline=[s.start]))}"childTokens"in s&&s.childTokens&&(t.childTokens[s.name]=s.childTokens)}),n.extensions=t),r.renderer){let s=this.defaults.renderer||new ts(this.defaults);for(let o in r.renderer){if(!(o in s))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let l=o,u=r.renderer[l],d=s[l];s[l]=(...f)=>{let m=u.apply(s,f);return m===!1&&(m=d.apply(s,f)),m||""}}n.renderer=s}if(r.tokenizer){let s=this.defaults.tokenizer||new es(this.defaults);for(let o in r.tokenizer){if(!(o in s))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let l=o,u=r.tokenizer[l],d=s[l];s[l]=(...f)=>{let m=u.apply(s,f);return m===!1&&(m=d.apply(s,f)),m}}n.tokenizer=s}if(r.hooks){let s=this.defaults.hooks||new Ba;for(let o in r.hooks){if(!(o in s))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let l=o,u=r.hooks[l],d=s[l];Ba.passThroughHooks.has(o)?s[l]=f=>{if(this.defaults.async)return Promise.resolve(u.call(s,f)).then(b=>d.call(s,b));let m=u.call(s,f);return d.call(s,m)}:s[l]=(...f)=>{let m=u.apply(s,f);return m===!1&&(m=d.apply(s,f)),m}}n.hooks=s}if(r.walkTokens){let s=this.defaults.walkTokens,o=r.walkTokens;n.walkTokens=function(l){let u=[];return u.push(o.call(this,l)),s&&(u=u.concat(s.call(this,l))),u}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return cr.lex(e,t??this.defaults)}parser(e,t){return dr.parse(e,t??this.defaults)}parseMarkdown(e){return(t,r)=>{let n={...r},s={...this.defaults,...n},o=this.onError(!!s.silent,!!s.async);if(this.defaults.async===!0&&n.async===!1)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return o(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));s.hooks&&(s.hooks.options=s,s.hooks.block=e);let l=s.hooks?s.hooks.provideLexer():e?cr.lex:cr.lexInline,u=s.hooks?s.hooks.provideParser():e?dr.parse:dr.parseInline;if(s.async)return Promise.resolve(s.hooks?s.hooks.preprocess(t):t).then(d=>l(d,s)).then(d=>s.hooks?s.hooks.processAllTokens(d):d).then(d=>s.walkTokens?Promise.all(this.walkTokens(d,s.walkTokens)).then(()=>d):d).then(d=>u(d,s)).then(d=>s.hooks?s.hooks.postprocess(d):d).catch(o);try{s.hooks&&(t=s.hooks.preprocess(t));let d=l(t,s);s.hooks&&(d=s.hooks.processAllTokens(d)),s.walkTokens&&this.walkTokens(d,s.walkTokens);let f=u(d,s);return s.hooks&&(f=s.hooks.postprocess(f)),f}catch(d){return o(d)}}}onError(e,t){return r=>{if(r.message+=`
92Please report this to https://github.com/markedjs/marked.`,e){let n="<p>An error occurred:</p><pre>"+er(r.message+"",!0)+"</pre>";return t?Promise.resolve(n):n}if(t)return Promise.reject(r);throw r}}},rn=new eb;function ze(e,t){return rn.parse(e,t)}ze.options=ze.setOptions=function(e){return rn.setOptions(e),ze.defaults=rn.defaults,_d(ze.defaults),ze};ze.getDefaults=jo;ze.defaults=sn;ze.use=function(...e){return rn.use(...e),ze.defaults=rn.defaults,_d(ze.defaults),ze};ze.walkTokens=function(e,t){return rn.walkTokens(e,t)};ze.parseInline=rn.parseInline;ze.Parser=dr;ze.parser=dr.parse;ze.Renderer=ts;ze.TextRenderer=Vo;ze.Lexer=cr;ze.lexer=cr.lex;ze.Tokenizer=es;ze.Hooks=Ba;ze.parse=ze;ze.options;ze.setOptions;ze.use;ze.walkTokens;ze.parseInline;dr.parse;var x_=cr.lex,da=(e=>(e.Builtin="builtin",e.Preset="preset",e.Custom="custom",e))(da||{});class Bt extends Error{}const tb=`## Instructions
93* Respond in the user's language
94* Do not reveal specific model names, nor model provider information
95* The following "UserRules" take priority over Instructions when there are conflicts
96* Never provide code snippets for replacement - always use tools to write files
97* The page is rendered in an iframe environment without bundler and real file system
98* Never create image files. Use 'get-image' tool to get image URLs when needed
99* If the same tool fails 3 times consecutively, do not attempt again
100* After completing all edits, you MUST call the \`inspectPage\` tool to render the page and check for runtime/console errors and that key elements render. Fix any error it reports, then re-inspect, before you finish.
101* Prioritize using the \`grep\` tool to search for patterns in text or files.
102
103## Standard Workflows
104
105### Modifying Existing Pages
106
107** User may provide ACTIVE_FILE. Only modify ACTIVE_FILE unless demanded ** 
108
109**If the user expresses strong dissatisfaction with the existing version or requests a redesign, do not reference the existing page content and follow the 'Creating New Pages' workflow. Otherwise, always follow this workflow in order**:
110
1111. **Locate the target file**
112   - Call \`listFiles\` to get all available page files
113   - Identify the target file path based on user requirements
114   - If the file path is already known or obvious, you may skip this 
114step
115
1162. **Find the code to modify**
117   - **Use \`grep\` tool** when searching for specific patterns:
118     - HTML tags, CSS classes, text content, attributes
119     - Example: \`grep({ grepPattern: 'class.*login-button', globPattern: '*.html' })\`
120     - Example: \`grep({ grepPattern: '<div.*id="header">', globPattern: 'pages/*.html' })\`
121   - **Use \`read-file\` tool** when you need to view the complete file structure:
122     - Read entire file: \`read-file({ filePath: 'login.html' })\`
123     - Read specific lines: \`read-file({ filePath: 'login.html', lines: { start: 50, end: 100 } })\`
124
1253. **Make precise modifications**
126   - Use \`replace-file-content\` tool to modify the located code
127   - Only modify what the user requested, keep other code unchanged
128   - If no results found from search, don't repeat the same query
129
130**Example**:
131\`\`\`
132User: "Change login page button color"
133→ Step 1: listFiles → identify "login.html"
134→ Step 2: grep({ grepPattern: '<button', globPattern: 'login.html' }) OR read-file({ filePath: 'login.html' })
135→ Step 3: replace-file-content with the modification
136\`\`\`
137
138### Creating New Pages
1391. **Check if file already exists** (unless user explicitly requests a new file)
140   - Call \`listFiles\` to verify the file doesn't exist
141   - If similar file exists, consider modifying it instead
142
1432. **Create the new file**
144   - Call \`create-file\` tool to write new HTML code
145   - Use raw text as input, must not use escape characters like \`\\\\n\`, \`\\\\\\n\`, \`\\\\"\`, \`\\\\\\"\`
146
1473. **Handle images** (if needed)
148   - First generate complete HTML code with image placeholders, then immediately write it to the file
149   - For each image element, call \`get-image\` tool to get contextually relevant image URL
150   - After successfully obtaining the image URL, immediately replace placeholder with actual URL in the file
151   - Read the code snippet to verify replacement succeeded
152
153## Requirements
154
155### For Modifying Pages
156* Always follow the standard modification workflow: locate → find → modify
157* Only modify the parts the user asks you to change
158* Don't change the existing code structure
159* Try to preserve and reuse existing text and formatting
160* When modifying the page, to guarantee style application and override potential conflicts, always prepend the ! modifier to every class 
160name (e.g., !flex, !text-red-500).
161
162
163### For Code Output
164* Never return HTML code directly in responses - always use tools to write files
165* When writing content, use raw text as input, ensure no extra escape characters like '\\\\n'
166* Do not use LocalStorage
167* Charts must use SVG - do not use canvas
168* Use Tailwind CSS for styling unless otherwise specified
169* Define reusable CSS classes for better maintainability
170
171`;var it=(e=>(e.CreateFile="createFile",e.ReadFile="readFile",e.ReplaceFileContent="replaceFileContent",e.UpdateFileContent="updateFileContent",e.Grep="grep",e.GetImage="getImage",e.ListFiles="listFiles",e.SetViewportWidth="setViewportWidth",e.InspectPage="inspectPage",e.VisualCheck="visualCheck",e))(it||{});const rb=z({filePath:D().describe("The name of the newly created file, including its relative path."),content:D().describe("The initial content of the newly created file.")}),nb=z({filePath:D().describe("The relative path of the created file.")}),ab=Rr("tools:create-file");function sb(e){const{switchPreviewFile:t}=e,{createFile:r}=Or(),n={name:it.CreateFile,description:"Create a new text file in the project. Use this tool when you need to add a new html file to the project.",inputSchema:rb,outputSchema:nb};async function s(l,u){return ab("on tool call, filename: %o",l),u.throwIfAborted(),await r(ds.Agent,l.filePath,l.content),u.throwIfAborted(),t(l.filePath),{filePath:l.filePath}}return{name:it.CreateFile,tool:n,onToolCall:s}}const ob=z({description:D().trim().min(1).max(200).describe("The text description of the image you want to get. Length limit: 200 characters."),width:we().default(512).describe("The width of the generated image in pixels. Recommended range: 512px to 2048px."),height:we().default(512).describe("The height of the generated image in pixels. Recommended range: 512px to 2048px.")}),ib=z({imageUrl:D().describe("The URL of the image.")});function Bn(e){try{const t=new URL(e,"https://localhost");return Lp(t.href,[Ei.CHINA,Ei.WORLD])}catch{return!1}}function lb(e){const t=[];try{const n=new DOMParser().parseFromString(e,"text/html"),s=n.querySelectorAll("img[src]");for(const d of s){const f=d.getAttribute("src");f&&Bn(f)&&t.push(f)}const o=n.querySelectorAll('[style*="url"]');for(const d of o){const m=(d.getAttribute("style")||"").match(/url\(['"]?([^'"\)]+)['"]?\)/g);if(m)for(const b of m){const v=b.match(/url\(['"]?([^'"\)]+)['"]?\)/);if(v){const y=v[1];Bn(y)&&t.push(y)}}}const l=n.querySelectorAll("[srcset]");for(const d of l){const m=(d.getAttribute("srcset")||"").split(",");for(const b of m){const v=b.trim().split(/\s+/)[0];v&&Bn(v)&&t.push(v)}}const u=n.querySelectorAll("source[srcset]");for(const d of u){const m=(d.getAttribute("srcset")||"").split(",");for(const b of m){const v=b.trim().split(/\s+/)[0];v&&Bn(v)&&t.push(v)}}}catch{const r=e.match(/https?:\/\/[^\s"'<>]+/gi)?.filter(Bn);r&&t.push(...r)}return t}function ub(e){const{lastMessage:t,activeVersionNumber:r,activeFilename:n}=e,s=At(),{readFile:o}=Or(),l={name:it.GetImage,description:"Find or generate an image match the description text using AI. The prompt's length should not exceed 200 characters. The image's aspect ratio should between 1:3 and 3:1, the product of width and height is between [512*512, 2048*2048]. Use this tool when you need an image to fill content.",inputSchema:ob,outputSchema:ib};async function u(f,m){const b=[],v=ie(t)?.parts??[];for(const R of v)if(!(!Gt(R)||R.type!==`tool-${it.GetImage}`||R.state!=="output-available"||!R.output?.imageUrl))try{const B=new URL(R.output.imageUrl);b.push(B.pathname)}catch(B){window.reportError(B)}const y=ie(n),x=ie(r);if(y&&x)try{const R=await o(y,x);if(R?.content){const B=lb(R.content);for(const V of B)try{const E=new URL(V);b.includes(E.pathname)||b.push(E.pathname)}catch{}}}catch(R){window.reportError(R)}const S=await s("/api/refore/text-to-image",{method:"POST",body:{prompt:f.description,width:f.width,height:f.height,exclude:b},signal:m});return{imageUrl:`${ns(S.cdnPath)}?imageMogr2/thumbnail/${f.width*2}x${f.height*2}>`}}return{name:it.GetImage,tool:l,onToolCall:u}}const Od=(e,t,r)=>{const n=e instanceof RegExp?Il(e,r):e,s=t instanceof RegExp?Il(t,r):t,o=n!==null&&s!=null&&cb(n,s,r);return o&&{start:o[0],end:o[1],pre:r.slice(0,o[0]),body:r.slice(o[0]+n.length,o[1]),post:r.slice(o[1]+s.length)}},Il=(e,t)=>{const r=t.match(e);return r?r[0]:null},cb=(e,t,r)=>{let n,s,o,l,u,d=r.indexOf(e),f=r.indexOf(t,d+1),m=d;if(d>=0&&f>0){if(e===t)return[d,f];for(n=[],o=r.length;m>=0&&!u;){if(m===d)n.push(m),d=r.indexOf(e,m+1);else if(n.length===1){const b=n.pop();b!==void 0&&(u=[b,f])}else s=n.pop(),s!==void 0&&s<o&&(o=s,l=f),f=r.indexOf(t,m+1);m=d<f&&d>=0?d:f}n.length&&l!==void 0&&(u=[o,l])}return u},Md="\0SLASH"+Math.random()+"\0",Nd="\0OPEN"+Math.random()+"\0",Ko="\0CLOSE"+Math.random()+"\0",jd="\0COMMA"+Math.random()+"\0",$d="\0PERIOD"+Math.random()+"\0",db=new RegExp(Md,"g"),pb=new RegExp(Nd,"g"),fb=new RegExp(Ko,"g"),hb=new RegExp(jd,"g"),mb=new RegExp($d,"g"),gb=/\\\\/g,vb=/\\{/g,yb=/\\}/g,bb=/\\,/g,wb=/\\./g;function Hs(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function _b(e){return e.replace(gb,Md).replace(vb,Nd).replace(yb,Ko).replace(bb,jd).replace(wb,$d)}function xb(e){return e.replace(db,"\\").replace(pb,"{").replace(fb,"}").replace(hb,",").replace(mb,".")}function Dd(e){if(!e)return[""];const t=[],r=Od("{","}",e);if(!r)return e.split(",");const{pre:n,body:s,post:o}=r,l=n.split(",");l[l.length-1]+="{"+s+"}";const u=Dd(o);return o.length&&(l[l.length-1]+=u.shift(),l.push.apply(l,u)),t.push.apply(t,l),t}function kb(e){return e?(e.slice(0,2)==="{}"&&(e="\\{\\}"+e.slice(2)),zn(_b(e),!0).map(xb)):[]}function Sb(e){return"{"+e+"}"}function Ib(e){return/^-?0\d/.test(e)}function Tb(e,t){return e<=t}function Eb(e,t){return e>=t}function zn(e,t){const r=[],n=Od("{","}",e);if(!n)return[e];const s=n.pre,o=n.post.length?zn(n.post,!1):[""];
171if(/\$$/.test(n.pre))for(let l=0;l<o.length;l++){const u=s+"{"+n.body+"}"+o[l];r.push(u)}else{const l=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(n.body),u=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(n.body),d=l||u,f=n.body.indexOf(",")>=0;if(!d&&!f)return n.post.match(/,(?!,).*\}/)?(e=n.pre+"{"+n.body+Ko+n.post,zn(e)):[e];let m;if(d)m=n.body.split(/\.\./);else if(m=Dd(n.body),m.length===1&&m[0]!==void 0&&(m=zn(m[0],!1).map(Sb),m.length===1))return o.map(v=>n.pre+m[0]+v);let b;if(d&&m[0]!==void 0&&m[1]!==void 0){const v=Hs(m[0]),y=Hs(m[1]),x=Math.max(m[0].length,m[1].length);let S=m.length===3&&m[2]!==void 0?Math.abs(Hs(m[2])):1,M=Tb;y<v&&(S*=-1,M=Eb);const B=m.some(Ib);b=[];for(let V=v;M(V,y);V+=S){let E;if(u)E=String.fromCharCode(V),E==="\\"&&(E="");else if(E=String(V),B){const te=x-E.length;if(te>0){const U=new Array(te+1).join("0");V<0?E="-"+U+E.slice(1):E=U+E}}b.push(E)}}else{b=[];for(let v=0;v<m.length;v++)b.push.apply(b,zn(m[v],!1))}for(let v=0;v<b.length;v++)for(let y=0;y<o.length;y++){const x=s+b[v]+o[y];(!t||d||x)&&r.push(x)}}return r}const Ab=1024*64,rs=e=>{if(typeof e!="string")throw new TypeError("invalid pattern");if(e.length>Ab)throw new TypeError("pattern is too long")},Cb={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},Un=e=>e.replace(/[[\]\\-]/g,"\\$&"),Rb=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Tl=e=>e.join(""),Pb=(e,t)=>{const r=t;if(e.charAt(r)!=="[")throw new Error("not in a brace expression");const n=[],s=[];let o=r+1,l=!1,u=!1,d=!1,f=!1,m=r,b="";e:for(;o<e.length;){const S=e.charAt(o);if((S==="!"||S==="^")&&o===r+1){f=!0,o++;continue}if(S==="]"&&l&&!d){m=o+1;break}if(l=!0,S==="\\"&&!d){d=!0,o++;continue}if(S==="["&&!d){for(const[M,[R,B,V]]of Object.entries(Cb))if(e.startsWith(M,o)){if(b)return["$.",!1,e.length-r,!0];o+=M.length,V?s.push(R):n.push(R),u=u||B;continue e}}if(d=!1,b){S>b?n.push(Un(b)+"-"+Un(S)):S===b&&n.push(Un(S)),b="",o++;continue}if(e.startsWith("-]",o+1)){n.push(Un(S+"-")),o+=2;continue}if(e.startsWith("-",o+1)){b=S,o+=2;continue}n.push(Un(S)),o++}if(m<o)return["",!1,0,!1];if(!n.length&&!s.length)return["$.",!1,e.length-r,!0];if(s.length===0&&n.length===1&&/^\\?.$/.test(n[0])&&!f){const S=n[0].length===2?n[0].slice(-1):n[0];return[Rb(S),!1,m-r,!1]}const v="["+(f?"^":"")+Tl(n)+"]",y="["+(f?"":"^")+Tl(s)+"]";return[n.length&&s.length?"("+v+"|"+y+")":n.length?v:y,u,m-r,!0]},Gn=(e,{windowsPathsNoEscape:t=!1}={})=>t?e.replace(/\[([^\/\\])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"),Ob=new Set(["!","?","+","*","@"]),El=e=>Ob.has(e),Mb="(?!(?:^|/)\\.\\.?(?:$|/))",Da="(?!\\.)",Nb=new Set(["[","."]),jb=new Set(["..","."]),$b=new Set("().*{}+?[]^$\\!"),Db=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),zo="[^/]",Al=zo+"*?",Cl=zo+"+?";class kt{type;#r;#n;#s=!1;#e=[];#t;#o;#l;#i=!1;#a;#u;#d=!1;constructor(t,r,n={}){this.type=t,t&&(this.#n=!0),this.#t=r,this.#r=this.#t?this.#t.#r:this,this.#a=this.#r===this?n:this.#r.#a,this.#l=this.#r===this?[]:this.#r.#l,t==="!"&&!this.#r.#i&&this.#l.push(this),this.#o=this.#t?this.#t.#e.length:0}get hasMagic(){if(this.#n!==void 0)return this.#n;for(const t of this.#e)if(typeof t!="string"&&(t.type||t.hasMagic))return this.#n=!0;return this.#n}toString(){return this.#u!==void 0?this.#u:this.type?this.#u=this.type+"("+this.#e.map(t=>String(t)).join("|")+")":this.#u=this.#e.map(t=>String(t)).join("")}#f(){if(this!==this.#r)throw new Error("should only call on root");if(this.#i)return this;this.toString(),this.#i=!0;let t;for(;t=this.#l.pop();){if(t.type!=="!")continue;let r=t,n=r.#t;for(;n;){for(let s=r.#o+1;!n.type&&s<n.#e.length;s++)for(const o of t.#e){if(typeof o=="string")throw new Error("string part in extglob AST??");o.copyIn(n.#e[s])}r=n,n=r.#t}}return this}push(...t){for(const r of t)if(r!==""){if(typeof r!="string"&&!(r instanceof kt&&r.#t===this))throw new Error("invalid part: "+r);this.#e.push(r)}}
171toJSON(){const t=this.type===null?this.#e.slice().map(r=>typeof r=="string"?r:r.toJSON()):[this.type,...this.#e.map(r=>r.toJSON())];return this.isStart()&&!this.type&&t.unshift([]),this.isEnd()&&(this===this.#r||this.#r.#i&&this.#t?.type==="!")&&t.push({}),t}isStart(){if(this.#r===this)return!0;if(!this.#t?.isStart())return!1;if(this.#o===0)return!0;const t=this.#t;for(let r=0;r<this.#o;r++){const n=t.#e[r];if(!(n instanceof kt&&n.type==="!"))return!1}return!0}isEnd(){if(this.#r===this||this.#t?.type==="!")return!0;if(!this.#t?.isEnd())return!1;if(!this.type)return this.#t?.isEnd();const t=this.#t?this.#t.#e.length:0;return this.#o===t-1}copyIn(t){typeof t=="string"?this.push(t):this.push(t.clone(this))}clone(t){const r=new kt(this.type,t);for(const n of this.#e)r.copyIn(n);return r}static#c(t,r,n,s){let o=!1,l=!1,u=-1,d=!1;if(r.type===null){let y=n,x="";for(;y<t.length;){const S=t.charAt(y++);if(o||S==="\\"){o=!o,x+=S;continue}if(l){y===u+1?(S==="^"||S==="!")&&(d=!0):S==="]"&&!(y===u+2&&d)&&(l=!1),x+=S;continue}else if(S==="["){l=!0,u=y,d=!1,x+=S;continue}if(!s.noext&&El(S)&&t.charAt(y)==="("){r.push(x),x="";const M=new kt(S,r);y=kt.#c(t,M,y,s),r.push(M);continue}x+=S}return r.push(x),y}let f=n+1,m=new kt(null,r);const b=[];let v="";for(;f<t.length;){const y=t.charAt(f++);if(o||y==="\\"){o=!o,v+=y;continue}if(l){f===u+1?(y==="^"||y==="!")&&(d=!0):y==="]"&&!(f===u+2&&d)&&(l=!1),v+=y;continue}else if(y==="["){l=!0,u=f,d=!1,v+=y;continue}if(El(y)&&t.charAt(f)==="("){m.push(v),v="";const x=new kt(y,m);m.push(x),f=kt.#c(t,x,f,s);continue}if(y==="|"){m.push(v),v="",b.push(m),m=new kt(null,r);continue}if(y===")")return v===""&&r.#e.length===0&&(r.#d=!0),m.push(v),v="",r.push(...b,m),f;v+=y}return r.type=null,r.#n=void 0,r.#e=[t.substring(n-1)],f}static fromGlob(t,r={}){const n=new kt(null,void 0,r);return kt.#c(t,n,0,r),n}toMMPattern(){if(this!==this.#r)return this.#r.toMMPattern();const t=this.toString(),[r,n,s,o]=this.toRegExpSource();if(!(s||this.#n||this.#a.nocase&&!this.#a.nocaseMagicOnly&&t.toUpperCase()!==t.toLowerCase()))return n;const u=(this.#a.nocase?"i":"")+(o?"u":"");return Object.assign(new RegExp(`^${r}$`,u),{_src:r,_glob:t})}get options(){return this.#a}toRegExpSource(t){const r=t??!!this.#a.dot;if(this.#r===this&&this.#f(),!this.type){const d=this.isStart()&&this.isEnd(),f=this.#e.map(y=>{const[x,S,M,R]=typeof y=="string"?kt.#h(y,this.#n,d):y.toRegExpSource(t);return this.#n=this.#n||M,this.#s=this.#s||R,x}).join("");let m="";if(this.isStart()&&typeof this.#e[0]=="string"&&!(this.#e.length===1&&jb.has(this.#e[0]))){const x=Nb,S=r&&x.has(f.charAt(0))||f.startsWith("\\.")&&x.has(f.charAt(2))||f.startsWith("\\.\\.")&&x.has(f.charAt(4)),M=!r&&!t&&x.has(f.charAt(0));m=S?Mb:M?Da:""}let b="";return this.isEnd()&&this.#r.#i&&this.#t?.type==="!"&&(b="(?:$|\\/)"),[m+f+b,Gn(f),this.#n=!!this.#n,this.#s]}const n=this.type==="*"||this.type==="+",s=this.type==="!"?"(?:(?!(?:":"(?:";let o=this.#p(r);if(this.isStart()&&this.isEnd()&&!o&&this.type!=="!"){const d=this.toString();return this.#e=[d],this.type=null,this.#n=void 0,[d,Gn(this.toString()),!1,!1]}let l=!n||t||r||!Da?"":this.#p(!0);l===o&&(l=""),l&&(o=`(?:${o})(?:${l})*?`);let u="";if(this.type==="!"&&this.#d)u=(this.isStart()&&!r?Da:"")+Cl;else{const d=this.type==="!"?"))"+(this.isStart()&&!r&&!t?Da:"")+Al+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&l?")":this.type==="*"&&l?")?":`)${this.type}`;u=s+o+d}return[u,Gn(o),this.#n=!!this.#n,this.#s]}#p(t){return this.#e.map(r=>{if(typeof r=="string")throw new Error("string type in extglob ast??");const[n,s,o,l]=r.toRegExpSource(t);return this.#s=this.#s||l,n}).filter(r=>!(this.isStart()&&this.isEnd())||!!r).join("|")}static#h(t,r,n=!1){let s=!1,o="",l=!1;for(let u=0;u<t.length;u++){const d=t.charAt(u);if(s){s=!1,o+=($b.has(d)?"\\":"")+d;continue}if(d==="\\"){u===t.length-1?o+="\\\\":s=!0;continue}if(d==="["){const[f,m,b,v]=Pb(t,u);if(b){o+=f,l=l||m,u+=b-1,r=r||v;continue}}if(d==="*"){n&&t==="*"?o+=Cl:o+=Al,r=!0;continue}if(d==="?"){o+=zo,r=!0;continue}o+=Db(d)}return[o,Gn(t),!!r,l]}}const Fb=(e,{windowsPathsNoEscape:t=!1}={})=>t?e.replace(/[?*()[\]]/g,"[$&]"):e.replace(/[?*()[\]\\]/g,"\\$&");var Js={};const yt=(e,t,r={})=>(rs(t),!r.nocomment&&t.charAt(0)==="#"?!1:new ls(t,r).match(e)),qb=/^\*+([^+@!?\*\[\(]*)$/,Lb=e=>t=>!t.startsWith(".")&&t.endsWith(e),Bb=e=>t=>t.endsWith(e),Ub=e=>(e=e.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(e)),Vb=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),Kb=/^\*+\.\*+$/,zb=e=>!e.startsWith(".")&&e.includes("."),Gb=e=>e!=="."&&e!==".."&&e.includes("."),Zb=/^\.\*+$/,Wb=e=>e!=="."&&e!==".."&&e.startsWith("."),Hb=/^\*+$/,Jb=e=>e.length!==0&&!e.startsWith("."),Qb=e=>e.length!==0&&e!=="."&&e!=="..",Yb=/^\?+([^+@!?\*\[\(]*)?$/,Xb=([e,t=""])=>{const r=Fd([e]);return t?(t=t.toLowerCase(),n=>r(n)&&n.toLowerCase().endsWith(t)):r},ew=([e,t=""])=>{const r=qd([e]);return t?(t=t.toLowerCase(),n=>r(n)&&n.toLowerCase().endsWith(t)):r},tw=([e,t=""])=>{const r=qd([e]);return t?n=>r(n)&&n.endsWith(t):r},rw=([e,t=""])=>{const r=Fd([e]);return t?n=>r(n)&&n.endsWith(t):r},Fd=([e])=>{const t=e.length;return r=>r.length===t&&!r.startsWith(".")},qd=([e])=>{const t=e.length;return r=>r.length===t&&r!=="."&&r!==".."},Ld=typeof process=="object"&&process?typeof Js=="object"&&Js&&Js.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",Rl
171={win32:{sep:"\\"},posix:{sep:"/"}},nw=Ld==="win32"?Rl.win32.sep:Rl.posix.sep;yt.sep=nw;const qt=Symbol("globstar **");yt.GLOBSTAR=qt;const aw="[^/]",sw=aw+"*?",ow="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",iw="(?:(?!(?:\\/|^)\\.).)*?",lw=(e,t={})=>r=>yt(r,e,t);yt.filter=lw;const Ft=(e,t={})=>Object.assign({},e,t),uw=e=>{if(!e||typeof e!="object"||!Object.keys(e).length)return yt;const t=yt;return Object.assign((n,s,o={})=>t(n,s,Ft(e,o)),{Minimatch:class extends t.Minimatch{constructor(s,o={}){super(s,Ft(e,o))}static defaults(s){return t.defaults(Ft(e,s)).Minimatch}},AST:class extends t.AST{constructor(s,o,l={}){super(s,o,Ft(e,l))}static fromGlob(s,o={}){return t.AST.fromGlob(s,Ft(e,o))}},unescape:(n,s={})=>t.unescape(n,Ft(e,s)),escape:(n,s={})=>t.escape(n,Ft(e,s)),filter:(n,s={})=>t.filter(n,Ft(e,s)),defaults:n=>t.defaults(Ft(e,n)),makeRe:(n,s={})=>t.makeRe(n,Ft(e,s)),braceExpand:(n,s={})=>t.braceExpand(n,Ft(e,s)),match:(n,s,o={})=>t.match(n,s,Ft(e,o)),sep:t.sep,GLOBSTAR:qt})};yt.defaults=uw;const Bd=(e,t={})=>(rs(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:kb(e));yt.braceExpand=Bd;const cw=(e,t={})=>new ls(e,t).makeRe();yt.makeRe=cw;const dw=(e,t,r={})=>{const n=new ls(t,r);return e=e.filter(s=>n.match(s)),n.options.nonull&&!e.length&&e.push(t),e};yt.match=dw;const Pl=/[?*]|[+@!]\(.*?\)|\[|\]/,pw=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");class ls{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(t,r={}){rs(t),r=r||{},this.options=r,this.pattern=t,this.platform=r.platform||Ld,this.isWindows=this.platform==="win32",this.windowsPathsNoEscape=!!r.windowsPathsNoEscape||r.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!r.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!r.nonegate,this.comment=!1,this.empty=!1,this.partial=!!r.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=r.windowsNoMagicRoot!==void 0?r.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(const t of this.set)for(const r of t)if(typeof r!="string")return!0;return!1}debug(...t){}make(){const t=this.pattern,r=this.options;if(!r.nocomment&&t.charAt(0)==="#"){this.comment=!0;return}if(!t){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],r.debug&&(this.debug=(...o)=>console.error(...o)),this.debug(this.pattern,this.globSet);const n=this.globSet.map(o=>this.slashSplit(o));this.globParts=this.preprocess(n),this.debug(this.pattern,this.globParts);let s=this.globParts.map((o,l,u)=>{if(this.isWindows&&this.windowsNoMagicRoot){const d=o[0]===""&&o[1]===""&&(o[2]==="?"||!Pl.test(o[2]))&&!Pl.test(o[3]),f=/^[a-z]:/i.test(o[0]);if(d)return[...o.slice(0,4),...o.slice(4).map(m=>this.parse(m))];if(f)return[o[0],...o.slice(1).map(m=>this.parse(m))]}return o.map(d=>this.parse(d))});if(this.debug(this.pattern,s),this.set=s.filter(o=>o.indexOf(!1)===-1),this.isWindows)for(let o=0;o<this.set.length;o++){const l=this.set[o];l[0]===""&&l[1]===""&&this.globParts[o][2]==="?"&&typeof l[3]=="string"&&/^[a-z]:$/i.test(l[3])&&(l[2]="?")}this.debug(this.pattern,this.set)}preprocess(t){if(this.options.noglobstar)for(let n=0;n<t.length;n++)for(let s=0;s<t[n].length;s++)t[n][s]==="**"&&(t[n][s]="*");const{optimizationLevel:r=1}=this.options;return r>=2?(t=this.firstPhasePreProcess(t),t=this.secondPhasePreProcess(t)):r>=1?t=this.levelOneOptimize(t):t=this.adjascentGlobstarOptimize(t),t}adjascentGlobstarOptimize(t){return t.map(r=>{let n=-1;for(;(n=r.indexOf("**",n+1))!==-1;){let s=n;for(;r[s+1]==="**";)s++;s!==n&&r.splice(n,s-n)}return r})}levelOneOptimize(t){return t.map(r=>(r=r.reduce((n,s)=>{const o=n[n.length-1];return s==="**"&&o==="**"?n:s===".."&&o&&o!==".."&&o!=="."&&o!=="**"?(n.pop(),n):(n.push(s),n)},[]),r.length===0?[""]:r))}levelTwoFileOptimize(t){Array.isArray(t)||(t=this.slashSplit(t));let r=!1;
171do{if(r=!1,!this.preserveMultipleSlashes){for(let s=1;s<t.length-1;s++){const o=t[s];s===1&&o===""&&t[0]===""||(o==="."||o==="")&&(r=!0,t.splice(s,1),s--)}t[0]==="."&&t.length===2&&(t[1]==="."||t[1]==="")&&(r=!0,t.pop())}let n=0;for(;(n=t.indexOf("..",n+1))!==-1;){const s=t[n-1];s&&s!=="."&&s!==".."&&s!=="**"&&(r=!0,t.splice(n-1,2),n-=2)}}while(r);return t.length===0?[""]:t}firstPhasePreProcess(t){let r=!1;do{r=!1;for(let n of t){let s=-1;for(;(s=n.indexOf("**",s+1))!==-1;){let l=s;for(;n[l+1]==="**";)l++;l>s&&n.splice(s+1,l-s);let u=n[s+1];const d=n[s+2],f=n[s+3];if(u!==".."||!d||d==="."||d===".."||!f||f==="."||f==="..")continue;r=!0,n.splice(s,1);const m=n.slice(0);m[s]="**",t.push(m),s--}if(!this.preserveMultipleSlashes){for(let l=1;l<n.length-1;l++){const u=n[l];l===1&&u===""&&n[0]===""||(u==="."||u==="")&&(r=!0,n.splice(l,1),l--)}n[0]==="."&&n.length===2&&(n[1]==="."||n[1]==="")&&(r=!0,n.pop())}let o=0;for(;(o=n.indexOf("..",o+1))!==-1;){const l=n[o-1];if(l&&l!=="."&&l!==".."&&l!=="**"){r=!0;const d=o===1&&n[o+1]==="**"?["."]:[];n.splice(o-1,2,...d),n.length===0&&n.push(""),o-=2}}}}while(r);return t}secondPhasePreProcess(t){for(let r=0;r<t.length-1;r++)for(let n=r+1;n<t.length;n++){const s=this.partsMatch(t[r],t[n],!this.preserveMultipleSlashes);if(s){t[r]=[],t[n]=s;break}}return t.filter(r=>r.length)}partsMatch(t,r,n=!1){let s=0,o=0,l=[],u="";for(;s<t.length&&o<r.length;)if(t[s]===r[o])l.push(u==="b"?r[o]:t[s]),s++,o++;else if(n&&t[s]==="**"&&r[o]===t[s+1])l.push(t[s]),s++;else if(n&&r[o]==="**"&&t[s]===r[o+1])l.push(r[o]),o++;else if(t[s]==="*"&&r[o]&&(this.options.dot||!r[o].startsWith("."))&&r[o]!=="**"){if(u==="b")return!1;u="a",l.push(t[s]),s++,o++}else if(r[o]==="*"&&t[s]&&(this.options.dot||!t[s].startsWith("."))&&t[s]!=="**"){if(u==="a")return!1;u="b",l.push(r[o]),s++,o++}else return!1;return t.length===r.length&&l}parseNegate(){if(this.nonegate)return;const t=this.pattern;let r=!1,n=0;for(let s=0;s<t.length&&t.charAt(s)==="!";s++)r=!r,n++;n&&(this.pattern=t.slice(n)),this.negate=r}matchOne(t,r,n=!1){const s=this.options;if(this.isWindows){const S=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),M=!S&&t[0]===""&&t[1]===""&&t[2]==="?"&&/^[a-z]:$/i.test(t[3]),R=typeof r[0]=="string"&&/^[a-z]:$/i.test(r[0]),B=!R&&r[0]===""&&r[1]===""&&r[2]==="?"&&typeof r[3]=="string"&&/^[a-z]:$/i.test(r[3]),V=M?3:S?0:void 0,E=B?3:R?0:void 0;if(typeof V=="number"&&typeof E=="number"){const[te,U]=[t[V],r[E]];te.toLowerCase()===U.toLowerCase()&&(r[E]=te,E>V?r=r.slice(E):V>E&&(t=t.slice(V)))}}const{optimizationLevel:o=1}=this.options;o>=2&&(t=this.levelTwoFileOptimize(t)),this.debug("matchOne",this,{file:t,pattern:r}),this.debug("matchOne",t.length,r.length);for(var l=0,u=0,d=t.length,f=r.length;l<d&&u<f;l++,u++){this.debug("matchOne loop");var m=r[u],b=t[l];if(this.debug(r,m,b),m===!1)return!1;if(m===qt){this.debug("GLOBSTAR",[r,m,b]);var v=l,y=u+1;if(y===f){for(this.debug("** at the end");l<d;l++)if(t[l]==="."||t[l]===".."||!s.dot&&t[l].charAt(0)===".")return!1;return!0}for(;v<d;){var x=t[v];if(this.debug(`
172globstar while`,t,v,r,y,x),this.matchOne(t.slice(v),r.slice(y),n))return this.debug("globstar found match!",v,d,x),!0;if(x==="."||x===".."||!s.dot&&x.charAt(0)==="."){this.debug("dot detected!",t,v,r,y);break}this.debug("globstar swallow a segment, and continue"),v++}return!!(n&&(this.debug(`
173>>> no match, partial?`,t,v,r,y),v===d))}let S;if(typeof m=="string"?(S=b===m,this.debug("string match",m,b,S)):(S=m.test(b),this.debug("pattern match",m,b,S)),!S)return!1}if(l===d&&u===f)return!0;if(l===d)return n;if(u===f)return l===d-1&&t[l]==="";throw new Error("wtf?")}braceExpand(){return Bd(this.pattern,this.options)}parse(t){rs(t);const r=this.options;if(t==="**")return qt;if(t==="")return"";let n,s=null;(n=t.match(Hb))?s=r.dot?Qb:Jb:(n=t.match(qb))?s=(r.nocase?r.dot?Vb:Ub:r.dot?Bb:Lb)(n[1]):(n=t.match(Yb))?s=(r.nocase?r.dot?ew:Xb:r.dot?tw:rw)(n):(n=t.match(Kb))?s=r.dot?Gb:zb:(n=t.match(Zb))&&(s=Wb);const o=kt.fromGlob(t,this.options).toMMPattern();return s&&typeof o=="object"&&Reflect.defineProperty(o,"test",{value:s}),o}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;const t=this.set;if(!t.length)return this.regexp=!1,this.regexp;const r=this.options,n=r.noglobstar?sw:r.dot?ow:iw,s=new Set(r.nocase?["i"]:[]);let o=t.map(d=>{const f=d.map(m=>{if(m instanceof RegExp)for(const b of m.flags.split(""))s.add(b);return typeof m=="string"?pw(m):m===qt?qt:m._src});return f.forEach((m,b)=>{const v=f[b+1],y=f[b-1];m!==qt||y===qt||(y===void 0?v!==void 0&&v!==qt?f[b+1]="(?:\\/|"+n+"\\/)?"+v:f[b]=n:v===void 0?f[b-1]=y+"(?:\\/|"+n+")?":v!==qt&&(f[b-1]=y+"(?:\\/|\\/"+n+"\\/)"+v,f[b+1]=qt))}),f.filter(m=>m!==qt).join("/")}).join("|");const[l,u]=t.length>1?["(?:",")"]:["",""];o="^"+l+o+u+"$",this.negate&&(o="^(?!"+o+").+$");try{this.regexp=new RegExp(o,[...s].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(t){return this.preserveMultipleSlashes?t.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(t)?["",...t.split(/\/+/)]:t.split(/\/+/)}match(t,r=this.partial){if(this.debug("match",t,this.pattern),this.comment)return!1;if(this.empty)return t==="";if(t==="/"&&r)return!0;const n=this.options;
173this.isWindows&&(t=t.split("\\").join("/"));const s=this.slashSplit(t);this.debug(this.pattern,"split",s);const o=this.set;this.debug(this.pattern,"set",o);let l=s[s.length-1];if(!l)for(let u=s.length-2;!l&&u>=0;u--)l=s[u];for(let u=0;u<o.length;u++){const d=o[u];let f=s;if(n.matchBase&&d.length===1&&(f=[l]),this.matchOne(f,d,r))return n.flipNegate?!0:!this.negate}return n.flipNegate?!1:this.negate}static defaults(t){return yt.defaults(t).Minimatch}}yt.AST=kt;yt.Minimatch=ls;yt.escape=Fb;yt.unescape=Gn;function Go(e){const t=ie(e.activeVersionNumber);if(!t)throw new Error("Unreachable! Invalid version number");return t}const fw=z({grepPattern:D().describe("The regular expression (regex) pattern to search for within file contents (e.g., 'function\\s+myFunction', 'import\\s+\\{.*\\}\\s+from\\s+.*')."),path:D().optional().describe("Optional: The absolute path to the directory to search within. If omitted, searches all the files."),globPattern:D().optional().describe("Optional: A glob pattern to filter which files are searched (e.g., '*.js', '*.{ts,tsx}', 'src/**'). If omitted, searches all files (respecting potential global ignores)."),max:we().optional().describe("Maximum number of results to return. If omitted, return all matches."),insensitive:Ve().optional().describe("If true, the pattern matching is case-insensitive. Defaults to true.").default(!0),lines:z({before:we().describe("Number of context lines to include before each matching line. Defaults to 0."),after:we().describe("Number of context lines to include after each matching line. Defaults to 0.")}).default({before:0,after:0}).describe("Number of context lines to include before and after each matching line.")}),hw=Ze(z({filePath:D().describe("The path of the file where the match was found."),lineNumber:we().describe("The line number in the file where the match occurred."),content:D().describe("The text of the line containing the match and required other lines.")}));function mw(e){const{useProjectFiles:t}=Wo(),{readFile:r}=Or(),n=t(e.activeVersionNumber),s={name:it.Grep,description:`
174Searches for regex or glob patterns within file contents across the project. Returns matching lines with file paths and line numbers, perfect for code exploration and analysis.
175
176Primary use cases:
177• Find function definitions: 'function\\s+myFunction' or 'const\\s+\\w+\\s*='
178• Locate imports/exports: 'import.*from' or 'export\\s+(default|\\{)'
179• Search for specific classes: 'class\\s+ComponentName' or 'interface\\s+\\w+'
180• Find API calls: 'fetch\\(' or 'api\\.(get|post)'
181• Discover configuration: 'process\\.env' or specific config keys
182• Track usage patterns: component names, variables, or method calls
183• Find specific text: 'User Admin' or 'TODO'
184
185Search strategies:
186• Use glob patterns to focus on relevant file types (*.ts, *.jsx, src/**)
187• Combine with path filtering for specific directories
188• Start broad, then narrow down with more specific patterns
189• Remember: case-insensitive matching`,inputSchema:fw,outputSchema:hw};async function o(u,d){const f=Go(e),{grepPattern:m,path:b,globPattern:v,max:y,insensitive:x,lines:S}=u,M=[],R=v?yt.filter(v):Bp(!0);d.throwIfAborted();for(const B of n.value||[]){if(d.throwIfAborted(),b&&!B.filename.startsWith(b)||!R(B.filename))continue;const V=await r(B.filename,f);if(!V)continue;const E=V.content;if(!E)continue;const te=new RegExp(m,x?"i":void 0),U=E.split(`
190`);for(let K=0;K<U.length;K++){const ce=U[K];if(te.test(ce)){const me=U.slice(Math.max(0,K-S.before),K),de=U.slice(K+1,K+1+S.after);M.push({filePath:B.filename,lineNumber:K+1,content:[...me,ce,...de].join(`
191`)})}if(y&&M.length>=y)break}}return M}return{name:it.Grep,tool:s,onToolCall:o}}const gw=z({filePath:D().optional().describe("The page file to render and inspect. Defaults to the currently active file if omitted."),selectors:Ze(D()).optional().describe("Optional CSS selectors to verify. For each one, reports whether it renders, its bounding rect and inner text — use to confirm your edit actually took effect.")}),vw=z({x:we(),y:we(),width:we(),height:we()}),yw=z({rendered:Ve().describe("Whether the page rendered a non-empty body without a fatal error."),errors:Ze(D()).describe("Runtime / console / resource-load errors captured while rendering."),elements:Ze(z({selector:D(),found:Ve(),rect:vw.optional(),text:D().optional()})).describe("Result for each requested selector.")}),bw=Rr("tools:inspect-page"),ww=1e4,Ud=50,Vd=200,Qs=`<script>(function(){
192  window.__inspectErrors = [];
193  function push(msg){ try { if (window.__inspectErrors.length < ${Ud}) window.__inspectErrors.push(String(msg).slice(0, ${Vd})); } catch(_){} }
194  window.addEventListener('error', function(e){
195    if (e && e.target && e.target !== window && (e.target.src || e.target.href)) {
196      push('Resource failed to load: ' + (e.target.src || e.target.href));
197    } else {
198      push('Error: ' + (e && e.message ? e.message : e));
199    }
200  }, true);
201  window.addEventListener('unhandledrejection', function(e){
202    push('Unhandled rejection: ' + (e && e.reason ? (e.reason.message || e.reason) : 'unknown'));
203  });
204  var _err = console.error;
205  console.error = function(){ push('console.error: ' + Array.prototype.join.call(arguments, ' ')); return _err.apply(console, arguments); };
206})();<\/script>`;function _w(e){return/<head[^>]*>/i.test(e)?e.replace(/<head[^>]*>/i,t=>t+Qs):/<html[^>]*>/i.test(e)?e.replace(/<html[^>]*>/i,t=>`${t}<head>${Qs}</head>`):Qs+e}function xw(e){const{readFile:t}=Or(),r={name:it.InspectPage,description:"Render the current page in an offscreen frame and report runtime/console errors and whether it rendered. Optionally verify that specific CSS 
206selectors render (with their rect and text). ALWAYS call this after finishing your edits to catch broken code, then fix any reported errors before ending.",inputSchema:gw,outputSchema:yw};async function n(o,l){l.throwIfAborted();const u=o.filePath??ie(e.activeFilename);if(!u)throw new Bt("no target file: both filePath and the active file are empty");const d=ie(e.activeVersionNumber);if(!d)throw new Bt("Unreachable! Invalid version number");const f=await t(u,d);if(!f)throw new Bt(`file not found: ${u}`);bw("inspect page %s (version %s)",u,d);const m=document.createElement("iframe");m.style.visibility="hidden",m.style.position="fixed",m.style.top="-100000px",m.style.left="-100000px",m.width="1280",m.height="800",m.sandbox.add("allow-same-origin","allow-scripts"),m.srcdoc=_w(f.content||"");try{document.body.appendChild(m),await new Promise(M=>{m.onload=()=>M(),m.onerror=()=>M(),setTimeout(M,ww)}),l.throwIfAborted();const b=m.contentWindow,v=m.contentDocument,y=Array.isArray(b?.__inspectErrors)?b.__inspectErrors.slice(0,Ud):[],x=!!v?.body&&v.body.childElementCount>0,S=(o.selectors??[]).map(M=>{let R=null;try{R=v?.querySelector(M)??null}catch{return{selector:M,found:!1}}if(!R)return{selector:M,found:!1};const B=R.getBoundingClientRect();return{selector:M,found:!0,rect:{x:B.x,y:B.y,width:B.width,height:B.height},text:(R.innerText||R.textContent||"").trim().slice(0,Vd)}});return{rendered:x,errors:y,elements:S}}finally{m.remove()}}return{name:it.InspectPage,tool:r,onToolCall:n}}const kw=z({}),Sw=z({filePath:D(),title:D().optional()}),Iw=z({files:Ze(Sw).describe("File list of existing files")});function Tw(e){const{listFiles:t}=Or(),r={name:it.ListFiles,description:"",inputSchema:kw,outputSchema:Iw};async function n(o,l){const u=Go(e);return l.throwIfAborted(),{files:(await t(u)).map(f=>({filePath:f.filename,title:f.displayName}))}}return{name:it.ListFiles,tool:r,onToolCall:n}}const Ew=z({filePath:D().describe("The path of the file to read."),lines:z({start:we().optional().describe("The starting line number to read (1-based index). If omitted, starts from the beginning of the file."),end:we().optional().describe("The ending line number to read (inclusive). If omitted, reads to the end of the file.")}).optional().describe("Optional line range to read from the file. If not provided, the entire file will be read.")}),Aw=z({content:D().describe("The content of the file or the specified line range.")}),Cw=Rr("tools:read-file");function Rw(e){const{readFile:t}=Or(),r={name:it.ReadFile,description:"Read the content of a file in the project. Use this tool when you need to access the contents of an existing file.",inputSchema:Ew,outputSchema:Aw};async function n(o,l){const u=Go(e),{filePath:d,lines:f}=o;Cw("read file %o",o),l.throwIfAborted();const m=await t(d,u);if(!m)throw new Bt("file not found");if(f){const b=m.content.split(`
207`),v=Math.max(f.start??1,1)-1,y=Math.min(f.end??b.length,b.length)-1;return{content:b.slice(v,y+1).join(`
208`)}}return{content:m.content}}return{name:it.ReadFile,tool:r,onToolCall:n}}class mn extends Error{constructor(t,r){super(`${t} at position ${r}`),this.position=r}}const Kd=32,Pw=10,zd=9,Gd=13,Ow=160,Mw=8192,Nw=8202,jw=8239,$w=8287,Dw=12288;function Fw(e){return/^[0-9A-Fa-f]$/.test(e)}function zr(e){return e>="0"&&e<="9"}function qw(e){return e>=" "}function Fa(e){return`,:[]/{}()
209+`.includes(e)}function Ol(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_"||e==="$"}function Ml(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_"||e==="$"||e>="0"&&e<="9"}const Nl=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,jl=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function $l(e){return`,[]/{}
210+`.includes(e)}function Dl(e){return Ua(e)||Lw.test(e)}const Lw=/^[[{\w-]$/;function Bw(e){return e===`
211`||e==="\r"||e==="	"||e==="\b"||e==="\f"}function Zr(e,t){const r=e.charCodeAt(t);return r===Kd||r===Pw||r===zd||r===Gd}function Uw(e,t){const r=e.charCodeAt(t);return r===Kd||r===zd||r===Gd}function Vw(e,t){const r=e.charCodeAt(t);return r===Ow||r>=Mw&&r<=Nw||r===jw||r===$w||r===Dw}function Ua(e){return Zd(e)||vo(e)}function Zd(e){return e==='"'||e==="“"||e==="”"}function Fl(e){return e==='"'}function vo(e){return e==="'"||e==="‘"||e==="’"||e==="`"||e==="´"}function ql(e){return e==="'"}function Vn(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;const n=e.lastIndexOf(t);return n!==-1?e.substring(0,n)+(r?"":e.substring(n+1)):e}function zt(e,t){let r=e.length;if(!Zr(e,r-1))return e+t;for(;Zr(e,r-1);)r--;return e.substring(0,r)+t+e.substring(r)}function Kw(e,t,r){return e.substring(0,t)+e.substring(t+r)}function zw(e){return/[,\n][ \t\r]*$/.test(e)}const Gw={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","	":"\\t"},Zw={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
212`,r:"\r",t:"	"};function Ww(e){let t=0,r="";f(["```","[```","{```"]),o()||Ce(),f(["```","```]","```}"]);const s=b(",");
212for(s&&l(),Dl(e[t])&&zw(r)?(s||(r=zt(r,",")),R()):s&&(r=Vn(r,","));e[t]==="}"||e[t]==="]";)t++,l();if(t>=e.length)return r;ke();function o(){l();const H=S()||M()||B()||E()||te()||K(!1)||ce();return l(),H}function l(){let H=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;const pe=t;let ne=u(H);do ne=d(),ne&&(ne=u(H));while(ne);return t>pe}function u(H){const pe=H?Zr:Uw;let ne="";for(;;)if(pe(e,t))ne+=e[t],t++;else if(Vw(e,t))ne+=" ",t++;else break;return ne.length>0?(r+=ne,!0):!1}function d(){if(e[t]==="/"&&e[t+1]==="*"){for(;t<e.length&&!Hw(e,t);)t++;return t+=2,!0}if(e[t]==="/"&&e[t+1]==="/"){for(;t<e.length&&e[t]!==`
213`;)t++;return!0}return!1}function f(H){if(m(H)){if(Ol(e[t]))for(;t<e.length&&Ml(e[t]);)t++;return l(),!0}return!1}function m(H){u(!0);for(const pe of H){const ne=t+pe.length;if(e.slice(t,ne)===pe)return t=ne,!0}return!1}function b(H){return e[t]===H?(r+=e[t],t++,!0):!1}function v(H){return e[t]===H?(t++,!0):!1}function y(){return v("\\")}function x(){return l(),e[t]==="."&&e[t+1]==="."&&e[t+2]==="."?(t+=3,l(),v(","),!0):!1}function S(){if(e[t]==="{"){r+="{",t++,l(),v(",")&&l();let H=!0;for(;t<e.length&&e[t]!=="}";){let pe;if(H?(pe=!0,H=!1):(pe=b(","),pe||(r=zt(r,",")),l()),x(),!(B()||K(!0))){e[t]==="}"||e[t]==="{"||e[t]==="]"||e[t]==="["||e[t]===void 0?r=Vn(r,","):pt();break}l();const je=b(":"),qe=t>=e.length;je||(Dl(e[t])||qe?r=zt(r,":"):lt()),o()||(je||qe?r+="null":lt())}return e[t]==="}"?(r+="}",t++):r=zt(r,"}"),!0}return!1}function M(){if(e[t]==="["){r+="[",t++,l(),v(",")&&l();let H=!0;for(;t<e.length&&e[t]!=="]";)if(H?H=!1:b(",")||(r=zt(r,",")),x(),!o()){r=Vn(r,",");break}return e[t]==="]"?(r+="]",t++):r=zt(r,"]"),!0}return!1}function R(){let H=!0,pe=!0;for(;pe;)H?H=!1:b(",")||(r=zt(r,",")),pe=o();pe||(r=Vn(r,",")),r=`[
214${r}
215]`}function B(){let H=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,pe=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,ne=e[t]==="\\";if(ne&&(t++,ne=!0),Ua(e[t])){const je=Fl(e[t])?Fl:ql(e[t])?ql:vo(e[t])?vo:Zd,qe=t,et=r.length;let Le='"';for(t++;;){if(t>=e.length){const Y=me(t-1);return!H&&Fa(e.charAt(Y))?(t=qe,r=r.substring(0,et),B(!0)):(Le=zt(Le,'"'),r+=Le,!0)}if(t===pe)return Le=zt(Le,'"'),r+=Le,!0;if(je(e[t])){const Y=t,le=Le.length;if(Le+='"',t++,r+=Le,l(!1),H||t>=e.length||Fa(e[t])||Ua(e[t])||zr(e[t]))return V(),!0;const Ie=me(Y-1),$e=e.charAt(Ie);if($e===",")return t=qe,r=r.substring(0,et),B(!1,Ie);if(Fa($e))return t=qe,r=r.substring(0,et),B(!0);r=r.substring(0,et),t=Y+1,Le=`${Le.substring(0,le)}\\${Le.substring(le)}`}else if(H&&$l(e[t])){if(e[t-1]===":"&&Nl.test(e.substring(qe+1,t+2)))for(;t<e.length&&jl.test(e[t]);)Le+=e[t],t++;return Le=zt(Le,'"'),r+=Le,V(),!0}else if(e[t]==="\\"){const Y=e.charAt(t+1);if(Zw[Y]!==void 0)Le+=e.slice(t,t+2),t+=2;else if(Y==="u"){let Ie=2;for(;Ie<6&&Fw(e[t+Ie]);)Ie++;Ie===6?(Le+=e.slice(t,t+6),t+=6):t+Ie>=e.length?t=e.length:Ct()}else Le+=Y,t+=2}else{const Y=e.charAt(t);Y==='"'&&e[t-1]!=="\\"?(Le+=`\\${Y}`,t++):Bw(Y)?(Le+=Gw[Y],t++):(qw(Y)||ve(Y),Le+=Y,t++)}ne&&y()}}return!1}function V(){let H=!1;for(l();e[t]==="+";){H=!0,t++,l(),r=Vn(r,'"',!0);const pe=r.length;B()?r=Kw(r,pe,1):r=zt(r,'"')}return H}function E(){const H=t;if(e[t]==="-"){if(t++,de())return he(H),!0;if(!zr(e[t]))return t=H,!1}for(;zr(e[t]);)t++;if(e[t]==="."){if(t++,de())return he(H),!0;if(!zr(e[t]))return t=H,!1;for(;zr(e[t]);)t++}if(e[t]==="e"||e[t]==="E"){if(t++,(e[t]==="-"||e[t]==="+")&&t++,de())return he(H),!0;if(!zr(e[t]))return t=H,!1;for(;zr(e[t]);)t++}if(!de())return t=H,!1;if(t>H){const pe=e.slice(H,t),ne=/^0\d/.test(pe);return r+=ne?`"${pe}"`:pe,!0}return!1}function te(){return U("true","true")||U("false","false")||U("null","null")||U("True","true")||U("False","false")||U("None","null")}function U(H,pe){return e.slice(t,t+H.length)===H?(r+=pe,t+=H.length,!0):!1}function K(H){const pe=t;if(Ol(e[t])){for(;t<e.length&&Ml(e[t]);)t++;let ne=t;for(;Zr(e,ne);)ne++;if(e[ne]==="(")return t=ne+1,o(),e[t]===")"&&(t++,e[t]===";"&&t++),!0}for(;t<e.length&&!$l(e[t])&&!Ua(e[t])&&(!H||e[t]!==":");)t++;if(e[t-1]===":"&&Nl.test(e.substring(pe,t+2)))for(;t<e.length&&jl.test(e[t]);)t++;if(t>pe){for(;Zr(e,t-1)&&t>0;)t--;const ne=e.slice(pe,t);return r+=ne==="undefined"?"null":JSON.stringify(ne),e[t]==='"'&&t++,!0}}
215function ce(){if(e[t]==="/"){const H=t;for(t++;t<e.length&&(e[t]!=="/"||e[t-1]==="\\");)t++;return t++,r+=`"${e.substring(H,t)}"`,!0}}function me(H){let pe=H;for(;pe>0&&Zr(e,pe);)pe--;return pe}function de(){return t>=e.length||Fa(e[t])||Zr(e,t)}function he(H){r+=`${e.slice(H,t)}0`}function ve(H){throw new mn(`Invalid character ${JSON.stringify(H)}`,t)}function ke(){throw new mn(`Unexpected character ${JSON.stringify(e[t])}`,t)}function Ce(){throw new mn("Unexpected end of json string",e.length)}function pt(){throw new mn("Object key expected",t)}function lt(){throw new mn("Colon expected",t)}function Ct(){const H=e.slice(t,t+6);throw new mn(`Invalid unicode character "${H}"`,t)}}function Hw(e,t){return e[t]==="*"&&e[t+1]==="/"}function yo(e){const t=Ww(e);try{return JSON.parse(t)}catch{return e}}const Jw=z({filePath:D().describe("The full path of the file to update."),replaceBlocks:Up(e=>typeof e=="string"?yo(e):e,Ze(z({old:D().describe("The existing content block to be replaced."),new:D().describe("The new content to replace the existing block."),global:Ve().default(!1).describe("Whether to replace all occurrences of the old content block. Default is false (replace first occurrence only).")})).describe("An array of blocks to replace, each with the old content and the new content."))}),Qw=z({success:we().describe("Succeeded operations count")}),Xt=Rr("tools:replace-file-content");function Yw(e){const{switchPreviewFile:t}=e,{readFile:r,writeFile:n}=Or(),s={name:it.ReplaceFileContent,description:"Replace specific content blocks in an existing file within the project. Use this tool when you need to modify certain parts of a file's content based on matching text. Recommended for use when modifications do not involve multi-line text.",inputSchema:Jw,outputSc
215hema:Qw};async function o(u,d){const f=ie(e.activeVersionNumber);if(!f)throw new Error("Unreachable! Invalid version number");d.throwIfAborted();const m=await r(u.filePath,f);if(!m)throw new Bt("file not found");let b=0,v=m.content||"";for(const y of u.replaceBlocks){d.throwIfAborted(),Xt.enabled&&(Xt("old",y.old),Xt("found",v.indexOf(y.old)));const x=v;v=y.global?v.replaceAll(y.old.replaceAll("\\n",`
216`),y.new.replaceAll("\\n",`
217`)):v.replace(y.old.replaceAll("\\n",`
218`),y.new.replaceAll("\\n",`
219`)),x!==v&&b++,Xt.enabled&&(Xt("new",y.new),Xt("result",v.indexOf(y.new)))}if(Xt("write file filename: %s, version: %s",u.filePath,f,v),d.throwIfAborted(),await n({filename:u.filePath,content:v,source:ds.Agent}),Xt.enabled){const{diffLines:y}=await vn(async()=>{const{diffLines:M}=await import("./Cw_ls5F0.js");return{diffLines:M}},[],import.meta.url),x=y(m.content,v);Xt("diff",x);const S=await r(u.filePath,f);Xt("eq %s",v===S?.content)}return t(u.filePath),{success:b}}return{name:it.ReplaceFileContent,tool:s,onToolCall:o}}const Xw=z({width:we().min(280).max(1920).describe("The viewport width in pixels. Must be between 280 and 1920. Common mobile widths: 375 (iPhone), 390 (iPhone 14), 414 (iPhone Plus). Common tablet widths: 768 (iPad), 1024 (iPad Pro). Common desktop widths: 1280, 1440, 1920.")}),e0=z({success:Ve().describe("Whether the viewport width was successfully set."),width:we().describe("The viewport width that was set.")}),t0=Rr("tools:set-viewport-width");function r0(e){const t={name:it.SetViewportWidth,description:"Set the preview viewport width. Use this tool when you detect the current page is a mobile page or when you need to preview the design at a specific viewport width. This adjusts the preview area to simulate different device widths.",inputSchema:Xw,outputSchema:e0};async function r(s,o){const{width:l}=s;if(t0("set viewport width %o",s),o.throwIfAborted(),l<280||l>1920)throw new Bt(`Invalid viewport width: ${l}. Must be between 280 and 1920 pixels.`);try{return e.setViewportWidth&&await e.setViewportWidth(l),{success:!0,width:l}}catch(u){throw new Bt(`Failed to set viewport width: ${u.message}`)}}return{name:it.SetViewportWidth,tool:t,onToolCall:r}}const n0=z({filePath:D().optional().describe("The page file to screenshot and review. Defaults to the currently active file if omitted."),expectation:D().min(1).describe("What this edit was supposed to achieve, in your own words (the user's request restated). The vision model judges the screenshot against this.")}),a0=z({meets:Ve().describe("Whether the rendered page meets the expectation."),reason:D().describe("Concise explanation, pointing out concrete mismatches when it does not."),suggestions:D().optional().describe("Concrete fix suggestions when meets=false.")}),s0=Rr("tools:visual-check");function o0(e){const{readFile:t}=Or(),{uploadFile:r}=ru([]),n=At(),s={name:it.VisualCheck,description:"Screenshot the current page and have a vision model judge whether the rendered result matches the user's request. Call this after edits pass inspectPage. If it returns meets=false, fix the page per reason/suggestions and re-run until it passes or you have done your best.",inputSchema:n0,outputSchema:a0};async function o(u,d){d.throwIfAborted();const f=u.filePath??ie(e.activeFilename);if(!f)throw new Bt("no target file: both filePath and the active file are empty");const m=ie(e.activeVersionNumber);if(!m)throw new Bt("Unreachable! Invalid version number");const b=await t(f,m);if(!b)throw new Bt(`file not found: ${f}`);s0("visual check %s (version %s)",f,m);const{takeScreenshot:v}=await vn(async()=>{const{takeScreenshot:R}=await import("./D6B7PRGu.js");return{takeScreenshot:R}},__vite__mapDeps([0,1,2]),import.meta.url),y=await v(b.content||"");if(!y)throw new Bt("failed to render screenshot for visual check");d.throwIfAborted();const{key:x}=await r(Xs.ReforeVisualCheck,{type:Jl.Other,body:y,contentType:"image/png",filename:"visual-check.png"}),S=ns(x);d.throwIfAborted();const M=await n("/api/refore/visual-check",{method:"POST",body:{imageUrl:S,expectation:u.expectation},signal:d});return{meets:!!M.meets,reason:M.reason??"",suggestions:M.suggestions}}return{name:it.VisualCheck,tool:s,onToolCall:o}}const i0=Rr("tools:stub");function l0(e){const t=mw(e),r=sb(e),n=Rw(e),s=Yw(e),o=Tw(e),l=ub(e),u=r0(e),d=xw(e);o0(e);const f=Ne(()=>[t,r,n,s,l,o,u,d]),m=Ne(()=>Vp(f.value,v=>v.name,v=>v.tool));async function b(){}return{tools:m,onFinish:b,onToolCall:async(v,y)=>{i0("call %s",v.toolName,v);const{toolName:x}=v,S=f.value.find(R=>R.name===x);if(!S)throw new Error(`Unknown tool: ${x}`);let M=v.input;if(S.tool.inputSchema instanceof Kp){const R=S.tool.inputSchema.safeParse(v.input);if(!R.success)throw new Error(`Invalid input for tool ${x}: ${R.error.message}`);M=R.data}return S.onToolCall(M,y)}}}function Kn(e){var t,r;return(r=(t=e?.providerOptions)==null?void 0:t.openaiCompatible)!=null?r:{}}function u0(e){const t=[];for(const{role:r,content:n,...s}of e){const o=Kn({...s});switch(r){case"system":{t.push({role:"system",content:n,...o});break}case"user":{if(n.length===1&&n[0].type==="text"){t.push({role:"user",content:n[0].text,...Kn(n[0])});break}t.push({role:"user",content:n.map(l=>{const u=Kn(l);switch(l.type){case"text":return{type:"text",text:l.text,...u};case"file":if(l.mediaType.startsWith("image/")){const d=l.mediaType==="image/*"?"image/jpeg":l.mediaType;return{type:"image_url",image_url:{url:l.data instanceof URL?l.data.toString():`data:${d};base64,${Kh(l.data)}`},...u}}else throw new za({functionality:`file part media type ${l.mediaType}`})}}),...o});break}case"assistant":{let l="";const u=[];for(const d of n){const f=Kn(d);switch(d.type){case"text":{l+=d.text;break}case"tool-call":{u.push({id:d.toolCallId,type:"function",function:{name:d.toolName,arguments:JSON.stringify(d.input)},...f});break}}}t.push({role:"assistant",content:l,tool_calls:u.length>0?u:void 0,...o});break}case"tool":{for(const l of n){const u=l.output;let d;switch(u.type){case"text":case"error-text":d=u.value;break;case"content":case"json":case"error-json":d=JSON.stringify(u.value);break}const f=Kn(l);t.push({role:"tool",tool_call_id:l.toolCallId,content:d,...f})}break}
219default:{const l=r;throw new Error(`Unsupported role: ${l}`)}}}return t}function Ll({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function Bl(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var Ys=z({user:D().optional(),reasoningEffort:D().optional(),textVerbosity:D().optional()}),c0=z({error:z({message:D(),type:D().nullish(),param:ur().nullish(),code:Xe([D(),we()]).nullish()})}),us={errorSchema:c0,errorToMessage:e=>e.error.message};function d0({tools:e,toolChoice:t}){e=e?.length?e:void 0;const r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const n=[];for(const o of e)o.type==="provider-defined"?r.push({type:"unsupported-tool",tool:o}):n.push({type:"function",function:{name:o.name,description:o.description,parameters:o.inputSchema}});if(t==null)return{tools:n,toolChoice:void 0,toolWarnings:r};const s=t.type;switch(s){case"auto":case"none":case"required":return{tools:n,toolChoice:s,toolWarnings:r};case"tool":return{tools:n,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:r};default:{const o=s;throw new za({functionality:`tool choice type: ${o}`})}}}var Wd=class{constructor(e,t){this.specificationVersion="v2";var r,n;this.modelId=e,this.config=t;const s=(r=t.errorStructure)!=null?r:us;this.chunkSchema=f0(s.errorSchema),this.failedResponseHandler=mr(s),this.supportsStructuredOutputs=(n=t.supportsStructuredOutputs)!=null?n:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var e,t,r;return(r=(t=(e=this.config).supportedUrls)==null?void 0:t.call(e))!=null?r:{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:r,topP:n,topK:s,frequencyPenalty:o,presencePenalty:l,providerOptions:u,stopSequences:d,responseFormat:f,seed:m,toolChoice:b,tools:v}){var y,x,S,M;const R=[],B=Object.assign((y=await ta({provider:"openai-compatible",providerOptions:u,schema:Ys}))!=null?y:{},(x=await ta({provider:this.providerOptionsName,providerOptions:u,schema:Ys}))!=null?x:{});s!=null&&R.push({type:"unsupported-setting",setting:"topK"}),f?.type==="json"&&f.schema!=null&&!this.supportsStructuredOutputs&&R.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:V,toolChoice:E,toolWarnings:te}=d0({tools:v,toolChoice:b});return{args:{model:this.modelId,user:B.user,max_tokens:t,temperature:r,top_p:n,frequency_penalty:o,presence_penalty:l,response_format:f?.type==="json"?this.supportsStructuredOutputs===!0&&f.schema!=null?{type:"json_schema",json_schema:{schema:f.schema,name:(S=f.name)!=null?S:"response",description:f.description}}:{type:"json_object"}:void 0,stop:d,seed:m,...Object.fromEntries(Object.entries((M=u?.[this.providerOptionsName])!=null?M:{}).filter(([U])=>!Object.keys(Ys.shape).includes(U))),reasoning_effort:B.reasoningEffort,verbosity:B.textVerbosity,messages:u0(e),tools:V,tool_choice:E},warnings:[...R,...te]}}async doGenerate(e){var t,r,n,s,o,l,u,d,f,m,b,v,y,x,S,M,R;const{args:B,warnings:V}=await this.getArgs({...e}),E=JSON.stringify(B),{responseHeaders:te,value:U,rawValue:K}=await hr({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:pr(this.config.headers(),e.headers),body:B,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Cr(p0),abortSignal:e.abortSignal,fetch:this.config.fetch}),ce=U.choices[0],me=[],de=ce.message.content;de!=null&&de.length>0&&me.push({type:"text",text:de});const he=(t=ce.message.reasoning_content)!=null?t:ce.message.reasoning;if(he!=null&&he.length>0&&me.push({type:"reasoning",text:he}),ce.message.tool_calls!=null)for(const Ce of ce.message.tool_calls)me.push({type:"tool-call",toolCallId:(r=Ce.id)!=null?r:yn(),toolName:Ce.function.name,input:Ce.function.arguments});const ve={[this.providerOptionsName]:{},...await((s=(n=this.config.metadataExtractor)==null?void 0:n.extractMetadata)==null?void 0:s.call(n,{parsedBody:K}))},ke=(o=U.usage)==null?void 0:o.completion_tokens_details;return ke?.accepted_prediction_tokens!=null&&(ve[this.providerOptionsName].acceptedPredictionTokens=ke?.accepted_prediction_tokens),ke?.rejected_prediction_tokens!=null&&(ve[this.providerOptionsName].rejectedPredictionTokens=ke?.rejected_prediction_tokens),{content:me,finishReason:Bl(ce.finish_reason),usage:{inputTokens:(u=(l=U.usage)==null?void 0:l.prompt_tokens)!=null?u:void 0,outputTokens:(f=(d=U.usage)==null?void 0:d.completion_tokens)!=null?f:void 0,totalTokens:(b=(m=U.usage)==null?void 0:m.total_tokens)!=null?b:void 0,reasoningTokens:(x=(y=(v=U.usage)==null?void 0:v.completion_tokens_details)==null?void 0:y.reasoning_tokens)!=null?x:void 0,cachedInputTokens:(R=(M=(S=U.usage)==null?void 0:S.prompt_tokens_details)==null?void 0:M.cached_tokens)!=null?R:void 0},providerMetadata:ve,request:{body:E},response:{...Ll(U),headers:te,body:K},warnings:V}}async doStream(e){var t;const{args:r,warnings:n}=await this.getArgs({...e}),s={...r,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},o=(t=this.config.metadataExtractor)==null?void 0:t.createStreamExtractor(),{responseHeaders:l,value:u}=await hr({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:pr(this.config.headers(),e.headers),body:s,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Io(this.chunkSchema),abortSignal:e.abortSignal,fetch:this.config.fetch}),d=[];let f="unknown";
219const m={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0};let b=!0;const v=this.providerOptionsName;let y=!1,x=!1;return{stream:u.pipeThrough(new TransformStream({start(S){S.enqueue({type:"stream-start",warnings:n})},transform(S,M){var R,B,V,E,te,U,K,ce,me,de,he,ve,ke;if(e.includeRawChunks&&M.enqueue({type:"raw",rawValue:S.rawValue}),!S.success){f="error",M.enqueue({type:"error",error:S.error});return}const Ce=S.value;if(o?.processChunk(S.rawValue),"error"in Ce){f="error",M.enqueue({type:"error",error:Ce.error.message});return}if(b&&(b=!1,M.enqueue({type:"response-metadata",...Ll(Ce)})),Ce.usage!=null){const{prompt_tokens:H,completion_tokens:pe,total_tokens:ne,prompt_tokens_details:je,completion_tokens_details:qe}=Ce.usage;m.promptTokens=H??void 0,m.completionTokens=pe??void 0,m.totalTokens=ne??void 0,qe?.reasoning_tokens!=null&&(m.completionTokensDetail
219s.reasoningTokens=qe?.reasoning_tokens),qe?.accepted_prediction_tokens!=null&&(m.completionTokensDetails.acceptedPredictionTokens=qe?.accepted_prediction_tokens),qe?.rejected_prediction_tokens!=null&&(m.completionTokensDetails.rejectedPredictionTokens=qe?.rejected_prediction_tokens),je?.cached_tokens!=null&&(m.promptTokensDetails.cachedTokens=je?.cached_tokens)}const pt=Ce.choices[0];if(pt?.finish_reason!=null&&(f=Bl(pt.finish_reason)),pt?.delta==null)return;const lt=pt.delta,Ct=(R=lt.reasoning_content)!=null?R:lt.reasoning;if(Ct&&(y||(M.enqueue({type:"reasoning-start",id:"reasoning-0"}),y=!0),M.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:Ct})),lt.content&&(x||(M.enqueue({type:"text-start",id:"txt-0"}),x=!0),M.enqueue({type:"text-delta",id:"txt-0",delta:lt.content})),lt.tool_calls!=null)for(const H of lt.tool_calls){const pe=H.index;if(d[pe]==null){if(H.id==null)throw new Ri({data:H,message:"Expected 'id' to be a string."});if(((B=H.function)==null?void 0:B.name)==null)throw new Ri({data:H,message:"Expected 'function.name' to be a string."});M.enqueue({type:"tool-input-start",id:H.id,toolName:H.function.name}),d[pe]={id:H.id,type:"function",function:{name:H.function.name,arguments:(V=H.function.arguments)!=null?V:""},hasFinished:!1};const je=d[pe];((E=je.function)==null?void 0:E.name)!=null&&((te=je.function)==null?void 0:te.arguments)!=null&&(je.function.arguments.length>0&&M.enqueue({type:"tool-input-delta",id:je.id,delta:je.function.arguments}),Ni(je.function.arguments)&&(M.enqueue({type:"tool-input-end",id:je.id}),M.enqueue({type:"tool-call",toolCallId:(U=je.id)!=null?U:yn(),toolName:je.function.name,input:je.function.arguments}),je.hasFinished=!0));continue}const ne=d[pe];ne.hasFinished||(((K=H.function)==null?void 0:K.arguments)!=null&&(ne.function.arguments+=(me=(ce=H.function)==null?void 0:ce.arguments)!=null?me:""),M.enqueue({type:"tool-input-delta",id:ne.id,delta:(de=H.function.arguments)!=null?de:""}),((he=ne.function)==null?void 0:he.name)!=null&&((ve=ne.function)==null?void 0:ve.arguments)!=null&&Ni(ne.function.arguments)&&(M.enqueue({type:"tool-input-end",id:ne.id}),M.enqueue({type:"tool-call",toolCallId:(ke=ne.id)!=null?ke:yn(),toolName:ne.function.name,input:ne.function.arguments}),ne.hasFinished=!0))}},flush(S){var M,R,B,V,E,te;y&&S.enqueue({type:"reasoning-end",id:"reasoning-0"}),x&&S.enqueue({type:"text-end",id:"txt-0"});for(const K of d.filter(ce=>!ce.hasFinished))S.enqueue({type:"tool-input-end",id:K.id}),S.enqueue({type:"tool-call",toolCallId:(M=K.id)!=null?M:yn(),toolName:K.function.name,input:K.function.arguments});const U={[v]:{},...o?.buildMetadata()};
219m.completionTokensDetails.acceptedPredictionTokens!=null&&(U[v].acceptedPredictionTokens=m.completionTokensDetails.acceptedPredictionTokens),m.completionTokensDetails.rejectedPredictionTokens!=null&&(U[v].rejectedPredictionTokens=m.completionTokensDetails.rejectedPredictionTokens),S.enqueue({type:"finish",finishReason:f,usage:{inputTokens:(R=m.promptTokens)!=null?R:void 0,outputTokens:(B=m.completionTokens)!=null?B:void 0,totalTokens:(V=m.totalTokens)!=null?V:void 0,reasoningTokens:(E=m.completionTokensDetails.reasoningTokens)!=null?E:void 0,cachedInputTokens:(te=m.promptTokensDetails.cachedTokens)!=null?te:void 0},providerMetadata:U})}})),request:{body:s},response:{headers:l}}}},Hd=z({prompt_tokens:we().nullish(),completion_tokens:we().nullish(),total_tokens:we().nullish(),prompt_tokens_details:z({cached_tokens:we().nullish()}).nullish(),completion_tokens_details:z({reasoning_tokens:we().nullish(),accepted_prediction_tokens:we().nullish(),rejected_prediction_tokens:we().nullish()}).nullish()}).nullish(),p0=z({id:D().nullish(),created:we().nullish(),model:D().nullish(),choices:Ze(z({message:z({role:ge("assistant").nullish(),content:D().nullish(),reasoning_content:D().nullish(),reasoning:D().nullish(),tool_calls:Ze(z({id:D().nullish(),function:z({name:D(),arguments:D()})})).nullish()}),finish_reason:D().nullish()})),usage:Hd}),f0=e=>Xe([z({id:D().nullish(),created:we().nullish(),model:D().nullish(),choices:Ze(z({delta:z({role:Gl(["assistant"]).nullish(),content:D().nullish(),reasoning_content:D().nullish(),reasoning:D().nullish(),tool_calls:Ze(z({index:we(),id:D().nullish(),function:z({name:D().nullish(),arguments:D().nullish()})})).nullish()}).nullish(),finish_reason:D().nullish()})),usage:Hd}),e]);function h0({prompt:e,user:t="user",assistant:r="assistant"}){let n="";e[0].role==="system"&&(n+=`${e[0].content}
220
221`,e=e.slice(1));for(const{role:s,content:o}of e)switch(s){case"system":throw new Gr({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":{const l=o.map(u=>{switch(u.type){case"text":return u.text}}).filter(Boolean).join("");n+=`${t}:
222${l}
223
224`;break}case"assistant":{const l=o.map(u=>{switch(u.type){case"text":return u.text;case"tool-call":throw new za({functionality:"tool-call messages"})}}).join("");n+=`${r}:
225${l}
226
227`;break}case"tool":throw new za({functionality:"tool messages"});default:{const l=s;throw new Error(`Unsupported role: ${l}`)}}return n+=`${r}:
228`,{prompt:n,stopSequences:[`
229${t}:`]}}function Ul({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function Vl(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var m0=z({echo:Ve().optional(),logitBias:Ar(D(),we()).optional(),suffix:D().optional(),user:D().optional()}),g0=class{constructor(e,t){this.specificationVersion="v2";var r;this.modelId=e,this.config=t;const n=(r=t.errorStructure)!=null?r:us;this.chunkSchema=y0(n.errorSchema),this.failedResponseHandler=mr(n)}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var e,t,r;return(r=(t=(e=this.config).supportedUrls)==null?void 0:t.call(e))!=null?r:{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:r,topP:n,topK:s,frequencyPenalty:o,presencePenalty:l,stopSequences:u,responseFormat:d,seed:f,providerOptions:m,tools:b,toolChoice:v}){var y;const x=[],S=(y=await ta({provider:this.providerOptionsName,providerOptions:m,schema:m0}))!=null?y:{};s!=null&&x.push({type:"unsupported-setting",setting:"topK"}),b?.length&&x.push({type:"unsupported-setting",setting:"tools"}),v!=null&&x.push({type:"unsupported-setting",setting:"toolChoice"}),d!=null&&d.type!=="text"&&x.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:M,stopSequences:R}=h0({prompt:e}),B=[...R??[],...u??[]];return{args:{model:this.modelId,echo:S.echo,logit_bias:S.logitBias,suffix:S.suffix,user:S.user,max_tokens:t,temperature:r,top_p:n,frequency_penalty:o,presence_penalty:l,seed:f,...m?.[this.providerOptionsName],prompt:M,stop:B.length>0?B:void 0},warnings:x}}async doGenerate(e){var t,r,n,s,o,l;const{args:u,warnings:d}=await this.getArgs(e),{responseHeaders:f,value:m,rawValue:b}=await hr({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:pr(this.config.headers(),e.headers),body:u,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Cr(v0),abortSignal:e.abortSignal,fetch:this.config.fetch}),v=m.choices[0],y=[];return v.text!=null&&v.text.length>0&&y.push({type:"text",text:v.text}),{content:y,usage:{inputTokens:(r=(t=m.usage)==null?void 0:t.prompt_tokens)!=null?r:void 0,outputTokens:(s=(n=m.usage)==null?void 0:n.completion_tokens)!=null?s:void 0,totalTokens:(l=(o=m.usage)==null?void 0:o.total_tokens)!=null?l:void 0},finishReason:Vl(v.finish_reason),request:{body:u},response:{...Ul(m),headers:f,body:b},warnings:d}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),n={...t,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},{responseHeaders:s,value:o}=await hr({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:pr(this.config.headers(),e.headers),body:n,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Io(this.chunkSchema),abortSignal:e.abortSignal,fetch:this.config.fetch});let l="unknown";const u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let d=!0;
229return{stream:o.pipeThrough(new TransformStream({start(f){f.enqueue({type:"stream-start",warnings:r})},transform(f,m){var b,v,y;if(e.includeRawChunks&&m.enqueue({type:"raw",rawValue:f.rawValue}),!f.success){l="error",m.enqueue({type:"error",error:f.error});return}const x=f.value;if("error"in x){l="error",m.enqueue({type:"error",error:x.error});return}d&&(d=!1,m.enqueue({type:"response-metadata",...Ul(x)}),m.enqueue({type:"text-start",id:"0"})),x.usage!=null&&(u.inputTokens=(b=x.usage.prompt_tokens)!=null?b:void 0,u.outputTokens=(v=x.usage.completion_tokens)!=null?v:void 0,u.totalTokens=(y=x.usage.total_tokens)!=null?y:void 0);const S=x.choices[0];S?.finish_reason!=null&&(l=Vl(S.finish_reason)),S?.text!=null&&m.enqueue({type:"text-delta",id:"0",delta:S.text})},flush(f){d||f.enqueue({type:"text-end",id:"0"}),f.enqueue({type:"finish",finishReason:l,usage:u})}})),request:{body:n},response:{headers:s}}}},Jd=z({prompt_tokens:we(),completion_tokens:we(),total_tokens:we()}),v0=z({id:D().nullish(),created:we().nullish(),model:D().nullish(),choices:Ze(z({text:D(),finish_reason:D()})),usage:Jd.nullish()}),y0=e=>Xe([z({id:D().nullish(),created:we().nullish(),model:D().nullish(),choices:Ze(z({text:D(),finish_reason:D().nullish(),index:we()})),usage:Jd.nullish()}),e]),Kl=z({dimensions:we().optional(),user:D().optional()}),b0=class{constructor(e,t){this.specificationVersion="v2",this.modelId=e,this.config=t}get provider(){return this.config.provider}get maxEmbeddingsPerCall(){var e;return(e=this.config.maxEmbeddingsPerCall)!=null?e:2048}get supportsParallelCalls(){var e;return(e=this.config.supportsParallelCalls)!=null?e:!0}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}async doEmbed({values:e,headers:t,abortSignal:r,providerOptions:n}){var s,o,l;const u=Object.assign((s=await ta({provider:"openai-compatible",providerOptions:n,schema:Kl}))!=null?s:{},(o=await ta({provider:this.providerOptionsName,providerOptions:n,schema:Kl}))!=null?o:{});if(e.length>this.maxEmbeddingsPerCall)throw new Cf({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const{responseHeaders:d,value:f,rawValue:m}=await hr({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:pr(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:u.dimensions,user:u.user},failedResponseHandler:mr((l=this.config.errorStructure)!=null?l:us),successfulResponseHandler:Cr(w0),abortSignal:r,fetch:this.config.fetch});return{embeddings:f.data.map(b=>b.embedding),usage:f.usage?{tokens:f.usage.prompt_tokens}:void 0,providerMetadata:f.providerMetadata,response:{headers:d,body:m}}}},w0=z({data:Ze(z({embedding:Ze(we())})),usage:z({prompt_tokens:we()}).nullish(),providerMetadata:Ar(D(),Ar(D(),ur())).optional()}),_0=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2",this.maxImagesPerCall=10}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:r,aspectRatio:n,seed:s,providerOptions:o,headers:l,abortSignal:u}){var d,f,m,b,v;const y=[];n!=null&&y.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),s!=null&&y.push({type:"unsupported-setting",setting:"seed"});const x=(m=(f=(d=this.config._internal)==null?void 0:d.currentDate)==null?void 0:f.call(d))!=null?m:new Date,{value:S,responseHeaders:M}=await hr({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:pr(this.config.headers(),l),body:{model:this.modelId,prompt:e,n:t,size:r,...(b=o.openai)!=null?b:{},response_format:"b64_json"},failedResponseHandler:mr((v=this.config.errorStructure)!=null?v:us),successfulResponseHandler:Cr(x0),abortSignal:u,fetch:this.config.fetch});return{images:S.data.map(R=>R.b64_json),warnings:y,response:{timestamp:x,modelId:this.modelId,headers:M}}}},x0=z({data:Ze(z({b64_json:D()}))}),k0="1.0.22";function S0(e){const t=Xu(e.baseURL),r=e.name,n={...e.apiKey&&{Authorization:`Bearer ${e.apiKey}`},...e.headers},s=()=>Xr(n,`ai-sdk/openai-compatible/${k0}`),o=v=>({provider:`${r}.${v}`,url:({path:y})=>{const x=new URL(`${t}${y}`);return e.queryParams&&(x.search=new URLSearchParams(e.queryParams).toString()),x.toString()},headers:s,fetch:e.fetch}),l=v=>u(v),u=v=>new Wd(v,{...o("chat"),includeUsage:e.includeUsage,supportsStructuredOutputs:e.supportsStructuredOutputs}),d=v=>new g0(v,{...o("completion"),includeUsage:e.includeUsage}),f=v=>new b0(v,{...o("embedding")}),m=v=>new _0(v,o("image")),b=v=>l(v);return b.languageModel=l,b.chatModel=u,b.completionModel=d,b.textEmbeddingModel=f,b.imageModel=m,b}function I0(e){const t=s=>({provider:`builtin.${s}`,headers:()=>({}),url:()=>"",fetch:e.fetch}
229),r=(s,o={})=>new Wd(s,t("chat")),n=(s,o)=>r(s,o);return n.chatModel=r,n}const T0=[{name:"OpenAI",apiKeyUrl:"https://platform.openai.com/api-keys",logoPath:"/logo/provider/openai.svg",models:[{id:"gpt-4o",name:"GPT-4o",logoPath:"/logo/model/openai.svg"},{id:"gpt-4o-mini",name:"GPT-4o Mini",logoPath:"/logo/model/openai.svg"},{id:"gpt-4-turbo",name:"GPT-4 Turbo",logoPath:"/logo/model/openai.svg"}]},{name:"Anthropic",apiKeyUrl:"https://console.anthropic.com/",logoPath:"/logo/provider/anthropic.svg",models:[{id:"claude-3-5-sonnet-20241022",name:"Claude 3.5 Sonnet",logoPath:"/logo/model/claude.svg"},{id:"claude-3-5-haiku-20241022",name:"Claude 3.5 Haiku",logoPath:"/logo/model/claude.svg"},{id:"claude-3-opus-20240229",name:"Claude 3 Opus",logoPath:"/logo/model/claude.svg"}]},{name:"Google",apiKeyUrl:"https://makersuite.google.com/app/apikey",logoPath:"/logo/provider/google.svg",models:[{id:"gemini-pro",name:"Gemini Pro",logoPath:"/logo/model/gemini.svg"},{id:"gemini-pro-vision",name:"Gemini Pro Vision",logoPath:"/logo/model/gemini.svg"}]},{name:"DeepSeek",apiKeyUrl:"https://platform.deepseek.com/api_keys",logoPath:"/logo/provider/deepseek.svg",models:[{id:"deepseek-chat",name:"DeepSeek Chat",logoPath:"/logo/model/deepseek.svg"},{id:"deepseek-coder",name:"DeepSeek Coder",logoPath:"/logo/model/deepseek.svg"}]}],I_=(e,t)=>{if(!t)return null;const r=T0.find(s=>s.name===t);return r?e?r.models.find(s=>s.id===e)?.logoPath:r.logoPath:null};async function E0(e){const{type:t,apiKey:r}=e;function n(){return S0({name:"custom",apiKey:r,baseURL:e.url})(e.name)}if(t===da.Custom)return n();switch(e.provider){case"OpenAI":{const{createOpenAI:s}=await vn(async()=>{const{createOpenAI:o}=await import("./B-pQ2ZuD.js");return{createOpenAI:o}},__vite__mapDeps([3,1,2,4,5,6,7,8,9,10,11]),import.meta.url);return s({apiKey:r})(e.name)}case"Anthropic":{const{createAnthropic:s}=await vn(async()=>{const{createAnthropic:o}=await import("./IHOOn322.js");return{createAnthropic:o}},__vite__mapDeps([12,1,2,4,5,6,7,8,9,10,11]),import.meta.url);return s({apiKey:r})(e.name)}case"Google":{const{createGoogleGenerativeAI:s}=await vn(async()=>{const{createGoogleGenerativeAI:o}=await import("./DtNbtGvo.js");return{createGoogleGenerativeAI:o}},__vite__mapDeps([13,1,2,4,5,6,7,8,9,10,11]),import.meta.url);return s({apiKey:r})(e.name)}case"DeepSeek":{const{createDeepSeek:s}=await vn(async()=>{const{createDeepSeek:o}=await import("./C7aAIYbN.js");return{createDeepSeek:o}},__vite__mapDeps([14,1,2,4,5,6,7,8,9,10,11]),import.meta.url);return s({apiKey:r})(e.name)}default:return n()}}var cs=(e=>(e.PRO="BUILTIN_PRO_MODEL_ID",e.STANDARD="BUILTIN_STANDARD_MODEL_ID",e.FLASH="BUILTIN_FLASH_MODEL_ID",e.SONNET="sonnet",e.GEMINI_PRO="gemini-pro",e.OPUS="opus",e))(cs||{});const A0=["opus","sonnet","gemini-pro","BUILTIN_PRO_MODEL_ID","BUILTIN_STANDARD_MODEL_ID"],T_=new Set(["opus","sonnet","gemini-pro"]);function Zo(e){return A0.includes(e)}const C0={BUILTIN_FLASH_MODEL_ID:"BUILTIN_STANDARD_MODEL_ID","sonnet-4-5":"sonnet","sonnet-4":"sonnet","opus-4":"opus","gemini-3-pro":"gemini-pro"};function Qd(e){return e&&(C0[e]??e)}const Yd=zp("model",()=>{const{t:e}=la(),t=Ne(()=>{const d={apiKey:"",createdAt:new Date().toISOString(),type:da.Builtin,displayName:void 0};return{opus:{...d,name:"Claude Opus 5",provider:e("model.builtinModels.desc.opus"),id:"opus",logo:"/logo/model/claude.svg"},sonnet:{...d,name:"Claude Sonnet 5",provider:e("model.builtinModels.desc.sonnet"),id:"sonnet",logo:"/logo/model/claude.svg"},"gemini-pro":{...d,name:"Gemini 3.1 Pro",provider:e("model.builtinModels.desc.gemini_pro"),id:"gemini-pro",logo:"/logo/model/gemini.svg",promo:{originalDesc:e("model.builtinModels.desc.gemini_pro_original"),label:e("model.builtinModels.promo-label")}},BUILTIN_PRO_MODEL_ID:{...d,name:e("model.builtinModels.pro"),provider:e("model.builtinModels.desc.pro"),id:"BUILTIN_PRO_MODEL_ID",logo:"/libs-common/logo/refore.svg"},BUILTIN_STANDARD_MODEL_ID:{...d,name:e("model.builtinModels.standard"),provider:e("model.builtinModels.desc.standard"),id:"BUILTIN_STANDARD_MODEL_ID",logo:"/logo/model/standard-model-logo.svg"}}}),r=Jr(()=>oe.models.orderBy("createdAt").toArray()),n=Ne(()=>r.value??[]);async function s(d){const f={...d,id:vt.createId(),createdAt:new Date().toISOString()};return await oe.models.add(f),f}function o(d,f){return oe.models.where({id:d}).modify(f)}
229async function l(d){await oe.models.delete(d)}async function u(d){const f=n.value.find(v=>v.id===d);if(!f)throw new Error("Model not found");const m=e("model.copy.suffix"),b={...f,name:`${f.name} ${m}`,displayName:f.displayName?`${f.displayName} ${m}`:void 0};return await s(b)}return{builtinModelConfigs:t,storedModels:r,models:n,addModel:s,updateModel:o,deleteModel:l,copyModel:u}}),R0=I0({fetch:()=>{throw new Error("Unreachable")}});function P0(){return Gp("default-model-id",cs.STANDARD,{serializer:{read:e=>Qd(e)??e,write:e=>String(e)}})}function E_(e){const t=Yd(),r=P0(),n=Jr(s=>s?oe.projectModel.where({id:s}).first().then(o=>{if(!o)return null;const l=Qd(o.modelId)??o.modelId;return l!==o.modelId&&setTimeout(()=>{oe.projectModel.put({id:s,modelId:l})}),{id:s,modelId:l}}):Promise.resolve(null),e);return bo(()=>{Qn(()=>[n.value,t.storedModels],async([s])=>{if(!s)return;t.storedModels||await Zn(()=>t.storedModels).toBeTruthy();const{id:o,modelId:l}=s;Zo(l)||t.storedModels?.find(u=>u.id===l)||oe.projectModel.put({id:o,modelId:cs.STANDARD})},{immediate:!0}),Qn(n,s=>{s===null&&oe.projectModel.put({id:ie(e),modelId:r.value})},{immediate:!0})}),Ne({get(){return n.value?.modelId??r.value},set(s){oe.projectModel.put({id:ie(e),modelId:s})}})}function O0(e){const t=Yd();return Ne(()=>{const r=e.value;if(r)return Zo(r)?t.builtinModelConfigs[r]:t.models?.find(n=>n.id===r)})}function M0(e){return Zp(async()=>e.value?e.value.type===da.Builtin?Ai(R0("builtin")):Ai(await E0(e.value)):null)}const lr=Rr("refore:chat");function A_(e){const{t}=la(),{activeVersionNumber:r,switchPreviewFile:n,setViewportWidth:s,activeVersion:o}=e,l=At(),{refetch:u}=cf(),d=O0(e.modelId),f=M0(d),m=Wr(!1),b=Wr(!1),v=Ne(()=>b.value||N0(Ce.value)),y=Wr(),x=Ne(()=>ie(e.versions)),S=Ne(()=>{const Y=ie(e.rules);if(!Y)return null;const le=[{id:vt.createId(),role:"system",parts:[{type:"text",text:tb}],metadata:{version:-1,projectId:ie(e.project).id,order:-2,createdAt:new Date().toISOString()}}],Ie=["<user_rules>",...Y.map($e=>$e.content),"</user_rules>"].join(`
230  * `);return le.push({id:vt.createId(),role:"system",parts:[{type:"text",text:Ie}],metadata:{version:-1,projectId:ie(e.project).id,order:-1,createdAt:new Date().toISOString()}}),le}),M=l0({activeVersionNumber:r,activeFilename:e.activeFilename,lastMessage:()=>ke.value,switchPreviewFile:n,setViewportWidth:s}),R=async(Y,le)=>{if(!d.value||!f.value)throw new Error;const Ie=le?.body?JSON.parse(le.body):{},$e=ie(e.project),Q=$e.id,We=r.value;if(d.value.type===da.Builtin){const ye=Xp(M.tools.value,Re=>({description:Re.description,inputJsonSchema:kn(Re.inputSchema).jsonSchema,outputJsonSchema:kn(Re.outputSchema).jsonSchema}));return l.raw("/api/refore/chat",{...le,parseResponse:async Re=>Re.response.ok?null:await Re.response.json(),retry:!1,body:{model:d.value.id,tools:ye,projectId:Q,version:We,projectType:$e.isLocal?"local":"cloud",...Ie}})}
230return Tv({model:f.value,messages:Cv(Ie.messages,{ignoreIncompleteToolCalls:!0}),abortSignal:le?.signal??U?.signal,tools:M.tools.value,maxRetries:1,async experimental_repairToolCall({toolCall:ye}){let Re=yo(ye.input);for(let Ge=0;Ge<5&&typeof Re=="string";Ge++)Re=yo(ye.input);return typeof Re=="string"&&(Re={value:Re}),{...ye,input:JSON.stringify(Re)}}}).toUIMessageStreamResponse({originalMessages:Ie.messages,generateMessageId:vt.createId,messageMetadata({part:ye}){if(ye.type==="start")return{createdAt:new Date().toISOString(),projectId:Q,version:We}},onError:ye=>(ce(),U?.abort(),U=void 0,window.reportError(ye),ye?.message||String(ye))})},B=Wp(()=>`${ie(e.project).id}:input`,"",{serializer:Hp.string}),{mutateAsync:V,isPending:E,isError:te}=Zt({mutationFn:async Y=>{if(lr("persist messages",Y.messages),!Y.messages.length)return;const le=ef(Y.messages,$e=>$e.id),Ie=await e.persistMessages({...Y,messages:le});return lr("persist messages version: %s, params.version: %s",Ie,Y.version),Ie}});let U;const{start:K,stop:ce}=Jp(()=>{r.value&&e.patchVersion({version:r.value,data:{errorMessage:t("chat.timeout")}}),U?.abort(t("chat.timeout"))},600*1e3);function me(Y){const{messages:le}=Y,Ie=le.at(-1);if(!Ie||!U||U?.signal.aborted)return!1;let $e=0;for(const Q of Ie.parts)Gt(Q)&&$e++;return $e>=100?(r.value&&e.patchVersion({version:r.value,data:{errorMessage:t("chat.tool.error.exceed")}}),!1):Qv(Y)}const de=new yy({transport:new hd({fetch:R}),generateId:vt.createId,sendAutomaticallyWhen:me,onToolCall:async({toolCall:Y})=>{if(!Y.dynamic){U||(U=new AbortController);try{const le=await M.onToolCall(Y,U.signal);U.signal.throwIfAborted(),de.addToolResult({tool:Y.toolName,toolCallId:Y.toolCallId,output:le})}catch(le){window.reportError(le),de.addToolResult({tool:Y.toolName,toolCallId:Y.toolCallId,state:"output-error",errorText:le?.message||String(le)})}}},async onFinish(Y){const{messages:le,isAbort:Ie,isDisconnect:$e,isError:Q}=Y;if(lr("onFinish",le),setTimeout(()=>{Yp(u)},3e3),!r.value)return;const We=le.at(-1);if(!We)return;const st=ie(e.project).id,ye=xn(We,r.value),Re=Ie||$e||Q||!me({messages:le});if(ye.isFinished=Re,Re){U=void 0,ce();for(const Pe of We.parts)Gt(Pe)&&Xv(Pe)&&(Pe.state="output-error",Ie&&(Pe.errorText="aborted"),$e&&(Pe.errorText="disconnected"))}y.value&&!ye.startTime&&(ye.startTime=new Date(y.value).toISOString()),await M.onFinish(),ye.endTime=new Date().toISOString();const Ge=Map.groupBy(le,Pe=>Pe.metadata?.version),De=new Set;for(const Pe of le)if(!(Pe.role==="system"||Pe.metadata?.isPersisted)){if(!Pe.metadata?.version)throw lr("message.version",Pe),new Error;De.add(Pe.metadata.version)}lr("versions",Array.from(De));for(const Pe of De){const Ae=Ge.get(Pe);if(!Ae)continue;const bt=he.value.length+de.messages.length-Ae.length;for(let jt=0;jt<Ae.length;jt++){const se=Ae[jt],Ee=xn(se,void 0);Ee.order=bt+jt,Ee.projectId=st,typeof Ee.isFinished!="boolean"&&(Ee.isFinished=!0)}await V({messages:Ae,parentVersion:r.value,state:St.Ready,version:Pe})}Re&&(await e.onFinish?.(r.value,le.at(-1)),await e.patchVersion({version:r.value,data:{modelId:Zo(d.value?.id)?d.value.id:"custom",modelName:d.value?.displayName||d.value?.name}}),y.value=void 0)},onError(Y){o.value&&(e.patchVersion({version:o.value.version,state:St.Error,data:{errorMessage:Qp(Y)}}),y.value=void 0,!(Y instanceof Bt)&&window.reportError(Y))}}),he=Wr([]),ve=Ne(()=>de.messages),ke=Ne(()=>de.lastMessage),Ce=Ne(()=>de.status),pt=Ne(()=>Ce.value==="error"||o.value?.state===St.Error||te.value),lt=Ne(()=>!b.value&&Ce.value==="ready"&&o.value?.state!==St.Error);function Ct(){y.value=Date.now(),U=new AbortController,U.signal.addEventListener("abort",()=>{r.value&&e.patchVersion({version:r.value,state:St.Error,data:{errorMessage:U?.signal.reason}}),U=void 0,Le()}),K()}function H(Y,le,Ie={}){const $e=ie(e.project).id;return{id:vt.createId(),parts:[{type:"text",text:Y}],role:"user",metadata:{createdAt:new Date().toISOString(),order:le,projectId:$e,...Ie}}}async function pe(Y){if(!d.value||Ce.value!=="ready"||b.value)return;const{prompt:le=B.value.trim(),parentVersion:Ie}=Y;if(!le&&!Y.messages)return;b.value=!0;const $e=he.value.length+de.messages.length;try{await Zn(f).toBeTruthy();const Q=[];if(Y.messages)Q.push(...Y.messages);else{const st=e.getContextPrompt?.();st&&Q.push(H(st,$e,{isHidden:!0})),Q.push(H(le,$e+Q.length))}const We=await V({messages:Q,parentVersion:Ie,state:St.Pending});await je(We),await ne(We),B.value="",Ct(),e.onSubmit?.(),await de.sendMessage()}finally{b.value=!1}}Qn(S,async Y=>{Y&&(de.messages=Y.concat(de.messages.filter(le=>le.role!=="system")))},{immediate:!0});async function ne(Y){let le=Y?await e.restoreMessages({version:Y}):[];S.value||await Zn(()=>S).toBeTruthy();for(const Q of le){const We=xn(Q,Y);typeof We.isFinished!="boolean"&&(We.isFinished=!0),We.isPersisted=!0}le=le.sort((Q,We)=>Q.metadata.createdAt>We.metadata.createdAt?-1:1).sort((Q,We)=>Q.metadata.order-We.metadata.order),lr("initial",le.slice());let Ie=0,$e=null;for(let Q=0;Q<le.length;Q++)le[Q].role==="assistant"&&(Ie+=1,Ie%5===0&&($e=Q));$e!==null&&(lr("history end at %s",$e),he.value=le.splice(0,$e+1)),lr("history messages",Hl(he.value)),lr("restore messages",le),le=S.value.concat(le),de.messages=le}bo(async()=>{x.value||await Zn(x).toBeTruthy();const Y=x.value?.at(0)?.version;r.value=Y,await ne(Y),e.onRestore?.(de.messages),m.value=!0});async function je(Y){Y&&(de.messages.find(le=>le.metadata?.version===Y)||await ne(Y),r.value=Y)}async function qe(){if(!(!r.value||!d.value||!["ready","error"].includes(Ce.value)||b.value)){b.value=!0;try{de.lastMessage&&!de.lastMessage.parts.length&&de.messages.pop(),Ct(),await e.patchVersion({version:r.value,state:St.Pending}),await de.sendMessage()}finally{b.value=!1}}}function et(Y){const le=[];for(let Ie=Y-1;Ie>=0;Ie--){const $e=ve.value[Ie];if($e.role!=="user")break;le.push($e)}pe({messages:le,parentVersion:o.value?.parent})}async function Le(){U?.abort(t("chat.aborted-by-user")),ce(),await de.stop(),U=void 0}return{startTime:y,versions:x,activeVersionNumber:r,initialized:m,chat:de,historyMessages:he,messages:ve,lastMessage:ke,status:Ce,input:B,isPersistMessagePending:E,isReady:lt,isError:pt,isPending:v,handleSubmit:pe,onRegenerate:et,switchVersion:je,onRetry:qe,stop:Le}}function N0(e){return["submitted","streaming"].includes(e)}var j0=(e=>(e.Cloud="cloud",e.Local="local",e))(j0||{}),ds=(e=>(e[e.Agent=0]="Agent",e[e.User=1]="User",e))(ds||{});const[Wo,C_]=Yl("Project"),[Or,R_]=Yl("VirtualFileSystem");function $0(){const e=At(),t=nn(),r=tf(),{data:n,isLoading:s,refetch:o}=wn({queryKey:["rules"],queryFn(){return e("/api/ai-design/rules")},enabled:()=>!!r.profile});async function l(f){const m=await e("/api/ai-design/rule",{method:"POST",body:f});return t.setQueryData(["rules"],b=>[...b,m]),m}async function u(f){await e("/api/ai-design/rule",{method:"PATCH",body:f}),t.setQueryData(["rules"],_n(m=>{const b=m.find(v=>v.id===f.id);b?Object.assign(b,f):o()}))}async function d(f){await e("/api/ai-design/rule",{method:"DELETE",query:{id:f}}),t.setQueryData(["rules"],m=>m.filter(b=>b.id!==f))}return{list:n,isLoading:s,add:l,update:u,remove:d,refresh:o}}function P_(){const e=cy(),t=$0(),r=Ne(()=>{if(!(!e.list.value||!t.list.value))return e.list.value.concat(t.list.value).sort((d,f)=>d.createdAt>f.createdAt?1:-1)}),n=Ne(()=>e.isLoading.value||t.isLoading.value);async function s(d){return d.isLocal?e.add(d):t.add(d)}async function o(d){const f=r.value?.find(m=>m.id===d.id);if(f)return f.isLocal?e.update(d):t.update(d)}async function l(d){const f=r.value?.find(m=>m.id===d);if(f)return f.isLocal?e.remove(d):t.remove(d)}function u(){t.refresh()}return{list:r,isLoading:n,add:s,update:o,remove:l,refresh:u}}function D0(e){const t=ey(e),r=fy(e);return{project:Ne(()=>t.project.value||r.project.value)}}function O_(e){return e.replace(/(\\?-)/g,t=>{switch(t){case"\\-":return"\\\\\\-";case"-":return"\\-";default:return t}})}function zl(e){return e.replace(new RegExp("(?<!\\\\)\\\\-","g"),"-").replace("\\\\-","\\-")}function M_(){const{t:e}=la(),t=At(),r=my(),n=nn(),s=yd(),{createId:o}=Xl();return Zt({mutationFn:async l=>{const u=o();let d;if(l.isLocal)d=await r({...l,id:u,createId:o});else{const{project:f,files:m}=await t("/api/ai-design/project",{method:"POST",body:{...l,files:l.files.map(b=>Qr(b,["content"])),id:u}});d=f,await s(u,1,l.files,m)}return await oe.projectModel.put({id:u,modelId:l.modelId||cs.STANDARD}),{project:d,prompt:l.prompt}},onSuccess(l,u){l&&(l.project.isLocal||n.invalidateQueries({queryKey:["/api/ai-design/projects"]}),eu({path:`/${Sn("project",l.project.id)}`,query:{prompt:l.prompt,submit:String(u.submit)}},{open:u.target?{target:u.target}:void 0}))},onError(l){nf.error(e("project.create-fail")),window.reportError(l)}})}function N_(){const e=At();return async function(r){return await oe.projects.where({source:r}).first()||await e("/api/ai-design/project-check",{method:"POST",body:{source:r}})}}function j_(){const e=At(),{createId:t}=Xl();return Zt({async mutationFn(r){return r.isLocal?gy(r,t):e("/api/ai-design/project/clone",{method:"POST",body:Qr(r,["isLocal"])})},onSuccess(r){eu({path:`/${Sn("project",r.projectId)}`,query:{submit:String(!1)}},{open:{target:"_blank"}})}})}function Xd(e){const{endpoint:t,filterExclude:r,query:n}=e,s=At(),{data:o,fetchNextPage:l,isFetching:u,hasNextPage:d,...f}
230=pf({queryKey:[t,n],initialPageParam:void 0,enabled:af(e.enabled),queryFn:async({pageParam:y})=>s(t,{query:{...y,...ie(n)}}),getNextPageParam:(y,x)=>{if(!y.nextCursor)return null;const S=y.nextCursor,M=[];for(const R of x)for(const B of R.list)r(B,S)&&M.push(B.id);return{cursor:S,exclude:M}}}),m=Ne(()=>{if(!o.value?.pages)return[];const y=[],x=new Set;for(const S of o.value.pages)for(const M of S.list)x.has(M.id)||(x.add(M.id),y.push(M));return y}),b=Ne(()=>o.value?.pages.at(-1)?.total??0);function v(){d.value&&!u.value&&l()}return{list:m,total:b,fetchNextPage:v,isFetching:u,hasNextPage:d,...f}}function $_(e){return Xd({endpoint:"/api/ai-design/projects",enabled:e?.enabled,query:()=>({...ie(e?.query),sortBy:ie(e?.sortBy)??"createdAt"}),filterExclude:(t,r)=>{const n=ie(e?.sortBy)??"createdAt";return t[n]===r}})}function D_(e){return Xd({...e,endpoint:"/api/ai-design/templates",filterExclude:(t,r)=>t.share?.curated===r})}function F_(e,t){let r=e.id;return e.name&&(r=`${encodeURIComponent(e.name)}-${r}`),t||(t=e.projectType===nu.Snapshot?"preview":"project"),`/${Sn(t,r)}`}function q_(e){const{updatedAt:t,createdAt:r}=e;return t?eo(t).fromNow():r?eo(r).fromNow():au}function L_(e){return e.createdAt?eo(e.createdAt).fromNow():au}function B_(){const e=Ci("project","",{transform:String}),t=Ne(()=>rf(e.value)),r=Ci("file","",{transform:String}),n=Ne({set(l){r.value=l},get(){if(!r.value)return;const u=Array.from(r.value.matchAll(new RegExp("(?<!\\\\)-","g"))).at(-1)?.index;return zl(!u||u===-1?r.value:r.value.substring(u+1))}}),s=sf("version",void 0,{transform(l){if(l)return Number(l)}}),{project:o}=D0(t);return Qn(()=>o.value?.name,()=>{const l=o.value?.name;if(!l)return;const u=e.value.lastIndexOf("-"),d=e.value.substring(0,u),f=e.value.substring(u+1);d!==l&&(e.value=`${l}-${f}`)},{immediate:!0}),{projectId:t,activeFilename:n,activeVersionNumber:s,project:o}}function ep(e,t){const{useProjectVersions:r}=Wo(),n=r(e),s=Ne(()=>n.value?.find(l=>l.version===t.value));async function o(l){return l===ds.Agent?{version:t.value}:(await Zn(s).toBeTruthy()).state!==St.Draft?{parentVersion:t.value}:{version:t.value}}return{versions:n,activeVersion:s,getVersionParams:o}}function U_(e,t,r){const{useFileContent:n,useProjectFiles:s}=Wo(),{versions:o,activeVersion:l}=ep(e,r),u=s(r),d=hf(t,u),f=n(d);return{versions:o,activeVersion:l,files:u,activeFile:d,virtualFile:f}}export{e_ as $,b_ as A,wd as B,oe as C,Yn as D,ny as E,Z0 as F,St as G,__ as H,l_ as I,R_ as J,Or as K,H0 as L,da as M,au as N,Xv as O,j0 as P,N0 as Q,x_ as R,Gt as S,it as T,G0 as U,ds as V,Qd as W,s_ as X,A_ as Y,j_ as Z,E_ as _,co as a,yy as a0,hd as a1,Qv as a2,kn as a3,q_ as a4,Jr as a5,o_ as a6,md as a7,w_ as a8,T0 as a9,ro as aA,Ef as aB,t_ as aC,Et as aD,Wd as aE,fr as aF,hf as aG,l0 as aH,Xu as aa,qa as ab,r_ as ac,Xr as ad,ta as ae,hr as af,pr as ag,yn as ah,Ri as ai,Ni as aj,Cf as ak,Eo as al,Y0 as am,X0 as an,a_ as ao,Q0 as ap,Cr as aq,Io as ar,Kh as as,za as at,Gr as au,ft as av,mr as aw,n_ as ax,Pr as ay,an as az,N_ as b,M_ as c,P0 as d,L_ as e,O0 as f,F_ as g,Yd as h,Zo as i,T_ as j,P_ as k,I_ as l,i_ as m,D0 as n,U_ as o,C_ as p,D_ as q,nu as r,B_ as s,ry as t,$_ as u,Wo as v,mf as w,W0 as x,O_ as y,ep as z};

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.