@rizom/ops 0.2.0-alpha.729 → 0.2.0-alpha.730
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/brains-ops.js +2 -2
- package/dist/index.js +2 -2
- package/package.json +1 -1
package/dist/brains-ops.js
CHANGED
|
@@ -410,7 +410,7 @@ Your code should look like:
|
|
|
410
410
|
2. You might be breaking the Rules of Hooks
|
|
411
411
|
3. You might have more than one copy of React in the same app
|
|
412
412
|
See https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem.`),g}function j(){Le.asyncTransitions--}function T(g){if(U===null)try{var E=("require"+Math.random()).slice(0,7);U=(hy&&hy[E]).call(hy,"timers").setImmediate}catch(D){U=function(K){f===!1&&(f=!0,typeof MessageChannel>"u"&&console.error("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."));var M=new MessageChannel;M.port1.onmessage=K,M.port2.postMessage(void 0)}}return U(g)}function B(g){return 1<g.length&&typeof AggregateError==="function"?AggregateError(g):g[0]}function k(g,E){E!==ne-1&&console.error("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "),ne=E}function R(g,E,D){var K=Le.actQueue;if(K!==null)if(K.length!==0)try{I(K),T(function(){return R(g,E,D)});return}catch(M){Le.thrownErrors.push(M)}else Le.actQueue=null;0<Le.thrownErrors.length?(K=B(Le.thrownErrors),Le.thrownErrors.length=0,D(K)):E(g)}function I(g){if(!X){X=!0;var E=0;try{for(;E<g.length;E++){var D=g[E];do{Le.didUsePromise=!1;var K=D(!1);if(K!==null){if(Le.didUsePromise){g[E]=D,g.splice(0,E);return}D=K}else break}while(1)}g.length=0}catch(M){g.splice(0,E+1),Le.thrownErrors.push(M)}finally{X=!1}}}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart==="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var q=Symbol.for("react.transitional.element"),N=Symbol.for("react.portal"),H=Symbol.for("react.fragment"),G=Symbol.for("react.strict_mode"),re=Symbol.for("react.profiler"),ae=Symbol.for("react.consumer"),me=Symbol.for("react.context"),be=Symbol.for("react.forward_ref"),ve=Symbol.for("react.suspense"),Ae=Symbol.for("react.suspense_list"),Ie=Symbol.for("react.memo"),we=Symbol.for("react.lazy"),Ue=Symbol.for("react.activity"),De=Symbol.iterator,Qe={},bt={isMounted:function(){return!1},enqueueForceUpdate:function(g){r(g,"forceUpdate")},enqueueReplaceState:function(g){r(g,"replaceState")},enqueueSetState:function(g){r(g,"setState")}},Rt=Object.assign,Dt={};Object.freeze(Dt),o.prototype.isReactComponent={},o.prototype.setState=function(g,E){if(typeof g!=="object"&&typeof g!=="function"&&g!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,g,E,"setState")},o.prototype.forceUpdate=function(g){this.updater.enqueueForceUpdate(this,g,"forceUpdate")};var lt={isMounted:["isMounted","Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."],replaceState:["replaceState","Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."]};for(V in lt)lt.hasOwnProperty(V)&&e(V,lt[V]);n.prototype=o.prototype,lt=i.prototype=new n,lt.constructor=i,Rt(lt,o.prototype),lt.isPureReactComponent=!0;var $r=Array.isArray,Tn=Symbol.for("react.client.reference"),Le={H:null,A:null,T:null,S:null,actQueue:null,asyncTransitions:0,isBatchingLegacy:!1,didScheduleLegacyUpdate:!1,didUsePromise:!1,thrownErrors:[],getCurrentStack:null,recentlyCreatedOwnerStacks:0},so=Object.prototype.hasOwnProperty,as=console.createTask?console.createTask:function(){return null};lt={react_stack_bottom_frame:function(g){return g()}};var cs,wa,ls={},$n=lt.react_stack_bottom_frame.bind(lt,m)(),Zl=as(d(m)),Wo=!1,xa=/\/+/g,_a=typeof reportError==="function"?reportError:function(g){if(typeof window==="object"&&typeof window.ErrorEvent==="function"){var E=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof g==="object"&&g!==null&&typeof g.message==="string"?String(g.message):String(g),error:g});if(!window.dispatchEvent(E))return}else if(typeof process==="object"&&typeof process.emit==="function"){process.emit("uncaughtException",g);return}console.error(g)},f=!1,U=null,ne=0,ie=!1,X=!1,w=typeof queueMicrotask==="function"?function(g){queueMicrotask(function(){return queueMicrotask(g)})}:T;lt=Object.freeze({__proto__:null,c:function(g){return ee().useMemoCache(g)}});var V={map:P,forEach:function(g,E,D){P(g,function(){E.apply(this,arguments)},D)},count:function(g){var E=0;return P(g,function(){E++}),E},toArray:function(g){return P(g,function(E){return E})||[]},only:function(g){if(!A(g))throw Error("React.Children.only expected to receive a single React element child.");return g}};lde.Activity=Ue,lde.Children=V,lde.Component=o,lde.Fragment=H,lde.Profiler=re,lde.PureComponent=i,lde.StrictMode=G,lde.Suspense=ve,lde.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=Le,lde.__COMPILER_RUNTIME=lt,lde.act=function(g){var E=Le.actQueue,D=ne;ne++;var K=Le.actQueue=E!==null?E:[],M=!1;try{var te=g()}catch(fe){Le.thrownErrors.push(fe)}if(0<Le.thrownErrors.length)throw k(E,D),g=B(Le.thrownErrors),Le.thrownErrors.length=0,g;if(te!==null&&typeof te==="object"&&typeof te.then==="function"){var se=te;return w(function(){M||ie||(ie=!0,console.error("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"))}),{then:function(fe,Te){M=!0,se.then(function(ze){if(k(E,D),D===0){try{I(K),T(function(){return R(ze,fe,Te)})}catch(us){Le.thrownErrors.push(us)}if(0<Le.thrownErrors.length){var On=B(Le.thrownErrors);Le.thrownErrors.length=0,Te(On)}}else fe(ze)},function(ze){k(E,D),0<Le.thrownErrors.length?(ze=B(Le.thrownErrors),Le.thrownErrors.length=0,Te(ze)):Te(ze)})}}}var ye=te;if(k(E,D),D===0&&(I(K),K.length!==0&&w(function(){M||ie||(ie=!0,console.error("A component suspended inside an `act` scope, but the `act` call was not awaited. When testing React components that depend on asynchronous data, you must await the result:\n\nawait act(() => ...)"))}),Le.actQueue=null),0<Le.thrownErrors.length)throw g=B(Le.thrownErrors),Le.thrownErrors.length=0,g;return{then:function(fe,Te){M=!0,D===0?(Le.actQueue=K,T(function(){return R(ye,fe,Te)})):fe(ye)}}},lde.cache=function(g){return function(){return g.apply(null,arguments)}},lde.cacheSignal=function(){return null},lde.captureOwnerStack=function(){var g=Le.getCurrentStack;return g===null?null:g()},lde.cloneElement=function(g,E,D){if(g===null||g===void 0)throw Error("The argument must be a React element, but you passed "+g+".");var K=Rt({},g.props),M=g.key,te=g._owner;if(E!=null){var se;e:{if(so.call(E,"ref")&&(se=Object.getOwnPropertyDescriptor(E,"ref").get)&&se.isReactWarning){se=!1;break e}se=E.ref!==void 0}se&&(te=p()),h(E)&&(l(E.key),M=""+E.key);for(ye in E)!so.call(E,ye)||ye==="key"||ye==="__self"||ye==="__source"||ye==="ref"&&E.ref===void 0||(K[ye]=E[ye])}var ye=arguments.length-2;if(ye===1)K.children=D;else if(1<ye){se=Array(ye);for(var fe=0;fe<ye;fe++)se[fe]=arguments[fe+2];K.children=se}K=S(g.type,M,K,te,g._debugStack,g._debugTask);for(M=2;M<arguments.length;M++)_(arguments[M]);return K},lde.createContext=function(g){return g={$$typeof:me,_currentValue:g,_currentValue2:g,_threadCount:0,Provider:null,Consumer:null},g.Provider=g,g.Consumer={$$typeof:ae,_context:g},g._currentRenderer=null,g._currentRenderer2=null,g},lde.createElement=function(g,E,D){for(var K=2;K<arguments.length;K++)_(arguments[K]);K={};var M=null;if(E!=null)for(fe in wa||!("__self"in E)||"key"in E||(wa=!0,console.warn("Your app (or one of its dependencies) is using an outdated JSX transform. Update to the modern JSX transform for faster performance: https://react.dev/link/new-jsx-transform")),h(E)&&(l(E.key),M=""+E.key),E)so.call(E,fe)&&fe!=="key"&&fe!=="__self"&&fe!=="__source"&&(K[fe]=E[fe]);var te=arguments.length-2;if(te===1)K.children=D;else if(1<te){for(var se=Array(te),ye=0;ye<te;ye++)se[ye]=arguments[ye+2];Object.freeze&&Object.freeze(se),K.children=se}if(g&&g.defaultProps)for(fe in te=g.defaultProps,te)K[fe]===void 0&&(K[fe]=te[fe]);M&&b(K,typeof g==="function"?g.displayName||g.name||"Unknown":g);var fe=1e4>Le.recentlyCreatedOwnerStacks++;return S(g,M,K,p(),fe?Error("react-stack-top-frame"):$n,fe?as(d(g)):Zl)},lde.createRef=function(){var g={current:null};return Object.seal(g),g},lde.forwardRef=function(g){g!=null&&g.$$typeof===Ie?console.error("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."):typeof g!=="function"?console.error("forwardRef requires a render function but was given %s.",g===null?"null":typeof g):g.length!==0&&g.length!==2&&console.error("forwardRef render functions accept exactly two parameters: props and ref. %s",g.length===1?"Did you forget to use the ref parameter?":"Any additional parameter will be undefined."),g!=null&&g.defaultProps!=null&&console.error("forwardRef render functions do not support defaultProps. Did you accidentally pass a React component?");var E={$$typeof:be,render:g},D;return Object.defineProperty(E,"displayName",{enumerable:!1,configurable:!0,get:function(){return D},set:function(K){D=K,g.name||g.displayName||(Object.defineProperty(g,"name",{value:K}),g.displayName=K)}}),E},lde.isValidElement=A,lde.lazy=function(g){g={_status:-1,_result:g};var E={$$typeof:we,_payload:g,_init:W},D={name:"lazy",start:-1,end:-1,value:null,owner:null,debugStack:Error("react-stack-top-frame"),debugTask:console.createTask?console.createTask("lazy()"):null};return g._ioInfo=D,E._debugInfo=[{awaited:D}],E},lde.memo=function(g,E){g==null&&console.error("memo: The first argument must be a component. Instead received: %s",g===null?"null":typeof g),E={$$typeof:Ie,type:g,compare:E===void 0?null:E};var D;return Object.defineProperty(E,"displayName",{enumerable:!1,configurable:!0,get:function(){return D},set:function(K){D=K,g.name||g.displayName||(Object.defineProperty(g,"name",{value:K}),g.displayName=K)}}),E},lde.startTransition=function(g){var E=Le.T,D={};D._updatedFibers=new Set,Le.T=D;try{var K=g(),M=Le.S;M!==null&&M(D,K),typeof K==="object"&&K!==null&&typeof K.then==="function"&&(Le.asyncTransitions++,K.then(j,j),K.then(s,_a))}catch(te){_a(te)}finally{E===null&&D._updatedFibers&&(g=D._updatedFibers.size,D._updatedFibers.clear(),10<g&&console.warn("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table.")),E!==null&&D.types!==null&&(E.types!==null&&E.types!==D.types&&console.error("We expected inner Transitions to have transferred the outer types set and that you cannot add to the outer Transition while inside the inner.This is a bug in React."),E.types=D.types),Le.T=E}},lde.unstable_useCacheRefresh=function(){return ee().useCacheRefresh()},lde.use=function(g){return ee().use(g)},lde.useActionState=function(g,E,D){return ee().useActionState(g,E,D)},lde.useCallback=function(g,E){return ee().useCallback(g,E)},lde.useContext=function(g){var E=ee();return g.$$typeof===ae&&console.error("Calling useContext(Context.Consumer) is not supported and will cause bugs. Did you mean to call useContext(Context) instead?"),E.useContext(g)},lde.useDebugValue=function(g,E){return ee().useDebugValue(g,E)},lde.useDeferredValue=function(g,E){return ee().useDeferredValue(g,E)},lde.useEffect=function(g,E){return g==null&&console.warn("React Hook useEffect requires an effect callback. Did you forget to pass a callback to the hook?"),ee().useEffect(g,E)},lde.useEffectEvent=function(g){return ee().useEffectEvent(g)},lde.useId=function(){return ee().useId()},lde.useImperativeHandle=function(g,E,D){return ee().useImperativeHandle(g,E,D)},lde.useInsertionEffect=function(g,E){return g==null&&console.warn("React Hook useInsertionEffect requires an effect callback. Did you forget to pass a callback to the hook?"),ee().useInsertionEffect(g,E)},lde.useLayoutEffect=function(g,E){return g==null&&console.warn("React Hook useLayoutEffect requires an effect callback. Did you forget to pass a callback to the hook?"),ee().useLayoutEffect(g,E)},lde.useMemo=function(g,E){return ee().useMemo(g,E)},lde.useOptimistic=function(g,E){return ee().useOptimistic(g,E)},lde.useReducer=function(g,E,D){return ee().useReducer(g,E,D)},lde.useRef=function(g){return ee().useRef(g)},lde.useState=function(g){return ee().useState(g)},lde.useSyncExternalStore=function(g,E,D){return ee().useSyncExternalStore(g,E,D)},lde.useTransition=function(){return ee().useTransition()},lde.version="19.2.7",typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop==="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())})()});var ZM,UM;var RR=v(()=>{ZM=Ml(AR(),1),UM=ZM.createContext(void 0)});var ude;var MM=v(()=>{ER();jM();RR();pe();ude=Ml(AR(),1)});var dde,pde;var qM=v(()=>{Ot();pe();wR();dde=Xc.omit({url:!0,analyticsScript:!0}),pde=dde.extend({title:c.string().optional().describe("Optional site title override"),description:c.string().optional().describe("Optional site description override")})});function TR(e,t={}){let r=FM(e),o=FM(t.sharedDomain??"rizom.ai").replace(/^\./,""),n=`.${o}`;if(r.endsWith(n)){let i=r.slice(0,-n.length);if(i.length>0&&!i.includes("."))return`${i}-preview.${o}`}return`preview.${r}`}function FM(e){return e.trim().replace(/^https?:\/\//i,"").replace(/\/$/,"").toLowerCase()}var KM=v(()=>{ug()});var hde,gde;var JM=v(()=>{pe();ay();kR();hde=c.string(),gde=c.custom((e)=>Hs(e)&&sM.safeParse(e).success)});var yde;var HM=v(()=>{ug();pe();yde=c.object({title:c.string().min(1),slug:c.string().min(1),description:c.string(),content:c.string(),author:c.string(),publishedAt:c.iso.datetime({offset:!0}),category:c.string().min(1).optional()})});var VM=v(()=>{vR();bM();wR();OM();kR();MM();qM();KM();JM();RR();HM()});function WM(e,t={}){return TR(e,t)}var GM=v(()=>{VM()});var rq={};Lt(rq,{assertPilotUsersRemoved:()=>tq,createPilotOffboardDriver:()=>YM,offboardPilotUsers:()=>_de});import{access as bde,readdir as Sde,readFile as vde,rm as sp,writeFile as wde}from"fs/promises";import{basename as xde,join as zo}from"path";async function _de(e,t){let r=[...new Set(t.handles.map((p)=>br.parse(p)))].sort((p,m)=>p.localeCompare(m));if(r.length===0)throw Error("At least one pilot handle is required");let o=t.dryRun??!0,n=`sunset:${r.join(",")}`;if(!o&&t.confirmation!==n)throw Error(`Exact confirmation required: ${n}`);let i=t.env??process.env,s=t.logger??console.info,a=await wt(e),l=r.map((p)=>Ede(a,p,i)),u=t.driver??YM({env:i,fetchImpl:t.fetchImpl,contentRepoTokenName:a.pilot.contentRepoAdminToken}),d=await Promise.all(l.map(async(p)=>({target:p,inspection:await u.inspect(p)})));if(Ide(d),Ade(d,o,s),!o){for(let p of d)if(!p.inspection.contentRepoArchived)await u.archiveContentRepo(p.target),s(`[${p.target.handle}] archived ${p.target.contentRepo}`);for(let p of d)for(let m of p.inspection.dnsRecords)await u.deleteDnsRecord(p.target,m),s(`[${p.target.handle}] deleted DNS ${m.name}`);for(let p of d)if(p.inspection.server)await u.deleteServer(p.target,p.inspection.server),s(`[${p.target.handle}] deleted ${p.target.instanceName}`);await kde(l,u,t.sleep??((p)=>new Promise((m)=>setTimeout(m,p)))),await Rde(e,r),await Ci(e),await tq(e,r),s(`Removed desired state for ${r.length} pilot user(s)`)}return{dryRun:o,handles:r,confirmation:n,plans:d}}function Ede(e,t,r){let o=e.users.find((d)=>d.handle===t),n=`${t}${e.pilot.domainSuffix}`,i=o?.domain??n,s=WM(i,{sharedDomain:e.pilot.domainSuffix}),a=o?.cloudflareZoneId??gy(r,"CF_ZONE_ID"),l=o?.contentRepo??`${e.pilot.contentRepoPrefix}${t}-content`,u=l.includes("/")?l:`${e.pilot.githubOrg}/${l}`;return{handle:t,instanceName:`rover-${t}`,domain:i,previewDomain:s,...i===n?{}:{wwwDomain:`www.${i}`},contentRepo:u,cloudflareZoneId:a}}async function kde(e,t,r){for(let o of e)for(let n=1;n<=20;n+=1){let i=await t.inspect(o);if(!i.server&&i.dnsRecords.length===0&&i.contentRepoArchived)break;if(n===20)throw Error(`[${o.handle}] provider cleanup did not converge`);await r(1500)}}function Ide(e){for(let{target:t,inspection:r}of e){if(r.server&&r.server.name!==t.instanceName)throw Error(`[${t.handle}] unexpected server name: ${r.server.name}`);let o=new Set([t.domain,t.previewDomain,...t.wwwDomain?[t.wwwDomain]:[]]);for(let n of r.dnsRecords){if(!o.has(n.name))throw Error(`[${t.handle}] refusing unexpected DNS record ${n.name}`);if(n.type==="A"&&r.server?.ip&&n.content!==r.server.ip)throw Error(`[${t.handle}] ${n.name} does not point to the retiring server`)}}}function Ade(e,t,r){r(`${t?"Dry run":"Apply"}: ${e.map(({target:o})=>o.handle).join(", ")}`);for(let{target:o,inspection:n}of e){let i=n.server?`delete ${o.instanceName}`:"already absent",s=n.dnsRecords.length>0?n.dnsRecords.map((l)=>`${l.type} ${l.name}`).join(", "):"already absent",a=n.contentRepoArchived?"already archived":`archive ${o.contentRepo}`;r(`[${o.handle}] server: ${i}; DNS: ${s}; repo: ${a}`)}r("Runtime backups: none")}async function Rde(e,t){let r=new Set(t),o=zo(e,"cohorts");for(let n of(await Sde(o)).filter((i)=>i.endsWith(".yaml"))){let i=zo(o,n),s=await vde(i,"utf8"),a=en(s);if(a.errors.length>0)throw Error(`${n}: ${a.errors[0]?.message??"invalid YAML"}`);let l=a.get("members",!0);if(!pR(l))throw Error(`${n}: members must be a sequence`);let u=l.items.filter((d)=>!Oo(d)||typeof d.value!=="string"||!r.has(d.value));if(u.length===l.items.length)continue;if(u.length===0){await sp(i);continue}l.items=u,mn.parse(a.toJS()),await wde(i,a.toString())}for(let n of t)await Promise.all([sp(zo(e,"users",`${n}.yaml`),{force:!0}),sp(zo(e,"users",`${n}.secrets.yaml`),{force:!0}),sp(zo(e,"users",`${n}.secrets.yaml.age`),{force:!0}),sp(zo(e,"users",n),{recursive:!0,force:!0})])}function YM(e){let t=e.fetchImpl??fetch,r=gy(e.env,"HCLOUD_TOKEN"),o=gy(e.env,"CF_API_TOKEN"),n=gy(e.env,e.contentRepoTokenName);return{async inspect(i){let[s,a,l]=await Promise.all([Tde(t,r,i.instanceName),Promise.all([i.domain,i.previewDomain,...i.wwwDomain?[i.wwwDomain]:[]].map((u)=>$de(t,o,i.cloudflareZoneId,u))).then((u)=>u.flat()),Ode(t,n,i.contentRepo)]);if(s.length>1)throw Error(`[${i.handle}] expected at most one server, found ${s.length}`);return{...s[0]?{server:s[0]}:{},dnsRecords:a,contentRepoArchived:l.archived}},async archiveContentRepo(i){await tl(t,`https://api.github.com/repos/${i.contentRepo}`,{method:"PATCH",headers:XM(n),body:JSON.stringify({archived:!0})},"GitHub repository archive")},async deleteDnsRecord(i,s){if(rl(await tl(t,`https://api.cloudflare.com/client/v4/zones/${i.cloudflareZoneId}/dns_records/${s.id}`,{method:"DELETE",headers:eq(o)},"Cloudflare DNS delete")).success!==!0)throw Error(`Cloudflare DNS delete failed for ${s.name}`)},async deleteServer(i,s){await tl(t,`https://api.hetzner.cloud/v1/servers/${s.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}},"Hetzner server delete",!0)}}}async function Tde(e,t,r){let o=new URL("https://api.hetzner.cloud/v1/servers");o.searchParams.set("label_selector",`brain=${r}`);let i=rl(await tl(e,o.toString(),{headers:{Authorization:`Bearer ${t}`}},"Hetzner server lookup")).servers;if(!Array.isArray(i))throw Error("Hetzner server lookup returned an invalid payload");return i.map((s)=>{let a=rl(s),l=QM(a.public_net),u=QM(l?.ipv4);return{id:Cde(a.id,"Hetzner server id"),name:ap(a.name,"Hetzner server name"),...typeof u?.ip==="string"?{ip:u.ip}:{}}})}async function $de(e,t,r,o){let n=new URL(`https://api.cloudflare.com/client/v4/zones/${r}/dns_records`);n.searchParams.set("name",o);let i=rl(await tl(e,n.toString(),{headers:eq(t)},"Cloudflare DNS lookup")),s=i.result;if(i.success!==!0||!Array.isArray(s))throw Error(`Cloudflare DNS lookup failed for ${o}`);return s.map((a)=>{let l=rl(a),u=ap(l.type,"Cloudflare record type");if(u!=="A"&&u!=="CNAME")throw Error(`Unsupported Cloudflare record type ${u} for ${o}`);return{id:ap(l.id,"Cloudflare record id"),name:ap(l.name,"Cloudflare record name"),type:u,content:ap(l.content,"Cloudflare record content")}})}async function Ode(e,t,r){let o=rl(await tl(e,`https://api.github.com/repos/${r}`,{headers:XM(t)},"GitHub repository lookup"));if(typeof o.archived!=="boolean")throw Error(`Invalid repository archive state for ${r}`);return{archived:o.archived}}async function tl(e,t,r,o,n=!1){let i=await e(t,r),s=await i.text();if(!i.ok)throw Error(`${o} failed (${i.status}): ${s}`);if(!s&&n)return{};try{return JSON.parse(s)}catch{throw Error(`${o} returned an invalid JSON response`)}}function XM(e){return{Accept:"application/vnd.github+json",Authorization:`Bearer ${e}`,"Content-Type":"application/json","X-GitHub-Api-Version":"2022-11-28"}}function eq(e){return{Authorization:`Bearer ${e}`}}function gy(e,t){let r=e[t];if(!r)throw Error(`Missing required environment variable: ${t}`);return r}function rl(e){if(!Hs(e))throw Error("Provider returned an unexpected payload");return e}function QM(e){return Hs(e)?e:void 0}function ap(e,t){if(typeof e!=="string"||e.length===0)throw Error(`Missing ${t}`);return e}function Cde(e,t){if(typeof e!=="number")throw Error(`Missing ${t}`);return e}async function Pde(e){try{return await bde(e),!0}catch{return!1}}async function tq(e,t){for(let r of t)for(let o of[zo(e,"users",`${r}.yaml`),zo(e,"users",`${r}.secrets.yaml.age`),zo(e,"users",r)])if(await Pde(o))throw Error(`Offboarded user state remains: ${xde(o)}`)}var nq=v(()=>{Gc();hn();GM();Rd();Io()});var oq="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";import{webcrypto as iq}from"crypto";function Nde(e){if(e<0)throw RangeError("Wrong ID size");try{if(!qi||qi.length<e)qi=Buffer.allocUnsafe(e*zde),iq.getRandomValues(qi),nl=0;else if(nl+e>qi.length)iq.getRandomValues(qi),nl=0}catch(t){throw qi=void 0,t}nl+=e}function sq(e=21){Nde(e|=0);let t="";for(let r=nl-e;r<nl;r++)t+=oq[qi[r]&63];return t}var zde=128,qi,nl;var aq=()=>{};function No(e=12){return sq(e)}var cp=v(()=>{aq()});import{openSync as Dde,writeSync as Lde}from"fs";function Bde(e){return ol?`[${ol}] ${e}`:e}class Ar{static instance=null;level;context;useStderr;format;logFile;fileHandle;constructor(e={},t){if(this.level=e.level??ia.INFO,this.context=e.context??void 0,this.useStderr=e.useStderr??!1,this.format=e.format??"text",this.logFile=e.logFile,t!==void 0)this.fileHandle=t;else if(this.logFile)try{this.fileHandle=Dde(this.logFile,"a")}catch{}}static getInstance(e){if(!Ar.instance)Ar.instance=new Ar(e);else{if(e?.useStderr!==void 0)Ar.instance.useStderr=e.useStderr;if(e?.level!==void 0)Ar.instance.level=e.level}return Ar.instance}static resetInstance(){Ar.instance=null,ol=void 0}static setProcessRole(e){ol=e}static createFresh(e){return new Ar(e)}formatEntry(e,t,r){if(this.format==="json")return this.formatJsonEntry(e,t,r);return Bde([`[${new Date().toISOString()}]`,...this.context?[`[${this.context}]`]:[],t].join(" "))}write(e,t,r,o){if(this.format==="json")e(this.formatEntry(t,r,o));else if(o.length>0)e(this.formatEntry(t,r,[]),...o);else e(this.formatEntry(t,r,[]));if(this.fileHandle!==void 0){let n=this.formatJsonEntry(t,r,o);try{Lde(this.fileHandle,n+`
|
|
413
|
-
`)}catch{}}}formatJsonEntry(e,t,r){let o={ts:new Date().toISOString(),level:e,...ol&&{role:ol},msg:t};if(this.context)o.ctx=this.context;if(r.length>0)o.data=r;return JSON.stringify(o)}debugStream(){return this.useStderr?console.error.bind(console):console.debug.bind(console)}silly(e,...t){if(this.level<=ia.SILLY)this.write(this.debugStream(),"silly",e,t)}verbose(e,...t){if(this.level<=ia.VERBOSE)this.write(this.debugStream(),"verbose",e,t)}debug(e,...t){if(this.level<=ia.DEBUG)this.write(this.debugStream(),"debug",e,t)}info(e,...t){if(this.level<=ia.INFO){let r=this.useStderr?console.error.bind(console):console.info.bind(console);this.write(r,"info",e,t)}}warn(e,...t){if(this.level<=ia.WARN)this.write(console.warn.bind(console),"warn",e,t)}error(e,...t){if(this.level<=ia.ERROR)this.write(console.error.bind(console),"error",e,t)}child(e){return new Ar({level:this.level,context:e,useStderr:this.useStderr,format:this.format},this.fileHandle)}setUseStderr(e){this.useStderr=e}}var ia,ol,JNe;var $R=v(()=>{ia={SILLY:0,VERBOSE:1,DEBUG:2,INFO:3,WARN:4,ERROR:5,NONE:6};JNe=Ar.getInstance()});var OR,jde,il,GNe;var lp=v(()=>{Ot();pe();OR=c.enum(["file_operations","content_operations","data_processing","batch_processing"]),jde=c.looseObject({pluginId:c.string().optional(),progressToken:c.union([c.string(),c.number()]).optional(),operationType:OR,operationTarget:c.string().optional(),interfaceType:c.string().optional(),conversationId:c.string().optional(),channelId:c.string().optional(),requestedByActor:Vn.optional(),requestedByUserId:c.string().optional(),requestedByInterface:c.string().optional(),silent:c.boolean().optional(),provenance:ko.optional()}),il=c.looseObject({pluginId:c.string().optional(),progressToken:c.union([c.string(),c.number()]).optional(),operationType:OR,operationTarget:c.string().optional(),interfaceType:c.string().optional(),conversationId:c.string().optional(),channelId:c.string().optional(),requestedByActor:Vn.optional(),requestedByUserId:c.string().optional(),requestedByInterface:c.string().optional(),silent:c.boolean().optional(),provenance:ko.optional(),rootJobId:c.string()}),GNe=c.enum(["none","skip","replace","coalesce"])});var Zde,Fi=15000;var up=v(()=>{lp();pe();Zde=c.object({id:c.string(),type:c.string(),data:c.string(),status:c.enum(["pending","processing","completed","failed"]),source:c.string().nullable(),priority:c.number(),retryCount:c.number(),maxRetries:c.number(),lastError:c.string().nullable(),lastErrorPublic:c.unknown(),createdAt:c.number(),scheduledFor:c.number(),startedAt:c.number().nullable(),completedAt:c.number().nullable(),attemptId:c.string().nullable(),workerSlotId:c.string().nullable(),workerSessionId:c.string().nullable(),leaseExpiresAt:c.number().nullable(),attemptHeartbeatAt:c.number().nullable(),runtimeUpdatedAt:c.number().nullable(),metadata:il,progress:c.custom((e)=>typeof e==="object"&&e!==null&&("progress"in e)&&typeof e.progress==="number").nullable(),result:c.unknown().nullable().optional()})});var CR,cq,Oe,Ude,Mde,lq,uq,dq;var Do=v(()=>{Ot();pe();lp();CR=c.enum(["pending","processing","completed","failed"]),cq=c.enum(["completed","failed"]),Oe={PENDING:"pending",PROCESSING:"processing",COMPLETED:"completed",FAILED:"failed"},Ude=c.object({id:c.string(),type:c.string(),status:CR,data:c.unknown(),result:c.unknown().optional(),lastError:c.string().optional().nullable(),attempts:c.number(),maxRetries:c.number(),priority:c.number(),createdAt:c.date(),updatedAt:c.date(),processedAt:c.date().optional().nullable(),completedAt:c.date().optional().nullable(),failedAt:c.date().optional().nullable()}),Mde=c.object({jobId:c.string(),type:c.string(),status:cq,result:c.unknown().optional(),error:c.string().optional()}),lq=c.object({success:c.literal(!1),error:c.string().optional()}),uq=c.object({id:c.string(),type:c.enum(["job","batch"]),status:CR,message:c.string().optional(),progress:c.object({current:c.number(),total:c.number(),percentage:c.number()}).optional(),aggregationKey:c.string().optional(),batchDetails:c.object({totalOperations:c.number(),completedOperations:c.number(),failedOperations:c.number(),currentOperation:c.string().optional(),errors:c.array(c.string()).optional()}).optional(),jobDetails:c.object({jobType:c.string(),priority:c.number(),retryCount:c.number()}).optional(),metadata:il}),dq=Oi(II.progress,uq)});var Ce,Wt;var vn=v(()=>{Ce=class Ce extends Error{code;extendedCode;rawCode;constructor(e,t,r,o,n){if(t!==void 0)e=`${t}: ${e}`;super(e,{cause:n});this.code=t,this.extendedCode=r,this.rawCode=o,this.name="LibsqlError"}};Wt=class Wt extends Ce{statementIndex;constructor(e,t,r,o,n,i){super(e,r,o,n,i);this.statementIndex=t,this.name="LibsqlBatchError"}}});function pq(e){let t=qde.exec(e);if(t===null)throw new Ce(`The URL '${e}' is not in a valid format`,"URL_INVALID");let r=t.groups,o=r.scheme,n=r.authority!==void 0?Fde(r.authority):void 0,i=sa(r.path),s=r.query!==void 0?Jde(r.query):void 0,a=r.fragment!==void 0?sa(r.fragment):void 0;return{scheme:o,authority:n,path:i,query:s,fragment:a}}function Fde(e){let t=Kde.exec(e);if(t===null)throw new Ce("The authority part of the URL is not in a valid format","URL_INVALID");let r=t.groups,o=sa(r.host_br??r.host),n=r.port?parseInt(r.port,10):void 0,i=r.username!==void 0?{username:sa(r.username),password:r.password!==void 0?sa(r.password):void 0}:void 0;return{host:o,port:n,userinfo:i}}function Jde(e){let t=e.split("&"),r=[];for(let o of t){if(o==="")continue;let n,i,s=o.indexOf("=");if(s<0)n=o,i="";else n=o.substring(0,s),i=o.substring(s+1);r.push({key:sa(n.replaceAll("+"," ")),value:sa(i.replaceAll("+"," "))})}return{pairs:r}}function sa(e){try{return decodeURIComponent(e)}catch(t){if(t instanceof URIError)throw new Ce(`URL component has invalid percent encoding: ${t}`,"URL_INVALID",void 0,void 0,t);throw t}}function dp(e,t,r){if(t===void 0)throw new Ce(`URL with scheme ${JSON.stringify(e+":")} requires authority (the "//" part)`,"URL_INVALID");let o=`${e}:`,n=Hde(t.host),i=Vde(t.port),a=`//${Wde(t.userinfo)}${n}${i}`,l=r.split("/").map(encodeURIComponent).join("/");if(l!==""&&!l.startsWith("/"))l="/"+l;return new URL(`${o}${a}${l}`)}function Hde(e){return e.includes(":")?`[${encodeURI(e)}]`:encodeURI(e)}function Vde(e){return e!==void 0?`:${e}`:""}function Wde(e){if(e===void 0)return"";let t=encodeURIComponent(e.username),r=e.password!==void 0?`:${encodeURIComponent(e.password)}`:"";return`${t}${r}@`}var qde,Kde;var yy=v(()=>{vn();qde=(()=>new RegExp("^(?<scheme>[A-Za-z][A-Za-z.+-]*):(//(?<authority>[^/?#]*))?(?<path>[^?#]*)(\\?(?<query>[^#]*))?(#(?<fragment>.*))?$","su"))();Kde=(()=>new RegExp("^((?<username>[^:]*)(:(?<password>.*))?@)?((?<host>[^:\\[\\]]*)|(\\[(?<host_br>[^\\[\\]]*)\\]))(:(?<port>[0-9]*))?$","su"))()});var al,fq,mq,pp,by,Gde,Gt,hq,bq=(e)=>e.replace(/=/g,"").replace(/[+\/]/g,(t)=>t=="+"?"-":"_"),Sq=(e)=>e.replace(/[^A-Za-z0-9\+\/]/g,""),vq=(e)=>{let t,r,o,n,i="",s=e.length%3;for(let a=0;a<e.length;){if((r=e.charCodeAt(a++))>255||(o=e.charCodeAt(a++))>255||(n=e.charCodeAt(a++))>255)throw TypeError("invalid character found");t=r<<16|o<<8|n,i+=pp[t>>18&63]+pp[t>>12&63]+pp[t>>6&63]+pp[t&63]}return s?i.slice(0,s-3)+"===".substring(s):i},NR,PR,Sy=(e,t=!1)=>t?bq(PR(e)):PR(e),Qde=(e)=>{if(e.length<2){var t=e.charCodeAt(0);return t<128?e:t<2048?Gt(192|t>>>6)+Gt(128|t&63):Gt(224|t>>>12&15)+Gt(128|t>>>6&63)+Gt(128|t&63)}else{var t=65536+(e.charCodeAt(0)-55296)*1024+(e.charCodeAt(1)-56320);return Gt(240|t>>>18&7)+Gt(128|t>>>12&63)+Gt(128|t>>>6&63)+Gt(128|t&63)}},Yde,wq=(e)=>e.replace(Yde,Qde),gq,sl=(e,t=!1)=>t?bq(gq(e)):gq(e),yq=(e)=>sl(e,!0),Xde,epe=(e)=>{switch(e.length){case 4:var t=(7&e.charCodeAt(0))<<18|(63&e.charCodeAt(1))<<12|(63&e.charCodeAt(2))<<6|63&e.charCodeAt(3),r=t-65536;return Gt((r>>>10)+55296)+Gt((r&1023)+56320);case 3:return Gt((15&e.charCodeAt(0))<<12|(63&e.charCodeAt(1))<<6|63&e.charCodeAt(2));default:return Gt((31&e.charCodeAt(0))<<6|63&e.charCodeAt(1))}},xq=(e)=>e.replace(Xde,epe),_q=(e)=>{if(e=e.replace(/\s+/g,""),!Gde.test(e))throw TypeError("malformed base64.");e+="==".slice(2-(e.length&3));let t,r,o,n=[];for(let i=0;i<e.length;)if(t=by[e.charAt(i++)]<<18|by[e.charAt(i++)]<<12|(r=by[e.charAt(i++)])<<6|(o=by[e.charAt(i++)]),r===64)n.push(Gt(t>>16&255));else if(o===64)n.push(Gt(t>>16&255,t>>8&255));else n.push(Gt(t>>16&255,t>>8&255,t&255));return n.join("")},DR,Eq,kq=(e)=>Eq(Iq(e)),tpe,Iq=(e)=>Sq(e.replace(/[-_]/g,(t)=>t=="-"?"+":"/")),zR=(e)=>tpe(Iq(e)),rpe=(e)=>{if(typeof e!=="string")return!1;let t=e.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(t)||!/[^\s0-9a-zA-Z\-_]/.test(t)},Aq=(e)=>({value:e,enumerable:!1,writable:!0,configurable:!0}),Rq=function(){let e=(t,r)=>Object.defineProperty(String.prototype,t,Aq(r));e("fromBase64",function(){return zR(this)}),e("toBase64",function(t){return sl(this,t)}),e("toBase64URI",function(){return sl(this,!0)}),e("toBase64URL",function(){return sl(this,!0)}),e("toUint8Array",function(){return kq(this)})},Tq=function(){let e=(t,r)=>Object.defineProperty(Uint8Array.prototype,t,Aq(r));e("toBase64",function(t){return Sy(this,t)}),e("toBase64URI",function(){return Sy(this,!0)}),e("toBase64URL",function(){return Sy(this,!0)})},npe=()=>{Rq(),Tq()},cl;var vy=v(()=>{al=typeof Buffer==="function",fq=typeof TextDecoder==="function"?new TextDecoder("utf-8",{ignoreBOM:!0}):void 0,mq=typeof TextEncoder==="function"?new TextEncoder:void 0,pp=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),by=((e)=>{let t={};return e.forEach((r,o)=>t[r]=o),t})(pp),Gde=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,Gt=String.fromCharCode.bind(String),hq=typeof Uint8Array.from==="function"?Uint8Array.from.bind(Uint8Array):(e)=>new Uint8Array(Array.prototype.slice.call(e,0)),NR=typeof btoa==="function"?(e)=>btoa(e):al?(e)=>Buffer.from(e,"binary").toString("base64"):vq,PR=al?(e)=>Buffer.from(e).toString("base64"):(e)=>{let r=[];for(let o=0,n=e.length;o<n;o+=4096)r.push(Gt.apply(null,e.subarray(o,o+4096)));return NR(r.join(""))},Yde=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,gq=al?(e)=>Buffer.from(e,"utf8").toString("base64"):mq?(e)=>PR(mq.encode(e)):(e)=>NR(wq(e)),Xde=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,DR=typeof atob==="function"?(e)=>atob(Sq(e)):al?(e)=>Buffer.from(e,"base64").toString("binary"):_q,Eq=al?(e)=>hq(Buffer.from(e,"base64")):(e)=>hq(DR(e).split("").map((t)=>t.charCodeAt(0))),tpe=al?(e)=>Buffer.from(e,"base64").toString("utf8"):fq?(e)=>fq.decode(Eq(e)):(e)=>xq(DR(e)),cl={version:"3.8.0",VERSION:"3.8.0",atob:DR,atobPolyfill:_q,btoa:NR,btoaPolyfill:vq,fromBase64:zR,toBase64:sl,encode:sl,encodeURI:yq,encodeURL:yq,utob:wq,btou:xq,decode:zR,isValid:rpe,fromUint8Array:Sy,toUint8Array:kq,extendString:Rq,extendUint8Array:Tq,extendBuiltins:npe}});function Ki(e){if(e==="write")return"BEGIN IMMEDIATE";else if(e==="read")return"BEGIN TRANSACTION READONLY";else if(e==="deferred")return"BEGIN DEFERRED";else throw RangeError('Unknown transaction mode, supported values are "write", "read" and "deferred"')}class ll{columns;columnTypes;rows;rowsAffected;lastInsertRowid;constructor(e,t,r,o,n){this.columns=e,this.columnTypes=t,this.rows=r,this.rowsAffected=o,this.lastInsertRowid=n}toJSON(){return{columns:this.columns,columnTypes:this.columnTypes,rows:this.rows.map(ope),rowsAffected:this.rowsAffected,lastInsertRowid:this.lastInsertRowid!==void 0?""+this.lastInsertRowid:null}}}function ope(e){return Array.prototype.map.call(e,ipe)}function ipe(e){if(typeof e==="bigint")return""+e;else if(e instanceof ArrayBuffer)return cl.fromUint8Array(new Uint8Array(e));else return e}var Yn="https://github.com/libsql/libsql-client-ts#supported-urls";var ul=v(()=>{vy()});function Oq(e){return e.scheme==="file"&&(e.path===":memory:"||e.path.startsWith(":memory:?"))}function fp(e,t){if(typeof e!=="object")throw TypeError(`Expected client configuration as object, got ${typeof e}`);let{url:r,authToken:o,tls:n,intMode:i,concurrency:s}=e;s=Math.max(0,s||20),i??="number";let a=[];if(r===$q)r="file::memory:";let l=pq(r),u=l.scheme.toLowerCase(),d=u==="file"&&l.path===$q&&l.authority===void 0,p;if(d)p={cache:{values:["shared","private"],update:(y,S)=>a.push(`${y}=${S}`)}};else p={tls:{values:["0","1"],update:(y,S)=>n=S==="1"},authToken:{update:(y,S)=>o=S}};for(let{key:y,value:S}of l.query?.pairs??[]){if(!Object.hasOwn(p,y))throw new Ce(`Unsupported URL query parameter ${JSON.stringify(y)}`,"URL_PARAM_NOT_SUPPORTED");let x=p[y];if(x.values!==void 0&&!x.values.includes(S))throw new Ce(`Unknown value for the "${y}" query argument: ${JSON.stringify(S)}. Supported values are: [${x.values.map((_)=>'"'+_+'"').join(", ")}]`,"URL_INVALID");if(x.update!==void 0)x?.update(y,S)}let m=a.length===0?"":`?${a.join("&")}`,h=l.path+m,b;if(u==="libsql")if(n===!1){if(l.authority?.port===void 0)throw new Ce('A "libsql:" URL with ?tls=0 must specify an explicit port',"URL_INVALID");b=t?"http":"ws"}else b=t?"https":"wss";else b=u;if(b==="http"||b==="ws")n??=!1;else n??=!0;if(b!=="http"&&b!=="ws"&&b!=="https"&&b!=="wss"&&b!=="file")throw new Ce(`The client supports only "libsql:", "wss:", "ws:", "https:", "http:" and "file:" URLs, got ${JSON.stringify(l.scheme+":")}. For more information, please read ${Yn}`,"URL_SCHEME_NOT_SUPPORTED");if(i!=="number"&&i!=="bigint"&&i!=="string")throw TypeError(`Invalid value for intMode, expected "number", "bigint" or "string", got ${JSON.stringify(i)}`);if(l.fragment!==void 0)throw new Ce(`URL fragments are not supported: ${JSON.stringify("#"+l.fragment)}`,"URL_INVALID");if(d)return{scheme:"file",tls:!1,path:h,intMode:i,concurrency:s,syncUrl:e.syncUrl,syncInterval:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,fetch:e.fetch,timeout:e.timeout,authToken:void 0,encryptionKey:void 0,remoteEncryptionKey:void 0,authority:void 0};return{scheme:b,tls:n,authority:l.authority,path:h,authToken:o,intMode:i,concurrency:s,encryptionKey:e.encryptionKey,remoteEncryptionKey:e.remoteEncryptionKey,syncUrl:e.syncUrl,syncInterval:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,fetch:e.fetch,timeout:e.timeout}}var $q=":memory:";var mp=v(()=>{vn();yy();ul()});var Pq=ge(function(tn){var spe=tn&&tn.__createBinding||(Object.create?function(e,t,r,o){if(o===void 0)o=r;var n=Object.getOwnPropertyDescriptor(t,r);if(!n||("get"in n?!t.__esModule:n.writable||n.configurable))n={enumerable:!0,get:function(){return t[r]}};Object.defineProperty(e,o,n)}:function(e,t,r,o){if(o===void 0)o=r;e[o]=t[r]}),ape=tn&&tn.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Cq=tn&&tn.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null){for(var r in e)if(r!=="default"&&Object.prototype.hasOwnProperty.call(e,r))spe(t,e,r)}return ape(t,e),t};Object.defineProperty(tn,"__esModule",{value:!0});tn.load=tn.currentTarget=void 0;var cpe=Cq(qr("path")),lpe=Cq(qr("fs"));function upe(){let e=null;switch(process.platform){case"android":switch(process.arch){case"arm":return"android-arm-eabi";case"arm64":return"android-arm64"}e="Android";break;case"win32":switch(process.arch){case"x64":return"win32-x64-msvc";case"arm64":return"win32-arm64-msvc";case"ia32":return"win32-ia32-msvc"}e="Windows";break;case"darwin":switch(process.arch){case"x64":return"darwin-x64";case"arm64":return"darwin-arm64"}e="macOS";break;case"linux":switch(process.arch){case"x64":case"arm64":return dpe()?`linux-${process.arch}-gnu`:`linux-${process.arch}-musl`;case"arm":return"linux-arm-gnueabihf"}e="Linux";break;case"freebsd":if(process.arch==="x64")return"freebsd-x64";e="FreeBSD";break}if(e)throw Error(`Neon: unsupported ${e} architecture: ${process.arch}`);throw Error(`Neon: unsupported system: ${process.platform}`)}tn.currentTarget=upe;function dpe(){let e=process.report?.getReport();if(typeof e!=="object"||!e||!("header"in e))return!1;let t=e.header;return typeof t==="object"&&!!t&&"glibcVersionRuntime"in t}function ppe(e){let t=cpe.join(e,"index.node");return lpe.existsSync(t)?qr(t):null}tn.load=ppe});var Dq=ge(function(y2e,Nq){var zq=()=>process.platform==="linux",LR=null,fpe=()=>{if(!LR)LR=zq()&&process.report?process.report.getReport():{};return LR};Nq.exports={isLinux:zq,getReport:fpe}});var jq=ge(function(b2e,Bq){var Lq=qr("fs"),mpe=(e)=>Lq.readFileSync(e,"utf-8"),hpe=(e)=>new Promise((t,r)=>{Lq.readFile(e,"utf-8",(o,n)=>{if(o)r(o);else t(n)})});Bq.exports={LDD_PATH:"/usr/bin/ldd",readFileSync:mpe,readFile:hpe}});var r4=ge(function(S2e,t4){var Uq=qr("child_process"),{isLinux:dl,getReport:Mq}=Dq(),{LDD_PATH:wy,readFile:qq,readFileSync:Fq}=jq(),Xn,eo,Ji="",Kq=()=>{if(!Ji)return new Promise((e)=>{Uq.exec("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",(t,r)=>{Ji=t?" ":r,e(Ji)})});return Ji},Jq=()=>{if(!Ji)try{Ji=Uq.execSync("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",{encoding:"utf8"})}catch(e){Ji=" "}return Ji},Lo="glibc",Hq=/GLIBC\s(\d+\.\d+)/,aa="musl",gpe=Lo.toUpperCase(),ype=aa.toLowerCase(),bpe=(e)=>e.includes("libc.musl-")||e.includes("ld-musl-"),Vq=()=>{let e=Mq();if(e.header&&e.header.glibcVersionRuntime)return Lo;if(Array.isArray(e.sharedObjects)){if(e.sharedObjects.some(bpe))return aa}return null},Wq=(e)=>{let[t,r]=e.split(/[\r\n]+/);if(t&&t.includes(Lo))return Lo;if(r&&r.includes(aa))return aa;return null},Gq=(e)=>{if(e.includes(ype))return aa;if(e.includes(gpe))return Lo;return null},Spe=async()=>{if(Xn!==void 0)return Xn;Xn=null;try{let e=await qq(wy);Xn=Gq(e)}catch(e){}return Xn},vpe=()=>{if(Xn!==void 0)return Xn;Xn=null;try{let e=Fq(wy);Xn=Gq(e)}catch(e){}return Xn},Qq=async()=>{let e=null;if(dl()){if(e=await Spe(),!e)e=Vq();if(!e){let t=await Kq();e=Wq(t)}}return e},Yq=()=>{let e=null;if(dl()){if(e=vpe(),!e)e=Vq();if(!e){let t=Jq();e=Wq(t)}}return e},wpe=async()=>dl()&&await Qq()!==Lo,xpe=()=>dl()&&Yq()!==Lo,_pe=async()=>{if(eo!==void 0)return eo;eo=null;try{let t=(await qq(wy)).match(Hq);if(t)eo=t[1]}catch(e){}return eo},Epe=()=>{if(eo!==void 0)return eo;eo=null;try{let t=Fq(wy).match(Hq);if(t)eo=t[1]}catch(e){}return eo},Xq=()=>{let e=Mq();if(e.header&&e.header.glibcVersionRuntime)return e.header.glibcVersionRuntime;return null},Zq=(e)=>e.trim().split(/\s+/)[1],e4=(e)=>{let[t,r,o]=e.split(/[\r\n]+/);if(t&&t.includes(Lo))return Zq(t);if(r&&o&&r.includes(aa))return Zq(o);return null},kpe=async()=>{let e=null;if(dl()){if(e=await _pe(),!e)e=Xq();if(!e){let t=await Kq();e=e4(t)}}return e},Ipe=()=>{let e=null;if(dl()){if(e=Epe(),!e)e=Xq();if(!e){let t=Jq();e=e4(t)}}return e};t4.exports={GLIBC:Lo,MUSL:aa,family:Qq,familySync:Yq,isNonGlibcLinux:wpe,isNonGlibcLinuxSync:xpe,version:kpe,versionSync:Ipe}});var o4=ge(function(v2e,n4){var Ape={ALLOW:0,DENY:1};n4.exports=Ape});var s4=ge(function(w2e,i4){var BR={value:"SqliteError",writable:!0,enumerable:!1,configurable:!0};function ca(e,t,r){if(new.target!==ca)return new ca(e,t);if(typeof t!=="string")throw TypeError("Expected second argument to be a string");Error.call(this,e),BR.value=""+e,Object.defineProperty(this,"message",BR),Error.captureStackTrace(this,ca),this.code=t,this.rawCode=r}Object.setPrototypeOf(ca,Error);Object.setPrototypeOf(ca.prototype,Error.prototype);Object.defineProperty(ca.prototype,"name",BR);i4.exports=ca});var m4=ge(function(x2e,xy){var __dirname="/home/runner/work/brains/brains/node_modules/libsql",{load:Rpe,currentTarget:Tpe}=Pq(),{familySync:a4,GLIBC:$pe,MUSL:Ope}=r4();function Cpe(){if(process.env.LIBSQL_JS_DEV)return Rpe(__dirname);let e=Tpe();if(a4()==$pe)switch(e){case"linux-x64-musl":e="linux-x64-gnu";break;case"linux-arm64-musl":e="linux-arm64-gnu";break}if(e==="linux-arm-gnueabihf"&&a4()==Ope)e="linux-arm-musleabihf";return qr(`@libsql/${e}`)}var{databaseOpen:Ppe,databaseOpenWithSync:zpe,databaseInTransaction:Npe,databaseInterrupt:Dpe,databaseClose:Lpe,databaseSyncSync:Bpe,databaseSyncUntilSync:jpe,databaseExecSync:Zpe,databasePrepareSync:Upe,databaseDefaultSafeIntegers:Mpe,databaseAuthorizer:qpe,databaseLoadExtension:Fpe,databaseMaxWriteReplicationIndex:Kpe,statementRaw:Jpe,statementIsReader:Hpe,statementGet:c4,statementRun:l4,statementInterrupt:Vpe,statementRowsSync:u4,statementColumns:Wpe,statementSafeIntegers:Gpe,rowsNext:Qpe}=Cpe(),Ype=o4(),d4=s4();function pl(e){if(e.libsqlError)return new d4(e.message,e.code,e.rawCode);return e}class p4{constructor(e,t){let r=t?.encryptionCipher??"aes256cbc";if(t&&t.syncUrl){var o="";if(t.syncAuth)console.warn("Warning: The `syncAuth` option is deprecated, please use `authToken` option instead."),o=t.syncAuth;else if(t.authToken)o=t.authToken;let i=t?.encryptionKey??"",s=t?.syncPeriod??0,a=t?.readYourWrites??!0,l=t?.offline??!1,u=t?.remoteEncryptionKey??"";this.db=zpe(e,t.syncUrl,o,r,i,s,a,l,u)}else{let i=t?.authToken??"",s=t?.encryptionKey??"",a=t?.timeout??0,l=t?.remoteEncryptionKey??"";this.db=Ppe(e,i,r,s,a,l)}this.memory=e===":memory:",this.readonly=!1,this.name="",this.open=!0;let n=this.db;Object.defineProperties(this,{inTransaction:{get(){return Npe(n)}}})}sync(){return Bpe.call(this.db)}syncUntil(e){return jpe.call(this.db,e)}prepare(e){try{let t=Upe.call(this.db,e);return new f4(t)}catch(t){throw pl(t)}}transaction(e){if(typeof e!=="function")throw TypeError("Expected first argument to be a function");let t=this,r=(n)=>(...i)=>{t.exec("BEGIN "+n);try{let s=e(...i);return t.exec("COMMIT"),s}catch(s){throw t.exec("ROLLBACK"),s}},o={default:{value:r("")},deferred:{value:r("DEFERRED")},immediate:{value:r("IMMEDIATE")},exclusive:{value:r("EXCLUSIVE")},database:{value:this,enumerable:!0}};return Object.defineProperties(o.default.value,o),Object.defineProperties(o.deferred.value,o),Object.defineProperties(o.immediate.value,o),Object.defineProperties(o.exclusive.value,o),o.default.value}pragma(e,t){if(t==null)t={};if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof t!=="object")throw TypeError("Expected second argument to be an options object");let r=t.simple,o=this.prepare(`PRAGMA ${e}`,this,!0);return r?o.pluck().get():o.all()}backup(e,t){throw Error("not implemented")}serialize(e){throw Error("not implemented")}function(e,t,r){if(t==null)t={};if(typeof t==="function")r=t,t={};if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof r!=="function")throw TypeError("Expected last argument to be a function");if(typeof t!=="object")throw TypeError("Expected second argument to be an options object");if(!e)throw TypeError("User-defined function name cannot be an empty string");throw Error("not implemented")}aggregate(e,t){if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof t!=="object"||t===null)throw TypeError("Expected second argument to be an options object");if(!e)throw TypeError("User-defined function name cannot be an empty string");throw Error("not implemented")}table(e,t){if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(!e)throw TypeError("Virtual table module name cannot be an empty string");throw Error("not implemented")}authorizer(e){qpe.call(this.db,e)}loadExtension(...e){Fpe.call(this.db,...e)}maxWriteReplicationIndex(){return Kpe.call(this.db)}exec(e){try{Zpe.call(this.db,e)}catch(t){throw pl(t)}}interrupt(){Dpe.call(this.db)}close(){Lpe.call(this.db),this.open=!1}defaultSafeIntegers(e){return Mpe.call(this.db,e??!0),this}unsafeMode(...e){throw Error("not implemented")}}class f4{constructor(e){this.stmt=e,this.pluckMode=!1}raw(e){return Jpe.call(this.stmt,e??!0),this}pluck(e){return this.pluckMode=e??!0,this}get reader(){return Hpe.call(this.stmt)}run(...e){try{if(e.length==1&&typeof e[0]==="object")return l4.call(this.stmt,e[0]);else return l4.call(this.stmt,e.flat())}catch(t){throw pl(t)}}get(...e){try{if(e.length==1&&typeof e[0]==="object")return c4.call(this.stmt,e[0]);else return c4.call(this.stmt,e.flat())}catch(t){throw pl(t)}}iterate(...e){var t=void 0;if(e.length==1&&typeof e[0]==="object")t=u4.call(this.stmt,e[0]);else t=u4.call(this.stmt,e.flat());return{nextRows:Array(100),nextRowIndex:100,next(){try{if(this.nextRowIndex===100)Qpe.call(t,this.nextRows),this.nextRowIndex=0;let o=this.nextRows[this.nextRowIndex];if(this.nextRows[this.nextRowIndex]=void 0,!o)return{done:!0};return this.nextRowIndex++,{value:o,done:!1}}catch(o){throw pl(o)}},[Symbol.iterator](){return this}}}all(...e){try{let t=[];for(let r of this.iterate(...e))if(this.pluckMode)t.push(r[Object.keys(r)[0]]);else t.push(r);return t}catch(t){throw pl(t)}}interrupt(){Vpe.call(this.stmt)}columns(){return Wpe.call(this.stmt)}safeIntegers(e){return Gpe.call(this.stmt,e??!0),this}}xy.exports=p4;xy.exports.Authorization=Ype;xy.exports.SqliteError=d4});import{Buffer as g4}from"buffer";function y4(e){if(e.scheme!=="file")throw new Ce(`URL scheme ${JSON.stringify(e.scheme+":")} is not supported by the local sqlite3 client. For more information, please read ${Yn}`,"URL_SCHEME_NOT_SUPPORTED");let t=e.authority;if(t!==void 0){let s=t.host.toLowerCase();if(s!==""&&s!=="localhost")throw new Ce(`Invalid host in file URL: ${JSON.stringify(t.host)}. A "file:" URL with an absolute path should start with one slash ("file:/absolute/path.db") or with three slashes ("file:///absolute/path.db"). For more information, please read ${Yn}`,"URL_INVALID");if(t.port!==void 0)throw new Ce("File URL cannot have a port","URL_INVALID");if(t.userinfo!==void 0)throw new Ce("File URL cannot have username and password","URL_INVALID")}let r=Oq(e);if(r&&e.syncUrl)throw new Ce(`Embedded replica must use file for local db but URI with in-memory mode were provided instead: ${e.path}`,"URL_INVALID");let o=e.path;if(r)o=`${e.scheme}:${e.path}`;let n={authToken:e.authToken,encryptionKey:e.encryptionKey,remoteEncryptionKey:e.remoteEncryptionKey,syncUrl:e.syncUrl,syncPeriod:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,timeout:e.timeout},i=new hp.default(o,n);return zt(i,"SELECT 1 AS checkThatTheDatabaseCanBeOpened",e.intMode),new b4(o,n,i,e.intMode)}class b4{#e;#t;#r;#n;closed;protocol;constructor(e,t,r,o){this.#e=e,this.#t=t,this.#r=r,this.#n=o,this.closed=!1,this.protocol="file"}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.#o(),zt(this.#i(),r,this.#n)}async batch(e,t="deferred"){this.#o();let r=this.#i();try{zt(r,Ki(t),this.#n);let o=[];for(let n=0;n<e.length;n++)try{if(!r.inTransaction)throw new Wt("The transaction has been rolled back",n,"TRANSACTION_CLOSED");let i=e[n],s=Array.isArray(i)?{sql:i[0],args:i[1]||[]}:i;o.push(zt(r,s,this.#n))}catch(i){if(i instanceof Wt)throw i;if(i instanceof Ce)throw new Wt(i.message,n,i.code,i.extendedCode,i.rawCode,i.cause instanceof Error?i.cause:void 0);throw i}return zt(r,"COMMIT",this.#n),o}finally{if(r.inTransaction)zt(r,"ROLLBACK",this.#n)}}async migrate(e){this.#o();let t=this.#i();try{zt(t,"PRAGMA foreign_keys=off",this.#n),zt(t,Ki("deferred"),this.#n);let r=[];for(let o=0;o<e.length;o++)try{if(!t.inTransaction)throw new Wt("The transaction has been rolled back",o,"TRANSACTION_CLOSED");r.push(zt(t,e[o],this.#n))}catch(n){if(n instanceof Wt)throw n;if(n instanceof Ce)throw new Wt(n.message,o,n.code,n.extendedCode,n.rawCode,n.cause instanceof Error?n.cause:void 0);throw n}return zt(t,"COMMIT",this.#n),r}finally{if(t.inTransaction)zt(t,"ROLLBACK",this.#n);zt(t,"PRAGMA foreign_keys=on",this.#n)}}async transaction(e="write"){let t=this.#i();return zt(t,Ki(e),this.#n),this.#r=null,new S4(t,this.#n)}async executeMultiple(e){this.#o();let t=this.#i();try{return v4(t,e)}finally{if(t.inTransaction)zt(t,"ROLLBACK",this.#n)}}async sync(){this.#o();let e=await this.#i().sync();return{frames_synced:e.frames_synced,frame_no:e.frame_no}}async reconnect(){try{if(!this.closed&&this.#r!==null)this.#r.close()}finally{this.#r=new hp.default(this.#e,this.#t),this.closed=!1}}close(){if(this.closed=!0,this.#r!==null)this.#r.close(),this.#r=null}#o(){if(this.closed)throw new Ce("The client is closed","CLIENT_CLOSED")}#i(){if(this.#r===null)this.#r=new hp.default(this.#e,this.#t);return this.#r}}class S4{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.#r(),zt(this.#e,r,this.#t)}async batch(e){let t=[];for(let r=0;r<e.length;r++)try{this.#r();let o=e[r],n=Array.isArray(o)?{sql:o[0],args:o[1]||[]}:o;t.push(zt(this.#e,n,this.#t))}catch(o){if(o instanceof Wt)throw o;if(o instanceof Ce)throw new Wt(o.message,r,o.code,o.extendedCode,o.rawCode,o.cause instanceof Error?o.cause:void 0);throw o}return t}async executeMultiple(e){return this.#r(),v4(this.#e,e)}async rollback(){if(!this.#e.open)return;this.#r(),zt(this.#e,"ROLLBACK",this.#t)}async commit(){this.#r(),zt(this.#e,"COMMIT",this.#t)}close(){if(this.#e.inTransaction)zt(this.#e,"ROLLBACK",this.#t)}get closed(){return!this.#e.inTransaction}#r(){if(this.closed)throw new Ce("The transaction is closed","TRANSACTION_CLOSED")}}function zt(e,t,r){let o,n;if(typeof t==="string")o=t,n=[];else if(o=t.sql,Array.isArray(t.args))n=t.args.map((i)=>h4(i,r));else{n={};for(let i in t.args){let s=i[0]==="@"||i[0]==="$"||i[0]===":"?i.substring(1):i;n[s]=h4(t.args[i],r)}}try{let i=e.prepare(o);i.safeIntegers(!0);let s=!0;try{i.raw(!0)}catch{s=!1}if(s){let a=Array.from(i.columns().map((m)=>m.name)),l=Array.from(i.columns().map((m)=>m.type??"")),u=i.all(n).map((m)=>Xpe(m,a,r)),d=0,p=void 0;return new ll(a,l,u,0,void 0)}else{let a=i.run(n),l=a.changes,u=BigInt(a.lastInsertRowid);return new ll([],[],[],l,u)}}catch(i){throw w4(i)}}function Xpe(e,t,r){let o={};Object.defineProperty(o,"length",{value:e.length});for(let n=0;n<e.length;++n){let i=efe(e[n],r);Object.defineProperty(o,n,{value:i});let s=t[n];if(!Object.hasOwn(o,s))Object.defineProperty(o,s,{value:i,enumerable:!0,configurable:!0,writable:!0})}return o}function efe(e,t){if(typeof e==="bigint")if(t==="number"){if(e<tfe||e>rfe)throw RangeError("Received integer which cannot be safely represented as a JavaScript number");return Number(e)}else if(t==="bigint")return e;else if(t==="string")return""+e;else throw Error("Invalid value for IntMode");else if(e instanceof g4)return e.buffer;return e}function h4(e,t){if(typeof e==="number"){if(!Number.isFinite(e))throw RangeError("Only finite numbers (not Infinity or NaN) can be passed as arguments");return e}else if(typeof e==="bigint"){if(e<nfe||e>ofe)throw RangeError("bigint is too large to be represented as a 64-bit integer and passed as argument");return e}else if(typeof e==="boolean")switch(t){case"bigint":return e?1n:0n;case"string":return e?"1":"0";default:return e?1:0}else if(e instanceof ArrayBuffer)return g4.from(e);else if(e instanceof Date)return e.valueOf();else if(e===void 0)throw TypeError("undefined cannot be passed as argument to the database");else return e}function v4(e,t){try{e.exec(t)}catch(r){throw w4(r)}}function w4(e){if(e instanceof hp.default.SqliteError){let t=e.code,r=ife(e.rawCode);return new Ce(e.message,r,t,e.rawCode,e)}return e}function ife(e){if(e===void 0)return"SQLITE_UNKNOWN";let t=e&255;return sfe[t]??`SQLITE_UNKNOWN_${t.toString()}`}var hp,tfe,rfe=9007199254740991n,nfe,ofe=9223372036854775807n,sfe;var x4=v(()=>{vn();mp();ul();hp=Ml(m4(),1);vn();tfe=-9007199254740991n;nfe=-9223372036854775808n;sfe={1:"SQLITE_ERROR",2:"SQLITE_INTERNAL",3:"SQLITE_PERM",4:"SQLITE_ABORT",5:"SQLITE_BUSY",6:"SQLITE_LOCKED",7:"SQLITE_NOMEM",8:"SQLITE_READONLY",9:"SQLITE_INTERRUPT",10:"SQLITE_IOERR",11:"SQLITE_CORRUPT",12:"SQLITE_NOTFOUND",13:"SQLITE_FULL",14:"SQLITE_CANTOPEN",15:"SQLITE_PROTOCOL",16:"SQLITE_EMPTY",17:"SQLITE_SCHEMA",18:"SQLITE_TOOBIG",19:"SQLITE_CONSTRAINT",20:"SQLITE_MISMATCH",21:"SQLITE_MISUSE",22:"SQLITE_NOLFS",23:"SQLITE_AUTH",24:"SQLITE_FORMAT",25:"SQLITE_RANGE",26:"SQLITE_NOTADB",27:"SQLITE_NOTICE",28:"SQLITE_WARNING"}});var Hi;var jR=v(()=>{if(typeof WebSocket<"u")Hi=WebSocket;else if(typeof global<"u")Hi=global.WebSocket;else if(typeof window<"u")Hi=window.WebSocket;else if(typeof self<"u")Hi=self.WebSocket});class fl{constructor(){this.intMode="number"}intMode}var Ge,Pe,gp,xt,yp,ml,la,wn,or,to;var _t=v(()=>{Ge=class Ge extends Error{constructor(e){super(e);this.name="ClientError"}};Pe=class Pe extends Ge{constructor(e){super(e);this.name="ProtoError"}};gp=class gp extends Ge{code;proto;constructor(e,t){super(e);this.name="ResponseError",this.code=t.code,this.proto=t,this.stack=void 0}};xt=class xt extends Ge{constructor(e,t){if(t!==void 0){super(`${e}: ${t}`);this.cause=t}else super(e);this.name="ClosedError"}};yp=class yp extends Ge{constructor(e){super(e);this.name="WebSocketUnsupportedError"}};ml=class ml extends Ge{constructor(e){super(e);this.name="WebSocketError"}};la=class la extends Ge{status;constructor(e,t){super(e);this.status=t,this.name="HttpServerError"}};wn=class wn extends Ge{constructor(e){super(e);this.name="ProtocolVersionError"}};or=class or extends Ge{constructor(e){super(e);this.name="InternalError"}};to=class to extends Ge{constructor(e){super(e);this.name="MisuseError"}}});function Rr(e){if(typeof e==="string")return e;throw hl(e,"string")}function Zr(e){if(e===null||e===void 0)return;else if(typeof e==="string")return e;throw hl(e,"string or null")}function Bo(e){if(typeof e==="number")return e;throw hl(e,"number")}function Vi(e){if(typeof e==="boolean")return e;throw hl(e,"boolean")}function bp(e){if(Array.isArray(e))return e;throw hl(e,"array")}function It(e){if(e!==null&&typeof e==="object"&&!Array.isArray(e))return e;throw hl(e,"object")}function xn(e,t){return bp(e).map((r)=>t(It(r)))}function hl(e,t){if(e===void 0)return new Pe(`Expected ${t}, but the property was missing`);let r=typeof e;if(e===null)r="null";else if(Array.isArray(e))r="array";return new Pe(`Expected ${t}, received ${r}`)}function ua(e,t){return t(It(e))}var gl=v(()=>{_t()});class _4{#e;#t;constructor(e){this.#e=e,this.#t=!1}begin(){this.#e.push("{"),this.#t=!0}end(){this.#e.push("}"),this.#t=!1}#r(e){if(this.#t)this.#e.push('"'),this.#t=!1;else this.#e.push(',"');this.#e.push(e),this.#e.push('":')}string(e,t){this.#r(e),this.#e.push(JSON.stringify(t))}stringRaw(e,t){this.#r(e),this.#e.push('"'),this.#e.push(t),this.#e.push('"')}number(e,t){this.#r(e),this.#e.push(""+t)}boolean(e,t){this.#r(e),this.#e.push(t?"true":"false")}object(e,t,r){this.#r(e),this.begin(),r(this,t),this.end()}arrayObjects(e,t,r){this.#r(e),this.#e.push("[");for(let o=0;o<t.length;++o){if(o!==0)this.#e.push(",");this.begin(),r(this,t[o]),this.end()}this.#e.push("]")}}function Sp(e,t){let r=[],o=new _4(r);return o.begin(),t(o,e),o.end(),r.join("")}var da=0,vp=1,wp=2,E4=5;class k4{#e;#t;#r;constructor(e){this.#e=e,this.#t=new DataView(e.buffer,e.byteOffset,e.byteLength),this.#r=0}varint(){let e=0;for(let t=0;;t+=7){let r=this.#e[this.#r++];if(e|=(r&127)<<t,!(r&128))break}return e}varintBig(){let e=0n;for(let t=0n;;t+=7n){let r=this.#e[this.#r++];if(e|=BigInt(r&127)<<t,!(r&128))break}return e}bytes(e){let t=new Uint8Array(this.#e.buffer,this.#e.byteOffset+this.#r,e);return this.#r+=e,t}double(){let e=this.#t.getFloat64(this.#r,!0);return this.#r+=8,e}skipVarint(){for(;;)if(!(this.#e[this.#r++]&128))break}skip(e){this.#r+=e}eof(){return this.#r>=this.#e.byteLength}}class I4{#e;#t;constructor(e){this.#e=e,this.#t=-1}setup(e){this.#t=e}#r(e){if(this.#t!==e)throw new Pe(`Expected wire type ${e}, got ${this.#t}`);this.#t=-1}bytes(){this.#r(wp);let e=this.#e.varint();return this.#e.bytes(e)}string(){return new TextDecoder().decode(this.bytes())}message(e){return Wi(this.bytes(),e)}int32(){return this.#r(da),this.#e.varint()}uint32(){return this.int32()}bool(){return this.int32()!==0}uint64(){return this.#r(da),this.#e.varintBig()}sint64(){let e=this.uint64();return e>>1n^-(e&1n)}double(){return this.#r(vp),this.#e.double()}maybeSkip(){if(this.#t<0)return;else if(this.#t===da)this.#e.skipVarint();else if(this.#t===vp)this.#e.skip(8);else if(this.#t===wp){let e=this.#e.varint();this.#e.skip(e)}else if(this.#t===E4)this.#e.skip(4);else throw new Pe(`Unexpected wire type ${this.#t}`);this.#t=-1}}function Wi(e,t){let r=new k4(e),o=new I4(r),n=t.default();while(!r.eof()){let i=r.varint(),s=i>>3,a=i&7;o.setup(a);let l=t[s];if(l!==void 0){let u=l(o,n);if(u!==void 0)n=u}o.maybeSkip()}return n}var ZR=v(()=>{_t()});class UR{#e;#t;#r;#n;constructor(){this.#e=new ArrayBuffer(256),this.#t=new Uint8Array(this.#e),this.#r=new DataView(this.#e),this.#n=0}#o(e){if(this.#n+e<=this.#e.byteLength)return;let t=this.#e.byteLength;while(t<this.#n+e)t*=2;let r=new ArrayBuffer(t),o=new Uint8Array(r),n=new DataView(r);o.set(new Uint8Array(this.#e,0,this.#n)),this.#e=r,this.#t=o,this.#r=n}#i(e){this.#o(5),e=0|e;do{let t=e&127;e>>>=7,t|=e?128:0,this.#t[this.#n++]=t}while(e)}#a(e){this.#o(10),e=e&0xffffffffffffffffn;do{let t=Number(e&0x7fn);e>>=7n,t|=e?128:0,this.#t[this.#n++]=t}while(e)}#s(e,t){this.#i(e<<3|t)}bytes(e,t){this.#s(e,wp),this.#i(t.byteLength),this.#o(t.byteLength),this.#t.set(t,this.#n),this.#n+=t.byteLength}string(e,t){this.bytes(e,new TextEncoder().encode(t))}message(e,t,r){let o=new UR;r(o,t),this.bytes(e,o.data())}int32(e,t){this.#s(e,da),this.#i(t)}uint32(e,t){this.int32(e,t)}bool(e,t){this.int32(e,t?1:0)}sint64(e,t){this.#s(e,da),this.#a(t<<1n^t>>63n)}double(e,t){this.#s(e,vp),this.#o(8),this.#r.setFloat64(this.#n,t,!0),this.#n+=8}data(){return new Uint8Array(this.#e,0,this.#n)}}function xp(e,t){let r=new UR;return t(r,e),r.data()}var A4=()=>{};var MR=v(()=>{gl();ZR();A4()});class Gi{#e;#t;constructor(){this.#e=new Set,this.#t=new Set}alloc(){for(let t of this.#t){if(this.#t.delete(t),this.#e.add(t),!this.#e.has(this.#e.size-1))this.#t.add(this.#e.size-1);return t}let e=this.#e.size;return this.#e.add(e),e}free(e){if(!this.#e.delete(e))throw new or("Freeing an id that is not allocated");if(this.#t.delete(this.#e.size),e<this.#e.size)this.#t.add(e)}}var qR=v(()=>{_t()});function Je(e,t){throw new or(t)}var rn=v(()=>{_t()});function yl(e){if(e===null)return null;else if(typeof e==="string")return e;else if(typeof e==="number"){if(!Number.isFinite(e))throw RangeError("Only finite numbers (not Infinity or NaN) can be passed as arguments");return e}else if(typeof e==="bigint"){if(e<cfe||e>lfe)throw RangeError("This bigint value is too large to be represented as a 64-bit integer and passed as argument");return e}else if(typeof e==="boolean")return e?1n:0n;else if(e instanceof ArrayBuffer)return new Uint8Array(e);else if(e instanceof Uint8Array)return e;else if(e instanceof Date)return+e.valueOf();else if(typeof e==="object")return""+e.toString();else throw TypeError("Unsupported type of value")}function FR(e,t){if(e===null)return null;else if(typeof e==="number")return e;else if(typeof e==="string")return e;else if(typeof e==="bigint")if(t==="number"){let r=Number(e);if(!Number.isSafeInteger(r))throw RangeError("Received integer which is too large to be safely represented as a JavaScript number");return r}else if(t==="bigint")return e;else if(t==="string")return""+e;else throw new to("Invalid value for IntMode");else if(e instanceof Uint8Array)return e.slice().buffer;else if(e===void 0)throw new Pe("Received unrecognized type of Value");else throw Je(e,"Impossible type of Value")}var cfe,lfe=9223372036854775807n;var KR=v(()=>{_t();rn();cfe=-9223372036854775808n});function pa(e){return{affectedRowCount:e.affectedRowCount,lastInsertRowid:e.lastInsertRowid,columnNames:e.cols.map((t)=>t.name),columnDecltypes:e.cols.map((t)=>t.decltype)}}function Ey(e,t){let r=pa(e),o=e.rows.map((n)=>R4(r.columnNames,n,t));return{...r,rows:o}}function ky(e,t){let r=pa(e),o;if(e.rows.length>0)o=R4(r.columnNames,e.rows[0],t);return{...r,row:o}}function Iy(e,t){let r=pa(e),o;if(e.rows.length>0&&r.columnNames.length>0)o=FR(e.rows[0][0],t);return{...r,value:o}}function R4(e,t,r){let o={};Object.defineProperty(o,"length",{value:t.length});for(let n=0;n<t.length;++n){let i=FR(t[n],r);Object.defineProperty(o,n,{value:i});let s=e[n];if(s!==void 0&&!Object.hasOwn(o,s))Object.defineProperty(o,s,{value:i,enumerable:!0,configurable:!0,writable:!0})}return o}function jo(e){return new gp(e.message,e)}var _p=v(()=>{_t();KR()});class fa{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}_getSqlId(e){if(this.#e!==e)throw new to("Attempted to use SQL text opened with other object");else if(this.#r!==void 0)throw new xt("SQL text is closed",this.#r);return this.#t}close(){this._setClosed(new Ge("SQL text was manually closed"))}_setClosed(e){if(this.#r===void 0)this.#r=e,this.#e._closeSql(this.#t)}get closed(){return this.#r!==void 0}}function Ep(e,t){if(t instanceof fa)return{sqlId:t._getSqlId(e)};else return{sql:""+t}}var bl=v(()=>{_t()});class Qi{#e;#t;constructor(){this.#e=[],this.#t=[]}get length(){return this.#e.length+this.#t.length}push(e){this.#e.push(e)}shift(){if(this.#t.length===0&&this.#e.length>0)this.#t=this.#e.reverse(),this.#e=[];return this.#t.pop()}first(){return this.#t.length!==0?this.#t[this.#t.length-1]:this.#e[0]}}class kp{sql;_args;_namedArgs;constructor(e){this.sql=e,this._args=[],this._namedArgs=new Map}bindIndexes(e){this._args.length=0;for(let t of e)this._args.push(yl(t));return this}bindIndex(e,t){if(e!==(e|0)||e<=0)throw RangeError("Index of a positional argument must be positive integer");while(this._args.length<e)this._args.push(null);return this._args[e-1]=yl(t),this}bindName(e,t){return this._namedArgs.set(e,yl(t)),this}unbindAll(){return this._args.length=0,this._namedArgs.clear(),this}}function Ay(e,t,r){let o,n=[],i=[];if(t instanceof kp){o=t.sql,n=t._args;for(let[l,u]of t._namedArgs.entries())i.push({name:l,value:u})}else if(Array.isArray(t))if(o=t[0],Array.isArray(t[1]))n=t[1].map((l)=>yl(l));else i=Object.entries(t[1]).map(([l,u])=>({name:l,value:yl(u)}));else o=t;let{sql:s,sqlId:a}=Ep(e,o);return{sql:s,sqlId:a,args:n,namedArgs:i,wantRows:r}}var Ry=v(()=>{bl();KR()});class Ty{_stream;#e;_steps;#t;constructor(e,t){this._stream=e,this.#e=t,this._steps=[],this.#t=!1}step(){return new JR(this)}execute(){if(this.#t)throw new to("This batch has already been executed");this.#t=!0;let e={steps:this._steps.map((t)=>t.proto)};if(this.#e)return dfe(this._stream,this._steps,e);else return ufe(this._stream,this._steps,e)}}function ufe(e,t,r){return e._batch(r).then((o)=>{for(let n=0;n<t.length;++n){let i=o.stepResults.get(n),s=o.stepErrors.get(n);t[n].callback(i,s)}})}async function dfe(e,t,r){let o=await e._openCursor(r);try{let n=0,i=void 0,s=[];for(;;){let a=await o.next();if(a===void 0)break;if(a.type==="step_begin"){if(a.step<n||a.step>=t.length)throw new Pe("Server produced StepBeginEntry for unexpected step");else if(i!==void 0)throw new Pe("Server produced StepBeginEntry before terminating previous step");for(let l=n;l<a.step;++l)t[l].callback(void 0,void 0);n=a.step+1,i=a,s=[]}else if(a.type==="step_end"){if(i===void 0)throw new Pe("Server produced StepEndEntry but no step is active");let l={cols:i.cols,rows:s,affectedRowCount:a.affectedRowCount,lastInsertRowid:a.lastInsertRowid};t[i.step].callback(l,void 0),i=void 0,s=[]}else if(a.type==="step_error"){if(i===void 0){if(a.step>=t.length)throw new Pe("Server produced StepErrorEntry for unexpected step");for(let l=n;l<a.step;++l)t[l].callback(void 0,void 0)}else{if(a.step!==i.step)throw new Pe("Server produced StepErrorEntry for unexpected step");i=void 0,s=[]}t[a.step].callback(void 0,a.error),n=a.step+1}else if(a.type==="row"){if(i===void 0)throw new Pe("Server produced RowEntry but no step is active");s.push(a.row)}else if(a.type==="error")throw jo(a.error);else if(a.type==="none")throw new Pe("Server produced unrecognized CursorEntry");else throw Je(a,"Impossible CursorEntry")}if(i!==void 0)throw new Pe("Server closed Cursor before terminating active step");for(let a=n;a<t.length;++a)t[a].callback(void 0,void 0)}finally{o.close()}}class JR{_batch;#e;_index;constructor(e){this._batch=e,this.#e=[],this._index=void 0}condition(e){return this.#e.push(e._proto),this}query(e){return this.#t(e,!0,Ey)}queryRow(e){return this.#t(e,!0,ky)}queryValue(e){return this.#t(e,!0,Iy)}run(e){return this.#t(e,!1,pa)}#t(e,t,r){if(this._index!==void 0)throw new to("This BatchStep has already been added to the batch");let o=Ay(this._batch._stream._sqlOwner(),e,t),n;if(this.#e.length===0)n=void 0;else if(this.#e.length===1)n=this.#e[0];else n={type:"and",conds:this.#e.slice()};let i={stmt:o,condition:n};return new Promise((s,a)=>{let l=(u,d)=>{if(u!==void 0&&d!==void 0)a(new Pe("Server returned both result and error"));else if(d!==void 0)a(jo(d));else if(u!==void 0)s(r(u,this._batch._stream.intMode));else s(void 0)};this._index=this._batch._steps.length,this._batch._steps.push({proto:i,callback:l})})}}class ut{_batch;_proto;constructor(e,t){this._batch=e,this._proto=t}static ok(e){return new ut(e._batch,{type:"ok",step:T4(e)})}static error(e){return new ut(e._batch,{type:"error",step:T4(e)})}static not(e){return new ut(e._batch,{type:"not",cond:e._proto})}static and(e,t){for(let r of t)$4(e,r);return new ut(e,{type:"and",conds:t.map((r)=>r._proto)})}static or(e,t){for(let r of t)$4(e,r);return new ut(e,{type:"or",conds:t.map((r)=>r._proto)})}static isAutocommit(e){return e._stream.client()._ensureVersion(3,"BatchCond.isAutocommit()"),new ut(e,{type:"is_autocommit"})}}function T4(e){if(e._index===void 0)throw new to("Cannot add a condition referencing a step that has not been added to the batch");return e._index}function $4(e,t){if(t._batch!==e)throw new to("Cannot mix BatchCond objects for different Batch objects")}var HR=v(()=>{_t();_p();Ry();rn()});function O4(e){return{paramNames:e.params.map((t)=>t.name),columns:e.cols,isExplain:e.isExplain,isReadonly:e.isReadonly}}class Sl{constructor(e){this.intMode=e}query(e){return this.#e(e,!0,Ey)}queryRow(e){return this.#e(e,!0,ky)}queryValue(e){return this.#e(e,!0,Iy)}run(e){return this.#e(e,!1,pa)}#e(e,t,r){let o=Ay(this._sqlOwner(),e,t);return this._execute(o).then((n)=>r(n,this.intMode))}batch(e=!1){return new Ty(this,e)}describe(e){let t=Ep(this._sqlOwner(),e);return this._describe(t).then(O4)}sequence(e){let t=Ep(this._sqlOwner(),e);return this._sequence(t)}intMode}var $y=v(()=>{HR();_p();bl();Ry()});class Ip{}var pfe=1000,ffe=10,VR;var C4=v(()=>{_t();VR=class VR extends Ip{#e;#t;#r;#n;#o;#i;#a;constructor(e,t,r){super();this.#e=e,this.#t=t,this.#r=r,this.#n=new Qi,this.#o=new Qi,this.#i=void 0,this.#a=!1}async next(){for(;;){if(this.#i!==void 0)throw new xt("Cursor is closed",this.#i);while(!this.#a&&this.#o.length<ffe)this.#o.push(this.#s());let e=this.#n.shift();if(this.#a||e!==void 0)return e;await this.#o.shift().then((t)=>{if(t===void 0)return;for(let r of t.entries)this.#n.push(r);this.#a||=t.done})}}#s(){return this.#t._sendCursorRequest(this,{type:"fetch_cursor",cursorId:this.#r,maxCount:pfe}).then((e)=>e,(e)=>{this._setClosed(e);return})}_setClosed(e){if(this.#i!==void 0)return;this.#i=e,this.#t._sendCursorRequest(this,{type:"close_cursor",cursorId:this.#r}).catch(()=>{return}),this.#t._cursorClosed(this)}close(){this._setClosed(new Ge("Cursor was manually closed"))}get closed(){return this.#i!==void 0}}});var Ap;var WR=v(()=>{_t();$y();C4();Ap=class Ap extends Sl{#e;#t;#r;#n;#o;#i;static open(e){let t=e._streamIdAlloc.alloc(),r=new Ap(e,t),o=()=>{return},n=(s)=>r.#l(s),i={type:"open_stream",streamId:t};return e._sendRequest(i,{responseCallback:o,errorCallback:n}),r}constructor(e,t){super(e.intMode);this.#e=e,this.#t=t,this.#r=new Qi,this.#n=void 0,this.#o=!1,this.#i=void 0}client(){return this.#e}_sqlOwner(){return this.#e}_execute(e){return this.#a({type:"execute",streamId:this.#t,stmt:e}).then((t)=>t.result)}_batch(e){return this.#a({type:"batch",streamId:this.#t,batch:e}).then((t)=>t.result)}_describe(e){return this.#e._ensureVersion(2,"describe()"),this.#a({type:"describe",streamId:this.#t,sql:e.sql,sqlId:e.sqlId}).then((t)=>t.result)}_sequence(e){return this.#e._ensureVersion(2,"sequence()"),this.#a({type:"sequence",streamId:this.#t,sql:e.sql,sqlId:e.sqlId}).then((t)=>{return})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#a({type:"get_autocommit",streamId:this.#t}).then((e)=>e.isAutocommit)}#a(e){return new Promise((t,r)=>{this.#s({type:"request",request:e,responseCallback:t,errorCallback:r})})}_openCursor(e){return this.#e._ensureVersion(3,"cursor"),new Promise((t,r)=>{this.#s({type:"cursor",batch:e,cursorCallback:t,errorCallback:r})})}_sendCursorRequest(e,t){if(e!==this.#n)throw new or("Cursor not associated with the stream attempted to execute a request");return new Promise((r,o)=>{if(this.#i!==void 0)o(new xt("Stream is closed",this.#i));else this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})})}_cursorClosed(e){if(e!==this.#n)throw new or("Cursor was closed, but it was not associated with the stream");this.#n=void 0,this.#c()}#s(e){if(this.#i!==void 0)e.errorCallback(new xt("Stream is closed",this.#i));else if(this.#o)e.errorCallback(new xt("Stream is closing",void 0));else this.#r.push(e),this.#c()}#c(){for(;;){let e=this.#r.first();if(e===void 0&&this.#n===void 0&&this.#o){this.#l(new Ge("Stream was gracefully closed"));break}else if(e?.type==="request"&&this.#n===void 0){let{request:t,responseCallback:r,errorCallback:o}=e;this.#r.shift(),this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})}else if(e?.type==="cursor"&&this.#n===void 0){let{batch:t,cursorCallback:r}=e;this.#r.shift();let o=this.#e._cursorIdAlloc.alloc(),n=new VR(this.#e,this,o),i={type:"open_cursor",streamId:this.#t,cursorId:o,batch:t},s=()=>{return},a=(l)=>n._setClosed(l);this.#e._sendRequest(i,{responseCallback:s,errorCallback:a}),this.#n=n,r(n)}else break}}#l(e){if(this.#i!==void 0)return;if(this.#i=e,this.#n!==void 0)this.#n._setClosed(e);for(;;){let n=this.#r.shift();if(n!==void 0)n.errorCallback(e);else break}let t={type:"close_stream",streamId:this.#t},r=()=>this.#e._streamIdAlloc.free(this.#t),o=()=>{return};this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})}close(){this.#l(new Ge("Stream was manually closed"))}closeGracefully(){this.#o=!0,this.#c()}get closed(){return this.#i!==void 0||this.#o}}});function Rp(e,t){if(t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId);e.arrayObjects("args",t.args,P4),e.arrayObjects("named_args",t.namedArgs,mfe),e.boolean("want_rows",t.wantRows)}function mfe(e,t){e.string("name",t.name),e.object("value",t.value,P4)}function vl(e,t){e.arrayObjects("steps",t.steps,hfe)}function hfe(e,t){if(t.condition!==void 0)e.object("condition",t.condition,GR);e.object("stmt",t.stmt,Rp)}function GR(e,t){if(e.stringRaw("type",t.type),t.type==="ok"||t.type==="error")e.number("step",t.step);else if(t.type==="not")e.object("cond",t.cond,GR);else if(t.type==="and"||t.type==="or")e.arrayObjects("conds",t.conds,GR);else if(t.type==="is_autocommit");else throw Je(t,"Impossible type of BatchCond")}function P4(e,t){if(t===null)e.stringRaw("type","null");else if(typeof t==="bigint")e.stringRaw("type","integer"),e.stringRaw("value",""+t);else if(typeof t==="number")e.stringRaw("type","float"),e.number("value",t);else if(typeof t==="string")e.stringRaw("type","text"),e.string("value",t);else if(t instanceof Uint8Array)e.stringRaw("type","blob"),e.stringRaw("base64",cl.fromUint8Array(t));else if(t===void 0);else throw Je(t,"Impossible type of Value")}var QR=v(()=>{vy();rn()});function z4(e,t){if(e.stringRaw("type",t.type),t.type==="hello"){if(t.jwt!==void 0)e.string("jwt",t.jwt)}else if(t.type==="request")e.number("request_id",t.requestId),e.object("request",t.request,gfe);else throw Je(t,"Impossible type of ClientMsg")}function gfe(e,t){if(e.stringRaw("type",t.type),t.type==="open_stream")e.number("stream_id",t.streamId);else if(t.type==="close_stream")e.number("stream_id",t.streamId);else if(t.type==="execute")e.number("stream_id",t.streamId),e.object("stmt",t.stmt,Rp);else if(t.type==="batch")e.number("stream_id",t.streamId),e.object("batch",t.batch,vl);else if(t.type==="open_cursor")e.number("stream_id",t.streamId),e.number("cursor_id",t.cursorId),e.object("batch",t.batch,vl);else if(t.type==="close_cursor")e.number("cursor_id",t.cursorId);else if(t.type==="fetch_cursor")e.number("cursor_id",t.cursorId),e.number("max_count",t.maxCount);else if(t.type==="sequence"){if(e.number("stream_id",t.streamId),t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="describe"){if(e.number("stream_id",t.streamId),t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="store_sql")e.number("sql_id",t.sqlId),e.string("sql",t.sql);else if(t.type==="close_sql")e.number("sql_id",t.sqlId);else if(t.type==="get_autocommit")e.number("stream_id",t.streamId);else throw Je(t,"Impossible type of Request")}var N4=v(()=>{QR();rn()});function Tp(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId);for(let r of t.args)e.message(3,r,L4);for(let r of t.namedArgs)e.message(4,r,yfe);e.bool(5,t.wantRows)}function yfe(e,t){e.string(1,t.name),e.message(2,t.value,L4)}function wl(e,t){for(let r of t.steps)e.message(1,r,bfe)}function bfe(e,t){if(t.condition!==void 0)e.message(1,t.condition,YR);e.message(2,t.stmt,Tp)}function YR(e,t){if(t.type==="ok")e.uint32(1,t.step);else if(t.type==="error")e.uint32(2,t.step);else if(t.type==="not")e.message(3,t.cond,YR);else if(t.type==="and")e.message(4,t.conds,D4);else if(t.type==="or")e.message(5,t.conds,D4);else if(t.type==="is_autocommit")e.message(6,void 0,B4);else throw Je(t,"Impossible type of BatchCond")}function D4(e,t){for(let r of t)e.message(1,r,YR)}function L4(e,t){if(t===null)e.message(1,void 0,B4);else if(typeof t==="bigint")e.sint64(2,t);else if(typeof t==="number")e.double(3,t);else if(typeof t==="string")e.string(4,t);else if(t instanceof Uint8Array)e.bytes(5,t);else if(t===void 0);else throw Je(t,"Impossible type of Value")}function B4(e,t){}var XR=v(()=>{rn()});function j4(e,t){if(t.type==="hello")e.message(1,t,Sfe);else if(t.type==="request")e.message(2,t,vfe);else throw Je(t,"Impossible type of ClientMsg")}function Sfe(e,t){if(t.jwt!==void 0)e.string(1,t.jwt)}function vfe(e,t){e.int32(1,t.requestId);let r=t.request;if(r.type==="open_stream")e.message(2,r,wfe);else if(r.type==="close_stream")e.message(3,r,xfe);else if(r.type==="execute")e.message(4,r,_fe);else if(r.type==="batch")e.message(5,r,Efe);else if(r.type==="open_cursor")e.message(6,r,kfe);else if(r.type==="close_cursor")e.message(7,r,Ife);else if(r.type==="fetch_cursor")e.message(8,r,Afe);else if(r.type==="sequence")e.message(9,r,Rfe);else if(r.type==="describe")e.message(10,r,Tfe);else if(r.type==="store_sql")e.message(11,r,$fe);else if(r.type==="close_sql")e.message(12,r,Ofe);else if(r.type==="get_autocommit")e.message(13,r,Cfe);else throw Je(r,"Impossible type of Request")}function wfe(e,t){e.int32(1,t.streamId)}function xfe(e,t){e.int32(1,t.streamId)}function _fe(e,t){e.int32(1,t.streamId),e.message(2,t.stmt,Tp)}function Efe(e,t){e.int32(1,t.streamId),e.message(2,t.batch,wl)}function kfe(e,t){e.int32(1,t.streamId),e.int32(2,t.cursorId),e.message(3,t.batch,wl)}function Ife(e,t){e.int32(1,t.cursorId)}function Afe(e,t){e.int32(1,t.cursorId),e.uint32(2,t.maxCount)}function Rfe(e,t){if(e.int32(1,t.streamId),t.sql!==void 0)e.string(2,t.sql);if(t.sqlId!==void 0)e.int32(3,t.sqlId)}function Tfe(e,t){if(e.int32(1,t.streamId),t.sql!==void 0)e.string(2,t.sql);if(t.sqlId!==void 0)e.int32(3,t.sqlId)}function $fe(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function Ofe(e,t){e.int32(1,t.sqlId)}function Cfe(e,t){e.int32(1,t.streamId)}var Z4=v(()=>{XR();rn()});function Yi(e){let t=Rr(e.message),r=Zr(e.code);return{message:t,code:r}}function $p(e){let t=xn(e.cols,U4),r=bp(e.rows).map((s)=>xn(s,M4)),o=Bo(e.affected_row_count),n=Zr(e.last_insert_rowid),i=n!==void 0?BigInt(n):void 0;return{cols:t,rows:r,affectedRowCount:o,lastInsertRowid:i}}function U4(e){let t=Zr(e.name),r=Zr(e.decltype);return{name:t,decltype:r}}function Oy(e){let t=new Map;bp(e.step_results).forEach((o,n)=>{if(o!==null)t.set(n,$p(It(o)))});let r=new Map;return bp(e.step_errors).forEach((o,n)=>{if(o!==null)r.set(n,Yi(It(o)))}),{stepResults:t,stepErrors:r}}function Cy(e){let t=Rr(e.type);if(t==="step_begin"){let r=Bo(e.step),o=xn(e.cols,U4);return{type:"step_begin",step:r,cols:o}}else if(t==="step_end"){let r=Bo(e.affected_row_count),o=Zr(e.last_insert_rowid),n=o!==void 0?BigInt(o):void 0;return{type:"step_end",affectedRowCount:r,lastInsertRowid:n}}else if(t==="step_error"){let r=Bo(e.step),o=Yi(It(e.error));return{type:"step_error",step:r,error:o}}else if(t==="row")return{type:"row",row:xn(e.row,M4)};else if(t==="error")return{type:"error",error:Yi(It(e.error))};else throw new Pe("Unexpected type of CursorEntry")}function Py(e){let t=xn(e.params,Pfe),r=xn(e.cols,zfe),o=Vi(e.is_explain),n=Vi(e.is_readonly);return{params:t,cols:r,isExplain:o,isReadonly:n}}function Pfe(e){return{name:Zr(e.name)}}function zfe(e){let t=Rr(e.name),r=Zr(e.decltype);return{name:t,decltype:r}}function M4(e){let t=Rr(e.type);if(t==="null")return null;else if(t==="integer"){let r=Rr(e.value);return BigInt(r)}else if(t==="float")return Bo(e.value);else if(t==="text")return Rr(e.value);else if(t==="blob")return cl.toUint8Array(Rr(e.base64));else throw new Pe("Unexpected type of Value")}var zy=v(()=>{vy();_t();gl()});function q4(e){let t=Rr(e.type);if(t==="hello_ok")return{type:"hello_ok"};else if(t==="hello_error")return{type:"hello_error",error:Yi(It(e.error))};else if(t==="response_ok"){let r=Bo(e.request_id),o=Nfe(It(e.response));return{type:"response_ok",requestId:r,response:o}}else if(t==="response_error"){let r=Bo(e.request_id),o=Yi(It(e.error));return{type:"response_error",requestId:r,error:o}}else throw new Pe("Unexpected type of ServerMsg")}function Nfe(e){let t=Rr(e.type);if(t==="open_stream")return{type:"open_stream"};else if(t==="close_stream")return{type:"close_stream"};else if(t==="execute")return{type:"execute",result:$p(It(e.result))};else if(t==="batch")return{type:"batch",result:Oy(It(e.result))};else if(t==="open_cursor")return{type:"open_cursor"};else if(t==="close_cursor")return{type:"close_cursor"};else if(t==="fetch_cursor"){let r=xn(e.entries,Cy),o=Vi(e.done);return{type:"fetch_cursor",entries:r,done:o}}else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:Py(It(e.result))};else if(t==="store_sql")return{type:"store_sql"};else if(t==="close_sql")return{type:"close_sql"};else if(t==="get_autocommit")return{type:"get_autocommit",isAutocommit:Vi(e.is_autocommit)};else throw new Pe("Unexpected type of Response")}var F4=v(()=>{_t();gl();zy()});var nn,Xi,K4,J4,xl,Dfe,Lfe,Ny,Bfe,jfe,Zfe,_l,Ufe,Mfe,qfe;var Dy=v(()=>{nn={default(){return{message:"",code:void 0}},1(e,t){t.message=e.string()},2(e,t){t.code=e.string()}},Xi={default(){return{cols:[],rows:[],affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.cols.push(e.message(K4))},2(e,t){t.rows.push(e.message(J4))},3(e,t){t.affectedRowCount=Number(e.uint64())},4(e,t){t.lastInsertRowid=e.sint64()}},K4={default(){return{name:void 0,decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},J4={default(){return[]},1(e,t){t.push(e.message(qfe))}},xl={default(){return{stepResults:new Map,stepErrors:new Map}},1(e,t){let[r,o]=e.message(Dfe);t.stepResults.set(r,o)},2(e,t){let[r,o]=e.message(Lfe);t.stepErrors.set(r,o)}},Dfe={default(){return[0,Xi.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(Xi)}},Lfe={default(){return[0,nn.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(nn)}},Ny={default(){return{type:"none"}},1(e){return e.message(Bfe)},2(e){return e.message(jfe)},3(e){return e.message(Zfe)},4(e){return{type:"row",row:e.message(J4)}},5(e){return{type:"error",error:e.message(nn)}}},Bfe={default(){return{type:"step_begin",step:0,cols:[]}},1(e,t){t.step=e.uint32()},2(e,t){t.cols.push(e.message(K4))}},jfe={default(){return{type:"step_end",affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.affectedRowCount=e.uint32()},2(e,t){t.lastInsertRowid=e.uint64()}},Zfe={default(){return{type:"step_error",step:0,error:nn.default()}},1(e,t){t.step=e.uint32()},2(e,t){t.error=e.message(nn)}},_l={default(){return{params:[],cols:[],isExplain:!1,isReadonly:!1}},1(e,t){t.params.push(e.message(Ufe))},2(e,t){t.cols.push(e.message(Mfe))},3(e,t){t.isExplain=e.bool()},4(e,t){t.isReadonly=e.bool()}},Ufe={default(){return{name:void 0}},1(e,t){t.name=e.string()}},Mfe={default(){return{name:"",decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},qfe={default(){return},1(e){return null},2(e){return e.sint64()},3(e){return e.double()},4(e){return e.string()},5(e){return e.bytes()}}});var H4,Ffe,Kfe,Jfe,Hfe,Vfe,Wfe,Gfe,Qfe;var V4=v(()=>{Dy();H4={default(){return{type:"none"}},1(e){return{type:"hello_ok"}},2(e){return e.message(Ffe)},3(e){return e.message(Jfe)},4(e){return e.message(Kfe)}},Ffe={default(){return{type:"hello_error",error:nn.default()}},1(e,t){t.error=e.message(nn)}},Kfe={default(){return{type:"response_error",requestId:0,error:nn.default()}},1(e,t){t.requestId=e.int32()},2(e,t){t.error=e.message(nn)}},Jfe={default(){return{type:"response_ok",requestId:0,response:{type:"none"}}},1(e,t){t.requestId=e.int32()},2(e,t){t.response={type:"open_stream"}},3(e,t){t.response={type:"close_stream"}},4(e,t){t.response=e.message(Hfe)},5(e,t){t.response=e.message(Vfe)},6(e,t){t.response={type:"open_cursor"}},7(e,t){t.response={type:"close_cursor"}},8(e,t){t.response=e.message(Wfe)},9(e,t){t.response={type:"sequence"}},10(e,t){t.response=e.message(Gfe)},11(e,t){t.response={type:"store_sql"}},12(e,t){t.response={type:"close_sql"}},13(e,t){t.response=e.message(Qfe)}},Hfe={default(){return{type:"execute",result:Xi.default()}},1(e,t){t.result=e.message(Xi)}},Vfe={default(){return{type:"batch",result:xl.default()}},1(e,t){t.result=e.message(xl)}},Wfe={default(){return{type:"fetch_cursor",entries:[],done:!1}},1(e,t){t.entries.push(e.message(Ny))},2(e,t){t.done=e.bool()}},Gfe={default(){return{type:"describe",result:_l.default()}},1(e,t){t.result=e.message(_l)}},Qfe={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}}});var W4,eT,Ly;var By=v(()=>{MR();_t();qR();_p();bl();rn();WR();N4();Z4();F4();V4();W4=new Map([["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]),eT=new Map([["hrana3-protobuf",{version:3,encoding:"protobuf"}],["hrana3",{version:3,encoding:"json"}],["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]);Ly=class Ly extends fl{#e;#t;#r;#n;#o;#i;#a;#s;#c;_streamIdAlloc;_cursorIdAlloc;#l;constructor(e,t){super();this.#e=e,this.#t=[],this.#r=!1,this.#n=void 0,this.#o=!1,this.#i=void 0,this.#a=!1,this.#s=new Map,this.#c=new Gi,this._streamIdAlloc=new Gi,this._cursorIdAlloc=new Gi,this.#l=new Gi,this.#e.binaryType="arraybuffer",this.#e.addEventListener("open",()=>this.#p()),this.#e.addEventListener("close",(r)=>this.#g(r)),this.#e.addEventListener("error",(r)=>this.#f(r)),this.#e.addEventListener("message",(r)=>this.#y(r)),this.#d({type:"hello",jwt:t})}#d(e){if(this.#n!==void 0)throw new or("Trying to send a message on a closed client");if(this.#r)this.#m(e);else{let t=()=>this.#m(e),r=()=>{return};this.#t.push({openCallback:t,errorCallback:r})}}#p(){let e=this.#e.protocol;if(e===void 0){this.#u(new Ge("The `WebSocket.protocol` property is undefined. This most likely means that the WebSocket implementation provided by the environment is broken. If you are using Miniflare 2, please update to Miniflare 3, which fixes this problem."));return}else if(e==="")this.#i={version:1,encoding:"json"};else if(this.#i=eT.get(e),this.#i===void 0){this.#u(new Pe(`Unrecognized WebSocket subprotocol: ${JSON.stringify(e)}`));return}for(let t of this.#t)t.openCallback();this.#t.length=0,this.#r=!0}#m(e){let t=this.#i.encoding;if(t==="json"){let r=Sp(e,z4);this.#e.send(r)}else if(t==="protobuf"){let r=xp(e,j4);this.#e.send(r)}else throw Je(t,"Impossible encoding")}getVersion(){return new Promise((e,t)=>{if(this.#a=!0,this.#n!==void 0)t(this.#n);else if(!this.#r){let r=()=>e(this.#i.version);this.#t.push({openCallback:r,errorCallback:t})}else e(this.#i.version)})}_ensureVersion(e,t){if(this.#i===void 0||!this.#a)throw new wn(`${t} is supported only on protocol version ${e} and higher, but the version supported by the WebSocket server is not yet known. Use Client.getVersion() to wait until the version is available.`);else if(this.#i.version<e)throw new wn(`${t} is supported on protocol version ${e} and higher, but the WebSocket server only supports version ${this.#i.version}`)}_sendRequest(e,t){if(this.#n!==void 0){t.errorCallback(new xt("Client is closed",this.#n));return}let r=this.#c.alloc();this.#s.set(r,{...t,type:e.type}),this.#d({type:"request",requestId:r,request:e})}#f(e){let r=e.message??"WebSocket was closed due to an error";this.#u(new ml(r))}#g(e){let t=`WebSocket was closed with code ${e.code}`;if(e.reason)t+=`: ${e.reason}`;this.#u(new ml(t))}#u(e){if(this.#n!==void 0)return;this.#n=e;for(let t of this.#t)t.errorCallback(e);this.#t.length=0;for(let[t,r]of this.#s.entries())r.errorCallback(e),this.#c.free(t);this.#s.clear(),this.#e.close()}#y(e){if(this.#n!==void 0)return;try{let t,r=this.#i.encoding;if(r==="json"){if(typeof e.data!=="string"){this.#e.close(3003,"Only text messages are accepted with JSON encoding"),this.#u(new Pe("Received non-text message from server with JSON encoding"));return}t=ua(JSON.parse(e.data),q4)}else if(r==="protobuf"){if(!(e.data instanceof ArrayBuffer)){this.#e.close(3003,"Only binary messages are accepted with Protobuf encoding"),this.#u(new Pe("Received non-binary message from server with Protobuf encoding"));return}t=Wi(new Uint8Array(e.data),H4)}else throw Je(r,"Impossible encoding");this.#b(t)}catch(t){this.#e.close(3007,"Could not handle message"),this.#u(t)}}#b(e){if(e.type==="none")throw new Pe("Received an unrecognized ServerMsg");else if(e.type==="hello_ok"||e.type==="hello_error"){if(this.#o)throw new Pe("Received a duplicated hello response");if(this.#o=!0,e.type==="hello_error")throw jo(e.error);return}else if(!this.#o)throw new Pe("Received a non-hello message before a hello response");if(e.type==="response_ok"){let t=e.requestId,r=this.#s.get(t);if(this.#s.delete(t),r===void 0)throw new Pe("Received unexpected OK response");this.#c.free(t);try{if(r.type!==e.response.type)throw console.dir({responseState:r,msg:e}),new Pe("Received unexpected type of response");r.responseCallback(e.response)}catch(o){throw r.errorCallback(o),o}}else if(e.type==="response_error"){let t=e.requestId,r=this.#s.get(t);if(this.#s.delete(t),r===void 0)throw new Pe("Received unexpected error response");this.#c.free(t),r.errorCallback(jo(e.error))}else throw Je(e,"Impossible ServerMsg type")}openStream(){return Ap.open(this)}storeSql(e){this._ensureVersion(2,"storeSql()");let t=this.#l.alloc(),r=new fa(this,t),o=()=>{return},n=(s)=>r._setClosed(s),i={type:"store_sql",sqlId:t,sql:e};return this._sendRequest(i,{responseCallback:o,errorCallback:n}),r}_closeSql(e){if(this.#n!==void 0)return;let t=()=>this.#l.free(e),r=(n)=>this.#u(n),o={type:"close_sql",sqlId:e};this._sendRequest(o,{responseCallback:t,errorCallback:r})}close(){this.#u(new Ge("Client was manually closed"))}get closed(){return this.#n!==void 0}}});var ma;var G4=v(()=>{if(typeof queueMicrotask<"u")ma=queueMicrotask;else{let e=Promise.resolve();ma=(t)=>{e.then(t)}}});class tT{#e;#t;#r;constructor(e){this.#e=new Uint8Array(new ArrayBuffer(e)),this.#t=0,this.#r=0}get length(){return this.#r-this.#t}data(){return this.#e.slice(this.#t,this.#r)}push(e){this.#n(e.byteLength),this.#e.set(e,this.#r),this.#r+=e.byteLength}#n(e){if(this.#r+e<=this.#e.byteLength)return;let t=this.#r-this.#t;if(t+e<=this.#e.byteLength&&2*this.#r>=this.#e.byteLength)this.#e.copyWithin(0,this.#t,this.#r);else{let r=this.#e.byteLength;do r*=2;while(t+e>r);let o=new Uint8Array(new ArrayBuffer(r));o.set(this.#e.slice(this.#t,this.#r),0),this.#e=o}this.#r=t,this.#t=0}shift(e){this.#t+=e}}function Q4(e){let t=Zr(e.baton),r=Zr(e.base_url),o=xn(e.results,Yfe);return{baton:t,baseUrl:r,results:o}}function Yfe(e){let t=Rr(e.type);if(t==="ok")return{type:"ok",response:Xfe(It(e.response))};else if(t==="error")return{type:"error",error:Yi(It(e.error))};else throw new Pe("Unexpected type of StreamResult")}function Xfe(e){let t=Rr(e.type);if(t==="close")return{type:"close"};else if(t==="execute")return{type:"execute",result:$p(It(e.result))};else if(t==="batch")return{type:"batch",result:Oy(It(e.result))};else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:Py(It(e.result))};else if(t==="store_sql")return{type:"store_sql"};else if(t==="close_sql")return{type:"close_sql"};else if(t==="get_autocommit")return{type:"get_autocommit",isAutocommit:Vi(e.is_autocommit)};else throw new Pe("Unexpected type of StreamResponse")}function Y4(e){let t=Zr(e.baton),r=Zr(e.base_url);return{baton:t,baseUrl:r}}var rT=v(()=>{_t();gl();zy()});var X4,eme,tme,rme,nme,ome,ime,eF;var nT=v(()=>{Dy();X4={default(){return{baton:void 0,baseUrl:void 0,results:[]}},1(e,t){t.baton=e.string()},2(e,t){t.baseUrl=e.string()},3(e,t){t.results.push(e.message(eme))}},eme={default(){return{type:"none"}},1(e){return{type:"ok",response:e.message(tme)}},2(e){return{type:"error",error:e.message(nn)}}},tme={default(){return{type:"none"}},1(e){return{type:"close"}},2(e){return e.message(rme)},3(e){return e.message(nme)},4(e){return{type:"sequence"}},5(e){return e.message(ome)},6(e){return{type:"store_sql"}},7(e){return{type:"close_sql"}},8(e){return e.message(ime)}},rme={default(){return{type:"execute",result:Xi.default()}},1(e,t){t.result=e.message(Xi)}},nme={default(){return{type:"batch",result:xl.default()}},1(e,t){t.result=e.message(xl)}},ome={default(){return{type:"describe",result:_l.default()}},1(e,t){t.result=e.message(_l)}},ime={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}},eF={default(){return{baton:void 0,baseUrl:void 0}},1(e,t){t.baton=e.string()},2(e,t){t.baseUrl=e.string()}}});var oT;var tF=v(()=>{gl();ZR();_t();rn();rT();nT();zy();Dy();oT=class oT extends Ip{#e;#t;#r;#n;#o;#i;constructor(e,t){super();this.#e=e,this.#t=t,this.#r=void 0,this.#n=new tT(16384),this.#o=void 0,this.#i=!1}async open(e){if(e.body===null)throw new Pe("No response body for cursor request");this.#r=e.body[Symbol.asyncIterator]();let t=await this.#a(Y4,eF);if(t===void 0)throw new Pe("Empty response to cursor request");return t}next(){return this.#a(Cy,Ny)}close(){this._setClosed(new Ge("Cursor was manually closed"))}_setClosed(e){if(this.#o!==void 0)return;if(this.#o=e,this.#e._cursorClosed(this),this.#r!==void 0)this.#r.return()}get closed(){return this.#o!==void 0}async#a(e,t){for(;;){if(this.#i)return;else if(this.#o!==void 0)throw new xt("Cursor is closed",this.#o);if(this.#t==="json"){let n=this.#s();if(n!==void 0){let i=new TextDecoder().decode(n),s=JSON.parse(i);return ua(s,e)}}else if(this.#t==="protobuf"){let n=this.#c();if(n!==void 0)return Wi(n,t)}else throw Je(this.#t,"Impossible encoding");if(this.#r===void 0)throw new or("Attempted to read from HTTP cursor before it was opened");let{value:r,done:o}=await this.#r.next();if(o&&this.#n.length===0)this.#i=!0;else if(o)throw new Pe("Unexpected end of cursor stream");else this.#n.push(r)}}#s(){let e=this.#n.data(),t=10,r=e.indexOf(10);if(r<0)return;let o=e.slice(0,r);return this.#n.shift(r+1),o}#c(){let e=this.#n.data(),t=0,r=0;for(;;){if(r>=e.byteLength)return;let n=e[r];if(t|=(n&127)<<7*r,r+=1,!(n&128))break}if(e.byteLength<r+t)return;let o=e.slice(r,r+t);return this.#n.shift(r+t),o}}});function rF(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.arrayObjects("requests",t.requests,sme)}function sme(e,t){if(e.stringRaw("type",t.type),t.type==="close");else if(t.type==="execute")e.object("stmt",t.stmt,Rp);else if(t.type==="batch")e.object("batch",t.batch,vl);else if(t.type==="sequence"){if(t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="describe"){if(t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="store_sql")e.number("sql_id",t.sqlId),e.string("sql",t.sql);else if(t.type==="close_sql")e.number("sql_id",t.sqlId);else if(t.type==="get_autocommit");else throw Je(t,"Impossible type of StreamRequest")}function nF(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.object("batch",t.batch,vl)}var iT=v(()=>{QR();rn()});function oF(e,t){if(t.baton!==void 0)e.string(1,t.baton);for(let r of t.requests)e.message(2,r,ame)}function ame(e,t){if(t.type==="close")e.message(1,t,cme);else if(t.type==="execute")e.message(2,t,lme);else if(t.type==="batch")e.message(3,t,ume);else if(t.type==="sequence")e.message(4,t,dme);else if(t.type==="describe")e.message(5,t,pme);else if(t.type==="store_sql")e.message(6,t,fme);else if(t.type==="close_sql")e.message(7,t,mme);else if(t.type==="get_autocommit")e.message(8,t,hme);else throw Je(t,"Impossible type of StreamRequest")}function cme(e,t){}function lme(e,t){e.message(1,t.stmt,Tp)}function ume(e,t){e.message(1,t.batch,wl)}function dme(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function pme(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function fme(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function mme(e,t){e.int32(1,t.sqlId)}function hme(e,t){}function iF(e,t){if(t.baton!==void 0)e.string(1,t.baton);e.message(2,t.batch,wl)}var sT=v(()=>{XR();rn()});function gme(e,t){if(t.results.length!==e.length)throw new Pe("Server returned unexpected number of pipeline results");for(let r=0;r<e.length;++r){let o=t.results[r],n=e[r];if(o.type==="ok"){if(o.response.type!==n.request.type)throw new Pe("Received unexpected type of response");n.responseCallback(o.response)}else if(o.type==="error")n.errorCallback(jo(o.error));else if(o.type==="none")throw new Pe("Received unrecognized type of StreamResult");else throw Je(o,"Received impossible type of StreamResult")}}async function yme(e,t){if(t==="json"){let r=await e.json();return ua(r,Q4)}if(t==="protobuf"){let r=await e.arrayBuffer();return Wi(new Uint8Array(r),X4)}throw await e.body?.cancel(),Je(t,"Impossible encoding")}async function bme(e){let t=e.headers.get("content-type")??"text/plain",r=`Server returned HTTP status ${e.status}`;if(t==="application/json"){let o=await e.json();if("message"in o)return jo(o);return new la(r,e.status)}if(t==="text/plain"){let o=(await e.text()).trim();if(o!=="")r+=`: ${o}`;return new la(r,e.status)}return await e.body?.cancel(),new la(r,e.status)}var jy;var aT=v(()=>{_t();MR();qR();G4();_p();bl();$y();rn();tF();iT();sT();iT();sT();rT();nT();jy=class jy extends Sl{#e;#t;#r;#n;#o;#i;#a;#s;#c;#l;#d;#p;#m;constructor(e,t,r,o,n){super(e.intMode);this.#e=e,this.#t=t.toString(),this.#r=r,this.#n=o,this.#o=n,this.#i=void 0,this.#a=new Qi,this.#s=!1,this.#l=!1,this.#d=!1,this.#p=void 0,this.#m=new Gi}client(){return this.#e}_sqlOwner(){return this}storeSql(e){let t=this.#m.alloc();return this.#f({type:"store_sql",sqlId:t,sql:e}).then(()=>{return},(r)=>this._setClosed(r)),new fa(this,t)}_closeSql(e){if(this.#p!==void 0)return;this.#f({type:"close_sql",sqlId:e}).then(()=>this.#m.free(e),(t)=>this._setClosed(t))}_execute(e){return this.#f({type:"execute",stmt:e}).then((t)=>t.result)}_batch(e){return this.#f({type:"batch",batch:e}).then((t)=>t.result)}_describe(e){return this.#f({type:"describe",sql:e.sql,sqlId:e.sqlId}).then((t)=>t.result)}_sequence(e){return this.#f({type:"sequence",sql:e.sql,sqlId:e.sqlId}).then((t)=>{return})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#f({type:"get_autocommit"}).then((e)=>e.isAutocommit)}#f(e){return new Promise((t,r)=>{this.#g({type:"pipeline",request:e,responseCallback:t,errorCallback:r})})}_openCursor(e){return new Promise((t,r)=>{this.#g({type:"cursor",batch:e,cursorCallback:t,errorCallback:r})})}_cursorClosed(e){if(e!==this.#c)throw new or("Cursor was closed, but it was not associated with the stream");this.#c=void 0,ma(()=>this.#u())}close(){this._setClosed(new Ge("Stream was manually closed"))}closeGracefully(){this.#l=!0,ma(()=>this.#u())}get closed(){return this.#p!==void 0||this.#l}_setClosed(e){if(this.#p!==void 0)return;if(this.#p=e,this.#c!==void 0)this.#c._setClosed(e);this.#e._streamClosed(this);for(;;){let t=this.#a.shift();if(t!==void 0)t.errorCallback(e);else break}if((this.#i!==void 0||this.#s)&&!this.#d)this.#a.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0,ma(()=>this.#u())}#g(e){if(this.#p!==void 0)throw new xt("Stream is closed",this.#p);else if(this.#l)throw new xt("Stream is closing",void 0);else this.#a.push(e),ma(()=>this.#u())}#u(){if(this.#s||this.#c!==void 0)return;if(this.#l&&this.#a.length===0){this._setClosed(new Ge("Stream was gracefully closed"));return}let e=this.#e._endpoint;if(e===void 0){this.#e._endpointPromise.then(()=>this.#u(),(r)=>this._setClosed(r));return}let t=this.#a.shift();if(t===void 0)return;else if(t.type==="pipeline"){let r=[t];for(;;){let o=this.#a.first();if(o!==void 0&&o.type==="pipeline")r.push(o),this.#a.shift();else if(o===void 0&&this.#l&&!this.#d){r.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0;break}else break}this.#y(e,r)}else if(t.type==="cursor")this.#b(e,t);else throw Je(t,"Impossible type of QueueEntry")}#y(e,t){this.#h(()=>this.#S(t,e),(r)=>yme(r,e.encoding),(r)=>r.baton,(r)=>r.baseUrl,(r)=>gme(t,r),(r)=>t.forEach((o)=>o.errorCallback(r)))}#b(e,t){let r=new oT(this,e.encoding);this.#c=r,this.#h(()=>this.#v(t,e),(o)=>r.open(o),(o)=>o.baton,(o)=>o.baseUrl,(o)=>t.cursorCallback(r),(o)=>t.errorCallback(o))}#h(e,t,r,o,n,i){let s;try{let a=e(),l=this.#n;s=l(a)}catch(a){s=Promise.reject(a)}this.#s=!0,s.then((a)=>{if(!a.ok)return bme(a).then((l)=>{throw l});return t(a)}).then((a)=>{this.#i=r(a),this.#t=o(a)??this.#t,n(a)}).catch((a)=>{this._setClosed(a),i(a)}).finally(()=>{this.#s=!1,this.#u()})}#S(e,t){return this.#w(new URL(t.pipelinePath,this.#t),{baton:this.#i,requests:e.map((r)=>r.request)},t.encoding,rF,oF)}#v(e,t){if(t.cursorPath===void 0)throw new wn(`Cursors are supported only on protocol version 3 and higher, but the HTTP server only supports version ${t.version}.`);return this.#w(new URL(t.cursorPath,this.#t),{baton:this.#i,batch:e.batch},t.encoding,nF,iF)}#w(e,t,r,o,n){let i,s;if(r==="json")i=Sp(t,o),s="application/json";else if(r==="protobuf")i=xp(t,n),s="application/x-protobuf";else throw Je(r,"Impossible encoding");let a=new Headers;if(a.set("content-type",s),this.#r!==void 0)a.set("authorization",`Bearer ${this.#r}`);if(this.#o!==void 0)a.set("x-turso-encryption-key",this.#o);return new Request(e.toString(),{method:"POST",headers:a,body:i})}}});async function vme(e,t){let r=e;for(let o of Sme){let n=new URL(o.versionPath,t),i=new Request(n.toString(),{method:"GET"}),s=await r(i);if(await s.arrayBuffer(),s.ok)return o}return cT}var Sme,cT,Zy;var lT=v(()=>{_t();aT();Sme=[{versionPath:"v3-protobuf",pipelinePath:"v3-protobuf/pipeline",cursorPath:"v3-protobuf/cursor",version:3,encoding:"protobuf"}],cT={versionPath:"v2",pipelinePath:"v2/pipeline",cursorPath:void 0,version:2,encoding:"json"};Zy=class Zy extends fl{#e;#t;#r;#n;#o;#i;_endpointPromise;_endpoint;constructor(e,t,r,o,n=2){super();if(this.#e=e,this.#t=t,this.#r=r??globalThis.fetch,this.#n=o,this.#o=void 0,this.#i=new Set,n==3)this._endpointPromise=vme(this.#r,this.#e),this._endpointPromise.then((i)=>this._endpoint=i,(i)=>this.#a(i));else this._endpointPromise=Promise.resolve(cT),this._endpointPromise.then((i)=>this._endpoint=i,(i)=>this.#a(i))}async getVersion(){if(this._endpoint!==void 0)return this._endpoint.version;return(await this._endpointPromise).version}_ensureVersion(e,t){if(e<=cT.version)return;else if(this._endpoint===void 0)throw new wn(`${t} is supported only on protocol version ${e} and higher, but the version supported by the HTTP server is not yet known. Use Client.getVersion() to wait until the version is available.`);else if(this._endpoint.version<e)throw new wn(`${t} is supported only on protocol version ${e} and higher, but the HTTP server only supports version ${this._endpoint.version}.`)}openStream(){if(this.#o!==void 0)throw new xt("Client is closed",this.#o);let e=new jy(this,this.#e,this.#t,this.#r,this.#n);return this.#i.add(e),e}_streamClosed(e){this.#i.delete(e)}close(){this.#a(new Ge("Client was manually closed"))}get closed(){return this.#o!==void 0}#a(e){if(this.#o!==void 0)return;this.#o=e;for(let t of Array.from(this.#i))t._setClosed(new xt("Client was closed",e))}}});var sF=v(()=>{_t()});function uT(e,t,r=2){if(typeof Hi>"u")throw new yp("WebSockets are not supported in this environment");var o=void 0;if(r==3)o=Array.from(eT.keys());else o=Array.from(W4.keys());let n=new Hi(e,o);return new Ly(n,t)}function dT(e,t,r,o,n=2){return new Zy(e instanceof URL?e:new URL(e),t,r,o,n)}var Uy=v(()=>{jR();By();_t();lT();By();jR();HR();sF();bl();Ry();$y();lT();aT();By();WR();_t()});class Op{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}execute(e){return this.batch([e]).then((t)=>t[0])}async batch(e){let t=this._getStream();if(t.closed)throw new Ce("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{let r=e.map(Zo),o;if(this.#r===void 0){this._getSqlCache().apply(r);let i=t.batch(this.#t>=3),s=i.step(),a=s.run(Ki(this.#e)),l=s;o=r.map((u)=>{let d=i.step().condition(ut.ok(l));if(this.#t>=3)d.condition(ut.not(ut.isAutocommit(i)));let p=d.query(u);return p.catch(()=>{return}),l=d,p}),this.#r=i.execute().then(()=>a).then(()=>{return});try{await this.#r}catch(u){throw this.close(),u}}else{if(this.#t<3)await this.#r;this._getSqlCache().apply(r);let i=t.batch(this.#t>=3),s=void 0;o=r.map((a)=>{let l=i.step();if(s!==void 0)l.condition(ut.ok(s));if(this.#t>=3)l.condition(ut.not(ut.isAutocommit(i)));let u=l.query(a);return u.catch(()=>{return}),s=l,u}),await i.execute()}let n=[];for(let i=0;i<o.length;i++)try{let s=await o[i];if(s===void 0)throw new Wt("Statement in a transaction was not executed, probably because the transaction has been rolled back",i,"TRANSACTION_CLOSED");n.push(kl(s))}catch(s){if(s instanceof Wt)throw s;let a=st(s);if(a instanceof Ce)throw new Wt(a.message,i,a.code,a.extendedCode,a.rawCode,a.cause instanceof Error?a.cause:void 0);throw a}return n}catch(r){throw st(r)}}async executeMultiple(e){let t=this._getStream();if(t.closed)throw new Ce("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{if(this.#r===void 0){this.#r=t.run(Ki(this.#e)).then(()=>{return});try{await this.#r}catch(r){throw this.close(),r}}else await this.#r;await t.sequence(e)}catch(r){throw st(r)}}async rollback(){try{let e=this._getStream();if(e.closed)return;if(this.#r!==void 0);else return;let t=e.run("ROLLBACK").catch((r)=>{throw st(r)});e.closeGracefully(),await t}catch(e){throw st(e)}finally{this.close()}}async commit(){try{let e=this._getStream();if(e.closed)throw new Ce("Cannot commit the transaction because it is already closed","TRANSACTION_CLOSED");if(this.#r!==void 0)await this.#r;else return;let t=e.run("COMMIT").catch((r)=>{throw st(r)});e.closeGracefully(),await t}catch(e){throw st(e)}finally{this.close()}}}async function El(e,t,r,o,n=!1){if(n)r.step().run("PRAGMA foreign_keys=off");let i=r.step(),s=i.run(Ki(e)),a=i,l=o.map((h)=>{let b=r.step().condition(ut.ok(a));if(t>=3)b.condition(ut.not(ut.isAutocommit(r)));let y=b.query(h);return a=b,y}),u=r.step().condition(ut.ok(a));if(t>=3)u.condition(ut.not(ut.isAutocommit(r)));let d=u.run("COMMIT");if(r.step().condition(ut.not(ut.ok(u))).run("ROLLBACK").catch((h)=>{return}),n)r.step().run("PRAGMA foreign_keys=on");await r.execute();let m=[];await s;for(let h=0;h<l.length;h++)try{let b=await l[h];if(b===void 0)throw new Wt("Statement in a batch was not executed, probably because the transaction has been rolled back",h,"TRANSACTION_CLOSED");m.push(kl(b))}catch(b){if(b instanceof Wt)throw b;let y=st(b);if(y instanceof Ce)throw new Wt(y.message,h,y.code,y.extendedCode,y.rawCode,y.cause instanceof Error?y.cause:void 0);throw y}return await d,m}function Zo(e){let t,r;if(Array.isArray(e))[t,r]=e;else if(typeof e==="string")t=e;else t=e.sql,r=e.args;let o=new kp(t);if(r)if(Array.isArray(r))o.bindIndexes(r);else for(let[n,i]of Object.entries(r))o.bindName(n,i);return o}function kl(e){let t=e.columnNames.map((s)=>s??""),r=e.columnDecltypes.map((s)=>s??""),o=e.rows,n=e.affectedRowCount,i=e.lastInsertRowid!==void 0?e.lastInsertRowid:void 0;return new ll(t,r,o,n,i)}function st(e){if(e instanceof Ge){let t=aF(e);return new Ce(e.message,t,void 0,void 0,e)}return e}function aF(e){if(e instanceof gp&&e.code!==void 0)return e.code;else if(e instanceof Pe)return"HRANA_PROTO_ERROR";else if(e instanceof xt)return e.cause instanceof Ge?aF(e.cause):"HRANA_CLOSED_ERROR";else if(e instanceof ml)return"HRANA_WEBSOCKET_ERROR";else if(e instanceof la)return"SERVER_ERROR";else if(e instanceof wn)return"PROTOCOL_VERSION_ERROR";else if(e instanceof or)return"INTERNAL_ERROR";else return"UNKNOWN"}var fT=v(()=>{Uy();vn();ul()});class Il{#e;#t;capacity;constructor(e,t){this.#e=e,this.#t=new cF,this.capacity=t}apply(e){if(this.capacity<=0)return;let t=new Set;for(let r of e){if(typeof r.sql!=="string")continue;let o=r.sql;if(o.length>=5000)continue;let n=this.#t.get(o);if(n===void 0){while(this.#t.size+1>this.capacity){let[i,s]=this.#t.peekLru();if(t.has(s))break;s.close(),this.#t.delete(i)}if(this.#t.size+1<=this.capacity)n=this.#e.storeSql(o),this.#t.set(o,n)}if(n!==void 0)r.sql=n,t.add(n)}}}class cF{#e;constructor(){this.#e=new Map}get(e){let t=this.#e.get(e);if(t!==void 0)this.#e.delete(e),this.#e.set(e,t);return t}set(e,t){this.#e.set(e,t)}peekLru(){for(let e of this.#e.entries())return e;return}delete(e){this.#e.delete(e)}get size(){return this.#e.size}}var mT=ge(function(xBe,uF){function wme(e){var t=0,r=[];function o(){if(t--,t<e)n()}function n(){var l=r.shift();if(a.queue=r.length,l)s(l.fn).then(l.resolve).catch(l.reject)}function i(l){return new Promise(function(u,d){r.push({fn:l,resolve:u,reject:d}),a.queue=r.length})}function s(l){t++;try{return Promise.resolve(l()).then(function(u){return o(),u},function(u){throw o(),u})}catch(u){return o(),Promise.reject(u)}}var a=function(l){if(t>=e)return i(l);else return s(l)};return a}function xme(e,t){var r=!1,o=this;return Promise.all(e.map(function(){var n=arguments;return o(function(){if(!r)return t.apply(void 0,n).catch(function(i){throw r=!0,i})})}))}function lF(e){return e.queue=0,e.map=xme,e}uF.exports=function(e){if(e)return lF(wme(e));else return lF(function(t){return t()})}});function fF(e){if(e.scheme!=="wss"&&e.scheme!=="ws")throw new Ce(`The WebSocket client supports only "libsql:", "wss:" and "ws:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${Yn}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Ce("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="ws"&&e.tls)throw new Ce('A "ws:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="wss"&&!e.tls)throw new Ce('A "wss:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=dp(e.scheme,e.authority,e.path),r;try{r=uT(t,e.authToken)}catch(o){if(o instanceof yp){let n=e.scheme==="wss"?"https":"http",i=dp(n,e.authority,e.path);throw new Ce(`This environment does not support WebSockets, please switch to the HTTP client by using a "${n}:" URL (${JSON.stringify(i)}). For more information, please read ${Yn}`,"WEBSOCKETS_NOT_SUPPORTED")}throw st(o)}return new mF(r,t,e.authToken,e.intMode,e.concurrency)}class mF{#e;#t;#r;#n;#o;closed;protocol;#i;#a;constructor(e,t,r,o,n){this.#e=t,this.#t=r,this.#r=o,this.#n=this.#c(e),this.#o=void 0,this.closed=!1,this.protocol="ws",this.#a=pF.default(n)}async limit(e){return this.#a(e)}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.limit(async()=>{let o=await this.#s();try{let n=Zo(r);o.conn.sqlCache.apply([n]);let i=o.stream.query(n);o.stream.closeGracefully();let s=await i;return kl(s)}catch(n){throw st(n)}finally{this._closeStream(o)}})}async batch(e,t="deferred"){return this.limit(async()=>{let r=await this.#s();try{let n=e.map((u)=>{if(Array.isArray(u))return{sql:u[0],args:u[1]||[]};return u}).map(Zo),i=await r.conn.client.getVersion();r.conn.sqlCache.apply(n);let s=r.stream.batch(i>=3);return await El(t,i,s,n)}catch(o){throw st(o)}finally{this._closeStream(r)}})}async migrate(e){return this.limit(async()=>{let t=await this.#s();try{let r=e.map(Zo),o=await t.conn.client.getVersion(),n=t.stream.batch(o>=3);return await El("deferred",o,n,r,!0)}catch(r){throw st(r)}finally{this._closeStream(t)}})}async transaction(e="write"){return this.limit(async()=>{let t=await this.#s();try{let r=await t.conn.client.getVersion();return new hF(this,t,e,r)}catch(r){throw this._closeStream(t),st(r)}})}async executeMultiple(e){return this.limit(async()=>{let t=await this.#s();try{let r=t.stream.sequence(e);t.stream.closeGracefully(),await r}catch(r){throw st(r)}finally{this._closeStream(t)}})}sync(){throw new Ce("sync not supported in ws mode","SYNC_NOT_SUPPORTED")}async#s(){if(this.closed)throw new Ce("The client is closed","CLIENT_CLOSED");if(new Date().valueOf()-this.#n.openTime.valueOf()>_me&&this.#o===void 0){let o=this.#c();this.#o=o,o.client.getVersion().then((n)=>{if(this.#n!==o){if(this.#n.streamStates.size===0)this.#n.client.close()}this.#n=o,this.#o=void 0},(n)=>{this.#o=void 0})}if(this.#n.client.closed)try{if(this.#o!==void 0)this.#n=this.#o;else this.#n=this.#c()}catch(o){throw st(o)}let r=this.#n;try{if(r.useSqlCache===void 0){if(r.useSqlCache=await r.client.getVersion()>=2,r.useSqlCache)r.sqlCache.capacity=dF}let o=r.client.openStream();o.intMode=this.#r;let n={conn:r,stream:o};return r.streamStates.add(n),n}catch(o){throw st(o)}}#c(e){try{return e??=uT(this.#e,this.#t),{client:e,useSqlCache:void 0,sqlCache:new Il(e,0),openTime:new Date,streamStates:new Set}}catch(t){throw st(t)}}async reconnect(){try{for(let r of Array.from(this.#n.streamStates))try{r.stream.close()}catch{}this.#n.client.close()}catch{}if(this.#o){try{this.#o.client.close()}catch{}this.#o=void 0}let e=this.#c(),t=await e.client.getVersion();if(e.useSqlCache=t>=2,e.useSqlCache)e.sqlCache.capacity=dF;this.#n=e,this.closed=!1}_closeStream(e){e.stream.close();let t=e.conn;if(t.streamStates.delete(e),t.streamStates.size===0&&t!==this.#n)t.client.close()}close(){if(this.#n.client.close(),this.closed=!0,this.#o){try{this.#o.client.close()}catch{}this.#o=void 0}this.closed=!0}}var pF,_me=60000,dF=100,hF;var gF=v(()=>{Uy();vn();mp();fT();yy();ul();pF=Ml(mT(),1);vn();hF=class hF extends Op{#e;#t;constructor(e,t,r,o){super(r,o);this.#e=e,this.#t=t}_getStream(){return this.#t.stream}_getSqlCache(){return this.#t.conn.sqlCache}close(){this.#e._closeStream(this.#t)}get closed(){return this.#t.stream.closed}}});function bF(e){if(e.scheme!=="https"&&e.scheme!=="http")throw new Ce(`The HTTP client supports only "libsql:", "https:" and "http:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${Yn}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Ce("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="http"&&e.tls)throw new Ce('A "http:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="https"&&!e.tls)throw new Ce('A "https:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=dp(e.scheme,e.authority,e.path);return new vF(t,e.authToken,e.intMode,e.fetch,e.concurrency,e.remoteEncryptionKey)}class vF{#e;protocol;#t;#r;#n;#o;#i;#a;#s;constructor(e,t,r,o,n,i){this.#t=e,this.#i=t,this.#r=r,this.#n=o,this.#o=n,this.#a=i,this.#e=dT(this.#t,this.#i,this.#n,i),this.#e.intMode=this.#r,this.protocol="http",this.#s=yF.default(this.#o)}async limit(e){return this.#s(e)}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.limit(async()=>{try{let o=Zo(r),n,i=this.#e.openStream();try{n=i.query(o)}finally{i.closeGracefully()}let s=await n;return kl(s)}catch(o){throw st(o)}})}async batch(e,t="deferred"){return this.limit(async()=>{try{let o=e.map((l)=>{if(Array.isArray(l))return{sql:l[0],args:l[1]||[]};return l}).map(Zo),n=await this.#e.getVersion(),i,s=this.#e.openStream();try{new Il(s,SF).apply(o);let u=s.batch(!1);i=El(t,n,u,o)}finally{s.closeGracefully()}return await i}catch(r){throw st(r)}})}async migrate(e){return this.limit(async()=>{try{let t=e.map(Zo),r=await this.#e.getVersion(),o,n=this.#e.openStream();try{let s=n.batch(!1);o=El("deferred",r,s,t,!0)}finally{n.closeGracefully()}return await o}catch(t){throw st(t)}})}async transaction(e="write"){return this.limit(async()=>{try{let t=await this.#e.getVersion();return new wF(this.#e.openStream(),e,t)}catch(t){throw st(t)}})}async executeMultiple(e){return this.limit(async()=>{try{let t,r=this.#e.openStream();try{t=r.sequence(e)}finally{r.closeGracefully()}await t}catch(t){throw st(t)}})}sync(){throw new Ce("sync not supported in http mode","SYNC_NOT_SUPPORTED")}close(){this.#e.close()}async reconnect(){try{if(!this.closed)this.#e.close()}finally{this.#e=dT(this.#t,this.#i,this.#n,this.#a),this.#e.intMode=this.#r}}get closed(){return this.#e.closed}}var yF,SF=30,wF;var xF=v(()=>{Uy();vn();mp();fT();yy();ul();yF=Ml(mT(),1);vn();wF=class wF extends Op{#e;#t;constructor(e,t,r){super(t,r);this.#e=e,this.#t=new Il(e,SF)}_getStream(){return this.#e}_getSqlCache(){return this.#t}close(){this.#e.close()}get closed(){return this.#e.closed}}});function Al(e){return Eme(fp(e,!0))}function Eme(e){if(e.scheme==="wss"||e.scheme==="ws")return fF(e);else if(e.scheme==="https"||e.scheme==="http")return bF(e);else return y4(e)}var hT=v(()=>{mp();x4();gF();xF();vn()});function oe(e,t){if(!e||typeof e!=="object")return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,F))throw Error(`Class "${t.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let r=Object.getPrototypeOf(e).constructor;if(r)while(r){if(F in r&&r[F]===t[F])return!0;r=Object.getPrototypeOf(r)}return!1}var F;var $e=v(()=>{F=Symbol.for("drizzle:entityKind")});var He;var _n=v(()=>{$e();He=class He{constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.keyAsName=t.keyAsName,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.onUpdateFn=t.onUpdateFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType,this.generated=t.generated,this.generatedIdentity=t.generatedIdentity}static[F]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(e){return e}mapToDriverValue(e){return e}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}});var Cp;var My=v(()=>{$e();Cp=class Cp{static[F]="ColumnBuilder";config;constructor(e,t,r){this.config={name:e,keyAsName:e==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:t,columnType:r,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e){if(this.config.name!=="")return;this.config.name=e}}});var ir;var Rl=v(()=>{ir=Symbol.for("drizzle:Name")});var gT,_F;var EF=v(()=>{$e();Rl();gT=class gT{static[F]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,t){if(this.reference=()=>{let{name:r,columns:o,foreignColumns:n}=e();return{name:r,columns:o,foreignTable:n[0].table,foreignColumns:n}},t)this._onUpdate=t.onUpdate,this._onDelete=t.onDelete}onUpdate(e){return this._onUpdate=e===void 0?"no action":e,this}onDelete(e){return this._onDelete=e===void 0?"no action":e,this}build(e){return new _F(e,this)}};_F=class _F{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[F]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),o=t.map((s)=>s.name),n=r.map((s)=>s.name),i=[this.table[ir],...o,r[0].table[ir],...n];return e??`${i.join("_")}_fk`}}});function qy(e,...t){return e(...t)}var yT=()=>{};function bT(e,t){return`${e[ir]}_${t.join("_")}_unique`}var kF,kme,IF;var AF=v(()=>{$e();Rl();kF=class kF{constructor(e,t){this.name=t,this.columns=e}static[F]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new IF(e,this.columns,this.nullsNotDistinctConfig,this.name)}};kme=class kme{static[F]="PgUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new kF(e,this.name)}};IF=class IF{constructor(e,t,r,o){this.table=e,this.columns=t,this.name=o??bT(this.table,this.columns.map((n)=>n.name)),this.nullsNotDistinct=r}static[F]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}}});function RF(e,t,r){for(let o=t;o<e.length;o++){let n=e[o];if(n==="\\"){o++;continue}if(n==='"')return[e.slice(t,o).replace(/\\/g,""),o+1];if(r)continue;if(n===","||n==="}")return[e.slice(t,o).replace(/\\/g,""),o]}return[e.slice(t).replace(/\\/g,""),e.length]}function TF(e,t=0){let r=[],o=t,n=!1;while(o<e.length){let i=e[o];if(i===","){if(n||o===t)r.push("");n=!0,o++;continue}if(n=!1,i==="\\"){o+=2;continue}if(i==='"'){let[l,u]=RF(e,o+1,!0);r.push(l),o=u;continue}if(i==="}")return[r,o+1];if(i==="{"){let[l,u]=TF(e,o+1);r.push(l),o=u;continue}let[s,a]=RF(e,o,!1);r.push(s),o=a}return[r,o]}function $F(e){let[t]=TF(e,1);return t}function ST(e){return`{${e.map((t)=>{if(Array.isArray(t))return ST(t);if(typeof t==="string")return`"${t.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${t}`}).join(",")}}`}var OF=()=>{};var Pp,Tl,CF,Ime,PF,vT;var zF=v(()=>{My();_n();$e();EF();yT();AF();OF();Pp=class Pp extends Cp{foreignKeyConfigs=[];static[F]="PgColumnBuilder";array(e){return new PF(this.config.name,this,e)}references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e,t){return this.config.isUnique=!0,this.config.uniqueName=e,this.config.uniqueType=t?.nulls,this}generatedAlwaysAs(e){return this.config.generated={as:e,type:"always",mode:"stored"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:r,actions:o})=>qy((n,i)=>{let s=new gT(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(i.onUpdate)s.onUpdate(i.onUpdate);if(i.onDelete)s.onDelete(i.onDelete);return s.build(t)},r,o))}buildExtraConfigColumn(e){return new CF(e,this.config)}};Tl=class Tl extends He{constructor(e,t){if(!t.uniqueName)t.uniqueName=bT(e,[t.name]);super(e,t);this.table=e}static[F]="PgColumn"};CF=class CF extends Tl{static[F]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(e){return this.indexConfig.opClass=e,this}};Ime=class Ime{static[F]="IndexedColumn";constructor(e,t,r,o){this.name=e,this.keyAsName=t,this.type=r,this.indexConfig=o}name;keyAsName;type;indexConfig};PF=class PF extends Pp{static[F]="PgArrayBuilder";constructor(e,t,r){super(e,"array","PgArray");this.config.baseBuilder=t,this.config.size=r}build(e){let t=this.config.baseBuilder.build(e);return new vT(e,this.config,t)}};vT=class vT extends Tl{constructor(e,t,r,o){super(e,t);this.baseColumn=r,this.range=o,this.size=t.size}size;static[F]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(e){if(typeof e==="string")e=$F(e);return e.map((t)=>this.baseColumn.mapFromDriverValue(t))}mapToDriverValue(e,t=!1){let r=e.map((o)=>o===null?null:oe(this.baseColumn,vT)?this.baseColumn.mapToDriverValue(o,!0):this.baseColumn.mapToDriverValue(o));if(t)return r;return ST(r)}}});function LF(e){return!!e&&typeof e==="function"&&NF in e&&e[NF]===!0}var Ame,DF,NF,Rme,BF;var jF=v(()=>{$e();zF();Ame=class Ame extends Pp{static[F]="PgEnumObjectColumnBuilder";constructor(e,t){super(e,"string","PgEnumObjectColumn");this.config.enum=t}build(e){return new DF(e,this.config)}};DF=class DF extends Tl{static[F]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}};NF=Symbol.for("drizzle:isPgEnum");Rme=class Rme extends Pp{static[F]="PgEnumColumnBuilder";constructor(e,t){super(e,"string","PgEnumColumn");this.config.enum=t}build(e){return new BF(e,this.config)}};BF=class BF extends Tl{static[F]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}}});var dt,zp;var En=v(()=>{$e();dt=class dt{static[F]="Subquery";constructor(e,t,r,o=!1,n=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:r,isWith:o,usedTables:n}}};zp=class zp extends dt{static[F]="WithSubquery"}});var ZF="0.45.2";var UF=()=>{};var wT,xT,MF;var qF=v(()=>{yT();UF();MF={startActiveSpan(e,t){if(!wT)return t();if(!xT)xT=wT.trace.getTracer("drizzle-orm",ZF);return qy((r,o)=>o.startActiveSpan(e,(n)=>{try{return t(n)}catch(i){throw n.setStatus({code:r.SpanStatusCode.ERROR,message:i instanceof Error?i.message:"Unknown error"}),i}finally{n.end()}}),wT,xT)}}});var pt;var Uo=v(()=>{pt=Symbol.for("drizzle:ViewBaseConfig")});function es(e){return e[ir]}function ha(e){return`${e[Fy]??"public"}.${e[ir]}`}var Fy,Ky,FF,_T,ET,Np,KF,Tme,he;var sr=v(()=>{$e();Rl();Fy=Symbol.for("drizzle:Schema"),Ky=Symbol.for("drizzle:Columns"),FF=Symbol.for("drizzle:ExtraConfigColumns"),_T=Symbol.for("drizzle:OriginalName"),ET=Symbol.for("drizzle:BaseName"),Np=Symbol.for("drizzle:IsAlias"),KF=Symbol.for("drizzle:ExtraConfigBuilder"),Tme=Symbol.for("drizzle:IsDrizzleTable");he=class he{static[F]="Table";static Symbol={Name:ir,Schema:Fy,OriginalName:_T,Columns:Ky,ExtraConfigColumns:FF,BaseName:ET,IsAlias:Np,ExtraConfigBuilder:KF};[ir];[_T];[Fy];[Ky];[FF];[ET];[Np]=!1;[Tme]=!0;[KF]=void 0;constructor(e,t,r){this[ir]=this[_T]=e,this[Fy]=t,this[ET]=r}}});function kT(e){return e!==null&&e!==void 0&&typeof e.getSQL==="function"}function Ome(e){let t={sql:"",params:[]};for(let r of e)if(t.sql+=r.sql,t.params.push(...r.params),r.typings?.length){if(!t.typings)t.typings=[];t.typings.push(...r.typings)}return t}function JF(e){return typeof e==="object"&&e!==null&&"mapToDriverValue"in e&&typeof e.mapToDriverValue==="function"}function C(e,...t){let r=[];if(t.length>0||e.length>0&&e[0]!=="")r.push(new Nt(e[0]));for(let[o,n]of t.entries())r.push(n,new Nt(e[o+1]));return new _e(r)}function Dp(e,t){return e.map((r)=>{if(oe(r,ts)){if(!(r.name in t))throw Error(`No value for placeholder "${r.name}" was provided`);return t[r.name]}if(oe(r,Ur)&&oe(r.value,ts)){if(!(r.value.name in t))throw Error(`No value for placeholder "${r.value.name}" was provided`);return r.encoder.mapToDriverValue(t[r.value.name])}return r})}var $me,Nt,_e,Jy,HF,VF,Pje,Ur,ts,Cme,on;var Qt=v(()=>{$e();jF();En();qF();Uo();_n();sr();$me=class $me{static[F]="FakePrimitiveParam"};Nt=class Nt{static[F]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new _e([this])}};_e=class _e{constructor(e){this.queryChunks=e;for(let t of e)if(oe(t,he)){let r=t[he.Symbol.Schema];this.usedTables.push(r===void 0?t[he.Symbol.Name]:r+"."+t[he.Symbol.Name])}}static[F]="SQL";decoder=HF;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return MF.startActiveSpan("drizzle.buildSQL",(t)=>{let r=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":r.sql,"drizzle.query.params":JSON.stringify(r.params)}),r})}buildQueryFromSourceParams(e,t){let r=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{casing:o,escapeName:n,escapeParam:i,prepareTyping:s,inlineParams:a,paramStartIndex:l}=r;return Ome(e.map((u)=>{if(oe(u,Nt))return{sql:u.value.join(""),params:[]};if(oe(u,Jy))return{sql:n(u.value),params:[]};if(u===void 0)return{sql:"",params:[]};if(Array.isArray(u)){let d=[new Nt("(")];for(let[p,m]of u.entries())if(d.push(m),p<u.length-1)d.push(new Nt(", "));return d.push(new Nt(")")),this.buildQueryFromSourceParams(d,r)}if(oe(u,_e))return this.buildQueryFromSourceParams(u.queryChunks,{...r,inlineParams:a||u.shouldInlineParams});if(oe(u,he)){let d=u[he.Symbol.Schema],p=u[he.Symbol.Name];return{sql:d===void 0||u[Np]?n(p):n(d)+"."+n(p),params:[]}}if(oe(u,He)){let d=o.getColumnCasing(u);if(t.invokeSource==="indexes")return{sql:n(d),params:[]};let p=u.table[he.Symbol.Schema];return{sql:u.table[Np]||p===void 0?n(u.table[he.Symbol.Name])+"."+n(d):n(p)+"."+n(u.table[he.Symbol.Name])+"."+n(d),params:[]}}if(oe(u,on)){let d=u[pt].schema,p=u[pt].name;return{sql:d===void 0||u[pt].isAlias?n(p):n(d)+"."+n(p),params:[]}}if(oe(u,Ur)){if(oe(u.value,ts))return{sql:i(l.value++,u),params:[u],typings:["none"]};let d=u.value===null?null:u.encoder.mapToDriverValue(u.value);if(oe(d,_e))return this.buildQueryFromSourceParams([d],r);if(a)return{sql:this.mapInlineParam(d,r),params:[]};let p=["none"];if(s)p=[s(u.encoder)];return{sql:i(l.value++,d),params:[d],typings:p}}if(oe(u,ts))return{sql:i(l.value++,u),params:[u],typings:["none"]};if(oe(u,_e.Aliased)&&u.fieldAlias!==void 0)return{sql:n(u.fieldAlias),params:[]};if(oe(u,dt)){if(u._.isWith)return{sql:n(u._.alias),params:[]};return this.buildQueryFromSourceParams([new Nt("("),u._.sql,new Nt(") "),new Jy(u._.alias)],r)}if(LF(u)){if(u.schema)return{sql:n(u.schema)+"."+n(u.enumName),params:[]};return{sql:n(u.enumName),params:[]}}if(kT(u)){if(u.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([u.getSQL()],r);return this.buildQueryFromSourceParams([new Nt("("),u.getSQL(),new Nt(")")],r)}if(a)return{sql:this.mapInlineParam(u,r),params:[]};return{sql:i(l.value++,u),params:[u],typings:["none"]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return"null";if(typeof e==="number"||typeof e==="boolean")return e.toString();if(typeof e==="string")return t(e);if(typeof e==="object"){let r=e.toString();if(r==="[object Object]")return t(JSON.stringify(e));return t(r)}throw Error("Unexpected param value: "+e)}getSQL(){return this}as(e){if(e===void 0)return this;return new _e.Aliased(this,e)}mapWith(e){return this.decoder=typeof e==="function"?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}if(e){return e?this:void 0}};Jy=class Jy{constructor(e){this.value=e}static[F]="Name";brand;getSQL(){return new _e([this])}};HF={mapFromDriverValue:(e)=>e},VF={mapToDriverValue:(e)=>e},Pje={...HF,...VF};Ur=class Ur{constructor(e,t=VF){this.value=e,this.encoder=t}static[F]="Param";brand;getSQL(){return new _e([this])}};((e)=>{function t(){return new _e([])}e.empty=t;function r(l){return new _e(l)}e.fromList=r;function o(l){return new _e([new Nt(l)])}e.raw=o;function n(l,u){let d=[];for(let[p,m]of l.entries()){if(p>0&&u!==void 0)d.push(u);d.push(m)}return new _e(d)}e.join=n;function i(l){return new Jy(l)}e.identifier=i;function s(l){return new ts(l)}e.placeholder=s;function a(l,u){return new Ur(l,u)}e.param=a})(C||(C={}));((e)=>{class t{constructor(r,o){this.sql=r,this.fieldAlias=o}static[F]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new t(this.sql,this.fieldAlias)}}e.Aliased=t})(_e||(_e={}));ts=class ts{constructor(e){this.name=e}static[F]="Placeholder";getSQL(){return new _e([this])}};Cme=Symbol.for("drizzle:IsDrizzleView");on=class on{static[F]="View";[pt];[Cme]=!0;constructor({name:e,schema:t,selectedFields:r,query:o}){this[pt]={name:e,originalName:e,schema:t,selectedFields:r,query:o,isExisting:!o,isAlias:!1}}getSQL(){return new _e([this])}};He.prototype.getSQL=function(){return new _e([this])};he.prototype.getSQL=function(){return new _e([this])};dt.prototype.getSQL=function(){return new _e([this])}});function IT(e,t,r){let o={},n=e.reduce((i,{path:s,field:a},l)=>{let u;if(oe(a,He))u=a;else if(oe(a,_e))u=a.decoder;else if(oe(a,dt))u=a._.sql.decoder;else u=a.sql.decoder;let d=i;for(let[p,m]of s.entries())if(p<s.length-1){if(!(m in d))d[m]={};d=d[m]}else{let h=t[l],b=d[m]=h===null?null:u.mapFromDriverValue(h);if(r&&oe(a,He)&&s.length===2){let y=s[0];if(!(y in o))o[y]=b===null?es(a.table):!1;else if(typeof o[y]==="string"&&o[y]!==es(a.table))o[y]=!1}}return i},{});if(r&&Object.keys(o).length>0){for(let[i,s]of Object.entries(o))if(typeof s==="string"&&!r[s])n[i]=null}return n}function sn(e,t){return Object.entries(e).reduce((r,[o,n])=>{if(typeof o!=="string")return r;let i=t?[...t,o]:[o];if(oe(n,He)||oe(n,_e)||oe(n,_e.Aliased)||oe(n,dt))r.push({path:i,field:n});else if(oe(n,he))r.push(...sn(n[he.Symbol.Columns],i));else r.push(...sn(n,i));return r},[])}function Lp(e,t){let r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return!1;for(let[n,i]of r.entries())if(i!==o[n])return!1;return!0}function Hy(e,t){let r=Object.entries(t).filter(([,o])=>o!==void 0).map(([o,n])=>{if(oe(n,_e)||oe(n,He))return[o,n];else return[o,new Ur(n,e[he.Symbol.Columns][o])]});if(r.length===0)throw Error("No values to set");return Object.fromEntries(r)}function WF(e,t){for(let r of t)for(let o of Object.getOwnPropertyNames(r.prototype)){if(o==="constructor")continue;Object.defineProperty(e.prototype,o,Object.getOwnPropertyDescriptor(r.prototype,o)||Object.create(null))}}function Vy(e){return e[he.Symbol.Columns]}function Bp(e){return oe(e,dt)?e._.alias:oe(e,on)?e[pt].name:oe(e,_e)?void 0:e[he.Symbol.IsAlias]?e[he.Symbol.Name]:e[he.Symbol.BaseName]}function ro(e,t){return{name:typeof e==="string"&&e.length>0?e:"",config:typeof e==="object"?e:t}}function GF(e){if(typeof e!=="object"||e===null)return!1;if(e.constructor.name!=="Object")return!1;if("logger"in e){let t=typeof e.logger;if(t!=="boolean"&&(t!=="object"||typeof e.logger.logQuery!=="function")&&t!=="undefined")return!1;return!0}if("schema"in e){let t=typeof e.schema;if(t!=="object"&&t!=="undefined")return!1;return!0}if("casing"in e){let t=typeof e.casing;if(t!=="string"&&t!=="undefined")return!1;return!0}if("mode"in e){if(e.mode!=="default"||e.mode!=="planetscale"||e.mode!==void 0)return!1;return!0}if("connection"in e){let t=typeof e.connection;if(t!=="string"&&t!=="object"&&t!=="undefined")return!1;return!0}if("client"in e){let t=typeof e.client;if(t!=="object"&&t!=="function"&&t!=="undefined")return!1;return!0}if(Object.keys(e).length===0)return!0;return!1}var AT;var Sr=v(()=>{_n();$e();Qt();En();sr();Uo();AT=typeof TextDecoder>"u"?null:new TextDecoder});var QF,RT,TT;var Wy=v(()=>{$e();QF=class QF{static[F]="ConsoleLogWriter";write(e){console.log(e)}};RT=class RT{static[F]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new QF}logQuery(e,t){let r=t.map((n)=>{try{return JSON.stringify(n)}catch{return String(n)}}),o=r.length?` -- params: [${r.join(", ")}]`:"";this.writer.write(`Query: ${e}${o}`)}};TT=class TT{static[F]="NoopLogger";logQuery(){}}});var YF,XF,$T;var e3=v(()=>{$e();sr();YF=Symbol.for("drizzle:PgInlineForeignKeys"),XF=Symbol.for("drizzle:EnableRLS");$T=class $T extends he{static[F]="PgTable";static Symbol=Object.assign({},he.Symbol,{InlineForeignKeys:YF,EnableRLS:XF});[YF]=[];[XF]=!1;[he.Symbol.ExtraConfigBuilder]=void 0;[he.Symbol.ExtraConfigColumns]={}}});var OT,t3;var r3=v(()=>{$e();e3();OT=class OT{static[F]="PgPrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new t3(e,this.columns,this.name)}};t3=class t3{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[F]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[$T.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function Tr(e,t){if(JF(t)&&!kT(e)&&!oe(e,Ur)&&!oe(e,ts)&&!oe(e,He)&&!oe(e,he)&&!oe(e,on))return new Ur(e,t);return e}function tt(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new _e(t);return new _e([new Nt("("),C.join(t,new Nt(" and ")),new Nt(")")])}function an(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new _e(t);return new _e([new Nt("("),C.join(t,new Nt(" or ")),new Nt(")")])}function o3(e){return C`not ${e}`}function ns(e,t){if(Array.isArray(t)){if(t.length===0)return C`false`;return C`${e} in ${t.map((r)=>Tr(r,e))}`}return C`${e} in ${Tr(t,e)}`}function Gy(e,t){if(Array.isArray(t)){if(t.length===0)return C`true`;return C`${e} not in ${t.map((r)=>Tr(r,e))}`}return C`${e} not in ${Tr(t,e)}`}function Mr(e){return C`${e} is null`}function a3(e){return C`${e} is not null`}function Qy(e){return C`exists ${e}`}function os(e){return C`not exists ${e}`}function c3(e,t,r){return C`${e} between ${Tr(t,e)} and ${Tr(r,e)}`}function l3(e,t,r){return C`${e} not between ${Tr(t,e)} and ${Tr(r,e)}`}function u3(e,t){return C`${e} like ${t}`}function d3(e,t){return C`${e} not like ${t}`}function p3(e,t){return C`${e} ilike ${t}`}function f3(e,t){return C`${e} not ilike ${t}`}var je=(e,t)=>C`${e} = ${Tr(t,e)}`,n3=(e,t)=>C`${e} <> ${Tr(t,e)}`,kn=(e,t)=>C`${e} > ${Tr(t,e)}`,i3=(e,t)=>C`${e} >= ${Tr(t,e)}`,s3=(e,t)=>C`${e} < ${Tr(t,e)}`,rs=(e,t)=>C`${e} <= ${Tr(t,e)}`;var m3=v(()=>{_n();$e();sr();Qt()});function Mo(e){return C`${e} asc`}function ga(e){return C`${e} desc`}var h3=v(()=>{Qt()});var CT=v(()=>{m3();h3()});function y3(){return{and:tt,between:c3,eq:je,exists:Qy,gt:kn,gte:i3,ilike:p3,inArray:ns,isNull:Mr,isNotNull:a3,like:u3,lt:s3,lte:rs,ne:n3,not:o3,notBetween:l3,notExists:os,notLike:d3,notIlike:f3,notInArray:Gy,or:an,sql:C}}function b3(){return{sql:C,asc:Mo,desc:ga}}function S3(e,t){if(Object.keys(e).length===1&&"default"in e&&!oe(e.default,he))e=e.default;let r={},o={},n={};for(let[i,s]of Object.entries(e))if(oe(s,he)){let a=ha(s),l=o[a];r[a]=i,n[i]={tsName:i,dbName:s[he.Symbol.Name],schema:s[he.Symbol.Schema],columns:s[he.Symbol.Columns],relations:l?.relations??{},primaryKey:l?.primaryKey??[]};for(let d of Object.values(s[he.Symbol.Columns]))if(d.primary)n[i].primaryKey.push(d);let u=s[he.Symbol.ExtraConfigBuilder]?.(s[he.Symbol.ExtraConfigColumns]);if(u){for(let d of Object.values(u))if(oe(d,OT))n[i].primaryKey.push(...d.columns)}}else if(oe(s,g3)){let a=ha(s.table),l=r[a],u=s.config(t(s.table)),d;for(let[p,m]of Object.entries(u))if(l){let h=n[l];if(h.relations[p]=m,d)h.primaryKey.push(...d)}else{if(!(a in o))o[a]={relations:{},primaryKey:d};o[a].relations[p]=m}}return{tables:n,tableNamesMap:r}}function Pme(e){return function(r,o){return new is(e,r,o,o?.fields.reduce((n,i)=>n&&i.notNull,!0)??!1)}}function zme(e){return function(r,o){return new jp(e,r,o)}}function v3(e,t,r){if(oe(r,is)&&r.config)return{fields:r.config.fields,references:r.config.references};let o=t[ha(r.referencedTable)];if(!o)throw Error(`Table "${r.referencedTable[he.Symbol.Name]}" not found in schema`);let n=e[o];if(!n)throw Error(`Table "${o}" not found in schema`);let i=r.sourceTable,s=t[ha(i)];if(!s)throw Error(`Table "${i[he.Symbol.Name]}" not found in schema`);let a=[];for(let l of Object.values(n.relations))if(r.relationName&&r!==l&&l.relationName===r.relationName||!r.relationName&&l.referencedTable===r.sourceTable)a.push(l);if(a.length>1)throw r.relationName?Error(`There are multiple relations with name "${r.relationName}" in table "${o}"`):Error(`There are multiple relations between "${o}" and "${r.sourceTable[he.Symbol.Name]}". Please specify relation name`);if(a[0]&&oe(a[0],is)&&a[0].config)return{fields:a[0].config.references,references:a[0].config.fields};throw Error(`There is not enough information to infer relation "${s}.${r.fieldName}"`)}function w3(e){return{one:Pme(e),many:zme(e)}}function Yy(e,t,r,o,n=(i)=>i){let i={};for(let[s,a]of o.entries())if(a.isJson){let l=t.relations[a.tsKey],u=r[s],d=typeof u==="string"?JSON.parse(u):u;i[a.tsKey]=oe(l,is)?d&&Yy(e,e[a.relationTableTsKey],d,a.selection,n):d.map((p)=>Yy(e,e[a.relationTableTsKey],p,a.selection,n))}else{let l=n(r[s]),u=a.field,d;if(oe(u,He))d=u;else if(oe(u,_e))d=u.decoder;else d=u.sql.decoder;i[a.tsKey]=l===null?null:d.mapFromDriverValue(l)}return i}var PT,g3,is,jp;var Zp=v(()=>{sr();_n();$e();r3();CT();Qt();PT=class PT{constructor(e,t,r){this.sourceTable=e,this.referencedTable=t,this.relationName=r,this.referencedTableName=t[he.Symbol.Name]}static[F]="Relation";referencedTableName;fieldName};g3=class g3{constructor(e,t){this.table=e,this.config=t}static[F]="Relations"};is=class is extends PT{constructor(e,t,r,o){super(e,t,r?.relationName);this.config=r,this.isNullable=o}static[F]="One";withFieldName(e){let t=new is(this.sourceTable,this.referencedTable,this.config,this.isNullable);return t.fieldName=e,t}};jp=class jp extends PT{constructor(e,t,r){super(e,t,r?.relationName);this.config=r}static[F]="Many";withFieldName(e){let t=new jp(this.sourceTable,this.referencedTable,this.config);return t.fieldName=e,t}}});function Up(e,t){return new Proxy(e,new ya(t,!1))}function no(e,t){return new Proxy(e,new $l(new Proxy(e.table,new ya(t,!1))))}function zT(e,t){return new _e.Aliased(Mp(e.sql,t),e.fieldAlias)}function Mp(e,t){return C.join(e.queryChunks.map((r)=>{if(oe(r,He))return no(r,t);if(oe(r,_e))return Mp(r,t);if(oe(r,_e.Aliased))return zT(r,t);return r}))}var $l,ya,Nme;var qp=v(()=>{_n();$e();Qt();sr();Uo();$l=class $l{constructor(e){this.table=e}static[F]="ColumnAliasProxyHandler";get(e,t){if(t==="table")return this.table;return e[t]}};ya=class ya{constructor(e,t){this.alias=e,this.replaceOriginalName=t}static[F]="TableAliasProxyHandler";get(e,t){if(t===he.Symbol.IsAlias)return!0;if(t===he.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===he.Symbol.OriginalName)return this.alias;if(t===pt)return{...e[pt],name:this.alias,isAlias:!0};if(t===he.Symbol.Columns){let o=e[he.Symbol.Columns];if(!o)return o;let n={};return Object.keys(o).map((i)=>{n[i]=new Proxy(o[i],new $l(new Proxy(e,this)))}),n}let r=e[t];if(oe(r,He))return new Proxy(r,new $l(new Proxy(e,this)));return r}};Nme=class Nme{constructor(e){this.alias=e}static[F]="RelationTableAliasProxyHandler";get(e,t){if(t==="sourceTable")return Up(e.sourceTable,this.alias);return e[t]}}});var at;var ba=v(()=>{qp();_n();$e();Qt();En();Uo();at=class at{static[F]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t==="_")return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(t===pt)return{...e[pt],selectedFields:new Proxy(e[pt].selectedFields,this)};if(typeof t==="symbol")return e[t];let o=(oe(e,dt)?e._.selectedFields:oe(e,on)?e[pt].selectedFields:e)[t];if(oe(o,_e.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!o.isSelectionField)return o.sql;let n=o.clone();return n.isSelectionField=!0,n}if(oe(o,_e)){if(this.config.sqlBehavior==="sql")return o;throw Error(`You tried to reference "${t}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(oe(o,He)){if(this.config.alias)return new Proxy(o,new $l(new Proxy(o.table,new ya(this.config.alias,this.config.replaceOriginalName??!1))));return o}if(typeof o!=="object"||o===null)return o;return new Proxy(o,new at(this.config))}}});var vr;var qo=v(()=>{$e();vr=class vr{static[F]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then((t)=>(e?.(),t),(t)=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}}});var NT,x3;var DT=v(()=>{$e();Rl();NT=class NT{static[F]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(e,t){if(this.reference=()=>{let{name:r,columns:o,foreignColumns:n}=e();return{name:r,columns:o,foreignTable:n[0].table,foreignColumns:n}},t)this._onUpdate=t.onUpdate,this._onDelete=t.onDelete}onUpdate(e){return this._onUpdate=e,this}onDelete(e){return this._onDelete=e,this}build(e){return new x3(e,this)}};x3=class x3{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[F]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),o=t.map((s)=>s.name),n=r.map((s)=>s.name),i=[this.table[ir],...o,r[0].table[ir],...n];return e??`${i.join("_")}_fk`}}});function LT(e,t){return`${e[ir]}_${t.join("_")}_unique`}var _3,Dme,E3;var BT=v(()=>{$e();Rl();_3=class _3{constructor(e,t){this.name=t,this.columns=e}static[F]="SQLiteUniqueConstraintBuilder";columns;build(e){return new E3(e,this.columns,this.name)}};Dme=class Dme{static[F]="SQLiteUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new _3(e,this.name)}};E3=class E3{constructor(e,t,r){this.table=e,this.columns=t,this.name=r??LT(this.table,this.columns.map((o)=>o.name))}static[F]="SQLiteUniqueConstraint";columns;name;getName(){return this.name}}});var Zt,yt;var ss=v(()=>{My();_n();$e();DT();BT();Zt=class Zt extends Cp{static[F]="SQLiteColumnBuilder";foreignKeyConfigs=[];references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e){return this.config.isUnique=!0,this.config.uniqueName=e,this}generatedAlwaysAs(e,t){return this.config.generated={as:e,type:"always",mode:t?.mode??"virtual"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:r,actions:o})=>((n,i)=>{let s=new NT(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(i.onUpdate)s.onUpdate(i.onUpdate);if(i.onDelete)s.onDelete(i.onDelete);return s.build(t)})(r,o))}};yt=class yt extends He{constructor(e,t){if(!t.uniqueName)t.uniqueName=LT(e,[t.name]);super(e,t);this.table=e}static[F]="SQLiteColumn"}});function O3(e,t){let{name:r,config:o}=ro(e,t);if(o?.mode==="json")return new A3(r);if(o?.mode==="bigint")return new k3(r);return new T3(r)}var k3,I3,A3,R3,T3,$3;var jT=v(()=>{$e();Sr();ss();k3=class k3 extends Zt{static[F]="SQLiteBigIntBuilder";constructor(e){super(e,"bigint","SQLiteBigInt")}build(e){return new I3(e,this.config)}};I3=class I3 extends yt{static[F]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){let t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return BigInt(t.toString("utf8"))}return BigInt(AT.decode(e))}mapToDriverValue(e){return Buffer.from(e.toString())}};A3=class A3 extends Zt{static[F]="SQLiteBlobJsonBuilder";constructor(e){super(e,"json","SQLiteBlobJson")}build(e){return new R3(e,this.config)}};R3=class R3 extends yt{static[F]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){let t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return JSON.parse(t.toString("utf8"))}return JSON.parse(AT.decode(e))}mapToDriverValue(e){return Buffer.from(JSON.stringify(e))}};T3=class T3 extends Zt{static[F]="SQLiteBlobBufferBuilder";constructor(e){super(e,"buffer","SQLiteBlobBuffer")}build(e){return new $3(e,this.config)}};$3=class $3 extends yt{static[F]="SQLiteBlobBuffer";mapFromDriverValue(e){if(Buffer.isBuffer(e))return e;return Buffer.from(e)}getSQLType(){return"blob"}}});function z3(e){return(t,r)=>{let{name:o,config:n}=ro(t,r);return new C3(o,n,e)}}var C3,P3;var ZT=v(()=>{$e();Sr();ss();C3=class C3 extends Zt{static[F]="SQLiteCustomColumnBuilder";constructor(e,t,r){super(e,"custom","SQLiteCustomColumn");this.config.fieldConfig=t,this.config.customTypeParams=r}build(e){return new P3(e,this.config)}};P3=class P3 extends yt{static[F]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;constructor(e,t){super(e,t);this.sqlName=t.customTypeParams.dataType(t.fieldConfig),this.mapTo=t.customTypeParams.toDriver,this.mapFrom=t.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(e){return typeof this.mapFrom==="function"?this.mapFrom(e):e}mapToDriverValue(e){return typeof this.mapTo==="function"?this.mapTo(e):e}}});function ar(e,t){let{name:r,config:o}=ro(e,t);if(o?.mode==="timestamp"||o?.mode==="timestamp_ms")return new L3(r,o.mode);if(o?.mode==="boolean")return new j3(r,o.mode);return new N3(r)}var Xy,eb,N3,D3,L3,B3,j3,Z3;var UT=v(()=>{$e();Qt();Sr();ss();Xy=class Xy extends Zt{static[F]="SQLiteBaseIntegerBuilder";constructor(e,t,r){super(e,t,r);this.config.autoIncrement=!1}primaryKey(e){if(e?.autoIncrement)this.config.autoIncrement=!0;return this.config.hasDefault=!0,super.primaryKey()}};eb=class eb extends yt{static[F]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}};N3=class N3 extends Xy{static[F]="SQLiteIntegerBuilder";constructor(e){super(e,"number","SQLiteInteger")}build(e){return new D3(e,this.config)}};D3=class D3 extends eb{static[F]="SQLiteInteger"};L3=class L3 extends Xy{static[F]="SQLiteTimestampBuilder";constructor(e,t){super(e,"date","SQLiteTimestamp");this.config.mode=t}defaultNow(){return this.default(C`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new B3(e,this.config)}};B3=class B3 extends eb{static[F]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue(e){if(this.config.mode==="timestamp")return new Date(e*1000);return new Date(e)}mapToDriverValue(e){let t=e.getTime();if(this.config.mode==="timestamp")return Math.floor(t/1000);return t}};j3=class j3 extends Xy{static[F]="SQLiteBooleanBuilder";constructor(e,t){super(e,"boolean","SQLiteBoolean");this.config.mode=t}build(e){return new Z3(e,this.config)}};Z3=class Z3 extends eb{static[F]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue(e){return Number(e)===1}mapToDriverValue(e){return e?1:0}}});function H3(e,t){let{name:r,config:o}=ro(e,t),n=o?.mode;return n==="number"?new q3(r):n==="bigint"?new K3(r):new U3(r)}var U3,M3,q3,F3,K3,J3;var MT=v(()=>{$e();Sr();ss();U3=class U3 extends Zt{static[F]="SQLiteNumericBuilder";constructor(e){super(e,"string","SQLiteNumeric")}build(e){return new M3(e,this.config)}};M3=class M3 extends yt{static[F]="SQLiteNumeric";mapFromDriverValue(e){if(typeof e==="string")return e;return String(e)}getSQLType(){return"numeric"}};q3=class q3 extends Zt{static[F]="SQLiteNumericNumberBuilder";constructor(e){super(e,"number","SQLiteNumericNumber")}build(e){return new F3(e,this.config)}};F3=class F3 extends yt{static[F]="SQLiteNumericNumber";mapFromDriverValue(e){if(typeof e==="number")return e;return Number(e)}mapToDriverValue=String;getSQLType(){return"numeric"}};K3=class K3 extends Zt{static[F]="SQLiteNumericBigIntBuilder";constructor(e){super(e,"bigint","SQLiteNumericBigInt")}build(e){return new J3(e,this.config)}};J3=class J3 extends yt{static[F]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}});function G3(e){return new V3(e??"")}var V3,W3;var qT=v(()=>{$e();ss();V3=class V3 extends Zt{static[F]="SQLiteRealBuilder";constructor(e){super(e,"number","SQLiteReal")}build(e){return new W3(e,this.config)}};W3=class W3 extends yt{static[F]="SQLiteReal";getSQLType(){return"real"}}});function ft(e,t={}){let{name:r,config:o}=ro(e,t);if(o.mode==="json")return new X3(r);return new Q3(r,o)}var Q3,Y3,X3,e5;var FT=v(()=>{$e();Sr();ss();Q3=class Q3 extends Zt{static[F]="SQLiteTextBuilder";constructor(e,t){super(e,"string","SQLiteText");this.config.enumValues=t.enum,this.config.length=t.length}build(e){return new Y3(e,this.config)}};Y3=class Y3 extends yt{static[F]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor(e,t){super(e,t)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}};X3=class X3 extends Zt{static[F]="SQLiteTextJsonBuilder";constructor(e){super(e,"json","SQLiteTextJson")}build(e){return new e5(e,this.config)}};e5=class e5 extends yt{static[F]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue(e){return JSON.parse(e)}mapToDriverValue(e){return JSON.stringify(e)}}});function t5(){return{blob:O3,customType:z3,integer:ar,numeric:H3,real:G3,text:ft}}var r5=v(()=>{jT();ZT();UT();MT();qT();FT()});function Lme(e,t,r,o,n=e){let i=new At(e,o,n),s=typeof t==="function"?t(t5()):t,a=Object.fromEntries(Object.entries(s).map(([u,d])=>{let p=d;p.setName(u);let m=p.build(i);return i[KT].push(...p.buildForeignKeys(m,i)),[u,m]})),l=Object.assign(i,a);if(l[he.Symbol.Columns]=a,l[he.Symbol.ExtraConfigColumns]=a,r)l[At.Symbol.ExtraConfigBuilder]=r;return l}var KT,At,Fp=(e,t,r)=>Lme(e,t,r);var Fo=v(()=>{$e();sr();r5();KT=Symbol.for("drizzle:SQLiteInlineForeignKeys");At=class At extends he{static[F]="SQLiteTable";static Symbol=Object.assign({},he.Symbol,{InlineForeignKeys:KT});[he.Symbol.Columns];[KT]=[];[he.Symbol.ExtraConfigBuilder]=void 0}});var Bme,n5;var o5=v(()=>{$e();Bme=class Bme{constructor(e,t){this.name=e,this.value=t}static[F]="SQLiteCheckBuilder";brand;build(e){return new n5(e,this)}};n5=class n5{constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}static[F]="SQLiteCheck";name;value}});function Ko(e){return new i5(e,!1)}var i5,s5,a5;var c5=v(()=>{$e();i5=class i5{constructor(e,t){this.name=e,this.unique=t}static[F]="SQLiteIndexBuilderOn";on(...e){return new s5(this.name,e,this.unique)}};s5=class s5{static[F]="SQLiteIndexBuilder";config;constructor(e,t,r){this.config={name:e,columns:t,unique:r,where:void 0}}where(e){return this.config.where=e,this}build(e){return new a5(this.config,e)}};a5=class a5{static[F]="SQLiteIndex";config;constructor(e,t){this.config={...e,table:t}}}});var jme,l5;var u5=v(()=>{$e();Fo();jme=class jme{static[F]="SQLitePrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new l5(e,this.columns,this.name)}};l5=class l5{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[F]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[At.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function In(e){if(oe(e,At))return[`${e[he.Symbol.BaseName]}`];if(oe(e,dt))return e._.usedTables??[];if(oe(e,_e))return e.usedTables??[];return[]}var Ol=v(()=>{$e();Qt();En();sr();Fo()});var tb;var d5=v(()=>{$e();qo();ba();Fo();sr();Sr();Ol();tb=class tb extends vr{constructor(e,t,r,o){super();this.table=e,this.session=t,this.dialect=r,this.config={table:e,withList:o}}static[F]="SQLiteDelete";config;where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.table[he.Symbol.Columns],new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];this.config.orderBy=r}else{let t=e;this.config.orderBy=t}return this}limit(e){return this.config.limit=e,this}returning(e=this.table[At.Symbol.Columns]){return this.config.returning=sn(e),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"delete",tables:In(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(e){return this._prepare().execute(e)}$dynamic(){return this}}});function Zme(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((r)=>r.toLowerCase()).join("_")}function Ume(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((r,o,n)=>{let i=n===0?o.toLowerCase():`${o[0].toUpperCase()}${o.slice(1)}`;return r+i},"")}function Mme(e){return e}var JT;var p5=v(()=>{$e();sr();JT=class JT{static[F]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert=e==="snake_case"?Zme:e==="camelCase"?Ume:Mme}getColumnCasing(e){if(!e.keyAsName)return e.name;let t=e.table[he.Symbol.Schema]??"public",r=e.table[he.Symbol.OriginalName],o=`${t}.${r}.${e.name}`;if(!this.cache[o])this.cacheTable(e.table);return this.cache[o]}cacheTable(e){let t=e[he.Symbol.Schema]??"public",r=e[he.Symbol.OriginalName],o=`${t}.${r}`;if(!this.cachedTables[o]){for(let n of Object.values(e[he.Symbol.Columns])){let i=`${o}.${n.name}`;this.cache[i]=this.convert(n.name)}this.cachedTables[o]=!0}}clearCache(){this.cache={},this.cachedTables={}}}});var Cl,Jo,HT;var rb=v(()=>{$e();Cl=class Cl extends Error{static[F]="DrizzleError";constructor({message:e,cause:t}){super(e);this.name="DrizzleError",this.cause=t}};Jo=class Jo extends Error{constructor(e,t,r){super(`Failed query: ${e}
|
|
413
|
+
`)}catch{}}}formatJsonEntry(e,t,r){let o={ts:new Date().toISOString(),level:e,...ol&&{role:ol},msg:t};if(this.context)o.ctx=this.context;if(r.length>0)o.data=r;return JSON.stringify(o)}debugStream(){return this.useStderr?console.error.bind(console):console.debug.bind(console)}silly(e,...t){if(this.level<=ia.SILLY)this.write(this.debugStream(),"silly",e,t)}verbose(e,...t){if(this.level<=ia.VERBOSE)this.write(this.debugStream(),"verbose",e,t)}debug(e,...t){if(this.level<=ia.DEBUG)this.write(this.debugStream(),"debug",e,t)}info(e,...t){if(this.level<=ia.INFO){let r=this.useStderr?console.error.bind(console):console.info.bind(console);this.write(r,"info",e,t)}}warn(e,...t){if(this.level<=ia.WARN)this.write(console.warn.bind(console),"warn",e,t)}error(e,...t){if(this.level<=ia.ERROR)this.write(console.error.bind(console),"error",e,t)}child(e){return new Ar({level:this.level,context:e,useStderr:this.useStderr,format:this.format},this.fileHandle)}setUseStderr(e){this.useStderr=e}}var ia,ol,JNe;var $R=v(()=>{ia={SILLY:0,VERBOSE:1,DEBUG:2,INFO:3,WARN:4,ERROR:5,NONE:6};JNe=Ar.getInstance()});var OR,jde,il,GNe;var lp=v(()=>{Ot();pe();OR=c.enum(["file_operations","content_operations","data_processing","batch_processing"]),jde=c.looseObject({pluginId:c.string().optional(),progressToken:c.union([c.string(),c.number()]).optional(),operationType:OR,operationTarget:c.string().optional(),interfaceType:c.string().optional(),interfaceId:c.string().optional(),conversationId:c.string().optional(),channelId:c.string().optional(),requestedByActor:Vn.optional(),requestedByUserId:c.string().optional(),requestedByInterface:c.string().optional(),silent:c.boolean().optional(),provenance:ko.optional()}),il=c.looseObject({pluginId:c.string().optional(),progressToken:c.union([c.string(),c.number()]).optional(),operationType:OR,operationTarget:c.string().optional(),interfaceType:c.string().optional(),interfaceId:c.string().optional(),conversationId:c.string().optional(),channelId:c.string().optional(),requestedByActor:Vn.optional(),requestedByUserId:c.string().optional(),requestedByInterface:c.string().optional(),silent:c.boolean().optional(),provenance:ko.optional(),rootJobId:c.string()}),GNe=c.enum(["none","skip","replace","coalesce"])});var Zde,Fi=15000;var up=v(()=>{lp();pe();Zde=c.object({id:c.string(),type:c.string(),data:c.string(),status:c.enum(["pending","processing","completed","failed"]),source:c.string().nullable(),priority:c.number(),retryCount:c.number(),maxRetries:c.number(),lastError:c.string().nullable(),lastErrorPublic:c.unknown(),createdAt:c.number(),scheduledFor:c.number(),startedAt:c.number().nullable(),completedAt:c.number().nullable(),attemptId:c.string().nullable(),workerSlotId:c.string().nullable(),workerSessionId:c.string().nullable(),leaseExpiresAt:c.number().nullable(),attemptHeartbeatAt:c.number().nullable(),runtimeUpdatedAt:c.number().nullable(),metadata:il,progress:c.custom((e)=>typeof e==="object"&&e!==null&&("progress"in e)&&typeof e.progress==="number").nullable(),result:c.unknown().nullable().optional()})});var CR,cq,Oe,Ude,Mde,lq,uq,dq;var Do=v(()=>{Ot();pe();lp();CR=c.enum(["pending","processing","completed","failed"]),cq=c.enum(["completed","failed"]),Oe={PENDING:"pending",PROCESSING:"processing",COMPLETED:"completed",FAILED:"failed"},Ude=c.object({id:c.string(),type:c.string(),status:CR,data:c.unknown(),result:c.unknown().optional(),lastError:c.string().optional().nullable(),attempts:c.number(),maxRetries:c.number(),priority:c.number(),createdAt:c.date(),updatedAt:c.date(),processedAt:c.date().optional().nullable(),completedAt:c.date().optional().nullable(),failedAt:c.date().optional().nullable()}),Mde=c.object({jobId:c.string(),type:c.string(),status:cq,result:c.unknown().optional(),error:c.string().optional()}),lq=c.object({success:c.literal(!1),error:c.string().optional()}),uq=c.object({id:c.string(),type:c.enum(["job","batch"]),status:CR,message:c.string().optional(),progress:c.object({current:c.number(),total:c.number(),percentage:c.number()}).optional(),aggregationKey:c.string().optional(),batchDetails:c.object({totalOperations:c.number(),completedOperations:c.number(),failedOperations:c.number(),currentOperation:c.string().optional(),errors:c.array(c.string()).optional()}).optional(),jobDetails:c.object({jobType:c.string(),priority:c.number(),retryCount:c.number()}).optional(),metadata:il}),dq=Oi(II.progress,uq)});var Ce,Wt;var vn=v(()=>{Ce=class Ce extends Error{code;extendedCode;rawCode;constructor(e,t,r,o,n){if(t!==void 0)e=`${t}: ${e}`;super(e,{cause:n});this.code=t,this.extendedCode=r,this.rawCode=o,this.name="LibsqlError"}};Wt=class Wt extends Ce{statementIndex;constructor(e,t,r,o,n,i){super(e,r,o,n,i);this.statementIndex=t,this.name="LibsqlBatchError"}}});function pq(e){let t=qde.exec(e);if(t===null)throw new Ce(`The URL '${e}' is not in a valid format`,"URL_INVALID");let r=t.groups,o=r.scheme,n=r.authority!==void 0?Fde(r.authority):void 0,i=sa(r.path),s=r.query!==void 0?Jde(r.query):void 0,a=r.fragment!==void 0?sa(r.fragment):void 0;return{scheme:o,authority:n,path:i,query:s,fragment:a}}function Fde(e){let t=Kde.exec(e);if(t===null)throw new Ce("The authority part of the URL is not in a valid format","URL_INVALID");let r=t.groups,o=sa(r.host_br??r.host),n=r.port?parseInt(r.port,10):void 0,i=r.username!==void 0?{username:sa(r.username),password:r.password!==void 0?sa(r.password):void 0}:void 0;return{host:o,port:n,userinfo:i}}function Jde(e){let t=e.split("&"),r=[];for(let o of t){if(o==="")continue;let n,i,s=o.indexOf("=");if(s<0)n=o,i="";else n=o.substring(0,s),i=o.substring(s+1);r.push({key:sa(n.replaceAll("+"," ")),value:sa(i.replaceAll("+"," "))})}return{pairs:r}}function sa(e){try{return decodeURIComponent(e)}catch(t){if(t instanceof URIError)throw new Ce(`URL component has invalid percent encoding: ${t}`,"URL_INVALID",void 0,void 0,t);throw t}}function dp(e,t,r){if(t===void 0)throw new Ce(`URL with scheme ${JSON.stringify(e+":")} requires authority (the "//" part)`,"URL_INVALID");let o=`${e}:`,n=Hde(t.host),i=Vde(t.port),a=`//${Wde(t.userinfo)}${n}${i}`,l=r.split("/").map(encodeURIComponent).join("/");if(l!==""&&!l.startsWith("/"))l="/"+l;return new URL(`${o}${a}${l}`)}function Hde(e){return e.includes(":")?`[${encodeURI(e)}]`:encodeURI(e)}function Vde(e){return e!==void 0?`:${e}`:""}function Wde(e){if(e===void 0)return"";let t=encodeURIComponent(e.username),r=e.password!==void 0?`:${encodeURIComponent(e.password)}`:"";return`${t}${r}@`}var qde,Kde;var yy=v(()=>{vn();qde=(()=>new RegExp("^(?<scheme>[A-Za-z][A-Za-z.+-]*):(//(?<authority>[^/?#]*))?(?<path>[^?#]*)(\\?(?<query>[^#]*))?(#(?<fragment>.*))?$","su"))();Kde=(()=>new RegExp("^((?<username>[^:]*)(:(?<password>.*))?@)?((?<host>[^:\\[\\]]*)|(\\[(?<host_br>[^\\[\\]]*)\\]))(:(?<port>[0-9]*))?$","su"))()});var al,fq,mq,pp,by,Gde,Gt,hq,bq=(e)=>e.replace(/=/g,"").replace(/[+\/]/g,(t)=>t=="+"?"-":"_"),Sq=(e)=>e.replace(/[^A-Za-z0-9\+\/]/g,""),vq=(e)=>{let t,r,o,n,i="",s=e.length%3;for(let a=0;a<e.length;){if((r=e.charCodeAt(a++))>255||(o=e.charCodeAt(a++))>255||(n=e.charCodeAt(a++))>255)throw TypeError("invalid character found");t=r<<16|o<<8|n,i+=pp[t>>18&63]+pp[t>>12&63]+pp[t>>6&63]+pp[t&63]}return s?i.slice(0,s-3)+"===".substring(s):i},NR,PR,Sy=(e,t=!1)=>t?bq(PR(e)):PR(e),Qde=(e)=>{if(e.length<2){var t=e.charCodeAt(0);return t<128?e:t<2048?Gt(192|t>>>6)+Gt(128|t&63):Gt(224|t>>>12&15)+Gt(128|t>>>6&63)+Gt(128|t&63)}else{var t=65536+(e.charCodeAt(0)-55296)*1024+(e.charCodeAt(1)-56320);return Gt(240|t>>>18&7)+Gt(128|t>>>12&63)+Gt(128|t>>>6&63)+Gt(128|t&63)}},Yde,wq=(e)=>e.replace(Yde,Qde),gq,sl=(e,t=!1)=>t?bq(gq(e)):gq(e),yq=(e)=>sl(e,!0),Xde,epe=(e)=>{switch(e.length){case 4:var t=(7&e.charCodeAt(0))<<18|(63&e.charCodeAt(1))<<12|(63&e.charCodeAt(2))<<6|63&e.charCodeAt(3),r=t-65536;return Gt((r>>>10)+55296)+Gt((r&1023)+56320);case 3:return Gt((15&e.charCodeAt(0))<<12|(63&e.charCodeAt(1))<<6|63&e.charCodeAt(2));default:return Gt((31&e.charCodeAt(0))<<6|63&e.charCodeAt(1))}},xq=(e)=>e.replace(Xde,epe),_q=(e)=>{if(e=e.replace(/\s+/g,""),!Gde.test(e))throw TypeError("malformed base64.");e+="==".slice(2-(e.length&3));let t,r,o,n=[];for(let i=0;i<e.length;)if(t=by[e.charAt(i++)]<<18|by[e.charAt(i++)]<<12|(r=by[e.charAt(i++)])<<6|(o=by[e.charAt(i++)]),r===64)n.push(Gt(t>>16&255));else if(o===64)n.push(Gt(t>>16&255,t>>8&255));else n.push(Gt(t>>16&255,t>>8&255,t&255));return n.join("")},DR,Eq,kq=(e)=>Eq(Iq(e)),tpe,Iq=(e)=>Sq(e.replace(/[-_]/g,(t)=>t=="-"?"+":"/")),zR=(e)=>tpe(Iq(e)),rpe=(e)=>{if(typeof e!=="string")return!1;let t=e.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(t)||!/[^\s0-9a-zA-Z\-_]/.test(t)},Aq=(e)=>({value:e,enumerable:!1,writable:!0,configurable:!0}),Rq=function(){let e=(t,r)=>Object.defineProperty(String.prototype,t,Aq(r));e("fromBase64",function(){return zR(this)}),e("toBase64",function(t){return sl(this,t)}),e("toBase64URI",function(){return sl(this,!0)}),e("toBase64URL",function(){return sl(this,!0)}),e("toUint8Array",function(){return kq(this)})},Tq=function(){let e=(t,r)=>Object.defineProperty(Uint8Array.prototype,t,Aq(r));e("toBase64",function(t){return Sy(this,t)}),e("toBase64URI",function(){return Sy(this,!0)}),e("toBase64URL",function(){return Sy(this,!0)})},npe=()=>{Rq(),Tq()},cl;var vy=v(()=>{al=typeof Buffer==="function",fq=typeof TextDecoder==="function"?new TextDecoder("utf-8",{ignoreBOM:!0}):void 0,mq=typeof TextEncoder==="function"?new TextEncoder:void 0,pp=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),by=((e)=>{let t={};return e.forEach((r,o)=>t[r]=o),t})(pp),Gde=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,Gt=String.fromCharCode.bind(String),hq=typeof Uint8Array.from==="function"?Uint8Array.from.bind(Uint8Array):(e)=>new Uint8Array(Array.prototype.slice.call(e,0)),NR=typeof btoa==="function"?(e)=>btoa(e):al?(e)=>Buffer.from(e,"binary").toString("base64"):vq,PR=al?(e)=>Buffer.from(e).toString("base64"):(e)=>{let r=[];for(let o=0,n=e.length;o<n;o+=4096)r.push(Gt.apply(null,e.subarray(o,o+4096)));return NR(r.join(""))},Yde=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,gq=al?(e)=>Buffer.from(e,"utf8").toString("base64"):mq?(e)=>PR(mq.encode(e)):(e)=>NR(wq(e)),Xde=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,DR=typeof atob==="function"?(e)=>atob(Sq(e)):al?(e)=>Buffer.from(e,"base64").toString("binary"):_q,Eq=al?(e)=>hq(Buffer.from(e,"base64")):(e)=>hq(DR(e).split("").map((t)=>t.charCodeAt(0))),tpe=al?(e)=>Buffer.from(e,"base64").toString("utf8"):fq?(e)=>fq.decode(Eq(e)):(e)=>xq(DR(e)),cl={version:"3.8.0",VERSION:"3.8.0",atob:DR,atobPolyfill:_q,btoa:NR,btoaPolyfill:vq,fromBase64:zR,toBase64:sl,encode:sl,encodeURI:yq,encodeURL:yq,utob:wq,btou:xq,decode:zR,isValid:rpe,fromUint8Array:Sy,toUint8Array:kq,extendString:Rq,extendUint8Array:Tq,extendBuiltins:npe}});function Ki(e){if(e==="write")return"BEGIN IMMEDIATE";else if(e==="read")return"BEGIN TRANSACTION READONLY";else if(e==="deferred")return"BEGIN DEFERRED";else throw RangeError('Unknown transaction mode, supported values are "write", "read" and "deferred"')}class ll{columns;columnTypes;rows;rowsAffected;lastInsertRowid;constructor(e,t,r,o,n){this.columns=e,this.columnTypes=t,this.rows=r,this.rowsAffected=o,this.lastInsertRowid=n}toJSON(){return{columns:this.columns,columnTypes:this.columnTypes,rows:this.rows.map(ope),rowsAffected:this.rowsAffected,lastInsertRowid:this.lastInsertRowid!==void 0?""+this.lastInsertRowid:null}}}function ope(e){return Array.prototype.map.call(e,ipe)}function ipe(e){if(typeof e==="bigint")return""+e;else if(e instanceof ArrayBuffer)return cl.fromUint8Array(new Uint8Array(e));else return e}var Yn="https://github.com/libsql/libsql-client-ts#supported-urls";var ul=v(()=>{vy()});function Oq(e){return e.scheme==="file"&&(e.path===":memory:"||e.path.startsWith(":memory:?"))}function fp(e,t){if(typeof e!=="object")throw TypeError(`Expected client configuration as object, got ${typeof e}`);let{url:r,authToken:o,tls:n,intMode:i,concurrency:s}=e;s=Math.max(0,s||20),i??="number";let a=[];if(r===$q)r="file::memory:";let l=pq(r),u=l.scheme.toLowerCase(),d=u==="file"&&l.path===$q&&l.authority===void 0,p;if(d)p={cache:{values:["shared","private"],update:(y,S)=>a.push(`${y}=${S}`)}};else p={tls:{values:["0","1"],update:(y,S)=>n=S==="1"},authToken:{update:(y,S)=>o=S}};for(let{key:y,value:S}of l.query?.pairs??[]){if(!Object.hasOwn(p,y))throw new Ce(`Unsupported URL query parameter ${JSON.stringify(y)}`,"URL_PARAM_NOT_SUPPORTED");let x=p[y];if(x.values!==void 0&&!x.values.includes(S))throw new Ce(`Unknown value for the "${y}" query argument: ${JSON.stringify(S)}. Supported values are: [${x.values.map((_)=>'"'+_+'"').join(", ")}]`,"URL_INVALID");if(x.update!==void 0)x?.update(y,S)}let m=a.length===0?"":`?${a.join("&")}`,h=l.path+m,b;if(u==="libsql")if(n===!1){if(l.authority?.port===void 0)throw new Ce('A "libsql:" URL with ?tls=0 must specify an explicit port',"URL_INVALID");b=t?"http":"ws"}else b=t?"https":"wss";else b=u;if(b==="http"||b==="ws")n??=!1;else n??=!0;if(b!=="http"&&b!=="ws"&&b!=="https"&&b!=="wss"&&b!=="file")throw new Ce(`The client supports only "libsql:", "wss:", "ws:", "https:", "http:" and "file:" URLs, got ${JSON.stringify(l.scheme+":")}. For more information, please read ${Yn}`,"URL_SCHEME_NOT_SUPPORTED");if(i!=="number"&&i!=="bigint"&&i!=="string")throw TypeError(`Invalid value for intMode, expected "number", "bigint" or "string", got ${JSON.stringify(i)}`);if(l.fragment!==void 0)throw new Ce(`URL fragments are not supported: ${JSON.stringify("#"+l.fragment)}`,"URL_INVALID");if(d)return{scheme:"file",tls:!1,path:h,intMode:i,concurrency:s,syncUrl:e.syncUrl,syncInterval:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,fetch:e.fetch,timeout:e.timeout,authToken:void 0,encryptionKey:void 0,remoteEncryptionKey:void 0,authority:void 0};return{scheme:b,tls:n,authority:l.authority,path:h,authToken:o,intMode:i,concurrency:s,encryptionKey:e.encryptionKey,remoteEncryptionKey:e.remoteEncryptionKey,syncUrl:e.syncUrl,syncInterval:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,fetch:e.fetch,timeout:e.timeout}}var $q=":memory:";var mp=v(()=>{vn();yy();ul()});var Pq=ge(function(tn){var spe=tn&&tn.__createBinding||(Object.create?function(e,t,r,o){if(o===void 0)o=r;var n=Object.getOwnPropertyDescriptor(t,r);if(!n||("get"in n?!t.__esModule:n.writable||n.configurable))n={enumerable:!0,get:function(){return t[r]}};Object.defineProperty(e,o,n)}:function(e,t,r,o){if(o===void 0)o=r;e[o]=t[r]}),ape=tn&&tn.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Cq=tn&&tn.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null){for(var r in e)if(r!=="default"&&Object.prototype.hasOwnProperty.call(e,r))spe(t,e,r)}return ape(t,e),t};Object.defineProperty(tn,"__esModule",{value:!0});tn.load=tn.currentTarget=void 0;var cpe=Cq(qr("path")),lpe=Cq(qr("fs"));function upe(){let e=null;switch(process.platform){case"android":switch(process.arch){case"arm":return"android-arm-eabi";case"arm64":return"android-arm64"}e="Android";break;case"win32":switch(process.arch){case"x64":return"win32-x64-msvc";case"arm64":return"win32-arm64-msvc";case"ia32":return"win32-ia32-msvc"}e="Windows";break;case"darwin":switch(process.arch){case"x64":return"darwin-x64";case"arm64":return"darwin-arm64"}e="macOS";break;case"linux":switch(process.arch){case"x64":case"arm64":return dpe()?`linux-${process.arch}-gnu`:`linux-${process.arch}-musl`;case"arm":return"linux-arm-gnueabihf"}e="Linux";break;case"freebsd":if(process.arch==="x64")return"freebsd-x64";e="FreeBSD";break}if(e)throw Error(`Neon: unsupported ${e} architecture: ${process.arch}`);throw Error(`Neon: unsupported system: ${process.platform}`)}tn.currentTarget=upe;function dpe(){let e=process.report?.getReport();if(typeof e!=="object"||!e||!("header"in e))return!1;let t=e.header;return typeof t==="object"&&!!t&&"glibcVersionRuntime"in t}function ppe(e){let t=cpe.join(e,"index.node");return lpe.existsSync(t)?qr(t):null}tn.load=ppe});var Dq=ge(function(y2e,Nq){var zq=()=>process.platform==="linux",LR=null,fpe=()=>{if(!LR)LR=zq()&&process.report?process.report.getReport():{};return LR};Nq.exports={isLinux:zq,getReport:fpe}});var jq=ge(function(b2e,Bq){var Lq=qr("fs"),mpe=(e)=>Lq.readFileSync(e,"utf-8"),hpe=(e)=>new Promise((t,r)=>{Lq.readFile(e,"utf-8",(o,n)=>{if(o)r(o);else t(n)})});Bq.exports={LDD_PATH:"/usr/bin/ldd",readFileSync:mpe,readFile:hpe}});var r4=ge(function(S2e,t4){var Uq=qr("child_process"),{isLinux:dl,getReport:Mq}=Dq(),{LDD_PATH:wy,readFile:qq,readFileSync:Fq}=jq(),Xn,eo,Ji="",Kq=()=>{if(!Ji)return new Promise((e)=>{Uq.exec("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",(t,r)=>{Ji=t?" ":r,e(Ji)})});return Ji},Jq=()=>{if(!Ji)try{Ji=Uq.execSync("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",{encoding:"utf8"})}catch(e){Ji=" "}return Ji},Lo="glibc",Hq=/GLIBC\s(\d+\.\d+)/,aa="musl",gpe=Lo.toUpperCase(),ype=aa.toLowerCase(),bpe=(e)=>e.includes("libc.musl-")||e.includes("ld-musl-"),Vq=()=>{let e=Mq();if(e.header&&e.header.glibcVersionRuntime)return Lo;if(Array.isArray(e.sharedObjects)){if(e.sharedObjects.some(bpe))return aa}return null},Wq=(e)=>{let[t,r]=e.split(/[\r\n]+/);if(t&&t.includes(Lo))return Lo;if(r&&r.includes(aa))return aa;return null},Gq=(e)=>{if(e.includes(ype))return aa;if(e.includes(gpe))return Lo;return null},Spe=async()=>{if(Xn!==void 0)return Xn;Xn=null;try{let e=await qq(wy);Xn=Gq(e)}catch(e){}return Xn},vpe=()=>{if(Xn!==void 0)return Xn;Xn=null;try{let e=Fq(wy);Xn=Gq(e)}catch(e){}return Xn},Qq=async()=>{let e=null;if(dl()){if(e=await Spe(),!e)e=Vq();if(!e){let t=await Kq();e=Wq(t)}}return e},Yq=()=>{let e=null;if(dl()){if(e=vpe(),!e)e=Vq();if(!e){let t=Jq();e=Wq(t)}}return e},wpe=async()=>dl()&&await Qq()!==Lo,xpe=()=>dl()&&Yq()!==Lo,_pe=async()=>{if(eo!==void 0)return eo;eo=null;try{let t=(await qq(wy)).match(Hq);if(t)eo=t[1]}catch(e){}return eo},Epe=()=>{if(eo!==void 0)return eo;eo=null;try{let t=Fq(wy).match(Hq);if(t)eo=t[1]}catch(e){}return eo},Xq=()=>{let e=Mq();if(e.header&&e.header.glibcVersionRuntime)return e.header.glibcVersionRuntime;return null},Zq=(e)=>e.trim().split(/\s+/)[1],e4=(e)=>{let[t,r,o]=e.split(/[\r\n]+/);if(t&&t.includes(Lo))return Zq(t);if(r&&o&&r.includes(aa))return Zq(o);return null},kpe=async()=>{let e=null;if(dl()){if(e=await _pe(),!e)e=Xq();if(!e){let t=await Kq();e=e4(t)}}return e},Ipe=()=>{let e=null;if(dl()){if(e=Epe(),!e)e=Xq();if(!e){let t=Jq();e=e4(t)}}return e};t4.exports={GLIBC:Lo,MUSL:aa,family:Qq,familySync:Yq,isNonGlibcLinux:wpe,isNonGlibcLinuxSync:xpe,version:kpe,versionSync:Ipe}});var o4=ge(function(v2e,n4){var Ape={ALLOW:0,DENY:1};n4.exports=Ape});var s4=ge(function(w2e,i4){var BR={value:"SqliteError",writable:!0,enumerable:!1,configurable:!0};function ca(e,t,r){if(new.target!==ca)return new ca(e,t);if(typeof t!=="string")throw TypeError("Expected second argument to be a string");Error.call(this,e),BR.value=""+e,Object.defineProperty(this,"message",BR),Error.captureStackTrace(this,ca),this.code=t,this.rawCode=r}Object.setPrototypeOf(ca,Error);Object.setPrototypeOf(ca.prototype,Error.prototype);Object.defineProperty(ca.prototype,"name",BR);i4.exports=ca});var m4=ge(function(x2e,xy){var __dirname="/home/runner/work/brains/brains/node_modules/libsql",{load:Rpe,currentTarget:Tpe}=Pq(),{familySync:a4,GLIBC:$pe,MUSL:Ope}=r4();function Cpe(){if(process.env.LIBSQL_JS_DEV)return Rpe(__dirname);let e=Tpe();if(a4()==$pe)switch(e){case"linux-x64-musl":e="linux-x64-gnu";break;case"linux-arm64-musl":e="linux-arm64-gnu";break}if(e==="linux-arm-gnueabihf"&&a4()==Ope)e="linux-arm-musleabihf";return qr(`@libsql/${e}`)}var{databaseOpen:Ppe,databaseOpenWithSync:zpe,databaseInTransaction:Npe,databaseInterrupt:Dpe,databaseClose:Lpe,databaseSyncSync:Bpe,databaseSyncUntilSync:jpe,databaseExecSync:Zpe,databasePrepareSync:Upe,databaseDefaultSafeIntegers:Mpe,databaseAuthorizer:qpe,databaseLoadExtension:Fpe,databaseMaxWriteReplicationIndex:Kpe,statementRaw:Jpe,statementIsReader:Hpe,statementGet:c4,statementRun:l4,statementInterrupt:Vpe,statementRowsSync:u4,statementColumns:Wpe,statementSafeIntegers:Gpe,rowsNext:Qpe}=Cpe(),Ype=o4(),d4=s4();function pl(e){if(e.libsqlError)return new d4(e.message,e.code,e.rawCode);return e}class p4{constructor(e,t){let r=t?.encryptionCipher??"aes256cbc";if(t&&t.syncUrl){var o="";if(t.syncAuth)console.warn("Warning: The `syncAuth` option is deprecated, please use `authToken` option instead."),o=t.syncAuth;else if(t.authToken)o=t.authToken;let i=t?.encryptionKey??"",s=t?.syncPeriod??0,a=t?.readYourWrites??!0,l=t?.offline??!1,u=t?.remoteEncryptionKey??"";this.db=zpe(e,t.syncUrl,o,r,i,s,a,l,u)}else{let i=t?.authToken??"",s=t?.encryptionKey??"",a=t?.timeout??0,l=t?.remoteEncryptionKey??"";this.db=Ppe(e,i,r,s,a,l)}this.memory=e===":memory:",this.readonly=!1,this.name="",this.open=!0;let n=this.db;Object.defineProperties(this,{inTransaction:{get(){return Npe(n)}}})}sync(){return Bpe.call(this.db)}syncUntil(e){return jpe.call(this.db,e)}prepare(e){try{let t=Upe.call(this.db,e);return new f4(t)}catch(t){throw pl(t)}}transaction(e){if(typeof e!=="function")throw TypeError("Expected first argument to be a function");let t=this,r=(n)=>(...i)=>{t.exec("BEGIN "+n);try{let s=e(...i);return t.exec("COMMIT"),s}catch(s){throw t.exec("ROLLBACK"),s}},o={default:{value:r("")},deferred:{value:r("DEFERRED")},immediate:{value:r("IMMEDIATE")},exclusive:{value:r("EXCLUSIVE")},database:{value:this,enumerable:!0}};return Object.defineProperties(o.default.value,o),Object.defineProperties(o.deferred.value,o),Object.defineProperties(o.immediate.value,o),Object.defineProperties(o.exclusive.value,o),o.default.value}pragma(e,t){if(t==null)t={};if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof t!=="object")throw TypeError("Expected second argument to be an options object");let r=t.simple,o=this.prepare(`PRAGMA ${e}`,this,!0);return r?o.pluck().get():o.all()}backup(e,t){throw Error("not implemented")}serialize(e){throw Error("not implemented")}function(e,t,r){if(t==null)t={};if(typeof t==="function")r=t,t={};if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof r!=="function")throw TypeError("Expected last argument to be a function");if(typeof t!=="object")throw TypeError("Expected second argument to be an options object");if(!e)throw TypeError("User-defined function name cannot be an empty string");throw Error("not implemented")}aggregate(e,t){if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof t!=="object"||t===null)throw TypeError("Expected second argument to be an options object");if(!e)throw TypeError("User-defined function name cannot be an empty string");throw Error("not implemented")}table(e,t){if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(!e)throw TypeError("Virtual table module name cannot be an empty string");throw Error("not implemented")}authorizer(e){qpe.call(this.db,e)}loadExtension(...e){Fpe.call(this.db,...e)}maxWriteReplicationIndex(){return Kpe.call(this.db)}exec(e){try{Zpe.call(this.db,e)}catch(t){throw pl(t)}}interrupt(){Dpe.call(this.db)}close(){Lpe.call(this.db),this.open=!1}defaultSafeIntegers(e){return Mpe.call(this.db,e??!0),this}unsafeMode(...e){throw Error("not implemented")}}class f4{constructor(e){this.stmt=e,this.pluckMode=!1}raw(e){return Jpe.call(this.stmt,e??!0),this}pluck(e){return this.pluckMode=e??!0,this}get reader(){return Hpe.call(this.stmt)}run(...e){try{if(e.length==1&&typeof e[0]==="object")return l4.call(this.stmt,e[0]);else return l4.call(this.stmt,e.flat())}catch(t){throw pl(t)}}get(...e){try{if(e.length==1&&typeof e[0]==="object")return c4.call(this.stmt,e[0]);else return c4.call(this.stmt,e.flat())}catch(t){throw pl(t)}}iterate(...e){var t=void 0;if(e.length==1&&typeof e[0]==="object")t=u4.call(this.stmt,e[0]);else t=u4.call(this.stmt,e.flat());return{nextRows:Array(100),nextRowIndex:100,next(){try{if(this.nextRowIndex===100)Qpe.call(t,this.nextRows),this.nextRowIndex=0;let o=this.nextRows[this.nextRowIndex];if(this.nextRows[this.nextRowIndex]=void 0,!o)return{done:!0};return this.nextRowIndex++,{value:o,done:!1}}catch(o){throw pl(o)}},[Symbol.iterator](){return this}}}all(...e){try{let t=[];for(let r of this.iterate(...e))if(this.pluckMode)t.push(r[Object.keys(r)[0]]);else t.push(r);return t}catch(t){throw pl(t)}}interrupt(){Vpe.call(this.stmt)}columns(){return Wpe.call(this.stmt)}safeIntegers(e){return Gpe.call(this.stmt,e??!0),this}}xy.exports=p4;xy.exports.Authorization=Ype;xy.exports.SqliteError=d4});import{Buffer as g4}from"buffer";function y4(e){if(e.scheme!=="file")throw new Ce(`URL scheme ${JSON.stringify(e.scheme+":")} is not supported by the local sqlite3 client. For more information, please read ${Yn}`,"URL_SCHEME_NOT_SUPPORTED");let t=e.authority;if(t!==void 0){let s=t.host.toLowerCase();if(s!==""&&s!=="localhost")throw new Ce(`Invalid host in file URL: ${JSON.stringify(t.host)}. A "file:" URL with an absolute path should start with one slash ("file:/absolute/path.db") or with three slashes ("file:///absolute/path.db"). For more information, please read ${Yn}`,"URL_INVALID");if(t.port!==void 0)throw new Ce("File URL cannot have a port","URL_INVALID");if(t.userinfo!==void 0)throw new Ce("File URL cannot have username and password","URL_INVALID")}let r=Oq(e);if(r&&e.syncUrl)throw new Ce(`Embedded replica must use file for local db but URI with in-memory mode were provided instead: ${e.path}`,"URL_INVALID");let o=e.path;if(r)o=`${e.scheme}:${e.path}`;let n={authToken:e.authToken,encryptionKey:e.encryptionKey,remoteEncryptionKey:e.remoteEncryptionKey,syncUrl:e.syncUrl,syncPeriod:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,timeout:e.timeout},i=new hp.default(o,n);return zt(i,"SELECT 1 AS checkThatTheDatabaseCanBeOpened",e.intMode),new b4(o,n,i,e.intMode)}class b4{#e;#t;#r;#n;closed;protocol;constructor(e,t,r,o){this.#e=e,this.#t=t,this.#r=r,this.#n=o,this.closed=!1,this.protocol="file"}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.#o(),zt(this.#i(),r,this.#n)}async batch(e,t="deferred"){this.#o();let r=this.#i();try{zt(r,Ki(t),this.#n);let o=[];for(let n=0;n<e.length;n++)try{if(!r.inTransaction)throw new Wt("The transaction has been rolled back",n,"TRANSACTION_CLOSED");let i=e[n],s=Array.isArray(i)?{sql:i[0],args:i[1]||[]}:i;o.push(zt(r,s,this.#n))}catch(i){if(i instanceof Wt)throw i;if(i instanceof Ce)throw new Wt(i.message,n,i.code,i.extendedCode,i.rawCode,i.cause instanceof Error?i.cause:void 0);throw i}return zt(r,"COMMIT",this.#n),o}finally{if(r.inTransaction)zt(r,"ROLLBACK",this.#n)}}async migrate(e){this.#o();let t=this.#i();try{zt(t,"PRAGMA foreign_keys=off",this.#n),zt(t,Ki("deferred"),this.#n);let r=[];for(let o=0;o<e.length;o++)try{if(!t.inTransaction)throw new Wt("The transaction has been rolled back",o,"TRANSACTION_CLOSED");r.push(zt(t,e[o],this.#n))}catch(n){if(n instanceof Wt)throw n;if(n instanceof Ce)throw new Wt(n.message,o,n.code,n.extendedCode,n.rawCode,n.cause instanceof Error?n.cause:void 0);throw n}return zt(t,"COMMIT",this.#n),r}finally{if(t.inTransaction)zt(t,"ROLLBACK",this.#n);zt(t,"PRAGMA foreign_keys=on",this.#n)}}async transaction(e="write"){let t=this.#i();return zt(t,Ki(e),this.#n),this.#r=null,new S4(t,this.#n)}async executeMultiple(e){this.#o();let t=this.#i();try{return v4(t,e)}finally{if(t.inTransaction)zt(t,"ROLLBACK",this.#n)}}async sync(){this.#o();let e=await this.#i().sync();return{frames_synced:e.frames_synced,frame_no:e.frame_no}}async reconnect(){try{if(!this.closed&&this.#r!==null)this.#r.close()}finally{this.#r=new hp.default(this.#e,this.#t),this.closed=!1}}close(){if(this.closed=!0,this.#r!==null)this.#r.close(),this.#r=null}#o(){if(this.closed)throw new Ce("The client is closed","CLIENT_CLOSED")}#i(){if(this.#r===null)this.#r=new hp.default(this.#e,this.#t);return this.#r}}class S4{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.#r(),zt(this.#e,r,this.#t)}async batch(e){let t=[];for(let r=0;r<e.length;r++)try{this.#r();let o=e[r],n=Array.isArray(o)?{sql:o[0],args:o[1]||[]}:o;t.push(zt(this.#e,n,this.#t))}catch(o){if(o instanceof Wt)throw o;if(o instanceof Ce)throw new Wt(o.message,r,o.code,o.extendedCode,o.rawCode,o.cause instanceof Error?o.cause:void 0);throw o}return t}async executeMultiple(e){return this.#r(),v4(this.#e,e)}async rollback(){if(!this.#e.open)return;this.#r(),zt(this.#e,"ROLLBACK",this.#t)}async commit(){this.#r(),zt(this.#e,"COMMIT",this.#t)}close(){if(this.#e.inTransaction)zt(this.#e,"ROLLBACK",this.#t)}get closed(){return!this.#e.inTransaction}#r(){if(this.closed)throw new Ce("The transaction is closed","TRANSACTION_CLOSED")}}function zt(e,t,r){let o,n;if(typeof t==="string")o=t,n=[];else if(o=t.sql,Array.isArray(t.args))n=t.args.map((i)=>h4(i,r));else{n={};for(let i in t.args){let s=i[0]==="@"||i[0]==="$"||i[0]===":"?i.substring(1):i;n[s]=h4(t.args[i],r)}}try{let i=e.prepare(o);i.safeIntegers(!0);let s=!0;try{i.raw(!0)}catch{s=!1}if(s){let a=Array.from(i.columns().map((m)=>m.name)),l=Array.from(i.columns().map((m)=>m.type??"")),u=i.all(n).map((m)=>Xpe(m,a,r)),d=0,p=void 0;return new ll(a,l,u,0,void 0)}else{let a=i.run(n),l=a.changes,u=BigInt(a.lastInsertRowid);return new ll([],[],[],l,u)}}catch(i){throw w4(i)}}function Xpe(e,t,r){let o={};Object.defineProperty(o,"length",{value:e.length});for(let n=0;n<e.length;++n){let i=efe(e[n],r);Object.defineProperty(o,n,{value:i});let s=t[n];if(!Object.hasOwn(o,s))Object.defineProperty(o,s,{value:i,enumerable:!0,configurable:!0,writable:!0})}return o}function efe(e,t){if(typeof e==="bigint")if(t==="number"){if(e<tfe||e>rfe)throw RangeError("Received integer which cannot be safely represented as a JavaScript number");return Number(e)}else if(t==="bigint")return e;else if(t==="string")return""+e;else throw Error("Invalid value for IntMode");else if(e instanceof g4)return e.buffer;return e}function h4(e,t){if(typeof e==="number"){if(!Number.isFinite(e))throw RangeError("Only finite numbers (not Infinity or NaN) can be passed as arguments");return e}else if(typeof e==="bigint"){if(e<nfe||e>ofe)throw RangeError("bigint is too large to be represented as a 64-bit integer and passed as argument");return e}else if(typeof e==="boolean")switch(t){case"bigint":return e?1n:0n;case"string":return e?"1":"0";default:return e?1:0}else if(e instanceof ArrayBuffer)return g4.from(e);else if(e instanceof Date)return e.valueOf();else if(e===void 0)throw TypeError("undefined cannot be passed as argument to the database");else return e}function v4(e,t){try{e.exec(t)}catch(r){throw w4(r)}}function w4(e){if(e instanceof hp.default.SqliteError){let t=e.code,r=ife(e.rawCode);return new Ce(e.message,r,t,e.rawCode,e)}return e}function ife(e){if(e===void 0)return"SQLITE_UNKNOWN";let t=e&255;return sfe[t]??`SQLITE_UNKNOWN_${t.toString()}`}var hp,tfe,rfe=9007199254740991n,nfe,ofe=9223372036854775807n,sfe;var x4=v(()=>{vn();mp();ul();hp=Ml(m4(),1);vn();tfe=-9007199254740991n;nfe=-9223372036854775808n;sfe={1:"SQLITE_ERROR",2:"SQLITE_INTERNAL",3:"SQLITE_PERM",4:"SQLITE_ABORT",5:"SQLITE_BUSY",6:"SQLITE_LOCKED",7:"SQLITE_NOMEM",8:"SQLITE_READONLY",9:"SQLITE_INTERRUPT",10:"SQLITE_IOERR",11:"SQLITE_CORRUPT",12:"SQLITE_NOTFOUND",13:"SQLITE_FULL",14:"SQLITE_CANTOPEN",15:"SQLITE_PROTOCOL",16:"SQLITE_EMPTY",17:"SQLITE_SCHEMA",18:"SQLITE_TOOBIG",19:"SQLITE_CONSTRAINT",20:"SQLITE_MISMATCH",21:"SQLITE_MISUSE",22:"SQLITE_NOLFS",23:"SQLITE_AUTH",24:"SQLITE_FORMAT",25:"SQLITE_RANGE",26:"SQLITE_NOTADB",27:"SQLITE_NOTICE",28:"SQLITE_WARNING"}});var Hi;var jR=v(()=>{if(typeof WebSocket<"u")Hi=WebSocket;else if(typeof global<"u")Hi=global.WebSocket;else if(typeof window<"u")Hi=window.WebSocket;else if(typeof self<"u")Hi=self.WebSocket});class fl{constructor(){this.intMode="number"}intMode}var Ge,Pe,gp,xt,yp,ml,la,wn,or,to;var _t=v(()=>{Ge=class Ge extends Error{constructor(e){super(e);this.name="ClientError"}};Pe=class Pe extends Ge{constructor(e){super(e);this.name="ProtoError"}};gp=class gp extends Ge{code;proto;constructor(e,t){super(e);this.name="ResponseError",this.code=t.code,this.proto=t,this.stack=void 0}};xt=class xt extends Ge{constructor(e,t){if(t!==void 0){super(`${e}: ${t}`);this.cause=t}else super(e);this.name="ClosedError"}};yp=class yp extends Ge{constructor(e){super(e);this.name="WebSocketUnsupportedError"}};ml=class ml extends Ge{constructor(e){super(e);this.name="WebSocketError"}};la=class la extends Ge{status;constructor(e,t){super(e);this.status=t,this.name="HttpServerError"}};wn=class wn extends Ge{constructor(e){super(e);this.name="ProtocolVersionError"}};or=class or extends Ge{constructor(e){super(e);this.name="InternalError"}};to=class to extends Ge{constructor(e){super(e);this.name="MisuseError"}}});function Rr(e){if(typeof e==="string")return e;throw hl(e,"string")}function Zr(e){if(e===null||e===void 0)return;else if(typeof e==="string")return e;throw hl(e,"string or null")}function Bo(e){if(typeof e==="number")return e;throw hl(e,"number")}function Vi(e){if(typeof e==="boolean")return e;throw hl(e,"boolean")}function bp(e){if(Array.isArray(e))return e;throw hl(e,"array")}function It(e){if(e!==null&&typeof e==="object"&&!Array.isArray(e))return e;throw hl(e,"object")}function xn(e,t){return bp(e).map((r)=>t(It(r)))}function hl(e,t){if(e===void 0)return new Pe(`Expected ${t}, but the property was missing`);let r=typeof e;if(e===null)r="null";else if(Array.isArray(e))r="array";return new Pe(`Expected ${t}, received ${r}`)}function ua(e,t){return t(It(e))}var gl=v(()=>{_t()});class _4{#e;#t;constructor(e){this.#e=e,this.#t=!1}begin(){this.#e.push("{"),this.#t=!0}end(){this.#e.push("}"),this.#t=!1}#r(e){if(this.#t)this.#e.push('"'),this.#t=!1;else this.#e.push(',"');this.#e.push(e),this.#e.push('":')}string(e,t){this.#r(e),this.#e.push(JSON.stringify(t))}stringRaw(e,t){this.#r(e),this.#e.push('"'),this.#e.push(t),this.#e.push('"')}number(e,t){this.#r(e),this.#e.push(""+t)}boolean(e,t){this.#r(e),this.#e.push(t?"true":"false")}object(e,t,r){this.#r(e),this.begin(),r(this,t),this.end()}arrayObjects(e,t,r){this.#r(e),this.#e.push("[");for(let o=0;o<t.length;++o){if(o!==0)this.#e.push(",");this.begin(),r(this,t[o]),this.end()}this.#e.push("]")}}function Sp(e,t){let r=[],o=new _4(r);return o.begin(),t(o,e),o.end(),r.join("")}var da=0,vp=1,wp=2,E4=5;class k4{#e;#t;#r;constructor(e){this.#e=e,this.#t=new DataView(e.buffer,e.byteOffset,e.byteLength),this.#r=0}varint(){let e=0;for(let t=0;;t+=7){let r=this.#e[this.#r++];if(e|=(r&127)<<t,!(r&128))break}return e}varintBig(){let e=0n;for(let t=0n;;t+=7n){let r=this.#e[this.#r++];if(e|=BigInt(r&127)<<t,!(r&128))break}return e}bytes(e){let t=new Uint8Array(this.#e.buffer,this.#e.byteOffset+this.#r,e);return this.#r+=e,t}double(){let e=this.#t.getFloat64(this.#r,!0);return this.#r+=8,e}skipVarint(){for(;;)if(!(this.#e[this.#r++]&128))break}skip(e){this.#r+=e}eof(){return this.#r>=this.#e.byteLength}}class I4{#e;#t;constructor(e){this.#e=e,this.#t=-1}setup(e){this.#t=e}#r(e){if(this.#t!==e)throw new Pe(`Expected wire type ${e}, got ${this.#t}`);this.#t=-1}bytes(){this.#r(wp);let e=this.#e.varint();return this.#e.bytes(e)}string(){return new TextDecoder().decode(this.bytes())}message(e){return Wi(this.bytes(),e)}int32(){return this.#r(da),this.#e.varint()}uint32(){return this.int32()}bool(){return this.int32()!==0}uint64(){return this.#r(da),this.#e.varintBig()}sint64(){let e=this.uint64();return e>>1n^-(e&1n)}double(){return this.#r(vp),this.#e.double()}maybeSkip(){if(this.#t<0)return;else if(this.#t===da)this.#e.skipVarint();else if(this.#t===vp)this.#e.skip(8);else if(this.#t===wp){let e=this.#e.varint();this.#e.skip(e)}else if(this.#t===E4)this.#e.skip(4);else throw new Pe(`Unexpected wire type ${this.#t}`);this.#t=-1}}function Wi(e,t){let r=new k4(e),o=new I4(r),n=t.default();while(!r.eof()){let i=r.varint(),s=i>>3,a=i&7;o.setup(a);let l=t[s];if(l!==void 0){let u=l(o,n);if(u!==void 0)n=u}o.maybeSkip()}return n}var ZR=v(()=>{_t()});class UR{#e;#t;#r;#n;constructor(){this.#e=new ArrayBuffer(256),this.#t=new Uint8Array(this.#e),this.#r=new DataView(this.#e),this.#n=0}#o(e){if(this.#n+e<=this.#e.byteLength)return;let t=this.#e.byteLength;while(t<this.#n+e)t*=2;let r=new ArrayBuffer(t),o=new Uint8Array(r),n=new DataView(r);o.set(new Uint8Array(this.#e,0,this.#n)),this.#e=r,this.#t=o,this.#r=n}#i(e){this.#o(5),e=0|e;do{let t=e&127;e>>>=7,t|=e?128:0,this.#t[this.#n++]=t}while(e)}#a(e){this.#o(10),e=e&0xffffffffffffffffn;do{let t=Number(e&0x7fn);e>>=7n,t|=e?128:0,this.#t[this.#n++]=t}while(e)}#s(e,t){this.#i(e<<3|t)}bytes(e,t){this.#s(e,wp),this.#i(t.byteLength),this.#o(t.byteLength),this.#t.set(t,this.#n),this.#n+=t.byteLength}string(e,t){this.bytes(e,new TextEncoder().encode(t))}message(e,t,r){let o=new UR;r(o,t),this.bytes(e,o.data())}int32(e,t){this.#s(e,da),this.#i(t)}uint32(e,t){this.int32(e,t)}bool(e,t){this.int32(e,t?1:0)}sint64(e,t){this.#s(e,da),this.#a(t<<1n^t>>63n)}double(e,t){this.#s(e,vp),this.#o(8),this.#r.setFloat64(this.#n,t,!0),this.#n+=8}data(){return new Uint8Array(this.#e,0,this.#n)}}function xp(e,t){let r=new UR;return t(r,e),r.data()}var A4=()=>{};var MR=v(()=>{gl();ZR();A4()});class Gi{#e;#t;constructor(){this.#e=new Set,this.#t=new Set}alloc(){for(let t of this.#t){if(this.#t.delete(t),this.#e.add(t),!this.#e.has(this.#e.size-1))this.#t.add(this.#e.size-1);return t}let e=this.#e.size;return this.#e.add(e),e}free(e){if(!this.#e.delete(e))throw new or("Freeing an id that is not allocated");if(this.#t.delete(this.#e.size),e<this.#e.size)this.#t.add(e)}}var qR=v(()=>{_t()});function Je(e,t){throw new or(t)}var rn=v(()=>{_t()});function yl(e){if(e===null)return null;else if(typeof e==="string")return e;else if(typeof e==="number"){if(!Number.isFinite(e))throw RangeError("Only finite numbers (not Infinity or NaN) can be passed as arguments");return e}else if(typeof e==="bigint"){if(e<cfe||e>lfe)throw RangeError("This bigint value is too large to be represented as a 64-bit integer and passed as argument");return e}else if(typeof e==="boolean")return e?1n:0n;else if(e instanceof ArrayBuffer)return new Uint8Array(e);else if(e instanceof Uint8Array)return e;else if(e instanceof Date)return+e.valueOf();else if(typeof e==="object")return""+e.toString();else throw TypeError("Unsupported type of value")}function FR(e,t){if(e===null)return null;else if(typeof e==="number")return e;else if(typeof e==="string")return e;else if(typeof e==="bigint")if(t==="number"){let r=Number(e);if(!Number.isSafeInteger(r))throw RangeError("Received integer which is too large to be safely represented as a JavaScript number");return r}else if(t==="bigint")return e;else if(t==="string")return""+e;else throw new to("Invalid value for IntMode");else if(e instanceof Uint8Array)return e.slice().buffer;else if(e===void 0)throw new Pe("Received unrecognized type of Value");else throw Je(e,"Impossible type of Value")}var cfe,lfe=9223372036854775807n;var KR=v(()=>{_t();rn();cfe=-9223372036854775808n});function pa(e){return{affectedRowCount:e.affectedRowCount,lastInsertRowid:e.lastInsertRowid,columnNames:e.cols.map((t)=>t.name),columnDecltypes:e.cols.map((t)=>t.decltype)}}function Ey(e,t){let r=pa(e),o=e.rows.map((n)=>R4(r.columnNames,n,t));return{...r,rows:o}}function ky(e,t){let r=pa(e),o;if(e.rows.length>0)o=R4(r.columnNames,e.rows[0],t);return{...r,row:o}}function Iy(e,t){let r=pa(e),o;if(e.rows.length>0&&r.columnNames.length>0)o=FR(e.rows[0][0],t);return{...r,value:o}}function R4(e,t,r){let o={};Object.defineProperty(o,"length",{value:t.length});for(let n=0;n<t.length;++n){let i=FR(t[n],r);Object.defineProperty(o,n,{value:i});let s=e[n];if(s!==void 0&&!Object.hasOwn(o,s))Object.defineProperty(o,s,{value:i,enumerable:!0,configurable:!0,writable:!0})}return o}function jo(e){return new gp(e.message,e)}var _p=v(()=>{_t();KR()});class fa{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}_getSqlId(e){if(this.#e!==e)throw new to("Attempted to use SQL text opened with other object");else if(this.#r!==void 0)throw new xt("SQL text is closed",this.#r);return this.#t}close(){this._setClosed(new Ge("SQL text was manually closed"))}_setClosed(e){if(this.#r===void 0)this.#r=e,this.#e._closeSql(this.#t)}get closed(){return this.#r!==void 0}}function Ep(e,t){if(t instanceof fa)return{sqlId:t._getSqlId(e)};else return{sql:""+t}}var bl=v(()=>{_t()});class Qi{#e;#t;constructor(){this.#e=[],this.#t=[]}get length(){return this.#e.length+this.#t.length}push(e){this.#e.push(e)}shift(){if(this.#t.length===0&&this.#e.length>0)this.#t=this.#e.reverse(),this.#e=[];return this.#t.pop()}first(){return this.#t.length!==0?this.#t[this.#t.length-1]:this.#e[0]}}class kp{sql;_args;_namedArgs;constructor(e){this.sql=e,this._args=[],this._namedArgs=new Map}bindIndexes(e){this._args.length=0;for(let t of e)this._args.push(yl(t));return this}bindIndex(e,t){if(e!==(e|0)||e<=0)throw RangeError("Index of a positional argument must be positive integer");while(this._args.length<e)this._args.push(null);return this._args[e-1]=yl(t),this}bindName(e,t){return this._namedArgs.set(e,yl(t)),this}unbindAll(){return this._args.length=0,this._namedArgs.clear(),this}}function Ay(e,t,r){let o,n=[],i=[];if(t instanceof kp){o=t.sql,n=t._args;for(let[l,u]of t._namedArgs.entries())i.push({name:l,value:u})}else if(Array.isArray(t))if(o=t[0],Array.isArray(t[1]))n=t[1].map((l)=>yl(l));else i=Object.entries(t[1]).map(([l,u])=>({name:l,value:yl(u)}));else o=t;let{sql:s,sqlId:a}=Ep(e,o);return{sql:s,sqlId:a,args:n,namedArgs:i,wantRows:r}}var Ry=v(()=>{bl();KR()});class Ty{_stream;#e;_steps;#t;constructor(e,t){this._stream=e,this.#e=t,this._steps=[],this.#t=!1}step(){return new JR(this)}execute(){if(this.#t)throw new to("This batch has already been executed");this.#t=!0;let e={steps:this._steps.map((t)=>t.proto)};if(this.#e)return dfe(this._stream,this._steps,e);else return ufe(this._stream,this._steps,e)}}function ufe(e,t,r){return e._batch(r).then((o)=>{for(let n=0;n<t.length;++n){let i=o.stepResults.get(n),s=o.stepErrors.get(n);t[n].callback(i,s)}})}async function dfe(e,t,r){let o=await e._openCursor(r);try{let n=0,i=void 0,s=[];for(;;){let a=await o.next();if(a===void 0)break;if(a.type==="step_begin"){if(a.step<n||a.step>=t.length)throw new Pe("Server produced StepBeginEntry for unexpected step");else if(i!==void 0)throw new Pe("Server produced StepBeginEntry before terminating previous step");for(let l=n;l<a.step;++l)t[l].callback(void 0,void 0);n=a.step+1,i=a,s=[]}else if(a.type==="step_end"){if(i===void 0)throw new Pe("Server produced StepEndEntry but no step is active");let l={cols:i.cols,rows:s,affectedRowCount:a.affectedRowCount,lastInsertRowid:a.lastInsertRowid};t[i.step].callback(l,void 0),i=void 0,s=[]}else if(a.type==="step_error"){if(i===void 0){if(a.step>=t.length)throw new Pe("Server produced StepErrorEntry for unexpected step");for(let l=n;l<a.step;++l)t[l].callback(void 0,void 0)}else{if(a.step!==i.step)throw new Pe("Server produced StepErrorEntry for unexpected step");i=void 0,s=[]}t[a.step].callback(void 0,a.error),n=a.step+1}else if(a.type==="row"){if(i===void 0)throw new Pe("Server produced RowEntry but no step is active");s.push(a.row)}else if(a.type==="error")throw jo(a.error);else if(a.type==="none")throw new Pe("Server produced unrecognized CursorEntry");else throw Je(a,"Impossible CursorEntry")}if(i!==void 0)throw new Pe("Server closed Cursor before terminating active step");for(let a=n;a<t.length;++a)t[a].callback(void 0,void 0)}finally{o.close()}}class JR{_batch;#e;_index;constructor(e){this._batch=e,this.#e=[],this._index=void 0}condition(e){return this.#e.push(e._proto),this}query(e){return this.#t(e,!0,Ey)}queryRow(e){return this.#t(e,!0,ky)}queryValue(e){return this.#t(e,!0,Iy)}run(e){return this.#t(e,!1,pa)}#t(e,t,r){if(this._index!==void 0)throw new to("This BatchStep has already been added to the batch");let o=Ay(this._batch._stream._sqlOwner(),e,t),n;if(this.#e.length===0)n=void 0;else if(this.#e.length===1)n=this.#e[0];else n={type:"and",conds:this.#e.slice()};let i={stmt:o,condition:n};return new Promise((s,a)=>{let l=(u,d)=>{if(u!==void 0&&d!==void 0)a(new Pe("Server returned both result and error"));else if(d!==void 0)a(jo(d));else if(u!==void 0)s(r(u,this._batch._stream.intMode));else s(void 0)};this._index=this._batch._steps.length,this._batch._steps.push({proto:i,callback:l})})}}class ut{_batch;_proto;constructor(e,t){this._batch=e,this._proto=t}static ok(e){return new ut(e._batch,{type:"ok",step:T4(e)})}static error(e){return new ut(e._batch,{type:"error",step:T4(e)})}static not(e){return new ut(e._batch,{type:"not",cond:e._proto})}static and(e,t){for(let r of t)$4(e,r);return new ut(e,{type:"and",conds:t.map((r)=>r._proto)})}static or(e,t){for(let r of t)$4(e,r);return new ut(e,{type:"or",conds:t.map((r)=>r._proto)})}static isAutocommit(e){return e._stream.client()._ensureVersion(3,"BatchCond.isAutocommit()"),new ut(e,{type:"is_autocommit"})}}function T4(e){if(e._index===void 0)throw new to("Cannot add a condition referencing a step that has not been added to the batch");return e._index}function $4(e,t){if(t._batch!==e)throw new to("Cannot mix BatchCond objects for different Batch objects")}var HR=v(()=>{_t();_p();Ry();rn()});function O4(e){return{paramNames:e.params.map((t)=>t.name),columns:e.cols,isExplain:e.isExplain,isReadonly:e.isReadonly}}class Sl{constructor(e){this.intMode=e}query(e){return this.#e(e,!0,Ey)}queryRow(e){return this.#e(e,!0,ky)}queryValue(e){return this.#e(e,!0,Iy)}run(e){return this.#e(e,!1,pa)}#e(e,t,r){let o=Ay(this._sqlOwner(),e,t);return this._execute(o).then((n)=>r(n,this.intMode))}batch(e=!1){return new Ty(this,e)}describe(e){let t=Ep(this._sqlOwner(),e);return this._describe(t).then(O4)}sequence(e){let t=Ep(this._sqlOwner(),e);return this._sequence(t)}intMode}var $y=v(()=>{HR();_p();bl();Ry()});class Ip{}var pfe=1000,ffe=10,VR;var C4=v(()=>{_t();VR=class VR extends Ip{#e;#t;#r;#n;#o;#i;#a;constructor(e,t,r){super();this.#e=e,this.#t=t,this.#r=r,this.#n=new Qi,this.#o=new Qi,this.#i=void 0,this.#a=!1}async next(){for(;;){if(this.#i!==void 0)throw new xt("Cursor is closed",this.#i);while(!this.#a&&this.#o.length<ffe)this.#o.push(this.#s());let e=this.#n.shift();if(this.#a||e!==void 0)return e;await this.#o.shift().then((t)=>{if(t===void 0)return;for(let r of t.entries)this.#n.push(r);this.#a||=t.done})}}#s(){return this.#t._sendCursorRequest(this,{type:"fetch_cursor",cursorId:this.#r,maxCount:pfe}).then((e)=>e,(e)=>{this._setClosed(e);return})}_setClosed(e){if(this.#i!==void 0)return;this.#i=e,this.#t._sendCursorRequest(this,{type:"close_cursor",cursorId:this.#r}).catch(()=>{return}),this.#t._cursorClosed(this)}close(){this._setClosed(new Ge("Cursor was manually closed"))}get closed(){return this.#i!==void 0}}});var Ap;var WR=v(()=>{_t();$y();C4();Ap=class Ap extends Sl{#e;#t;#r;#n;#o;#i;static open(e){let t=e._streamIdAlloc.alloc(),r=new Ap(e,t),o=()=>{return},n=(s)=>r.#l(s),i={type:"open_stream",streamId:t};return e._sendRequest(i,{responseCallback:o,errorCallback:n}),r}constructor(e,t){super(e.intMode);this.#e=e,this.#t=t,this.#r=new Qi,this.#n=void 0,this.#o=!1,this.#i=void 0}client(){return this.#e}_sqlOwner(){return this.#e}_execute(e){return this.#a({type:"execute",streamId:this.#t,stmt:e}).then((t)=>t.result)}_batch(e){return this.#a({type:"batch",streamId:this.#t,batch:e}).then((t)=>t.result)}_describe(e){return this.#e._ensureVersion(2,"describe()"),this.#a({type:"describe",streamId:this.#t,sql:e.sql,sqlId:e.sqlId}).then((t)=>t.result)}_sequence(e){return this.#e._ensureVersion(2,"sequence()"),this.#a({type:"sequence",streamId:this.#t,sql:e.sql,sqlId:e.sqlId}).then((t)=>{return})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#a({type:"get_autocommit",streamId:this.#t}).then((e)=>e.isAutocommit)}#a(e){return new Promise((t,r)=>{this.#s({type:"request",request:e,responseCallback:t,errorCallback:r})})}_openCursor(e){return this.#e._ensureVersion(3,"cursor"),new Promise((t,r)=>{this.#s({type:"cursor",batch:e,cursorCallback:t,errorCallback:r})})}_sendCursorRequest(e,t){if(e!==this.#n)throw new or("Cursor not associated with the stream attempted to execute a request");return new Promise((r,o)=>{if(this.#i!==void 0)o(new xt("Stream is closed",this.#i));else this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})})}_cursorClosed(e){if(e!==this.#n)throw new or("Cursor was closed, but it was not associated with the stream");this.#n=void 0,this.#c()}#s(e){if(this.#i!==void 0)e.errorCallback(new xt("Stream is closed",this.#i));else if(this.#o)e.errorCallback(new xt("Stream is closing",void 0));else this.#r.push(e),this.#c()}#c(){for(;;){let e=this.#r.first();if(e===void 0&&this.#n===void 0&&this.#o){this.#l(new Ge("Stream was gracefully closed"));break}else if(e?.type==="request"&&this.#n===void 0){let{request:t,responseCallback:r,errorCallback:o}=e;this.#r.shift(),this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})}else if(e?.type==="cursor"&&this.#n===void 0){let{batch:t,cursorCallback:r}=e;this.#r.shift();let o=this.#e._cursorIdAlloc.alloc(),n=new VR(this.#e,this,o),i={type:"open_cursor",streamId:this.#t,cursorId:o,batch:t},s=()=>{return},a=(l)=>n._setClosed(l);this.#e._sendRequest(i,{responseCallback:s,errorCallback:a}),this.#n=n,r(n)}else break}}#l(e){if(this.#i!==void 0)return;if(this.#i=e,this.#n!==void 0)this.#n._setClosed(e);for(;;){let n=this.#r.shift();if(n!==void 0)n.errorCallback(e);else break}let t={type:"close_stream",streamId:this.#t},r=()=>this.#e._streamIdAlloc.free(this.#t),o=()=>{return};this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})}close(){this.#l(new Ge("Stream was manually closed"))}closeGracefully(){this.#o=!0,this.#c()}get closed(){return this.#i!==void 0||this.#o}}});function Rp(e,t){if(t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId);e.arrayObjects("args",t.args,P4),e.arrayObjects("named_args",t.namedArgs,mfe),e.boolean("want_rows",t.wantRows)}function mfe(e,t){e.string("name",t.name),e.object("value",t.value,P4)}function vl(e,t){e.arrayObjects("steps",t.steps,hfe)}function hfe(e,t){if(t.condition!==void 0)e.object("condition",t.condition,GR);e.object("stmt",t.stmt,Rp)}function GR(e,t){if(e.stringRaw("type",t.type),t.type==="ok"||t.type==="error")e.number("step",t.step);else if(t.type==="not")e.object("cond",t.cond,GR);else if(t.type==="and"||t.type==="or")e.arrayObjects("conds",t.conds,GR);else if(t.type==="is_autocommit");else throw Je(t,"Impossible type of BatchCond")}function P4(e,t){if(t===null)e.stringRaw("type","null");else if(typeof t==="bigint")e.stringRaw("type","integer"),e.stringRaw("value",""+t);else if(typeof t==="number")e.stringRaw("type","float"),e.number("value",t);else if(typeof t==="string")e.stringRaw("type","text"),e.string("value",t);else if(t instanceof Uint8Array)e.stringRaw("type","blob"),e.stringRaw("base64",cl.fromUint8Array(t));else if(t===void 0);else throw Je(t,"Impossible type of Value")}var QR=v(()=>{vy();rn()});function z4(e,t){if(e.stringRaw("type",t.type),t.type==="hello"){if(t.jwt!==void 0)e.string("jwt",t.jwt)}else if(t.type==="request")e.number("request_id",t.requestId),e.object("request",t.request,gfe);else throw Je(t,"Impossible type of ClientMsg")}function gfe(e,t){if(e.stringRaw("type",t.type),t.type==="open_stream")e.number("stream_id",t.streamId);else if(t.type==="close_stream")e.number("stream_id",t.streamId);else if(t.type==="execute")e.number("stream_id",t.streamId),e.object("stmt",t.stmt,Rp);else if(t.type==="batch")e.number("stream_id",t.streamId),e.object("batch",t.batch,vl);else if(t.type==="open_cursor")e.number("stream_id",t.streamId),e.number("cursor_id",t.cursorId),e.object("batch",t.batch,vl);else if(t.type==="close_cursor")e.number("cursor_id",t.cursorId);else if(t.type==="fetch_cursor")e.number("cursor_id",t.cursorId),e.number("max_count",t.maxCount);else if(t.type==="sequence"){if(e.number("stream_id",t.streamId),t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="describe"){if(e.number("stream_id",t.streamId),t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="store_sql")e.number("sql_id",t.sqlId),e.string("sql",t.sql);else if(t.type==="close_sql")e.number("sql_id",t.sqlId);else if(t.type==="get_autocommit")e.number("stream_id",t.streamId);else throw Je(t,"Impossible type of Request")}var N4=v(()=>{QR();rn()});function Tp(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId);for(let r of t.args)e.message(3,r,L4);for(let r of t.namedArgs)e.message(4,r,yfe);e.bool(5,t.wantRows)}function yfe(e,t){e.string(1,t.name),e.message(2,t.value,L4)}function wl(e,t){for(let r of t.steps)e.message(1,r,bfe)}function bfe(e,t){if(t.condition!==void 0)e.message(1,t.condition,YR);e.message(2,t.stmt,Tp)}function YR(e,t){if(t.type==="ok")e.uint32(1,t.step);else if(t.type==="error")e.uint32(2,t.step);else if(t.type==="not")e.message(3,t.cond,YR);else if(t.type==="and")e.message(4,t.conds,D4);else if(t.type==="or")e.message(5,t.conds,D4);else if(t.type==="is_autocommit")e.message(6,void 0,B4);else throw Je(t,"Impossible type of BatchCond")}function D4(e,t){for(let r of t)e.message(1,r,YR)}function L4(e,t){if(t===null)e.message(1,void 0,B4);else if(typeof t==="bigint")e.sint64(2,t);else if(typeof t==="number")e.double(3,t);else if(typeof t==="string")e.string(4,t);else if(t instanceof Uint8Array)e.bytes(5,t);else if(t===void 0);else throw Je(t,"Impossible type of Value")}function B4(e,t){}var XR=v(()=>{rn()});function j4(e,t){if(t.type==="hello")e.message(1,t,Sfe);else if(t.type==="request")e.message(2,t,vfe);else throw Je(t,"Impossible type of ClientMsg")}function Sfe(e,t){if(t.jwt!==void 0)e.string(1,t.jwt)}function vfe(e,t){e.int32(1,t.requestId);let r=t.request;if(r.type==="open_stream")e.message(2,r,wfe);else if(r.type==="close_stream")e.message(3,r,xfe);else if(r.type==="execute")e.message(4,r,_fe);else if(r.type==="batch")e.message(5,r,Efe);else if(r.type==="open_cursor")e.message(6,r,kfe);else if(r.type==="close_cursor")e.message(7,r,Ife);else if(r.type==="fetch_cursor")e.message(8,r,Afe);else if(r.type==="sequence")e.message(9,r,Rfe);else if(r.type==="describe")e.message(10,r,Tfe);else if(r.type==="store_sql")e.message(11,r,$fe);else if(r.type==="close_sql")e.message(12,r,Ofe);else if(r.type==="get_autocommit")e.message(13,r,Cfe);else throw Je(r,"Impossible type of Request")}function wfe(e,t){e.int32(1,t.streamId)}function xfe(e,t){e.int32(1,t.streamId)}function _fe(e,t){e.int32(1,t.streamId),e.message(2,t.stmt,Tp)}function Efe(e,t){e.int32(1,t.streamId),e.message(2,t.batch,wl)}function kfe(e,t){e.int32(1,t.streamId),e.int32(2,t.cursorId),e.message(3,t.batch,wl)}function Ife(e,t){e.int32(1,t.cursorId)}function Afe(e,t){e.int32(1,t.cursorId),e.uint32(2,t.maxCount)}function Rfe(e,t){if(e.int32(1,t.streamId),t.sql!==void 0)e.string(2,t.sql);if(t.sqlId!==void 0)e.int32(3,t.sqlId)}function Tfe(e,t){if(e.int32(1,t.streamId),t.sql!==void 0)e.string(2,t.sql);if(t.sqlId!==void 0)e.int32(3,t.sqlId)}function $fe(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function Ofe(e,t){e.int32(1,t.sqlId)}function Cfe(e,t){e.int32(1,t.streamId)}var Z4=v(()=>{XR();rn()});function Yi(e){let t=Rr(e.message),r=Zr(e.code);return{message:t,code:r}}function $p(e){let t=xn(e.cols,U4),r=bp(e.rows).map((s)=>xn(s,M4)),o=Bo(e.affected_row_count),n=Zr(e.last_insert_rowid),i=n!==void 0?BigInt(n):void 0;return{cols:t,rows:r,affectedRowCount:o,lastInsertRowid:i}}function U4(e){let t=Zr(e.name),r=Zr(e.decltype);return{name:t,decltype:r}}function Oy(e){let t=new Map;bp(e.step_results).forEach((o,n)=>{if(o!==null)t.set(n,$p(It(o)))});let r=new Map;return bp(e.step_errors).forEach((o,n)=>{if(o!==null)r.set(n,Yi(It(o)))}),{stepResults:t,stepErrors:r}}function Cy(e){let t=Rr(e.type);if(t==="step_begin"){let r=Bo(e.step),o=xn(e.cols,U4);return{type:"step_begin",step:r,cols:o}}else if(t==="step_end"){let r=Bo(e.affected_row_count),o=Zr(e.last_insert_rowid),n=o!==void 0?BigInt(o):void 0;return{type:"step_end",affectedRowCount:r,lastInsertRowid:n}}else if(t==="step_error"){let r=Bo(e.step),o=Yi(It(e.error));return{type:"step_error",step:r,error:o}}else if(t==="row")return{type:"row",row:xn(e.row,M4)};else if(t==="error")return{type:"error",error:Yi(It(e.error))};else throw new Pe("Unexpected type of CursorEntry")}function Py(e){let t=xn(e.params,Pfe),r=xn(e.cols,zfe),o=Vi(e.is_explain),n=Vi(e.is_readonly);return{params:t,cols:r,isExplain:o,isReadonly:n}}function Pfe(e){return{name:Zr(e.name)}}function zfe(e){let t=Rr(e.name),r=Zr(e.decltype);return{name:t,decltype:r}}function M4(e){let t=Rr(e.type);if(t==="null")return null;else if(t==="integer"){let r=Rr(e.value);return BigInt(r)}else if(t==="float")return Bo(e.value);else if(t==="text")return Rr(e.value);else if(t==="blob")return cl.toUint8Array(Rr(e.base64));else throw new Pe("Unexpected type of Value")}var zy=v(()=>{vy();_t();gl()});function q4(e){let t=Rr(e.type);if(t==="hello_ok")return{type:"hello_ok"};else if(t==="hello_error")return{type:"hello_error",error:Yi(It(e.error))};else if(t==="response_ok"){let r=Bo(e.request_id),o=Nfe(It(e.response));return{type:"response_ok",requestId:r,response:o}}else if(t==="response_error"){let r=Bo(e.request_id),o=Yi(It(e.error));return{type:"response_error",requestId:r,error:o}}else throw new Pe("Unexpected type of ServerMsg")}function Nfe(e){let t=Rr(e.type);if(t==="open_stream")return{type:"open_stream"};else if(t==="close_stream")return{type:"close_stream"};else if(t==="execute")return{type:"execute",result:$p(It(e.result))};else if(t==="batch")return{type:"batch",result:Oy(It(e.result))};else if(t==="open_cursor")return{type:"open_cursor"};else if(t==="close_cursor")return{type:"close_cursor"};else if(t==="fetch_cursor"){let r=xn(e.entries,Cy),o=Vi(e.done);return{type:"fetch_cursor",entries:r,done:o}}else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:Py(It(e.result))};else if(t==="store_sql")return{type:"store_sql"};else if(t==="close_sql")return{type:"close_sql"};else if(t==="get_autocommit")return{type:"get_autocommit",isAutocommit:Vi(e.is_autocommit)};else throw new Pe("Unexpected type of Response")}var F4=v(()=>{_t();gl();zy()});var nn,Xi,K4,J4,xl,Dfe,Lfe,Ny,Bfe,jfe,Zfe,_l,Ufe,Mfe,qfe;var Dy=v(()=>{nn={default(){return{message:"",code:void 0}},1(e,t){t.message=e.string()},2(e,t){t.code=e.string()}},Xi={default(){return{cols:[],rows:[],affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.cols.push(e.message(K4))},2(e,t){t.rows.push(e.message(J4))},3(e,t){t.affectedRowCount=Number(e.uint64())},4(e,t){t.lastInsertRowid=e.sint64()}},K4={default(){return{name:void 0,decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},J4={default(){return[]},1(e,t){t.push(e.message(qfe))}},xl={default(){return{stepResults:new Map,stepErrors:new Map}},1(e,t){let[r,o]=e.message(Dfe);t.stepResults.set(r,o)},2(e,t){let[r,o]=e.message(Lfe);t.stepErrors.set(r,o)}},Dfe={default(){return[0,Xi.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(Xi)}},Lfe={default(){return[0,nn.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(nn)}},Ny={default(){return{type:"none"}},1(e){return e.message(Bfe)},2(e){return e.message(jfe)},3(e){return e.message(Zfe)},4(e){return{type:"row",row:e.message(J4)}},5(e){return{type:"error",error:e.message(nn)}}},Bfe={default(){return{type:"step_begin",step:0,cols:[]}},1(e,t){t.step=e.uint32()},2(e,t){t.cols.push(e.message(K4))}},jfe={default(){return{type:"step_end",affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.affectedRowCount=e.uint32()},2(e,t){t.lastInsertRowid=e.uint64()}},Zfe={default(){return{type:"step_error",step:0,error:nn.default()}},1(e,t){t.step=e.uint32()},2(e,t){t.error=e.message(nn)}},_l={default(){return{params:[],cols:[],isExplain:!1,isReadonly:!1}},1(e,t){t.params.push(e.message(Ufe))},2(e,t){t.cols.push(e.message(Mfe))},3(e,t){t.isExplain=e.bool()},4(e,t){t.isReadonly=e.bool()}},Ufe={default(){return{name:void 0}},1(e,t){t.name=e.string()}},Mfe={default(){return{name:"",decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},qfe={default(){return},1(e){return null},2(e){return e.sint64()},3(e){return e.double()},4(e){return e.string()},5(e){return e.bytes()}}});var H4,Ffe,Kfe,Jfe,Hfe,Vfe,Wfe,Gfe,Qfe;var V4=v(()=>{Dy();H4={default(){return{type:"none"}},1(e){return{type:"hello_ok"}},2(e){return e.message(Ffe)},3(e){return e.message(Jfe)},4(e){return e.message(Kfe)}},Ffe={default(){return{type:"hello_error",error:nn.default()}},1(e,t){t.error=e.message(nn)}},Kfe={default(){return{type:"response_error",requestId:0,error:nn.default()}},1(e,t){t.requestId=e.int32()},2(e,t){t.error=e.message(nn)}},Jfe={default(){return{type:"response_ok",requestId:0,response:{type:"none"}}},1(e,t){t.requestId=e.int32()},2(e,t){t.response={type:"open_stream"}},3(e,t){t.response={type:"close_stream"}},4(e,t){t.response=e.message(Hfe)},5(e,t){t.response=e.message(Vfe)},6(e,t){t.response={type:"open_cursor"}},7(e,t){t.response={type:"close_cursor"}},8(e,t){t.response=e.message(Wfe)},9(e,t){t.response={type:"sequence"}},10(e,t){t.response=e.message(Gfe)},11(e,t){t.response={type:"store_sql"}},12(e,t){t.response={type:"close_sql"}},13(e,t){t.response=e.message(Qfe)}},Hfe={default(){return{type:"execute",result:Xi.default()}},1(e,t){t.result=e.message(Xi)}},Vfe={default(){return{type:"batch",result:xl.default()}},1(e,t){t.result=e.message(xl)}},Wfe={default(){return{type:"fetch_cursor",entries:[],done:!1}},1(e,t){t.entries.push(e.message(Ny))},2(e,t){t.done=e.bool()}},Gfe={default(){return{type:"describe",result:_l.default()}},1(e,t){t.result=e.message(_l)}},Qfe={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}}});var W4,eT,Ly;var By=v(()=>{MR();_t();qR();_p();bl();rn();WR();N4();Z4();F4();V4();W4=new Map([["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]),eT=new Map([["hrana3-protobuf",{version:3,encoding:"protobuf"}],["hrana3",{version:3,encoding:"json"}],["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]);Ly=class Ly extends fl{#e;#t;#r;#n;#o;#i;#a;#s;#c;_streamIdAlloc;_cursorIdAlloc;#l;constructor(e,t){super();this.#e=e,this.#t=[],this.#r=!1,this.#n=void 0,this.#o=!1,this.#i=void 0,this.#a=!1,this.#s=new Map,this.#c=new Gi,this._streamIdAlloc=new Gi,this._cursorIdAlloc=new Gi,this.#l=new Gi,this.#e.binaryType="arraybuffer",this.#e.addEventListener("open",()=>this.#p()),this.#e.addEventListener("close",(r)=>this.#g(r)),this.#e.addEventListener("error",(r)=>this.#f(r)),this.#e.addEventListener("message",(r)=>this.#y(r)),this.#d({type:"hello",jwt:t})}#d(e){if(this.#n!==void 0)throw new or("Trying to send a message on a closed client");if(this.#r)this.#m(e);else{let t=()=>this.#m(e),r=()=>{return};this.#t.push({openCallback:t,errorCallback:r})}}#p(){let e=this.#e.protocol;if(e===void 0){this.#u(new Ge("The `WebSocket.protocol` property is undefined. This most likely means that the WebSocket implementation provided by the environment is broken. If you are using Miniflare 2, please update to Miniflare 3, which fixes this problem."));return}else if(e==="")this.#i={version:1,encoding:"json"};else if(this.#i=eT.get(e),this.#i===void 0){this.#u(new Pe(`Unrecognized WebSocket subprotocol: ${JSON.stringify(e)}`));return}for(let t of this.#t)t.openCallback();this.#t.length=0,this.#r=!0}#m(e){let t=this.#i.encoding;if(t==="json"){let r=Sp(e,z4);this.#e.send(r)}else if(t==="protobuf"){let r=xp(e,j4);this.#e.send(r)}else throw Je(t,"Impossible encoding")}getVersion(){return new Promise((e,t)=>{if(this.#a=!0,this.#n!==void 0)t(this.#n);else if(!this.#r){let r=()=>e(this.#i.version);this.#t.push({openCallback:r,errorCallback:t})}else e(this.#i.version)})}_ensureVersion(e,t){if(this.#i===void 0||!this.#a)throw new wn(`${t} is supported only on protocol version ${e} and higher, but the version supported by the WebSocket server is not yet known. Use Client.getVersion() to wait until the version is available.`);else if(this.#i.version<e)throw new wn(`${t} is supported on protocol version ${e} and higher, but the WebSocket server only supports version ${this.#i.version}`)}_sendRequest(e,t){if(this.#n!==void 0){t.errorCallback(new xt("Client is closed",this.#n));return}let r=this.#c.alloc();this.#s.set(r,{...t,type:e.type}),this.#d({type:"request",requestId:r,request:e})}#f(e){let r=e.message??"WebSocket was closed due to an error";this.#u(new ml(r))}#g(e){let t=`WebSocket was closed with code ${e.code}`;if(e.reason)t+=`: ${e.reason}`;this.#u(new ml(t))}#u(e){if(this.#n!==void 0)return;this.#n=e;for(let t of this.#t)t.errorCallback(e);this.#t.length=0;for(let[t,r]of this.#s.entries())r.errorCallback(e),this.#c.free(t);this.#s.clear(),this.#e.close()}#y(e){if(this.#n!==void 0)return;try{let t,r=this.#i.encoding;if(r==="json"){if(typeof e.data!=="string"){this.#e.close(3003,"Only text messages are accepted with JSON encoding"),this.#u(new Pe("Received non-text message from server with JSON encoding"));return}t=ua(JSON.parse(e.data),q4)}else if(r==="protobuf"){if(!(e.data instanceof ArrayBuffer)){this.#e.close(3003,"Only binary messages are accepted with Protobuf encoding"),this.#u(new Pe("Received non-binary message from server with Protobuf encoding"));return}t=Wi(new Uint8Array(e.data),H4)}else throw Je(r,"Impossible encoding");this.#b(t)}catch(t){this.#e.close(3007,"Could not handle message"),this.#u(t)}}#b(e){if(e.type==="none")throw new Pe("Received an unrecognized ServerMsg");else if(e.type==="hello_ok"||e.type==="hello_error"){if(this.#o)throw new Pe("Received a duplicated hello response");if(this.#o=!0,e.type==="hello_error")throw jo(e.error);return}else if(!this.#o)throw new Pe("Received a non-hello message before a hello response");if(e.type==="response_ok"){let t=e.requestId,r=this.#s.get(t);if(this.#s.delete(t),r===void 0)throw new Pe("Received unexpected OK response");this.#c.free(t);try{if(r.type!==e.response.type)throw console.dir({responseState:r,msg:e}),new Pe("Received unexpected type of response");r.responseCallback(e.response)}catch(o){throw r.errorCallback(o),o}}else if(e.type==="response_error"){let t=e.requestId,r=this.#s.get(t);if(this.#s.delete(t),r===void 0)throw new Pe("Received unexpected error response");this.#c.free(t),r.errorCallback(jo(e.error))}else throw Je(e,"Impossible ServerMsg type")}openStream(){return Ap.open(this)}storeSql(e){this._ensureVersion(2,"storeSql()");let t=this.#l.alloc(),r=new fa(this,t),o=()=>{return},n=(s)=>r._setClosed(s),i={type:"store_sql",sqlId:t,sql:e};return this._sendRequest(i,{responseCallback:o,errorCallback:n}),r}_closeSql(e){if(this.#n!==void 0)return;let t=()=>this.#l.free(e),r=(n)=>this.#u(n),o={type:"close_sql",sqlId:e};this._sendRequest(o,{responseCallback:t,errorCallback:r})}close(){this.#u(new Ge("Client was manually closed"))}get closed(){return this.#n!==void 0}}});var ma;var G4=v(()=>{if(typeof queueMicrotask<"u")ma=queueMicrotask;else{let e=Promise.resolve();ma=(t)=>{e.then(t)}}});class tT{#e;#t;#r;constructor(e){this.#e=new Uint8Array(new ArrayBuffer(e)),this.#t=0,this.#r=0}get length(){return this.#r-this.#t}data(){return this.#e.slice(this.#t,this.#r)}push(e){this.#n(e.byteLength),this.#e.set(e,this.#r),this.#r+=e.byteLength}#n(e){if(this.#r+e<=this.#e.byteLength)return;let t=this.#r-this.#t;if(t+e<=this.#e.byteLength&&2*this.#r>=this.#e.byteLength)this.#e.copyWithin(0,this.#t,this.#r);else{let r=this.#e.byteLength;do r*=2;while(t+e>r);let o=new Uint8Array(new ArrayBuffer(r));o.set(this.#e.slice(this.#t,this.#r),0),this.#e=o}this.#r=t,this.#t=0}shift(e){this.#t+=e}}function Q4(e){let t=Zr(e.baton),r=Zr(e.base_url),o=xn(e.results,Yfe);return{baton:t,baseUrl:r,results:o}}function Yfe(e){let t=Rr(e.type);if(t==="ok")return{type:"ok",response:Xfe(It(e.response))};else if(t==="error")return{type:"error",error:Yi(It(e.error))};else throw new Pe("Unexpected type of StreamResult")}function Xfe(e){let t=Rr(e.type);if(t==="close")return{type:"close"};else if(t==="execute")return{type:"execute",result:$p(It(e.result))};else if(t==="batch")return{type:"batch",result:Oy(It(e.result))};else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:Py(It(e.result))};else if(t==="store_sql")return{type:"store_sql"};else if(t==="close_sql")return{type:"close_sql"};else if(t==="get_autocommit")return{type:"get_autocommit",isAutocommit:Vi(e.is_autocommit)};else throw new Pe("Unexpected type of StreamResponse")}function Y4(e){let t=Zr(e.baton),r=Zr(e.base_url);return{baton:t,baseUrl:r}}var rT=v(()=>{_t();gl();zy()});var X4,eme,tme,rme,nme,ome,ime,eF;var nT=v(()=>{Dy();X4={default(){return{baton:void 0,baseUrl:void 0,results:[]}},1(e,t){t.baton=e.string()},2(e,t){t.baseUrl=e.string()},3(e,t){t.results.push(e.message(eme))}},eme={default(){return{type:"none"}},1(e){return{type:"ok",response:e.message(tme)}},2(e){return{type:"error",error:e.message(nn)}}},tme={default(){return{type:"none"}},1(e){return{type:"close"}},2(e){return e.message(rme)},3(e){return e.message(nme)},4(e){return{type:"sequence"}},5(e){return e.message(ome)},6(e){return{type:"store_sql"}},7(e){return{type:"close_sql"}},8(e){return e.message(ime)}},rme={default(){return{type:"execute",result:Xi.default()}},1(e,t){t.result=e.message(Xi)}},nme={default(){return{type:"batch",result:xl.default()}},1(e,t){t.result=e.message(xl)}},ome={default(){return{type:"describe",result:_l.default()}},1(e,t){t.result=e.message(_l)}},ime={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}},eF={default(){return{baton:void 0,baseUrl:void 0}},1(e,t){t.baton=e.string()},2(e,t){t.baseUrl=e.string()}}});var oT;var tF=v(()=>{gl();ZR();_t();rn();rT();nT();zy();Dy();oT=class oT extends Ip{#e;#t;#r;#n;#o;#i;constructor(e,t){super();this.#e=e,this.#t=t,this.#r=void 0,this.#n=new tT(16384),this.#o=void 0,this.#i=!1}async open(e){if(e.body===null)throw new Pe("No response body for cursor request");this.#r=e.body[Symbol.asyncIterator]();let t=await this.#a(Y4,eF);if(t===void 0)throw new Pe("Empty response to cursor request");return t}next(){return this.#a(Cy,Ny)}close(){this._setClosed(new Ge("Cursor was manually closed"))}_setClosed(e){if(this.#o!==void 0)return;if(this.#o=e,this.#e._cursorClosed(this),this.#r!==void 0)this.#r.return()}get closed(){return this.#o!==void 0}async#a(e,t){for(;;){if(this.#i)return;else if(this.#o!==void 0)throw new xt("Cursor is closed",this.#o);if(this.#t==="json"){let n=this.#s();if(n!==void 0){let i=new TextDecoder().decode(n),s=JSON.parse(i);return ua(s,e)}}else if(this.#t==="protobuf"){let n=this.#c();if(n!==void 0)return Wi(n,t)}else throw Je(this.#t,"Impossible encoding");if(this.#r===void 0)throw new or("Attempted to read from HTTP cursor before it was opened");let{value:r,done:o}=await this.#r.next();if(o&&this.#n.length===0)this.#i=!0;else if(o)throw new Pe("Unexpected end of cursor stream");else this.#n.push(r)}}#s(){let e=this.#n.data(),t=10,r=e.indexOf(10);if(r<0)return;let o=e.slice(0,r);return this.#n.shift(r+1),o}#c(){let e=this.#n.data(),t=0,r=0;for(;;){if(r>=e.byteLength)return;let n=e[r];if(t|=(n&127)<<7*r,r+=1,!(n&128))break}if(e.byteLength<r+t)return;let o=e.slice(r,r+t);return this.#n.shift(r+t),o}}});function rF(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.arrayObjects("requests",t.requests,sme)}function sme(e,t){if(e.stringRaw("type",t.type),t.type==="close");else if(t.type==="execute")e.object("stmt",t.stmt,Rp);else if(t.type==="batch")e.object("batch",t.batch,vl);else if(t.type==="sequence"){if(t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="describe"){if(t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="store_sql")e.number("sql_id",t.sqlId),e.string("sql",t.sql);else if(t.type==="close_sql")e.number("sql_id",t.sqlId);else if(t.type==="get_autocommit");else throw Je(t,"Impossible type of StreamRequest")}function nF(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.object("batch",t.batch,vl)}var iT=v(()=>{QR();rn()});function oF(e,t){if(t.baton!==void 0)e.string(1,t.baton);for(let r of t.requests)e.message(2,r,ame)}function ame(e,t){if(t.type==="close")e.message(1,t,cme);else if(t.type==="execute")e.message(2,t,lme);else if(t.type==="batch")e.message(3,t,ume);else if(t.type==="sequence")e.message(4,t,dme);else if(t.type==="describe")e.message(5,t,pme);else if(t.type==="store_sql")e.message(6,t,fme);else if(t.type==="close_sql")e.message(7,t,mme);else if(t.type==="get_autocommit")e.message(8,t,hme);else throw Je(t,"Impossible type of StreamRequest")}function cme(e,t){}function lme(e,t){e.message(1,t.stmt,Tp)}function ume(e,t){e.message(1,t.batch,wl)}function dme(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function pme(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function fme(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function mme(e,t){e.int32(1,t.sqlId)}function hme(e,t){}function iF(e,t){if(t.baton!==void 0)e.string(1,t.baton);e.message(2,t.batch,wl)}var sT=v(()=>{XR();rn()});function gme(e,t){if(t.results.length!==e.length)throw new Pe("Server returned unexpected number of pipeline results");for(let r=0;r<e.length;++r){let o=t.results[r],n=e[r];if(o.type==="ok"){if(o.response.type!==n.request.type)throw new Pe("Received unexpected type of response");n.responseCallback(o.response)}else if(o.type==="error")n.errorCallback(jo(o.error));else if(o.type==="none")throw new Pe("Received unrecognized type of StreamResult");else throw Je(o,"Received impossible type of StreamResult")}}async function yme(e,t){if(t==="json"){let r=await e.json();return ua(r,Q4)}if(t==="protobuf"){let r=await e.arrayBuffer();return Wi(new Uint8Array(r),X4)}throw await e.body?.cancel(),Je(t,"Impossible encoding")}async function bme(e){let t=e.headers.get("content-type")??"text/plain",r=`Server returned HTTP status ${e.status}`;if(t==="application/json"){let o=await e.json();if("message"in o)return jo(o);return new la(r,e.status)}if(t==="text/plain"){let o=(await e.text()).trim();if(o!=="")r+=`: ${o}`;return new la(r,e.status)}return await e.body?.cancel(),new la(r,e.status)}var jy;var aT=v(()=>{_t();MR();qR();G4();_p();bl();$y();rn();tF();iT();sT();iT();sT();rT();nT();jy=class jy extends Sl{#e;#t;#r;#n;#o;#i;#a;#s;#c;#l;#d;#p;#m;constructor(e,t,r,o,n){super(e.intMode);this.#e=e,this.#t=t.toString(),this.#r=r,this.#n=o,this.#o=n,this.#i=void 0,this.#a=new Qi,this.#s=!1,this.#l=!1,this.#d=!1,this.#p=void 0,this.#m=new Gi}client(){return this.#e}_sqlOwner(){return this}storeSql(e){let t=this.#m.alloc();return this.#f({type:"store_sql",sqlId:t,sql:e}).then(()=>{return},(r)=>this._setClosed(r)),new fa(this,t)}_closeSql(e){if(this.#p!==void 0)return;this.#f({type:"close_sql",sqlId:e}).then(()=>this.#m.free(e),(t)=>this._setClosed(t))}_execute(e){return this.#f({type:"execute",stmt:e}).then((t)=>t.result)}_batch(e){return this.#f({type:"batch",batch:e}).then((t)=>t.result)}_describe(e){return this.#f({type:"describe",sql:e.sql,sqlId:e.sqlId}).then((t)=>t.result)}_sequence(e){return this.#f({type:"sequence",sql:e.sql,sqlId:e.sqlId}).then((t)=>{return})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#f({type:"get_autocommit"}).then((e)=>e.isAutocommit)}#f(e){return new Promise((t,r)=>{this.#g({type:"pipeline",request:e,responseCallback:t,errorCallback:r})})}_openCursor(e){return new Promise((t,r)=>{this.#g({type:"cursor",batch:e,cursorCallback:t,errorCallback:r})})}_cursorClosed(e){if(e!==this.#c)throw new or("Cursor was closed, but it was not associated with the stream");this.#c=void 0,ma(()=>this.#u())}close(){this._setClosed(new Ge("Stream was manually closed"))}closeGracefully(){this.#l=!0,ma(()=>this.#u())}get closed(){return this.#p!==void 0||this.#l}_setClosed(e){if(this.#p!==void 0)return;if(this.#p=e,this.#c!==void 0)this.#c._setClosed(e);this.#e._streamClosed(this);for(;;){let t=this.#a.shift();if(t!==void 0)t.errorCallback(e);else break}if((this.#i!==void 0||this.#s)&&!this.#d)this.#a.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0,ma(()=>this.#u())}#g(e){if(this.#p!==void 0)throw new xt("Stream is closed",this.#p);else if(this.#l)throw new xt("Stream is closing",void 0);else this.#a.push(e),ma(()=>this.#u())}#u(){if(this.#s||this.#c!==void 0)return;if(this.#l&&this.#a.length===0){this._setClosed(new Ge("Stream was gracefully closed"));return}let e=this.#e._endpoint;if(e===void 0){this.#e._endpointPromise.then(()=>this.#u(),(r)=>this._setClosed(r));return}let t=this.#a.shift();if(t===void 0)return;else if(t.type==="pipeline"){let r=[t];for(;;){let o=this.#a.first();if(o!==void 0&&o.type==="pipeline")r.push(o),this.#a.shift();else if(o===void 0&&this.#l&&!this.#d){r.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0;break}else break}this.#y(e,r)}else if(t.type==="cursor")this.#b(e,t);else throw Je(t,"Impossible type of QueueEntry")}#y(e,t){this.#h(()=>this.#S(t,e),(r)=>yme(r,e.encoding),(r)=>r.baton,(r)=>r.baseUrl,(r)=>gme(t,r),(r)=>t.forEach((o)=>o.errorCallback(r)))}#b(e,t){let r=new oT(this,e.encoding);this.#c=r,this.#h(()=>this.#v(t,e),(o)=>r.open(o),(o)=>o.baton,(o)=>o.baseUrl,(o)=>t.cursorCallback(r),(o)=>t.errorCallback(o))}#h(e,t,r,o,n,i){let s;try{let a=e(),l=this.#n;s=l(a)}catch(a){s=Promise.reject(a)}this.#s=!0,s.then((a)=>{if(!a.ok)return bme(a).then((l)=>{throw l});return t(a)}).then((a)=>{this.#i=r(a),this.#t=o(a)??this.#t,n(a)}).catch((a)=>{this._setClosed(a),i(a)}).finally(()=>{this.#s=!1,this.#u()})}#S(e,t){return this.#w(new URL(t.pipelinePath,this.#t),{baton:this.#i,requests:e.map((r)=>r.request)},t.encoding,rF,oF)}#v(e,t){if(t.cursorPath===void 0)throw new wn(`Cursors are supported only on protocol version 3 and higher, but the HTTP server only supports version ${t.version}.`);return this.#w(new URL(t.cursorPath,this.#t),{baton:this.#i,batch:e.batch},t.encoding,nF,iF)}#w(e,t,r,o,n){let i,s;if(r==="json")i=Sp(t,o),s="application/json";else if(r==="protobuf")i=xp(t,n),s="application/x-protobuf";else throw Je(r,"Impossible encoding");let a=new Headers;if(a.set("content-type",s),this.#r!==void 0)a.set("authorization",`Bearer ${this.#r}`);if(this.#o!==void 0)a.set("x-turso-encryption-key",this.#o);return new Request(e.toString(),{method:"POST",headers:a,body:i})}}});async function vme(e,t){let r=e;for(let o of Sme){let n=new URL(o.versionPath,t),i=new Request(n.toString(),{method:"GET"}),s=await r(i);if(await s.arrayBuffer(),s.ok)return o}return cT}var Sme,cT,Zy;var lT=v(()=>{_t();aT();Sme=[{versionPath:"v3-protobuf",pipelinePath:"v3-protobuf/pipeline",cursorPath:"v3-protobuf/cursor",version:3,encoding:"protobuf"}],cT={versionPath:"v2",pipelinePath:"v2/pipeline",cursorPath:void 0,version:2,encoding:"json"};Zy=class Zy extends fl{#e;#t;#r;#n;#o;#i;_endpointPromise;_endpoint;constructor(e,t,r,o,n=2){super();if(this.#e=e,this.#t=t,this.#r=r??globalThis.fetch,this.#n=o,this.#o=void 0,this.#i=new Set,n==3)this._endpointPromise=vme(this.#r,this.#e),this._endpointPromise.then((i)=>this._endpoint=i,(i)=>this.#a(i));else this._endpointPromise=Promise.resolve(cT),this._endpointPromise.then((i)=>this._endpoint=i,(i)=>this.#a(i))}async getVersion(){if(this._endpoint!==void 0)return this._endpoint.version;return(await this._endpointPromise).version}_ensureVersion(e,t){if(e<=cT.version)return;else if(this._endpoint===void 0)throw new wn(`${t} is supported only on protocol version ${e} and higher, but the version supported by the HTTP server is not yet known. Use Client.getVersion() to wait until the version is available.`);else if(this._endpoint.version<e)throw new wn(`${t} is supported only on protocol version ${e} and higher, but the HTTP server only supports version ${this._endpoint.version}.`)}openStream(){if(this.#o!==void 0)throw new xt("Client is closed",this.#o);let e=new jy(this,this.#e,this.#t,this.#r,this.#n);return this.#i.add(e),e}_streamClosed(e){this.#i.delete(e)}close(){this.#a(new Ge("Client was manually closed"))}get closed(){return this.#o!==void 0}#a(e){if(this.#o!==void 0)return;this.#o=e;for(let t of Array.from(this.#i))t._setClosed(new xt("Client was closed",e))}}});var sF=v(()=>{_t()});function uT(e,t,r=2){if(typeof Hi>"u")throw new yp("WebSockets are not supported in this environment");var o=void 0;if(r==3)o=Array.from(eT.keys());else o=Array.from(W4.keys());let n=new Hi(e,o);return new Ly(n,t)}function dT(e,t,r,o,n=2){return new Zy(e instanceof URL?e:new URL(e),t,r,o,n)}var Uy=v(()=>{jR();By();_t();lT();By();jR();HR();sF();bl();Ry();$y();lT();aT();By();WR();_t()});class Op{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}execute(e){return this.batch([e]).then((t)=>t[0])}async batch(e){let t=this._getStream();if(t.closed)throw new Ce("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{let r=e.map(Zo),o;if(this.#r===void 0){this._getSqlCache().apply(r);let i=t.batch(this.#t>=3),s=i.step(),a=s.run(Ki(this.#e)),l=s;o=r.map((u)=>{let d=i.step().condition(ut.ok(l));if(this.#t>=3)d.condition(ut.not(ut.isAutocommit(i)));let p=d.query(u);return p.catch(()=>{return}),l=d,p}),this.#r=i.execute().then(()=>a).then(()=>{return});try{await this.#r}catch(u){throw this.close(),u}}else{if(this.#t<3)await this.#r;this._getSqlCache().apply(r);let i=t.batch(this.#t>=3),s=void 0;o=r.map((a)=>{let l=i.step();if(s!==void 0)l.condition(ut.ok(s));if(this.#t>=3)l.condition(ut.not(ut.isAutocommit(i)));let u=l.query(a);return u.catch(()=>{return}),s=l,u}),await i.execute()}let n=[];for(let i=0;i<o.length;i++)try{let s=await o[i];if(s===void 0)throw new Wt("Statement in a transaction was not executed, probably because the transaction has been rolled back",i,"TRANSACTION_CLOSED");n.push(kl(s))}catch(s){if(s instanceof Wt)throw s;let a=st(s);if(a instanceof Ce)throw new Wt(a.message,i,a.code,a.extendedCode,a.rawCode,a.cause instanceof Error?a.cause:void 0);throw a}return n}catch(r){throw st(r)}}async executeMultiple(e){let t=this._getStream();if(t.closed)throw new Ce("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{if(this.#r===void 0){this.#r=t.run(Ki(this.#e)).then(()=>{return});try{await this.#r}catch(r){throw this.close(),r}}else await this.#r;await t.sequence(e)}catch(r){throw st(r)}}async rollback(){try{let e=this._getStream();if(e.closed)return;if(this.#r!==void 0);else return;let t=e.run("ROLLBACK").catch((r)=>{throw st(r)});e.closeGracefully(),await t}catch(e){throw st(e)}finally{this.close()}}async commit(){try{let e=this._getStream();if(e.closed)throw new Ce("Cannot commit the transaction because it is already closed","TRANSACTION_CLOSED");if(this.#r!==void 0)await this.#r;else return;let t=e.run("COMMIT").catch((r)=>{throw st(r)});e.closeGracefully(),await t}catch(e){throw st(e)}finally{this.close()}}}async function El(e,t,r,o,n=!1){if(n)r.step().run("PRAGMA foreign_keys=off");let i=r.step(),s=i.run(Ki(e)),a=i,l=o.map((h)=>{let b=r.step().condition(ut.ok(a));if(t>=3)b.condition(ut.not(ut.isAutocommit(r)));let y=b.query(h);return a=b,y}),u=r.step().condition(ut.ok(a));if(t>=3)u.condition(ut.not(ut.isAutocommit(r)));let d=u.run("COMMIT");if(r.step().condition(ut.not(ut.ok(u))).run("ROLLBACK").catch((h)=>{return}),n)r.step().run("PRAGMA foreign_keys=on");await r.execute();let m=[];await s;for(let h=0;h<l.length;h++)try{let b=await l[h];if(b===void 0)throw new Wt("Statement in a batch was not executed, probably because the transaction has been rolled back",h,"TRANSACTION_CLOSED");m.push(kl(b))}catch(b){if(b instanceof Wt)throw b;let y=st(b);if(y instanceof Ce)throw new Wt(y.message,h,y.code,y.extendedCode,y.rawCode,y.cause instanceof Error?y.cause:void 0);throw y}return await d,m}function Zo(e){let t,r;if(Array.isArray(e))[t,r]=e;else if(typeof e==="string")t=e;else t=e.sql,r=e.args;let o=new kp(t);if(r)if(Array.isArray(r))o.bindIndexes(r);else for(let[n,i]of Object.entries(r))o.bindName(n,i);return o}function kl(e){let t=e.columnNames.map((s)=>s??""),r=e.columnDecltypes.map((s)=>s??""),o=e.rows,n=e.affectedRowCount,i=e.lastInsertRowid!==void 0?e.lastInsertRowid:void 0;return new ll(t,r,o,n,i)}function st(e){if(e instanceof Ge){let t=aF(e);return new Ce(e.message,t,void 0,void 0,e)}return e}function aF(e){if(e instanceof gp&&e.code!==void 0)return e.code;else if(e instanceof Pe)return"HRANA_PROTO_ERROR";else if(e instanceof xt)return e.cause instanceof Ge?aF(e.cause):"HRANA_CLOSED_ERROR";else if(e instanceof ml)return"HRANA_WEBSOCKET_ERROR";else if(e instanceof la)return"SERVER_ERROR";else if(e instanceof wn)return"PROTOCOL_VERSION_ERROR";else if(e instanceof or)return"INTERNAL_ERROR";else return"UNKNOWN"}var fT=v(()=>{Uy();vn();ul()});class Il{#e;#t;capacity;constructor(e,t){this.#e=e,this.#t=new cF,this.capacity=t}apply(e){if(this.capacity<=0)return;let t=new Set;for(let r of e){if(typeof r.sql!=="string")continue;let o=r.sql;if(o.length>=5000)continue;let n=this.#t.get(o);if(n===void 0){while(this.#t.size+1>this.capacity){let[i,s]=this.#t.peekLru();if(t.has(s))break;s.close(),this.#t.delete(i)}if(this.#t.size+1<=this.capacity)n=this.#e.storeSql(o),this.#t.set(o,n)}if(n!==void 0)r.sql=n,t.add(n)}}}class cF{#e;constructor(){this.#e=new Map}get(e){let t=this.#e.get(e);if(t!==void 0)this.#e.delete(e),this.#e.set(e,t);return t}set(e,t){this.#e.set(e,t)}peekLru(){for(let e of this.#e.entries())return e;return}delete(e){this.#e.delete(e)}get size(){return this.#e.size}}var mT=ge(function(xBe,uF){function wme(e){var t=0,r=[];function o(){if(t--,t<e)n()}function n(){var l=r.shift();if(a.queue=r.length,l)s(l.fn).then(l.resolve).catch(l.reject)}function i(l){return new Promise(function(u,d){r.push({fn:l,resolve:u,reject:d}),a.queue=r.length})}function s(l){t++;try{return Promise.resolve(l()).then(function(u){return o(),u},function(u){throw o(),u})}catch(u){return o(),Promise.reject(u)}}var a=function(l){if(t>=e)return i(l);else return s(l)};return a}function xme(e,t){var r=!1,o=this;return Promise.all(e.map(function(){var n=arguments;return o(function(){if(!r)return t.apply(void 0,n).catch(function(i){throw r=!0,i})})}))}function lF(e){return e.queue=0,e.map=xme,e}uF.exports=function(e){if(e)return lF(wme(e));else return lF(function(t){return t()})}});function fF(e){if(e.scheme!=="wss"&&e.scheme!=="ws")throw new Ce(`The WebSocket client supports only "libsql:", "wss:" and "ws:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${Yn}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Ce("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="ws"&&e.tls)throw new Ce('A "ws:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="wss"&&!e.tls)throw new Ce('A "wss:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=dp(e.scheme,e.authority,e.path),r;try{r=uT(t,e.authToken)}catch(o){if(o instanceof yp){let n=e.scheme==="wss"?"https":"http",i=dp(n,e.authority,e.path);throw new Ce(`This environment does not support WebSockets, please switch to the HTTP client by using a "${n}:" URL (${JSON.stringify(i)}). For more information, please read ${Yn}`,"WEBSOCKETS_NOT_SUPPORTED")}throw st(o)}return new mF(r,t,e.authToken,e.intMode,e.concurrency)}class mF{#e;#t;#r;#n;#o;closed;protocol;#i;#a;constructor(e,t,r,o,n){this.#e=t,this.#t=r,this.#r=o,this.#n=this.#c(e),this.#o=void 0,this.closed=!1,this.protocol="ws",this.#a=pF.default(n)}async limit(e){return this.#a(e)}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.limit(async()=>{let o=await this.#s();try{let n=Zo(r);o.conn.sqlCache.apply([n]);let i=o.stream.query(n);o.stream.closeGracefully();let s=await i;return kl(s)}catch(n){throw st(n)}finally{this._closeStream(o)}})}async batch(e,t="deferred"){return this.limit(async()=>{let r=await this.#s();try{let n=e.map((u)=>{if(Array.isArray(u))return{sql:u[0],args:u[1]||[]};return u}).map(Zo),i=await r.conn.client.getVersion();r.conn.sqlCache.apply(n);let s=r.stream.batch(i>=3);return await El(t,i,s,n)}catch(o){throw st(o)}finally{this._closeStream(r)}})}async migrate(e){return this.limit(async()=>{let t=await this.#s();try{let r=e.map(Zo),o=await t.conn.client.getVersion(),n=t.stream.batch(o>=3);return await El("deferred",o,n,r,!0)}catch(r){throw st(r)}finally{this._closeStream(t)}})}async transaction(e="write"){return this.limit(async()=>{let t=await this.#s();try{let r=await t.conn.client.getVersion();return new hF(this,t,e,r)}catch(r){throw this._closeStream(t),st(r)}})}async executeMultiple(e){return this.limit(async()=>{let t=await this.#s();try{let r=t.stream.sequence(e);t.stream.closeGracefully(),await r}catch(r){throw st(r)}finally{this._closeStream(t)}})}sync(){throw new Ce("sync not supported in ws mode","SYNC_NOT_SUPPORTED")}async#s(){if(this.closed)throw new Ce("The client is closed","CLIENT_CLOSED");if(new Date().valueOf()-this.#n.openTime.valueOf()>_me&&this.#o===void 0){let o=this.#c();this.#o=o,o.client.getVersion().then((n)=>{if(this.#n!==o){if(this.#n.streamStates.size===0)this.#n.client.close()}this.#n=o,this.#o=void 0},(n)=>{this.#o=void 0})}if(this.#n.client.closed)try{if(this.#o!==void 0)this.#n=this.#o;else this.#n=this.#c()}catch(o){throw st(o)}let r=this.#n;try{if(r.useSqlCache===void 0){if(r.useSqlCache=await r.client.getVersion()>=2,r.useSqlCache)r.sqlCache.capacity=dF}let o=r.client.openStream();o.intMode=this.#r;let n={conn:r,stream:o};return r.streamStates.add(n),n}catch(o){throw st(o)}}#c(e){try{return e??=uT(this.#e,this.#t),{client:e,useSqlCache:void 0,sqlCache:new Il(e,0),openTime:new Date,streamStates:new Set}}catch(t){throw st(t)}}async reconnect(){try{for(let r of Array.from(this.#n.streamStates))try{r.stream.close()}catch{}this.#n.client.close()}catch{}if(this.#o){try{this.#o.client.close()}catch{}this.#o=void 0}let e=this.#c(),t=await e.client.getVersion();if(e.useSqlCache=t>=2,e.useSqlCache)e.sqlCache.capacity=dF;this.#n=e,this.closed=!1}_closeStream(e){e.stream.close();let t=e.conn;if(t.streamStates.delete(e),t.streamStates.size===0&&t!==this.#n)t.client.close()}close(){if(this.#n.client.close(),this.closed=!0,this.#o){try{this.#o.client.close()}catch{}this.#o=void 0}this.closed=!0}}var pF,_me=60000,dF=100,hF;var gF=v(()=>{Uy();vn();mp();fT();yy();ul();pF=Ml(mT(),1);vn();hF=class hF extends Op{#e;#t;constructor(e,t,r,o){super(r,o);this.#e=e,this.#t=t}_getStream(){return this.#t.stream}_getSqlCache(){return this.#t.conn.sqlCache}close(){this.#e._closeStream(this.#t)}get closed(){return this.#t.stream.closed}}});function bF(e){if(e.scheme!=="https"&&e.scheme!=="http")throw new Ce(`The HTTP client supports only "libsql:", "https:" and "http:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${Yn}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Ce("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="http"&&e.tls)throw new Ce('A "http:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="https"&&!e.tls)throw new Ce('A "https:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=dp(e.scheme,e.authority,e.path);return new vF(t,e.authToken,e.intMode,e.fetch,e.concurrency,e.remoteEncryptionKey)}class vF{#e;protocol;#t;#r;#n;#o;#i;#a;#s;constructor(e,t,r,o,n,i){this.#t=e,this.#i=t,this.#r=r,this.#n=o,this.#o=n,this.#a=i,this.#e=dT(this.#t,this.#i,this.#n,i),this.#e.intMode=this.#r,this.protocol="http",this.#s=yF.default(this.#o)}async limit(e){return this.#s(e)}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.limit(async()=>{try{let o=Zo(r),n,i=this.#e.openStream();try{n=i.query(o)}finally{i.closeGracefully()}let s=await n;return kl(s)}catch(o){throw st(o)}})}async batch(e,t="deferred"){return this.limit(async()=>{try{let o=e.map((l)=>{if(Array.isArray(l))return{sql:l[0],args:l[1]||[]};return l}).map(Zo),n=await this.#e.getVersion(),i,s=this.#e.openStream();try{new Il(s,SF).apply(o);let u=s.batch(!1);i=El(t,n,u,o)}finally{s.closeGracefully()}return await i}catch(r){throw st(r)}})}async migrate(e){return this.limit(async()=>{try{let t=e.map(Zo),r=await this.#e.getVersion(),o,n=this.#e.openStream();try{let s=n.batch(!1);o=El("deferred",r,s,t,!0)}finally{n.closeGracefully()}return await o}catch(t){throw st(t)}})}async transaction(e="write"){return this.limit(async()=>{try{let t=await this.#e.getVersion();return new wF(this.#e.openStream(),e,t)}catch(t){throw st(t)}})}async executeMultiple(e){return this.limit(async()=>{try{let t,r=this.#e.openStream();try{t=r.sequence(e)}finally{r.closeGracefully()}await t}catch(t){throw st(t)}})}sync(){throw new Ce("sync not supported in http mode","SYNC_NOT_SUPPORTED")}close(){this.#e.close()}async reconnect(){try{if(!this.closed)this.#e.close()}finally{this.#e=dT(this.#t,this.#i,this.#n,this.#a),this.#e.intMode=this.#r}}get closed(){return this.#e.closed}}var yF,SF=30,wF;var xF=v(()=>{Uy();vn();mp();fT();yy();ul();yF=Ml(mT(),1);vn();wF=class wF extends Op{#e;#t;constructor(e,t,r){super(t,r);this.#e=e,this.#t=new Il(e,SF)}_getStream(){return this.#e}_getSqlCache(){return this.#t}close(){this.#e.close()}get closed(){return this.#e.closed}}});function Al(e){return Eme(fp(e,!0))}function Eme(e){if(e.scheme==="wss"||e.scheme==="ws")return fF(e);else if(e.scheme==="https"||e.scheme==="http")return bF(e);else return y4(e)}var hT=v(()=>{mp();x4();gF();xF();vn()});function oe(e,t){if(!e||typeof e!=="object")return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,F))throw Error(`Class "${t.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let r=Object.getPrototypeOf(e).constructor;if(r)while(r){if(F in r&&r[F]===t[F])return!0;r=Object.getPrototypeOf(r)}return!1}var F;var $e=v(()=>{F=Symbol.for("drizzle:entityKind")});var He;var _n=v(()=>{$e();He=class He{constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.keyAsName=t.keyAsName,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.onUpdateFn=t.onUpdateFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType,this.generated=t.generated,this.generatedIdentity=t.generatedIdentity}static[F]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(e){return e}mapToDriverValue(e){return e}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}});var Cp;var My=v(()=>{$e();Cp=class Cp{static[F]="ColumnBuilder";config;constructor(e,t,r){this.config={name:e,keyAsName:e==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:t,columnType:r,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e){if(this.config.name!=="")return;this.config.name=e}}});var ir;var Rl=v(()=>{ir=Symbol.for("drizzle:Name")});var gT,_F;var EF=v(()=>{$e();Rl();gT=class gT{static[F]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,t){if(this.reference=()=>{let{name:r,columns:o,foreignColumns:n}=e();return{name:r,columns:o,foreignTable:n[0].table,foreignColumns:n}},t)this._onUpdate=t.onUpdate,this._onDelete=t.onDelete}onUpdate(e){return this._onUpdate=e===void 0?"no action":e,this}onDelete(e){return this._onDelete=e===void 0?"no action":e,this}build(e){return new _F(e,this)}};_F=class _F{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[F]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),o=t.map((s)=>s.name),n=r.map((s)=>s.name),i=[this.table[ir],...o,r[0].table[ir],...n];return e??`${i.join("_")}_fk`}}});function qy(e,...t){return e(...t)}var yT=()=>{};function bT(e,t){return`${e[ir]}_${t.join("_")}_unique`}var kF,kme,IF;var AF=v(()=>{$e();Rl();kF=class kF{constructor(e,t){this.name=t,this.columns=e}static[F]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new IF(e,this.columns,this.nullsNotDistinctConfig,this.name)}};kme=class kme{static[F]="PgUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new kF(e,this.name)}};IF=class IF{constructor(e,t,r,o){this.table=e,this.columns=t,this.name=o??bT(this.table,this.columns.map((n)=>n.name)),this.nullsNotDistinct=r}static[F]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}}});function RF(e,t,r){for(let o=t;o<e.length;o++){let n=e[o];if(n==="\\"){o++;continue}if(n==='"')return[e.slice(t,o).replace(/\\/g,""),o+1];if(r)continue;if(n===","||n==="}")return[e.slice(t,o).replace(/\\/g,""),o]}return[e.slice(t).replace(/\\/g,""),e.length]}function TF(e,t=0){let r=[],o=t,n=!1;while(o<e.length){let i=e[o];if(i===","){if(n||o===t)r.push("");n=!0,o++;continue}if(n=!1,i==="\\"){o+=2;continue}if(i==='"'){let[l,u]=RF(e,o+1,!0);r.push(l),o=u;continue}if(i==="}")return[r,o+1];if(i==="{"){let[l,u]=TF(e,o+1);r.push(l),o=u;continue}let[s,a]=RF(e,o,!1);r.push(s),o=a}return[r,o]}function $F(e){let[t]=TF(e,1);return t}function ST(e){return`{${e.map((t)=>{if(Array.isArray(t))return ST(t);if(typeof t==="string")return`"${t.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${t}`}).join(",")}}`}var OF=()=>{};var Pp,Tl,CF,Ime,PF,vT;var zF=v(()=>{My();_n();$e();EF();yT();AF();OF();Pp=class Pp extends Cp{foreignKeyConfigs=[];static[F]="PgColumnBuilder";array(e){return new PF(this.config.name,this,e)}references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e,t){return this.config.isUnique=!0,this.config.uniqueName=e,this.config.uniqueType=t?.nulls,this}generatedAlwaysAs(e){return this.config.generated={as:e,type:"always",mode:"stored"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:r,actions:o})=>qy((n,i)=>{let s=new gT(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(i.onUpdate)s.onUpdate(i.onUpdate);if(i.onDelete)s.onDelete(i.onDelete);return s.build(t)},r,o))}buildExtraConfigColumn(e){return new CF(e,this.config)}};Tl=class Tl extends He{constructor(e,t){if(!t.uniqueName)t.uniqueName=bT(e,[t.name]);super(e,t);this.table=e}static[F]="PgColumn"};CF=class CF extends Tl{static[F]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(e){return this.indexConfig.opClass=e,this}};Ime=class Ime{static[F]="IndexedColumn";constructor(e,t,r,o){this.name=e,this.keyAsName=t,this.type=r,this.indexConfig=o}name;keyAsName;type;indexConfig};PF=class PF extends Pp{static[F]="PgArrayBuilder";constructor(e,t,r){super(e,"array","PgArray");this.config.baseBuilder=t,this.config.size=r}build(e){let t=this.config.baseBuilder.build(e);return new vT(e,this.config,t)}};vT=class vT extends Tl{constructor(e,t,r,o){super(e,t);this.baseColumn=r,this.range=o,this.size=t.size}size;static[F]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(e){if(typeof e==="string")e=$F(e);return e.map((t)=>this.baseColumn.mapFromDriverValue(t))}mapToDriverValue(e,t=!1){let r=e.map((o)=>o===null?null:oe(this.baseColumn,vT)?this.baseColumn.mapToDriverValue(o,!0):this.baseColumn.mapToDriverValue(o));if(t)return r;return ST(r)}}});function LF(e){return!!e&&typeof e==="function"&&NF in e&&e[NF]===!0}var Ame,DF,NF,Rme,BF;var jF=v(()=>{$e();zF();Ame=class Ame extends Pp{static[F]="PgEnumObjectColumnBuilder";constructor(e,t){super(e,"string","PgEnumObjectColumn");this.config.enum=t}build(e){return new DF(e,this.config)}};DF=class DF extends Tl{static[F]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}};NF=Symbol.for("drizzle:isPgEnum");Rme=class Rme extends Pp{static[F]="PgEnumColumnBuilder";constructor(e,t){super(e,"string","PgEnumColumn");this.config.enum=t}build(e){return new BF(e,this.config)}};BF=class BF extends Tl{static[F]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}}});var dt,zp;var En=v(()=>{$e();dt=class dt{static[F]="Subquery";constructor(e,t,r,o=!1,n=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:r,isWith:o,usedTables:n}}};zp=class zp extends dt{static[F]="WithSubquery"}});var ZF="0.45.2";var UF=()=>{};var wT,xT,MF;var qF=v(()=>{yT();UF();MF={startActiveSpan(e,t){if(!wT)return t();if(!xT)xT=wT.trace.getTracer("drizzle-orm",ZF);return qy((r,o)=>o.startActiveSpan(e,(n)=>{try{return t(n)}catch(i){throw n.setStatus({code:r.SpanStatusCode.ERROR,message:i instanceof Error?i.message:"Unknown error"}),i}finally{n.end()}}),wT,xT)}}});var pt;var Uo=v(()=>{pt=Symbol.for("drizzle:ViewBaseConfig")});function es(e){return e[ir]}function ha(e){return`${e[Fy]??"public"}.${e[ir]}`}var Fy,Ky,FF,_T,ET,Np,KF,Tme,he;var sr=v(()=>{$e();Rl();Fy=Symbol.for("drizzle:Schema"),Ky=Symbol.for("drizzle:Columns"),FF=Symbol.for("drizzle:ExtraConfigColumns"),_T=Symbol.for("drizzle:OriginalName"),ET=Symbol.for("drizzle:BaseName"),Np=Symbol.for("drizzle:IsAlias"),KF=Symbol.for("drizzle:ExtraConfigBuilder"),Tme=Symbol.for("drizzle:IsDrizzleTable");he=class he{static[F]="Table";static Symbol={Name:ir,Schema:Fy,OriginalName:_T,Columns:Ky,ExtraConfigColumns:FF,BaseName:ET,IsAlias:Np,ExtraConfigBuilder:KF};[ir];[_T];[Fy];[Ky];[FF];[ET];[Np]=!1;[Tme]=!0;[KF]=void 0;constructor(e,t,r){this[ir]=this[_T]=e,this[Fy]=t,this[ET]=r}}});function kT(e){return e!==null&&e!==void 0&&typeof e.getSQL==="function"}function Ome(e){let t={sql:"",params:[]};for(let r of e)if(t.sql+=r.sql,t.params.push(...r.params),r.typings?.length){if(!t.typings)t.typings=[];t.typings.push(...r.typings)}return t}function JF(e){return typeof e==="object"&&e!==null&&"mapToDriverValue"in e&&typeof e.mapToDriverValue==="function"}function C(e,...t){let r=[];if(t.length>0||e.length>0&&e[0]!=="")r.push(new Nt(e[0]));for(let[o,n]of t.entries())r.push(n,new Nt(e[o+1]));return new _e(r)}function Dp(e,t){return e.map((r)=>{if(oe(r,ts)){if(!(r.name in t))throw Error(`No value for placeholder "${r.name}" was provided`);return t[r.name]}if(oe(r,Ur)&&oe(r.value,ts)){if(!(r.value.name in t))throw Error(`No value for placeholder "${r.value.name}" was provided`);return r.encoder.mapToDriverValue(t[r.value.name])}return r})}var $me,Nt,_e,Jy,HF,VF,Pje,Ur,ts,Cme,on;var Qt=v(()=>{$e();jF();En();qF();Uo();_n();sr();$me=class $me{static[F]="FakePrimitiveParam"};Nt=class Nt{static[F]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new _e([this])}};_e=class _e{constructor(e){this.queryChunks=e;for(let t of e)if(oe(t,he)){let r=t[he.Symbol.Schema];this.usedTables.push(r===void 0?t[he.Symbol.Name]:r+"."+t[he.Symbol.Name])}}static[F]="SQL";decoder=HF;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return MF.startActiveSpan("drizzle.buildSQL",(t)=>{let r=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":r.sql,"drizzle.query.params":JSON.stringify(r.params)}),r})}buildQueryFromSourceParams(e,t){let r=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{casing:o,escapeName:n,escapeParam:i,prepareTyping:s,inlineParams:a,paramStartIndex:l}=r;return Ome(e.map((u)=>{if(oe(u,Nt))return{sql:u.value.join(""),params:[]};if(oe(u,Jy))return{sql:n(u.value),params:[]};if(u===void 0)return{sql:"",params:[]};if(Array.isArray(u)){let d=[new Nt("(")];for(let[p,m]of u.entries())if(d.push(m),p<u.length-1)d.push(new Nt(", "));return d.push(new Nt(")")),this.buildQueryFromSourceParams(d,r)}if(oe(u,_e))return this.buildQueryFromSourceParams(u.queryChunks,{...r,inlineParams:a||u.shouldInlineParams});if(oe(u,he)){let d=u[he.Symbol.Schema],p=u[he.Symbol.Name];return{sql:d===void 0||u[Np]?n(p):n(d)+"."+n(p),params:[]}}if(oe(u,He)){let d=o.getColumnCasing(u);if(t.invokeSource==="indexes")return{sql:n(d),params:[]};let p=u.table[he.Symbol.Schema];return{sql:u.table[Np]||p===void 0?n(u.table[he.Symbol.Name])+"."+n(d):n(p)+"."+n(u.table[he.Symbol.Name])+"."+n(d),params:[]}}if(oe(u,on)){let d=u[pt].schema,p=u[pt].name;return{sql:d===void 0||u[pt].isAlias?n(p):n(d)+"."+n(p),params:[]}}if(oe(u,Ur)){if(oe(u.value,ts))return{sql:i(l.value++,u),params:[u],typings:["none"]};let d=u.value===null?null:u.encoder.mapToDriverValue(u.value);if(oe(d,_e))return this.buildQueryFromSourceParams([d],r);if(a)return{sql:this.mapInlineParam(d,r),params:[]};let p=["none"];if(s)p=[s(u.encoder)];return{sql:i(l.value++,d),params:[d],typings:p}}if(oe(u,ts))return{sql:i(l.value++,u),params:[u],typings:["none"]};if(oe(u,_e.Aliased)&&u.fieldAlias!==void 0)return{sql:n(u.fieldAlias),params:[]};if(oe(u,dt)){if(u._.isWith)return{sql:n(u._.alias),params:[]};return this.buildQueryFromSourceParams([new Nt("("),u._.sql,new Nt(") "),new Jy(u._.alias)],r)}if(LF(u)){if(u.schema)return{sql:n(u.schema)+"."+n(u.enumName),params:[]};return{sql:n(u.enumName),params:[]}}if(kT(u)){if(u.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([u.getSQL()],r);return this.buildQueryFromSourceParams([new Nt("("),u.getSQL(),new Nt(")")],r)}if(a)return{sql:this.mapInlineParam(u,r),params:[]};return{sql:i(l.value++,u),params:[u],typings:["none"]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return"null";if(typeof e==="number"||typeof e==="boolean")return e.toString();if(typeof e==="string")return t(e);if(typeof e==="object"){let r=e.toString();if(r==="[object Object]")return t(JSON.stringify(e));return t(r)}throw Error("Unexpected param value: "+e)}getSQL(){return this}as(e){if(e===void 0)return this;return new _e.Aliased(this,e)}mapWith(e){return this.decoder=typeof e==="function"?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}if(e){return e?this:void 0}};Jy=class Jy{constructor(e){this.value=e}static[F]="Name";brand;getSQL(){return new _e([this])}};HF={mapFromDriverValue:(e)=>e},VF={mapToDriverValue:(e)=>e},Pje={...HF,...VF};Ur=class Ur{constructor(e,t=VF){this.value=e,this.encoder=t}static[F]="Param";brand;getSQL(){return new _e([this])}};((e)=>{function t(){return new _e([])}e.empty=t;function r(l){return new _e(l)}e.fromList=r;function o(l){return new _e([new Nt(l)])}e.raw=o;function n(l,u){let d=[];for(let[p,m]of l.entries()){if(p>0&&u!==void 0)d.push(u);d.push(m)}return new _e(d)}e.join=n;function i(l){return new Jy(l)}e.identifier=i;function s(l){return new ts(l)}e.placeholder=s;function a(l,u){return new Ur(l,u)}e.param=a})(C||(C={}));((e)=>{class t{constructor(r,o){this.sql=r,this.fieldAlias=o}static[F]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new t(this.sql,this.fieldAlias)}}e.Aliased=t})(_e||(_e={}));ts=class ts{constructor(e){this.name=e}static[F]="Placeholder";getSQL(){return new _e([this])}};Cme=Symbol.for("drizzle:IsDrizzleView");on=class on{static[F]="View";[pt];[Cme]=!0;constructor({name:e,schema:t,selectedFields:r,query:o}){this[pt]={name:e,originalName:e,schema:t,selectedFields:r,query:o,isExisting:!o,isAlias:!1}}getSQL(){return new _e([this])}};He.prototype.getSQL=function(){return new _e([this])};he.prototype.getSQL=function(){return new _e([this])};dt.prototype.getSQL=function(){return new _e([this])}});function IT(e,t,r){let o={},n=e.reduce((i,{path:s,field:a},l)=>{let u;if(oe(a,He))u=a;else if(oe(a,_e))u=a.decoder;else if(oe(a,dt))u=a._.sql.decoder;else u=a.sql.decoder;let d=i;for(let[p,m]of s.entries())if(p<s.length-1){if(!(m in d))d[m]={};d=d[m]}else{let h=t[l],b=d[m]=h===null?null:u.mapFromDriverValue(h);if(r&&oe(a,He)&&s.length===2){let y=s[0];if(!(y in o))o[y]=b===null?es(a.table):!1;else if(typeof o[y]==="string"&&o[y]!==es(a.table))o[y]=!1}}return i},{});if(r&&Object.keys(o).length>0){for(let[i,s]of Object.entries(o))if(typeof s==="string"&&!r[s])n[i]=null}return n}function sn(e,t){return Object.entries(e).reduce((r,[o,n])=>{if(typeof o!=="string")return r;let i=t?[...t,o]:[o];if(oe(n,He)||oe(n,_e)||oe(n,_e.Aliased)||oe(n,dt))r.push({path:i,field:n});else if(oe(n,he))r.push(...sn(n[he.Symbol.Columns],i));else r.push(...sn(n,i));return r},[])}function Lp(e,t){let r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return!1;for(let[n,i]of r.entries())if(i!==o[n])return!1;return!0}function Hy(e,t){let r=Object.entries(t).filter(([,o])=>o!==void 0).map(([o,n])=>{if(oe(n,_e)||oe(n,He))return[o,n];else return[o,new Ur(n,e[he.Symbol.Columns][o])]});if(r.length===0)throw Error("No values to set");return Object.fromEntries(r)}function WF(e,t){for(let r of t)for(let o of Object.getOwnPropertyNames(r.prototype)){if(o==="constructor")continue;Object.defineProperty(e.prototype,o,Object.getOwnPropertyDescriptor(r.prototype,o)||Object.create(null))}}function Vy(e){return e[he.Symbol.Columns]}function Bp(e){return oe(e,dt)?e._.alias:oe(e,on)?e[pt].name:oe(e,_e)?void 0:e[he.Symbol.IsAlias]?e[he.Symbol.Name]:e[he.Symbol.BaseName]}function ro(e,t){return{name:typeof e==="string"&&e.length>0?e:"",config:typeof e==="object"?e:t}}function GF(e){if(typeof e!=="object"||e===null)return!1;if(e.constructor.name!=="Object")return!1;if("logger"in e){let t=typeof e.logger;if(t!=="boolean"&&(t!=="object"||typeof e.logger.logQuery!=="function")&&t!=="undefined")return!1;return!0}if("schema"in e){let t=typeof e.schema;if(t!=="object"&&t!=="undefined")return!1;return!0}if("casing"in e){let t=typeof e.casing;if(t!=="string"&&t!=="undefined")return!1;return!0}if("mode"in e){if(e.mode!=="default"||e.mode!=="planetscale"||e.mode!==void 0)return!1;return!0}if("connection"in e){let t=typeof e.connection;if(t!=="string"&&t!=="object"&&t!=="undefined")return!1;return!0}if("client"in e){let t=typeof e.client;if(t!=="object"&&t!=="function"&&t!=="undefined")return!1;return!0}if(Object.keys(e).length===0)return!0;return!1}var AT;var Sr=v(()=>{_n();$e();Qt();En();sr();Uo();AT=typeof TextDecoder>"u"?null:new TextDecoder});var QF,RT,TT;var Wy=v(()=>{$e();QF=class QF{static[F]="ConsoleLogWriter";write(e){console.log(e)}};RT=class RT{static[F]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new QF}logQuery(e,t){let r=t.map((n)=>{try{return JSON.stringify(n)}catch{return String(n)}}),o=r.length?` -- params: [${r.join(", ")}]`:"";this.writer.write(`Query: ${e}${o}`)}};TT=class TT{static[F]="NoopLogger";logQuery(){}}});var YF,XF,$T;var e3=v(()=>{$e();sr();YF=Symbol.for("drizzle:PgInlineForeignKeys"),XF=Symbol.for("drizzle:EnableRLS");$T=class $T extends he{static[F]="PgTable";static Symbol=Object.assign({},he.Symbol,{InlineForeignKeys:YF,EnableRLS:XF});[YF]=[];[XF]=!1;[he.Symbol.ExtraConfigBuilder]=void 0;[he.Symbol.ExtraConfigColumns]={}}});var OT,t3;var r3=v(()=>{$e();e3();OT=class OT{static[F]="PgPrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new t3(e,this.columns,this.name)}};t3=class t3{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[F]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[$T.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function Tr(e,t){if(JF(t)&&!kT(e)&&!oe(e,Ur)&&!oe(e,ts)&&!oe(e,He)&&!oe(e,he)&&!oe(e,on))return new Ur(e,t);return e}function tt(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new _e(t);return new _e([new Nt("("),C.join(t,new Nt(" and ")),new Nt(")")])}function an(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new _e(t);return new _e([new Nt("("),C.join(t,new Nt(" or ")),new Nt(")")])}function o3(e){return C`not ${e}`}function ns(e,t){if(Array.isArray(t)){if(t.length===0)return C`false`;return C`${e} in ${t.map((r)=>Tr(r,e))}`}return C`${e} in ${Tr(t,e)}`}function Gy(e,t){if(Array.isArray(t)){if(t.length===0)return C`true`;return C`${e} not in ${t.map((r)=>Tr(r,e))}`}return C`${e} not in ${Tr(t,e)}`}function Mr(e){return C`${e} is null`}function a3(e){return C`${e} is not null`}function Qy(e){return C`exists ${e}`}function os(e){return C`not exists ${e}`}function c3(e,t,r){return C`${e} between ${Tr(t,e)} and ${Tr(r,e)}`}function l3(e,t,r){return C`${e} not between ${Tr(t,e)} and ${Tr(r,e)}`}function u3(e,t){return C`${e} like ${t}`}function d3(e,t){return C`${e} not like ${t}`}function p3(e,t){return C`${e} ilike ${t}`}function f3(e,t){return C`${e} not ilike ${t}`}var je=(e,t)=>C`${e} = ${Tr(t,e)}`,n3=(e,t)=>C`${e} <> ${Tr(t,e)}`,kn=(e,t)=>C`${e} > ${Tr(t,e)}`,i3=(e,t)=>C`${e} >= ${Tr(t,e)}`,s3=(e,t)=>C`${e} < ${Tr(t,e)}`,rs=(e,t)=>C`${e} <= ${Tr(t,e)}`;var m3=v(()=>{_n();$e();sr();Qt()});function Mo(e){return C`${e} asc`}function ga(e){return C`${e} desc`}var h3=v(()=>{Qt()});var CT=v(()=>{m3();h3()});function y3(){return{and:tt,between:c3,eq:je,exists:Qy,gt:kn,gte:i3,ilike:p3,inArray:ns,isNull:Mr,isNotNull:a3,like:u3,lt:s3,lte:rs,ne:n3,not:o3,notBetween:l3,notExists:os,notLike:d3,notIlike:f3,notInArray:Gy,or:an,sql:C}}function b3(){return{sql:C,asc:Mo,desc:ga}}function S3(e,t){if(Object.keys(e).length===1&&"default"in e&&!oe(e.default,he))e=e.default;let r={},o={},n={};for(let[i,s]of Object.entries(e))if(oe(s,he)){let a=ha(s),l=o[a];r[a]=i,n[i]={tsName:i,dbName:s[he.Symbol.Name],schema:s[he.Symbol.Schema],columns:s[he.Symbol.Columns],relations:l?.relations??{},primaryKey:l?.primaryKey??[]};for(let d of Object.values(s[he.Symbol.Columns]))if(d.primary)n[i].primaryKey.push(d);let u=s[he.Symbol.ExtraConfigBuilder]?.(s[he.Symbol.ExtraConfigColumns]);if(u){for(let d of Object.values(u))if(oe(d,OT))n[i].primaryKey.push(...d.columns)}}else if(oe(s,g3)){let a=ha(s.table),l=r[a],u=s.config(t(s.table)),d;for(let[p,m]of Object.entries(u))if(l){let h=n[l];if(h.relations[p]=m,d)h.primaryKey.push(...d)}else{if(!(a in o))o[a]={relations:{},primaryKey:d};o[a].relations[p]=m}}return{tables:n,tableNamesMap:r}}function Pme(e){return function(r,o){return new is(e,r,o,o?.fields.reduce((n,i)=>n&&i.notNull,!0)??!1)}}function zme(e){return function(r,o){return new jp(e,r,o)}}function v3(e,t,r){if(oe(r,is)&&r.config)return{fields:r.config.fields,references:r.config.references};let o=t[ha(r.referencedTable)];if(!o)throw Error(`Table "${r.referencedTable[he.Symbol.Name]}" not found in schema`);let n=e[o];if(!n)throw Error(`Table "${o}" not found in schema`);let i=r.sourceTable,s=t[ha(i)];if(!s)throw Error(`Table "${i[he.Symbol.Name]}" not found in schema`);let a=[];for(let l of Object.values(n.relations))if(r.relationName&&r!==l&&l.relationName===r.relationName||!r.relationName&&l.referencedTable===r.sourceTable)a.push(l);if(a.length>1)throw r.relationName?Error(`There are multiple relations with name "${r.relationName}" in table "${o}"`):Error(`There are multiple relations between "${o}" and "${r.sourceTable[he.Symbol.Name]}". Please specify relation name`);if(a[0]&&oe(a[0],is)&&a[0].config)return{fields:a[0].config.references,references:a[0].config.fields};throw Error(`There is not enough information to infer relation "${s}.${r.fieldName}"`)}function w3(e){return{one:Pme(e),many:zme(e)}}function Yy(e,t,r,o,n=(i)=>i){let i={};for(let[s,a]of o.entries())if(a.isJson){let l=t.relations[a.tsKey],u=r[s],d=typeof u==="string"?JSON.parse(u):u;i[a.tsKey]=oe(l,is)?d&&Yy(e,e[a.relationTableTsKey],d,a.selection,n):d.map((p)=>Yy(e,e[a.relationTableTsKey],p,a.selection,n))}else{let l=n(r[s]),u=a.field,d;if(oe(u,He))d=u;else if(oe(u,_e))d=u.decoder;else d=u.sql.decoder;i[a.tsKey]=l===null?null:d.mapFromDriverValue(l)}return i}var PT,g3,is,jp;var Zp=v(()=>{sr();_n();$e();r3();CT();Qt();PT=class PT{constructor(e,t,r){this.sourceTable=e,this.referencedTable=t,this.relationName=r,this.referencedTableName=t[he.Symbol.Name]}static[F]="Relation";referencedTableName;fieldName};g3=class g3{constructor(e,t){this.table=e,this.config=t}static[F]="Relations"};is=class is extends PT{constructor(e,t,r,o){super(e,t,r?.relationName);this.config=r,this.isNullable=o}static[F]="One";withFieldName(e){let t=new is(this.sourceTable,this.referencedTable,this.config,this.isNullable);return t.fieldName=e,t}};jp=class jp extends PT{constructor(e,t,r){super(e,t,r?.relationName);this.config=r}static[F]="Many";withFieldName(e){let t=new jp(this.sourceTable,this.referencedTable,this.config);return t.fieldName=e,t}}});function Up(e,t){return new Proxy(e,new ya(t,!1))}function no(e,t){return new Proxy(e,new $l(new Proxy(e.table,new ya(t,!1))))}function zT(e,t){return new _e.Aliased(Mp(e.sql,t),e.fieldAlias)}function Mp(e,t){return C.join(e.queryChunks.map((r)=>{if(oe(r,He))return no(r,t);if(oe(r,_e))return Mp(r,t);if(oe(r,_e.Aliased))return zT(r,t);return r}))}var $l,ya,Nme;var qp=v(()=>{_n();$e();Qt();sr();Uo();$l=class $l{constructor(e){this.table=e}static[F]="ColumnAliasProxyHandler";get(e,t){if(t==="table")return this.table;return e[t]}};ya=class ya{constructor(e,t){this.alias=e,this.replaceOriginalName=t}static[F]="TableAliasProxyHandler";get(e,t){if(t===he.Symbol.IsAlias)return!0;if(t===he.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===he.Symbol.OriginalName)return this.alias;if(t===pt)return{...e[pt],name:this.alias,isAlias:!0};if(t===he.Symbol.Columns){let o=e[he.Symbol.Columns];if(!o)return o;let n={};return Object.keys(o).map((i)=>{n[i]=new Proxy(o[i],new $l(new Proxy(e,this)))}),n}let r=e[t];if(oe(r,He))return new Proxy(r,new $l(new Proxy(e,this)));return r}};Nme=class Nme{constructor(e){this.alias=e}static[F]="RelationTableAliasProxyHandler";get(e,t){if(t==="sourceTable")return Up(e.sourceTable,this.alias);return e[t]}}});var at;var ba=v(()=>{qp();_n();$e();Qt();En();Uo();at=class at{static[F]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t==="_")return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(t===pt)return{...e[pt],selectedFields:new Proxy(e[pt].selectedFields,this)};if(typeof t==="symbol")return e[t];let o=(oe(e,dt)?e._.selectedFields:oe(e,on)?e[pt].selectedFields:e)[t];if(oe(o,_e.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!o.isSelectionField)return o.sql;let n=o.clone();return n.isSelectionField=!0,n}if(oe(o,_e)){if(this.config.sqlBehavior==="sql")return o;throw Error(`You tried to reference "${t}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(oe(o,He)){if(this.config.alias)return new Proxy(o,new $l(new Proxy(o.table,new ya(this.config.alias,this.config.replaceOriginalName??!1))));return o}if(typeof o!=="object"||o===null)return o;return new Proxy(o,new at(this.config))}}});var vr;var qo=v(()=>{$e();vr=class vr{static[F]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then((t)=>(e?.(),t),(t)=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}}});var NT,x3;var DT=v(()=>{$e();Rl();NT=class NT{static[F]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(e,t){if(this.reference=()=>{let{name:r,columns:o,foreignColumns:n}=e();return{name:r,columns:o,foreignTable:n[0].table,foreignColumns:n}},t)this._onUpdate=t.onUpdate,this._onDelete=t.onDelete}onUpdate(e){return this._onUpdate=e,this}onDelete(e){return this._onDelete=e,this}build(e){return new x3(e,this)}};x3=class x3{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[F]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),o=t.map((s)=>s.name),n=r.map((s)=>s.name),i=[this.table[ir],...o,r[0].table[ir],...n];return e??`${i.join("_")}_fk`}}});function LT(e,t){return`${e[ir]}_${t.join("_")}_unique`}var _3,Dme,E3;var BT=v(()=>{$e();Rl();_3=class _3{constructor(e,t){this.name=t,this.columns=e}static[F]="SQLiteUniqueConstraintBuilder";columns;build(e){return new E3(e,this.columns,this.name)}};Dme=class Dme{static[F]="SQLiteUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new _3(e,this.name)}};E3=class E3{constructor(e,t,r){this.table=e,this.columns=t,this.name=r??LT(this.table,this.columns.map((o)=>o.name))}static[F]="SQLiteUniqueConstraint";columns;name;getName(){return this.name}}});var Zt,yt;var ss=v(()=>{My();_n();$e();DT();BT();Zt=class Zt extends Cp{static[F]="SQLiteColumnBuilder";foreignKeyConfigs=[];references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e){return this.config.isUnique=!0,this.config.uniqueName=e,this}generatedAlwaysAs(e,t){return this.config.generated={as:e,type:"always",mode:t?.mode??"virtual"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:r,actions:o})=>((n,i)=>{let s=new NT(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(i.onUpdate)s.onUpdate(i.onUpdate);if(i.onDelete)s.onDelete(i.onDelete);return s.build(t)})(r,o))}};yt=class yt extends He{constructor(e,t){if(!t.uniqueName)t.uniqueName=LT(e,[t.name]);super(e,t);this.table=e}static[F]="SQLiteColumn"}});function O3(e,t){let{name:r,config:o}=ro(e,t);if(o?.mode==="json")return new A3(r);if(o?.mode==="bigint")return new k3(r);return new T3(r)}var k3,I3,A3,R3,T3,$3;var jT=v(()=>{$e();Sr();ss();k3=class k3 extends Zt{static[F]="SQLiteBigIntBuilder";constructor(e){super(e,"bigint","SQLiteBigInt")}build(e){return new I3(e,this.config)}};I3=class I3 extends yt{static[F]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){let t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return BigInt(t.toString("utf8"))}return BigInt(AT.decode(e))}mapToDriverValue(e){return Buffer.from(e.toString())}};A3=class A3 extends Zt{static[F]="SQLiteBlobJsonBuilder";constructor(e){super(e,"json","SQLiteBlobJson")}build(e){return new R3(e,this.config)}};R3=class R3 extends yt{static[F]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){let t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return JSON.parse(t.toString("utf8"))}return JSON.parse(AT.decode(e))}mapToDriverValue(e){return Buffer.from(JSON.stringify(e))}};T3=class T3 extends Zt{static[F]="SQLiteBlobBufferBuilder";constructor(e){super(e,"buffer","SQLiteBlobBuffer")}build(e){return new $3(e,this.config)}};$3=class $3 extends yt{static[F]="SQLiteBlobBuffer";mapFromDriverValue(e){if(Buffer.isBuffer(e))return e;return Buffer.from(e)}getSQLType(){return"blob"}}});function z3(e){return(t,r)=>{let{name:o,config:n}=ro(t,r);return new C3(o,n,e)}}var C3,P3;var ZT=v(()=>{$e();Sr();ss();C3=class C3 extends Zt{static[F]="SQLiteCustomColumnBuilder";constructor(e,t,r){super(e,"custom","SQLiteCustomColumn");this.config.fieldConfig=t,this.config.customTypeParams=r}build(e){return new P3(e,this.config)}};P3=class P3 extends yt{static[F]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;constructor(e,t){super(e,t);this.sqlName=t.customTypeParams.dataType(t.fieldConfig),this.mapTo=t.customTypeParams.toDriver,this.mapFrom=t.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(e){return typeof this.mapFrom==="function"?this.mapFrom(e):e}mapToDriverValue(e){return typeof this.mapTo==="function"?this.mapTo(e):e}}});function ar(e,t){let{name:r,config:o}=ro(e,t);if(o?.mode==="timestamp"||o?.mode==="timestamp_ms")return new L3(r,o.mode);if(o?.mode==="boolean")return new j3(r,o.mode);return new N3(r)}var Xy,eb,N3,D3,L3,B3,j3,Z3;var UT=v(()=>{$e();Qt();Sr();ss();Xy=class Xy extends Zt{static[F]="SQLiteBaseIntegerBuilder";constructor(e,t,r){super(e,t,r);this.config.autoIncrement=!1}primaryKey(e){if(e?.autoIncrement)this.config.autoIncrement=!0;return this.config.hasDefault=!0,super.primaryKey()}};eb=class eb extends yt{static[F]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}};N3=class N3 extends Xy{static[F]="SQLiteIntegerBuilder";constructor(e){super(e,"number","SQLiteInteger")}build(e){return new D3(e,this.config)}};D3=class D3 extends eb{static[F]="SQLiteInteger"};L3=class L3 extends Xy{static[F]="SQLiteTimestampBuilder";constructor(e,t){super(e,"date","SQLiteTimestamp");this.config.mode=t}defaultNow(){return this.default(C`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new B3(e,this.config)}};B3=class B3 extends eb{static[F]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue(e){if(this.config.mode==="timestamp")return new Date(e*1000);return new Date(e)}mapToDriverValue(e){let t=e.getTime();if(this.config.mode==="timestamp")return Math.floor(t/1000);return t}};j3=class j3 extends Xy{static[F]="SQLiteBooleanBuilder";constructor(e,t){super(e,"boolean","SQLiteBoolean");this.config.mode=t}build(e){return new Z3(e,this.config)}};Z3=class Z3 extends eb{static[F]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue(e){return Number(e)===1}mapToDriverValue(e){return e?1:0}}});function H3(e,t){let{name:r,config:o}=ro(e,t),n=o?.mode;return n==="number"?new q3(r):n==="bigint"?new K3(r):new U3(r)}var U3,M3,q3,F3,K3,J3;var MT=v(()=>{$e();Sr();ss();U3=class U3 extends Zt{static[F]="SQLiteNumericBuilder";constructor(e){super(e,"string","SQLiteNumeric")}build(e){return new M3(e,this.config)}};M3=class M3 extends yt{static[F]="SQLiteNumeric";mapFromDriverValue(e){if(typeof e==="string")return e;return String(e)}getSQLType(){return"numeric"}};q3=class q3 extends Zt{static[F]="SQLiteNumericNumberBuilder";constructor(e){super(e,"number","SQLiteNumericNumber")}build(e){return new F3(e,this.config)}};F3=class F3 extends yt{static[F]="SQLiteNumericNumber";mapFromDriverValue(e){if(typeof e==="number")return e;return Number(e)}mapToDriverValue=String;getSQLType(){return"numeric"}};K3=class K3 extends Zt{static[F]="SQLiteNumericBigIntBuilder";constructor(e){super(e,"bigint","SQLiteNumericBigInt")}build(e){return new J3(e,this.config)}};J3=class J3 extends yt{static[F]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}});function G3(e){return new V3(e??"")}var V3,W3;var qT=v(()=>{$e();ss();V3=class V3 extends Zt{static[F]="SQLiteRealBuilder";constructor(e){super(e,"number","SQLiteReal")}build(e){return new W3(e,this.config)}};W3=class W3 extends yt{static[F]="SQLiteReal";getSQLType(){return"real"}}});function ft(e,t={}){let{name:r,config:o}=ro(e,t);if(o.mode==="json")return new X3(r);return new Q3(r,o)}var Q3,Y3,X3,e5;var FT=v(()=>{$e();Sr();ss();Q3=class Q3 extends Zt{static[F]="SQLiteTextBuilder";constructor(e,t){super(e,"string","SQLiteText");this.config.enumValues=t.enum,this.config.length=t.length}build(e){return new Y3(e,this.config)}};Y3=class Y3 extends yt{static[F]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor(e,t){super(e,t)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}};X3=class X3 extends Zt{static[F]="SQLiteTextJsonBuilder";constructor(e){super(e,"json","SQLiteTextJson")}build(e){return new e5(e,this.config)}};e5=class e5 extends yt{static[F]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue(e){return JSON.parse(e)}mapToDriverValue(e){return JSON.stringify(e)}}});function t5(){return{blob:O3,customType:z3,integer:ar,numeric:H3,real:G3,text:ft}}var r5=v(()=>{jT();ZT();UT();MT();qT();FT()});function Lme(e,t,r,o,n=e){let i=new At(e,o,n),s=typeof t==="function"?t(t5()):t,a=Object.fromEntries(Object.entries(s).map(([u,d])=>{let p=d;p.setName(u);let m=p.build(i);return i[KT].push(...p.buildForeignKeys(m,i)),[u,m]})),l=Object.assign(i,a);if(l[he.Symbol.Columns]=a,l[he.Symbol.ExtraConfigColumns]=a,r)l[At.Symbol.ExtraConfigBuilder]=r;return l}var KT,At,Fp=(e,t,r)=>Lme(e,t,r);var Fo=v(()=>{$e();sr();r5();KT=Symbol.for("drizzle:SQLiteInlineForeignKeys");At=class At extends he{static[F]="SQLiteTable";static Symbol=Object.assign({},he.Symbol,{InlineForeignKeys:KT});[he.Symbol.Columns];[KT]=[];[he.Symbol.ExtraConfigBuilder]=void 0}});var Bme,n5;var o5=v(()=>{$e();Bme=class Bme{constructor(e,t){this.name=e,this.value=t}static[F]="SQLiteCheckBuilder";brand;build(e){return new n5(e,this)}};n5=class n5{constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}static[F]="SQLiteCheck";name;value}});function Ko(e){return new i5(e,!1)}var i5,s5,a5;var c5=v(()=>{$e();i5=class i5{constructor(e,t){this.name=e,this.unique=t}static[F]="SQLiteIndexBuilderOn";on(...e){return new s5(this.name,e,this.unique)}};s5=class s5{static[F]="SQLiteIndexBuilder";config;constructor(e,t,r){this.config={name:e,columns:t,unique:r,where:void 0}}where(e){return this.config.where=e,this}build(e){return new a5(this.config,e)}};a5=class a5{static[F]="SQLiteIndex";config;constructor(e,t){this.config={...e,table:t}}}});var jme,l5;var u5=v(()=>{$e();Fo();jme=class jme{static[F]="SQLitePrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new l5(e,this.columns,this.name)}};l5=class l5{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[F]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[At.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function In(e){if(oe(e,At))return[`${e[he.Symbol.BaseName]}`];if(oe(e,dt))return e._.usedTables??[];if(oe(e,_e))return e.usedTables??[];return[]}var Ol=v(()=>{$e();Qt();En();sr();Fo()});var tb;var d5=v(()=>{$e();qo();ba();Fo();sr();Sr();Ol();tb=class tb extends vr{constructor(e,t,r,o){super();this.table=e,this.session=t,this.dialect=r,this.config={table:e,withList:o}}static[F]="SQLiteDelete";config;where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.table[he.Symbol.Columns],new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];this.config.orderBy=r}else{let t=e;this.config.orderBy=t}return this}limit(e){return this.config.limit=e,this}returning(e=this.table[At.Symbol.Columns]){return this.config.returning=sn(e),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"delete",tables:In(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(e){return this._prepare().execute(e)}$dynamic(){return this}}});function Zme(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((r)=>r.toLowerCase()).join("_")}function Ume(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((r,o,n)=>{let i=n===0?o.toLowerCase():`${o[0].toUpperCase()}${o.slice(1)}`;return r+i},"")}function Mme(e){return e}var JT;var p5=v(()=>{$e();sr();JT=class JT{static[F]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert=e==="snake_case"?Zme:e==="camelCase"?Ume:Mme}getColumnCasing(e){if(!e.keyAsName)return e.name;let t=e.table[he.Symbol.Schema]??"public",r=e.table[he.Symbol.OriginalName],o=`${t}.${r}.${e.name}`;if(!this.cache[o])this.cacheTable(e.table);return this.cache[o]}cacheTable(e){let t=e[he.Symbol.Schema]??"public",r=e[he.Symbol.OriginalName],o=`${t}.${r}`;if(!this.cachedTables[o]){for(let n of Object.values(e[he.Symbol.Columns])){let i=`${o}.${n.name}`;this.cache[i]=this.convert(n.name)}this.cachedTables[o]=!0}}clearCache(){this.cache={},this.cachedTables={}}}});var Cl,Jo,HT;var rb=v(()=>{$e();Cl=class Cl extends Error{static[F]="DrizzleError";constructor({message:e,cause:t}){super(e);this.name="DrizzleError",this.cause=t}};Jo=class Jo extends Error{constructor(e,t,r){super(`Failed query: ${e}
|
|
414
414
|
params: ${t}`);if(this.query=e,this.params=t,this.cause=r,Error.captureStackTrace(this,Jo),r)this.cause=r}};HT=class HT extends Cl{static[F]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}});var f5=()=>{};var m5=()=>{};var h5=v(()=>{f5();m5()});var VT=v(()=>{CT();h5();Qt()});var WT=v(()=>{jT();ss();ZT();UT();MT();qT();FT()});var Ho;var Kp=v(()=>{$e();Qt();Ho=class Ho extends on{static[F]="SQLiteViewBase"}});var Pl,GT,QT;var nb=v(()=>{qp();p5();_n();$e();rb();Zp();VT();Qt();WT();Fo();En();sr();Sr();Uo();Kp();Pl=class Pl{static[F]="SQLiteDialect";casing;constructor(e){this.casing=new JT(e?.casing)}escapeName(e){return`"${e.replace(/"/g,'""')}"`}escapeParam(e){return"?"}escapeString(e){return`'${e.replace(/'/g,"''")}'`}buildWithCTE(e){if(!e?.length)return;let t=[C`with `];for(let[r,o]of e.entries())if(t.push(C`${C.identifier(o._.alias)} as (${o._.sql})`),r<e.length-1)t.push(C`, `);return t.push(C` `),C.join(t)}buildDeleteQuery({table:e,where:t,returning:r,withList:o,limit:n,orderBy:i}){let s=this.buildWithCTE(o),a=r?C` returning ${this.buildSelection(r,{isSingleTable:!0})}`:void 0,l=t?C` where ${t}`:void 0,u=this.buildOrderBy(i),d=this.buildLimit(n);return C`${s}delete from ${e}${l}${a}${u}${d}`}buildUpdateSet(e,t){let r=e[he.Symbol.Columns],o=Object.keys(r).filter((i)=>t[i]!==void 0||r[i]?.onUpdateFn!==void 0),n=o.length;return C.join(o.flatMap((i,s)=>{let a=r[i],l=a.onUpdateFn?.(),u=t[i]??(oe(l,_e)?l:C.param(l,a)),d=C`${C.identifier(this.casing.getColumnCasing(a))} = ${u}`;if(s<n-1)return[d,C.raw(", ")];return[d]}))}buildUpdateQuery({table:e,set:t,where:r,returning:o,withList:n,joins:i,from:s,limit:a,orderBy:l}){let u=this.buildWithCTE(n),d=this.buildUpdateSet(e,t),p=s&&C.join([C.raw(" from "),this.buildFromTable(s)]),m=this.buildJoins(i),h=o?C` returning ${this.buildSelection(o,{isSingleTable:!0})}`:void 0,b=r?C` where ${r}`:void 0,y=this.buildOrderBy(l),S=this.buildLimit(a);return C`${u}update ${e} set ${d}${p}${m}${b}${h}${y}${S}`}buildSelection(e,{isSingleTable:t=!1}={}){let r=e.length,o=e.flatMap(({field:n},i)=>{let s=[];if(oe(n,_e.Aliased)&&n.isSelectionField)s.push(C.identifier(n.fieldAlias));else if(oe(n,_e.Aliased)||oe(n,_e)){let a=oe(n,_e.Aliased)?n.sql:n;if(t)s.push(new _e(a.queryChunks.map((l)=>{if(oe(l,He))return C.identifier(this.casing.getColumnCasing(l));return l})));else s.push(a);if(oe(n,_e.Aliased))s.push(C` as ${C.identifier(n.fieldAlias)}`)}else if(oe(n,He)){let a=n.table[he.Symbol.Name];if(n.columnType==="SQLiteNumericBigInt")if(t)s.push(C`cast(${C.identifier(this.casing.getColumnCasing(n))} as text)`);else s.push(C`cast(${C.identifier(a)}.${C.identifier(this.casing.getColumnCasing(n))} as text)`);else if(t)s.push(C.identifier(this.casing.getColumnCasing(n)));else s.push(C`${C.identifier(a)}.${C.identifier(this.casing.getColumnCasing(n))}`)}else if(oe(n,dt)){let a=Object.entries(n._.selectedFields);if(a.length===1){let l=a[0][1],u=oe(l,_e)?l.decoder:oe(l,He)?{mapFromDriverValue:(d)=>l.mapFromDriverValue(d)}:l.sql.decoder;if(u)n._.sql.decoder=u}s.push(n)}if(i<r-1)s.push(C`, `);return s});return C.join(o)}buildJoins(e){if(!e||e.length===0)return;let t=[];if(e)for(let[r,o]of e.entries()){if(r===0)t.push(C` `);let n=o.table,i=o.on?C` on ${o.on}`:void 0;if(oe(n,At)){let s=n[At.Symbol.Name],a=n[At.Symbol.Schema],l=n[At.Symbol.OriginalName],u=s===l?void 0:o.alias;t.push(C`${C.raw(o.joinType)} join ${a?C`${C.identifier(a)}.`:void 0}${C.identifier(l)}${u&&C` ${C.identifier(u)}`}${i}`)}else t.push(C`${C.raw(o.joinType)} join ${n}${i}`);if(r<e.length-1)t.push(C` `)}return C.join(t)}buildLimit(e){return typeof e==="object"||typeof e==="number"&&e>=0?C` limit ${e}`:void 0}buildOrderBy(e){let t=[];if(e){for(let[r,o]of e.entries())if(t.push(o),r<e.length-1)t.push(C`, `)}return t.length>0?C` order by ${C.join(t)}`:void 0}buildFromTable(e){if(oe(e,he)&&e[he.Symbol.IsAlias])return C`${C`${C.identifier(e[he.Symbol.Schema]??"")}.`.if(e[he.Symbol.Schema])}${C.identifier(e[he.Symbol.OriginalName])} ${C.identifier(e[he.Symbol.Name])}`;return e}buildSelectQuery({withList:e,fields:t,fieldsFlat:r,where:o,having:n,table:i,joins:s,orderBy:a,groupBy:l,limit:u,offset:d,distinct:p,setOperators:m}){let h=r??sn(t);for(let T of h)if(oe(T.field,He)&&es(T.field.table)!==(oe(i,dt)?i._.alias:oe(i,Ho)?i[pt].name:oe(i,_e)?void 0:es(i))&&!((B)=>s?.some(({alias:k})=>k===(B[he.Symbol.IsAlias]?es(B):B[he.Symbol.BaseName])))(T.field.table)){let B=es(T.field.table);throw Error(`Your "${T.path.join("->")}" field references a column "${B}"."${T.field.name}", but the table "${B}" is not part of the query! Did you forget to join it?`)}let b=!s||s.length===0,y=this.buildWithCTE(e),S=p?C` distinct`:void 0,x=this.buildSelection(h,{isSingleTable:b}),_=this.buildFromTable(i),A=this.buildJoins(s),O=o?C` where ${o}`:void 0,L=n?C` having ${n}`:void 0,z=[];if(l){for(let[T,B]of l.entries())if(z.push(B),T<l.length-1)z.push(C`, `)}let J=z.length>0?C` group by ${C.join(z)}`:void 0,P=this.buildOrderBy(a),W=this.buildLimit(u),ee=d?C` offset ${d}`:void 0,j=C`${y}select${S} ${x} from ${_}${A}${O}${J}${L}${P}${W}${ee}`;if(m.length>0)return this.buildSetOperations(j,m);return j}buildSetOperations(e,t){let[r,...o]=t;if(!r)throw Error("Cannot pass undefined values to any set operator");if(o.length===0)return this.buildSetOperationQuery({leftSelect:e,setOperator:r});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:e,setOperator:r}),o)}buildSetOperationQuery({leftSelect:e,setOperator:{type:t,isAll:r,rightSelect:o,limit:n,orderBy:i,offset:s}}){let a=C`${e.getSQL()} `,l=C`${o.getSQL()}`,u;if(i&&i.length>0){let h=[];for(let b of i)if(oe(b,yt))h.push(C.identifier(b.name));else if(oe(b,_e)){for(let y=0;y<b.queryChunks.length;y++){let S=b.queryChunks[y];if(oe(S,yt))b.queryChunks[y]=C.identifier(this.casing.getColumnCasing(S))}h.push(C`${b}`)}else h.push(C`${b}`);u=C` order by ${C.join(h,C`, `)}`}let d=typeof n==="object"||typeof n==="number"&&n>=0?C` limit ${n}`:void 0,p=C.raw(`${t} ${r?"all ":""}`),m=s?C` offset ${s}`:void 0;return C`${a}${p}${l}${u}${d}${m}`}buildInsertQuery({table:e,values:t,onConflict:r,returning:o,withList:n,select:i}){let s=[],a=e[he.Symbol.Columns],l=Object.entries(a).filter(([b,y])=>!y.shouldDisableInsert()),u=l.map(([,b])=>C.identifier(this.casing.getColumnCasing(b)));if(i){let b=t;if(oe(b,_e))s.push(b);else s.push(b.getSQL())}else{let b=t;s.push(C.raw("values "));for(let[y,S]of b.entries()){let x=[];for(let[_,A]of l){let O=S[_];if(O===void 0||oe(O,Ur)&&O.value===void 0){let L;if(A.default!==null&&A.default!==void 0)L=oe(A.default,_e)?A.default:C.param(A.default,A);else if(A.defaultFn!==void 0){let z=A.defaultFn();L=oe(z,_e)?z:C.param(z,A)}else if(!A.default&&A.onUpdateFn!==void 0){let z=A.onUpdateFn();L=oe(z,_e)?z:C.param(z,A)}else L=C`null`;x.push(L)}else x.push(O)}if(s.push(x),y<b.length-1)s.push(C`, `)}}let d=this.buildWithCTE(n),p=C.join(s),m=o?C` returning ${this.buildSelection(o,{isSingleTable:!0})}`:void 0,h=r?.length?C.join(r):void 0;return C`${d}insert into ${e} ${u} ${p}${h}${m}`}sqlToQuery(e,t){return e.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,invokeSource:t})}buildRelationalQuery({fullSchema:e,schema:t,tableNamesMap:r,table:o,tableConfig:n,queryConfig:i,tableAlias:s,nestedQueryRelation:a,joinOn:l}){let u=[],d,p,m=[],h,b=[];if(i===!0)u=Object.entries(n.columns).map(([x,_])=>({dbKey:_.name,tsKey:x,field:no(_,s),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let S=Object.fromEntries(Object.entries(n.columns).map(([z,J])=>[z,no(J,s)]));if(i.where){let z=typeof i.where==="function"?i.where(S,y3()):i.where;h=z&&Mp(z,s)}let x=[],_=[];if(i.columns){let z=!1;for(let[J,P]of Object.entries(i.columns)){if(P===void 0)continue;if(J in n.columns){if(!z&&P===!0)z=!0;_.push(J)}}if(_.length>0)_=z?_.filter((J)=>i.columns?.[J]===!0):Object.keys(n.columns).filter((J)=>!_.includes(J))}else _=Object.keys(n.columns);for(let z of _){let J=n.columns[z];x.push({tsKey:z,value:J})}let A=[];if(i.with)A=Object.entries(i.with).filter((z)=>!!z[1]).map(([z,J])=>({tsKey:z,queryConfig:J,relation:n.relations[z]}));let O;if(i.extras){O=typeof i.extras==="function"?i.extras(S,{sql:C}):i.extras;for(let[z,J]of Object.entries(O))x.push({tsKey:z,value:zT(J,s)})}for(let{tsKey:z,value:J}of x)u.push({dbKey:oe(J,_e.Aliased)?J.fieldAlias:n.columns[z].name,tsKey:z,field:oe(J,He)?no(J,s):J,relationTableTsKey:void 0,isJson:!1,selection:[]});let L=typeof i.orderBy==="function"?i.orderBy(S,b3()):i.orderBy??[];if(!Array.isArray(L))L=[L];m=L.map((z)=>{if(oe(z,He))return no(z,s);return Mp(z,s)}),d=i.limit,p=i.offset;for(let{tsKey:z,queryConfig:J,relation:P}of A){let W=v3(t,r,P),ee=ha(P.referencedTable),j=r[ee],T=`${s}_${z}`,B=tt(...W.fields.map((I,q)=>je(no(W.references[q],T),no(I,s)))),k=this.buildRelationalQuery({fullSchema:e,schema:t,tableNamesMap:r,table:e[j],tableConfig:t[j],queryConfig:oe(P,is)?J===!0?{limit:1}:{...J,limit:1}:J,tableAlias:T,joinOn:B,nestedQueryRelation:P}),R=C`(${k.sql})`.as(z);u.push({dbKey:z,tsKey:z,field:R,relationTableTsKey:j,isJson:!0,selection:k.selection})}}if(u.length===0)throw new Cl({message:`No fields selected for table "${n.tsName}" ("${s}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.`});let y;if(h=tt(l,h),a){let S=C`json_array(${C.join(u.map(({field:A})=>oe(A,yt)?C.identifier(this.casing.getColumnCasing(A)):oe(A,_e.Aliased)?A.sql:A),C`, `)})`;if(oe(a,jp))S=C`coalesce(json_group_array(${S}), json_array())`;let x=[{dbKey:"data",tsKey:"data",field:S.as("data"),isJson:!0,relationTableTsKey:n.tsName,selection:u}];if(d!==void 0||p!==void 0||m.length>0)y=this.buildSelectQuery({table:Up(o,s),fields:{},fieldsFlat:[{path:[],field:C.raw("*")}],where:h,limit:d,offset:p,orderBy:m,setOperators:[]}),h=void 0,d=void 0,p=void 0,m=void 0;else y=Up(o,s);y=this.buildSelectQuery({table:oe(y,At)?y:new dt(y,{},s),fields:{},fieldsFlat:x.map(({field:A})=>({path:[],field:oe(A,He)?no(A,s):A})),joins:b,where:h,limit:d,offset:p,orderBy:m,setOperators:[]})}else y=this.buildSelectQuery({table:Up(o,s),fields:{},fieldsFlat:u.map(({field:S})=>({path:[],field:oe(S,He)?no(S,s):S})),joins:b,where:h,limit:d,offset:p,orderBy:m,setOperators:[]});return{tableTsKey:n.tsName,sql:y,selection:u}}};GT=class GT extends Pl{static[F]="SQLiteSyncDialect";migrate(e,t,r){let o=r===void 0?"__drizzle_migrations":typeof r==="string"?"__drizzle_migrations":r.migrationsTable??"__drizzle_migrations",n=C`
|
|
415
415
|
CREATE TABLE IF NOT EXISTS ${C.identifier(o)} (
|
|
416
416
|
id SERIAL PRIMARY KEY,
|
|
@@ -737,7 +737,7 @@ printf 'REMOTE_ARTIFACT_DIR=%s\\n' "$remote_dir"
|
|
|
737
737
|
`).replace(/\\n/g,`
|
|
738
738
|
`).trimEnd()}
|
|
739
739
|
`}var D8,sge;var V$=v(async()=>{pe();C8();hn();Yp();await O8();D8=c.object({HCLOUD_TOKEN:c.string().min(1),KAMAL_SSH_PRIVATE_KEY:c.string().min(1)}),sge=c.object({servers:c.array(c.object({status:c.string(),public_net:c.object({ipv4:c.object({ip:c.string().min(1)})})}))})});import{parseArgs as EK}from"util";function nt(e){return e}class nf extends Error{constructor(e){super(e);this.name="CliUsageError"}}function kK(e,t){let r={...t};for(let o of e)for(let[n,i]of Object.entries(o.flags??{})){let s=r[n];if(s===void 0){r[n]=i;continue}if(s.type!==i.type||s.short!==i.short||s.default!==i.default)throw Error(`Conflicting definitions for flag --${n}: commands must agree on type, short, and default`)}return r}function IK(e){let t={};for(let[r,o]of Object.entries(e))t[r]={type:o.type,...o.short!==void 0?{short:o.short}:{},...o.default!==void 0?{default:o.default}:{}};return t}function AK(e){if(!(e instanceof Error)||!("code"in e))return!1;return e.code==="ERR_PARSE_ARGS_UNKNOWN_OPTION"||e.code==="ERR_PARSE_ARGS_INVALID_OPTION_VALUE"}function Q$(e,t){let r=kK(t.commands,t.globalFlags??{}),o,n;try{({values:o,positionals:n}=EK({args:e,options:IK(r),allowPositionals:!0,strict:t.strict??!0}))}catch(s){if(AK(s))throw new nf(s.message.split(". ")[0]??s.message);throw s}if("help"in r&&o.help===!0)return{command:"help",args:[],flags:{help:!0}};if("version"in r&&o.version===!0)return{command:"version",args:[],flags:{version:!0}};let i={};for(let[s,a]of Object.entries(r)){let l=o[s];if(typeof l==="string"&&a.type==="string")i[s]=l;else if(typeof l==="boolean"&&a.type==="boolean")i[s]=l}return{command:n[0]??"help",args:n.slice(1),flags:i}}function Y$(e){let t=e.reduce((r,o)=>Math.max(r,o.label.length),0);return e.map((r)=>` ${r.label.padEnd(t)} ${r.description}`)}function RK(e){return Y$(e.map((t)=>({label:t.usage?`${t.name} ${t.usage}`:t.name,description:t.description})))}function TK(e,t){let r=t.type==="string"?` ${t.placeholder??"<value>"}`:"",o=t.short!==void 0?`, -${t.short}`:"";return`--${e}${r}${o}`}function X$(e){return Y$(Object.entries(e).map(([t,r])=>({label:TK(t,r),description:r.description})))}function eO(e,t){return`Usage: ${e} ${t.name}${t.usage?` ${t.usage}`:""}`}function $K(e){return JSON.stringify(Object.entries(e).map(([t,r])=>[t,r.type,r.short??"",r.description,r.placeholder??"",r.default??""]).sort((t,r)=>String(t[0]).localeCompare(String(r[0]))))}function OK(e){let t=[],r=new Map;for(let n of e){let i=n.flags??{};if(Object.keys(i).length===0)continue;let s=$K(i),a=r.get(s);if(a){a.names.push(n.name);continue}let l={names:[n.name],flags:i};r.set(s,l),t.push(l)}let o=[];for(let n of t)o.push("",`${n.names.join(" / ")} options:`),o.push(...X$(n.flags));return o}function tO(e){let t=[e.intro,"",`Usage: ${e.cliName} ${e.usage??"<command> [args]"}`,"","Commands:",...RK(e.commands)];if(e.globalFlags&&Object.keys(e.globalFlags).length>0)t.push("","Options:",...X$(e.globalFlags));return t.push(...OK(e.commands)),t.join(`
|
|
740
|
-
`)}function rO(e){let t=new Map;for(let r of e){if(t.has(r.name))throw Error(`Duplicate command name: ${r.name}`);t.set(r.name,r)}return t}function ot(e,t){let r=e[t];return typeof r==="string"?r:void 0}function ds(e,t){let r=e[t];return typeof r==="boolean"?r:void 0}var of={name:"@rizom/ops",version:"0.2.0-alpha.
|
|
740
|
+
`)}function rO(e){let t=new Map;for(let r of e){if(t.has(r.name))throw Error(`Duplicate command name: ${r.name}`);t.set(r.name,r)}return t}function ot(e,t){let r=e[t];return typeof r==="string"?r:void 0}function ds(e,t){let r=e[t];return typeof r==="boolean"?r:void 0}var of={name:"@rizom/ops",version:"0.2.0-alpha.730",description:"Operator CLI for managing private brain fleet registry repos",keywords:["brains","ops","cli","deploy","fleet","operator"],license:"AGPL-3.0-only",author:"Yeehaa <yeehaa@rizom.ai> (https://rizom.ai)",bin:{"brains-ops":"./dist/brains-ops.js"},bugs:"https://github.com/rizom-ai/brains/issues",dependencies:{"@libsql/client":"^0.17.4","age-encryption":"^0.3.0",yaml:"^2.9.0"},devDependencies:{"@brains/contracts":"workspace:*","@brains/deploy-support":"workspace:*","@brains/eslint-config":"workspace:*","@brains/job-queue":"workspace:*","@brains/profile":"workspace:*","@brains/site-composition":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@brains/utils":"workspace:*","@types/bun":"^1.4.0",typescript:"^7.0.2"},engines:{bun:">=1.3.3"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./deploy":{types:"./dist/deploy.d.ts",import:"./dist/deploy.js",bun:"./dist/deploy.js"}},files:["dist","templates"],homepage:"https://github.com/rizom-ai/brains/tree/main/packages/brains-ops#readme",main:"./dist/index.js",publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/rizom-ai/brains.git",directory:"packages/brains-ops"},scripts:{build:"bun scripts/build.ts",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",prepublishOnly:"bun scripts/build.ts",test:"bun test --timeout 20000","test:smoke":"bun run build && RUN_SMOKE_TESTS=1 bun test --timeout 60000",typecheck:"tsc --noEmit"},type:"module",types:"./dist/index.d.ts"};kv();Si();import{writeFile as MY}from"fs/promises";import{join as lj}from"path";import{createSign as SW,generateKeyPairSync as vW}from"crypto";import{mkdir as wW,writeFile as rD}from"fs/promises";import{join as nD}from"path";async function TV(e){let t=await e.text();if(!t.trim())return;try{return JSON.parse(t)}catch{return t}}async function Wa(e,t,r){let o=await TV(e),n=t.safeParse(o);if(!e.ok||!n.success){let i=r.formatError??$V;throw Error(`${r.label}${i(e,o)}`)}return n.data}function $V(e,t){let r=t===void 0?"":`: ${typeof t==="string"?t:JSON.stringify(t)}`;return` (${e.status} ${e.statusText}${r})`}pe();var xW="2.5.4.3",_W="1.2.840.113549.1.1.11",sD="https://api.cloudflare.com/client/v4",EW="origin-rsa",kW=5475,aD=15000;function cD(e){return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}var oD=c.looseObject({message:c.string().optional()}),IW=c.looseObject({errors:c.array(oD).optional(),messages:c.array(oD).optional()}),AW=c.looseObject({certificate:c.string().min(1),expires_on:c.string().optional()}),RW=c.looseObject({success:c.literal(!0),result:AW}),TW=c.looseObject({success:c.literal(!0)});function $W(){let{privateKey:e,publicKey:t}=vW("rsa",{modulusLength:2048,privateKeyEncoding:{type:"pkcs8",format:"pem"},publicKeyEncoding:{type:"spki",format:"der"}});return{privateKeyPem:e,publicKeyDer:Buffer.from(t)}}function OW(e,t){let r=bd(BW(bd(iD(xW),NW(e)))),o=bd(zW(0),r,Buffer.from(t.publicKeyDer),jW(0,Buffer.alloc(0))),n=SW("sha256").update(o).sign(t.privateKeyPem),i=bd(o,bd(iD(_W),LW()),DW(n));return{csrPem:PW("CERTIFICATE REQUEST",i),certificationRequestInfoDer:o,signature:n}}async function CW(e,t,r,o){let n=await e(`${sD}/certificates`,{method:"POST",headers:cD(t),body:JSON.stringify({hostnames:[o,`*.${o}`],requested_validity:kW,request_type:EW,csr:r}),signal:AbortSignal.timeout(aD)}),i=await Wa(n,RW,{label:"Cloudflare Origin CA request failed",formatError:uD}),a={certificatePem:`${i.result.certificate.trim()}
|
|
741
741
|
`};if(i.result.expires_on)a.expiresOn=i.result.expires_on;return a}async function lD(e,t,r){let o=await e(`${sD}/zones/${r}/settings/ssl`,{method:"PATCH",headers:cD(t),body:JSON.stringify({value:"strict"}),signal:AbortSignal.timeout(aD)});await Wa(o,TW,{label:"Cloudflare zone SSL update failed",formatError:uD})}function PW(e,t){let o=t.toString("base64").match(/.{1,64}/g)??[];return[`-----BEGIN ${e}-----`,...o,`-----END ${e}-----`,""].join(`
|
|
742
742
|
`)}function zW(e){if(e!==0)throw Error("Only zero-valued INTEGER encoding is currently supported");return Buffer.from([2,1,0])}function iD(e){let t=e.split(".").map((s)=>Number(s));if(t.length<2||t.some((s)=>Number.isNaN(s)))throw Error(`Invalid OID: ${e}`);let r=t[0],o=t[1];if(r===void 0||o===void 0)throw Error(`Invalid OID: ${e}`);let i=[r*40+o];for(let s of t.slice(2)){let a=UW(s);i.push(...a)}return Ac(6,Buffer.from(i))}function NW(e){return Ac(12,Buffer.from(e,"utf8"))}function DW(e){return Ac(3,Buffer.concat([Buffer.from([0]),e]))}function LW(){return Buffer.from([5,0])}function bd(...e){return Ac(48,Buffer.concat(e))}function BW(...e){return Ac(49,Buffer.concat(e))}function jW(e,t){return Ac(160+e,t)}function Ac(e,t){return Buffer.concat([Buffer.from([e]),ZW(t.length),t])}function ZW(e){if(e<128)return Buffer.from([e]);let t=[],r=e;while(r>0)t.unshift(r&255),r>>=8;return Buffer.from([128|t.length,...t])}function UW(e){if(!Number.isInteger(e)||e<0)throw Error(`Invalid OID component: ${e}`);if(e===0)return[0];let t=[],r=e;while(r>0)t.unshift(r&127),r>>=7;for(let o=0;o<t.length-1;o+=1)t[o]=(t[o]??0)|128;return t}function uD(e,t){let r=MW(t),o=r.length>0?`: ${r.join("; ")}`:"";return` (${e.status} ${e.statusText}${o})`}function MW(e){let t=IW.safeParse(e);if(!t.success)return[];return[...t.data.errors??[],...t.data.messages??[]].map((r)=>r.message).filter((r)=>typeof r==="string"&&r.length>0)}async function dD(e,t,r){let o=$W(),{csrPem:n}=OW(r,o),i=await CW(e,t,n,r);return{certificatePem:i.certificatePem,privateKeyPem:o.privateKeyPem,...i.expiresOn!==void 0&&{expiresOn:i.expiresOn}}}async function pD(e,t){let r=nD(e,"origin.pem"),o=nD(e,"origin.key");return await wW(e,{recursive:!0}),await Promise.all([rD(r,t.certificatePem,"utf-8"),rD(o,t.privateKeyPem,{encoding:"utf-8",mode:384})]),{certificatePath:r,privateKeyPath:o}}hn();Tu();Un();async function dj(e,t={}){try{return await qY(e,t),{success:!0}}catch(r){return{success:!1,message:Ve(r,"Certificate bootstrap failed")}}}async function qY(e,t={}){let r=await wt(e),o=KY(r,t.handle),n=o.domain,i=t.env??process.env,s=Dr(e),a=t.cfApiToken??jt("CF_API_TOKEN",i,s),l=t.cfZoneId??o.cloudflareZoneId??jt("CF_ZONE_ID",i,s);if(!a)throw Error("Missing CF_API_TOKEN");if(!l)throw Error("Missing CF_ZONE_ID");let u=t.fetchImpl??fetch,d=t.logger??console.log,p=await dD(u,a,n),m=lj(e,".brains-ops","certs",o.id),{certificatePath:h,privateKeyPath:b}=await pD(m,p),y=lj(m,"secrets.yaml");await MY(y,FY(p.certificatePem,p.privateKeyPem),"utf-8"),await lD(u,a,l);let S=Ha(t.pushTo);if(S)await yi([["CERTIFICATE_PEM",p.certificatePem],["PRIVATE_KEY_PEM",p.privateKeyPem]],{logger:d,runCommand:t.runCommand??tr});if(d(`Issued ${o.id} Origin CA cert for ${n} and *.${n}`),d(`Wrote ${h}`),d(`Wrote ${b}`),d(`Wrote ${y}`),p.expiresOn)d(`Expires on ${p.expiresOn}`);if(d("Cloudflare zone SSL mode set to Full (strict)"),S)d(`Pushed CERTIFICATE_PEM and PRIVATE_KEY_PEM to ${S}`);return{domain:n,certificatePath:h,privateKeyPath:b,certificatePem:p.certificatePem,secretsSnippetPath:y}}function FY(e,t){return[`certificatePem: ${uj(e)}`,`privateKeyPem: ${uj(t)}`,""].join(`
|
|
743
743
|
`)}function uj(e){return`"${e.replace(/"/g,"\\\"").replace(/\n/g,"\\n")}"`}function KY(e,t){if(!t)return{id:"shared",domain:JY(e.pilot.domainSuffix)};let r=e.users.find((o)=>o.handle===t);if(!r)throw Error(`Unknown user handle: ${t}`);return{id:t,domain:r.domain,...r.cloudflareZoneId?{cloudflareZoneId:r.cloudflareZoneId}:{}}}function JY(e){let t=e.trim().replace(/^\./,"").replace(/\.$/,"");if(!t||t.includes("*"))throw Error(`Invalid pilot domainSuffix: ${e}`);return t}import{access as fj,chmod as NI,mkdir as rg,readFile as hj,writeFile as mj}from"fs/promises";import{dirname as QY,join as Dc}from"path";import{fileURLToPath as YY}from"url";Si();Rd();var XY=["pilot.yaml","package.json",".env.schema",".gitignore","cohorts/cohort-1.yaml","users/alice.yaml",".github/actions/varlock-env/action.yml",".github/workflows/build.yml",".github/workflows/deploy.yml",".github/workflows/directory-sync-stress.yml",".github/workflows/health-watchdog-smoke.yml",".github/workflows/offboard.yml",".github/workflows/reconcile.yml",".github/workflows/upgrade.yml","deploy/Dockerfile","deploy/kamal/deploy.yml","deploy/scripts/helpers.ts","deploy/scripts/create-predeploy-backup.ts","deploy/scripts/install-health-watchdog.ts","deploy/scripts/provision-server.ts","deploy/scripts/pull-local-models.ts","deploy/scripts/update-dns.ts","deploy/scripts/write-ssh-key.ts","deploy/scripts/decrypt-user-secrets.ts","deploy/scripts/validate-secrets.ts","deploy/scripts/write-kamal-secrets.ts","deploy/scripts/resolve-user-config.ts","deploy/scripts/resolve-missing-images.ts","deploy/scripts/verify-runtime-image.ts","deploy/scripts/resolve-deploy-handles.ts","deploy/scripts/sync-content-repo.ts",".kamal/hooks/pre-deploy","docs/onboarding-checklist.md","docs/canonical-crossover-record.md","docs/operator-playbook.md","docs/user-onboarding.md","README.md"],DI=new Set([".kamal/hooks/pre-deploy"]),eX=new Set(["cohorts/cohort-1.yaml","users/alice.yaml","docs/canonical-crossover-record.md"]),tX=YY(new URL("../templates/rover-pilot/",import.meta.url));function Ao(e){return(t)=>t.includes(e)}function rX(e){return FP.find((t)=>e===`deploy/scripts/${t}`)}function LI(e){return e.replace(/\n {2}secret:\n(?: {4}- .*\n)+\nvolumes:\n/,`
|