@rizom/ops 0.2.0-alpha.590 → 0.2.0-alpha.591
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 +5 -5
- package/dist/index.js +5 -5
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -405,7 +405,7 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
|
|
|
405
405
|
`)+1;while(t!==0)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
406
406
|
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=ty(e),r=Yc(t);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=ty(e),r=Yc(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){if(this.type!=="comment")return!1;if(this.indent<=t)return!1;return e.every((r)=>r.type==="newline"||r.type==="space")}*documentEnd(e){if(this.type!=="doc-mode"){if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}oue.Parser=qq});var Kq=Se(function(mue){var Zq=G1(),aue=zd(),Ud=Nd(),cue=s1(),lue=Ge(),uue=sT(),Mq=aT();function Fq(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new uue.LineCounter||null,prettyErrors:t}}function due(e,t={}){let{lineCounter:r,prettyErrors:i}=Fq(t),n=new Mq.Parser(r?.addNewLine),o=new Zq.Composer(t),s=Array.from(o.compose(n.parse(e)));if(i&&r)for(let a of s)a.errors.forEach(Ud.prettifyError(e,r)),a.warnings.forEach(Ud.prettifyError(e,r));if(s.length>0)return s;return Object.assign([],{empty:!0},o.streamInfo())}function Hq(e,t={}){let{lineCounter:r,prettyErrors:i}=Fq(t),n=new Mq.Parser(r?.addNewLine),o=new Zq.Composer(t),s=null;for(let a of o.compose(n.parse(e),!0,e.length))if(!s)s=a;else if(s.options.logLevel!=="silent"){s.errors.push(new Ud.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(i&&r)s.errors.forEach(Ud.prettifyError(e,r)),s.warnings.forEach(Ud.prettifyError(e,r));return s}function fue(e,t,r){let i=void 0;if(typeof t==="function")i=t;else if(r===void 0&&t&&typeof t==="object")r=t;let n=Hq(e,r);if(!n)return null;if(n.warnings.forEach((o)=>cue.warn(n.options.logLevel,o)),n.errors.length>0)if(n.options.logLevel!=="silent")throw n.errors[0];else n.errors=[];return n.toJS(Object.assign({reviver:i},r))}function pue(e,t,r){let i=null;if(typeof t==="function"||Array.isArray(t))i=t;else if(r===void 0&&t)r=t;if(typeof r==="string")r=r.length;if(typeof r==="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=r??t??{};if(!n)return}if(lue.isDocument(e)&&!i)return e.toString(r);return new aue.Document(e,i,r).toString(r)}mue.parse=fue;mue.parseAllDocuments=due;mue.parseDocument=Hq;mue.stringify=pue});var Sue,xue,wue,cT,vue,jo,_ue,kue,Eue,Iue,yBe,Tue,Aue,$ue,ny,Jq,Cue,Rue,Oue,Pue,zue,Nue,Due,Lue,Bue,jue,Pi,zi,Uue,Xc,lT,que,Zue,Mue,Fue,Hue,Kue,Jue,Vue,Wue,ii,Gue,Que,Yue;var qd=S(()=>{Sue=G1(),xue=zd(),wue=z1(),cT=Nd(),vue=xd(),jo=Ge(),_ue=zo(),kue=Nt(),Eue=Do(),Iue=Lo(),yBe=Xg(),Tue=oT(),Aue=sT(),$ue=aT(),ny=Kq(),Jq=bd();Cue=Sue.Composer,Rue=xue.Document,Oue=wue.Schema,Pue=cT.YAMLError,zue=cT.YAMLParseError,Nue=cT.YAMLWarning,Due=vue.Alias,Lue=jo.isAlias,Bue=jo.isCollection,jue=jo.isDocument,Pi=jo.isMap,zi=jo.isNode,Uue=jo.isPair,Xc=jo.isScalar,lT=jo.isSeq,que=_ue.Pair,Zue=kue.Scalar,Mue=Eue.YAMLMap,Fue=Iue.YAMLSeq,Hue=Tue.Lexer,Kue=Aue.LineCounter,Jue=$ue.Parser,Vue=ny.parse,Wue=ny.parseAllDocuments,ii=ny.parseDocument,Gue=ny.stringify,Que=Jq.visit,Yue=Jq.visitAsync});var Xq={};Ht(Xq,{assertPilotUsersRemoved:()=>dT,createPilotOffboardDriver:()=>uT,offboardPilotUsers:()=>Wq});import{access as Xue,readdir as ede,readFile as tde,rm as Zd,writeFile as rde}from"fs/promises";import{basename as nde,join as Ni}from"path";async function Wq(e,t){let r=[...new Set(t.handles.map((f)=>$r.parse(f)))].sort((f,p)=>f.localeCompare(p));if(r.length===0)throw Error("At least one pilot handle is required");let i=t.dryRun??!0,n=`sunset:${r.join(",")}`;if(!i&&t.confirmation!==n)throw Error(`Exact confirmation required: ${n}`);let o=t.env??process.env,s=t.logger??console.info,a=await xt(e),c=r.map((f)=>ide(a,f,o)),l=t.driver??uT({env:o,fetchImpl:t.fetchImpl,contentRepoTokenName:a.pilot.contentRepoAdminToken}),u=await Promise.all(c.map(async(f)=>({target:f,inspection:await l.inspect(f)})));if(sde(u),ade(u,i,s),!i){for(let f of u)if(!f.inspection.contentRepoArchived)await l.archiveContentRepo(f.target),s(`[${f.target.handle}] archived ${f.target.contentRepo}`);for(let f of u)for(let p of f.inspection.dnsRecords)await l.deleteDnsRecord(f.target,p),s(`[${f.target.handle}] deleted DNS ${p.name}`);for(let f of u)if(f.inspection.server)await l.deleteServer(f.target,f.inspection.server),s(`[${f.target.handle}] deleted ${f.target.instanceName}`);await ode(c,l,t.sleep??((f)=>new Promise((p)=>setTimeout(p,f)))),await cde(e,r),await Ai(e),await dT(e,r),s(`Removed desired state for ${r.length} pilot user(s)`)}return{dryRun:i,handles:r,confirmation:n,plans:u}}function ide(e,t,r){let i=e.users.find((u)=>u.handle===t),n=`${t}${e.pilot.domainSuffix}`,o=i?.domain??n,s=FI(o,{sharedDomain:e.pilot.domainSuffix}),a=i?.cloudflareZoneId??iy(r,"CF_ZONE_ID"),c=i?.contentRepo??`${e.pilot.contentRepoPrefix}${t}-content`,l=c.includes("/")?c:`${e.pilot.githubOrg}/${c}`;return{handle:t,instanceName:`rover-${t}`,domain:o,previewDomain:s,...o===n?{}:{wwwDomain:`www.${o}`},contentRepo:l,cloudflareZoneId:a}}async function ode(e,t,r){for(let i of e)for(let n=1;n<=20;n+=1){let o=await t.inspect(i);if(!o.server&&o.dnsRecords.length===0&&o.contentRepoArchived)break;if(n===20)throw Error(`[${i.handle}] provider cleanup did not converge`);await r(1500)}}function sde(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 i=new Set([t.domain,t.previewDomain,...t.wwwDomain?[t.wwwDomain]:[]]);for(let n of r.dnsRecords){if(!i.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:i})=>i.handle).join(", ")}`);for(let{target:i,inspection:n}of e){let o=n.server?`delete ${i.instanceName}`:"already absent",s=n.dnsRecords.length>0?n.dnsRecords.map((c)=>`${c.type} ${c.name}`).join(", "):"already absent",a=n.contentRepoArchived?"already archived":`archive ${i.contentRepo}`;r(`[${i.handle}] server: ${o}; DNS: ${s}; repo: ${a}`)}r("Runtime backups: none")}async function cde(e,t){let r=new Set(t),i=Ni(e,"cohorts");for(let n of(await ede(i)).filter((o)=>o.endsWith(".yaml"))){let o=Ni(i,n),s=await tde(o,"utf8"),a=ii(s);if(a.errors.length>0)throw Error(`${n}: ${a.errors[0]?.message??"invalid YAML"}`);let c=a.get("members",!0);if(!lT(c))throw Error(`${n}: members must be a sequence`);let l=c.items.filter((u)=>!Xc(u)||typeof u.value!=="string"||!r.has(u.value));if(l.length===c.items.length)continue;if(l.length===0){await Zd(o);continue}c.items=l,ln.parse(a.toJS()),await rde(o,a.toString())}for(let n of t)await Promise.all([Zd(Ni(e,"users",`${n}.yaml`),{force:!0}),Zd(Ni(e,"users",`${n}.secrets.yaml`),{force:!0}),Zd(Ni(e,"users",`${n}.secrets.yaml.age`),{force:!0}),Zd(Ni(e,"users",n),{recursive:!0,force:!0})])}function uT(e){let t=e.fetchImpl??fetch,r=iy(e.env,"HCLOUD_TOKEN"),i=iy(e.env,"CF_API_TOKEN"),n=iy(e.env,e.contentRepoTokenName);return{async inspect(o){let[s,a,c]=await Promise.all([lde(t,r,o.instanceName),Promise.all([o.domain,o.previewDomain,...o.wwwDomain?[o.wwwDomain]:[]].map((l)=>ude(t,i,o.cloudflareZoneId,l))).then((l)=>l.flat()),dde(t,n,o.contentRepo)]);if(s.length>1)throw Error(`[${o.handle}] expected at most one server, found ${s.length}`);return{...s[0]?{server:s[0]}:{},dnsRecords:a,contentRepoArchived:c.archived}},async archiveContentRepo(o){await el(t,`https://api.github.com/repos/${o.contentRepo}`,{method:"PATCH",headers:Gq(n),body:JSON.stringify({archived:!0})},"GitHub repository archive")},async deleteDnsRecord(o,s){if(tl(await el(t,`https://api.cloudflare.com/client/v4/zones/${o.cloudflareZoneId}/dns_records/${s.id}`,{method:"DELETE",headers:Qq(i)},"Cloudflare DNS delete")).success!==!0)throw Error(`Cloudflare DNS delete failed for ${s.name}`)},async deleteServer(o,s){await el(t,`https://api.hetzner.cloud/v1/servers/${s.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}},"Hetzner server delete",!0)}}}async function lde(e,t,r){let i=new URL("https://api.hetzner.cloud/v1/servers");i.searchParams.set("label_selector",`brain=${r}`);let o=tl(await el(e,i.toString(),{headers:{Authorization:`Bearer ${t}`}},"Hetzner server lookup")).servers;if(!Array.isArray(o))throw Error("Hetzner server lookup returned an invalid payload");return o.map((s)=>{let a=tl(s),c=Vq(a.public_net),l=Vq(c?.ipv4);return{id:fde(a.id,"Hetzner server id"),name:Md(a.name,"Hetzner server name"),...typeof l?.ip==="string"?{ip:l.ip}:{}}})}async function ude(e,t,r,i){let n=new URL(`https://api.cloudflare.com/client/v4/zones/${r}/dns_records`);n.searchParams.set("name",i);let o=tl(await el(e,n.toString(),{headers:Qq(t)},"Cloudflare DNS lookup")),s=o.result;if(o.success!==!0||!Array.isArray(s))throw Error(`Cloudflare DNS lookup failed for ${i}`);return s.map((a)=>{let c=tl(a),l=Md(c.type,"Cloudflare record type");if(l!=="A"&&l!=="CNAME")throw Error(`Unsupported Cloudflare record type ${l} for ${i}`);return{id:Md(c.id,"Cloudflare record id"),name:Md(c.name,"Cloudflare record name"),type:l,content:Md(c.content,"Cloudflare record content")}})}async function dde(e,t,r){let i=tl(await el(e,`https://api.github.com/repos/${r}`,{headers:Gq(t)},"GitHub repository lookup"));if(typeof i.archived!=="boolean")throw Error(`Invalid repository archive state for ${r}`);return{archived:i.archived}}async function el(e,t,r,i,n=!1){let o=await e(t,r),s=await o.text();if(!o.ok)throw Error(`${i} failed (${o.status}): ${s}`);if(!s&&n)return{};try{return JSON.parse(s)}catch{throw Error(`${i} returned an invalid JSON response`)}}function Gq(e){return{Accept:"application/vnd.github+json",Authorization:`Bearer ${e}`,"Content-Type":"application/json","X-GitHub-Api-Version":"2022-11-28"}}function Qq(e){return{Authorization:`Bearer ${e}`}}function iy(e,t){let r=e[t];if(!r)throw Error(`Missing required environment variable: ${t}`);return r}function Yq(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function tl(e){if(!Yq(e))throw Error("Provider returned an unexpected payload");return e}function Vq(e){return Yq(e)?e:void 0}function Md(e,t){if(typeof e!=="string"||e.length===0)throw Error(`Missing ${t}`);return e}function fde(e,t){if(typeof e!=="number")throw Error(`Missing ${t}`);return e}async function pde(e){try{return await Xue(e),!0}catch{return!1}}async function dT(e,t){for(let r of t)for(let i of[Ni(e,"users",`${r}.yaml`),Ni(e,"users",`${r}.secrets.yaml.age`),Ni(e,"users",r)])if(await pde(i))throw Error(`Offboarded user state remains: ${nde(i)}`)}var fT=S(()=>{qd();un();HI();Ec();Xn()});var QF={};Ht(QF,{upgradePilotRepo:()=>The});import{readFile as _he}from"fs/promises";import{join as khe}from"path";async function GF(e){let t=khe(e,"package.json"),i=Ehe.parse(JSON.parse(await _he(t,"utf8"))).devDependencies?.["@rizom/ops"];if(!i)throw Error(`${t} does not pin @rizom/ops as a devDependency`);return i}async function Ihe(e,t){let i=await Bun.spawn(e,{cwd:t,stdout:"inherit",stderr:"inherit"}).exited;if(i!==0)throw Error(`${e.join(" ")} failed with exit ${i}`)}async function The(e,t={}){let r=t.exec??Ihe,i=await GF(e),n=t.version??"latest";await r(["bun","add","--dev","--exact",`@rizom/ops@${n}`],e);let o=await GF(e);return await r(["bun","x","brains-ops","init","."],e),{from:i,to:o}}var Ehe;var YF=S(()=>{Ae();Ehe=d.object({devDependencies:d.record(d.string(),d.string()).optional()})});function XF(e){if(e===null||typeof e!=="object"||Array.isArray(e))return!1;let t=Ahe(e);return t===Object.prototype||t===null}var Ahe;var e3=S(()=>{Ahe=Object.getPrototypeOf});function i3(e){if(e==="core")return{bundles:["core","media","web","chat"]};if(e==="default")return{bundles:["core","media","automation","web","chat","site","publishing","federation"],add:["obsidian-vault"],remove:[...Rhe]};return{bundles:["core","media","automation","web","chat","site","publishing","federation"],add:["obsidian-vault"]}}function Ohe(e){let t=$he.parse(e);return _o.parse({brainVersion:t.brainVersion,bundleContract:vo,...i3(t.preset),githubOrg:t.githubOrg,contentRepoPrefix:t.contentRepoPrefix,domainSuffix:t.domainSuffix,aiApiKey:t.aiApiKey,gitSyncToken:t.gitSyncToken,contentRepoAdminToken:t.contentRepoAdminToken,agePublicKey:t.agePublicKey})}function Phe(e){let t=Che.parse(e),r=t.presetOverride?i3(t.presetOverride):void 0;return ln.parse({members:[...t.members],...t.brainVersionOverride?{brainVersionOverride:t.brainVersionOverride}:{},...r?{bundlesOverride:r.bundles,...r.add?{addOverride:r.add}:{},...r.remove?{removeOverride:r.remove}:{}}:{},...t.aiApiKeyOverride?{aiApiKeyOverride:t.aiApiKeyOverride}:{},...t.gitSyncTokenOverride?{gitSyncTokenOverride:t.gitSyncTokenOverride}:{}})}function o3(e){let t=ii(e,{keepSourceTokens:!0});if(t.errors.length>0)throw Error(`Invalid desired-state YAML: ${t.errors[0]?.message}`);if(!Pi(t.contents))throw Error("Desired-state YAML must contain a mapping");return t}function f$(e,t){if(!Pi(e.contents))return;return e.contents.items.find((r)=>Xc(r.key)&&r.key.value===t)}function t3(e,t){if(!zi(e)||!zi(t))return;if(e.commentBefore!==void 0)t.commentBefore=e.commentBefore;if(e.comment!==void 0)t.comment=e.comment;if(e.spaceBefore!==void 0)t.spaceBefore=e.spaceBefore}function r3(e,t){if(!e||!zi(t))return;let r=[zi(e.key)?e.key.commentBefore:void 0,zi(e.key)?e.key.comment:void 0,zi(e.value)?e.value.commentBefore:void 0,zi(e.value)?e.value.comment:void 0].filter((i)=>i!==void 0);if(r.length===0)return;t.commentBefore=[t.commentBefore,...r].filter((i)=>i!==void 0).join(`
|
|
407
407
|
`)}function s3(e,t,r,i){if(!Pi(e.contents))throw Error("Desired-state YAML must contain a mapping");let n=e.contents.items.findIndex((s)=>Xc(s.key)&&s.key.value===t),o=e.createPair(r,[...i]);if(n>=0){let s=e.contents.items[n];t3(s?.key,o.key),t3(s?.value,o.value),e.contents.items.splice(n,1,o)}else e.contents.add(o);return o}function a3(e){let t=o3(e),r=Ohe(t.toJS()),i=f$(t,"schemaVersion"),n=f$(t,"model");r3(i,f$(t,"brainVersion")?.key),t.delete("schemaVersion"),t.set("bundleContract",vo);let o=s3(t,"preset","bundles",r.bundles);if(r3(n,o.key),t.delete("model"),r.add)t.set("add",r.add);else t.delete("add");if(r.remove)t.set("remove",r.remove);else t.delete("remove");return _o.parse(t.toJS()),t.toString({lineWidth:0})}function c3(e){let t=o3(e),r=Phe(t.toJS());if(r.bundlesOverride)s3(t,"presetOverride","bundlesOverride",r.bundlesOverride);else t.delete("presetOverride"),t.delete("bundlesOverride");if(r.addOverride)t.set("addOverride",r.addOverride);else t.delete("addOverride");if(r.removeOverride)t.set("removeOverride",r.removeOverride);else t.delete("removeOverride");return ln.parse(t.toJS()),t.toString({lineWidth:0})}var n3,Cf,$he,Che,Rhe;var l3=S(()=>{ki();Ae();qd();Xn();n3=d.enum(["core","default","pro"]),Cf=d.string().min(1),$he=d.strictObject({schemaVersion:d.literal(1),brainVersion:jt,model:d.literal("rover"),githubOrg:d.string().min(1),contentRepoPrefix:d.string().min(1),domainSuffix:d.string().min(1),preset:n3,aiApiKey:Cf,gitSyncToken:Cf,contentRepoAdminToken:Cf,agePublicKey:d.string().startsWith("age1").min(1)}),Che=d.strictObject({members:d.array($r).min(1),brainVersionOverride:jt.optional(),presetOverride:n3.optional(),aiApiKeyOverride:Cf.optional(),gitSyncTokenOverride:Cf.optional()}).superRefine((e,t)=>{if(new Set(e.members).size!==e.members.length)t.addIssue({code:d.ZodIssueCode.custom,path:["members"],message:"cohort members must be unique"})}),Rhe=["series","portfolio","content-pipeline","social-media","newsletter","stock-photo"]});function d3(e,t){let r=ii(e,{keepSourceTokens:!0});if(r.errors.length>0||!Pi(r.contents))throw Error(`Invalid ${t} YAML`);return r}function Bhe(e,t){return e.length===t.length&&e.every((r,i)=>r===t[i])}function f3(e,t,r){if(!Bhe(t,r.sourceBundles))throw Error(`${e} source bundles changed after review: expected [${r.sourceBundles.join(", ")}], received [${t.join(", ")}]`)}function p3(e){let t=An(e,Lhe);if(!t.ok)throw Error(`Invalid capability bundle review: ${t.error}`);return t.data}function m3(e,t){let r=d3(e,"pilot desired-state"),i=Nhe.parse(r.toJS());return f3("pilot.yaml",i.bundles,t),r.set("bundleContract",vo),r.set("bundles",t.targetBundles),_o.parse(r.toJS()),r.toString({lineWidth:0})}function h3(e,t,r){let i=d3(e,`cohort ${t}`),n=Dhe.parse(i.toJS());if(n.bundlesOverride===void 0){if(r!==void 0)throw Error(`Capability bundle review names inheriting cohort ${t}`)}else{if(r===void 0)throw Error(`Cohort ${t} has an explicit legacy bundle selection but no reviewed mapping`);f3(`cohort ${t}`,n.bundlesOverride,r),i.set("bundlesOverride",r.targetBundles)}return ln.parse(i.toJS()),i.toString({lineWidth:0})}var zhe,p$,ib,Nhe,Dhe,u3,Lhe;var g3=S(()=>{ki();Ae();qd();Xn();zhe=d.enum(["core","site","publishing","team"]),p$=d.array(zhe).min(1),ib=d.array(d.string().min(1)),Nhe=d.strictObject({brainVersion:jt,bundles:p$,add:ib.optional(),remove:ib.optional(),githubOrg:d.string().min(1),contentRepoPrefix:d.string().min(1),domainSuffix:d.string().min(1),aiApiKey:d.string().min(1),gitSyncToken:d.string().min(1),contentRepoAdminToken:d.string().min(1),agePublicKey:d.string().startsWith("age1").min(1)}),Dhe=d.strictObject({members:d.array($r).min(1),brainVersionOverride:jt.optional(),bundlesOverride:p$.optional(),addOverride:ib.optional(),removeOverride:ib.optional(),aiApiKeyOverride:d.string().min(1).optional(),gitSyncTokenOverride:d.string().min(1).optional()}),u3=d.strictObject({sourceBundles:p$,targetBundles:d.array(yh).min(1)}),Lhe=d.strictObject({bundleContract:d.literal(vo),pilot:u3,cohorts:d.record($r,u3)})});var w3={};Ht(w3,{loadCapabilityBundleReview:()=>Jhe,loadReviewedSitePins:()=>Khe,parseReviewedSitePins:()=>x3,stageLegacyCrossover:()=>Whe});import{access as jhe,cp as Uhe,mkdir as y3,readFile as Al,readdir as S3,writeFile as Tl}from"fs/promises";import{basename as qhe,join as mi,relative as ob,resolve as b3}from"path";import{fileURLToPath as Zhe}from"url";function x3(e){let t=An(e,Mhe);if(!t.ok)throw Error(`Invalid reviewed site pins: ${t.error}`);return t.data.sites}async function Khe(e){return x3(await Al(e,"utf8"))}async function Jhe(e){return p3(await Al(e,"utf8"))}async function Vhe(e,t){let r=mi(e,"users"),i=(await S3(r,{withFileTypes:!0})).filter((s)=>s.isFile()&&/\.ya?ml$/.test(s.name)).map((s)=>s.name).sort(),n=new Set(Object.keys(t??{})),o=[];for(let s of i){let a=mi(r,s),c=await Al(a,"utf8"),l=ii(c,{keepSourceTokens:!0});if(l.errors.length>0||!Pi(l.contents))throw Error(`Invalid user desired-state YAML: ${s}`);let u=Fhe.parse(l.toJS());if(!u.siteOverride)continue;let f=t?.[u.handle];if(!f)throw Error(`User ${u.handle} has a siteOverride but no reviewed site pin`);if(n.delete(u.handle),f.package!==u.siteOverride.package||f.theme!==u.siteOverride.theme)throw Error(`Reviewed site pin identity does not match user ${u.handle}`);if(u.siteOverride.version!==void 0&&u.siteOverride.version!==f.version)throw Error(`Reviewed site version does not match the existing pin for user ${u.handle}`);if(u.siteOverride.themeVersion!==void 0&&u.siteOverride.themeVersion!==f.themeVersion)throw Error(`Reviewed theme version does not match the existing pin for user ${u.handle}`);if(l.setIn(["siteOverride","version"],f.version),f.themeVersion!==void 0)l.setIn(["siteOverride","themeVersion"],f.themeVersion);else l.deleteIn(["siteOverride","themeVersion"]);bh.parse(l.toJS());let p=l.toString({lineWidth:0});if(p!==c)await Tl(a,p),o.push(ob(e,a))}if(n.size>0)throw Error(`Reviewed site pins do not match site users: ${[...n].sort().join(", ")}`);return o}async function Whe(e,t,r={}){let i=b3(e),n=b3(t);if(i===n||n.startsWith(`${i}/`))throw Error("Crossover output must be outside the source repository");await Uhe(i,n,{recursive:!0,errorOnExist:!0,force:!1,filter:(A)=>{let z=qhe(A);return z!==".git"&&z!==".operator"&&z!==".brains-ops"&&z!==".turbo"&&z!=="dist"&&z!=="node_modules"&&z!==".env"&&z!==".env.local"&&!z.endsWith(".secrets.yaml")}});let o=[],s=mi(n,"docs","canonical-crossover-record.md");try{await jhe(s)}catch{await y3(mi(n,"docs"),{recursive:!0}),await Tl(s,await Al(Hhe,"utf8")),o.push("docs/canonical-crossover-record.md")}let a=mi(n,"pilot.yaml"),c=await Al(a,"utf8"),u=ii(c).toJS();if(!XF(u))throw Error(`${a} is not a YAML mapping`);let f=Array.isArray(u.bundles),p=r.bundleReview,m;if(f){if(!p)throw Error("Current canonical desired state requires an explicit capability bundle review manifest");m=m3(c,p.pilot)}else m=a3(c);await Tl(a,m),o.push("pilot.yaml");let y=mi(n,"cohorts"),g=(await S3(y,{withFileTypes:!0})).filter((A)=>A.isFile()&&/\.ya?ml$/.test(A.name)).map((A)=>A.name).sort(),b=new Set(Object.keys(p?.cohorts??{}));for(let A of g){let z=mi(y,A),j=await Al(z,"utf8"),E=A.replace(/\.ya?ml$/,""),F=p?.cohorts[E];if(F)b.delete(E);await Tl(z,f?h3(j,E,F):c3(j)),o.push(ob(n,z))}if(f&&b.size>0)throw Error(`Capability bundle review names unknown cohorts: ${[...b].sort().join(", ")}`);o.push(...await Vhe(n,r.sitePins));let _=await xt(n),T=pg(_.pilot.githubOrg);for(let A of _.users){let z=await T(A),j=mi(n,"users",A.handle);if(await y3(j,{recursive:!0}),z.brainYaml){let E=mi(j,"brain.yaml");await Tl(E,z.brainYaml),o.push(ob(n,E))}if(z.envFile){let E=mi(j,".env");await Tl(E,z.envFile),o.push(ob(n,E))}}return await Ai(n,{registry:_}),o.push("views/users.md"),{outputDir:n,changedFiles:[...new Set(o)].sort()}}var Mhe,Fhe,Hhe;var v3=S(()=>{ki();e3();Ae();qd();VI();l3();g3();un();Ec();Xn();Mhe=d.strictObject({sites:d.record($r,rE)}),Fhe=d.object({handle:$r,siteOverride:d.object({package:d.string().min(1),version:jt.optional(),theme:d.string().min(1).optional(),themeVersion:jt.optional()}).optional()}).passthrough(),Hhe=Zhe(new URL("../templates/rover-pilot/docs/canonical-crossover-record.md",import.meta.url))});var _3="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";import{webcrypto as k3}from"crypto";function Qhe(e){if(e<0)throw RangeError("Wrong ID size");try{if(!os||os.length<e)os=Buffer.allocUnsafe(e*Ghe),k3.getRandomValues(os),$l=0;else if($l+e>os.length)k3.getRandomValues(os),$l=0}catch(t){throw os=void 0,t}$l+=e}function E3(e=21){Qhe(e|=0);let t="";for(let r=$l-e;r<$l;r++)t+=_3[os[r]&63];return t}var Ghe=128,os,$l;var I3=()=>{};function Gi(e=12){return E3(e)}var Rf=S(()=>{I3()});import{openSync as Yhe,writeSync as Xhe}from"fs";class on{static instance=null;level;context;useStderr;format;logFile;fileHandle;constructor(e={},t){if(this.level=e.level??ka.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=Yhe(this.logFile,"a")}catch{}}static getInstance(e){if(!on.instance)on.instance=new on(e);else if(e?.useStderr!==void 0)on.instance.useStderr=e.useStderr;return on.instance}static resetInstance(){on.instance=null}static createFresh(e){return new on(e)}formatEntry(e,t,r){let i=new Date().toISOString();if(this.format==="json"){let n={ts:i,level:e,msg:t};if(this.context)n.ctx=this.context;if(r.length>0)n.data=r;return JSON.stringify(n)}return this.context?`[${i}] [${this.context}] ${t}`:`[${i}] ${t}`}write(e,t,r,i){if(this.format==="json")e(this.formatEntry(t,r,i));else if(i.length>0)e(this.formatEntry(t,r,[]),...i);else e(this.formatEntry(t,r,[]));if(this.fileHandle!==void 0){let n=this.formatJsonEntry(t,r,i);try{Xhe(this.fileHandle,n+`
|
|
408
|
-
`)}catch{}}}formatJsonEntry(e,t,r){let i={ts:new Date().toISOString(),level:e,msg:t};if(this.context)i.ctx=this.context;if(r.length>0)i.data=r;return JSON.stringify(i)}silly(e,...t){if(this.level<=ka.SILLY)this.write(console.debug.bind(console),"silly",e,t)}verbose(e,...t){if(this.level<=ka.VERBOSE)this.write(console.debug.bind(console),"verbose",e,t)}debug(e,...t){if(this.level<=ka.DEBUG)this.write(console.debug.bind(console),"debug",e,t)}info(e,...t){if(this.level<=ka.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<=ka.WARN)this.write(console.warn.bind(console),"warn",e,t)}error(e,...t){if(this.level<=ka.ERROR)this.write(console.error.bind(console),"error",e,t)}child(e){return new on({level:this.level,context:e,useStderr:this.useStderr,format:this.format},this.fileHandle)}setUseStderr(e){this.useStderr=e}}var ka,_Ze;var m$=S(()=>{ka={SILLY:0,VERBOSE:1,DEBUG:2,INFO:3,WARN:4,ERROR:5,NONE:6};_Ze=on.getInstance()});var h$,ege,Cl,TZe;var Of=S(()=>{ti();Ae();h$=d.enum(["file_operations","content_operations","data_processing","batch_processing"]),ege=d.looseObject({pluginId:d.string().optional(),progressToken:d.union([d.string(),d.number()]).optional(),operationType:h$,operationTarget:d.string().optional(),interfaceType:d.string().optional(),conversationId:d.string().optional(),channelId:d.string().optional(),requestedByActor:Ac.optional(),requestedByUserId:d.string().optional(),requestedByInterface:d.string().optional(),silent:d.boolean().optional(),provenance:ko.optional()}),Cl=d.looseObject({pluginId:d.string().optional(),progressToken:d.union([d.string(),d.number()]).optional(),operationType:h$,operationTarget:d.string().optional(),interfaceType:d.string().optional(),conversationId:d.string().optional(),channelId:d.string().optional(),requestedByActor:Ac.optional(),requestedByUserId:d.string().optional(),requestedByInterface:d.string().optional(),silent:d.boolean().optional(),provenance:ko.optional(),rootJobId:d.string()}),TZe=d.enum(["none","skip","replace","coalesce"])});var tge,ss=15000;var Pf=S(()=>{Of();Ae();tge=d.object({id:d.string(),type:d.string(),data:d.string(),status:d.enum(["pending","processing","completed","failed"]),source:d.string().nullable(),priority:d.number(),retryCount:d.number(),maxRetries:d.number(),lastError:d.string().nullable(),createdAt:d.number(),scheduledFor:d.number(),startedAt:d.number().nullable(),completedAt:d.number().nullable(),attemptId:d.string().nullable(),workerSlotId:d.string().nullable(),workerSessionId:d.string().nullable(),leaseExpiresAt:d.number().nullable(),attemptHeartbeatAt:d.number().nullable(),runtimeUpdatedAt:d.number().nullable(),metadata:Cl,progress:d.custom((e)=>typeof e==="object"&&e!==null&&("progress"in e)&&typeof e.progress==="number").nullable(),result:d.unknown().nullable().optional()})});var g$,T3,Ue,rge,nge,A3,ige;var as=S(()=>{Ae();Of();g$=d.enum(["pending","processing","completed","failed"]),T3=d.enum(["completed","failed"]),Ue={PENDING:"pending",PROCESSING:"processing",COMPLETED:"completed",FAILED:"failed"},rge=d.object({id:d.string(),type:d.string(),status:g$,data:d.unknown(),result:d.unknown().optional(),lastError:d.string().optional().nullable(),attempts:d.number(),maxRetries:d.number(),priority:d.number(),createdAt:d.date(),updatedAt:d.date(),processedAt:d.date().optional().nullable(),completedAt:d.date().optional().nullable(),failedAt:d.date().optional().nullable()}),nge=d.object({jobId:d.string(),type:d.string(),status:T3,result:d.unknown().optional(),error:d.string().optional()}),A3=d.object({success:d.literal(!1),error:d.string().optional()}),ige=d.object({id:d.string(),type:d.enum(["job","batch"]),status:g$,message:d.string().optional(),progress:d.object({current:d.number(),total:d.number(),percentage:d.number()}).optional(),aggregationKey:d.string().optional(),batchDetails:d.object({totalOperations:d.number(),completedOperations:d.number(),failedOperations:d.number(),currentOperation:d.string().optional(),errors:d.array(d.string()).optional()}).optional(),jobDetails:d.object({jobType:d.string(),priority:d.number(),retryCount:d.number()}).optional(),metadata:Cl})});var Be,cr;var jn=S(()=>{Be=class Be extends Error{code;extendedCode;rawCode;constructor(e,t,r,i,n){if(t!==void 0)e=`${t}: ${e}`;super(e,{cause:n});this.code=t,this.extendedCode=r,this.rawCode=i,this.name="LibsqlError"}};cr=class cr extends Be{statementIndex;constructor(e,t,r,i,n,o){super(e,r,i,n,o);this.statementIndex=t,this.name="LibsqlBatchError"}}});function $3(e){let t=oge.exec(e);if(t===null)throw new Be(`The URL '${e}' is not in a valid format`,"URL_INVALID");let r=t.groups,i=r.scheme,n=r.authority!==void 0?sge(r.authority):void 0,o=Ea(r.path),s=r.query!==void 0?cge(r.query):void 0,a=r.fragment!==void 0?Ea(r.fragment):void 0;return{scheme:i,authority:n,path:o,query:s,fragment:a}}function sge(e){let t=age.exec(e);if(t===null)throw new Be("The authority part of the URL is not in a valid format","URL_INVALID");let r=t.groups,i=Ea(r.host_br??r.host),n=r.port?parseInt(r.port,10):void 0,o=r.username!==void 0?{username:Ea(r.username),password:r.password!==void 0?Ea(r.password):void 0}:void 0;return{host:i,port:n,userinfo:o}}function cge(e){let t=e.split("&"),r=[];for(let i of t){if(i==="")continue;let n,o,s=i.indexOf("=");if(s<0)n=i,o="";else n=i.substring(0,s),o=i.substring(s+1);r.push({key:Ea(n.replaceAll("+"," ")),value:Ea(o.replaceAll("+"," "))})}return{pairs:r}}function Ea(e){try{return decodeURIComponent(e)}catch(t){if(t instanceof URIError)throw new Be(`URL component has invalid percent encoding: ${t}`,"URL_INVALID",void 0,void 0,t);throw t}}function zf(e,t,r){if(t===void 0)throw new Be(`URL with scheme ${JSON.stringify(e+":")} requires authority (the "//" part)`,"URL_INVALID");let i=`${e}:`,n=lge(t.host),o=uge(t.port),a=`//${dge(t.userinfo)}${n}${o}`,c=r.split("/").map(encodeURIComponent).join("/");if(c!==""&&!c.startsWith("/"))c="/"+c;return new URL(`${i}${a}${c}`)}function lge(e){return e.includes(":")?`[${encodeURI(e)}]`:encodeURI(e)}function uge(e){return e!==void 0?`:${e}`:""}function dge(e){if(e===void 0)return"";let t=encodeURIComponent(e.username),r=e.password!==void 0?`:${encodeURIComponent(e.password)}`:"";return`${t}${r}@`}var oge,age;var sb=S(()=>{jn();oge=(()=>new RegExp("^(?<scheme>[A-Za-z][A-Za-z.+-]*):(//(?<authority>[^/?#]*))?(?<path>[^?#]*)(\\?(?<query>[^#]*))?(#(?<fragment>.*))?$","su"))();age=(()=>new RegExp("^((?<username>[^:]*)(:(?<password>.*))?@)?((?<host>[^:\\[\\]]*)|(\\[(?<host_br>[^\\[\\]]*)\\]))(:(?<port>[0-9]*))?$","su"))()});var Ol,C3,R3,Nf,ab,fge,lr,O3,N3=(e)=>e.replace(/=/g,"").replace(/[+\/]/g,(t)=>t=="+"?"-":"_"),D3=(e)=>e.replace(/[^A-Za-z0-9\+\/]/g,""),L3=(e)=>{let t,r,i,n,o="",s=e.length%3;for(let a=0;a<e.length;){if((r=e.charCodeAt(a++))>255||(i=e.charCodeAt(a++))>255||(n=e.charCodeAt(a++))>255)throw TypeError("invalid character found");t=r<<16|i<<8|n,o+=Nf[t>>18&63]+Nf[t>>12&63]+Nf[t>>6&63]+Nf[t&63]}return s?o.slice(0,s-3)+"===".substring(s):o},S$,y$,cb=(e,t=!1)=>t?N3(y$(e)):y$(e),pge=(e)=>{if(e.length<2){var t=e.charCodeAt(0);return t<128?e:t<2048?lr(192|t>>>6)+lr(128|t&63):lr(224|t>>>12&15)+lr(128|t>>>6&63)+lr(128|t&63)}else{var t=65536+(e.charCodeAt(0)-55296)*1024+(e.charCodeAt(1)-56320);return lr(240|t>>>18&7)+lr(128|t>>>12&63)+lr(128|t>>>6&63)+lr(128|t&63)}},mge,B3=(e)=>e.replace(mge,pge),P3,Rl=(e,t=!1)=>t?N3(P3(e)):P3(e),z3=(e)=>Rl(e,!0),hge,gge=(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 lr((r>>>10)+55296)+lr((r&1023)+56320);case 3:return lr((15&e.charCodeAt(0))<<12|(63&e.charCodeAt(1))<<6|63&e.charCodeAt(2));default:return lr((31&e.charCodeAt(0))<<6|63&e.charCodeAt(1))}},j3=(e)=>e.replace(hge,gge),U3=(e)=>{if(e=e.replace(/\s+/g,""),!fge.test(e))throw TypeError("malformed base64.");e+="==".slice(2-(e.length&3));let t,r,i,n=[];for(let o=0;o<e.length;)if(t=ab[e.charAt(o++)]<<18|ab[e.charAt(o++)]<<12|(r=ab[e.charAt(o++)])<<6|(i=ab[e.charAt(o++)]),r===64)n.push(lr(t>>16&255));else if(i===64)n.push(lr(t>>16&255,t>>8&255));else n.push(lr(t>>16&255,t>>8&255,t&255));return n.join("")},x$,q3,Z3=(e)=>q3(M3(e)),yge,M3=(e)=>D3(e.replace(/[-_]/g,(t)=>t=="-"?"+":"/")),b$=(e)=>yge(M3(e)),bge=(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)},F3=(e)=>({value:e,enumerable:!1,writable:!0,configurable:!0}),H3=function(){let e=(t,r)=>Object.defineProperty(String.prototype,t,F3(r));e("fromBase64",function(){return b$(this)}),e("toBase64",function(t){return Rl(this,t)}),e("toBase64URI",function(){return Rl(this,!0)}),e("toBase64URL",function(){return Rl(this,!0)}),e("toUint8Array",function(){return Z3(this)})},K3=function(){let e=(t,r)=>Object.defineProperty(Uint8Array.prototype,t,F3(r));e("toBase64",function(t){return cb(this,t)}),e("toBase64URI",function(){return cb(this,!0)}),e("toBase64URL",function(){return cb(this,!0)})},Sge=()=>{H3(),K3()},Pl;var lb=S(()=>{Ol=typeof Buffer==="function",C3=typeof TextDecoder==="function"?new TextDecoder("utf-8",{ignoreBOM:!0}):void 0,R3=typeof TextEncoder==="function"?new TextEncoder:void 0,Nf=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),ab=((e)=>{let t={};return e.forEach((r,i)=>t[r]=i),t})(Nf),fge=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,lr=String.fromCharCode.bind(String),O3=typeof Uint8Array.from==="function"?Uint8Array.from.bind(Uint8Array):(e)=>new Uint8Array(Array.prototype.slice.call(e,0)),S$=typeof btoa==="function"?(e)=>btoa(e):Ol?(e)=>Buffer.from(e,"binary").toString("base64"):L3,y$=Ol?(e)=>Buffer.from(e).toString("base64"):(e)=>{let r=[];for(let i=0,n=e.length;i<n;i+=4096)r.push(lr.apply(null,e.subarray(i,i+4096)));return S$(r.join(""))},mge=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,P3=Ol?(e)=>Buffer.from(e,"utf8").toString("base64"):R3?(e)=>y$(R3.encode(e)):(e)=>S$(B3(e)),hge=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,x$=typeof atob==="function"?(e)=>atob(D3(e)):Ol?(e)=>Buffer.from(e,"base64").toString("binary"):U3,q3=Ol?(e)=>O3(Buffer.from(e,"base64")):(e)=>O3(x$(e).split("").map((t)=>t.charCodeAt(0))),yge=Ol?(e)=>Buffer.from(e,"base64").toString("utf8"):C3?(e)=>C3.decode(q3(e)):(e)=>j3(x$(e)),Pl={version:"3.8.0",VERSION:"3.8.0",atob:x$,atobPolyfill:U3,btoa:S$,btoaPolyfill:L3,fromBase64:b$,toBase64:Rl,encode:Rl,encodeURI:z3,encodeURL:z3,utob:B3,btou:j3,decode:b$,isValid:bge,fromUint8Array:cb,toUint8Array:Z3,extendString:H3,extendUint8Array:K3,extendBuiltins:Sge}});function cs(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 zl{columns;columnTypes;rows;rowsAffected;lastInsertRowid;constructor(e,t,r,i,n){this.columns=e,this.columnTypes=t,this.rows=r,this.rowsAffected=i,this.lastInsertRowid=n}toJSON(){return{columns:this.columns,columnTypes:this.columnTypes,rows:this.rows.map(xge),rowsAffected:this.rowsAffected,lastInsertRowid:this.lastInsertRowid!==void 0?""+this.lastInsertRowid:null}}}function xge(e){return Array.prototype.map.call(e,wge)}function wge(e){if(typeof e==="bigint")return""+e;else if(e instanceof ArrayBuffer)return Pl.fromUint8Array(new Uint8Array(e));else return e}var hi="https://github.com/libsql/libsql-client-ts#supported-urls";var Nl=S(()=>{lb()});function V3(e){return e.scheme==="file"&&(e.path===":memory:"||e.path.startsWith(":memory:?"))}function Df(e,t){if(typeof e!=="object")throw TypeError(`Expected client configuration as object, got ${typeof e}`);let{url:r,authToken:i,tls:n,intMode:o,concurrency:s}=e;s=Math.max(0,s||20),o??="number";let a=[];if(r===J3)r="file::memory:";let c=$3(r),l=c.scheme.toLowerCase(),u=l==="file"&&c.path===J3&&c.authority===void 0,f;if(u)f={cache:{values:["shared","private"],update:(g,b)=>a.push(`${g}=${b}`)}};else f={tls:{values:["0","1"],update:(g,b)=>n=b==="1"},authToken:{update:(g,b)=>i=b}};for(let{key:g,value:b}of c.query?.pairs??[]){if(!Object.hasOwn(f,g))throw new Be(`Unsupported URL query parameter ${JSON.stringify(g)}`,"URL_PARAM_NOT_SUPPORTED");let _=f[g];if(_.values!==void 0&&!_.values.includes(b))throw new Be(`Unknown value for the "${g}" query argument: ${JSON.stringify(b)}. Supported values are: [${_.values.map((T)=>'"'+T+'"').join(", ")}]`,"URL_INVALID");if(_.update!==void 0)_?.update(g,b)}let p=a.length===0?"":`?${a.join("&")}`,m=c.path+p,y;if(l==="libsql")if(n===!1){if(c.authority?.port===void 0)throw new Be('A "libsql:" URL with ?tls=0 must specify an explicit port',"URL_INVALID");y=t?"http":"ws"}else y=t?"https":"wss";else y=l;if(y==="http"||y==="ws")n??=!1;else n??=!0;if(y!=="http"&&y!=="ws"&&y!=="https"&&y!=="wss"&&y!=="file")throw new Be(`The client supports only "libsql:", "wss:", "ws:", "https:", "http:" and "file:" URLs, got ${JSON.stringify(c.scheme+":")}. For more information, please read ${hi}`,"URL_SCHEME_NOT_SUPPORTED");if(o!=="number"&&o!=="bigint"&&o!=="string")throw TypeError(`Invalid value for intMode, expected "number", "bigint" or "string", got ${JSON.stringify(o)}`);if(c.fragment!==void 0)throw new Be(`URL fragments are not supported: ${JSON.stringify("#"+c.fragment)}`,"URL_INVALID");if(u)return{scheme:"file",tls:!1,path:m,intMode:o,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:y,tls:n,authority:c.authority,path:m,authToken:i,intMode:o,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 J3=":memory:";var Lf=S(()=>{jn();sb();Nl()});var G3=Se(function(xn){var vge=xn&&xn.__createBinding||(Object.create?function(e,t,r,i){if(i===void 0)i=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,i,n)}:function(e,t,r,i){if(i===void 0)i=r;e[i]=t[r]}),_ge=xn&&xn.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),W3=xn&&xn.__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))vge(t,e,r)}return _ge(t,e),t};Object.defineProperty(xn,"__esModule",{value:!0});xn.load=xn.currentTarget=void 0;var kge=W3(pr("path")),Ege=W3(pr("fs"));function Ige(){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 Tge()?`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}`)}xn.currentTarget=Ige;function Tge(){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 Age(e){let t=kge.join(e,"index.node");return Ege.existsSync(t)?pr(t):null}xn.load=Age});var X3=Se(function(JZe,Y3){var Q3=()=>process.platform==="linux",w$=null,$ge=()=>{if(!w$)w$=Q3()&&process.report?process.report.getReport():{};return w$};Y3.exports={isLinux:Q3,getReport:$ge}});var r5=Se(function(VZe,t5){var e5=pr("fs"),Cge=(e)=>e5.readFileSync(e,"utf-8"),Rge=(e)=>new Promise((t,r)=>{e5.readFile(e,"utf-8",(i,n)=>{if(i)r(i);else t(n)})});t5.exports={LDD_PATH:"/usr/bin/ldd",readFileSync:Cge,readFile:Rge}});var S5=Se(function(WZe,b5){var i5=pr("child_process"),{isLinux:Dl,getReport:o5}=X3(),{LDD_PATH:ub,readFile:s5,readFileSync:a5}=r5(),gi,yi,ls="",c5=()=>{if(!ls)return new Promise((e)=>{i5.exec("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",(t,r)=>{ls=t?" ":r,e(ls)})});return ls},l5=()=>{if(!ls)try{ls=i5.execSync("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",{encoding:"utf8"})}catch(e){ls=" "}return ls},Qi="glibc",u5=/GLIBC\s(\d+\.\d+)/,Ia="musl",Oge=Qi.toUpperCase(),Pge=Ia.toLowerCase(),zge=(e)=>e.includes("libc.musl-")||e.includes("ld-musl-"),d5=()=>{let e=o5();if(e.header&&e.header.glibcVersionRuntime)return Qi;if(Array.isArray(e.sharedObjects)){if(e.sharedObjects.some(zge))return Ia}return null},f5=(e)=>{let[t,r]=e.split(/[\r\n]+/);if(t&&t.includes(Qi))return Qi;if(r&&r.includes(Ia))return Ia;return null},p5=(e)=>{if(e.includes(Pge))return Ia;if(e.includes(Oge))return Qi;return null},Nge=async()=>{if(gi!==void 0)return gi;gi=null;try{let e=await s5(ub);gi=p5(e)}catch(e){}return gi},Dge=()=>{if(gi!==void 0)return gi;gi=null;try{let e=a5(ub);gi=p5(e)}catch(e){}return gi},m5=async()=>{let e=null;if(Dl()){if(e=await Nge(),!e)e=d5();if(!e){let t=await c5();e=f5(t)}}return e},h5=()=>{let e=null;if(Dl()){if(e=Dge(),!e)e=d5();if(!e){let t=l5();e=f5(t)}}return e},Lge=async()=>Dl()&&await m5()!==Qi,Bge=()=>Dl()&&h5()!==Qi,jge=async()=>{if(yi!==void 0)return yi;yi=null;try{let t=(await s5(ub)).match(u5);if(t)yi=t[1]}catch(e){}return yi},Uge=()=>{if(yi!==void 0)return yi;yi=null;try{let t=a5(ub).match(u5);if(t)yi=t[1]}catch(e){}return yi},g5=()=>{let e=o5();if(e.header&&e.header.glibcVersionRuntime)return e.header.glibcVersionRuntime;return null},n5=(e)=>e.trim().split(/\s+/)[1],y5=(e)=>{let[t,r,i]=e.split(/[\r\n]+/);if(t&&t.includes(Qi))return n5(t);if(r&&i&&r.includes(Ia))return n5(i);return null},qge=async()=>{let e=null;if(Dl()){if(e=await jge(),!e)e=g5();if(!e){let t=await c5();e=y5(t)}}return e},Zge=()=>{let e=null;if(Dl()){if(e=Uge(),!e)e=g5();if(!e){let t=l5();e=y5(t)}}return e};b5.exports={GLIBC:Qi,MUSL:Ia,family:m5,familySync:h5,isNonGlibcLinux:Lge,isNonGlibcLinuxSync:Bge,version:qge,versionSync:Zge}});var w5=Se(function(GZe,x5){var Mge={ALLOW:0,DENY:1};x5.exports=Mge});var _5=Se(function(QZe,v5){var v$={value:"SqliteError",writable:!0,enumerable:!1,configurable:!0};function Ta(e,t,r){if(new.target!==Ta)return new Ta(e,t);if(typeof t!=="string")throw TypeError("Expected second argument to be a string");Error.call(this,e),v$.value=""+e,Object.defineProperty(this,"message",v$),Error.captureStackTrace(this,Ta),this.code=t,this.rawCode=r}Object.setPrototypeOf(Ta,Error);Object.setPrototypeOf(Ta.prototype,Error.prototype);Object.defineProperty(Ta.prototype,"name",v$);v5.exports=Ta});var R5=Se(function(YZe,db){var __dirname="/home/runner/work/brains/brains/node_modules/libsql",{load:Fge,currentTarget:Hge}=G3(),{familySync:k5,GLIBC:Kge,MUSL:Jge}=S5();function Vge(){if(process.env.LIBSQL_JS_DEV)return Fge(__dirname);let e=Hge();if(k5()==Kge)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"&&k5()==Jge)e="linux-arm-musleabihf";return pr(`@libsql/${e}`)}var{databaseOpen:Wge,databaseOpenWithSync:Gge,databaseInTransaction:Qge,databaseInterrupt:Yge,databaseClose:Xge,databaseSyncSync:eye,databaseSyncUntilSync:tye,databaseExecSync:rye,databasePrepareSync:nye,databaseDefaultSafeIntegers:iye,databaseAuthorizer:oye,databaseLoadExtension:sye,databaseMaxWriteReplicationIndex:aye,statementRaw:cye,statementIsReader:lye,statementGet:E5,statementRun:I5,statementInterrupt:uye,statementRowsSync:T5,statementColumns:dye,statementSafeIntegers:fye,rowsNext:pye}=Vge(),mye=w5(),A5=_5();function Ll(e){if(e.libsqlError)return new A5(e.message,e.code,e.rawCode);return e}class $5{constructor(e,t){let r=t?.encryptionCipher??"aes256cbc";if(t&&t.syncUrl){var i="";if(t.syncAuth)console.warn("Warning: The `syncAuth` option is deprecated, please use `authToken` option instead."),i=t.syncAuth;else if(t.authToken)i=t.authToken;let o=t?.encryptionKey??"",s=t?.syncPeriod??0,a=t?.readYourWrites??!0,c=t?.offline??!1,l=t?.remoteEncryptionKey??"";this.db=Gge(e,t.syncUrl,i,r,o,s,a,c,l)}else{let o=t?.authToken??"",s=t?.encryptionKey??"",a=t?.timeout??0,c=t?.remoteEncryptionKey??"";this.db=Wge(e,o,r,s,a,c)}this.memory=e===":memory:",this.readonly=!1,this.name="",this.open=!0;let n=this.db;Object.defineProperties(this,{inTransaction:{get(){return Qge(n)}}})}sync(){return eye.call(this.db)}syncUntil(e){return tye.call(this.db,e)}prepare(e){try{let t=nye.call(this.db,e);return new C5(t)}catch(t){throw Ll(t)}}transaction(e){if(typeof e!=="function")throw TypeError("Expected first argument to be a function");let t=this,r=(n)=>(...o)=>{t.exec("BEGIN "+n);try{let s=e(...o);return t.exec("COMMIT"),s}catch(s){throw t.exec("ROLLBACK"),s}},i={default:{value:r("")},deferred:{value:r("DEFERRED")},immediate:{value:r("IMMEDIATE")},exclusive:{value:r("EXCLUSIVE")},database:{value:this,enumerable:!0}};return Object.defineProperties(i.default.value,i),Object.defineProperties(i.deferred.value,i),Object.defineProperties(i.immediate.value,i),Object.defineProperties(i.exclusive.value,i),i.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,i=this.prepare(`PRAGMA ${e}`,this,!0);return r?i.pluck().get():i.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){oye.call(this.db,e)}loadExtension(...e){sye.call(this.db,...e)}maxWriteReplicationIndex(){return aye.call(this.db)}exec(e){try{rye.call(this.db,e)}catch(t){throw Ll(t)}}interrupt(){Yge.call(this.db)}close(){Xge.call(this.db),this.open=!1}defaultSafeIntegers(e){return iye.call(this.db,e??!0),this}unsafeMode(...e){throw Error("not implemented")}}class C5{constructor(e){this.stmt=e,this.pluckMode=!1}raw(e){return cye.call(this.stmt,e??!0),this}pluck(e){return this.pluckMode=e??!0,this}get reader(){return lye.call(this.stmt)}run(...e){try{if(e.length==1&&typeof e[0]==="object")return I5.call(this.stmt,e[0]);else return I5.call(this.stmt,e.flat())}catch(t){throw Ll(t)}}get(...e){try{if(e.length==1&&typeof e[0]==="object")return E5.call(this.stmt,e[0]);else return E5.call(this.stmt,e.flat())}catch(t){throw Ll(t)}}iterate(...e){var t=void 0;if(e.length==1&&typeof e[0]==="object")t=T5.call(this.stmt,e[0]);else t=T5.call(this.stmt,e.flat());return{nextRows:Array(100),nextRowIndex:100,next(){try{if(this.nextRowIndex===100)pye.call(t,this.nextRows),this.nextRowIndex=0;let i=this.nextRows[this.nextRowIndex];if(this.nextRows[this.nextRowIndex]=void 0,!i)return{done:!0};return this.nextRowIndex++,{value:i,done:!1}}catch(i){throw Ll(i)}},[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 Ll(t)}}interrupt(){uye.call(this.stmt)}columns(){return dye.call(this.stmt)}safeIntegers(e){return fye.call(this.stmt,e??!0),this}}db.exports=$5;db.exports.Authorization=mye;db.exports.SqliteError=A5});import{Buffer as P5}from"buffer";function z5(e){if(e.scheme!=="file")throw new Be(`URL scheme ${JSON.stringify(e.scheme+":")} is not supported by the local sqlite3 client. For more information, please read ${hi}`,"URL_SCHEME_NOT_SUPPORTED");let t=e.authority;if(t!==void 0){let s=t.host.toLowerCase();if(s!==""&&s!=="localhost")throw new Be(`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 ${hi}`,"URL_INVALID");if(t.port!==void 0)throw new Be("File URL cannot have a port","URL_INVALID");if(t.userinfo!==void 0)throw new Be("File URL cannot have username and password","URL_INVALID")}let r=V3(e);if(r&&e.syncUrl)throw new Be(`Embedded replica must use file for local db but URI with in-memory mode were provided instead: ${e.path}`,"URL_INVALID");let i=e.path;if(r)i=`${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},o=new Bf.default(i,n);return Mt(o,"SELECT 1 AS checkThatTheDatabaseCanBeOpened",e.intMode),new N5(i,n,o,e.intMode)}class N5{#e;#t;#r;#n;closed;protocol;constructor(e,t,r,i){this.#e=e,this.#t=t,this.#r=r,this.#n=i,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.#i(),Mt(this.#o(),r,this.#n)}async batch(e,t="deferred"){this.#i();let r=this.#o();try{Mt(r,cs(t),this.#n);let i=[];for(let n=0;n<e.length;n++)try{if(!r.inTransaction)throw new cr("The transaction has been rolled back",n,"TRANSACTION_CLOSED");let o=e[n],s=Array.isArray(o)?{sql:o[0],args:o[1]||[]}:o;i.push(Mt(r,s,this.#n))}catch(o){if(o instanceof cr)throw o;if(o instanceof Be)throw new cr(o.message,n,o.code,o.extendedCode,o.rawCode,o.cause instanceof Error?o.cause:void 0);throw o}return Mt(r,"COMMIT",this.#n),i}finally{if(r.inTransaction)Mt(r,"ROLLBACK",this.#n)}}async migrate(e){this.#i();let t=this.#o();try{Mt(t,"PRAGMA foreign_keys=off",this.#n),Mt(t,cs("deferred"),this.#n);let r=[];for(let i=0;i<e.length;i++)try{if(!t.inTransaction)throw new cr("The transaction has been rolled back",i,"TRANSACTION_CLOSED");r.push(Mt(t,e[i],this.#n))}catch(n){if(n instanceof cr)throw n;if(n instanceof Be)throw new cr(n.message,i,n.code,n.extendedCode,n.rawCode,n.cause instanceof Error?n.cause:void 0);throw n}return Mt(t,"COMMIT",this.#n),r}finally{if(t.inTransaction)Mt(t,"ROLLBACK",this.#n);Mt(t,"PRAGMA foreign_keys=on",this.#n)}}async transaction(e="write"){let t=this.#o();return Mt(t,cs(e),this.#n),this.#r=null,new D5(t,this.#n)}async executeMultiple(e){this.#i();let t=this.#o();try{return L5(t,e)}finally{if(t.inTransaction)Mt(t,"ROLLBACK",this.#n)}}async sync(){this.#i();let e=await this.#o().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 Bf.default(this.#e,this.#t),this.closed=!1}}close(){if(this.closed=!0,this.#r!==null)this.#r.close(),this.#r=null}#i(){if(this.closed)throw new Be("The client is closed","CLIENT_CLOSED")}#o(){if(this.#r===null)this.#r=new Bf.default(this.#e,this.#t);return this.#r}}class D5{#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(),Mt(this.#e,r,this.#t)}async batch(e){let t=[];for(let r=0;r<e.length;r++)try{this.#r();let i=e[r],n=Array.isArray(i)?{sql:i[0],args:i[1]||[]}:i;t.push(Mt(this.#e,n,this.#t))}catch(i){if(i instanceof cr)throw i;if(i instanceof Be)throw new cr(i.message,r,i.code,i.extendedCode,i.rawCode,i.cause instanceof Error?i.cause:void 0);throw i}return t}async executeMultiple(e){return this.#r(),L5(this.#e,e)}async rollback(){if(!this.#e.open)return;this.#r(),Mt(this.#e,"ROLLBACK",this.#t)}async commit(){this.#r(),Mt(this.#e,"COMMIT",this.#t)}close(){if(this.#e.inTransaction)Mt(this.#e,"ROLLBACK",this.#t)}get closed(){return!this.#e.inTransaction}#r(){if(this.closed)throw new Be("The transaction is closed","TRANSACTION_CLOSED")}}function Mt(e,t,r){let i,n;if(typeof t==="string")i=t,n=[];else if(i=t.sql,Array.isArray(t.args))n=t.args.map((o)=>O5(o,r));else{n={};for(let o in t.args){let s=o[0]==="@"||o[0]==="$"||o[0]===":"?o.substring(1):o;n[s]=O5(t.args[o],r)}}try{let o=e.prepare(i);o.safeIntegers(!0);let s=!0;try{o.raw(!0)}catch{s=!1}if(s){let a=Array.from(o.columns().map((p)=>p.name)),c=Array.from(o.columns().map((p)=>p.type??"")),l=o.all(n).map((p)=>hye(p,a,r)),u=0,f=void 0;return new zl(a,c,l,0,void 0)}else{let a=o.run(n),c=a.changes,l=BigInt(a.lastInsertRowid);return new zl([],[],[],c,l)}}catch(o){throw B5(o)}}function hye(e,t,r){let i={};Object.defineProperty(i,"length",{value:e.length});for(let n=0;n<e.length;++n){let o=gye(e[n],r);Object.defineProperty(i,n,{value:o});let s=t[n];if(!Object.hasOwn(i,s))Object.defineProperty(i,s,{value:o,enumerable:!0,configurable:!0,writable:!0})}return i}function gye(e,t){if(typeof e==="bigint")if(t==="number"){if(e<yye||e>bye)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 P5)return e.buffer;return e}function O5(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<Sye||e>xye)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 P5.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 L5(e,t){try{e.exec(t)}catch(r){throw B5(r)}}function B5(e){if(e instanceof Bf.default.SqliteError){let t=e.code,r=wye(e.rawCode);return new Be(e.message,r,t,e.rawCode,e)}return e}function wye(e){if(e===void 0)return"SQLITE_UNKNOWN";let t=e&255;return vye[t]??`SQLITE_UNKNOWN_${t.toString()}`}var Bf,yye,bye=9007199254740991n,Sye,xye=9223372036854775807n,vye;var j5=S(()=>{jn();Lf();Nl();Bf=hu(R5(),1);jn();yye=-9007199254740991n;Sye=-9223372036854775808n;vye={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 us;var _$=S(()=>{if(typeof WebSocket<"u")us=WebSocket;else if(typeof global<"u")us=global.WebSocket;else if(typeof window<"u")us=window.WebSocket;else if(typeof self<"u")us=self.WebSocket});class Bl{constructor(){this.intMode="number"}intMode}var st,je,jf,Ot,Uf,jl,Aa,Un,xr,bi;var Pt=S(()=>{st=class st extends Error{constructor(e){super(e);this.name="ClientError"}};je=class je extends st{constructor(e){super(e);this.name="ProtoError"}};jf=class jf extends st{code;proto;constructor(e,t){super(e);this.name="ResponseError",this.code=t.code,this.proto=t,this.stack=void 0}};Ot=class Ot extends st{constructor(e,t){if(t!==void 0){super(`${e}: ${t}`);this.cause=t}else super(e);this.name="ClosedError"}};Uf=class Uf extends st{constructor(e){super(e);this.name="WebSocketUnsupportedError"}};jl=class jl extends st{constructor(e){super(e);this.name="WebSocketError"}};Aa=class Aa extends st{status;constructor(e,t){super(e);this.status=t,this.name="HttpServerError"}};Un=class Un extends st{constructor(e){super(e);this.name="ProtocolVersionError"}};xr=class xr extends st{constructor(e){super(e);this.name="InternalError"}};bi=class bi extends st{constructor(e){super(e);this.name="MisuseError"}}});function Fr(e){if(typeof e==="string")return e;throw Ul(e,"string")}function sn(e){if(e===null||e===void 0)return;else if(typeof e==="string")return e;throw Ul(e,"string or null")}function Yi(e){if(typeof e==="number")return e;throw Ul(e,"number")}function ds(e){if(typeof e==="boolean")return e;throw Ul(e,"boolean")}function qf(e){if(Array.isArray(e))return e;throw Ul(e,"array")}function Lt(e){if(e!==null&&typeof e==="object"&&!Array.isArray(e))return e;throw Ul(e,"object")}function qn(e,t){return qf(e).map((r)=>t(Lt(r)))}function Ul(e,t){if(e===void 0)return new je(`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 je(`Expected ${t}, received ${r}`)}function $a(e,t){return t(Lt(e))}var ql=S(()=>{Pt()});class U5{#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 i=0;i<t.length;++i){if(i!==0)this.#e.push(",");this.begin(),r(this,t[i]),this.end()}this.#e.push("]")}}function Zf(e,t){let r=[],i=new U5(r);return i.begin(),t(i,e),i.end(),r.join("")}var Ca=0,Mf=1,Ff=2,q5=5;class Z5{#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 M5{#e;#t;constructor(e){this.#e=e,this.#t=-1}setup(e){this.#t=e}#r(e){if(this.#t!==e)throw new je(`Expected wire type ${e}, got ${this.#t}`);this.#t=-1}bytes(){this.#r(Ff);let e=this.#e.varint();return this.#e.bytes(e)}string(){return new TextDecoder().decode(this.bytes())}message(e){return fs(this.bytes(),e)}int32(){return this.#r(Ca),this.#e.varint()}uint32(){return this.int32()}bool(){return this.int32()!==0}uint64(){return this.#r(Ca),this.#e.varintBig()}sint64(){let e=this.uint64();return e>>1n^-(e&1n)}double(){return this.#r(Mf),this.#e.double()}maybeSkip(){if(this.#t<0)return;else if(this.#t===Ca)this.#e.skipVarint();else if(this.#t===Mf)this.#e.skip(8);else if(this.#t===Ff){let e=this.#e.varint();this.#e.skip(e)}else if(this.#t===q5)this.#e.skip(4);else throw new je(`Unexpected wire type ${this.#t}`);this.#t=-1}}function fs(e,t){let r=new Z5(e),i=new M5(r),n=t.default();while(!r.eof()){let o=r.varint(),s=o>>3,a=o&7;i.setup(a);let c=t[s];if(c!==void 0){let l=c(i,n);if(l!==void 0)n=l}i.maybeSkip()}return n}var k$=S(()=>{Pt()});class E${#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}#i(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),i=new Uint8Array(r),n=new DataView(r);i.set(new Uint8Array(this.#e,0,this.#n)),this.#e=r,this.#t=i,this.#r=n}#o(e){this.#i(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.#i(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.#o(e<<3|t)}bytes(e,t){this.#s(e,Ff),this.#o(t.byteLength),this.#i(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 i=new E$;r(i,t),this.bytes(e,i.data())}int32(e,t){this.#s(e,Ca),this.#o(t)}uint32(e,t){this.int32(e,t)}bool(e,t){this.int32(e,t?1:0)}sint64(e,t){this.#s(e,Ca),this.#a(t<<1n^t>>63n)}double(e,t){this.#s(e,Mf),this.#i(8),this.#r.setFloat64(this.#n,t,!0),this.#n+=8}data(){return new Uint8Array(this.#e,0,this.#n)}}function Hf(e,t){let r=new E$;return t(r,e),r.data()}var F5=()=>{};var I$=S(()=>{ql();k$();F5()});class ps{#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 xr("Freeing an id that is not allocated");if(this.#t.delete(this.#e.size),e<this.#e.size)this.#t.add(e)}}var T$=S(()=>{Pt()});function rt(e,t){throw new xr(t)}var wn=S(()=>{Pt()});function Zl(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<kye||e>Eye)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 A$(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 bi("Invalid value for IntMode");else if(e instanceof Uint8Array)return e.slice().buffer;else if(e===void 0)throw new je("Received unrecognized type of Value");else throw rt(e,"Impossible type of Value")}var kye,Eye=9223372036854775807n;var $$=S(()=>{Pt();wn();kye=-9223372036854775808n});function Ra(e){return{affectedRowCount:e.affectedRowCount,lastInsertRowid:e.lastInsertRowid,columnNames:e.cols.map((t)=>t.name),columnDecltypes:e.cols.map((t)=>t.decltype)}}function pb(e,t){let r=Ra(e),i=e.rows.map((n)=>H5(r.columnNames,n,t));return{...r,rows:i}}function mb(e,t){let r=Ra(e),i;if(e.rows.length>0)i=H5(r.columnNames,e.rows[0],t);return{...r,row:i}}function hb(e,t){let r=Ra(e),i;if(e.rows.length>0&&r.columnNames.length>0)i=A$(e.rows[0][0],t);return{...r,value:i}}function H5(e,t,r){let i={};Object.defineProperty(i,"length",{value:t.length});for(let n=0;n<t.length;++n){let o=A$(t[n],r);Object.defineProperty(i,n,{value:o});let s=e[n];if(s!==void 0&&!Object.hasOwn(i,s))Object.defineProperty(i,s,{value:o,enumerable:!0,configurable:!0,writable:!0})}return i}function Xi(e){return new jf(e.message,e)}var Kf=S(()=>{Pt();$$()});class Oa{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}_getSqlId(e){if(this.#e!==e)throw new bi("Attempted to use SQL text opened with other object");else if(this.#r!==void 0)throw new Ot("SQL text is closed",this.#r);return this.#t}close(){this._setClosed(new st("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 Jf(e,t){if(t instanceof Oa)return{sqlId:t._getSqlId(e)};else return{sql:""+t}}var Ml=S(()=>{Pt()});class ms{#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 Vf{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(Zl(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]=Zl(t),this}bindName(e,t){return this._namedArgs.set(e,Zl(t)),this}unbindAll(){return this._args.length=0,this._namedArgs.clear(),this}}function gb(e,t,r){let i,n=[],o=[];if(t instanceof Vf){i=t.sql,n=t._args;for(let[c,l]of t._namedArgs.entries())o.push({name:c,value:l})}else if(Array.isArray(t))if(i=t[0],Array.isArray(t[1]))n=t[1].map((c)=>Zl(c));else o=Object.entries(t[1]).map(([c,l])=>({name:c,value:Zl(l)}));else i=t;let{sql:s,sqlId:a}=Jf(e,i);return{sql:s,sqlId:a,args:n,namedArgs:o,wantRows:r}}var yb=S(()=>{Ml();$$()});class bb{_stream;#e;_steps;#t;constructor(e,t){this._stream=e,this.#e=t,this._steps=[],this.#t=!1}step(){return new C$(this)}execute(){if(this.#t)throw new bi("This batch has already been executed");this.#t=!0;let e={steps:this._steps.map((t)=>t.proto)};if(this.#e)return Tye(this._stream,this._steps,e);else return Iye(this._stream,this._steps,e)}}function Iye(e,t,r){return e._batch(r).then((i)=>{for(let n=0;n<t.length;++n){let o=i.stepResults.get(n),s=i.stepErrors.get(n);t[n].callback(o,s)}})}async function Tye(e,t,r){let i=await e._openCursor(r);try{let n=0,o=void 0,s=[];for(;;){let a=await i.next();if(a===void 0)break;if(a.type==="step_begin"){if(a.step<n||a.step>=t.length)throw new je("Server produced StepBeginEntry for unexpected step");else if(o!==void 0)throw new je("Server produced StepBeginEntry before terminating previous step");for(let c=n;c<a.step;++c)t[c].callback(void 0,void 0);n=a.step+1,o=a,s=[]}else if(a.type==="step_end"){if(o===void 0)throw new je("Server produced StepEndEntry but no step is active");let c={cols:o.cols,rows:s,affectedRowCount:a.affectedRowCount,lastInsertRowid:a.lastInsertRowid};t[o.step].callback(c,void 0),o=void 0,s=[]}else if(a.type==="step_error"){if(o===void 0){if(a.step>=t.length)throw new je("Server produced StepErrorEntry for unexpected step");for(let c=n;c<a.step;++c)t[c].callback(void 0,void 0)}else{if(a.step!==o.step)throw new je("Server produced StepErrorEntry for unexpected step");o=void 0,s=[]}t[a.step].callback(void 0,a.error),n=a.step+1}else if(a.type==="row"){if(o===void 0)throw new je("Server produced RowEntry but no step is active");s.push(a.row)}else if(a.type==="error")throw Xi(a.error);else if(a.type==="none")throw new je("Server produced unrecognized CursorEntry");else throw rt(a,"Impossible CursorEntry")}if(o!==void 0)throw new je("Server closed Cursor before terminating active step");for(let a=n;a<t.length;++a)t[a].callback(void 0,void 0)}finally{i.close()}}class C${_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,pb)}queryRow(e){return this.#t(e,!0,mb)}queryValue(e){return this.#t(e,!0,hb)}run(e){return this.#t(e,!1,Ra)}#t(e,t,r){if(this._index!==void 0)throw new bi("This BatchStep has already been added to the batch");let i=gb(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 o={stmt:i,condition:n};return new Promise((s,a)=>{let c=(l,u)=>{if(l!==void 0&&u!==void 0)a(new je("Server returned both result and error"));else if(u!==void 0)a(Xi(u));else if(l!==void 0)s(r(l,this._batch._stream.intMode));else s(void 0)};this._index=this._batch._steps.length,this._batch._steps.push({proto:o,callback:c})})}}class wt{_batch;_proto;constructor(e,t){this._batch=e,this._proto=t}static ok(e){return new wt(e._batch,{type:"ok",step:K5(e)})}static error(e){return new wt(e._batch,{type:"error",step:K5(e)})}static not(e){return new wt(e._batch,{type:"not",cond:e._proto})}static and(e,t){for(let r of t)J5(e,r);return new wt(e,{type:"and",conds:t.map((r)=>r._proto)})}static or(e,t){for(let r of t)J5(e,r);return new wt(e,{type:"or",conds:t.map((r)=>r._proto)})}static isAutocommit(e){return e._stream.client()._ensureVersion(3,"BatchCond.isAutocommit()"),new wt(e,{type:"is_autocommit"})}}function K5(e){if(e._index===void 0)throw new bi("Cannot add a condition referencing a step that has not been added to the batch");return e._index}function J5(e,t){if(t._batch!==e)throw new bi("Cannot mix BatchCond objects for different Batch objects")}var R$=S(()=>{Pt();Kf();yb();wn()});function V5(e){return{paramNames:e.params.map((t)=>t.name),columns:e.cols,isExplain:e.isExplain,isReadonly:e.isReadonly}}class Fl{constructor(e){this.intMode=e}query(e){return this.#e(e,!0,pb)}queryRow(e){return this.#e(e,!0,mb)}queryValue(e){return this.#e(e,!0,hb)}run(e){return this.#e(e,!1,Ra)}#e(e,t,r){let i=gb(this._sqlOwner(),e,t);return this._execute(i).then((n)=>r(n,this.intMode))}batch(e=!1){return new bb(this,e)}describe(e){let t=Jf(this._sqlOwner(),e);return this._describe(t).then(V5)}sequence(e){let t=Jf(this._sqlOwner(),e);return this._sequence(t)}intMode}var Sb=S(()=>{R$();Kf();Ml();yb()});class Wf{}var Aye=1000,$ye=10,O$;var W5=S(()=>{Pt();O$=class O$ extends Wf{#e;#t;#r;#n;#i;#o;#a;constructor(e,t,r){super();this.#e=e,this.#t=t,this.#r=r,this.#n=new ms,this.#i=new ms,this.#o=void 0,this.#a=!1}async next(){for(;;){if(this.#o!==void 0)throw new Ot("Cursor is closed",this.#o);while(!this.#a&&this.#i.length<$ye)this.#i.push(this.#s());let e=this.#n.shift();if(this.#a||e!==void 0)return e;await this.#i.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:Aye}).then((e)=>e,(e)=>{this._setClosed(e);return})}_setClosed(e){if(this.#o!==void 0)return;this.#o=e,this.#t._sendCursorRequest(this,{type:"close_cursor",cursorId:this.#r}).catch(()=>{return}),this.#t._cursorClosed(this)}close(){this._setClosed(new st("Cursor was manually closed"))}get closed(){return this.#o!==void 0}}});var Gf;var P$=S(()=>{Pt();Sb();W5();Gf=class Gf extends Fl{#e;#t;#r;#n;#i;#o;static open(e){let t=e._streamIdAlloc.alloc(),r=new Gf(e,t),i=()=>{return},n=(s)=>r.#l(s),o={type:"open_stream",streamId:t};return e._sendRequest(o,{responseCallback:i,errorCallback:n}),r}constructor(e,t){super(e.intMode);this.#e=e,this.#t=t,this.#r=new ms,this.#n=void 0,this.#i=!1,this.#o=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 xr("Cursor not associated with the stream attempted to execute a request");return new Promise((r,i)=>{if(this.#o!==void 0)i(new Ot("Stream is closed",this.#o));else this.#e._sendRequest(t,{responseCallback:r,errorCallback:i})})}_cursorClosed(e){if(e!==this.#n)throw new xr("Cursor was closed, but it was not associated with the stream");this.#n=void 0,this.#c()}#s(e){if(this.#o!==void 0)e.errorCallback(new Ot("Stream is closed",this.#o));else if(this.#i)e.errorCallback(new Ot("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.#i){this.#l(new st("Stream was gracefully closed"));break}else if(e?.type==="request"&&this.#n===void 0){let{request:t,responseCallback:r,errorCallback:i}=e;this.#r.shift(),this.#e._sendRequest(t,{responseCallback:r,errorCallback:i})}else if(e?.type==="cursor"&&this.#n===void 0){let{batch:t,cursorCallback:r}=e;this.#r.shift();let i=this.#e._cursorIdAlloc.alloc(),n=new O$(this.#e,this,i),o={type:"open_cursor",streamId:this.#t,cursorId:i,batch:t},s=()=>{return},a=(c)=>n._setClosed(c);this.#e._sendRequest(o,{responseCallback:s,errorCallback:a}),this.#n=n,r(n)}else break}}#l(e){if(this.#o!==void 0)return;if(this.#o=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),i=()=>{return};this.#e._sendRequest(t,{responseCallback:r,errorCallback:i})}close(){this.#l(new st("Stream was manually closed"))}closeGracefully(){this.#i=!0,this.#c()}get closed(){return this.#o!==void 0||this.#i}}});function Qf(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,G5),e.arrayObjects("named_args",t.namedArgs,Cye),e.boolean("want_rows",t.wantRows)}function Cye(e,t){e.string("name",t.name),e.object("value",t.value,G5)}function Hl(e,t){e.arrayObjects("steps",t.steps,Rye)}function Rye(e,t){if(t.condition!==void 0)e.object("condition",t.condition,z$);e.object("stmt",t.stmt,Qf)}function z$(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,z$);else if(t.type==="and"||t.type==="or")e.arrayObjects("conds",t.conds,z$);else if(t.type==="is_autocommit");else throw rt(t,"Impossible type of BatchCond")}function G5(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",Pl.fromUint8Array(t));else if(t===void 0);else throw rt(t,"Impossible type of Value")}var N$=S(()=>{lb();wn()});function Q5(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,Oye);else throw rt(t,"Impossible type of ClientMsg")}function Oye(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,Qf);else if(t.type==="batch")e.number("stream_id",t.streamId),e.object("batch",t.batch,Hl);else if(t.type==="open_cursor")e.number("stream_id",t.streamId),e.number("cursor_id",t.cursorId),e.object("batch",t.batch,Hl);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 rt(t,"Impossible type of Request")}var Y5=S(()=>{N$();wn()});function Yf(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,e8);for(let r of t.namedArgs)e.message(4,r,Pye);e.bool(5,t.wantRows)}function Pye(e,t){e.string(1,t.name),e.message(2,t.value,e8)}function Kl(e,t){for(let r of t.steps)e.message(1,r,zye)}function zye(e,t){if(t.condition!==void 0)e.message(1,t.condition,D$);e.message(2,t.stmt,Yf)}function D$(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,D$);else if(t.type==="and")e.message(4,t.conds,X5);else if(t.type==="or")e.message(5,t.conds,X5);else if(t.type==="is_autocommit")e.message(6,void 0,t8);else throw rt(t,"Impossible type of BatchCond")}function X5(e,t){for(let r of t)e.message(1,r,D$)}function e8(e,t){if(t===null)e.message(1,void 0,t8);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 rt(t,"Impossible type of Value")}function t8(e,t){}var L$=S(()=>{wn()});function r8(e,t){if(t.type==="hello")e.message(1,t,Nye);else if(t.type==="request")e.message(2,t,Dye);else throw rt(t,"Impossible type of ClientMsg")}function Nye(e,t){if(t.jwt!==void 0)e.string(1,t.jwt)}function Dye(e,t){e.int32(1,t.requestId);let r=t.request;if(r.type==="open_stream")e.message(2,r,Lye);else if(r.type==="close_stream")e.message(3,r,Bye);else if(r.type==="execute")e.message(4,r,jye);else if(r.type==="batch")e.message(5,r,Uye);else if(r.type==="open_cursor")e.message(6,r,qye);else if(r.type==="close_cursor")e.message(7,r,Zye);else if(r.type==="fetch_cursor")e.message(8,r,Mye);else if(r.type==="sequence")e.message(9,r,Fye);else if(r.type==="describe")e.message(10,r,Hye);else if(r.type==="store_sql")e.message(11,r,Kye);else if(r.type==="close_sql")e.message(12,r,Jye);else if(r.type==="get_autocommit")e.message(13,r,Vye);else throw rt(r,"Impossible type of Request")}function Lye(e,t){e.int32(1,t.streamId)}function Bye(e,t){e.int32(1,t.streamId)}function jye(e,t){e.int32(1,t.streamId),e.message(2,t.stmt,Yf)}function Uye(e,t){e.int32(1,t.streamId),e.message(2,t.batch,Kl)}function qye(e,t){e.int32(1,t.streamId),e.int32(2,t.cursorId),e.message(3,t.batch,Kl)}function Zye(e,t){e.int32(1,t.cursorId)}function Mye(e,t){e.int32(1,t.cursorId),e.uint32(2,t.maxCount)}function Fye(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 Hye(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 Kye(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function Jye(e,t){e.int32(1,t.sqlId)}function Vye(e,t){e.int32(1,t.streamId)}var n8=S(()=>{L$();wn()});function hs(e){let t=Fr(e.message),r=sn(e.code);return{message:t,code:r}}function Xf(e){let t=qn(e.cols,i8),r=qf(e.rows).map((s)=>qn(s,o8)),i=Yi(e.affected_row_count),n=sn(e.last_insert_rowid),o=n!==void 0?BigInt(n):void 0;return{cols:t,rows:r,affectedRowCount:i,lastInsertRowid:o}}function i8(e){let t=sn(e.name),r=sn(e.decltype);return{name:t,decltype:r}}function xb(e){let t=new Map;qf(e.step_results).forEach((i,n)=>{if(i!==null)t.set(n,Xf(Lt(i)))});let r=new Map;return qf(e.step_errors).forEach((i,n)=>{if(i!==null)r.set(n,hs(Lt(i)))}),{stepResults:t,stepErrors:r}}function wb(e){let t=Fr(e.type);if(t==="step_begin"){let r=Yi(e.step),i=qn(e.cols,i8);return{type:"step_begin",step:r,cols:i}}else if(t==="step_end"){let r=Yi(e.affected_row_count),i=sn(e.last_insert_rowid),n=i!==void 0?BigInt(i):void 0;return{type:"step_end",affectedRowCount:r,lastInsertRowid:n}}else if(t==="step_error"){let r=Yi(e.step),i=hs(Lt(e.error));return{type:"step_error",step:r,error:i}}else if(t==="row")return{type:"row",row:qn(e.row,o8)};else if(t==="error")return{type:"error",error:hs(Lt(e.error))};else throw new je("Unexpected type of CursorEntry")}function vb(e){let t=qn(e.params,Wye),r=qn(e.cols,Gye),i=ds(e.is_explain),n=ds(e.is_readonly);return{params:t,cols:r,isExplain:i,isReadonly:n}}function Wye(e){return{name:sn(e.name)}}function Gye(e){let t=Fr(e.name),r=sn(e.decltype);return{name:t,decltype:r}}function o8(e){let t=Fr(e.type);if(t==="null")return null;else if(t==="integer"){let r=Fr(e.value);return BigInt(r)}else if(t==="float")return Yi(e.value);else if(t==="text")return Fr(e.value);else if(t==="blob")return Pl.toUint8Array(Fr(e.base64));else throw new je("Unexpected type of Value")}var _b=S(()=>{lb();Pt();ql()});function s8(e){let t=Fr(e.type);if(t==="hello_ok")return{type:"hello_ok"};else if(t==="hello_error")return{type:"hello_error",error:hs(Lt(e.error))};else if(t==="response_ok"){let r=Yi(e.request_id),i=Qye(Lt(e.response));return{type:"response_ok",requestId:r,response:i}}else if(t==="response_error"){let r=Yi(e.request_id),i=hs(Lt(e.error));return{type:"response_error",requestId:r,error:i}}else throw new je("Unexpected type of ServerMsg")}function Qye(e){let t=Fr(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:Xf(Lt(e.result))};else if(t==="batch")return{type:"batch",result:xb(Lt(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=qn(e.entries,wb),i=ds(e.done);return{type:"fetch_cursor",entries:r,done:i}}else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:vb(Lt(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:ds(e.is_autocommit)};else throw new je("Unexpected type of Response")}var a8=S(()=>{Pt();ql();_b()});var vn,gs,c8,l8,Jl,Yye,Xye,kb,ebe,tbe,rbe,Vl,nbe,ibe,obe;var Eb=S(()=>{vn={default(){return{message:"",code:void 0}},1(e,t){t.message=e.string()},2(e,t){t.code=e.string()}},gs={default(){return{cols:[],rows:[],affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.cols.push(e.message(c8))},2(e,t){t.rows.push(e.message(l8))},3(e,t){t.affectedRowCount=Number(e.uint64())},4(e,t){t.lastInsertRowid=e.sint64()}},c8={default(){return{name:void 0,decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},l8={default(){return[]},1(e,t){t.push(e.message(obe))}},Jl={default(){return{stepResults:new Map,stepErrors:new Map}},1(e,t){let[r,i]=e.message(Yye);t.stepResults.set(r,i)},2(e,t){let[r,i]=e.message(Xye);t.stepErrors.set(r,i)}},Yye={default(){return[0,gs.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(gs)}},Xye={default(){return[0,vn.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(vn)}},kb={default(){return{type:"none"}},1(e){return e.message(ebe)},2(e){return e.message(tbe)},3(e){return e.message(rbe)},4(e){return{type:"row",row:e.message(l8)}},5(e){return{type:"error",error:e.message(vn)}}},ebe={default(){return{type:"step_begin",step:0,cols:[]}},1(e,t){t.step=e.uint32()},2(e,t){t.cols.push(e.message(c8))}},tbe={default(){return{type:"step_end",affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.affectedRowCount=e.uint32()},2(e,t){t.lastInsertRowid=e.uint64()}},rbe={default(){return{type:"step_error",step:0,error:vn.default()}},1(e,t){t.step=e.uint32()},2(e,t){t.error=e.message(vn)}},Vl={default(){return{params:[],cols:[],isExplain:!1,isReadonly:!1}},1(e,t){t.params.push(e.message(nbe))},2(e,t){t.cols.push(e.message(ibe))},3(e,t){t.isExplain=e.bool()},4(e,t){t.isReadonly=e.bool()}},nbe={default(){return{name:void 0}},1(e,t){t.name=e.string()}},ibe={default(){return{name:"",decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},obe={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 u8,sbe,abe,cbe,lbe,ube,dbe,fbe,pbe;var d8=S(()=>{Eb();u8={default(){return{type:"none"}},1(e){return{type:"hello_ok"}},2(e){return e.message(sbe)},3(e){return e.message(cbe)},4(e){return e.message(abe)}},sbe={default(){return{type:"hello_error",error:vn.default()}},1(e,t){t.error=e.message(vn)}},abe={default(){return{type:"response_error",requestId:0,error:vn.default()}},1(e,t){t.requestId=e.int32()},2(e,t){t.error=e.message(vn)}},cbe={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(lbe)},5(e,t){t.response=e.message(ube)},6(e,t){t.response={type:"open_cursor"}},7(e,t){t.response={type:"close_cursor"}},8(e,t){t.response=e.message(dbe)},9(e,t){t.response={type:"sequence"}},10(e,t){t.response=e.message(fbe)},11(e,t){t.response={type:"store_sql"}},12(e,t){t.response={type:"close_sql"}},13(e,t){t.response=e.message(pbe)}},lbe={default(){return{type:"execute",result:gs.default()}},1(e,t){t.result=e.message(gs)}},ube={default(){return{type:"batch",result:Jl.default()}},1(e,t){t.result=e.message(Jl)}},dbe={default(){return{type:"fetch_cursor",entries:[],done:!1}},1(e,t){t.entries.push(e.message(kb))},2(e,t){t.done=e.bool()}},fbe={default(){return{type:"describe",result:Vl.default()}},1(e,t){t.result=e.message(Vl)}},pbe={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}}});var f8,B$,Ib;var Tb=S(()=>{I$();Pt();T$();Kf();Ml();wn();P$();Y5();n8();a8();d8();f8=new Map([["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]),B$=new Map([["hrana3-protobuf",{version:3,encoding:"protobuf"}],["hrana3",{version:3,encoding:"json"}],["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]);Ib=class Ib extends Bl{#e;#t;#r;#n;#i;#o;#a;#s;#c;_streamIdAlloc;_cursorIdAlloc;#l;constructor(e,t){super();this.#e=e,this.#t=[],this.#r=!1,this.#n=void 0,this.#i=!1,this.#o=void 0,this.#a=!1,this.#s=new Map,this.#c=new ps,this._streamIdAlloc=new ps,this._cursorIdAlloc=new ps,this.#l=new ps,this.#e.binaryType="arraybuffer",this.#e.addEventListener("open",()=>this.#f()),this.#e.addEventListener("close",(r)=>this.#g(r)),this.#e.addEventListener("error",(r)=>this.#p(r)),this.#e.addEventListener("message",(r)=>this.#y(r)),this.#d({type:"hello",jwt:t})}#d(e){if(this.#n!==void 0)throw new xr("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})}}#f(){let e=this.#e.protocol;if(e===void 0){this.#u(new st("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.#o={version:1,encoding:"json"};else if(this.#o=B$.get(e),this.#o===void 0){this.#u(new je(`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.#o.encoding;if(t==="json"){let r=Zf(e,Q5);this.#e.send(r)}else if(t==="protobuf"){let r=Hf(e,r8);this.#e.send(r)}else throw rt(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.#o.version);this.#t.push({openCallback:r,errorCallback:t})}else e(this.#o.version)})}_ensureVersion(e,t){if(this.#o===void 0||!this.#a)throw new Un(`${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.#o.version<e)throw new Un(`${t} is supported on protocol version ${e} and higher, but the WebSocket server only supports version ${this.#o.version}`)}_sendRequest(e,t){if(this.#n!==void 0){t.errorCallback(new Ot("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})}#p(e){let r=e.message??"WebSocket was closed due to an error";this.#u(new jl(r))}#g(e){let t=`WebSocket was closed with code ${e.code}`;if(e.reason)t+=`: ${e.reason}`;this.#u(new jl(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.#o.encoding;if(r==="json"){if(typeof e.data!=="string"){this.#e.close(3003,"Only text messages are accepted with JSON encoding"),this.#u(new je("Received non-text message from server with JSON encoding"));return}t=$a(JSON.parse(e.data),s8)}else if(r==="protobuf"){if(!(e.data instanceof ArrayBuffer)){this.#e.close(3003,"Only binary messages are accepted with Protobuf encoding"),this.#u(new je("Received non-binary message from server with Protobuf encoding"));return}t=fs(new Uint8Array(e.data),u8)}else throw rt(r,"Impossible encoding");this.#h(t)}catch(t){this.#e.close(3007,"Could not handle message"),this.#u(t)}}#h(e){if(e.type==="none")throw new je("Received an unrecognized ServerMsg");else if(e.type==="hello_ok"||e.type==="hello_error"){if(this.#i)throw new je("Received a duplicated hello response");if(this.#i=!0,e.type==="hello_error")throw Xi(e.error);return}else if(!this.#i)throw new je("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 je("Received unexpected OK response");this.#c.free(t);try{if(r.type!==e.response.type)throw console.dir({responseState:r,msg:e}),new je("Received unexpected type of response");r.responseCallback(e.response)}catch(i){throw r.errorCallback(i),i}}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 je("Received unexpected error response");this.#c.free(t),r.errorCallback(Xi(e.error))}else throw rt(e,"Impossible ServerMsg type")}openStream(){return Gf.open(this)}storeSql(e){this._ensureVersion(2,"storeSql()");let t=this.#l.alloc(),r=new Oa(this,t),i=()=>{return},n=(s)=>r._setClosed(s),o={type:"store_sql",sqlId:t,sql:e};return this._sendRequest(o,{responseCallback:i,errorCallback:n}),r}_closeSql(e){if(this.#n!==void 0)return;let t=()=>this.#l.free(e),r=(n)=>this.#u(n),i={type:"close_sql",sqlId:e};this._sendRequest(i,{responseCallback:t,errorCallback:r})}close(){this.#u(new st("Client was manually closed"))}get closed(){return this.#n!==void 0}}});var Pa;var p8=S(()=>{if(typeof queueMicrotask<"u")Pa=queueMicrotask;else{let e=Promise.resolve();Pa=(t)=>{e.then(t)}}});class j${#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 i=new Uint8Array(new ArrayBuffer(r));i.set(this.#e.slice(this.#t,this.#r),0),this.#e=i}this.#r=t,this.#t=0}shift(e){this.#t+=e}}function m8(e){let t=sn(e.baton),r=sn(e.base_url),i=qn(e.results,mbe);return{baton:t,baseUrl:r,results:i}}function mbe(e){let t=Fr(e.type);if(t==="ok")return{type:"ok",response:hbe(Lt(e.response))};else if(t==="error")return{type:"error",error:hs(Lt(e.error))};else throw new je("Unexpected type of StreamResult")}function hbe(e){let t=Fr(e.type);if(t==="close")return{type:"close"};else if(t==="execute")return{type:"execute",result:Xf(Lt(e.result))};else if(t==="batch")return{type:"batch",result:xb(Lt(e.result))};else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:vb(Lt(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:ds(e.is_autocommit)};else throw new je("Unexpected type of StreamResponse")}function h8(e){let t=sn(e.baton),r=sn(e.base_url);return{baton:t,baseUrl:r}}var U$=S(()=>{Pt();ql();_b()});var g8,gbe,ybe,bbe,Sbe,xbe,wbe,y8;var q$=S(()=>{Eb();g8={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(gbe))}},gbe={default(){return{type:"none"}},1(e){return{type:"ok",response:e.message(ybe)}},2(e){return{type:"error",error:e.message(vn)}}},ybe={default(){return{type:"none"}},1(e){return{type:"close"}},2(e){return e.message(bbe)},3(e){return e.message(Sbe)},4(e){return{type:"sequence"}},5(e){return e.message(xbe)},6(e){return{type:"store_sql"}},7(e){return{type:"close_sql"}},8(e){return e.message(wbe)}},bbe={default(){return{type:"execute",result:gs.default()}},1(e,t){t.result=e.message(gs)}},Sbe={default(){return{type:"batch",result:Jl.default()}},1(e,t){t.result=e.message(Jl)}},xbe={default(){return{type:"describe",result:Vl.default()}},1(e,t){t.result=e.message(Vl)}},wbe={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}},y8={default(){return{baton:void 0,baseUrl:void 0}},1(e,t){t.baton=e.string()},2(e,t){t.baseUrl=e.string()}}});var Z$;var b8=S(()=>{ql();k$();Pt();wn();U$();q$();_b();Eb();Z$=class Z$ extends Wf{#e;#t;#r;#n;#i;#o;constructor(e,t){super();this.#e=e,this.#t=t,this.#r=void 0,this.#n=new j$(16384),this.#i=void 0,this.#o=!1}async open(e){if(e.body===null)throw new je("No response body for cursor request");this.#r=e.body[Symbol.asyncIterator]();let t=await this.#a(h8,y8);if(t===void 0)throw new je("Empty response to cursor request");return t}next(){return this.#a(wb,kb)}close(){this._setClosed(new st("Cursor was manually closed"))}_setClosed(e){if(this.#i!==void 0)return;if(this.#i=e,this.#e._cursorClosed(this),this.#r!==void 0)this.#r.return()}get closed(){return this.#i!==void 0}async#a(e,t){for(;;){if(this.#o)return;else if(this.#i!==void 0)throw new Ot("Cursor is closed",this.#i);if(this.#t==="json"){let n=this.#s();if(n!==void 0){let o=new TextDecoder().decode(n),s=JSON.parse(o);return $a(s,e)}}else if(this.#t==="protobuf"){let n=this.#c();if(n!==void 0)return fs(n,t)}else throw rt(this.#t,"Impossible encoding");if(this.#r===void 0)throw new xr("Attempted to read from HTTP cursor before it was opened");let{value:r,done:i}=await this.#r.next();if(i&&this.#n.length===0)this.#o=!0;else if(i)throw new je("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 i=e.slice(0,r);return this.#n.shift(r+1),i}#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 i=e.slice(r,r+t);return this.#n.shift(r+t),i}}});function S8(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.arrayObjects("requests",t.requests,vbe)}function vbe(e,t){if(e.stringRaw("type",t.type),t.type==="close");else if(t.type==="execute")e.object("stmt",t.stmt,Qf);else if(t.type==="batch")e.object("batch",t.batch,Hl);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 rt(t,"Impossible type of StreamRequest")}function x8(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.object("batch",t.batch,Hl)}var M$=S(()=>{N$();wn()});function w8(e,t){if(t.baton!==void 0)e.string(1,t.baton);for(let r of t.requests)e.message(2,r,_be)}function _be(e,t){if(t.type==="close")e.message(1,t,kbe);else if(t.type==="execute")e.message(2,t,Ebe);else if(t.type==="batch")e.message(3,t,Ibe);else if(t.type==="sequence")e.message(4,t,Tbe);else if(t.type==="describe")e.message(5,t,Abe);else if(t.type==="store_sql")e.message(6,t,$be);else if(t.type==="close_sql")e.message(7,t,Cbe);else if(t.type==="get_autocommit")e.message(8,t,Rbe);else throw rt(t,"Impossible type of StreamRequest")}function kbe(e,t){}function Ebe(e,t){e.message(1,t.stmt,Yf)}function Ibe(e,t){e.message(1,t.batch,Kl)}function Tbe(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function Abe(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function $be(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function Cbe(e,t){e.int32(1,t.sqlId)}function Rbe(e,t){}function v8(e,t){if(t.baton!==void 0)e.string(1,t.baton);e.message(2,t.batch,Kl)}var F$=S(()=>{L$();wn()});function Obe(e,t){if(t.results.length!==e.length)throw new je("Server returned unexpected number of pipeline results");for(let r=0;r<e.length;++r){let i=t.results[r],n=e[r];if(i.type==="ok"){if(i.response.type!==n.request.type)throw new je("Received unexpected type of response");n.responseCallback(i.response)}else if(i.type==="error")n.errorCallback(Xi(i.error));else if(i.type==="none")throw new je("Received unrecognized type of StreamResult");else throw rt(i,"Received impossible type of StreamResult")}}async function Pbe(e,t){if(t==="json"){let r=await e.json();return $a(r,m8)}if(t==="protobuf"){let r=await e.arrayBuffer();return fs(new Uint8Array(r),g8)}throw await e.body?.cancel(),rt(t,"Impossible encoding")}async function zbe(e){let t=e.headers.get("content-type")??"text/plain",r=`Server returned HTTP status ${e.status}`;if(t==="application/json"){let i=await e.json();if("message"in i)return Xi(i);return new Aa(r,e.status)}if(t==="text/plain"){let i=(await e.text()).trim();if(i!=="")r+=`: ${i}`;return new Aa(r,e.status)}return await e.body?.cancel(),new Aa(r,e.status)}var Ab;var H$=S(()=>{Pt();I$();T$();p8();Kf();Ml();Sb();wn();b8();M$();F$();M$();F$();U$();q$();Ab=class Ab extends Fl{#e;#t;#r;#n;#i;#o;#a;#s;#c;#l;#d;#f;#m;constructor(e,t,r,i,n){super(e.intMode);this.#e=e,this.#t=t.toString(),this.#r=r,this.#n=i,this.#i=n,this.#o=void 0,this.#a=new ms,this.#s=!1,this.#l=!1,this.#d=!1,this.#f=void 0,this.#m=new ps}client(){return this.#e}_sqlOwner(){return this}storeSql(e){let t=this.#m.alloc();return this.#p({type:"store_sql",sqlId:t,sql:e}).then(()=>{return},(r)=>this._setClosed(r)),new Oa(this,t)}_closeSql(e){if(this.#f!==void 0)return;this.#p({type:"close_sql",sqlId:e}).then(()=>this.#m.free(e),(t)=>this._setClosed(t))}_execute(e){return this.#p({type:"execute",stmt:e}).then((t)=>t.result)}_batch(e){return this.#p({type:"batch",batch:e}).then((t)=>t.result)}_describe(e){return this.#p({type:"describe",sql:e.sql,sqlId:e.sqlId}).then((t)=>t.result)}_sequence(e){return this.#p({type:"sequence",sql:e.sql,sqlId:e.sqlId}).then((t)=>{return})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#p({type:"get_autocommit"}).then((e)=>e.isAutocommit)}#p(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 xr("Cursor was closed, but it was not associated with the stream");this.#c=void 0,Pa(()=>this.#u())}close(){this._setClosed(new st("Stream was manually closed"))}closeGracefully(){this.#l=!0,Pa(()=>this.#u())}get closed(){return this.#f!==void 0||this.#l}_setClosed(e){if(this.#f!==void 0)return;if(this.#f=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.#o!==void 0||this.#s)&&!this.#d)this.#a.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0,Pa(()=>this.#u())}#g(e){if(this.#f!==void 0)throw new Ot("Stream is closed",this.#f);else if(this.#l)throw new Ot("Stream is closing",void 0);else this.#a.push(e),Pa(()=>this.#u())}#u(){if(this.#s||this.#c!==void 0)return;if(this.#l&&this.#a.length===0){this._setClosed(new st("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 i=this.#a.first();if(i!==void 0&&i.type==="pipeline")r.push(i),this.#a.shift();else if(i===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.#h(e,t);else throw rt(t,"Impossible type of QueueEntry")}#y(e,t){this.#b(()=>this.#S(t,e),(r)=>Pbe(r,e.encoding),(r)=>r.baton,(r)=>r.baseUrl,(r)=>Obe(t,r),(r)=>t.forEach((i)=>i.errorCallback(r)))}#h(e,t){let r=new Z$(this,e.encoding);this.#c=r,this.#b(()=>this.#w(t,e),(i)=>r.open(i),(i)=>i.baton,(i)=>i.baseUrl,(i)=>t.cursorCallback(r),(i)=>t.errorCallback(i))}#b(e,t,r,i,n,o){let s;try{let a=e(),c=this.#n;s=c(a)}catch(a){s=Promise.reject(a)}this.#s=!0,s.then((a)=>{if(!a.ok)return zbe(a).then((c)=>{throw c});return t(a)}).then((a)=>{this.#o=r(a),this.#t=i(a)??this.#t,n(a)}).catch((a)=>{this._setClosed(a),o(a)}).finally(()=>{this.#s=!1,this.#u()})}#S(e,t){return this.#x(new URL(t.pipelinePath,this.#t),{baton:this.#o,requests:e.map((r)=>r.request)},t.encoding,S8,w8)}#w(e,t){if(t.cursorPath===void 0)throw new Un(`Cursors are supported only on protocol version 3 and higher, but the HTTP server only supports version ${t.version}.`);return this.#x(new URL(t.cursorPath,this.#t),{baton:this.#o,batch:e.batch},t.encoding,x8,v8)}#x(e,t,r,i,n){let o,s;if(r==="json")o=Zf(t,i),s="application/json";else if(r==="protobuf")o=Hf(t,n),s="application/x-protobuf";else throw rt(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.#i!==void 0)a.set("x-turso-encryption-key",this.#i);return new Request(e.toString(),{method:"POST",headers:a,body:o})}}});async function Dbe(e,t){let r=e;for(let i of Nbe){let n=new URL(i.versionPath,t),o=new Request(n.toString(),{method:"GET"}),s=await r(o);if(await s.arrayBuffer(),s.ok)return i}return K$}var Nbe,K$,$b;var J$=S(()=>{Pt();H$();Nbe=[{versionPath:"v3-protobuf",pipelinePath:"v3-protobuf/pipeline",cursorPath:"v3-protobuf/cursor",version:3,encoding:"protobuf"}],K$={versionPath:"v2",pipelinePath:"v2/pipeline",cursorPath:void 0,version:2,encoding:"json"};$b=class $b extends Bl{#e;#t;#r;#n;#i;#o;_endpointPromise;_endpoint;constructor(e,t,r,i,n=2){super();if(this.#e=e,this.#t=t,this.#r=r??globalThis.fetch,this.#n=i,this.#i=void 0,this.#o=new Set,n==3)this._endpointPromise=Dbe(this.#r,this.#e),this._endpointPromise.then((o)=>this._endpoint=o,(o)=>this.#a(o));else this._endpointPromise=Promise.resolve(K$),this._endpointPromise.then((o)=>this._endpoint=o,(o)=>this.#a(o))}async getVersion(){if(this._endpoint!==void 0)return this._endpoint.version;return(await this._endpointPromise).version}_ensureVersion(e,t){if(e<=K$.version)return;else if(this._endpoint===void 0)throw new Un(`${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 Un(`${t} is supported only on protocol version ${e} and higher, but the HTTP server only supports version ${this._endpoint.version}.`)}openStream(){if(this.#i!==void 0)throw new Ot("Client is closed",this.#i);let e=new Ab(this,this.#e,this.#t,this.#r,this.#n);return this.#o.add(e),e}_streamClosed(e){this.#o.delete(e)}close(){this.#a(new st("Client was manually closed"))}get closed(){return this.#i!==void 0}#a(e){if(this.#i!==void 0)return;this.#i=e;for(let t of Array.from(this.#o))t._setClosed(new Ot("Client was closed",e))}}});var _8=S(()=>{Pt()});function V$(e,t,r=2){if(typeof us>"u")throw new Uf("WebSockets are not supported in this environment");var i=void 0;if(r==3)i=Array.from(B$.keys());else i=Array.from(f8.keys());let n=new us(e,i);return new Ib(n,t)}function W$(e,t,r,i,n=2){return new $b(e instanceof URL?e:new URL(e),t,r,i,n)}var Cb=S(()=>{_$();Tb();Pt();J$();Tb();_$();R$();_8();Ml();yb();Sb();J$();H$();Tb();P$();Pt()});class ep{#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 Be("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{let r=e.map(eo),i;if(this.#r===void 0){this._getSqlCache().apply(r);let o=t.batch(this.#t>=3),s=o.step(),a=s.run(cs(this.#e)),c=s;i=r.map((l)=>{let u=o.step().condition(wt.ok(c));if(this.#t>=3)u.condition(wt.not(wt.isAutocommit(o)));let f=u.query(l);return f.catch(()=>{return}),c=u,f}),this.#r=o.execute().then(()=>a).then(()=>{return});try{await this.#r}catch(l){throw this.close(),l}}else{if(this.#t<3)await this.#r;this._getSqlCache().apply(r);let o=t.batch(this.#t>=3),s=void 0;i=r.map((a)=>{let c=o.step();if(s!==void 0)c.condition(wt.ok(s));if(this.#t>=3)c.condition(wt.not(wt.isAutocommit(o)));let l=c.query(a);return l.catch(()=>{return}),s=c,l}),await o.execute()}let n=[];for(let o=0;o<i.length;o++)try{let s=await i[o];if(s===void 0)throw new cr("Statement in a transaction was not executed, probably because the transaction has been rolled back",o,"TRANSACTION_CLOSED");n.push(Gl(s))}catch(s){if(s instanceof cr)throw s;let a=yt(s);if(a instanceof Be)throw new cr(a.message,o,a.code,a.extendedCode,a.rawCode,a.cause instanceof Error?a.cause:void 0);throw a}return n}catch(r){throw yt(r)}}async executeMultiple(e){let t=this._getStream();if(t.closed)throw new Be("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{if(this.#r===void 0){this.#r=t.run(cs(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 yt(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 yt(r)});e.closeGracefully(),await t}catch(e){throw yt(e)}finally{this.close()}}async commit(){try{let e=this._getStream();if(e.closed)throw new Be("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 yt(r)});e.closeGracefully(),await t}catch(e){throw yt(e)}finally{this.close()}}}async function Wl(e,t,r,i,n=!1){if(n)r.step().run("PRAGMA foreign_keys=off");let o=r.step(),s=o.run(cs(e)),a=o,c=i.map((m)=>{let y=r.step().condition(wt.ok(a));if(t>=3)y.condition(wt.not(wt.isAutocommit(r)));let g=y.query(m);return a=y,g}),l=r.step().condition(wt.ok(a));if(t>=3)l.condition(wt.not(wt.isAutocommit(r)));let u=l.run("COMMIT");if(r.step().condition(wt.not(wt.ok(l))).run("ROLLBACK").catch((m)=>{return}),n)r.step().run("PRAGMA foreign_keys=on");await r.execute();let p=[];await s;for(let m=0;m<c.length;m++)try{let y=await c[m];if(y===void 0)throw new cr("Statement in a batch was not executed, probably because the transaction has been rolled back",m,"TRANSACTION_CLOSED");p.push(Gl(y))}catch(y){if(y instanceof cr)throw y;let g=yt(y);if(g instanceof Be)throw new cr(g.message,m,g.code,g.extendedCode,g.rawCode,g.cause instanceof Error?g.cause:void 0);throw g}return await u,p}function eo(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 i=new Vf(t);if(r)if(Array.isArray(r))i.bindIndexes(r);else for(let[n,o]of Object.entries(r))i.bindName(n,o);return i}function Gl(e){let t=e.columnNames.map((s)=>s??""),r=e.columnDecltypes.map((s)=>s??""),i=e.rows,n=e.affectedRowCount,o=e.lastInsertRowid!==void 0?e.lastInsertRowid:void 0;return new zl(t,r,i,n,o)}function yt(e){if(e instanceof st){let t=k8(e);return new Be(e.message,t,void 0,void 0,e)}return e}function k8(e){if(e instanceof jf&&e.code!==void 0)return e.code;else if(e instanceof je)return"HRANA_PROTO_ERROR";else if(e instanceof Ot)return e.cause instanceof st?k8(e.cause):"HRANA_CLOSED_ERROR";else if(e instanceof jl)return"HRANA_WEBSOCKET_ERROR";else if(e instanceof Aa)return"SERVER_ERROR";else if(e instanceof Un)return"PROTOCOL_VERSION_ERROR";else if(e instanceof xr)return"INTERNAL_ERROR";else return"UNKNOWN"}var Q$=S(()=>{Cb();jn();Nl()});class Ql{#e;#t;capacity;constructor(e,t){this.#e=e,this.#t=new E8,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 i=r.sql;if(i.length>=5000)continue;let n=this.#t.get(i);if(n===void 0){while(this.#t.size+1>this.capacity){let[o,s]=this.#t.peekLru();if(t.has(s))break;s.close(),this.#t.delete(o)}if(this.#t.size+1<=this.capacity)n=this.#e.storeSql(i),this.#t.set(i,n)}if(n!==void 0)r.sql=n,t.add(n)}}}class E8{#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 Y$=Se(function(Y3e,T8){function Lbe(e){var t=0,r=[];function i(){if(t--,t<e)n()}function n(){var c=r.shift();if(a.queue=r.length,c)s(c.fn).then(c.resolve).catch(c.reject)}function o(c){return new Promise(function(l,u){r.push({fn:c,resolve:l,reject:u}),a.queue=r.length})}function s(c){t++;try{return Promise.resolve(c()).then(function(l){return i(),l},function(l){throw i(),l})}catch(l){return i(),Promise.reject(l)}}var a=function(c){if(t>=e)return o(c);else return s(c)};return a}function Bbe(e,t){var r=!1,i=this;return Promise.all(e.map(function(){var n=arguments;return i(function(){if(!r)return t.apply(void 0,n).catch(function(o){throw r=!0,o})})}))}function I8(e){return e.queue=0,e.map=Bbe,e}T8.exports=function(e){if(e)return I8(Lbe(e));else return I8(function(t){return t()})}});function C8(e){if(e.scheme!=="wss"&&e.scheme!=="ws")throw new Be(`The WebSocket client supports only "libsql:", "wss:" and "ws:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${hi}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Be("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="ws"&&e.tls)throw new Be('A "ws:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="wss"&&!e.tls)throw new Be('A "wss:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=zf(e.scheme,e.authority,e.path),r;try{r=V$(t,e.authToken)}catch(i){if(i instanceof Uf){let n=e.scheme==="wss"?"https":"http",o=zf(n,e.authority,e.path);throw new Be(`This environment does not support WebSockets, please switch to the HTTP client by using a "${n}:" URL (${JSON.stringify(o)}). For more information, please read ${hi}`,"WEBSOCKETS_NOT_SUPPORTED")}throw yt(i)}return new R8(r,t,e.authToken,e.intMode,e.concurrency)}class R8{#e;#t;#r;#n;#i;closed;protocol;#o;#a;constructor(e,t,r,i,n){this.#e=t,this.#t=r,this.#r=i,this.#n=this.#c(e),this.#i=void 0,this.closed=!1,this.protocol="ws",this.#a=$8.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 i=await this.#s();try{let n=eo(r);i.conn.sqlCache.apply([n]);let o=i.stream.query(n);i.stream.closeGracefully();let s=await o;return Gl(s)}catch(n){throw yt(n)}finally{this._closeStream(i)}})}async batch(e,t="deferred"){return this.limit(async()=>{let r=await this.#s();try{let n=e.map((l)=>{if(Array.isArray(l))return{sql:l[0],args:l[1]||[]};return l}).map(eo),o=await r.conn.client.getVersion();r.conn.sqlCache.apply(n);let s=r.stream.batch(o>=3);return await Wl(t,o,s,n)}catch(i){throw yt(i)}finally{this._closeStream(r)}})}async migrate(e){return this.limit(async()=>{let t=await this.#s();try{let r=e.map(eo),i=await t.conn.client.getVersion(),n=t.stream.batch(i>=3);return await Wl("deferred",i,n,r,!0)}catch(r){throw yt(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 O8(this,t,e,r)}catch(r){throw this._closeStream(t),yt(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 yt(r)}finally{this._closeStream(t)}})}sync(){throw new Be("sync not supported in ws mode","SYNC_NOT_SUPPORTED")}async#s(){if(this.closed)throw new Be("The client is closed","CLIENT_CLOSED");if(new Date().valueOf()-this.#n.openTime.valueOf()>jbe&&this.#i===void 0){let i=this.#c();this.#i=i,i.client.getVersion().then((n)=>{if(this.#n!==i){if(this.#n.streamStates.size===0)this.#n.client.close()}this.#n=i,this.#i=void 0},(n)=>{this.#i=void 0})}if(this.#n.client.closed)try{if(this.#i!==void 0)this.#n=this.#i;else this.#n=this.#c()}catch(i){throw yt(i)}let r=this.#n;try{if(r.useSqlCache===void 0){if(r.useSqlCache=await r.client.getVersion()>=2,r.useSqlCache)r.sqlCache.capacity=A8}let i=r.client.openStream();i.intMode=this.#r;let n={conn:r,stream:i};return r.streamStates.add(n),n}catch(i){throw yt(i)}}#c(e){try{return e??=V$(this.#e,this.#t),{client:e,useSqlCache:void 0,sqlCache:new Ql(e,0),openTime:new Date,streamStates:new Set}}catch(t){throw yt(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.#i){try{this.#i.client.close()}catch{}this.#i=void 0}let e=this.#c(),t=await e.client.getVersion();if(e.useSqlCache=t>=2,e.useSqlCache)e.sqlCache.capacity=A8;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.#i){try{this.#i.client.close()}catch{}this.#i=void 0}this.closed=!0}}var $8,jbe=60000,A8=100,O8;var P8=S(()=>{Cb();jn();Lf();Q$();sb();Nl();$8=hu(Y$(),1);jn();O8=class O8 extends ep{#e;#t;constructor(e,t,r,i){super(r,i);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 N8(e){if(e.scheme!=="https"&&e.scheme!=="http")throw new Be(`The HTTP client supports only "libsql:", "https:" and "http:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${hi}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Be("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="http"&&e.tls)throw new Be('A "http:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="https"&&!e.tls)throw new Be('A "https:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=zf(e.scheme,e.authority,e.path);return new L8(t,e.authToken,e.intMode,e.fetch,e.concurrency,e.remoteEncryptionKey)}class L8{#e;protocol;#t;#r;#n;#i;#o;#a;#s;constructor(e,t,r,i,n,o){this.#t=e,this.#o=t,this.#r=r,this.#n=i,this.#i=n,this.#a=o,this.#e=W$(this.#t,this.#o,this.#n,o),this.#e.intMode=this.#r,this.protocol="http",this.#s=z8.default(this.#i)}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 i=eo(r),n,o=this.#e.openStream();try{n=o.query(i)}finally{o.closeGracefully()}let s=await n;return Gl(s)}catch(i){throw yt(i)}})}async batch(e,t="deferred"){return this.limit(async()=>{try{let i=e.map((c)=>{if(Array.isArray(c))return{sql:c[0],args:c[1]||[]};return c}).map(eo),n=await this.#e.getVersion(),o,s=this.#e.openStream();try{new Ql(s,D8).apply(i);let l=s.batch(!1);o=Wl(t,n,l,i)}finally{s.closeGracefully()}return await o}catch(r){throw yt(r)}})}async migrate(e){return this.limit(async()=>{try{let t=e.map(eo),r=await this.#e.getVersion(),i,n=this.#e.openStream();try{let s=n.batch(!1);i=Wl("deferred",r,s,t,!0)}finally{n.closeGracefully()}return await i}catch(t){throw yt(t)}})}async transaction(e="write"){return this.limit(async()=>{try{let t=await this.#e.getVersion();return new B8(this.#e.openStream(),e,t)}catch(t){throw yt(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 yt(t)}})}sync(){throw new Be("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=W$(this.#t,this.#o,this.#n,this.#a),this.#e.intMode=this.#r}}get closed(){return this.#e.closed}}var z8,D8=30,B8;var j8=S(()=>{Cb();jn();Lf();Q$();sb();Nl();z8=hu(Y$(),1);jn();B8=class B8 extends ep{#e;#t;constructor(e,t,r){super(t,r);this.#e=e,this.#t=new Ql(e,D8)}_getStream(){return this.#e}_getSqlCache(){return this.#t}close(){this.#e.close()}get closed(){return this.#e.closed}}});function Yl(e){return Ube(Df(e,!0))}function Ube(e){if(e.scheme==="wss"||e.scheme==="ws")return C8(e);else if(e.scheme==="https"||e.scheme==="http")return N8(e);else return z5(e)}var X$=S(()=>{Lf();j5();P8();j8();jn()});function ae(e,t){if(!e||typeof e!=="object")return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,J))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(J in r&&r[J]===t[J])return!0;r=Object.getPrototypeOf(r)}return!1}var J;var ze=S(()=>{J=Symbol.for("drizzle:entityKind")});var nt;var Zn=S(()=>{ze();nt=class nt{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[J]="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 tp;var Rb=S(()=>{ze();tp=class tp{static[J]="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 wr;var Xl=S(()=>{wr=Symbol.for("drizzle:Name")});var eC,U8;var q8=S(()=>{ze();Xl();eC=class eC{static[J]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,t){if(this.reference=()=>{let{name:r,columns:i,foreignColumns:n}=e();return{name:r,columns:i,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 U8(e,this)}};U8=class U8{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[J]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),i=t.map((s)=>s.name),n=r.map((s)=>s.name),o=[this.table[wr],...i,r[0].table[wr],...n];return e??`${o.join("_")}_fk`}}});function Ob(e,...t){return e(...t)}var tC=()=>{};function rC(e,t){return`${e[wr]}_${t.join("_")}_unique`}var Z8,qbe,M8;var F8=S(()=>{ze();Xl();Z8=class Z8{constructor(e,t){this.name=t,this.columns=e}static[J]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new M8(e,this.columns,this.nullsNotDistinctConfig,this.name)}};qbe=class qbe{static[J]="PgUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new Z8(e,this.name)}};M8=class M8{constructor(e,t,r,i){this.table=e,this.columns=t,this.name=i??rC(this.table,this.columns.map((n)=>n.name)),this.nullsNotDistinct=r}static[J]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}}});function H8(e,t,r){for(let i=t;i<e.length;i++){let n=e[i];if(n==="\\"){i++;continue}if(n==='"')return[e.slice(t,i).replace(/\\/g,""),i+1];if(r)continue;if(n===","||n==="}")return[e.slice(t,i).replace(/\\/g,""),i]}return[e.slice(t).replace(/\\/g,""),e.length]}function K8(e,t=0){let r=[],i=t,n=!1;while(i<e.length){let o=e[i];if(o===","){if(n||i===t)r.push("");n=!0,i++;continue}if(n=!1,o==="\\"){i+=2;continue}if(o==='"'){let[c,l]=H8(e,i+1,!0);r.push(c),i=l;continue}if(o==="}")return[r,i+1];if(o==="{"){let[c,l]=K8(e,i+1);r.push(c),i=l;continue}let[s,a]=H8(e,i,!1);r.push(s),i=a}return[r,i]}function J8(e){let[t]=K8(e,1);return t}function nC(e){return`{${e.map((t)=>{if(Array.isArray(t))return nC(t);if(typeof t==="string")return`"${t.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${t}`}).join(",")}}`}var V8=()=>{};var rp,eu,W8,Zbe,G8,iC;var Q8=S(()=>{Rb();Zn();ze();q8();tC();F8();V8();rp=class rp extends tp{foreignKeyConfigs=[];static[J]="PgColumnBuilder";array(e){return new G8(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:i})=>Ob((n,o)=>{let s=new eC(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(o.onUpdate)s.onUpdate(o.onUpdate);if(o.onDelete)s.onDelete(o.onDelete);return s.build(t)},r,i))}buildExtraConfigColumn(e){return new W8(e,this.config)}};eu=class eu extends nt{constructor(e,t){if(!t.uniqueName)t.uniqueName=rC(e,[t.name]);super(e,t);this.table=e}static[J]="PgColumn"};W8=class W8 extends eu{static[J]="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}};Zbe=class Zbe{static[J]="IndexedColumn";constructor(e,t,r,i){this.name=e,this.keyAsName=t,this.type=r,this.indexConfig=i}name;keyAsName;type;indexConfig};G8=class G8 extends rp{static[J]="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 iC(e,this.config,t)}};iC=class iC extends eu{constructor(e,t,r,i){super(e,t);this.baseColumn=r,this.range=i,this.size=t.size}size;static[J]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(e){if(typeof e==="string")e=J8(e);return e.map((t)=>this.baseColumn.mapFromDriverValue(t))}mapToDriverValue(e,t=!1){let r=e.map((i)=>i===null?null:ae(this.baseColumn,iC)?this.baseColumn.mapToDriverValue(i,!0):this.baseColumn.mapToDriverValue(i));if(t)return r;return nC(r)}}});function eH(e){return!!e&&typeof e==="function"&&Y8 in e&&e[Y8]===!0}var Mbe,X8,Y8,Fbe,tH;var rH=S(()=>{ze();Q8();Mbe=class Mbe extends rp{static[J]="PgEnumObjectColumnBuilder";constructor(e,t){super(e,"string","PgEnumObjectColumn");this.config.enum=t}build(e){return new X8(e,this.config)}};X8=class X8 extends eu{static[J]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}};Y8=Symbol.for("drizzle:isPgEnum");Fbe=class Fbe extends rp{static[J]="PgEnumColumnBuilder";constructor(e,t){super(e,"string","PgEnumColumn");this.config.enum=t}build(e){return new tH(e,this.config)}};tH=class tH extends eu{static[J]="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 vt,np;var Mn=S(()=>{ze();vt=class vt{static[J]="Subquery";constructor(e,t,r,i=!1,n=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:r,isWith:i,usedTables:n}}};np=class np extends vt{static[J]="WithSubquery"}});var nH="0.45.2";var iH=()=>{};var oC,sC,oH;var sH=S(()=>{tC();iH();oH={startActiveSpan(e,t){if(!oC)return t();if(!sC)sC=oC.trace.getTracer("drizzle-orm",nH);return Ob((r,i)=>i.startActiveSpan(e,(n)=>{try{return t(n)}catch(o){throw n.setStatus({code:r.SpanStatusCode.ERROR,message:o instanceof Error?o.message:"Unknown error"}),o}finally{n.end()}}),oC,sC)}}});var _t;var to=S(()=>{_t=Symbol.for("drizzle:ViewBaseConfig")});function ys(e){return e[wr]}function za(e){return`${e[Pb]??"public"}.${e[wr]}`}var Pb,zb,aH,aC,cC,ip,cH,Hbe,we;var vr=S(()=>{ze();Xl();Pb=Symbol.for("drizzle:Schema"),zb=Symbol.for("drizzle:Columns"),aH=Symbol.for("drizzle:ExtraConfigColumns"),aC=Symbol.for("drizzle:OriginalName"),cC=Symbol.for("drizzle:BaseName"),ip=Symbol.for("drizzle:IsAlias"),cH=Symbol.for("drizzle:ExtraConfigBuilder"),Hbe=Symbol.for("drizzle:IsDrizzleTable");we=class we{static[J]="Table";static Symbol={Name:wr,Schema:Pb,OriginalName:aC,Columns:zb,ExtraConfigColumns:aH,BaseName:cC,IsAlias:ip,ExtraConfigBuilder:cH};[wr];[aC];[Pb];[zb];[aH];[cC];[ip]=!1;[Hbe]=!0;[cH]=void 0;constructor(e,t,r){this[wr]=this[aC]=e,this[Pb]=t,this[cC]=r}}});function lC(e){return e!==null&&e!==void 0&&typeof e.getSQL==="function"}function Jbe(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 lH(e){return typeof e==="object"&&e!==null&&"mapToDriverValue"in e&&typeof e.mapToDriverValue==="function"}function U(e,...t){let r=[];if(t.length>0||e.length>0&&e[0]!=="")r.push(new Ft(e[0]));for(let[i,n]of t.entries())r.push(n,new Ft(e[i+1]));return new Te(r)}function op(e,t){return e.map((r)=>{if(ae(r,bs)){if(!(r.name in t))throw Error(`No value for placeholder "${r.name}" was provided`);return t[r.name]}if(ae(r,an)&&ae(r.value,bs)){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 Kbe,Ft,Te,Nb,uH,dH,l8e,an,bs,Vbe,_n;var ur=S(()=>{ze();rH();Mn();sH();to();Zn();vr();Kbe=class Kbe{static[J]="FakePrimitiveParam"};Ft=class Ft{static[J]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new Te([this])}};Te=class Te{constructor(e){this.queryChunks=e;for(let t of e)if(ae(t,we)){let r=t[we.Symbol.Schema];this.usedTables.push(r===void 0?t[we.Symbol.Name]:r+"."+t[we.Symbol.Name])}}static[J]="SQL";decoder=uH;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return oH.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:i,escapeName:n,escapeParam:o,prepareTyping:s,inlineParams:a,paramStartIndex:c}=r;return Jbe(e.map((l)=>{if(ae(l,Ft))return{sql:l.value.join(""),params:[]};if(ae(l,Nb))return{sql:n(l.value),params:[]};if(l===void 0)return{sql:"",params:[]};if(Array.isArray(l)){let u=[new Ft("(")];for(let[f,p]of l.entries())if(u.push(p),f<l.length-1)u.push(new Ft(", "));return u.push(new Ft(")")),this.buildQueryFromSourceParams(u,r)}if(ae(l,Te))return this.buildQueryFromSourceParams(l.queryChunks,{...r,inlineParams:a||l.shouldInlineParams});if(ae(l,we)){let u=l[we.Symbol.Schema],f=l[we.Symbol.Name];return{sql:u===void 0||l[ip]?n(f):n(u)+"."+n(f),params:[]}}if(ae(l,nt)){let u=i.getColumnCasing(l);if(t.invokeSource==="indexes")return{sql:n(u),params:[]};let f=l.table[we.Symbol.Schema];return{sql:l.table[ip]||f===void 0?n(l.table[we.Symbol.Name])+"."+n(u):n(f)+"."+n(l.table[we.Symbol.Name])+"."+n(u),params:[]}}if(ae(l,_n)){let u=l[_t].schema,f=l[_t].name;return{sql:u===void 0||l[_t].isAlias?n(f):n(u)+"."+n(f),params:[]}}if(ae(l,an)){if(ae(l.value,bs))return{sql:o(c.value++,l),params:[l],typings:["none"]};let u=l.value===null?null:l.encoder.mapToDriverValue(l.value);if(ae(u,Te))return this.buildQueryFromSourceParams([u],r);if(a)return{sql:this.mapInlineParam(u,r),params:[]};let f=["none"];if(s)f=[s(l.encoder)];return{sql:o(c.value++,u),params:[u],typings:f}}if(ae(l,bs))return{sql:o(c.value++,l),params:[l],typings:["none"]};if(ae(l,Te.Aliased)&&l.fieldAlias!==void 0)return{sql:n(l.fieldAlias),params:[]};if(ae(l,vt)){if(l._.isWith)return{sql:n(l._.alias),params:[]};return this.buildQueryFromSourceParams([new Ft("("),l._.sql,new Ft(") "),new Nb(l._.alias)],r)}if(eH(l)){if(l.schema)return{sql:n(l.schema)+"."+n(l.enumName),params:[]};return{sql:n(l.enumName),params:[]}}if(lC(l)){if(l.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([l.getSQL()],r);return this.buildQueryFromSourceParams([new Ft("("),l.getSQL(),new Ft(")")],r)}if(a)return{sql:this.mapInlineParam(l,r),params:[]};return{sql:o(c.value++,l),params:[l],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 Te.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}};Nb=class Nb{constructor(e){this.value=e}static[J]="Name";brand;getSQL(){return new Te([this])}};uH={mapFromDriverValue:(e)=>e},dH={mapToDriverValue:(e)=>e},l8e={...uH,...dH};an=class an{constructor(e,t=dH){this.value=e,this.encoder=t}static[J]="Param";brand;getSQL(){return new Te([this])}};((e)=>{function t(){return new Te([])}e.empty=t;function r(c){return new Te(c)}e.fromList=r;function i(c){return new Te([new Ft(c)])}e.raw=i;function n(c,l){let u=[];for(let[f,p]of c.entries()){if(f>0&&l!==void 0)u.push(l);u.push(p)}return new Te(u)}e.join=n;function o(c){return new Nb(c)}e.identifier=o;function s(c){return new bs(c)}e.placeholder=s;function a(c,l){return new an(c,l)}e.param=a})(U||(U={}));((e)=>{class t{constructor(r,i){this.sql=r,this.fieldAlias=i}static[J]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new t(this.sql,this.fieldAlias)}}e.Aliased=t})(Te||(Te={}));bs=class bs{constructor(e){this.name=e}static[J]="Placeholder";getSQL(){return new Te([this])}};Vbe=Symbol.for("drizzle:IsDrizzleView");_n=class _n{static[J]="View";[_t];[Vbe]=!0;constructor({name:e,schema:t,selectedFields:r,query:i}){this[_t]={name:e,originalName:e,schema:t,selectedFields:r,query:i,isExisting:!i,isAlias:!1}}getSQL(){return new Te([this])}};nt.prototype.getSQL=function(){return new Te([this])};we.prototype.getSQL=function(){return new Te([this])};vt.prototype.getSQL=function(){return new Te([this])}});function uC(e,t,r){let i={},n=e.reduce((o,{path:s,field:a},c)=>{let l;if(ae(a,nt))l=a;else if(ae(a,Te))l=a.decoder;else if(ae(a,vt))l=a._.sql.decoder;else l=a.sql.decoder;let u=o;for(let[f,p]of s.entries())if(f<s.length-1){if(!(p in u))u[p]={};u=u[p]}else{let m=t[c],y=u[p]=m===null?null:l.mapFromDriverValue(m);if(r&&ae(a,nt)&&s.length===2){let g=s[0];if(!(g in i))i[g]=y===null?ys(a.table):!1;else if(typeof i[g]==="string"&&i[g]!==ys(a.table))i[g]=!1}}return o},{});if(r&&Object.keys(i).length>0){for(let[o,s]of Object.entries(i))if(typeof s==="string"&&!r[s])n[o]=null}return n}function kn(e,t){return Object.entries(e).reduce((r,[i,n])=>{if(typeof i!=="string")return r;let o=t?[...t,i]:[i];if(ae(n,nt)||ae(n,Te)||ae(n,Te.Aliased)||ae(n,vt))r.push({path:o,field:n});else if(ae(n,we))r.push(...kn(n[we.Symbol.Columns],o));else r.push(...kn(n,o));return r},[])}function sp(e,t){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let[n,o]of r.entries())if(o!==i[n])return!1;return!0}function Db(e,t){let r=Object.entries(t).filter(([,i])=>i!==void 0).map(([i,n])=>{if(ae(n,Te)||ae(n,nt))return[i,n];else return[i,new an(n,e[we.Symbol.Columns][i])]});if(r.length===0)throw Error("No values to set");return Object.fromEntries(r)}function fH(e,t){for(let r of t)for(let i of Object.getOwnPropertyNames(r.prototype)){if(i==="constructor")continue;Object.defineProperty(e.prototype,i,Object.getOwnPropertyDescriptor(r.prototype,i)||Object.create(null))}}function Lb(e){return e[we.Symbol.Columns]}function ap(e){return ae(e,vt)?e._.alias:ae(e,_n)?e[_t].name:ae(e,Te)?void 0:e[we.Symbol.IsAlias]?e[we.Symbol.Name]:e[we.Symbol.BaseName]}function Si(e,t){return{name:typeof e==="string"&&e.length>0?e:"",config:typeof e==="object"?e:t}}function pH(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 dC;var Dr=S(()=>{Zn();ze();ur();Mn();vr();to();dC=typeof TextDecoder>"u"?null:new TextDecoder});var mH,fC,pC;var Bb=S(()=>{ze();mH=class mH{static[J]="ConsoleLogWriter";write(e){console.log(e)}};fC=class fC{static[J]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new mH}logQuery(e,t){let r=t.map((n)=>{try{return JSON.stringify(n)}catch{return String(n)}}),i=r.length?` -- params: [${r.join(", ")}]`:"";this.writer.write(`Query: ${e}${i}`)}};pC=class pC{static[J]="NoopLogger";logQuery(){}}});var hH,gH,mC;var yH=S(()=>{ze();vr();hH=Symbol.for("drizzle:PgInlineForeignKeys"),gH=Symbol.for("drizzle:EnableRLS");mC=class mC extends we{static[J]="PgTable";static Symbol=Object.assign({},we.Symbol,{InlineForeignKeys:hH,EnableRLS:gH});[hH]=[];[gH]=!1;[we.Symbol.ExtraConfigBuilder]=void 0;[we.Symbol.ExtraConfigColumns]={}}});var hC,bH;var SH=S(()=>{ze();yH();hC=class hC{static[J]="PgPrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new bH(e,this.columns,this.name)}};bH=class bH{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[J]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[mC.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function Hr(e,t){if(lH(t)&&!lC(e)&&!ae(e,an)&&!ae(e,bs)&&!ae(e,nt)&&!ae(e,we)&&!ae(e,_n))return new an(e,t);return e}function It(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new Te(t);return new Te([new Ft("("),U.join(t,new Ft(" and ")),new Ft(")")])}function xi(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new Te(t);return new Te([new Ft("("),U.join(t,new Ft(" or ")),new Ft(")")])}function wH(e){return U`not ${e}`}function Ss(e,t){if(Array.isArray(t)){if(t.length===0)return U`false`;return U`${e} in ${t.map((r)=>Hr(r,e))}`}return U`${e} in ${Hr(t,e)}`}function jb(e,t){if(Array.isArray(t)){if(t.length===0)return U`true`;return U`${e} not in ${t.map((r)=>Hr(r,e))}`}return U`${e} not in ${Hr(t,e)}`}function En(e){return U`${e} is null`}function kH(e){return U`${e} is not null`}function Ub(e){return U`exists ${e}`}function lp(e){return U`not exists ${e}`}function EH(e,t,r){return U`${e} between ${Hr(t,e)} and ${Hr(r,e)}`}function IH(e,t,r){return U`${e} not between ${Hr(t,e)} and ${Hr(r,e)}`}function TH(e,t){return U`${e} like ${t}`}function AH(e,t){return U`${e} not like ${t}`}function $H(e,t){return U`${e} ilike ${t}`}function CH(e,t){return U`${e} not ilike ${t}`}var Qe=(e,t)=>U`${e} = ${Hr(t,e)}`,xH=(e,t)=>U`${e} <> ${Hr(t,e)}`,cp=(e,t)=>U`${e} > ${Hr(t,e)}`,vH=(e,t)=>U`${e} >= ${Hr(t,e)}`,_H=(e,t)=>U`${e} < ${Hr(t,e)}`,tu=(e,t)=>U`${e} <= ${Hr(t,e)}`;var RH=S(()=>{Zn();ze();vr();ur()});function ro(e){return U`${e} asc`}function Na(e){return U`${e} desc`}var OH=S(()=>{ur()});var gC=S(()=>{RH();OH()});function zH(){return{and:It,between:EH,eq:Qe,exists:Ub,gt:cp,gte:vH,ilike:$H,inArray:Ss,isNull:En,isNotNull:kH,like:TH,lt:_H,lte:tu,ne:xH,not:wH,notBetween:IH,notExists:lp,notLike:AH,notIlike:CH,notInArray:jb,or:xi,sql:U}}function NH(){return{sql:U,asc:ro,desc:Na}}function DH(e,t){if(Object.keys(e).length===1&&"default"in e&&!ae(e.default,we))e=e.default;let r={},i={},n={};for(let[o,s]of Object.entries(e))if(ae(s,we)){let a=za(s),c=i[a];r[a]=o,n[o]={tsName:o,dbName:s[we.Symbol.Name],schema:s[we.Symbol.Schema],columns:s[we.Symbol.Columns],relations:c?.relations??{},primaryKey:c?.primaryKey??[]};for(let u of Object.values(s[we.Symbol.Columns]))if(u.primary)n[o].primaryKey.push(u);let l=s[we.Symbol.ExtraConfigBuilder]?.(s[we.Symbol.ExtraConfigColumns]);if(l){for(let u of Object.values(l))if(ae(u,hC))n[o].primaryKey.push(...u.columns)}}else if(ae(s,PH)){let a=za(s.table),c=r[a],l=s.config(t(s.table)),u;for(let[f,p]of Object.entries(l))if(c){let m=n[c];if(m.relations[f]=p,u)m.primaryKey.push(...u)}else{if(!(a in i))i[a]={relations:{},primaryKey:u};i[a].relations[f]=p}}return{tables:n,tableNamesMap:r}}function Wbe(e){return function(r,i){return new xs(e,r,i,i?.fields.reduce((n,o)=>n&&o.notNull,!0)??!1)}}function Gbe(e){return function(r,i){return new up(e,r,i)}}function LH(e,t,r){if(ae(r,xs)&&r.config)return{fields:r.config.fields,references:r.config.references};let i=t[za(r.referencedTable)];if(!i)throw Error(`Table "${r.referencedTable[we.Symbol.Name]}" not found in schema`);let n=e[i];if(!n)throw Error(`Table "${i}" not found in schema`);let o=r.sourceTable,s=t[za(o)];if(!s)throw Error(`Table "${o[we.Symbol.Name]}" not found in schema`);let a=[];for(let c of Object.values(n.relations))if(r.relationName&&r!==c&&c.relationName===r.relationName||!r.relationName&&c.referencedTable===r.sourceTable)a.push(c);if(a.length>1)throw r.relationName?Error(`There are multiple relations with name "${r.relationName}" in table "${i}"`):Error(`There are multiple relations between "${i}" and "${r.sourceTable[we.Symbol.Name]}". Please specify relation name`);if(a[0]&&ae(a[0],xs)&&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 BH(e){return{one:Wbe(e),many:Gbe(e)}}function qb(e,t,r,i,n=(o)=>o){let o={};for(let[s,a]of i.entries())if(a.isJson){let c=t.relations[a.tsKey],l=r[s],u=typeof l==="string"?JSON.parse(l):l;o[a.tsKey]=ae(c,xs)?u&&qb(e,e[a.relationTableTsKey],u,a.selection,n):u.map((f)=>qb(e,e[a.relationTableTsKey],f,a.selection,n))}else{let c=n(r[s]),l=a.field,u;if(ae(l,nt))u=l;else if(ae(l,Te))u=l.decoder;else u=l.sql.decoder;o[a.tsKey]=c===null?null:u.mapFromDriverValue(c)}return o}var yC,PH,xs,up;var dp=S(()=>{vr();Zn();ze();SH();gC();ur();yC=class yC{constructor(e,t,r){this.sourceTable=e,this.referencedTable=t,this.relationName=r,this.referencedTableName=t[we.Symbol.Name]}static[J]="Relation";referencedTableName;fieldName};PH=class PH{constructor(e,t){this.table=e,this.config=t}static[J]="Relations"};xs=class xs extends yC{constructor(e,t,r,i){super(e,t,r?.relationName);this.config=r,this.isNullable=i}static[J]="One";withFieldName(e){let t=new xs(this.sourceTable,this.referencedTable,this.config,this.isNullable);return t.fieldName=e,t}};up=class up extends yC{constructor(e,t,r){super(e,t,r?.relationName);this.config=r}static[J]="Many";withFieldName(e){let t=new up(this.sourceTable,this.referencedTable,this.config);return t.fieldName=e,t}}});function fp(e,t){return new Proxy(e,new Da(t,!1))}function wi(e,t){return new Proxy(e,new ru(new Proxy(e.table,new Da(t,!1))))}function bC(e,t){return new Te.Aliased(pp(e.sql,t),e.fieldAlias)}function pp(e,t){return U.join(e.queryChunks.map((r)=>{if(ae(r,nt))return wi(r,t);if(ae(r,Te))return pp(r,t);if(ae(r,Te.Aliased))return bC(r,t);return r}))}var ru,Da,Qbe;var mp=S(()=>{Zn();ze();ur();vr();to();ru=class ru{constructor(e){this.table=e}static[J]="ColumnAliasProxyHandler";get(e,t){if(t==="table")return this.table;return e[t]}};Da=class Da{constructor(e,t){this.alias=e,this.replaceOriginalName=t}static[J]="TableAliasProxyHandler";get(e,t){if(t===we.Symbol.IsAlias)return!0;if(t===we.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===we.Symbol.OriginalName)return this.alias;if(t===_t)return{...e[_t],name:this.alias,isAlias:!0};if(t===we.Symbol.Columns){let i=e[we.Symbol.Columns];if(!i)return i;let n={};return Object.keys(i).map((o)=>{n[o]=new Proxy(i[o],new ru(new Proxy(e,this)))}),n}let r=e[t];if(ae(r,nt))return new Proxy(r,new ru(new Proxy(e,this)));return r}};Qbe=class Qbe{constructor(e){this.alias=e}static[J]="RelationTableAliasProxyHandler";get(e,t){if(t==="sourceTable")return fp(e.sourceTable,this.alias);return e[t]}}});var bt;var La=S(()=>{mp();Zn();ze();ur();Mn();to();bt=class bt{static[J]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t==="_")return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(t===_t)return{...e[_t],selectedFields:new Proxy(e[_t].selectedFields,this)};if(typeof t==="symbol")return e[t];let i=(ae(e,vt)?e._.selectedFields:ae(e,_n)?e[_t].selectedFields:e)[t];if(ae(i,Te.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!i.isSelectionField)return i.sql;let n=i.clone();return n.isSelectionField=!0,n}if(ae(i,Te)){if(this.config.sqlBehavior==="sql")return i;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(ae(i,nt)){if(this.config.alias)return new Proxy(i,new ru(new Proxy(i.table,new Da(this.config.alias,this.config.replaceOriginalName??!1))));return i}if(typeof i!=="object"||i===null)return i;return new Proxy(i,new bt(this.config))}}});var Lr;var no=S(()=>{ze();Lr=class Lr{static[J]="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 SC,jH;var xC=S(()=>{ze();Xl();SC=class SC{static[J]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(e,t){if(this.reference=()=>{let{name:r,columns:i,foreignColumns:n}=e();return{name:r,columns:i,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 jH(e,this)}};jH=class jH{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[J]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),i=t.map((s)=>s.name),n=r.map((s)=>s.name),o=[this.table[wr],...i,r[0].table[wr],...n];return e??`${o.join("_")}_fk`}}});function wC(e,t){return`${e[wr]}_${t.join("_")}_unique`}var UH,Ybe,qH;var vC=S(()=>{ze();Xl();UH=class UH{constructor(e,t){this.name=t,this.columns=e}static[J]="SQLiteUniqueConstraintBuilder";columns;build(e){return new qH(e,this.columns,this.name)}};Ybe=class Ybe{static[J]="SQLiteUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new UH(e,this.name)}};qH=class qH{constructor(e,t,r){this.table=e,this.columns=t,this.name=r??wC(this.table,this.columns.map((i)=>i.name))}static[J]="SQLiteUniqueConstraint";columns;name;getName(){return this.name}}});var Qt,Tt;var ws=S(()=>{Rb();Zn();ze();xC();vC();Qt=class Qt extends tp{static[J]="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:i})=>((n,o)=>{let s=new SC(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(o.onUpdate)s.onUpdate(o.onUpdate);if(o.onDelete)s.onDelete(o.onDelete);return s.build(t)})(r,i))}};Tt=class Tt extends nt{constructor(e,t){if(!t.uniqueName)t.uniqueName=wC(e,[t.name]);super(e,t);this.table=e}static[J]="SQLiteColumn"}});function VH(e,t){let{name:r,config:i}=Si(e,t);if(i?.mode==="json")return new FH(r);if(i?.mode==="bigint")return new ZH(r);return new KH(r)}var ZH,MH,FH,HH,KH,JH;var _C=S(()=>{ze();Dr();ws();ZH=class ZH extends Qt{static[J]="SQLiteBigIntBuilder";constructor(e){super(e,"bigint","SQLiteBigInt")}build(e){return new MH(e,this.config)}};MH=class MH extends Tt{static[J]="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(dC.decode(e))}mapToDriverValue(e){return Buffer.from(e.toString())}};FH=class FH extends Qt{static[J]="SQLiteBlobJsonBuilder";constructor(e){super(e,"json","SQLiteBlobJson")}build(e){return new HH(e,this.config)}};HH=class HH extends Tt{static[J]="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(dC.decode(e))}mapToDriverValue(e){return Buffer.from(JSON.stringify(e))}};KH=class KH extends Qt{static[J]="SQLiteBlobBufferBuilder";constructor(e){super(e,"buffer","SQLiteBlobBuffer")}build(e){return new JH(e,this.config)}};JH=class JH extends Tt{static[J]="SQLiteBlobBuffer";mapFromDriverValue(e){if(Buffer.isBuffer(e))return e;return Buffer.from(e)}getSQLType(){return"blob"}}});function QH(e){return(t,r)=>{let{name:i,config:n}=Si(t,r);return new WH(i,n,e)}}var WH,GH;var kC=S(()=>{ze();Dr();ws();WH=class WH extends Qt{static[J]="SQLiteCustomColumnBuilder";constructor(e,t,r){super(e,"custom","SQLiteCustomColumn");this.config.fieldConfig=t,this.config.customTypeParams=r}build(e){return new GH(e,this.config)}};GH=class GH extends Tt{static[J]="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 _r(e,t){let{name:r,config:i}=Si(e,t);if(i?.mode==="timestamp"||i?.mode==="timestamp_ms")return new eK(r,i.mode);if(i?.mode==="boolean")return new rK(r,i.mode);return new YH(r)}var Zb,Mb,YH,XH,eK,tK,rK,nK;var EC=S(()=>{ze();ur();Dr();ws();Zb=class Zb extends Qt{static[J]="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()}};Mb=class Mb extends Tt{static[J]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}};YH=class YH extends Zb{static[J]="SQLiteIntegerBuilder";constructor(e){super(e,"number","SQLiteInteger")}build(e){return new XH(e,this.config)}};XH=class XH extends Mb{static[J]="SQLiteInteger"};eK=class eK extends Zb{static[J]="SQLiteTimestampBuilder";constructor(e,t){super(e,"date","SQLiteTimestamp");this.config.mode=t}defaultNow(){return this.default(U`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new tK(e,this.config)}};tK=class tK extends Mb{static[J]="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}};rK=class rK extends Zb{static[J]="SQLiteBooleanBuilder";constructor(e,t){super(e,"boolean","SQLiteBoolean");this.config.mode=t}build(e){return new nK(e,this.config)}};nK=class nK extends Mb{static[J]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue(e){return Number(e)===1}mapToDriverValue(e){return e?1:0}}});function uK(e,t){let{name:r,config:i}=Si(e,t),n=i?.mode;return n==="number"?new sK(r):n==="bigint"?new cK(r):new iK(r)}var iK,oK,sK,aK,cK,lK;var IC=S(()=>{ze();Dr();ws();iK=class iK extends Qt{static[J]="SQLiteNumericBuilder";constructor(e){super(e,"string","SQLiteNumeric")}build(e){return new oK(e,this.config)}};oK=class oK extends Tt{static[J]="SQLiteNumeric";mapFromDriverValue(e){if(typeof e==="string")return e;return String(e)}getSQLType(){return"numeric"}};sK=class sK extends Qt{static[J]="SQLiteNumericNumberBuilder";constructor(e){super(e,"number","SQLiteNumericNumber")}build(e){return new aK(e,this.config)}};aK=class aK extends Tt{static[J]="SQLiteNumericNumber";mapFromDriverValue(e){if(typeof e==="number")return e;return Number(e)}mapToDriverValue=String;getSQLType(){return"numeric"}};cK=class cK extends Qt{static[J]="SQLiteNumericBigIntBuilder";constructor(e){super(e,"bigint","SQLiteNumericBigInt")}build(e){return new lK(e,this.config)}};lK=class lK extends Tt{static[J]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}});function pK(e){return new dK(e??"")}var dK,fK;var TC=S(()=>{ze();ws();dK=class dK extends Qt{static[J]="SQLiteRealBuilder";constructor(e){super(e,"number","SQLiteReal")}build(e){return new fK(e,this.config)}};fK=class fK extends Tt{static[J]="SQLiteReal";getSQLType(){return"real"}}});function dr(e,t={}){let{name:r,config:i}=Si(e,t);if(i.mode==="json")return new gK(r);return new mK(r,i)}var mK,hK,gK,yK;var AC=S(()=>{ze();Dr();ws();mK=class mK extends Qt{static[J]="SQLiteTextBuilder";constructor(e,t){super(e,"string","SQLiteText");this.config.enumValues=t.enum,this.config.length=t.length}build(e){return new hK(e,this.config)}};hK=class hK extends Tt{static[J]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor(e,t){super(e,t)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}};gK=class gK extends Qt{static[J]="SQLiteTextJsonBuilder";constructor(e){super(e,"json","SQLiteTextJson")}build(e){return new yK(e,this.config)}};yK=class yK extends Tt{static[J]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue(e){return JSON.parse(e)}mapToDriverValue(e){return JSON.stringify(e)}}});function bK(){return{blob:VH,customType:QH,integer:_r,numeric:uK,real:pK,text:dr}}var SK=S(()=>{_C();kC();EC();IC();TC();AC()});function Xbe(e,t,r,i,n=e){let o=new Bt(e,i,n),s=typeof t==="function"?t(bK()):t,a=Object.fromEntries(Object.entries(s).map(([l,u])=>{let f=u;f.setName(l);let p=f.build(o);return o[$C].push(...f.buildForeignKeys(p,o)),[l,p]})),c=Object.assign(o,a);if(c[we.Symbol.Columns]=a,c[we.Symbol.ExtraConfigColumns]=a,r)c[Bt.Symbol.ExtraConfigBuilder]=r;return c}var $C,Bt,hp=(e,t,r)=>Xbe(e,t,r);var io=S(()=>{ze();vr();SK();$C=Symbol.for("drizzle:SQLiteInlineForeignKeys");Bt=class Bt extends we{static[J]="SQLiteTable";static Symbol=Object.assign({},we.Symbol,{InlineForeignKeys:$C});[we.Symbol.Columns];[$C]=[];[we.Symbol.ExtraConfigBuilder]=void 0}});var eSe,xK;var wK=S(()=>{ze();eSe=class eSe{constructor(e,t){this.name=e,this.value=t}static[J]="SQLiteCheckBuilder";brand;build(e){return new xK(e,this)}};xK=class xK{constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}static[J]="SQLiteCheck";name;value}});function oo(e){return new vK(e,!1)}var vK,_K,kK;var EK=S(()=>{ze();vK=class vK{constructor(e,t){this.name=e,this.unique=t}static[J]="SQLiteIndexBuilderOn";on(...e){return new _K(this.name,e,this.unique)}};_K=class _K{static[J]="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 kK(this.config,e)}};kK=class kK{static[J]="SQLiteIndex";config;constructor(e,t){this.config={...e,table:t}}}});var tSe,IK;var TK=S(()=>{ze();io();tSe=class tSe{static[J]="SQLitePrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new IK(e,this.columns,this.name)}};IK=class IK{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[J]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[Bt.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function Fn(e){if(ae(e,Bt))return[`${e[we.Symbol.BaseName]}`];if(ae(e,vt))return e._.usedTables??[];if(ae(e,Te))return e.usedTables??[];return[]}var nu=S(()=>{ze();ur();Mn();vr();io()});var Fb;var AK=S(()=>{ze();no();La();io();vr();Dr();nu();Fb=class Fb extends Lr{constructor(e,t,r,i){super();this.table=e,this.session=t,this.dialect=r,this.config={table:e,withList:i}}static[J]="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[we.Symbol.Columns],new bt({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[Bt.Symbol.Columns]){return this.config.returning=kn(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:Fn(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 rSe(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((r)=>r.toLowerCase()).join("_")}function nSe(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((r,i,n)=>{let o=n===0?i.toLowerCase():`${i[0].toUpperCase()}${i.slice(1)}`;return r+o},"")}function iSe(e){return e}var CC;var $K=S(()=>{ze();vr();CC=class CC{static[J]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert=e==="snake_case"?rSe:e==="camelCase"?nSe:iSe}getColumnCasing(e){if(!e.keyAsName)return e.name;let t=e.table[we.Symbol.Schema]??"public",r=e.table[we.Symbol.OriginalName],i=`${t}.${r}.${e.name}`;if(!this.cache[i])this.cacheTable(e.table);return this.cache[i]}cacheTable(e){let t=e[we.Symbol.Schema]??"public",r=e[we.Symbol.OriginalName],i=`${t}.${r}`;if(!this.cachedTables[i]){for(let n of Object.values(e[we.Symbol.Columns])){let o=`${i}.${n.name}`;this.cache[o]=this.convert(n.name)}this.cachedTables[i]=!0}}clearCache(){this.cache={},this.cachedTables={}}}});var iu,so,RC;var Hb=S(()=>{ze();iu=class iu extends Error{static[J]="DrizzleError";constructor({message:e,cause:t}){super(e);this.name="DrizzleError",this.cause=t}};so=class so extends Error{constructor(e,t,r){super(`Failed query: ${e}
|
|
408
|
+
`)}catch{}}}formatJsonEntry(e,t,r){let i={ts:new Date().toISOString(),level:e,msg:t};if(this.context)i.ctx=this.context;if(r.length>0)i.data=r;return JSON.stringify(i)}silly(e,...t){if(this.level<=ka.SILLY)this.write(console.debug.bind(console),"silly",e,t)}verbose(e,...t){if(this.level<=ka.VERBOSE)this.write(console.debug.bind(console),"verbose",e,t)}debug(e,...t){if(this.level<=ka.DEBUG)this.write(console.debug.bind(console),"debug",e,t)}info(e,...t){if(this.level<=ka.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<=ka.WARN)this.write(console.warn.bind(console),"warn",e,t)}error(e,...t){if(this.level<=ka.ERROR)this.write(console.error.bind(console),"error",e,t)}child(e){return new on({level:this.level,context:e,useStderr:this.useStderr,format:this.format},this.fileHandle)}setUseStderr(e){this.useStderr=e}}var ka,kZe;var m$=S(()=>{ka={SILLY:0,VERBOSE:1,DEBUG:2,INFO:3,WARN:4,ERROR:5,NONE:6};kZe=on.getInstance()});var h$,ege,Cl,AZe;var Of=S(()=>{ti();Ae();h$=d.enum(["file_operations","content_operations","data_processing","batch_processing"]),ege=d.looseObject({pluginId:d.string().optional(),progressToken:d.union([d.string(),d.number()]).optional(),operationType:h$,operationTarget:d.string().optional(),interfaceType:d.string().optional(),conversationId:d.string().optional(),channelId:d.string().optional(),requestedByActor:Ac.optional(),requestedByUserId:d.string().optional(),requestedByInterface:d.string().optional(),silent:d.boolean().optional(),provenance:ko.optional()}),Cl=d.looseObject({pluginId:d.string().optional(),progressToken:d.union([d.string(),d.number()]).optional(),operationType:h$,operationTarget:d.string().optional(),interfaceType:d.string().optional(),conversationId:d.string().optional(),channelId:d.string().optional(),requestedByActor:Ac.optional(),requestedByUserId:d.string().optional(),requestedByInterface:d.string().optional(),silent:d.boolean().optional(),provenance:ko.optional(),rootJobId:d.string()}),AZe=d.enum(["none","skip","replace","coalesce"])});var tge,ss=15000;var Pf=S(()=>{Of();Ae();tge=d.object({id:d.string(),type:d.string(),data:d.string(),status:d.enum(["pending","processing","completed","failed"]),source:d.string().nullable(),priority:d.number(),retryCount:d.number(),maxRetries:d.number(),lastError:d.string().nullable(),createdAt:d.number(),scheduledFor:d.number(),startedAt:d.number().nullable(),completedAt:d.number().nullable(),attemptId:d.string().nullable(),workerSlotId:d.string().nullable(),workerSessionId:d.string().nullable(),leaseExpiresAt:d.number().nullable(),attemptHeartbeatAt:d.number().nullable(),runtimeUpdatedAt:d.number().nullable(),metadata:Cl,progress:d.custom((e)=>typeof e==="object"&&e!==null&&("progress"in e)&&typeof e.progress==="number").nullable(),result:d.unknown().nullable().optional()})});var g$,T3,Ue,rge,nge,A3,ige;var as=S(()=>{Ae();Of();g$=d.enum(["pending","processing","completed","failed"]),T3=d.enum(["completed","failed"]),Ue={PENDING:"pending",PROCESSING:"processing",COMPLETED:"completed",FAILED:"failed"},rge=d.object({id:d.string(),type:d.string(),status:g$,data:d.unknown(),result:d.unknown().optional(),lastError:d.string().optional().nullable(),attempts:d.number(),maxRetries:d.number(),priority:d.number(),createdAt:d.date(),updatedAt:d.date(),processedAt:d.date().optional().nullable(),completedAt:d.date().optional().nullable(),failedAt:d.date().optional().nullable()}),nge=d.object({jobId:d.string(),type:d.string(),status:T3,result:d.unknown().optional(),error:d.string().optional()}),A3=d.object({success:d.literal(!1),error:d.string().optional()}),ige=d.object({id:d.string(),type:d.enum(["job","batch"]),status:g$,message:d.string().optional(),progress:d.object({current:d.number(),total:d.number(),percentage:d.number()}).optional(),aggregationKey:d.string().optional(),batchDetails:d.object({totalOperations:d.number(),completedOperations:d.number(),failedOperations:d.number(),currentOperation:d.string().optional(),errors:d.array(d.string()).optional()}).optional(),jobDetails:d.object({jobType:d.string(),priority:d.number(),retryCount:d.number()}).optional(),metadata:Cl})});var Be,cr;var jn=S(()=>{Be=class Be extends Error{code;extendedCode;rawCode;constructor(e,t,r,i,n){if(t!==void 0)e=`${t}: ${e}`;super(e,{cause:n});this.code=t,this.extendedCode=r,this.rawCode=i,this.name="LibsqlError"}};cr=class cr extends Be{statementIndex;constructor(e,t,r,i,n,o){super(e,r,i,n,o);this.statementIndex=t,this.name="LibsqlBatchError"}}});function $3(e){let t=oge.exec(e);if(t===null)throw new Be(`The URL '${e}' is not in a valid format`,"URL_INVALID");let r=t.groups,i=r.scheme,n=r.authority!==void 0?sge(r.authority):void 0,o=Ea(r.path),s=r.query!==void 0?cge(r.query):void 0,a=r.fragment!==void 0?Ea(r.fragment):void 0;return{scheme:i,authority:n,path:o,query:s,fragment:a}}function sge(e){let t=age.exec(e);if(t===null)throw new Be("The authority part of the URL is not in a valid format","URL_INVALID");let r=t.groups,i=Ea(r.host_br??r.host),n=r.port?parseInt(r.port,10):void 0,o=r.username!==void 0?{username:Ea(r.username),password:r.password!==void 0?Ea(r.password):void 0}:void 0;return{host:i,port:n,userinfo:o}}function cge(e){let t=e.split("&"),r=[];for(let i of t){if(i==="")continue;let n,o,s=i.indexOf("=");if(s<0)n=i,o="";else n=i.substring(0,s),o=i.substring(s+1);r.push({key:Ea(n.replaceAll("+"," ")),value:Ea(o.replaceAll("+"," "))})}return{pairs:r}}function Ea(e){try{return decodeURIComponent(e)}catch(t){if(t instanceof URIError)throw new Be(`URL component has invalid percent encoding: ${t}`,"URL_INVALID",void 0,void 0,t);throw t}}function zf(e,t,r){if(t===void 0)throw new Be(`URL with scheme ${JSON.stringify(e+":")} requires authority (the "//" part)`,"URL_INVALID");let i=`${e}:`,n=lge(t.host),o=uge(t.port),a=`//${dge(t.userinfo)}${n}${o}`,c=r.split("/").map(encodeURIComponent).join("/");if(c!==""&&!c.startsWith("/"))c="/"+c;return new URL(`${i}${a}${c}`)}function lge(e){return e.includes(":")?`[${encodeURI(e)}]`:encodeURI(e)}function uge(e){return e!==void 0?`:${e}`:""}function dge(e){if(e===void 0)return"";let t=encodeURIComponent(e.username),r=e.password!==void 0?`:${encodeURIComponent(e.password)}`:"";return`${t}${r}@`}var oge,age;var sb=S(()=>{jn();oge=(()=>new RegExp("^(?<scheme>[A-Za-z][A-Za-z.+-]*):(//(?<authority>[^/?#]*))?(?<path>[^?#]*)(\\?(?<query>[^#]*))?(#(?<fragment>.*))?$","su"))();age=(()=>new RegExp("^((?<username>[^:]*)(:(?<password>.*))?@)?((?<host>[^:\\[\\]]*)|(\\[(?<host_br>[^\\[\\]]*)\\]))(:(?<port>[0-9]*))?$","su"))()});var Ol,C3,R3,Nf,ab,fge,lr,O3,N3=(e)=>e.replace(/=/g,"").replace(/[+\/]/g,(t)=>t=="+"?"-":"_"),D3=(e)=>e.replace(/[^A-Za-z0-9\+\/]/g,""),L3=(e)=>{let t,r,i,n,o="",s=e.length%3;for(let a=0;a<e.length;){if((r=e.charCodeAt(a++))>255||(i=e.charCodeAt(a++))>255||(n=e.charCodeAt(a++))>255)throw TypeError("invalid character found");t=r<<16|i<<8|n,o+=Nf[t>>18&63]+Nf[t>>12&63]+Nf[t>>6&63]+Nf[t&63]}return s?o.slice(0,s-3)+"===".substring(s):o},S$,y$,cb=(e,t=!1)=>t?N3(y$(e)):y$(e),pge=(e)=>{if(e.length<2){var t=e.charCodeAt(0);return t<128?e:t<2048?lr(192|t>>>6)+lr(128|t&63):lr(224|t>>>12&15)+lr(128|t>>>6&63)+lr(128|t&63)}else{var t=65536+(e.charCodeAt(0)-55296)*1024+(e.charCodeAt(1)-56320);return lr(240|t>>>18&7)+lr(128|t>>>12&63)+lr(128|t>>>6&63)+lr(128|t&63)}},mge,B3=(e)=>e.replace(mge,pge),P3,Rl=(e,t=!1)=>t?N3(P3(e)):P3(e),z3=(e)=>Rl(e,!0),hge,gge=(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 lr((r>>>10)+55296)+lr((r&1023)+56320);case 3:return lr((15&e.charCodeAt(0))<<12|(63&e.charCodeAt(1))<<6|63&e.charCodeAt(2));default:return lr((31&e.charCodeAt(0))<<6|63&e.charCodeAt(1))}},j3=(e)=>e.replace(hge,gge),U3=(e)=>{if(e=e.replace(/\s+/g,""),!fge.test(e))throw TypeError("malformed base64.");e+="==".slice(2-(e.length&3));let t,r,i,n=[];for(let o=0;o<e.length;)if(t=ab[e.charAt(o++)]<<18|ab[e.charAt(o++)]<<12|(r=ab[e.charAt(o++)])<<6|(i=ab[e.charAt(o++)]),r===64)n.push(lr(t>>16&255));else if(i===64)n.push(lr(t>>16&255,t>>8&255));else n.push(lr(t>>16&255,t>>8&255,t&255));return n.join("")},x$,q3,Z3=(e)=>q3(M3(e)),yge,M3=(e)=>D3(e.replace(/[-_]/g,(t)=>t=="-"?"+":"/")),b$=(e)=>yge(M3(e)),bge=(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)},F3=(e)=>({value:e,enumerable:!1,writable:!0,configurable:!0}),H3=function(){let e=(t,r)=>Object.defineProperty(String.prototype,t,F3(r));e("fromBase64",function(){return b$(this)}),e("toBase64",function(t){return Rl(this,t)}),e("toBase64URI",function(){return Rl(this,!0)}),e("toBase64URL",function(){return Rl(this,!0)}),e("toUint8Array",function(){return Z3(this)})},K3=function(){let e=(t,r)=>Object.defineProperty(Uint8Array.prototype,t,F3(r));e("toBase64",function(t){return cb(this,t)}),e("toBase64URI",function(){return cb(this,!0)}),e("toBase64URL",function(){return cb(this,!0)})},Sge=()=>{H3(),K3()},Pl;var lb=S(()=>{Ol=typeof Buffer==="function",C3=typeof TextDecoder==="function"?new TextDecoder("utf-8",{ignoreBOM:!0}):void 0,R3=typeof TextEncoder==="function"?new TextEncoder:void 0,Nf=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),ab=((e)=>{let t={};return e.forEach((r,i)=>t[r]=i),t})(Nf),fge=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,lr=String.fromCharCode.bind(String),O3=typeof Uint8Array.from==="function"?Uint8Array.from.bind(Uint8Array):(e)=>new Uint8Array(Array.prototype.slice.call(e,0)),S$=typeof btoa==="function"?(e)=>btoa(e):Ol?(e)=>Buffer.from(e,"binary").toString("base64"):L3,y$=Ol?(e)=>Buffer.from(e).toString("base64"):(e)=>{let r=[];for(let i=0,n=e.length;i<n;i+=4096)r.push(lr.apply(null,e.subarray(i,i+4096)));return S$(r.join(""))},mge=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,P3=Ol?(e)=>Buffer.from(e,"utf8").toString("base64"):R3?(e)=>y$(R3.encode(e)):(e)=>S$(B3(e)),hge=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,x$=typeof atob==="function"?(e)=>atob(D3(e)):Ol?(e)=>Buffer.from(e,"base64").toString("binary"):U3,q3=Ol?(e)=>O3(Buffer.from(e,"base64")):(e)=>O3(x$(e).split("").map((t)=>t.charCodeAt(0))),yge=Ol?(e)=>Buffer.from(e,"base64").toString("utf8"):C3?(e)=>C3.decode(q3(e)):(e)=>j3(x$(e)),Pl={version:"3.8.0",VERSION:"3.8.0",atob:x$,atobPolyfill:U3,btoa:S$,btoaPolyfill:L3,fromBase64:b$,toBase64:Rl,encode:Rl,encodeURI:z3,encodeURL:z3,utob:B3,btou:j3,decode:b$,isValid:bge,fromUint8Array:cb,toUint8Array:Z3,extendString:H3,extendUint8Array:K3,extendBuiltins:Sge}});function cs(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 zl{columns;columnTypes;rows;rowsAffected;lastInsertRowid;constructor(e,t,r,i,n){this.columns=e,this.columnTypes=t,this.rows=r,this.rowsAffected=i,this.lastInsertRowid=n}toJSON(){return{columns:this.columns,columnTypes:this.columnTypes,rows:this.rows.map(xge),rowsAffected:this.rowsAffected,lastInsertRowid:this.lastInsertRowid!==void 0?""+this.lastInsertRowid:null}}}function xge(e){return Array.prototype.map.call(e,wge)}function wge(e){if(typeof e==="bigint")return""+e;else if(e instanceof ArrayBuffer)return Pl.fromUint8Array(new Uint8Array(e));else return e}var hi="https://github.com/libsql/libsql-client-ts#supported-urls";var Nl=S(()=>{lb()});function V3(e){return e.scheme==="file"&&(e.path===":memory:"||e.path.startsWith(":memory:?"))}function Df(e,t){if(typeof e!=="object")throw TypeError(`Expected client configuration as object, got ${typeof e}`);let{url:r,authToken:i,tls:n,intMode:o,concurrency:s}=e;s=Math.max(0,s||20),o??="number";let a=[];if(r===J3)r="file::memory:";let c=$3(r),l=c.scheme.toLowerCase(),u=l==="file"&&c.path===J3&&c.authority===void 0,f;if(u)f={cache:{values:["shared","private"],update:(g,b)=>a.push(`${g}=${b}`)}};else f={tls:{values:["0","1"],update:(g,b)=>n=b==="1"},authToken:{update:(g,b)=>i=b}};for(let{key:g,value:b}of c.query?.pairs??[]){if(!Object.hasOwn(f,g))throw new Be(`Unsupported URL query parameter ${JSON.stringify(g)}`,"URL_PARAM_NOT_SUPPORTED");let _=f[g];if(_.values!==void 0&&!_.values.includes(b))throw new Be(`Unknown value for the "${g}" query argument: ${JSON.stringify(b)}. Supported values are: [${_.values.map((T)=>'"'+T+'"').join(", ")}]`,"URL_INVALID");if(_.update!==void 0)_?.update(g,b)}let p=a.length===0?"":`?${a.join("&")}`,m=c.path+p,y;if(l==="libsql")if(n===!1){if(c.authority?.port===void 0)throw new Be('A "libsql:" URL with ?tls=0 must specify an explicit port',"URL_INVALID");y=t?"http":"ws"}else y=t?"https":"wss";else y=l;if(y==="http"||y==="ws")n??=!1;else n??=!0;if(y!=="http"&&y!=="ws"&&y!=="https"&&y!=="wss"&&y!=="file")throw new Be(`The client supports only "libsql:", "wss:", "ws:", "https:", "http:" and "file:" URLs, got ${JSON.stringify(c.scheme+":")}. For more information, please read ${hi}`,"URL_SCHEME_NOT_SUPPORTED");if(o!=="number"&&o!=="bigint"&&o!=="string")throw TypeError(`Invalid value for intMode, expected "number", "bigint" or "string", got ${JSON.stringify(o)}`);if(c.fragment!==void 0)throw new Be(`URL fragments are not supported: ${JSON.stringify("#"+c.fragment)}`,"URL_INVALID");if(u)return{scheme:"file",tls:!1,path:m,intMode:o,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:y,tls:n,authority:c.authority,path:m,authToken:i,intMode:o,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 J3=":memory:";var Lf=S(()=>{jn();sb();Nl()});var G3=Se(function(xn){var vge=xn&&xn.__createBinding||(Object.create?function(e,t,r,i){if(i===void 0)i=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,i,n)}:function(e,t,r,i){if(i===void 0)i=r;e[i]=t[r]}),_ge=xn&&xn.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),W3=xn&&xn.__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))vge(t,e,r)}return _ge(t,e),t};Object.defineProperty(xn,"__esModule",{value:!0});xn.load=xn.currentTarget=void 0;var kge=W3(pr("path")),Ege=W3(pr("fs"));function Ige(){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 Tge()?`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}`)}xn.currentTarget=Ige;function Tge(){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 Age(e){let t=kge.join(e,"index.node");return Ege.existsSync(t)?pr(t):null}xn.load=Age});var X3=Se(function(VZe,Y3){var Q3=()=>process.platform==="linux",w$=null,$ge=()=>{if(!w$)w$=Q3()&&process.report?process.report.getReport():{};return w$};Y3.exports={isLinux:Q3,getReport:$ge}});var r5=Se(function(WZe,t5){var e5=pr("fs"),Cge=(e)=>e5.readFileSync(e,"utf-8"),Rge=(e)=>new Promise((t,r)=>{e5.readFile(e,"utf-8",(i,n)=>{if(i)r(i);else t(n)})});t5.exports={LDD_PATH:"/usr/bin/ldd",readFileSync:Cge,readFile:Rge}});var S5=Se(function(GZe,b5){var i5=pr("child_process"),{isLinux:Dl,getReport:o5}=X3(),{LDD_PATH:ub,readFile:s5,readFileSync:a5}=r5(),gi,yi,ls="",c5=()=>{if(!ls)return new Promise((e)=>{i5.exec("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",(t,r)=>{ls=t?" ":r,e(ls)})});return ls},l5=()=>{if(!ls)try{ls=i5.execSync("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",{encoding:"utf8"})}catch(e){ls=" "}return ls},Qi="glibc",u5=/GLIBC\s(\d+\.\d+)/,Ia="musl",Oge=Qi.toUpperCase(),Pge=Ia.toLowerCase(),zge=(e)=>e.includes("libc.musl-")||e.includes("ld-musl-"),d5=()=>{let e=o5();if(e.header&&e.header.glibcVersionRuntime)return Qi;if(Array.isArray(e.sharedObjects)){if(e.sharedObjects.some(zge))return Ia}return null},f5=(e)=>{let[t,r]=e.split(/[\r\n]+/);if(t&&t.includes(Qi))return Qi;if(r&&r.includes(Ia))return Ia;return null},p5=(e)=>{if(e.includes(Pge))return Ia;if(e.includes(Oge))return Qi;return null},Nge=async()=>{if(gi!==void 0)return gi;gi=null;try{let e=await s5(ub);gi=p5(e)}catch(e){}return gi},Dge=()=>{if(gi!==void 0)return gi;gi=null;try{let e=a5(ub);gi=p5(e)}catch(e){}return gi},m5=async()=>{let e=null;if(Dl()){if(e=await Nge(),!e)e=d5();if(!e){let t=await c5();e=f5(t)}}return e},h5=()=>{let e=null;if(Dl()){if(e=Dge(),!e)e=d5();if(!e){let t=l5();e=f5(t)}}return e},Lge=async()=>Dl()&&await m5()!==Qi,Bge=()=>Dl()&&h5()!==Qi,jge=async()=>{if(yi!==void 0)return yi;yi=null;try{let t=(await s5(ub)).match(u5);if(t)yi=t[1]}catch(e){}return yi},Uge=()=>{if(yi!==void 0)return yi;yi=null;try{let t=a5(ub).match(u5);if(t)yi=t[1]}catch(e){}return yi},g5=()=>{let e=o5();if(e.header&&e.header.glibcVersionRuntime)return e.header.glibcVersionRuntime;return null},n5=(e)=>e.trim().split(/\s+/)[1],y5=(e)=>{let[t,r,i]=e.split(/[\r\n]+/);if(t&&t.includes(Qi))return n5(t);if(r&&i&&r.includes(Ia))return n5(i);return null},qge=async()=>{let e=null;if(Dl()){if(e=await jge(),!e)e=g5();if(!e){let t=await c5();e=y5(t)}}return e},Zge=()=>{let e=null;if(Dl()){if(e=Uge(),!e)e=g5();if(!e){let t=l5();e=y5(t)}}return e};b5.exports={GLIBC:Qi,MUSL:Ia,family:m5,familySync:h5,isNonGlibcLinux:Lge,isNonGlibcLinuxSync:Bge,version:qge,versionSync:Zge}});var w5=Se(function(QZe,x5){var Mge={ALLOW:0,DENY:1};x5.exports=Mge});var _5=Se(function(YZe,v5){var v$={value:"SqliteError",writable:!0,enumerable:!1,configurable:!0};function Ta(e,t,r){if(new.target!==Ta)return new Ta(e,t);if(typeof t!=="string")throw TypeError("Expected second argument to be a string");Error.call(this,e),v$.value=""+e,Object.defineProperty(this,"message",v$),Error.captureStackTrace(this,Ta),this.code=t,this.rawCode=r}Object.setPrototypeOf(Ta,Error);Object.setPrototypeOf(Ta.prototype,Error.prototype);Object.defineProperty(Ta.prototype,"name",v$);v5.exports=Ta});var R5=Se(function(XZe,db){var __dirname="/home/runner/work/brains/brains/node_modules/libsql",{load:Fge,currentTarget:Hge}=G3(),{familySync:k5,GLIBC:Kge,MUSL:Jge}=S5();function Vge(){if(process.env.LIBSQL_JS_DEV)return Fge(__dirname);let e=Hge();if(k5()==Kge)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"&&k5()==Jge)e="linux-arm-musleabihf";return pr(`@libsql/${e}`)}var{databaseOpen:Wge,databaseOpenWithSync:Gge,databaseInTransaction:Qge,databaseInterrupt:Yge,databaseClose:Xge,databaseSyncSync:eye,databaseSyncUntilSync:tye,databaseExecSync:rye,databasePrepareSync:nye,databaseDefaultSafeIntegers:iye,databaseAuthorizer:oye,databaseLoadExtension:sye,databaseMaxWriteReplicationIndex:aye,statementRaw:cye,statementIsReader:lye,statementGet:E5,statementRun:I5,statementInterrupt:uye,statementRowsSync:T5,statementColumns:dye,statementSafeIntegers:fye,rowsNext:pye}=Vge(),mye=w5(),A5=_5();function Ll(e){if(e.libsqlError)return new A5(e.message,e.code,e.rawCode);return e}class $5{constructor(e,t){let r=t?.encryptionCipher??"aes256cbc";if(t&&t.syncUrl){var i="";if(t.syncAuth)console.warn("Warning: The `syncAuth` option is deprecated, please use `authToken` option instead."),i=t.syncAuth;else if(t.authToken)i=t.authToken;let o=t?.encryptionKey??"",s=t?.syncPeriod??0,a=t?.readYourWrites??!0,c=t?.offline??!1,l=t?.remoteEncryptionKey??"";this.db=Gge(e,t.syncUrl,i,r,o,s,a,c,l)}else{let o=t?.authToken??"",s=t?.encryptionKey??"",a=t?.timeout??0,c=t?.remoteEncryptionKey??"";this.db=Wge(e,o,r,s,a,c)}this.memory=e===":memory:",this.readonly=!1,this.name="",this.open=!0;let n=this.db;Object.defineProperties(this,{inTransaction:{get(){return Qge(n)}}})}sync(){return eye.call(this.db)}syncUntil(e){return tye.call(this.db,e)}prepare(e){try{let t=nye.call(this.db,e);return new C5(t)}catch(t){throw Ll(t)}}transaction(e){if(typeof e!=="function")throw TypeError("Expected first argument to be a function");let t=this,r=(n)=>(...o)=>{t.exec("BEGIN "+n);try{let s=e(...o);return t.exec("COMMIT"),s}catch(s){throw t.exec("ROLLBACK"),s}},i={default:{value:r("")},deferred:{value:r("DEFERRED")},immediate:{value:r("IMMEDIATE")},exclusive:{value:r("EXCLUSIVE")},database:{value:this,enumerable:!0}};return Object.defineProperties(i.default.value,i),Object.defineProperties(i.deferred.value,i),Object.defineProperties(i.immediate.value,i),Object.defineProperties(i.exclusive.value,i),i.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,i=this.prepare(`PRAGMA ${e}`,this,!0);return r?i.pluck().get():i.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){oye.call(this.db,e)}loadExtension(...e){sye.call(this.db,...e)}maxWriteReplicationIndex(){return aye.call(this.db)}exec(e){try{rye.call(this.db,e)}catch(t){throw Ll(t)}}interrupt(){Yge.call(this.db)}close(){Xge.call(this.db),this.open=!1}defaultSafeIntegers(e){return iye.call(this.db,e??!0),this}unsafeMode(...e){throw Error("not implemented")}}class C5{constructor(e){this.stmt=e,this.pluckMode=!1}raw(e){return cye.call(this.stmt,e??!0),this}pluck(e){return this.pluckMode=e??!0,this}get reader(){return lye.call(this.stmt)}run(...e){try{if(e.length==1&&typeof e[0]==="object")return I5.call(this.stmt,e[0]);else return I5.call(this.stmt,e.flat())}catch(t){throw Ll(t)}}get(...e){try{if(e.length==1&&typeof e[0]==="object")return E5.call(this.stmt,e[0]);else return E5.call(this.stmt,e.flat())}catch(t){throw Ll(t)}}iterate(...e){var t=void 0;if(e.length==1&&typeof e[0]==="object")t=T5.call(this.stmt,e[0]);else t=T5.call(this.stmt,e.flat());return{nextRows:Array(100),nextRowIndex:100,next(){try{if(this.nextRowIndex===100)pye.call(t,this.nextRows),this.nextRowIndex=0;let i=this.nextRows[this.nextRowIndex];if(this.nextRows[this.nextRowIndex]=void 0,!i)return{done:!0};return this.nextRowIndex++,{value:i,done:!1}}catch(i){throw Ll(i)}},[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 Ll(t)}}interrupt(){uye.call(this.stmt)}columns(){return dye.call(this.stmt)}safeIntegers(e){return fye.call(this.stmt,e??!0),this}}db.exports=$5;db.exports.Authorization=mye;db.exports.SqliteError=A5});import{Buffer as P5}from"buffer";function z5(e){if(e.scheme!=="file")throw new Be(`URL scheme ${JSON.stringify(e.scheme+":")} is not supported by the local sqlite3 client. For more information, please read ${hi}`,"URL_SCHEME_NOT_SUPPORTED");let t=e.authority;if(t!==void 0){let s=t.host.toLowerCase();if(s!==""&&s!=="localhost")throw new Be(`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 ${hi}`,"URL_INVALID");if(t.port!==void 0)throw new Be("File URL cannot have a port","URL_INVALID");if(t.userinfo!==void 0)throw new Be("File URL cannot have username and password","URL_INVALID")}let r=V3(e);if(r&&e.syncUrl)throw new Be(`Embedded replica must use file for local db but URI with in-memory mode were provided instead: ${e.path}`,"URL_INVALID");let i=e.path;if(r)i=`${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},o=new Bf.default(i,n);return Mt(o,"SELECT 1 AS checkThatTheDatabaseCanBeOpened",e.intMode),new N5(i,n,o,e.intMode)}class N5{#e;#t;#r;#n;closed;protocol;constructor(e,t,r,i){this.#e=e,this.#t=t,this.#r=r,this.#n=i,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.#i(),Mt(this.#o(),r,this.#n)}async batch(e,t="deferred"){this.#i();let r=this.#o();try{Mt(r,cs(t),this.#n);let i=[];for(let n=0;n<e.length;n++)try{if(!r.inTransaction)throw new cr("The transaction has been rolled back",n,"TRANSACTION_CLOSED");let o=e[n],s=Array.isArray(o)?{sql:o[0],args:o[1]||[]}:o;i.push(Mt(r,s,this.#n))}catch(o){if(o instanceof cr)throw o;if(o instanceof Be)throw new cr(o.message,n,o.code,o.extendedCode,o.rawCode,o.cause instanceof Error?o.cause:void 0);throw o}return Mt(r,"COMMIT",this.#n),i}finally{if(r.inTransaction)Mt(r,"ROLLBACK",this.#n)}}async migrate(e){this.#i();let t=this.#o();try{Mt(t,"PRAGMA foreign_keys=off",this.#n),Mt(t,cs("deferred"),this.#n);let r=[];for(let i=0;i<e.length;i++)try{if(!t.inTransaction)throw new cr("The transaction has been rolled back",i,"TRANSACTION_CLOSED");r.push(Mt(t,e[i],this.#n))}catch(n){if(n instanceof cr)throw n;if(n instanceof Be)throw new cr(n.message,i,n.code,n.extendedCode,n.rawCode,n.cause instanceof Error?n.cause:void 0);throw n}return Mt(t,"COMMIT",this.#n),r}finally{if(t.inTransaction)Mt(t,"ROLLBACK",this.#n);Mt(t,"PRAGMA foreign_keys=on",this.#n)}}async transaction(e="write"){let t=this.#o();return Mt(t,cs(e),this.#n),this.#r=null,new D5(t,this.#n)}async executeMultiple(e){this.#i();let t=this.#o();try{return L5(t,e)}finally{if(t.inTransaction)Mt(t,"ROLLBACK",this.#n)}}async sync(){this.#i();let e=await this.#o().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 Bf.default(this.#e,this.#t),this.closed=!1}}close(){if(this.closed=!0,this.#r!==null)this.#r.close(),this.#r=null}#i(){if(this.closed)throw new Be("The client is closed","CLIENT_CLOSED")}#o(){if(this.#r===null)this.#r=new Bf.default(this.#e,this.#t);return this.#r}}class D5{#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(),Mt(this.#e,r,this.#t)}async batch(e){let t=[];for(let r=0;r<e.length;r++)try{this.#r();let i=e[r],n=Array.isArray(i)?{sql:i[0],args:i[1]||[]}:i;t.push(Mt(this.#e,n,this.#t))}catch(i){if(i instanceof cr)throw i;if(i instanceof Be)throw new cr(i.message,r,i.code,i.extendedCode,i.rawCode,i.cause instanceof Error?i.cause:void 0);throw i}return t}async executeMultiple(e){return this.#r(),L5(this.#e,e)}async rollback(){if(!this.#e.open)return;this.#r(),Mt(this.#e,"ROLLBACK",this.#t)}async commit(){this.#r(),Mt(this.#e,"COMMIT",this.#t)}close(){if(this.#e.inTransaction)Mt(this.#e,"ROLLBACK",this.#t)}get closed(){return!this.#e.inTransaction}#r(){if(this.closed)throw new Be("The transaction is closed","TRANSACTION_CLOSED")}}function Mt(e,t,r){let i,n;if(typeof t==="string")i=t,n=[];else if(i=t.sql,Array.isArray(t.args))n=t.args.map((o)=>O5(o,r));else{n={};for(let o in t.args){let s=o[0]==="@"||o[0]==="$"||o[0]===":"?o.substring(1):o;n[s]=O5(t.args[o],r)}}try{let o=e.prepare(i);o.safeIntegers(!0);let s=!0;try{o.raw(!0)}catch{s=!1}if(s){let a=Array.from(o.columns().map((p)=>p.name)),c=Array.from(o.columns().map((p)=>p.type??"")),l=o.all(n).map((p)=>hye(p,a,r)),u=0,f=void 0;return new zl(a,c,l,0,void 0)}else{let a=o.run(n),c=a.changes,l=BigInt(a.lastInsertRowid);return new zl([],[],[],c,l)}}catch(o){throw B5(o)}}function hye(e,t,r){let i={};Object.defineProperty(i,"length",{value:e.length});for(let n=0;n<e.length;++n){let o=gye(e[n],r);Object.defineProperty(i,n,{value:o});let s=t[n];if(!Object.hasOwn(i,s))Object.defineProperty(i,s,{value:o,enumerable:!0,configurable:!0,writable:!0})}return i}function gye(e,t){if(typeof e==="bigint")if(t==="number"){if(e<yye||e>bye)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 P5)return e.buffer;return e}function O5(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<Sye||e>xye)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 P5.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 L5(e,t){try{e.exec(t)}catch(r){throw B5(r)}}function B5(e){if(e instanceof Bf.default.SqliteError){let t=e.code,r=wye(e.rawCode);return new Be(e.message,r,t,e.rawCode,e)}return e}function wye(e){if(e===void 0)return"SQLITE_UNKNOWN";let t=e&255;return vye[t]??`SQLITE_UNKNOWN_${t.toString()}`}var Bf,yye,bye=9007199254740991n,Sye,xye=9223372036854775807n,vye;var j5=S(()=>{jn();Lf();Nl();Bf=hu(R5(),1);jn();yye=-9007199254740991n;Sye=-9223372036854775808n;vye={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 us;var _$=S(()=>{if(typeof WebSocket<"u")us=WebSocket;else if(typeof global<"u")us=global.WebSocket;else if(typeof window<"u")us=window.WebSocket;else if(typeof self<"u")us=self.WebSocket});class Bl{constructor(){this.intMode="number"}intMode}var st,je,jf,Ot,Uf,jl,Aa,Un,xr,bi;var Pt=S(()=>{st=class st extends Error{constructor(e){super(e);this.name="ClientError"}};je=class je extends st{constructor(e){super(e);this.name="ProtoError"}};jf=class jf extends st{code;proto;constructor(e,t){super(e);this.name="ResponseError",this.code=t.code,this.proto=t,this.stack=void 0}};Ot=class Ot extends st{constructor(e,t){if(t!==void 0){super(`${e}: ${t}`);this.cause=t}else super(e);this.name="ClosedError"}};Uf=class Uf extends st{constructor(e){super(e);this.name="WebSocketUnsupportedError"}};jl=class jl extends st{constructor(e){super(e);this.name="WebSocketError"}};Aa=class Aa extends st{status;constructor(e,t){super(e);this.status=t,this.name="HttpServerError"}};Un=class Un extends st{constructor(e){super(e);this.name="ProtocolVersionError"}};xr=class xr extends st{constructor(e){super(e);this.name="InternalError"}};bi=class bi extends st{constructor(e){super(e);this.name="MisuseError"}}});function Fr(e){if(typeof e==="string")return e;throw Ul(e,"string")}function sn(e){if(e===null||e===void 0)return;else if(typeof e==="string")return e;throw Ul(e,"string or null")}function Yi(e){if(typeof e==="number")return e;throw Ul(e,"number")}function ds(e){if(typeof e==="boolean")return e;throw Ul(e,"boolean")}function qf(e){if(Array.isArray(e))return e;throw Ul(e,"array")}function Lt(e){if(e!==null&&typeof e==="object"&&!Array.isArray(e))return e;throw Ul(e,"object")}function qn(e,t){return qf(e).map((r)=>t(Lt(r)))}function Ul(e,t){if(e===void 0)return new je(`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 je(`Expected ${t}, received ${r}`)}function $a(e,t){return t(Lt(e))}var ql=S(()=>{Pt()});class U5{#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 i=0;i<t.length;++i){if(i!==0)this.#e.push(",");this.begin(),r(this,t[i]),this.end()}this.#e.push("]")}}function Zf(e,t){let r=[],i=new U5(r);return i.begin(),t(i,e),i.end(),r.join("")}var Ca=0,Mf=1,Ff=2,q5=5;class Z5{#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 M5{#e;#t;constructor(e){this.#e=e,this.#t=-1}setup(e){this.#t=e}#r(e){if(this.#t!==e)throw new je(`Expected wire type ${e}, got ${this.#t}`);this.#t=-1}bytes(){this.#r(Ff);let e=this.#e.varint();return this.#e.bytes(e)}string(){return new TextDecoder().decode(this.bytes())}message(e){return fs(this.bytes(),e)}int32(){return this.#r(Ca),this.#e.varint()}uint32(){return this.int32()}bool(){return this.int32()!==0}uint64(){return this.#r(Ca),this.#e.varintBig()}sint64(){let e=this.uint64();return e>>1n^-(e&1n)}double(){return this.#r(Mf),this.#e.double()}maybeSkip(){if(this.#t<0)return;else if(this.#t===Ca)this.#e.skipVarint();else if(this.#t===Mf)this.#e.skip(8);else if(this.#t===Ff){let e=this.#e.varint();this.#e.skip(e)}else if(this.#t===q5)this.#e.skip(4);else throw new je(`Unexpected wire type ${this.#t}`);this.#t=-1}}function fs(e,t){let r=new Z5(e),i=new M5(r),n=t.default();while(!r.eof()){let o=r.varint(),s=o>>3,a=o&7;i.setup(a);let c=t[s];if(c!==void 0){let l=c(i,n);if(l!==void 0)n=l}i.maybeSkip()}return n}var k$=S(()=>{Pt()});class E${#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}#i(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),i=new Uint8Array(r),n=new DataView(r);i.set(new Uint8Array(this.#e,0,this.#n)),this.#e=r,this.#t=i,this.#r=n}#o(e){this.#i(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.#i(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.#o(e<<3|t)}bytes(e,t){this.#s(e,Ff),this.#o(t.byteLength),this.#i(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 i=new E$;r(i,t),this.bytes(e,i.data())}int32(e,t){this.#s(e,Ca),this.#o(t)}uint32(e,t){this.int32(e,t)}bool(e,t){this.int32(e,t?1:0)}sint64(e,t){this.#s(e,Ca),this.#a(t<<1n^t>>63n)}double(e,t){this.#s(e,Mf),this.#i(8),this.#r.setFloat64(this.#n,t,!0),this.#n+=8}data(){return new Uint8Array(this.#e,0,this.#n)}}function Hf(e,t){let r=new E$;return t(r,e),r.data()}var F5=()=>{};var I$=S(()=>{ql();k$();F5()});class ps{#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 xr("Freeing an id that is not allocated");if(this.#t.delete(this.#e.size),e<this.#e.size)this.#t.add(e)}}var T$=S(()=>{Pt()});function rt(e,t){throw new xr(t)}var wn=S(()=>{Pt()});function Zl(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<kye||e>Eye)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 A$(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 bi("Invalid value for IntMode");else if(e instanceof Uint8Array)return e.slice().buffer;else if(e===void 0)throw new je("Received unrecognized type of Value");else throw rt(e,"Impossible type of Value")}var kye,Eye=9223372036854775807n;var $$=S(()=>{Pt();wn();kye=-9223372036854775808n});function Ra(e){return{affectedRowCount:e.affectedRowCount,lastInsertRowid:e.lastInsertRowid,columnNames:e.cols.map((t)=>t.name),columnDecltypes:e.cols.map((t)=>t.decltype)}}function pb(e,t){let r=Ra(e),i=e.rows.map((n)=>H5(r.columnNames,n,t));return{...r,rows:i}}function mb(e,t){let r=Ra(e),i;if(e.rows.length>0)i=H5(r.columnNames,e.rows[0],t);return{...r,row:i}}function hb(e,t){let r=Ra(e),i;if(e.rows.length>0&&r.columnNames.length>0)i=A$(e.rows[0][0],t);return{...r,value:i}}function H5(e,t,r){let i={};Object.defineProperty(i,"length",{value:t.length});for(let n=0;n<t.length;++n){let o=A$(t[n],r);Object.defineProperty(i,n,{value:o});let s=e[n];if(s!==void 0&&!Object.hasOwn(i,s))Object.defineProperty(i,s,{value:o,enumerable:!0,configurable:!0,writable:!0})}return i}function Xi(e){return new jf(e.message,e)}var Kf=S(()=>{Pt();$$()});class Oa{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}_getSqlId(e){if(this.#e!==e)throw new bi("Attempted to use SQL text opened with other object");else if(this.#r!==void 0)throw new Ot("SQL text is closed",this.#r);return this.#t}close(){this._setClosed(new st("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 Jf(e,t){if(t instanceof Oa)return{sqlId:t._getSqlId(e)};else return{sql:""+t}}var Ml=S(()=>{Pt()});class ms{#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 Vf{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(Zl(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]=Zl(t),this}bindName(e,t){return this._namedArgs.set(e,Zl(t)),this}unbindAll(){return this._args.length=0,this._namedArgs.clear(),this}}function gb(e,t,r){let i,n=[],o=[];if(t instanceof Vf){i=t.sql,n=t._args;for(let[c,l]of t._namedArgs.entries())o.push({name:c,value:l})}else if(Array.isArray(t))if(i=t[0],Array.isArray(t[1]))n=t[1].map((c)=>Zl(c));else o=Object.entries(t[1]).map(([c,l])=>({name:c,value:Zl(l)}));else i=t;let{sql:s,sqlId:a}=Jf(e,i);return{sql:s,sqlId:a,args:n,namedArgs:o,wantRows:r}}var yb=S(()=>{Ml();$$()});class bb{_stream;#e;_steps;#t;constructor(e,t){this._stream=e,this.#e=t,this._steps=[],this.#t=!1}step(){return new C$(this)}execute(){if(this.#t)throw new bi("This batch has already been executed");this.#t=!0;let e={steps:this._steps.map((t)=>t.proto)};if(this.#e)return Tye(this._stream,this._steps,e);else return Iye(this._stream,this._steps,e)}}function Iye(e,t,r){return e._batch(r).then((i)=>{for(let n=0;n<t.length;++n){let o=i.stepResults.get(n),s=i.stepErrors.get(n);t[n].callback(o,s)}})}async function Tye(e,t,r){let i=await e._openCursor(r);try{let n=0,o=void 0,s=[];for(;;){let a=await i.next();if(a===void 0)break;if(a.type==="step_begin"){if(a.step<n||a.step>=t.length)throw new je("Server produced StepBeginEntry for unexpected step");else if(o!==void 0)throw new je("Server produced StepBeginEntry before terminating previous step");for(let c=n;c<a.step;++c)t[c].callback(void 0,void 0);n=a.step+1,o=a,s=[]}else if(a.type==="step_end"){if(o===void 0)throw new je("Server produced StepEndEntry but no step is active");let c={cols:o.cols,rows:s,affectedRowCount:a.affectedRowCount,lastInsertRowid:a.lastInsertRowid};t[o.step].callback(c,void 0),o=void 0,s=[]}else if(a.type==="step_error"){if(o===void 0){if(a.step>=t.length)throw new je("Server produced StepErrorEntry for unexpected step");for(let c=n;c<a.step;++c)t[c].callback(void 0,void 0)}else{if(a.step!==o.step)throw new je("Server produced StepErrorEntry for unexpected step");o=void 0,s=[]}t[a.step].callback(void 0,a.error),n=a.step+1}else if(a.type==="row"){if(o===void 0)throw new je("Server produced RowEntry but no step is active");s.push(a.row)}else if(a.type==="error")throw Xi(a.error);else if(a.type==="none")throw new je("Server produced unrecognized CursorEntry");else throw rt(a,"Impossible CursorEntry")}if(o!==void 0)throw new je("Server closed Cursor before terminating active step");for(let a=n;a<t.length;++a)t[a].callback(void 0,void 0)}finally{i.close()}}class C${_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,pb)}queryRow(e){return this.#t(e,!0,mb)}queryValue(e){return this.#t(e,!0,hb)}run(e){return this.#t(e,!1,Ra)}#t(e,t,r){if(this._index!==void 0)throw new bi("This BatchStep has already been added to the batch");let i=gb(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 o={stmt:i,condition:n};return new Promise((s,a)=>{let c=(l,u)=>{if(l!==void 0&&u!==void 0)a(new je("Server returned both result and error"));else if(u!==void 0)a(Xi(u));else if(l!==void 0)s(r(l,this._batch._stream.intMode));else s(void 0)};this._index=this._batch._steps.length,this._batch._steps.push({proto:o,callback:c})})}}class wt{_batch;_proto;constructor(e,t){this._batch=e,this._proto=t}static ok(e){return new wt(e._batch,{type:"ok",step:K5(e)})}static error(e){return new wt(e._batch,{type:"error",step:K5(e)})}static not(e){return new wt(e._batch,{type:"not",cond:e._proto})}static and(e,t){for(let r of t)J5(e,r);return new wt(e,{type:"and",conds:t.map((r)=>r._proto)})}static or(e,t){for(let r of t)J5(e,r);return new wt(e,{type:"or",conds:t.map((r)=>r._proto)})}static isAutocommit(e){return e._stream.client()._ensureVersion(3,"BatchCond.isAutocommit()"),new wt(e,{type:"is_autocommit"})}}function K5(e){if(e._index===void 0)throw new bi("Cannot add a condition referencing a step that has not been added to the batch");return e._index}function J5(e,t){if(t._batch!==e)throw new bi("Cannot mix BatchCond objects for different Batch objects")}var R$=S(()=>{Pt();Kf();yb();wn()});function V5(e){return{paramNames:e.params.map((t)=>t.name),columns:e.cols,isExplain:e.isExplain,isReadonly:e.isReadonly}}class Fl{constructor(e){this.intMode=e}query(e){return this.#e(e,!0,pb)}queryRow(e){return this.#e(e,!0,mb)}queryValue(e){return this.#e(e,!0,hb)}run(e){return this.#e(e,!1,Ra)}#e(e,t,r){let i=gb(this._sqlOwner(),e,t);return this._execute(i).then((n)=>r(n,this.intMode))}batch(e=!1){return new bb(this,e)}describe(e){let t=Jf(this._sqlOwner(),e);return this._describe(t).then(V5)}sequence(e){let t=Jf(this._sqlOwner(),e);return this._sequence(t)}intMode}var Sb=S(()=>{R$();Kf();Ml();yb()});class Wf{}var Aye=1000,$ye=10,O$;var W5=S(()=>{Pt();O$=class O$ extends Wf{#e;#t;#r;#n;#i;#o;#a;constructor(e,t,r){super();this.#e=e,this.#t=t,this.#r=r,this.#n=new ms,this.#i=new ms,this.#o=void 0,this.#a=!1}async next(){for(;;){if(this.#o!==void 0)throw new Ot("Cursor is closed",this.#o);while(!this.#a&&this.#i.length<$ye)this.#i.push(this.#s());let e=this.#n.shift();if(this.#a||e!==void 0)return e;await this.#i.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:Aye}).then((e)=>e,(e)=>{this._setClosed(e);return})}_setClosed(e){if(this.#o!==void 0)return;this.#o=e,this.#t._sendCursorRequest(this,{type:"close_cursor",cursorId:this.#r}).catch(()=>{return}),this.#t._cursorClosed(this)}close(){this._setClosed(new st("Cursor was manually closed"))}get closed(){return this.#o!==void 0}}});var Gf;var P$=S(()=>{Pt();Sb();W5();Gf=class Gf extends Fl{#e;#t;#r;#n;#i;#o;static open(e){let t=e._streamIdAlloc.alloc(),r=new Gf(e,t),i=()=>{return},n=(s)=>r.#l(s),o={type:"open_stream",streamId:t};return e._sendRequest(o,{responseCallback:i,errorCallback:n}),r}constructor(e,t){super(e.intMode);this.#e=e,this.#t=t,this.#r=new ms,this.#n=void 0,this.#i=!1,this.#o=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 xr("Cursor not associated with the stream attempted to execute a request");return new Promise((r,i)=>{if(this.#o!==void 0)i(new Ot("Stream is closed",this.#o));else this.#e._sendRequest(t,{responseCallback:r,errorCallback:i})})}_cursorClosed(e){if(e!==this.#n)throw new xr("Cursor was closed, but it was not associated with the stream");this.#n=void 0,this.#c()}#s(e){if(this.#o!==void 0)e.errorCallback(new Ot("Stream is closed",this.#o));else if(this.#i)e.errorCallback(new Ot("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.#i){this.#l(new st("Stream was gracefully closed"));break}else if(e?.type==="request"&&this.#n===void 0){let{request:t,responseCallback:r,errorCallback:i}=e;this.#r.shift(),this.#e._sendRequest(t,{responseCallback:r,errorCallback:i})}else if(e?.type==="cursor"&&this.#n===void 0){let{batch:t,cursorCallback:r}=e;this.#r.shift();let i=this.#e._cursorIdAlloc.alloc(),n=new O$(this.#e,this,i),o={type:"open_cursor",streamId:this.#t,cursorId:i,batch:t},s=()=>{return},a=(c)=>n._setClosed(c);this.#e._sendRequest(o,{responseCallback:s,errorCallback:a}),this.#n=n,r(n)}else break}}#l(e){if(this.#o!==void 0)return;if(this.#o=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),i=()=>{return};this.#e._sendRequest(t,{responseCallback:r,errorCallback:i})}close(){this.#l(new st("Stream was manually closed"))}closeGracefully(){this.#i=!0,this.#c()}get closed(){return this.#o!==void 0||this.#i}}});function Qf(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,G5),e.arrayObjects("named_args",t.namedArgs,Cye),e.boolean("want_rows",t.wantRows)}function Cye(e,t){e.string("name",t.name),e.object("value",t.value,G5)}function Hl(e,t){e.arrayObjects("steps",t.steps,Rye)}function Rye(e,t){if(t.condition!==void 0)e.object("condition",t.condition,z$);e.object("stmt",t.stmt,Qf)}function z$(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,z$);else if(t.type==="and"||t.type==="or")e.arrayObjects("conds",t.conds,z$);else if(t.type==="is_autocommit");else throw rt(t,"Impossible type of BatchCond")}function G5(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",Pl.fromUint8Array(t));else if(t===void 0);else throw rt(t,"Impossible type of Value")}var N$=S(()=>{lb();wn()});function Q5(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,Oye);else throw rt(t,"Impossible type of ClientMsg")}function Oye(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,Qf);else if(t.type==="batch")e.number("stream_id",t.streamId),e.object("batch",t.batch,Hl);else if(t.type==="open_cursor")e.number("stream_id",t.streamId),e.number("cursor_id",t.cursorId),e.object("batch",t.batch,Hl);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 rt(t,"Impossible type of Request")}var Y5=S(()=>{N$();wn()});function Yf(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,e8);for(let r of t.namedArgs)e.message(4,r,Pye);e.bool(5,t.wantRows)}function Pye(e,t){e.string(1,t.name),e.message(2,t.value,e8)}function Kl(e,t){for(let r of t.steps)e.message(1,r,zye)}function zye(e,t){if(t.condition!==void 0)e.message(1,t.condition,D$);e.message(2,t.stmt,Yf)}function D$(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,D$);else if(t.type==="and")e.message(4,t.conds,X5);else if(t.type==="or")e.message(5,t.conds,X5);else if(t.type==="is_autocommit")e.message(6,void 0,t8);else throw rt(t,"Impossible type of BatchCond")}function X5(e,t){for(let r of t)e.message(1,r,D$)}function e8(e,t){if(t===null)e.message(1,void 0,t8);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 rt(t,"Impossible type of Value")}function t8(e,t){}var L$=S(()=>{wn()});function r8(e,t){if(t.type==="hello")e.message(1,t,Nye);else if(t.type==="request")e.message(2,t,Dye);else throw rt(t,"Impossible type of ClientMsg")}function Nye(e,t){if(t.jwt!==void 0)e.string(1,t.jwt)}function Dye(e,t){e.int32(1,t.requestId);let r=t.request;if(r.type==="open_stream")e.message(2,r,Lye);else if(r.type==="close_stream")e.message(3,r,Bye);else if(r.type==="execute")e.message(4,r,jye);else if(r.type==="batch")e.message(5,r,Uye);else if(r.type==="open_cursor")e.message(6,r,qye);else if(r.type==="close_cursor")e.message(7,r,Zye);else if(r.type==="fetch_cursor")e.message(8,r,Mye);else if(r.type==="sequence")e.message(9,r,Fye);else if(r.type==="describe")e.message(10,r,Hye);else if(r.type==="store_sql")e.message(11,r,Kye);else if(r.type==="close_sql")e.message(12,r,Jye);else if(r.type==="get_autocommit")e.message(13,r,Vye);else throw rt(r,"Impossible type of Request")}function Lye(e,t){e.int32(1,t.streamId)}function Bye(e,t){e.int32(1,t.streamId)}function jye(e,t){e.int32(1,t.streamId),e.message(2,t.stmt,Yf)}function Uye(e,t){e.int32(1,t.streamId),e.message(2,t.batch,Kl)}function qye(e,t){e.int32(1,t.streamId),e.int32(2,t.cursorId),e.message(3,t.batch,Kl)}function Zye(e,t){e.int32(1,t.cursorId)}function Mye(e,t){e.int32(1,t.cursorId),e.uint32(2,t.maxCount)}function Fye(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 Hye(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 Kye(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function Jye(e,t){e.int32(1,t.sqlId)}function Vye(e,t){e.int32(1,t.streamId)}var n8=S(()=>{L$();wn()});function hs(e){let t=Fr(e.message),r=sn(e.code);return{message:t,code:r}}function Xf(e){let t=qn(e.cols,i8),r=qf(e.rows).map((s)=>qn(s,o8)),i=Yi(e.affected_row_count),n=sn(e.last_insert_rowid),o=n!==void 0?BigInt(n):void 0;return{cols:t,rows:r,affectedRowCount:i,lastInsertRowid:o}}function i8(e){let t=sn(e.name),r=sn(e.decltype);return{name:t,decltype:r}}function xb(e){let t=new Map;qf(e.step_results).forEach((i,n)=>{if(i!==null)t.set(n,Xf(Lt(i)))});let r=new Map;return qf(e.step_errors).forEach((i,n)=>{if(i!==null)r.set(n,hs(Lt(i)))}),{stepResults:t,stepErrors:r}}function wb(e){let t=Fr(e.type);if(t==="step_begin"){let r=Yi(e.step),i=qn(e.cols,i8);return{type:"step_begin",step:r,cols:i}}else if(t==="step_end"){let r=Yi(e.affected_row_count),i=sn(e.last_insert_rowid),n=i!==void 0?BigInt(i):void 0;return{type:"step_end",affectedRowCount:r,lastInsertRowid:n}}else if(t==="step_error"){let r=Yi(e.step),i=hs(Lt(e.error));return{type:"step_error",step:r,error:i}}else if(t==="row")return{type:"row",row:qn(e.row,o8)};else if(t==="error")return{type:"error",error:hs(Lt(e.error))};else throw new je("Unexpected type of CursorEntry")}function vb(e){let t=qn(e.params,Wye),r=qn(e.cols,Gye),i=ds(e.is_explain),n=ds(e.is_readonly);return{params:t,cols:r,isExplain:i,isReadonly:n}}function Wye(e){return{name:sn(e.name)}}function Gye(e){let t=Fr(e.name),r=sn(e.decltype);return{name:t,decltype:r}}function o8(e){let t=Fr(e.type);if(t==="null")return null;else if(t==="integer"){let r=Fr(e.value);return BigInt(r)}else if(t==="float")return Yi(e.value);else if(t==="text")return Fr(e.value);else if(t==="blob")return Pl.toUint8Array(Fr(e.base64));else throw new je("Unexpected type of Value")}var _b=S(()=>{lb();Pt();ql()});function s8(e){let t=Fr(e.type);if(t==="hello_ok")return{type:"hello_ok"};else if(t==="hello_error")return{type:"hello_error",error:hs(Lt(e.error))};else if(t==="response_ok"){let r=Yi(e.request_id),i=Qye(Lt(e.response));return{type:"response_ok",requestId:r,response:i}}else if(t==="response_error"){let r=Yi(e.request_id),i=hs(Lt(e.error));return{type:"response_error",requestId:r,error:i}}else throw new je("Unexpected type of ServerMsg")}function Qye(e){let t=Fr(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:Xf(Lt(e.result))};else if(t==="batch")return{type:"batch",result:xb(Lt(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=qn(e.entries,wb),i=ds(e.done);return{type:"fetch_cursor",entries:r,done:i}}else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:vb(Lt(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:ds(e.is_autocommit)};else throw new je("Unexpected type of Response")}var a8=S(()=>{Pt();ql();_b()});var vn,gs,c8,l8,Jl,Yye,Xye,kb,ebe,tbe,rbe,Vl,nbe,ibe,obe;var Eb=S(()=>{vn={default(){return{message:"",code:void 0}},1(e,t){t.message=e.string()},2(e,t){t.code=e.string()}},gs={default(){return{cols:[],rows:[],affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.cols.push(e.message(c8))},2(e,t){t.rows.push(e.message(l8))},3(e,t){t.affectedRowCount=Number(e.uint64())},4(e,t){t.lastInsertRowid=e.sint64()}},c8={default(){return{name:void 0,decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},l8={default(){return[]},1(e,t){t.push(e.message(obe))}},Jl={default(){return{stepResults:new Map,stepErrors:new Map}},1(e,t){let[r,i]=e.message(Yye);t.stepResults.set(r,i)},2(e,t){let[r,i]=e.message(Xye);t.stepErrors.set(r,i)}},Yye={default(){return[0,gs.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(gs)}},Xye={default(){return[0,vn.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(vn)}},kb={default(){return{type:"none"}},1(e){return e.message(ebe)},2(e){return e.message(tbe)},3(e){return e.message(rbe)},4(e){return{type:"row",row:e.message(l8)}},5(e){return{type:"error",error:e.message(vn)}}},ebe={default(){return{type:"step_begin",step:0,cols:[]}},1(e,t){t.step=e.uint32()},2(e,t){t.cols.push(e.message(c8))}},tbe={default(){return{type:"step_end",affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.affectedRowCount=e.uint32()},2(e,t){t.lastInsertRowid=e.uint64()}},rbe={default(){return{type:"step_error",step:0,error:vn.default()}},1(e,t){t.step=e.uint32()},2(e,t){t.error=e.message(vn)}},Vl={default(){return{params:[],cols:[],isExplain:!1,isReadonly:!1}},1(e,t){t.params.push(e.message(nbe))},2(e,t){t.cols.push(e.message(ibe))},3(e,t){t.isExplain=e.bool()},4(e,t){t.isReadonly=e.bool()}},nbe={default(){return{name:void 0}},1(e,t){t.name=e.string()}},ibe={default(){return{name:"",decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},obe={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 u8,sbe,abe,cbe,lbe,ube,dbe,fbe,pbe;var d8=S(()=>{Eb();u8={default(){return{type:"none"}},1(e){return{type:"hello_ok"}},2(e){return e.message(sbe)},3(e){return e.message(cbe)},4(e){return e.message(abe)}},sbe={default(){return{type:"hello_error",error:vn.default()}},1(e,t){t.error=e.message(vn)}},abe={default(){return{type:"response_error",requestId:0,error:vn.default()}},1(e,t){t.requestId=e.int32()},2(e,t){t.error=e.message(vn)}},cbe={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(lbe)},5(e,t){t.response=e.message(ube)},6(e,t){t.response={type:"open_cursor"}},7(e,t){t.response={type:"close_cursor"}},8(e,t){t.response=e.message(dbe)},9(e,t){t.response={type:"sequence"}},10(e,t){t.response=e.message(fbe)},11(e,t){t.response={type:"store_sql"}},12(e,t){t.response={type:"close_sql"}},13(e,t){t.response=e.message(pbe)}},lbe={default(){return{type:"execute",result:gs.default()}},1(e,t){t.result=e.message(gs)}},ube={default(){return{type:"batch",result:Jl.default()}},1(e,t){t.result=e.message(Jl)}},dbe={default(){return{type:"fetch_cursor",entries:[],done:!1}},1(e,t){t.entries.push(e.message(kb))},2(e,t){t.done=e.bool()}},fbe={default(){return{type:"describe",result:Vl.default()}},1(e,t){t.result=e.message(Vl)}},pbe={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}}});var f8,B$,Ib;var Tb=S(()=>{I$();Pt();T$();Kf();Ml();wn();P$();Y5();n8();a8();d8();f8=new Map([["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]),B$=new Map([["hrana3-protobuf",{version:3,encoding:"protobuf"}],["hrana3",{version:3,encoding:"json"}],["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]);Ib=class Ib extends Bl{#e;#t;#r;#n;#i;#o;#a;#s;#c;_streamIdAlloc;_cursorIdAlloc;#l;constructor(e,t){super();this.#e=e,this.#t=[],this.#r=!1,this.#n=void 0,this.#i=!1,this.#o=void 0,this.#a=!1,this.#s=new Map,this.#c=new ps,this._streamIdAlloc=new ps,this._cursorIdAlloc=new ps,this.#l=new ps,this.#e.binaryType="arraybuffer",this.#e.addEventListener("open",()=>this.#f()),this.#e.addEventListener("close",(r)=>this.#g(r)),this.#e.addEventListener("error",(r)=>this.#p(r)),this.#e.addEventListener("message",(r)=>this.#y(r)),this.#d({type:"hello",jwt:t})}#d(e){if(this.#n!==void 0)throw new xr("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})}}#f(){let e=this.#e.protocol;if(e===void 0){this.#u(new st("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.#o={version:1,encoding:"json"};else if(this.#o=B$.get(e),this.#o===void 0){this.#u(new je(`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.#o.encoding;if(t==="json"){let r=Zf(e,Q5);this.#e.send(r)}else if(t==="protobuf"){let r=Hf(e,r8);this.#e.send(r)}else throw rt(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.#o.version);this.#t.push({openCallback:r,errorCallback:t})}else e(this.#o.version)})}_ensureVersion(e,t){if(this.#o===void 0||!this.#a)throw new Un(`${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.#o.version<e)throw new Un(`${t} is supported on protocol version ${e} and higher, but the WebSocket server only supports version ${this.#o.version}`)}_sendRequest(e,t){if(this.#n!==void 0){t.errorCallback(new Ot("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})}#p(e){let r=e.message??"WebSocket was closed due to an error";this.#u(new jl(r))}#g(e){let t=`WebSocket was closed with code ${e.code}`;if(e.reason)t+=`: ${e.reason}`;this.#u(new jl(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.#o.encoding;if(r==="json"){if(typeof e.data!=="string"){this.#e.close(3003,"Only text messages are accepted with JSON encoding"),this.#u(new je("Received non-text message from server with JSON encoding"));return}t=$a(JSON.parse(e.data),s8)}else if(r==="protobuf"){if(!(e.data instanceof ArrayBuffer)){this.#e.close(3003,"Only binary messages are accepted with Protobuf encoding"),this.#u(new je("Received non-binary message from server with Protobuf encoding"));return}t=fs(new Uint8Array(e.data),u8)}else throw rt(r,"Impossible encoding");this.#h(t)}catch(t){this.#e.close(3007,"Could not handle message"),this.#u(t)}}#h(e){if(e.type==="none")throw new je("Received an unrecognized ServerMsg");else if(e.type==="hello_ok"||e.type==="hello_error"){if(this.#i)throw new je("Received a duplicated hello response");if(this.#i=!0,e.type==="hello_error")throw Xi(e.error);return}else if(!this.#i)throw new je("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 je("Received unexpected OK response");this.#c.free(t);try{if(r.type!==e.response.type)throw console.dir({responseState:r,msg:e}),new je("Received unexpected type of response");r.responseCallback(e.response)}catch(i){throw r.errorCallback(i),i}}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 je("Received unexpected error response");this.#c.free(t),r.errorCallback(Xi(e.error))}else throw rt(e,"Impossible ServerMsg type")}openStream(){return Gf.open(this)}storeSql(e){this._ensureVersion(2,"storeSql()");let t=this.#l.alloc(),r=new Oa(this,t),i=()=>{return},n=(s)=>r._setClosed(s),o={type:"store_sql",sqlId:t,sql:e};return this._sendRequest(o,{responseCallback:i,errorCallback:n}),r}_closeSql(e){if(this.#n!==void 0)return;let t=()=>this.#l.free(e),r=(n)=>this.#u(n),i={type:"close_sql",sqlId:e};this._sendRequest(i,{responseCallback:t,errorCallback:r})}close(){this.#u(new st("Client was manually closed"))}get closed(){return this.#n!==void 0}}});var Pa;var p8=S(()=>{if(typeof queueMicrotask<"u")Pa=queueMicrotask;else{let e=Promise.resolve();Pa=(t)=>{e.then(t)}}});class j${#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 i=new Uint8Array(new ArrayBuffer(r));i.set(this.#e.slice(this.#t,this.#r),0),this.#e=i}this.#r=t,this.#t=0}shift(e){this.#t+=e}}function m8(e){let t=sn(e.baton),r=sn(e.base_url),i=qn(e.results,mbe);return{baton:t,baseUrl:r,results:i}}function mbe(e){let t=Fr(e.type);if(t==="ok")return{type:"ok",response:hbe(Lt(e.response))};else if(t==="error")return{type:"error",error:hs(Lt(e.error))};else throw new je("Unexpected type of StreamResult")}function hbe(e){let t=Fr(e.type);if(t==="close")return{type:"close"};else if(t==="execute")return{type:"execute",result:Xf(Lt(e.result))};else if(t==="batch")return{type:"batch",result:xb(Lt(e.result))};else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:vb(Lt(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:ds(e.is_autocommit)};else throw new je("Unexpected type of StreamResponse")}function h8(e){let t=sn(e.baton),r=sn(e.base_url);return{baton:t,baseUrl:r}}var U$=S(()=>{Pt();ql();_b()});var g8,gbe,ybe,bbe,Sbe,xbe,wbe,y8;var q$=S(()=>{Eb();g8={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(gbe))}},gbe={default(){return{type:"none"}},1(e){return{type:"ok",response:e.message(ybe)}},2(e){return{type:"error",error:e.message(vn)}}},ybe={default(){return{type:"none"}},1(e){return{type:"close"}},2(e){return e.message(bbe)},3(e){return e.message(Sbe)},4(e){return{type:"sequence"}},5(e){return e.message(xbe)},6(e){return{type:"store_sql"}},7(e){return{type:"close_sql"}},8(e){return e.message(wbe)}},bbe={default(){return{type:"execute",result:gs.default()}},1(e,t){t.result=e.message(gs)}},Sbe={default(){return{type:"batch",result:Jl.default()}},1(e,t){t.result=e.message(Jl)}},xbe={default(){return{type:"describe",result:Vl.default()}},1(e,t){t.result=e.message(Vl)}},wbe={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}},y8={default(){return{baton:void 0,baseUrl:void 0}},1(e,t){t.baton=e.string()},2(e,t){t.baseUrl=e.string()}}});var Z$;var b8=S(()=>{ql();k$();Pt();wn();U$();q$();_b();Eb();Z$=class Z$ extends Wf{#e;#t;#r;#n;#i;#o;constructor(e,t){super();this.#e=e,this.#t=t,this.#r=void 0,this.#n=new j$(16384),this.#i=void 0,this.#o=!1}async open(e){if(e.body===null)throw new je("No response body for cursor request");this.#r=e.body[Symbol.asyncIterator]();let t=await this.#a(h8,y8);if(t===void 0)throw new je("Empty response to cursor request");return t}next(){return this.#a(wb,kb)}close(){this._setClosed(new st("Cursor was manually closed"))}_setClosed(e){if(this.#i!==void 0)return;if(this.#i=e,this.#e._cursorClosed(this),this.#r!==void 0)this.#r.return()}get closed(){return this.#i!==void 0}async#a(e,t){for(;;){if(this.#o)return;else if(this.#i!==void 0)throw new Ot("Cursor is closed",this.#i);if(this.#t==="json"){let n=this.#s();if(n!==void 0){let o=new TextDecoder().decode(n),s=JSON.parse(o);return $a(s,e)}}else if(this.#t==="protobuf"){let n=this.#c();if(n!==void 0)return fs(n,t)}else throw rt(this.#t,"Impossible encoding");if(this.#r===void 0)throw new xr("Attempted to read from HTTP cursor before it was opened");let{value:r,done:i}=await this.#r.next();if(i&&this.#n.length===0)this.#o=!0;else if(i)throw new je("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 i=e.slice(0,r);return this.#n.shift(r+1),i}#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 i=e.slice(r,r+t);return this.#n.shift(r+t),i}}});function S8(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.arrayObjects("requests",t.requests,vbe)}function vbe(e,t){if(e.stringRaw("type",t.type),t.type==="close");else if(t.type==="execute")e.object("stmt",t.stmt,Qf);else if(t.type==="batch")e.object("batch",t.batch,Hl);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 rt(t,"Impossible type of StreamRequest")}function x8(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.object("batch",t.batch,Hl)}var M$=S(()=>{N$();wn()});function w8(e,t){if(t.baton!==void 0)e.string(1,t.baton);for(let r of t.requests)e.message(2,r,_be)}function _be(e,t){if(t.type==="close")e.message(1,t,kbe);else if(t.type==="execute")e.message(2,t,Ebe);else if(t.type==="batch")e.message(3,t,Ibe);else if(t.type==="sequence")e.message(4,t,Tbe);else if(t.type==="describe")e.message(5,t,Abe);else if(t.type==="store_sql")e.message(6,t,$be);else if(t.type==="close_sql")e.message(7,t,Cbe);else if(t.type==="get_autocommit")e.message(8,t,Rbe);else throw rt(t,"Impossible type of StreamRequest")}function kbe(e,t){}function Ebe(e,t){e.message(1,t.stmt,Yf)}function Ibe(e,t){e.message(1,t.batch,Kl)}function Tbe(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function Abe(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function $be(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function Cbe(e,t){e.int32(1,t.sqlId)}function Rbe(e,t){}function v8(e,t){if(t.baton!==void 0)e.string(1,t.baton);e.message(2,t.batch,Kl)}var F$=S(()=>{L$();wn()});function Obe(e,t){if(t.results.length!==e.length)throw new je("Server returned unexpected number of pipeline results");for(let r=0;r<e.length;++r){let i=t.results[r],n=e[r];if(i.type==="ok"){if(i.response.type!==n.request.type)throw new je("Received unexpected type of response");n.responseCallback(i.response)}else if(i.type==="error")n.errorCallback(Xi(i.error));else if(i.type==="none")throw new je("Received unrecognized type of StreamResult");else throw rt(i,"Received impossible type of StreamResult")}}async function Pbe(e,t){if(t==="json"){let r=await e.json();return $a(r,m8)}if(t==="protobuf"){let r=await e.arrayBuffer();return fs(new Uint8Array(r),g8)}throw await e.body?.cancel(),rt(t,"Impossible encoding")}async function zbe(e){let t=e.headers.get("content-type")??"text/plain",r=`Server returned HTTP status ${e.status}`;if(t==="application/json"){let i=await e.json();if("message"in i)return Xi(i);return new Aa(r,e.status)}if(t==="text/plain"){let i=(await e.text()).trim();if(i!=="")r+=`: ${i}`;return new Aa(r,e.status)}return await e.body?.cancel(),new Aa(r,e.status)}var Ab;var H$=S(()=>{Pt();I$();T$();p8();Kf();Ml();Sb();wn();b8();M$();F$();M$();F$();U$();q$();Ab=class Ab extends Fl{#e;#t;#r;#n;#i;#o;#a;#s;#c;#l;#d;#f;#m;constructor(e,t,r,i,n){super(e.intMode);this.#e=e,this.#t=t.toString(),this.#r=r,this.#n=i,this.#i=n,this.#o=void 0,this.#a=new ms,this.#s=!1,this.#l=!1,this.#d=!1,this.#f=void 0,this.#m=new ps}client(){return this.#e}_sqlOwner(){return this}storeSql(e){let t=this.#m.alloc();return this.#p({type:"store_sql",sqlId:t,sql:e}).then(()=>{return},(r)=>this._setClosed(r)),new Oa(this,t)}_closeSql(e){if(this.#f!==void 0)return;this.#p({type:"close_sql",sqlId:e}).then(()=>this.#m.free(e),(t)=>this._setClosed(t))}_execute(e){return this.#p({type:"execute",stmt:e}).then((t)=>t.result)}_batch(e){return this.#p({type:"batch",batch:e}).then((t)=>t.result)}_describe(e){return this.#p({type:"describe",sql:e.sql,sqlId:e.sqlId}).then((t)=>t.result)}_sequence(e){return this.#p({type:"sequence",sql:e.sql,sqlId:e.sqlId}).then((t)=>{return})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#p({type:"get_autocommit"}).then((e)=>e.isAutocommit)}#p(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 xr("Cursor was closed, but it was not associated with the stream");this.#c=void 0,Pa(()=>this.#u())}close(){this._setClosed(new st("Stream was manually closed"))}closeGracefully(){this.#l=!0,Pa(()=>this.#u())}get closed(){return this.#f!==void 0||this.#l}_setClosed(e){if(this.#f!==void 0)return;if(this.#f=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.#o!==void 0||this.#s)&&!this.#d)this.#a.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0,Pa(()=>this.#u())}#g(e){if(this.#f!==void 0)throw new Ot("Stream is closed",this.#f);else if(this.#l)throw new Ot("Stream is closing",void 0);else this.#a.push(e),Pa(()=>this.#u())}#u(){if(this.#s||this.#c!==void 0)return;if(this.#l&&this.#a.length===0){this._setClosed(new st("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 i=this.#a.first();if(i!==void 0&&i.type==="pipeline")r.push(i),this.#a.shift();else if(i===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.#h(e,t);else throw rt(t,"Impossible type of QueueEntry")}#y(e,t){this.#b(()=>this.#S(t,e),(r)=>Pbe(r,e.encoding),(r)=>r.baton,(r)=>r.baseUrl,(r)=>Obe(t,r),(r)=>t.forEach((i)=>i.errorCallback(r)))}#h(e,t){let r=new Z$(this,e.encoding);this.#c=r,this.#b(()=>this.#w(t,e),(i)=>r.open(i),(i)=>i.baton,(i)=>i.baseUrl,(i)=>t.cursorCallback(r),(i)=>t.errorCallback(i))}#b(e,t,r,i,n,o){let s;try{let a=e(),c=this.#n;s=c(a)}catch(a){s=Promise.reject(a)}this.#s=!0,s.then((a)=>{if(!a.ok)return zbe(a).then((c)=>{throw c});return t(a)}).then((a)=>{this.#o=r(a),this.#t=i(a)??this.#t,n(a)}).catch((a)=>{this._setClosed(a),o(a)}).finally(()=>{this.#s=!1,this.#u()})}#S(e,t){return this.#x(new URL(t.pipelinePath,this.#t),{baton:this.#o,requests:e.map((r)=>r.request)},t.encoding,S8,w8)}#w(e,t){if(t.cursorPath===void 0)throw new Un(`Cursors are supported only on protocol version 3 and higher, but the HTTP server only supports version ${t.version}.`);return this.#x(new URL(t.cursorPath,this.#t),{baton:this.#o,batch:e.batch},t.encoding,x8,v8)}#x(e,t,r,i,n){let o,s;if(r==="json")o=Zf(t,i),s="application/json";else if(r==="protobuf")o=Hf(t,n),s="application/x-protobuf";else throw rt(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.#i!==void 0)a.set("x-turso-encryption-key",this.#i);return new Request(e.toString(),{method:"POST",headers:a,body:o})}}});async function Dbe(e,t){let r=e;for(let i of Nbe){let n=new URL(i.versionPath,t),o=new Request(n.toString(),{method:"GET"}),s=await r(o);if(await s.arrayBuffer(),s.ok)return i}return K$}var Nbe,K$,$b;var J$=S(()=>{Pt();H$();Nbe=[{versionPath:"v3-protobuf",pipelinePath:"v3-protobuf/pipeline",cursorPath:"v3-protobuf/cursor",version:3,encoding:"protobuf"}],K$={versionPath:"v2",pipelinePath:"v2/pipeline",cursorPath:void 0,version:2,encoding:"json"};$b=class $b extends Bl{#e;#t;#r;#n;#i;#o;_endpointPromise;_endpoint;constructor(e,t,r,i,n=2){super();if(this.#e=e,this.#t=t,this.#r=r??globalThis.fetch,this.#n=i,this.#i=void 0,this.#o=new Set,n==3)this._endpointPromise=Dbe(this.#r,this.#e),this._endpointPromise.then((o)=>this._endpoint=o,(o)=>this.#a(o));else this._endpointPromise=Promise.resolve(K$),this._endpointPromise.then((o)=>this._endpoint=o,(o)=>this.#a(o))}async getVersion(){if(this._endpoint!==void 0)return this._endpoint.version;return(await this._endpointPromise).version}_ensureVersion(e,t){if(e<=K$.version)return;else if(this._endpoint===void 0)throw new Un(`${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 Un(`${t} is supported only on protocol version ${e} and higher, but the HTTP server only supports version ${this._endpoint.version}.`)}openStream(){if(this.#i!==void 0)throw new Ot("Client is closed",this.#i);let e=new Ab(this,this.#e,this.#t,this.#r,this.#n);return this.#o.add(e),e}_streamClosed(e){this.#o.delete(e)}close(){this.#a(new st("Client was manually closed"))}get closed(){return this.#i!==void 0}#a(e){if(this.#i!==void 0)return;this.#i=e;for(let t of Array.from(this.#o))t._setClosed(new Ot("Client was closed",e))}}});var _8=S(()=>{Pt()});function V$(e,t,r=2){if(typeof us>"u")throw new Uf("WebSockets are not supported in this environment");var i=void 0;if(r==3)i=Array.from(B$.keys());else i=Array.from(f8.keys());let n=new us(e,i);return new Ib(n,t)}function W$(e,t,r,i,n=2){return new $b(e instanceof URL?e:new URL(e),t,r,i,n)}var Cb=S(()=>{_$();Tb();Pt();J$();Tb();_$();R$();_8();Ml();yb();Sb();J$();H$();Tb();P$();Pt()});class ep{#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 Be("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{let r=e.map(eo),i;if(this.#r===void 0){this._getSqlCache().apply(r);let o=t.batch(this.#t>=3),s=o.step(),a=s.run(cs(this.#e)),c=s;i=r.map((l)=>{let u=o.step().condition(wt.ok(c));if(this.#t>=3)u.condition(wt.not(wt.isAutocommit(o)));let f=u.query(l);return f.catch(()=>{return}),c=u,f}),this.#r=o.execute().then(()=>a).then(()=>{return});try{await this.#r}catch(l){throw this.close(),l}}else{if(this.#t<3)await this.#r;this._getSqlCache().apply(r);let o=t.batch(this.#t>=3),s=void 0;i=r.map((a)=>{let c=o.step();if(s!==void 0)c.condition(wt.ok(s));if(this.#t>=3)c.condition(wt.not(wt.isAutocommit(o)));let l=c.query(a);return l.catch(()=>{return}),s=c,l}),await o.execute()}let n=[];for(let o=0;o<i.length;o++)try{let s=await i[o];if(s===void 0)throw new cr("Statement in a transaction was not executed, probably because the transaction has been rolled back",o,"TRANSACTION_CLOSED");n.push(Gl(s))}catch(s){if(s instanceof cr)throw s;let a=yt(s);if(a instanceof Be)throw new cr(a.message,o,a.code,a.extendedCode,a.rawCode,a.cause instanceof Error?a.cause:void 0);throw a}return n}catch(r){throw yt(r)}}async executeMultiple(e){let t=this._getStream();if(t.closed)throw new Be("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{if(this.#r===void 0){this.#r=t.run(cs(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 yt(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 yt(r)});e.closeGracefully(),await t}catch(e){throw yt(e)}finally{this.close()}}async commit(){try{let e=this._getStream();if(e.closed)throw new Be("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 yt(r)});e.closeGracefully(),await t}catch(e){throw yt(e)}finally{this.close()}}}async function Wl(e,t,r,i,n=!1){if(n)r.step().run("PRAGMA foreign_keys=off");let o=r.step(),s=o.run(cs(e)),a=o,c=i.map((m)=>{let y=r.step().condition(wt.ok(a));if(t>=3)y.condition(wt.not(wt.isAutocommit(r)));let g=y.query(m);return a=y,g}),l=r.step().condition(wt.ok(a));if(t>=3)l.condition(wt.not(wt.isAutocommit(r)));let u=l.run("COMMIT");if(r.step().condition(wt.not(wt.ok(l))).run("ROLLBACK").catch((m)=>{return}),n)r.step().run("PRAGMA foreign_keys=on");await r.execute();let p=[];await s;for(let m=0;m<c.length;m++)try{let y=await c[m];if(y===void 0)throw new cr("Statement in a batch was not executed, probably because the transaction has been rolled back",m,"TRANSACTION_CLOSED");p.push(Gl(y))}catch(y){if(y instanceof cr)throw y;let g=yt(y);if(g instanceof Be)throw new cr(g.message,m,g.code,g.extendedCode,g.rawCode,g.cause instanceof Error?g.cause:void 0);throw g}return await u,p}function eo(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 i=new Vf(t);if(r)if(Array.isArray(r))i.bindIndexes(r);else for(let[n,o]of Object.entries(r))i.bindName(n,o);return i}function Gl(e){let t=e.columnNames.map((s)=>s??""),r=e.columnDecltypes.map((s)=>s??""),i=e.rows,n=e.affectedRowCount,o=e.lastInsertRowid!==void 0?e.lastInsertRowid:void 0;return new zl(t,r,i,n,o)}function yt(e){if(e instanceof st){let t=k8(e);return new Be(e.message,t,void 0,void 0,e)}return e}function k8(e){if(e instanceof jf&&e.code!==void 0)return e.code;else if(e instanceof je)return"HRANA_PROTO_ERROR";else if(e instanceof Ot)return e.cause instanceof st?k8(e.cause):"HRANA_CLOSED_ERROR";else if(e instanceof jl)return"HRANA_WEBSOCKET_ERROR";else if(e instanceof Aa)return"SERVER_ERROR";else if(e instanceof Un)return"PROTOCOL_VERSION_ERROR";else if(e instanceof xr)return"INTERNAL_ERROR";else return"UNKNOWN"}var Q$=S(()=>{Cb();jn();Nl()});class Ql{#e;#t;capacity;constructor(e,t){this.#e=e,this.#t=new E8,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 i=r.sql;if(i.length>=5000)continue;let n=this.#t.get(i);if(n===void 0){while(this.#t.size+1>this.capacity){let[o,s]=this.#t.peekLru();if(t.has(s))break;s.close(),this.#t.delete(o)}if(this.#t.size+1<=this.capacity)n=this.#e.storeSql(i),this.#t.set(i,n)}if(n!==void 0)r.sql=n,t.add(n)}}}class E8{#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 Y$=Se(function(X3e,T8){function Lbe(e){var t=0,r=[];function i(){if(t--,t<e)n()}function n(){var c=r.shift();if(a.queue=r.length,c)s(c.fn).then(c.resolve).catch(c.reject)}function o(c){return new Promise(function(l,u){r.push({fn:c,resolve:l,reject:u}),a.queue=r.length})}function s(c){t++;try{return Promise.resolve(c()).then(function(l){return i(),l},function(l){throw i(),l})}catch(l){return i(),Promise.reject(l)}}var a=function(c){if(t>=e)return o(c);else return s(c)};return a}function Bbe(e,t){var r=!1,i=this;return Promise.all(e.map(function(){var n=arguments;return i(function(){if(!r)return t.apply(void 0,n).catch(function(o){throw r=!0,o})})}))}function I8(e){return e.queue=0,e.map=Bbe,e}T8.exports=function(e){if(e)return I8(Lbe(e));else return I8(function(t){return t()})}});function C8(e){if(e.scheme!=="wss"&&e.scheme!=="ws")throw new Be(`The WebSocket client supports only "libsql:", "wss:" and "ws:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${hi}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Be("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="ws"&&e.tls)throw new Be('A "ws:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="wss"&&!e.tls)throw new Be('A "wss:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=zf(e.scheme,e.authority,e.path),r;try{r=V$(t,e.authToken)}catch(i){if(i instanceof Uf){let n=e.scheme==="wss"?"https":"http",o=zf(n,e.authority,e.path);throw new Be(`This environment does not support WebSockets, please switch to the HTTP client by using a "${n}:" URL (${JSON.stringify(o)}). For more information, please read ${hi}`,"WEBSOCKETS_NOT_SUPPORTED")}throw yt(i)}return new R8(r,t,e.authToken,e.intMode,e.concurrency)}class R8{#e;#t;#r;#n;#i;closed;protocol;#o;#a;constructor(e,t,r,i,n){this.#e=t,this.#t=r,this.#r=i,this.#n=this.#c(e),this.#i=void 0,this.closed=!1,this.protocol="ws",this.#a=$8.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 i=await this.#s();try{let n=eo(r);i.conn.sqlCache.apply([n]);let o=i.stream.query(n);i.stream.closeGracefully();let s=await o;return Gl(s)}catch(n){throw yt(n)}finally{this._closeStream(i)}})}async batch(e,t="deferred"){return this.limit(async()=>{let r=await this.#s();try{let n=e.map((l)=>{if(Array.isArray(l))return{sql:l[0],args:l[1]||[]};return l}).map(eo),o=await r.conn.client.getVersion();r.conn.sqlCache.apply(n);let s=r.stream.batch(o>=3);return await Wl(t,o,s,n)}catch(i){throw yt(i)}finally{this._closeStream(r)}})}async migrate(e){return this.limit(async()=>{let t=await this.#s();try{let r=e.map(eo),i=await t.conn.client.getVersion(),n=t.stream.batch(i>=3);return await Wl("deferred",i,n,r,!0)}catch(r){throw yt(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 O8(this,t,e,r)}catch(r){throw this._closeStream(t),yt(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 yt(r)}finally{this._closeStream(t)}})}sync(){throw new Be("sync not supported in ws mode","SYNC_NOT_SUPPORTED")}async#s(){if(this.closed)throw new Be("The client is closed","CLIENT_CLOSED");if(new Date().valueOf()-this.#n.openTime.valueOf()>jbe&&this.#i===void 0){let i=this.#c();this.#i=i,i.client.getVersion().then((n)=>{if(this.#n!==i){if(this.#n.streamStates.size===0)this.#n.client.close()}this.#n=i,this.#i=void 0},(n)=>{this.#i=void 0})}if(this.#n.client.closed)try{if(this.#i!==void 0)this.#n=this.#i;else this.#n=this.#c()}catch(i){throw yt(i)}let r=this.#n;try{if(r.useSqlCache===void 0){if(r.useSqlCache=await r.client.getVersion()>=2,r.useSqlCache)r.sqlCache.capacity=A8}let i=r.client.openStream();i.intMode=this.#r;let n={conn:r,stream:i};return r.streamStates.add(n),n}catch(i){throw yt(i)}}#c(e){try{return e??=V$(this.#e,this.#t),{client:e,useSqlCache:void 0,sqlCache:new Ql(e,0),openTime:new Date,streamStates:new Set}}catch(t){throw yt(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.#i){try{this.#i.client.close()}catch{}this.#i=void 0}let e=this.#c(),t=await e.client.getVersion();if(e.useSqlCache=t>=2,e.useSqlCache)e.sqlCache.capacity=A8;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.#i){try{this.#i.client.close()}catch{}this.#i=void 0}this.closed=!0}}var $8,jbe=60000,A8=100,O8;var P8=S(()=>{Cb();jn();Lf();Q$();sb();Nl();$8=hu(Y$(),1);jn();O8=class O8 extends ep{#e;#t;constructor(e,t,r,i){super(r,i);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 N8(e){if(e.scheme!=="https"&&e.scheme!=="http")throw new Be(`The HTTP client supports only "libsql:", "https:" and "http:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${hi}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Be("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="http"&&e.tls)throw new Be('A "http:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="https"&&!e.tls)throw new Be('A "https:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=zf(e.scheme,e.authority,e.path);return new L8(t,e.authToken,e.intMode,e.fetch,e.concurrency,e.remoteEncryptionKey)}class L8{#e;protocol;#t;#r;#n;#i;#o;#a;#s;constructor(e,t,r,i,n,o){this.#t=e,this.#o=t,this.#r=r,this.#n=i,this.#i=n,this.#a=o,this.#e=W$(this.#t,this.#o,this.#n,o),this.#e.intMode=this.#r,this.protocol="http",this.#s=z8.default(this.#i)}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 i=eo(r),n,o=this.#e.openStream();try{n=o.query(i)}finally{o.closeGracefully()}let s=await n;return Gl(s)}catch(i){throw yt(i)}})}async batch(e,t="deferred"){return this.limit(async()=>{try{let i=e.map((c)=>{if(Array.isArray(c))return{sql:c[0],args:c[1]||[]};return c}).map(eo),n=await this.#e.getVersion(),o,s=this.#e.openStream();try{new Ql(s,D8).apply(i);let l=s.batch(!1);o=Wl(t,n,l,i)}finally{s.closeGracefully()}return await o}catch(r){throw yt(r)}})}async migrate(e){return this.limit(async()=>{try{let t=e.map(eo),r=await this.#e.getVersion(),i,n=this.#e.openStream();try{let s=n.batch(!1);i=Wl("deferred",r,s,t,!0)}finally{n.closeGracefully()}return await i}catch(t){throw yt(t)}})}async transaction(e="write"){return this.limit(async()=>{try{let t=await this.#e.getVersion();return new B8(this.#e.openStream(),e,t)}catch(t){throw yt(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 yt(t)}})}sync(){throw new Be("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=W$(this.#t,this.#o,this.#n,this.#a),this.#e.intMode=this.#r}}get closed(){return this.#e.closed}}var z8,D8=30,B8;var j8=S(()=>{Cb();jn();Lf();Q$();sb();Nl();z8=hu(Y$(),1);jn();B8=class B8 extends ep{#e;#t;constructor(e,t,r){super(t,r);this.#e=e,this.#t=new Ql(e,D8)}_getStream(){return this.#e}_getSqlCache(){return this.#t}close(){this.#e.close()}get closed(){return this.#e.closed}}});function Yl(e){return Ube(Df(e,!0))}function Ube(e){if(e.scheme==="wss"||e.scheme==="ws")return C8(e);else if(e.scheme==="https"||e.scheme==="http")return N8(e);else return z5(e)}var X$=S(()=>{Lf();j5();P8();j8();jn()});function ae(e,t){if(!e||typeof e!=="object")return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,J))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(J in r&&r[J]===t[J])return!0;r=Object.getPrototypeOf(r)}return!1}var J;var ze=S(()=>{J=Symbol.for("drizzle:entityKind")});var nt;var Zn=S(()=>{ze();nt=class nt{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[J]="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 tp;var Rb=S(()=>{ze();tp=class tp{static[J]="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 wr;var Xl=S(()=>{wr=Symbol.for("drizzle:Name")});var eC,U8;var q8=S(()=>{ze();Xl();eC=class eC{static[J]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,t){if(this.reference=()=>{let{name:r,columns:i,foreignColumns:n}=e();return{name:r,columns:i,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 U8(e,this)}};U8=class U8{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[J]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),i=t.map((s)=>s.name),n=r.map((s)=>s.name),o=[this.table[wr],...i,r[0].table[wr],...n];return e??`${o.join("_")}_fk`}}});function Ob(e,...t){return e(...t)}var tC=()=>{};function rC(e,t){return`${e[wr]}_${t.join("_")}_unique`}var Z8,qbe,M8;var F8=S(()=>{ze();Xl();Z8=class Z8{constructor(e,t){this.name=t,this.columns=e}static[J]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new M8(e,this.columns,this.nullsNotDistinctConfig,this.name)}};qbe=class qbe{static[J]="PgUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new Z8(e,this.name)}};M8=class M8{constructor(e,t,r,i){this.table=e,this.columns=t,this.name=i??rC(this.table,this.columns.map((n)=>n.name)),this.nullsNotDistinct=r}static[J]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}}});function H8(e,t,r){for(let i=t;i<e.length;i++){let n=e[i];if(n==="\\"){i++;continue}if(n==='"')return[e.slice(t,i).replace(/\\/g,""),i+1];if(r)continue;if(n===","||n==="}")return[e.slice(t,i).replace(/\\/g,""),i]}return[e.slice(t).replace(/\\/g,""),e.length]}function K8(e,t=0){let r=[],i=t,n=!1;while(i<e.length){let o=e[i];if(o===","){if(n||i===t)r.push("");n=!0,i++;continue}if(n=!1,o==="\\"){i+=2;continue}if(o==='"'){let[c,l]=H8(e,i+1,!0);r.push(c),i=l;continue}if(o==="}")return[r,i+1];if(o==="{"){let[c,l]=K8(e,i+1);r.push(c),i=l;continue}let[s,a]=H8(e,i,!1);r.push(s),i=a}return[r,i]}function J8(e){let[t]=K8(e,1);return t}function nC(e){return`{${e.map((t)=>{if(Array.isArray(t))return nC(t);if(typeof t==="string")return`"${t.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${t}`}).join(",")}}`}var V8=()=>{};var rp,eu,W8,Zbe,G8,iC;var Q8=S(()=>{Rb();Zn();ze();q8();tC();F8();V8();rp=class rp extends tp{foreignKeyConfigs=[];static[J]="PgColumnBuilder";array(e){return new G8(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:i})=>Ob((n,o)=>{let s=new eC(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(o.onUpdate)s.onUpdate(o.onUpdate);if(o.onDelete)s.onDelete(o.onDelete);return s.build(t)},r,i))}buildExtraConfigColumn(e){return new W8(e,this.config)}};eu=class eu extends nt{constructor(e,t){if(!t.uniqueName)t.uniqueName=rC(e,[t.name]);super(e,t);this.table=e}static[J]="PgColumn"};W8=class W8 extends eu{static[J]="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}};Zbe=class Zbe{static[J]="IndexedColumn";constructor(e,t,r,i){this.name=e,this.keyAsName=t,this.type=r,this.indexConfig=i}name;keyAsName;type;indexConfig};G8=class G8 extends rp{static[J]="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 iC(e,this.config,t)}};iC=class iC extends eu{constructor(e,t,r,i){super(e,t);this.baseColumn=r,this.range=i,this.size=t.size}size;static[J]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(e){if(typeof e==="string")e=J8(e);return e.map((t)=>this.baseColumn.mapFromDriverValue(t))}mapToDriverValue(e,t=!1){let r=e.map((i)=>i===null?null:ae(this.baseColumn,iC)?this.baseColumn.mapToDriverValue(i,!0):this.baseColumn.mapToDriverValue(i));if(t)return r;return nC(r)}}});function eH(e){return!!e&&typeof e==="function"&&Y8 in e&&e[Y8]===!0}var Mbe,X8,Y8,Fbe,tH;var rH=S(()=>{ze();Q8();Mbe=class Mbe extends rp{static[J]="PgEnumObjectColumnBuilder";constructor(e,t){super(e,"string","PgEnumObjectColumn");this.config.enum=t}build(e){return new X8(e,this.config)}};X8=class X8 extends eu{static[J]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}};Y8=Symbol.for("drizzle:isPgEnum");Fbe=class Fbe extends rp{static[J]="PgEnumColumnBuilder";constructor(e,t){super(e,"string","PgEnumColumn");this.config.enum=t}build(e){return new tH(e,this.config)}};tH=class tH extends eu{static[J]="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 vt,np;var Mn=S(()=>{ze();vt=class vt{static[J]="Subquery";constructor(e,t,r,i=!1,n=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:r,isWith:i,usedTables:n}}};np=class np extends vt{static[J]="WithSubquery"}});var nH="0.45.2";var iH=()=>{};var oC,sC,oH;var sH=S(()=>{tC();iH();oH={startActiveSpan(e,t){if(!oC)return t();if(!sC)sC=oC.trace.getTracer("drizzle-orm",nH);return Ob((r,i)=>i.startActiveSpan(e,(n)=>{try{return t(n)}catch(o){throw n.setStatus({code:r.SpanStatusCode.ERROR,message:o instanceof Error?o.message:"Unknown error"}),o}finally{n.end()}}),oC,sC)}}});var _t;var to=S(()=>{_t=Symbol.for("drizzle:ViewBaseConfig")});function ys(e){return e[wr]}function za(e){return`${e[Pb]??"public"}.${e[wr]}`}var Pb,zb,aH,aC,cC,ip,cH,Hbe,we;var vr=S(()=>{ze();Xl();Pb=Symbol.for("drizzle:Schema"),zb=Symbol.for("drizzle:Columns"),aH=Symbol.for("drizzle:ExtraConfigColumns"),aC=Symbol.for("drizzle:OriginalName"),cC=Symbol.for("drizzle:BaseName"),ip=Symbol.for("drizzle:IsAlias"),cH=Symbol.for("drizzle:ExtraConfigBuilder"),Hbe=Symbol.for("drizzle:IsDrizzleTable");we=class we{static[J]="Table";static Symbol={Name:wr,Schema:Pb,OriginalName:aC,Columns:zb,ExtraConfigColumns:aH,BaseName:cC,IsAlias:ip,ExtraConfigBuilder:cH};[wr];[aC];[Pb];[zb];[aH];[cC];[ip]=!1;[Hbe]=!0;[cH]=void 0;constructor(e,t,r){this[wr]=this[aC]=e,this[Pb]=t,this[cC]=r}}});function lC(e){return e!==null&&e!==void 0&&typeof e.getSQL==="function"}function Jbe(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 lH(e){return typeof e==="object"&&e!==null&&"mapToDriverValue"in e&&typeof e.mapToDriverValue==="function"}function U(e,...t){let r=[];if(t.length>0||e.length>0&&e[0]!=="")r.push(new Ft(e[0]));for(let[i,n]of t.entries())r.push(n,new Ft(e[i+1]));return new Te(r)}function op(e,t){return e.map((r)=>{if(ae(r,bs)){if(!(r.name in t))throw Error(`No value for placeholder "${r.name}" was provided`);return t[r.name]}if(ae(r,an)&&ae(r.value,bs)){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 Kbe,Ft,Te,Nb,uH,dH,u8e,an,bs,Vbe,_n;var ur=S(()=>{ze();rH();Mn();sH();to();Zn();vr();Kbe=class Kbe{static[J]="FakePrimitiveParam"};Ft=class Ft{static[J]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new Te([this])}};Te=class Te{constructor(e){this.queryChunks=e;for(let t of e)if(ae(t,we)){let r=t[we.Symbol.Schema];this.usedTables.push(r===void 0?t[we.Symbol.Name]:r+"."+t[we.Symbol.Name])}}static[J]="SQL";decoder=uH;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return oH.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:i,escapeName:n,escapeParam:o,prepareTyping:s,inlineParams:a,paramStartIndex:c}=r;return Jbe(e.map((l)=>{if(ae(l,Ft))return{sql:l.value.join(""),params:[]};if(ae(l,Nb))return{sql:n(l.value),params:[]};if(l===void 0)return{sql:"",params:[]};if(Array.isArray(l)){let u=[new Ft("(")];for(let[f,p]of l.entries())if(u.push(p),f<l.length-1)u.push(new Ft(", "));return u.push(new Ft(")")),this.buildQueryFromSourceParams(u,r)}if(ae(l,Te))return this.buildQueryFromSourceParams(l.queryChunks,{...r,inlineParams:a||l.shouldInlineParams});if(ae(l,we)){let u=l[we.Symbol.Schema],f=l[we.Symbol.Name];return{sql:u===void 0||l[ip]?n(f):n(u)+"."+n(f),params:[]}}if(ae(l,nt)){let u=i.getColumnCasing(l);if(t.invokeSource==="indexes")return{sql:n(u),params:[]};let f=l.table[we.Symbol.Schema];return{sql:l.table[ip]||f===void 0?n(l.table[we.Symbol.Name])+"."+n(u):n(f)+"."+n(l.table[we.Symbol.Name])+"."+n(u),params:[]}}if(ae(l,_n)){let u=l[_t].schema,f=l[_t].name;return{sql:u===void 0||l[_t].isAlias?n(f):n(u)+"."+n(f),params:[]}}if(ae(l,an)){if(ae(l.value,bs))return{sql:o(c.value++,l),params:[l],typings:["none"]};let u=l.value===null?null:l.encoder.mapToDriverValue(l.value);if(ae(u,Te))return this.buildQueryFromSourceParams([u],r);if(a)return{sql:this.mapInlineParam(u,r),params:[]};let f=["none"];if(s)f=[s(l.encoder)];return{sql:o(c.value++,u),params:[u],typings:f}}if(ae(l,bs))return{sql:o(c.value++,l),params:[l],typings:["none"]};if(ae(l,Te.Aliased)&&l.fieldAlias!==void 0)return{sql:n(l.fieldAlias),params:[]};if(ae(l,vt)){if(l._.isWith)return{sql:n(l._.alias),params:[]};return this.buildQueryFromSourceParams([new Ft("("),l._.sql,new Ft(") "),new Nb(l._.alias)],r)}if(eH(l)){if(l.schema)return{sql:n(l.schema)+"."+n(l.enumName),params:[]};return{sql:n(l.enumName),params:[]}}if(lC(l)){if(l.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([l.getSQL()],r);return this.buildQueryFromSourceParams([new Ft("("),l.getSQL(),new Ft(")")],r)}if(a)return{sql:this.mapInlineParam(l,r),params:[]};return{sql:o(c.value++,l),params:[l],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 Te.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}};Nb=class Nb{constructor(e){this.value=e}static[J]="Name";brand;getSQL(){return new Te([this])}};uH={mapFromDriverValue:(e)=>e},dH={mapToDriverValue:(e)=>e},u8e={...uH,...dH};an=class an{constructor(e,t=dH){this.value=e,this.encoder=t}static[J]="Param";brand;getSQL(){return new Te([this])}};((e)=>{function t(){return new Te([])}e.empty=t;function r(c){return new Te(c)}e.fromList=r;function i(c){return new Te([new Ft(c)])}e.raw=i;function n(c,l){let u=[];for(let[f,p]of c.entries()){if(f>0&&l!==void 0)u.push(l);u.push(p)}return new Te(u)}e.join=n;function o(c){return new Nb(c)}e.identifier=o;function s(c){return new bs(c)}e.placeholder=s;function a(c,l){return new an(c,l)}e.param=a})(U||(U={}));((e)=>{class t{constructor(r,i){this.sql=r,this.fieldAlias=i}static[J]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new t(this.sql,this.fieldAlias)}}e.Aliased=t})(Te||(Te={}));bs=class bs{constructor(e){this.name=e}static[J]="Placeholder";getSQL(){return new Te([this])}};Vbe=Symbol.for("drizzle:IsDrizzleView");_n=class _n{static[J]="View";[_t];[Vbe]=!0;constructor({name:e,schema:t,selectedFields:r,query:i}){this[_t]={name:e,originalName:e,schema:t,selectedFields:r,query:i,isExisting:!i,isAlias:!1}}getSQL(){return new Te([this])}};nt.prototype.getSQL=function(){return new Te([this])};we.prototype.getSQL=function(){return new Te([this])};vt.prototype.getSQL=function(){return new Te([this])}});function uC(e,t,r){let i={},n=e.reduce((o,{path:s,field:a},c)=>{let l;if(ae(a,nt))l=a;else if(ae(a,Te))l=a.decoder;else if(ae(a,vt))l=a._.sql.decoder;else l=a.sql.decoder;let u=o;for(let[f,p]of s.entries())if(f<s.length-1){if(!(p in u))u[p]={};u=u[p]}else{let m=t[c],y=u[p]=m===null?null:l.mapFromDriverValue(m);if(r&&ae(a,nt)&&s.length===2){let g=s[0];if(!(g in i))i[g]=y===null?ys(a.table):!1;else if(typeof i[g]==="string"&&i[g]!==ys(a.table))i[g]=!1}}return o},{});if(r&&Object.keys(i).length>0){for(let[o,s]of Object.entries(i))if(typeof s==="string"&&!r[s])n[o]=null}return n}function kn(e,t){return Object.entries(e).reduce((r,[i,n])=>{if(typeof i!=="string")return r;let o=t?[...t,i]:[i];if(ae(n,nt)||ae(n,Te)||ae(n,Te.Aliased)||ae(n,vt))r.push({path:o,field:n});else if(ae(n,we))r.push(...kn(n[we.Symbol.Columns],o));else r.push(...kn(n,o));return r},[])}function sp(e,t){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let[n,o]of r.entries())if(o!==i[n])return!1;return!0}function Db(e,t){let r=Object.entries(t).filter(([,i])=>i!==void 0).map(([i,n])=>{if(ae(n,Te)||ae(n,nt))return[i,n];else return[i,new an(n,e[we.Symbol.Columns][i])]});if(r.length===0)throw Error("No values to set");return Object.fromEntries(r)}function fH(e,t){for(let r of t)for(let i of Object.getOwnPropertyNames(r.prototype)){if(i==="constructor")continue;Object.defineProperty(e.prototype,i,Object.getOwnPropertyDescriptor(r.prototype,i)||Object.create(null))}}function Lb(e){return e[we.Symbol.Columns]}function ap(e){return ae(e,vt)?e._.alias:ae(e,_n)?e[_t].name:ae(e,Te)?void 0:e[we.Symbol.IsAlias]?e[we.Symbol.Name]:e[we.Symbol.BaseName]}function Si(e,t){return{name:typeof e==="string"&&e.length>0?e:"",config:typeof e==="object"?e:t}}function pH(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 dC;var Dr=S(()=>{Zn();ze();ur();Mn();vr();to();dC=typeof TextDecoder>"u"?null:new TextDecoder});var mH,fC,pC;var Bb=S(()=>{ze();mH=class mH{static[J]="ConsoleLogWriter";write(e){console.log(e)}};fC=class fC{static[J]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new mH}logQuery(e,t){let r=t.map((n)=>{try{return JSON.stringify(n)}catch{return String(n)}}),i=r.length?` -- params: [${r.join(", ")}]`:"";this.writer.write(`Query: ${e}${i}`)}};pC=class pC{static[J]="NoopLogger";logQuery(){}}});var hH,gH,mC;var yH=S(()=>{ze();vr();hH=Symbol.for("drizzle:PgInlineForeignKeys"),gH=Symbol.for("drizzle:EnableRLS");mC=class mC extends we{static[J]="PgTable";static Symbol=Object.assign({},we.Symbol,{InlineForeignKeys:hH,EnableRLS:gH});[hH]=[];[gH]=!1;[we.Symbol.ExtraConfigBuilder]=void 0;[we.Symbol.ExtraConfigColumns]={}}});var hC,bH;var SH=S(()=>{ze();yH();hC=class hC{static[J]="PgPrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new bH(e,this.columns,this.name)}};bH=class bH{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[J]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[mC.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function Hr(e,t){if(lH(t)&&!lC(e)&&!ae(e,an)&&!ae(e,bs)&&!ae(e,nt)&&!ae(e,we)&&!ae(e,_n))return new an(e,t);return e}function It(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new Te(t);return new Te([new Ft("("),U.join(t,new Ft(" and ")),new Ft(")")])}function xi(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new Te(t);return new Te([new Ft("("),U.join(t,new Ft(" or ")),new Ft(")")])}function wH(e){return U`not ${e}`}function Ss(e,t){if(Array.isArray(t)){if(t.length===0)return U`false`;return U`${e} in ${t.map((r)=>Hr(r,e))}`}return U`${e} in ${Hr(t,e)}`}function jb(e,t){if(Array.isArray(t)){if(t.length===0)return U`true`;return U`${e} not in ${t.map((r)=>Hr(r,e))}`}return U`${e} not in ${Hr(t,e)}`}function En(e){return U`${e} is null`}function kH(e){return U`${e} is not null`}function Ub(e){return U`exists ${e}`}function lp(e){return U`not exists ${e}`}function EH(e,t,r){return U`${e} between ${Hr(t,e)} and ${Hr(r,e)}`}function IH(e,t,r){return U`${e} not between ${Hr(t,e)} and ${Hr(r,e)}`}function TH(e,t){return U`${e} like ${t}`}function AH(e,t){return U`${e} not like ${t}`}function $H(e,t){return U`${e} ilike ${t}`}function CH(e,t){return U`${e} not ilike ${t}`}var Qe=(e,t)=>U`${e} = ${Hr(t,e)}`,xH=(e,t)=>U`${e} <> ${Hr(t,e)}`,cp=(e,t)=>U`${e} > ${Hr(t,e)}`,vH=(e,t)=>U`${e} >= ${Hr(t,e)}`,_H=(e,t)=>U`${e} < ${Hr(t,e)}`,tu=(e,t)=>U`${e} <= ${Hr(t,e)}`;var RH=S(()=>{Zn();ze();vr();ur()});function ro(e){return U`${e} asc`}function Na(e){return U`${e} desc`}var OH=S(()=>{ur()});var gC=S(()=>{RH();OH()});function zH(){return{and:It,between:EH,eq:Qe,exists:Ub,gt:cp,gte:vH,ilike:$H,inArray:Ss,isNull:En,isNotNull:kH,like:TH,lt:_H,lte:tu,ne:xH,not:wH,notBetween:IH,notExists:lp,notLike:AH,notIlike:CH,notInArray:jb,or:xi,sql:U}}function NH(){return{sql:U,asc:ro,desc:Na}}function DH(e,t){if(Object.keys(e).length===1&&"default"in e&&!ae(e.default,we))e=e.default;let r={},i={},n={};for(let[o,s]of Object.entries(e))if(ae(s,we)){let a=za(s),c=i[a];r[a]=o,n[o]={tsName:o,dbName:s[we.Symbol.Name],schema:s[we.Symbol.Schema],columns:s[we.Symbol.Columns],relations:c?.relations??{},primaryKey:c?.primaryKey??[]};for(let u of Object.values(s[we.Symbol.Columns]))if(u.primary)n[o].primaryKey.push(u);let l=s[we.Symbol.ExtraConfigBuilder]?.(s[we.Symbol.ExtraConfigColumns]);if(l){for(let u of Object.values(l))if(ae(u,hC))n[o].primaryKey.push(...u.columns)}}else if(ae(s,PH)){let a=za(s.table),c=r[a],l=s.config(t(s.table)),u;for(let[f,p]of Object.entries(l))if(c){let m=n[c];if(m.relations[f]=p,u)m.primaryKey.push(...u)}else{if(!(a in i))i[a]={relations:{},primaryKey:u};i[a].relations[f]=p}}return{tables:n,tableNamesMap:r}}function Wbe(e){return function(r,i){return new xs(e,r,i,i?.fields.reduce((n,o)=>n&&o.notNull,!0)??!1)}}function Gbe(e){return function(r,i){return new up(e,r,i)}}function LH(e,t,r){if(ae(r,xs)&&r.config)return{fields:r.config.fields,references:r.config.references};let i=t[za(r.referencedTable)];if(!i)throw Error(`Table "${r.referencedTable[we.Symbol.Name]}" not found in schema`);let n=e[i];if(!n)throw Error(`Table "${i}" not found in schema`);let o=r.sourceTable,s=t[za(o)];if(!s)throw Error(`Table "${o[we.Symbol.Name]}" not found in schema`);let a=[];for(let c of Object.values(n.relations))if(r.relationName&&r!==c&&c.relationName===r.relationName||!r.relationName&&c.referencedTable===r.sourceTable)a.push(c);if(a.length>1)throw r.relationName?Error(`There are multiple relations with name "${r.relationName}" in table "${i}"`):Error(`There are multiple relations between "${i}" and "${r.sourceTable[we.Symbol.Name]}". Please specify relation name`);if(a[0]&&ae(a[0],xs)&&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 BH(e){return{one:Wbe(e),many:Gbe(e)}}function qb(e,t,r,i,n=(o)=>o){let o={};for(let[s,a]of i.entries())if(a.isJson){let c=t.relations[a.tsKey],l=r[s],u=typeof l==="string"?JSON.parse(l):l;o[a.tsKey]=ae(c,xs)?u&&qb(e,e[a.relationTableTsKey],u,a.selection,n):u.map((f)=>qb(e,e[a.relationTableTsKey],f,a.selection,n))}else{let c=n(r[s]),l=a.field,u;if(ae(l,nt))u=l;else if(ae(l,Te))u=l.decoder;else u=l.sql.decoder;o[a.tsKey]=c===null?null:u.mapFromDriverValue(c)}return o}var yC,PH,xs,up;var dp=S(()=>{vr();Zn();ze();SH();gC();ur();yC=class yC{constructor(e,t,r){this.sourceTable=e,this.referencedTable=t,this.relationName=r,this.referencedTableName=t[we.Symbol.Name]}static[J]="Relation";referencedTableName;fieldName};PH=class PH{constructor(e,t){this.table=e,this.config=t}static[J]="Relations"};xs=class xs extends yC{constructor(e,t,r,i){super(e,t,r?.relationName);this.config=r,this.isNullable=i}static[J]="One";withFieldName(e){let t=new xs(this.sourceTable,this.referencedTable,this.config,this.isNullable);return t.fieldName=e,t}};up=class up extends yC{constructor(e,t,r){super(e,t,r?.relationName);this.config=r}static[J]="Many";withFieldName(e){let t=new up(this.sourceTable,this.referencedTable,this.config);return t.fieldName=e,t}}});function fp(e,t){return new Proxy(e,new Da(t,!1))}function wi(e,t){return new Proxy(e,new ru(new Proxy(e.table,new Da(t,!1))))}function bC(e,t){return new Te.Aliased(pp(e.sql,t),e.fieldAlias)}function pp(e,t){return U.join(e.queryChunks.map((r)=>{if(ae(r,nt))return wi(r,t);if(ae(r,Te))return pp(r,t);if(ae(r,Te.Aliased))return bC(r,t);return r}))}var ru,Da,Qbe;var mp=S(()=>{Zn();ze();ur();vr();to();ru=class ru{constructor(e){this.table=e}static[J]="ColumnAliasProxyHandler";get(e,t){if(t==="table")return this.table;return e[t]}};Da=class Da{constructor(e,t){this.alias=e,this.replaceOriginalName=t}static[J]="TableAliasProxyHandler";get(e,t){if(t===we.Symbol.IsAlias)return!0;if(t===we.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===we.Symbol.OriginalName)return this.alias;if(t===_t)return{...e[_t],name:this.alias,isAlias:!0};if(t===we.Symbol.Columns){let i=e[we.Symbol.Columns];if(!i)return i;let n={};return Object.keys(i).map((o)=>{n[o]=new Proxy(i[o],new ru(new Proxy(e,this)))}),n}let r=e[t];if(ae(r,nt))return new Proxy(r,new ru(new Proxy(e,this)));return r}};Qbe=class Qbe{constructor(e){this.alias=e}static[J]="RelationTableAliasProxyHandler";get(e,t){if(t==="sourceTable")return fp(e.sourceTable,this.alias);return e[t]}}});var bt;var La=S(()=>{mp();Zn();ze();ur();Mn();to();bt=class bt{static[J]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t==="_")return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(t===_t)return{...e[_t],selectedFields:new Proxy(e[_t].selectedFields,this)};if(typeof t==="symbol")return e[t];let i=(ae(e,vt)?e._.selectedFields:ae(e,_n)?e[_t].selectedFields:e)[t];if(ae(i,Te.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!i.isSelectionField)return i.sql;let n=i.clone();return n.isSelectionField=!0,n}if(ae(i,Te)){if(this.config.sqlBehavior==="sql")return i;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(ae(i,nt)){if(this.config.alias)return new Proxy(i,new ru(new Proxy(i.table,new Da(this.config.alias,this.config.replaceOriginalName??!1))));return i}if(typeof i!=="object"||i===null)return i;return new Proxy(i,new bt(this.config))}}});var Lr;var no=S(()=>{ze();Lr=class Lr{static[J]="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 SC,jH;var xC=S(()=>{ze();Xl();SC=class SC{static[J]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(e,t){if(this.reference=()=>{let{name:r,columns:i,foreignColumns:n}=e();return{name:r,columns:i,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 jH(e,this)}};jH=class jH{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[J]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),i=t.map((s)=>s.name),n=r.map((s)=>s.name),o=[this.table[wr],...i,r[0].table[wr],...n];return e??`${o.join("_")}_fk`}}});function wC(e,t){return`${e[wr]}_${t.join("_")}_unique`}var UH,Ybe,qH;var vC=S(()=>{ze();Xl();UH=class UH{constructor(e,t){this.name=t,this.columns=e}static[J]="SQLiteUniqueConstraintBuilder";columns;build(e){return new qH(e,this.columns,this.name)}};Ybe=class Ybe{static[J]="SQLiteUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new UH(e,this.name)}};qH=class qH{constructor(e,t,r){this.table=e,this.columns=t,this.name=r??wC(this.table,this.columns.map((i)=>i.name))}static[J]="SQLiteUniqueConstraint";columns;name;getName(){return this.name}}});var Qt,Tt;var ws=S(()=>{Rb();Zn();ze();xC();vC();Qt=class Qt extends tp{static[J]="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:i})=>((n,o)=>{let s=new SC(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(o.onUpdate)s.onUpdate(o.onUpdate);if(o.onDelete)s.onDelete(o.onDelete);return s.build(t)})(r,i))}};Tt=class Tt extends nt{constructor(e,t){if(!t.uniqueName)t.uniqueName=wC(e,[t.name]);super(e,t);this.table=e}static[J]="SQLiteColumn"}});function VH(e,t){let{name:r,config:i}=Si(e,t);if(i?.mode==="json")return new FH(r);if(i?.mode==="bigint")return new ZH(r);return new KH(r)}var ZH,MH,FH,HH,KH,JH;var _C=S(()=>{ze();Dr();ws();ZH=class ZH extends Qt{static[J]="SQLiteBigIntBuilder";constructor(e){super(e,"bigint","SQLiteBigInt")}build(e){return new MH(e,this.config)}};MH=class MH extends Tt{static[J]="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(dC.decode(e))}mapToDriverValue(e){return Buffer.from(e.toString())}};FH=class FH extends Qt{static[J]="SQLiteBlobJsonBuilder";constructor(e){super(e,"json","SQLiteBlobJson")}build(e){return new HH(e,this.config)}};HH=class HH extends Tt{static[J]="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(dC.decode(e))}mapToDriverValue(e){return Buffer.from(JSON.stringify(e))}};KH=class KH extends Qt{static[J]="SQLiteBlobBufferBuilder";constructor(e){super(e,"buffer","SQLiteBlobBuffer")}build(e){return new JH(e,this.config)}};JH=class JH extends Tt{static[J]="SQLiteBlobBuffer";mapFromDriverValue(e){if(Buffer.isBuffer(e))return e;return Buffer.from(e)}getSQLType(){return"blob"}}});function QH(e){return(t,r)=>{let{name:i,config:n}=Si(t,r);return new WH(i,n,e)}}var WH,GH;var kC=S(()=>{ze();Dr();ws();WH=class WH extends Qt{static[J]="SQLiteCustomColumnBuilder";constructor(e,t,r){super(e,"custom","SQLiteCustomColumn");this.config.fieldConfig=t,this.config.customTypeParams=r}build(e){return new GH(e,this.config)}};GH=class GH extends Tt{static[J]="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 _r(e,t){let{name:r,config:i}=Si(e,t);if(i?.mode==="timestamp"||i?.mode==="timestamp_ms")return new eK(r,i.mode);if(i?.mode==="boolean")return new rK(r,i.mode);return new YH(r)}var Zb,Mb,YH,XH,eK,tK,rK,nK;var EC=S(()=>{ze();ur();Dr();ws();Zb=class Zb extends Qt{static[J]="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()}};Mb=class Mb extends Tt{static[J]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}};YH=class YH extends Zb{static[J]="SQLiteIntegerBuilder";constructor(e){super(e,"number","SQLiteInteger")}build(e){return new XH(e,this.config)}};XH=class XH extends Mb{static[J]="SQLiteInteger"};eK=class eK extends Zb{static[J]="SQLiteTimestampBuilder";constructor(e,t){super(e,"date","SQLiteTimestamp");this.config.mode=t}defaultNow(){return this.default(U`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new tK(e,this.config)}};tK=class tK extends Mb{static[J]="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}};rK=class rK extends Zb{static[J]="SQLiteBooleanBuilder";constructor(e,t){super(e,"boolean","SQLiteBoolean");this.config.mode=t}build(e){return new nK(e,this.config)}};nK=class nK extends Mb{static[J]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue(e){return Number(e)===1}mapToDriverValue(e){return e?1:0}}});function uK(e,t){let{name:r,config:i}=Si(e,t),n=i?.mode;return n==="number"?new sK(r):n==="bigint"?new cK(r):new iK(r)}var iK,oK,sK,aK,cK,lK;var IC=S(()=>{ze();Dr();ws();iK=class iK extends Qt{static[J]="SQLiteNumericBuilder";constructor(e){super(e,"string","SQLiteNumeric")}build(e){return new oK(e,this.config)}};oK=class oK extends Tt{static[J]="SQLiteNumeric";mapFromDriverValue(e){if(typeof e==="string")return e;return String(e)}getSQLType(){return"numeric"}};sK=class sK extends Qt{static[J]="SQLiteNumericNumberBuilder";constructor(e){super(e,"number","SQLiteNumericNumber")}build(e){return new aK(e,this.config)}};aK=class aK extends Tt{static[J]="SQLiteNumericNumber";mapFromDriverValue(e){if(typeof e==="number")return e;return Number(e)}mapToDriverValue=String;getSQLType(){return"numeric"}};cK=class cK extends Qt{static[J]="SQLiteNumericBigIntBuilder";constructor(e){super(e,"bigint","SQLiteNumericBigInt")}build(e){return new lK(e,this.config)}};lK=class lK extends Tt{static[J]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}});function pK(e){return new dK(e??"")}var dK,fK;var TC=S(()=>{ze();ws();dK=class dK extends Qt{static[J]="SQLiteRealBuilder";constructor(e){super(e,"number","SQLiteReal")}build(e){return new fK(e,this.config)}};fK=class fK extends Tt{static[J]="SQLiteReal";getSQLType(){return"real"}}});function dr(e,t={}){let{name:r,config:i}=Si(e,t);if(i.mode==="json")return new gK(r);return new mK(r,i)}var mK,hK,gK,yK;var AC=S(()=>{ze();Dr();ws();mK=class mK extends Qt{static[J]="SQLiteTextBuilder";constructor(e,t){super(e,"string","SQLiteText");this.config.enumValues=t.enum,this.config.length=t.length}build(e){return new hK(e,this.config)}};hK=class hK extends Tt{static[J]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor(e,t){super(e,t)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}};gK=class gK extends Qt{static[J]="SQLiteTextJsonBuilder";constructor(e){super(e,"json","SQLiteTextJson")}build(e){return new yK(e,this.config)}};yK=class yK extends Tt{static[J]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue(e){return JSON.parse(e)}mapToDriverValue(e){return JSON.stringify(e)}}});function bK(){return{blob:VH,customType:QH,integer:_r,numeric:uK,real:pK,text:dr}}var SK=S(()=>{_C();kC();EC();IC();TC();AC()});function Xbe(e,t,r,i,n=e){let o=new Bt(e,i,n),s=typeof t==="function"?t(bK()):t,a=Object.fromEntries(Object.entries(s).map(([l,u])=>{let f=u;f.setName(l);let p=f.build(o);return o[$C].push(...f.buildForeignKeys(p,o)),[l,p]})),c=Object.assign(o,a);if(c[we.Symbol.Columns]=a,c[we.Symbol.ExtraConfigColumns]=a,r)c[Bt.Symbol.ExtraConfigBuilder]=r;return c}var $C,Bt,hp=(e,t,r)=>Xbe(e,t,r);var io=S(()=>{ze();vr();SK();$C=Symbol.for("drizzle:SQLiteInlineForeignKeys");Bt=class Bt extends we{static[J]="SQLiteTable";static Symbol=Object.assign({},we.Symbol,{InlineForeignKeys:$C});[we.Symbol.Columns];[$C]=[];[we.Symbol.ExtraConfigBuilder]=void 0}});var eSe,xK;var wK=S(()=>{ze();eSe=class eSe{constructor(e,t){this.name=e,this.value=t}static[J]="SQLiteCheckBuilder";brand;build(e){return new xK(e,this)}};xK=class xK{constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}static[J]="SQLiteCheck";name;value}});function oo(e){return new vK(e,!1)}var vK,_K,kK;var EK=S(()=>{ze();vK=class vK{constructor(e,t){this.name=e,this.unique=t}static[J]="SQLiteIndexBuilderOn";on(...e){return new _K(this.name,e,this.unique)}};_K=class _K{static[J]="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 kK(this.config,e)}};kK=class kK{static[J]="SQLiteIndex";config;constructor(e,t){this.config={...e,table:t}}}});var tSe,IK;var TK=S(()=>{ze();io();tSe=class tSe{static[J]="SQLitePrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new IK(e,this.columns,this.name)}};IK=class IK{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[J]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[Bt.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function Fn(e){if(ae(e,Bt))return[`${e[we.Symbol.BaseName]}`];if(ae(e,vt))return e._.usedTables??[];if(ae(e,Te))return e.usedTables??[];return[]}var nu=S(()=>{ze();ur();Mn();vr();io()});var Fb;var AK=S(()=>{ze();no();La();io();vr();Dr();nu();Fb=class Fb extends Lr{constructor(e,t,r,i){super();this.table=e,this.session=t,this.dialect=r,this.config={table:e,withList:i}}static[J]="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[we.Symbol.Columns],new bt({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[Bt.Symbol.Columns]){return this.config.returning=kn(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:Fn(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 rSe(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((r)=>r.toLowerCase()).join("_")}function nSe(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((r,i,n)=>{let o=n===0?i.toLowerCase():`${i[0].toUpperCase()}${i.slice(1)}`;return r+o},"")}function iSe(e){return e}var CC;var $K=S(()=>{ze();vr();CC=class CC{static[J]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert=e==="snake_case"?rSe:e==="camelCase"?nSe:iSe}getColumnCasing(e){if(!e.keyAsName)return e.name;let t=e.table[we.Symbol.Schema]??"public",r=e.table[we.Symbol.OriginalName],i=`${t}.${r}.${e.name}`;if(!this.cache[i])this.cacheTable(e.table);return this.cache[i]}cacheTable(e){let t=e[we.Symbol.Schema]??"public",r=e[we.Symbol.OriginalName],i=`${t}.${r}`;if(!this.cachedTables[i]){for(let n of Object.values(e[we.Symbol.Columns])){let o=`${i}.${n.name}`;this.cache[o]=this.convert(n.name)}this.cachedTables[i]=!0}}clearCache(){this.cache={},this.cachedTables={}}}});var iu,so,RC;var Hb=S(()=>{ze();iu=class iu extends Error{static[J]="DrizzleError";constructor({message:e,cause:t}){super(e);this.name="DrizzleError",this.cause=t}};so=class so extends Error{constructor(e,t,r){super(`Failed query: ${e}
|
|
409
409
|
params: ${t}`);if(this.query=e,this.params=t,this.cause=r,Error.captureStackTrace(this,so),r)this.cause=r}};RC=class RC extends iu{static[J]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}});var CK=()=>{};var RK=()=>{};var OK=S(()=>{CK();RK()});var OC=S(()=>{gC();OK();ur()});var PC=S(()=>{_C();ws();kC();EC();IC();TC();AC()});var ao;var gp=S(()=>{ze();ur();ao=class ao extends _n{static[J]="SQLiteViewBase"}});var ou,zC,NC;var Kb=S(()=>{mp();$K();Zn();ze();Hb();dp();OC();ur();PC();io();Mn();vr();Dr();to();gp();ou=class ou{static[J]="SQLiteDialect";casing;constructor(e){this.casing=new CC(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=[U`with `];for(let[r,i]of e.entries())if(t.push(U`${U.identifier(i._.alias)} as (${i._.sql})`),r<e.length-1)t.push(U`, `);return t.push(U` `),U.join(t)}buildDeleteQuery({table:e,where:t,returning:r,withList:i,limit:n,orderBy:o}){let s=this.buildWithCTE(i),a=r?U` returning ${this.buildSelection(r,{isSingleTable:!0})}`:void 0,c=t?U` where ${t}`:void 0,l=this.buildOrderBy(o),u=this.buildLimit(n);return U`${s}delete from ${e}${c}${a}${l}${u}`}buildUpdateSet(e,t){let r=e[we.Symbol.Columns],i=Object.keys(r).filter((o)=>t[o]!==void 0||r[o]?.onUpdateFn!==void 0),n=i.length;return U.join(i.flatMap((o,s)=>{let a=r[o],c=a.onUpdateFn?.(),l=t[o]??(ae(c,Te)?c:U.param(c,a)),u=U`${U.identifier(this.casing.getColumnCasing(a))} = ${l}`;if(s<n-1)return[u,U.raw(", ")];return[u]}))}buildUpdateQuery({table:e,set:t,where:r,returning:i,withList:n,joins:o,from:s,limit:a,orderBy:c}){let l=this.buildWithCTE(n),u=this.buildUpdateSet(e,t),f=s&&U.join([U.raw(" from "),this.buildFromTable(s)]),p=this.buildJoins(o),m=i?U` returning ${this.buildSelection(i,{isSingleTable:!0})}`:void 0,y=r?U` where ${r}`:void 0,g=this.buildOrderBy(c),b=this.buildLimit(a);return U`${l}update ${e} set ${u}${f}${p}${y}${m}${g}${b}`}buildSelection(e,{isSingleTable:t=!1}={}){let r=e.length,i=e.flatMap(({field:n},o)=>{let s=[];if(ae(n,Te.Aliased)&&n.isSelectionField)s.push(U.identifier(n.fieldAlias));else if(ae(n,Te.Aliased)||ae(n,Te)){let a=ae(n,Te.Aliased)?n.sql:n;if(t)s.push(new Te(a.queryChunks.map((c)=>{if(ae(c,nt))return U.identifier(this.casing.getColumnCasing(c));return c})));else s.push(a);if(ae(n,Te.Aliased))s.push(U` as ${U.identifier(n.fieldAlias)}`)}else if(ae(n,nt)){let a=n.table[we.Symbol.Name];if(n.columnType==="SQLiteNumericBigInt")if(t)s.push(U`cast(${U.identifier(this.casing.getColumnCasing(n))} as text)`);else s.push(U`cast(${U.identifier(a)}.${U.identifier(this.casing.getColumnCasing(n))} as text)`);else if(t)s.push(U.identifier(this.casing.getColumnCasing(n)));else s.push(U`${U.identifier(a)}.${U.identifier(this.casing.getColumnCasing(n))}`)}else if(ae(n,vt)){let a=Object.entries(n._.selectedFields);if(a.length===1){let c=a[0][1],l=ae(c,Te)?c.decoder:ae(c,nt)?{mapFromDriverValue:(u)=>c.mapFromDriverValue(u)}:c.sql.decoder;if(l)n._.sql.decoder=l}s.push(n)}if(o<r-1)s.push(U`, `);return s});return U.join(i)}buildJoins(e){if(!e||e.length===0)return;let t=[];if(e)for(let[r,i]of e.entries()){if(r===0)t.push(U` `);let n=i.table,o=i.on?U` on ${i.on}`:void 0;if(ae(n,Bt)){let s=n[Bt.Symbol.Name],a=n[Bt.Symbol.Schema],c=n[Bt.Symbol.OriginalName],l=s===c?void 0:i.alias;t.push(U`${U.raw(i.joinType)} join ${a?U`${U.identifier(a)}.`:void 0}${U.identifier(c)}${l&&U` ${U.identifier(l)}`}${o}`)}else t.push(U`${U.raw(i.joinType)} join ${n}${o}`);if(r<e.length-1)t.push(U` `)}return U.join(t)}buildLimit(e){return typeof e==="object"||typeof e==="number"&&e>=0?U` limit ${e}`:void 0}buildOrderBy(e){let t=[];if(e){for(let[r,i]of e.entries())if(t.push(i),r<e.length-1)t.push(U`, `)}return t.length>0?U` order by ${U.join(t)}`:void 0}buildFromTable(e){if(ae(e,we)&&e[we.Symbol.IsAlias])return U`${U`${U.identifier(e[we.Symbol.Schema]??"")}.`.if(e[we.Symbol.Schema])}${U.identifier(e[we.Symbol.OriginalName])} ${U.identifier(e[we.Symbol.Name])}`;return e}buildSelectQuery({withList:e,fields:t,fieldsFlat:r,where:i,having:n,table:o,joins:s,orderBy:a,groupBy:c,limit:l,offset:u,distinct:f,setOperators:p}){let m=r??kn(t);for(let P of m)if(ae(P.field,nt)&&ys(P.field.table)!==(ae(o,vt)?o._.alias:ae(o,ao)?o[_t].name:ae(o,Te)?void 0:ys(o))&&!((N)=>s?.some(({alias:I})=>I===(N[we.Symbol.IsAlias]?ys(N):N[we.Symbol.BaseName])))(P.field.table)){let N=ys(P.field.table);throw Error(`Your "${P.path.join("->")}" field references a column "${N}"."${P.field.name}", but the table "${N}" is not part of the query! Did you forget to join it?`)}let y=!s||s.length===0,g=this.buildWithCTE(e),b=f?U` distinct`:void 0,_=this.buildSelection(m,{isSingleTable:y}),T=this.buildFromTable(o),A=this.buildJoins(s),z=i?U` where ${i}`:void 0,j=n?U` having ${n}`:void 0,E=[];if(c){for(let[P,N]of c.entries())if(E.push(N),P<c.length-1)E.push(U`, `)}let F=E.length>0?U` group by ${U.join(E)}`:void 0,D=this.buildOrderBy(a),H=this.buildLimit(l),X=u?U` offset ${u}`:void 0,Z=U`${g}select${b} ${_} from ${T}${A}${z}${F}${j}${D}${H}${X}`;if(p.length>0)return this.buildSetOperations(Z,p);return Z}buildSetOperations(e,t){let[r,...i]=t;if(!r)throw Error("Cannot pass undefined values to any set operator");if(i.length===0)return this.buildSetOperationQuery({leftSelect:e,setOperator:r});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:e,setOperator:r}),i)}buildSetOperationQuery({leftSelect:e,setOperator:{type:t,isAll:r,rightSelect:i,limit:n,orderBy:o,offset:s}}){let a=U`${e.getSQL()} `,c=U`${i.getSQL()}`,l;if(o&&o.length>0){let m=[];for(let y of o)if(ae(y,Tt))m.push(U.identifier(y.name));else if(ae(y,Te)){for(let g=0;g<y.queryChunks.length;g++){let b=y.queryChunks[g];if(ae(b,Tt))y.queryChunks[g]=U.identifier(this.casing.getColumnCasing(b))}m.push(U`${y}`)}else m.push(U`${y}`);l=U` order by ${U.join(m,U`, `)}`}let u=typeof n==="object"||typeof n==="number"&&n>=0?U` limit ${n}`:void 0,f=U.raw(`${t} ${r?"all ":""}`),p=s?U` offset ${s}`:void 0;return U`${a}${f}${c}${l}${u}${p}`}buildInsertQuery({table:e,values:t,onConflict:r,returning:i,withList:n,select:o}){let s=[],a=e[we.Symbol.Columns],c=Object.entries(a).filter(([y,g])=>!g.shouldDisableInsert()),l=c.map(([,y])=>U.identifier(this.casing.getColumnCasing(y)));if(o){let y=t;if(ae(y,Te))s.push(y);else s.push(y.getSQL())}else{let y=t;s.push(U.raw("values "));for(let[g,b]of y.entries()){let _=[];for(let[T,A]of c){let z=b[T];if(z===void 0||ae(z,an)&&z.value===void 0){let j;if(A.default!==null&&A.default!==void 0)j=ae(A.default,Te)?A.default:U.param(A.default,A);else if(A.defaultFn!==void 0){let E=A.defaultFn();j=ae(E,Te)?E:U.param(E,A)}else if(!A.default&&A.onUpdateFn!==void 0){let E=A.onUpdateFn();j=ae(E,Te)?E:U.param(E,A)}else j=U`null`;_.push(j)}else _.push(z)}if(s.push(_),g<y.length-1)s.push(U`, `)}}let u=this.buildWithCTE(n),f=U.join(s),p=i?U` returning ${this.buildSelection(i,{isSingleTable:!0})}`:void 0,m=r?.length?U.join(r):void 0;return U`${u}insert into ${e} ${l} ${f}${m}${p}`}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:i,tableConfig:n,queryConfig:o,tableAlias:s,nestedQueryRelation:a,joinOn:c}){let l=[],u,f,p=[],m,y=[];if(o===!0)l=Object.entries(n.columns).map(([_,T])=>({dbKey:T.name,tsKey:_,field:wi(T,s),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let b=Object.fromEntries(Object.entries(n.columns).map(([E,F])=>[E,wi(F,s)]));if(o.where){let E=typeof o.where==="function"?o.where(b,zH()):o.where;m=E&&pp(E,s)}let _=[],T=[];if(o.columns){let E=!1;for(let[F,D]of Object.entries(o.columns)){if(D===void 0)continue;if(F in n.columns){if(!E&&D===!0)E=!0;T.push(F)}}if(T.length>0)T=E?T.filter((F)=>o.columns?.[F]===!0):Object.keys(n.columns).filter((F)=>!T.includes(F))}else T=Object.keys(n.columns);for(let E of T){let F=n.columns[E];_.push({tsKey:E,value:F})}let A=[];if(o.with)A=Object.entries(o.with).filter((E)=>!!E[1]).map(([E,F])=>({tsKey:E,queryConfig:F,relation:n.relations[E]}));let z;if(o.extras){z=typeof o.extras==="function"?o.extras(b,{sql:U}):o.extras;for(let[E,F]of Object.entries(z))_.push({tsKey:E,value:bC(F,s)})}for(let{tsKey:E,value:F}of _)l.push({dbKey:ae(F,Te.Aliased)?F.fieldAlias:n.columns[E].name,tsKey:E,field:ae(F,nt)?wi(F,s):F,relationTableTsKey:void 0,isJson:!1,selection:[]});let j=typeof o.orderBy==="function"?o.orderBy(b,NH()):o.orderBy??[];if(!Array.isArray(j))j=[j];p=j.map((E)=>{if(ae(E,nt))return wi(E,s);return pp(E,s)}),u=o.limit,f=o.offset;for(let{tsKey:E,queryConfig:F,relation:D}of A){let H=LH(t,r,D),X=za(D.referencedTable),Z=r[X],P=`${s}_${E}`,N=It(...H.fields.map((R,M)=>Qe(wi(H.references[M],P),wi(R,s)))),I=this.buildRelationalQuery({fullSchema:e,schema:t,tableNamesMap:r,table:e[Z],tableConfig:t[Z],queryConfig:ae(D,xs)?F===!0?{limit:1}:{...F,limit:1}:F,tableAlias:P,joinOn:N,nestedQueryRelation:D}),O=U`(${I.sql})`.as(E);l.push({dbKey:E,tsKey:E,field:O,relationTableTsKey:Z,isJson:!0,selection:I.selection})}}if(l.length===0)throw new iu({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 g;if(m=It(c,m),a){let b=U`json_array(${U.join(l.map(({field:A})=>ae(A,Tt)?U.identifier(this.casing.getColumnCasing(A)):ae(A,Te.Aliased)?A.sql:A),U`, `)})`;if(ae(a,up))b=U`coalesce(json_group_array(${b}), json_array())`;let _=[{dbKey:"data",tsKey:"data",field:b.as("data"),isJson:!0,relationTableTsKey:n.tsName,selection:l}];if(u!==void 0||f!==void 0||p.length>0)g=this.buildSelectQuery({table:fp(i,s),fields:{},fieldsFlat:[{path:[],field:U.raw("*")}],where:m,limit:u,offset:f,orderBy:p,setOperators:[]}),m=void 0,u=void 0,f=void 0,p=void 0;else g=fp(i,s);g=this.buildSelectQuery({table:ae(g,Bt)?g:new vt(g,{},s),fields:{},fieldsFlat:_.map(({field:A})=>({path:[],field:ae(A,nt)?wi(A,s):A})),joins:y,where:m,limit:u,offset:f,orderBy:p,setOperators:[]})}else g=this.buildSelectQuery({table:fp(i,s),fields:{},fieldsFlat:l.map(({field:b})=>({path:[],field:ae(b,nt)?wi(b,s):b})),joins:y,where:m,limit:u,offset:f,orderBy:p,setOperators:[]});return{tableTsKey:n.tsName,sql:g,selection:l}}};zC=class zC extends ou{static[J]="SQLiteSyncDialect";migrate(e,t,r){let i=r===void 0?"__drizzle_migrations":typeof r==="string"?"__drizzle_migrations":r.migrationsTable??"__drizzle_migrations",n=U`
|
|
410
410
|
CREATE TABLE IF NOT EXISTS ${U.identifier(i)} (
|
|
411
411
|
id SERIAL PRIMARY KEY,
|
|
@@ -418,7 +418,7 @@ params: ${t}`);if(this.query=e,this.params=t,this.cause=r,Error.captureStackTrac
|
|
|
418
418
|
hash text NOT NULL,
|
|
419
419
|
created_at numeric
|
|
420
420
|
)
|
|
421
|
-
`;await t.run(n);let s=(await t.values(U`SELECT id, hash, created_at FROM ${U.identifier(i)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0;await t.transaction(async(a)=>{for(let c of e)if(!s||Number(s[2])<c.folderMillis){for(let l of c.sql)await a.run(U.raw(l));await a.run(U`INSERT INTO ${U.identifier(i)} ("hash", "created_at") VALUES(${c.hash}, ${c.folderMillis})`)}})}}});var DC;var PK=S(()=>{ze();DC=class DC{static[J]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}});function Jb(e,t){return(r,i,...n)=>{let o=[i,...n].map((s)=>({type:e,isAll:t,rightSelect:s}));for(let s of o)if(!sp(r.getSelectedFields(),s.rightSelect.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return r.addSetOperators(o)}}var Hn,zK,LC,oSe=()=>({union:sSe,unionAll:aSe,intersect:cSe,except:lSe}),sSe,aSe,cSe,lSe;var BC=S(()=>{ze();PK();no();La();ur();Mn();vr();Dr();to();nu();gp();Hn=class Hn{static[J]="SQLiteSelectBuilder";fields;session;dialect;withList;distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,this.withList=e.withList,this.distinct=e.distinct}from(e){let t=!!this.fields,r;if(this.fields)r=this.fields;else if(ae(e,vt))r=Object.fromEntries(Object.keys(e._.selectedFields).map((i)=>[i,e[i]]));else if(ae(e,ao))r=e[_t].selectedFields;else if(ae(e,Te))r={};else r=Lb(e);return new LC({table:e,fields:r,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}};zK=class zK extends DC{static[J]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:r,session:i,dialect:n,withList:o,distinct:s}){super();this.config={withList:o,table:e,fields:{...t},distinct:s,setOperators:[]},this.isPartialSelect=r,this.session=i,this.dialect=n,this._={selectedFields:t,config:this.config},this.tableName=ap(e),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let a of Fn(e))this.usedTables.add(a)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(t,r)=>{let i=this.tableName,n=ap(t);for(let o of Fn(t))this.usedTables.add(o);if(typeof n==="string"&&this.config.joins?.some((o)=>o.alias===n))throw Error(`Alias "${n}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof i==="string")this.config.fields={[i]:this.config.fields};if(typeof n==="string"&&!ae(t,Te)){let o=ae(t,vt)?t._.selectedFields:ae(t,_n)?t[_t].selectedFields:t[we.Symbol.Columns];this.config.fields[n]=o}}if(typeof r==="function")r=r(new Proxy(this.config.fields,new bt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:r,table:t,joinType:e,alias:n}),typeof n==="string")switch(e){case"left":{this.joinsNotNullableMap[n]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([o])=>[o,!1])),this.joinsNotNullableMap[n]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[n]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([o])=>[o,!1])),this.joinsNotNullableMap[n]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");crossJoin=this.createJoin("cross");createSetOperator(e,t){return(r)=>{let i=typeof r==="function"?r(oSe()):r;if(!sp(this.getSelectedFields(),i.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:e,isAll:t,rightSelect:i}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);except=this.createSetOperator("except",!1);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new bt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=e,this}having(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new bt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=e,this}groupBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.fields,new bt({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.fields,new bt({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=r;else this.config.orderBy=r}else{let t=e;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=t;else this.config.orderBy=t}return this}limit(e){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=e;else this.config.limit=e;return this}offset(e){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=e;else this.config.offset=e;return this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){let t=[];if(t.push(...Fn(this.config.table)),this.config.joins)for(let r of this.config.joins)t.push(...Fn(r.table));return new Proxy(new vt(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new bt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new bt({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}};LC=class LC extends zK{static[J]="SQLiteSelect";_prepare(e=!0){if(!this.session)throw Error("Cannot execute a query on a query builder. Please use a database instance instead.");let t=kn(this.config.fields),r=this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),t,"all",!0,void 0,{type:"select",tables:[...this.usedTables]},this.cacheConfig);return r.joinsNotNullableMap=this.joinsNotNullableMap,r}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enable:!0,autoInvalidate:!0}:e===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...e},this}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(){return this.all()}};fH(LC,[Lr]);sSe=Jb("union",!1),aSe=Jb("union",!0),cSe=Jb("intersect",!1),lSe=Jb("except",!1)});var Ba;var Vb=S(()=>{ze();La();Kb();Mn();BC();Ba=class Ba{static[J]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=ae(e,ou)?e:void 0,this.dialectConfig=ae(e,ou)?void 0:e}$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(r);return new Proxy(new np(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new bt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...e){let t=this;function r(n){return new Hn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function i(n){return new Hn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:r,selectDistinct:i}}select(e){return new Hn({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new Hn({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new zC(this.dialectConfig);return this.dialect}}});var Wb,jC;var NK=S(()=>{ze();no();ur();io();vr();Dr();nu();Vb();Wb=class Wb{constructor(e,t,r,i){this.table=e,this.session=t,this.dialect=r,this.withList=i}static[J]="SQLiteInsertBuilder";values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw Error("values() must be called with at least one value");let t=e.map((r)=>{let i={},n=this.table[we.Symbol.Columns];for(let o of Object.keys(r)){let s=r[o];i[o]=ae(s,Te)?s:new an(s,n[o])}return i});return new jC(this.table,t,this.session,this.dialect,this.withList)}select(e){let t=typeof e==="function"?e(new Ba):e;if(!ae(t,Te)&&!sp(this.table[zb],t._.selectedFields))throw Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new jC(this.table,t,this.session,this.dialect,this.withList,!0)}};jC=class jC extends Lr{constructor(e,t,r,i,n,o){super();this.session=r,this.dialect=i,this.config={table:e,values:t,withList:n,select:o}}static[J]="SQLiteInsert";config;returning(e=this.config.table[Bt.Symbol.Columns]){return this.config.returning=kn(e),this}onConflictDoNothing(e={}){if(!this.config.onConflict)this.config.onConflict=[];if(e.target===void 0)this.config.onConflict.push(U` on conflict do nothing`);else{let t=Array.isArray(e.target)?U`${e.target}`:U`${[e.target]}`,r=e.where?U` where ${e.where}`:U``;this.config.onConflict.push(U` on conflict ${t} do nothing${r}`)}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');if(!this.config.onConflict)this.config.onConflict=[];let t=e.where?U` where ${e.where}`:void 0,r=e.targetWhere?U` where ${e.targetWhere}`:void 0,i=e.setWhere?U` where ${e.setWhere}`:void 0,n=Array.isArray(e.target)?U`${e.target}`:U`${[e.target]}`,o=this.dialect.buildUpdateSet(this.config.table,Db(this.config.table,e.set));return this.config.onConflict.push(U` on conflict ${n}${r} do update set ${o}${t}${i}`),this}getSQL(){return this.dialect.buildInsertQuery(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:"insert",tables:Fn(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(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var Gb,DK;var LK=S(()=>{ze();no();La();io();Mn();vr();Dr();to();nu();gp();Gb=class Gb{constructor(e,t,r,i){this.table=e,this.session=t,this.dialect=r,this.withList=i}static[J]="SQLiteUpdateBuilder";set(e){return new DK(this.table,Db(this.table,e),this.session,this.dialect,this.withList)}};DK=class DK extends Lr{constructor(e,t,r,i,n){super();this.session=r,this.dialect=i,this.config={set:t,table:e,withList:n,joins:[]}}static[J]="SQLiteUpdate";config;from(e){return this.config.from=e,this}createJoin(e){return(t,r)=>{let i=ap(t);if(typeof i==="string"&&this.config.joins.some((n)=>n.alias===i))throw Error(`Alias "${i}" is already used in this query`);if(typeof r==="function"){let n=this.config.from?ae(t,Bt)?t[we.Symbol.Columns]:ae(t,vt)?t._.selectedFields:ae(t,ao)?t[_t].selectedFields:void 0:void 0;r=r(new Proxy(this.config.table[we.Symbol.Columns],new bt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),n&&new Proxy(n,new bt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:r,table:t,joinType:e,alias:i}),this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.table[we.Symbol.Columns],new bt({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.config.table[Bt.Symbol.Columns]){return this.config.returning=kn(e),this}getSQL(){return this.dialect.buildUpdateQuery(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:"insert",tables:Fn(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(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var UC=S(()=>{AK();NK();Vb();BC();LK()});var yp;var BK=S(()=>{ze();ur();yp=class yp extends Te{constructor(e){super(yp.buildEmbeddedCount(e.source,e.filters).queryChunks);this.params=e,this.session=e.session,this.sql=yp.buildCount(e.source,e.filters)}sql;static[J]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(e,t){return U`(select count(*) from ${e}${U.raw(" where ").if(t)}${t})`}static buildCount(e,t){return U`select count(*) from ${e}${U.raw(" where ").if(t)}${t}`}then(e,t){return Promise.resolve(this.session.count(this.sql)).then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return this.then((t)=>(e?.(),t),(t)=>{throw e?.(),t})}}});var ZC,Qb,qC;var jK=S(()=>{ze();no();dp();ZC=class ZC{constructor(e,t,r,i,n,o,s,a){this.mode=e,this.fullSchema=t,this.schema=r,this.tableNamesMap=i,this.table=n,this.tableConfig=o,this.dialect=s,this.session=a}static[J]="SQLiteAsyncRelationalQueryBuilder";findMany(e){return this.mode==="sync"?new qC(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many"):new Qb(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many")}findFirst(e){return this.mode==="sync"?new qC(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new Qb(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}};Qb=class Qb extends Lr{constructor(e,t,r,i,n,o,s,a,c){super();this.fullSchema=e,this.schema=t,this.tableNamesMap=r,this.table=i,this.tableConfig=n,this.dialect=o,this.session=s,this.config=a,this.mode=c}static[J]="SQLiteAsyncRelationalQuery";mode;getSQL(){return this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}).sql}_prepare(e=!1){let{query:t,builtQuery:r}=this._toSQL();return this.session[e?"prepareOneTimeQuery":"prepareQuery"](r,void 0,this.mode==="first"?"get":"all",!0,(i,n)=>{let o=i.map((s)=>qb(this.schema,this.tableConfig,s,t.selection,n));if(this.mode==="first")return o[0];return o})}prepare(){return this._prepare(!1)}_toSQL(){let e=this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}),t=this.dialect.sqlToQuery(e.sql);return{query:e,builtQuery:t}}toSQL(){return this._toSQL().builtQuery}executeRaw(){if(this.mode==="first")return this._prepare(!1).get();return this._prepare(!1).all()}async execute(){return this.executeRaw()}};qC=class qC extends Qb{static[J]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}});var su;var UK=S(()=>{ze();no();su=class su extends Lr{constructor(e,t,r,i,n){super();this.execute=e,this.getSQL=t,this.dialect=i,this.mapBatchResult=n,this.config={action:r}}static[J]="SQLiteRaw";config;getQuery(){return{...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult(e,t){return t?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return!1}}});var bp;var Yb=S(()=>{ze();La();ur();UC();Mn();BK();jK();UK();bp=class bp{constructor(e,t,r,i){this.resultKind=e,this.dialect=t,this.session=r,this._=i?{schema:i.schema,fullSchema:i.fullSchema,tableNamesMap:i.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let n=this.query;if(this._.schema)for(let[o,s]of Object.entries(this._.schema))n[o]=new ZC(e,i.fullSchema,this._.schema,this._.tableNamesMap,i.fullSchema[o],s,t,r);this.$cache={invalidate:async(o)=>{}}}static[J]="BaseSQLiteDatabase";query;$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(new Ba(r.dialect));return new Proxy(new np(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new bt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(e,t){return new yp({source:e,filters:t,session:this.session})}with(...e){let t=this;function r(a){return new Hn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e})}function i(a){return new Hn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function n(a){return new Gb(a,t.session,t.dialect,e)}function o(a){return new Wb(a,t.session,t.dialect,e)}function s(a){return new Fb(a,t.session,t.dialect,e)}return{select:r,selectDistinct:i,update:n,insert:o,delete:s}}select(e){return new Hn({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new Hn({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new Gb(e,this.session,this.dialect)}$cache;insert(e){return new Wb(e,this.session,this.dialect)}delete(e){return new Fb(e,this.session,this.dialect)}run(e){let t=typeof e==="string"?U.raw(e):e.getSQL();if(this.resultKind==="async")return new su(async()=>this.session.run(t),()=>t,"run",this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session));return this.session.run(t)}all(e){let t=typeof e==="string"?U.raw(e):e.getSQL();if(this.resultKind==="async")return new su(async()=>this.session.all(t),()=>t,"all",this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session));return this.session.all(t)}get(e){let t=typeof e==="string"?U.raw(e):e.getSQL();if(this.resultKind==="async")return new su(async()=>this.session.get(t),()=>t,"get",this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session));return this.session.get(t)}values(e){let t=typeof e==="string"?U.raw(e):e.getSQL();if(this.resultKind==="async")return new su(async()=>this.session.values(t),()=>t,"values",this.dialect,this.session.extractRawValuesValueFromBatchResult.bind(this.session));return this.session.values(t)}transaction(e,t){return this.session.transaction(e,t)}}});async function MC(e,t){let r=`${e}-${JSON.stringify(t)}`,n=new TextEncoder().encode(r),o=await crypto.subtle.digest("SHA-256",n);return[...new Uint8Array(o)].map((c)=>c.toString(16).padStart(2,"0")).join("")}var qK,Sp;var FC=S(()=>{ze();qK=class qK{static[J]="Cache"};Sp=class Sp extends qK{strategy(){return"all"}static[J]="NoopCache";async get(e){return}async put(e,t,r,i){}async onMutate(e){}}});var ZK=S(()=>{FC()});function MK(e,t){return new Proxy(e,new Da(t,!1))}var FK=S(()=>{mp()});var HK,HC,KC,JC;var VC=S(()=>{FC();ze();Hb();no();Yb();HK=class HK extends Lr{constructor(e){super();this.resultCb=e}static[J]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}};HC=class HC{constructor(e,t,r,i,n,o){if(this.mode=e,this.executeMethod=t,this.query=r,this.cache=i,this.queryMetadata=n,this.cacheConfig=o,i&&i.strategy()==="all"&&o===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}static[J]="PreparedQuery";joinsNotNullableMap;async queryWithCache(e,t,r){if(this.cache===void 0||ae(this.cache,Sp)||this.queryMetadata===void 0)try{return await r()}catch(i){throw new so(e,t,i)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await r()}catch(i){throw new so(e,t,i)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[i]=await Promise.all([r(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return i}catch(i){throw new so(e,t,i)}if(!this.cacheConfig)try{return await r()}catch(i){throw new so(e,t,i)}if(this.queryMetadata.type==="select"){let i=await this.cache.get(this.cacheConfig.tag??await MC(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(i===void 0){let n;try{n=await r()}catch(o){throw new so(e,t,o)}return await this.cache.put(this.cacheConfig.tag??await MC(e,t),n,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),n}return i}try{return await r()}catch(i){throw new so(e,t,i)}}getQuery(){return this.query}mapRunResult(e,t){return e}mapAllResult(e,t){throw Error("Not implemented")}mapGetResult(e,t){throw Error("Not implemented")}execute(e){if(this.mode==="async")return this[this.executeMethod](e);return new HK(()=>this[this.executeMethod](e))}mapResult(e,t){switch(this.executeMethod){case"run":return this.mapRunResult(e,t);case"all":return this.mapAllResult(e,t);case"get":return this.mapGetResult(e,t)}}};KC=class KC{constructor(e){this.dialect=e}static[J]="SQLiteSession";prepareOneTimeQuery(e,t,r,i,n,o,s){return this.prepareQuery(e,t,r,i,n,o,s)}run(e){let t=this.dialect.sqlToQuery(e);try{return this.prepareOneTimeQuery(t,void 0,"run",!1).run()}catch(r){throw new iu({cause:r,message:`Failed to run the query '${t.sql}'`})}}extractRawRunValueFromBatchResult(e){return e}all(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).all()}extractRawAllValueFromBatchResult(e){throw Error("Not implemented")}get(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).get()}extractRawGetValueFromBatchResult(e){throw Error("Not implemented")}values(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).values()}async count(e){return(await this.values(e))[0][0]}extractRawValuesValueFromBatchResult(e){throw Error("Not implemented")}};JC=class JC extends bp{constructor(e,t,r,i,n=0){super(e,t,r,i);this.schema=i,this.nestedIndex=n}static[J]="SQLiteTransaction";rollback(){throw new RC}}});var WC,uSe,dSe,Xb;var KK=S(()=>{ze();La();Dr();Vb();io();gp();WC=class WC{constructor(e){this.name=e}static[J]="SQLiteViewBuilderCore";config={}};uSe=class uSe extends WC{static[J]="SQLiteViewBuilder";as(e){if(typeof e==="function")e=e(new Ba);let t=new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}),r=e.getSelectedFields();return new Proxy(new Xb({config:{name:this.name,schema:void 0,selectedFields:r,query:e.getSQL().inlineParams()}}),t)}};dSe=class dSe extends WC{static[J]="SQLiteManualViewBuilder";columns;constructor(e,t){super(e);this.columns=Lb(hp(e,t))}existing(){return new Proxy(new Xb({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:void 0}}),new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}as(e){return new Proxy(new Xb({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:e.inlineParams()}}),new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}};Xb=class Xb extends ao{static[J]="SQLiteView";constructor({config:e}){super(e)}}});var eS=S(()=>{FK();wK();PC();Yb();Kb();xC();EK();TK();UC();VC();io();vC();nu();KK()});function JK(e){return Object.keys(e).reduce((t,r)=>{if(Object.prototype.propertyIsEnumerable.call(e,r))t[r]=e[r];return t},{})}function tS(e){if(typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer){if(typeof Buffer<"u"){if(!(e instanceof Buffer))return Buffer.from(e);return e}if(typeof TextDecoder<"u")return new TextDecoder().decode(e);throw Error("TextDecoder is not available. Please provide either Buffer or TextDecoder polyfill.")}return e}var rS,GC,VK;var QC=S(()=>{ZK();ze();Bb();ur();eS();VC();Dr();rS=class rS extends KC{constructor(e,t,r,i,n){super(t);this.client=e,this.schema=r,this.options=i,this.tx=n,this.logger=i.logger??new pC,this.cache=i.cache??new Sp}static[J]="LibSQLSession";logger;cache;prepareQuery(e,t,r,i,n,o,s){return new VK(this.client,e,this.logger,this.cache,o,s,t,this.tx,r,i,n)}async batch(e){let t=[],r=[];for(let n of e){let o=n._prepare(),s=o.getQuery();t.push(o),r.push({sql:s.sql,args:s.params})}return(await this.client.batch(r)).map((n,o)=>t[o].mapResult(n,!0))}async migrate(e){let t=[],r=[];for(let n of e){let o=n._prepare(),s=o.getQuery();t.push(o),r.push({sql:s.sql,args:s.params})}return(await this.client.migrate(r)).map((n,o)=>t[o].mapResult(n,!0))}async transaction(e,t){let r=await this.client.transaction(),i=new rS(this.client,this.dialect,this.schema,this.options,r),n=new GC("async",this.dialect,i,this.schema);try{let o=await e(n);return await r.commit(),o}catch(o){throw await r.rollback(),o}}extractRawAllValueFromBatchResult(e){return e.rows}extractRawGetValueFromBatchResult(e){return e.rows[0]}extractRawValuesValueFromBatchResult(e){return e.rows}};GC=class GC extends JC{static[J]="LibSQLTransaction";async transaction(e){let t=`sp${this.nestedIndex}`,r=new GC("async",this.dialect,this.session,this.schema,this.nestedIndex+1);await this.session.run(U.raw(`savepoint ${t}`));try{let i=await e(r);return await this.session.run(U.raw(`release savepoint ${t}`)),i}catch(i){throw await this.session.run(U.raw(`rollback to savepoint ${t}`)),i}}};VK=class VK extends HC{constructor(e,t,r,i,n,o,s,a,c,l,u){super("async",c,t,i,n,o);this.client=e,this.logger=r,this.fields=s,this.tx=a,this._isResponseInArrayMode=l,this.customResultMapper=u,this.customResultMapper=u,this.fields=s}static[J]="LibSQLPreparedQuery";async run(e){let t=op(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),await this.queryWithCache(this.query.sql,t,async()=>{let r={sql:this.query.sql,args:t};return this.tx?this.tx.execute(r):this.client.execute(r)})}async all(e){let{fields:t,logger:r,query:i,tx:n,client:o,customResultMapper:s}=this;if(!t&&!s){let c=op(i.params,e??{});return r.logQuery(i.sql,c),await this.queryWithCache(i.sql,c,async()=>{let l={sql:i.sql,args:c};return(n?n.execute(l):o.execute(l)).then(({rows:u})=>this.mapAllResult(u))})}let a=await this.values(e);return this.mapAllResult(a)}mapAllResult(e,t){if(t)e=e.rows;if(!this.fields&&!this.customResultMapper)return e.map((r)=>JK(r));if(this.customResultMapper)return this.customResultMapper(e,tS);return e.map((r)=>uC(this.fields,Array.prototype.slice.call(r).map((i)=>tS(i)),this.joinsNotNullableMap))}async get(e){let{fields:t,logger:r,query:i,tx:n,client:o,customResultMapper:s}=this;if(!t&&!s){let c=op(i.params,e??{});return r.logQuery(i.sql,c),await this.queryWithCache(i.sql,c,async()=>{let l={sql:i.sql,args:c};return(n?n.execute(l):o.execute(l)).then(({rows:u})=>this.mapGetResult(u))})}let a=await this.values(e);return this.mapGetResult(a)}mapGetResult(e,t){if(t)e=e.rows;let r=e[0];if(!this.fields&&!this.customResultMapper)return JK(r);if(!r)return;if(this.customResultMapper)return this.customResultMapper(e,tS);return uC(this.fields,Array.prototype.slice.call(r).map((i)=>tS(i)),this.joinsNotNullableMap)}async values(e){let t=op(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),await this.queryWithCache(this.query.sql,t,async()=>{let r={sql:this.query.sql,args:t};return(this.tx?this.tx.execute(r):this.client.execute(r)).then(({rows:i})=>i)})}isResponseInArrayMode(){return this._isResponseInArrayMode}}});function au(e,t={}){let r=new NC({casing:t.casing}),i;if(t.logger===!0)i=new fC;else if(t.logger!==!1)i=t.logger;let n;if(t.schema){let a=DH(t.schema,BH);n={fullSchema:t.schema,schema:a.tables,tableNamesMap:a.tableNamesMap}}let o=new rS(e,r,n,{logger:i,cache:t.cache},void 0),s=new WK("async",r,o,n);if(s.$client=e,s.$cache=t.cache,s.$cache)s.$cache.invalidate=t.cache?.onMutate;return s}var WK;var GK=S(()=>{ze();Bb();dp();Yb();Kb();QC();WK=class WK extends bp{static[J]="LibSQLDatabase";async batch(e){return this.session.batch(e)}}});function nS(...e){if(typeof e[0]==="string"){let t=Yl({url:e[0]});return au(t,e[1])}if(pH(e[0])){let{connection:t,client:r,...i}=e[0];if(r)return au(r,i);let n=typeof t==="string"?Yl({url:t}):Yl(t);return au(n,i)}return au(e[0],e[1])}var QK=S(()=>{X$();Dr();GK();((e)=>{function t(r){return au({},r)}e.mock=t})(nS||(nS={}))});var YK=S(()=>{QK();QC()});function fSe(){return new Promise((e)=>setTimeout(e,0))}function mSe(){if(YC)return;YC=!0,setTimeout(()=>{YC=!1,XC=performance.now()},0)}async function xp(e=pSe){if(mSe(),performance.now()-XC<e)return;await fSe(),XC=performance.now()}var pSe=50,XC,YC=!1;var XK=S(()=>{XC=performance.now()});function eJ(e){if(e.authToken!==void 0)return e.authToken;if(e.authTokenEnv===void 0)return;return process.env[e.authTokenEnv]}function bSe(e){return e instanceof Be&&/^SQLITE_(?:BUSY|LOCKED)$/u.test(e.code)}async function iS(e,t){let r=Date.now()+(t.budgetMs??hSe),i=async(n)=>{if(t.isClosed())throw new Be("The client is closed","CLIENT_CLOSED");try{return await e()}catch(o){if(t.isClosed()||!bSe(o))throw o;await t.afterRefusal?.();let s=Math.min(gSe*2**(n-1),ySe),a=s/2+Math.random()*(s/2);if(t.isClosed()||Date.now()+a>=r)throw o;if(await new Promise((c)=>setTimeout(c,a)),t.isClosed()||Date.now()>=r)throw o;return i(n+1)}};return i(1)}function eR(e,t={}){let r=Yl({...e,...e.url.startsWith("file:")?{timeout:0}:{}});if(e.url.startsWith("file:")&&e.syncUrl===void 0){let i=r.transaction.bind(r),n=()=>r.closed,o=t.contentionRetryBudgetMs,s=r.execute.bind(r),a=r.batch.bind(r),c=r.migrate.bind(r),l={isClosed:n,budgetMs:o,afterRefusal:async()=>{await Promise.resolve(r.reconnect())}};async function u(f,p){return await xp(),iS(()=>typeof f==="string"?s(f,p):s(f),l)}r.execute=u,r.batch=async(f,p)=>(await xp(),iS(()=>a(f,p),l)),r.migrate=async(f)=>(await xp(),iS(()=>c(f),l)),r.transaction=async(f)=>(await xp(),iS(()=>i(f),l))}return r}function oS(e){let{url:t,schema:r}=e,i=eJ(e),n={contentionRetryBudgetMs:e.contentionRetryBudgetMs},o=i?eR({url:t,authToken:i},n):eR({url:t},n);return{db:nS(o,{schema:r}),client:o,url:t}}async function sS(e,t){if(!t.startsWith("file:"))return;for(let r of["PRAGMA busy_timeout = 0","PRAGMA journal_mode = WAL"])await e.execute(r)}var hSe=5000,gSe=5,ySe=40;var tR=S(()=>{X$();YK();XK()});var tJ=S(()=>{m$();tR()});var rR=S(()=>{tR();tJ()});var nR=S(()=>{mp();Rb();Zn();ze();Hb();Bb();no();dp();OC();Mn();vr();Dr();to()});var ne,pt;var iR=S(()=>{eS();nR();Rf();ne=hp("job_queue",{id:dr("id").primaryKey().$defaultFn(()=>Gi()),type:dr("type").notNull(),data:dr("data").notNull(),result:dr("result",{mode:"json"}),progress:dr("progress",{mode:"json"}).$type(),source:dr("source"),metadata:dr("metadata",{mode:"json"}).$type().notNull(),status:dr("status",{enum:["pending","processing","completed","failed"]}).notNull().default("pending"),priority:_r("priority").notNull().default(0),retryCount:_r("retryCount").notNull().default(0),maxRetries:_r("maxRetries").notNull().default(3),lastError:dr("lastError"),createdAt:_r("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:_r("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:_r("startedAt"),completedAt:_r("completedAt"),attemptId:dr("attemptId"),workerSlotId:dr("workerSlotId"),workerSessionId:dr("workerSessionId"),leaseExpiresAt:_r("leaseExpiresAt"),attemptHeartbeatAt:_r("attemptHeartbeatAt"),runtimeUpdatedAt:_r("runtimeUpdatedAt")},(e)=>({queueReadyIdx:oo("idx_job_queue_ready").on(e.status,e.priority,e.scheduledFor),jobTypeIdx:oo("idx_job_queue_type").on(e.type,e.status),runtimeUpdatesIdx:oo("idx_job_queue_runtime_updates").on(e.runtimeUpdatedAt,e.id),jobSourceIdx:oo("idx_job_queue_source").on(e.source),rootJobIdx:oo("idx_job_queue_root_job").on(U`json_extract(${e.metadata}, '$.rootJobId')`,e.createdAt,e.id),deduplicationIdx:oo("idx_job_queue_deduplication").on(e.type,U`json_extract(${e.metadata}, '$.deduplicationKey')`,e.status)})),pt=hp("job_worker_sessions",{slotId:dr("slotId").primaryKey(),sessionId:dr("sessionId").notNull().unique(),startedAt:_r("startedAt").notNull(),heartbeatAt:_r("heartbeatAt").notNull(),expiresAt:_r("expiresAt").notNull().default(0)},(e)=>({heartbeatIdx:oo("idx_job_worker_sessions_heartbeat").on(e.heartbeatAt),expiresIdx:oo("idx_job_worker_sessions_expires").on(e.expiresAt)}))});function rJ(e){return oS({url:e.url,schema:{jobQueue:ne,jobWorkerSessions:pt},authToken:e.authToken,authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",contentionRetryBudgetMs:0})}var nJ=S(()=>{rR();iR()});class oR{declarations=new Map;handlers=new Map;validators=new Map;logger;mode;finalizedRegistrations;constructor(e,t){this.logger=e.child("HandlerRegistry"),this.mode=t}registerHandler(e,t,r){if(this.finalizedRegistrations)throw Error("Job handler registrations are finalized");if(this.declarations.has(e))throw Error(`Job handler is already registered for type: ${e}`);if(this.declarations.set(e,{handler:t,pluginId:r}),this.validators.set(e,t),this.mode!=="validation-only")this.handlers.set(e,t);this.logger.debug("Registered job execution declaration",{type:e,pluginId:r,mode:this.mode})}unregisterHandler(e){this.declarations.delete(e),this.handlers.delete(e),this.validators.delete(e),this.logger.debug("Unregistered job handler",{type:e})}unregisterPluginHandlers(e){let t=[...this.declarations.entries()].filter(([,r])=>r.pluginId===e).map(([r])=>r);for(let r of t)this.declarations.delete(r),this.handlers.delete(r),this.validators.delete(r);if(t.length>0)this.logger.debug("Unregistered plugin handlers",{pluginId:e,count:t.length,types:t})}finalizeRegistrations(){return this.finalizedRegistrations??=Object.freeze([...this.declarations.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>Object.freeze({type:e,pluginId:t.pluginId}))),this.finalizedRegistrations}getExecutionRegistrations(){return this.finalizedRegistrations}getRegisteredTypes(){return[...this.handlers.keys()]}getExclusiveTypes(){return[...this.handlers].filter(([,e])=>e.exclusive===!0).map(([e])=>e)}getHandler(e){return this.handlers.get(e)}getValidator(e){return this.validators.get(e)}}class sR{tails=new Map;async run(e,t){let r=this.tails.get(e),i=()=>{},n=new Promise((o)=>{i=o});this.tails.set(e,n),await r;try{return await t()}finally{if(i(),this.tails.get(e)===n)this.tails.delete(e)}}}class aR{findDuplicate(e,t,r){if(!t||t==="none")return null;let i=this.filterByDeduplicationKey(e,r).sort((o,s)=>s.createdAt-o.createdAt||s.id.localeCompare(o.id)),n=i.find((o)=>o.status===Ue.PENDING)??null;if(t==="skip"||t==="replace")return n;return n??i[0]??null}filterByDeduplicationKey(e,t){if(!t)return e;return e.filter((r)=>{let i=SSe.safeParse(r.metadata);return i.success&&i.data.deduplicationKey===t})}}var SSe;var iJ=S(()=>{Ae();as();SSe=d.looseObject({deduplicationKey:d.string().optional()})});class cR{db;transactionClient;databaseUrl;logger;deduplicator=new aR;writeRetryBudgetMs;constructor(e,t,r,i,n){this.db=e,this.transactionClient=t,this.databaseUrl=r,this.logger=i.child("JobQueueRepository"),this.writeRetryBudgetMs=n?.writeRetryBudgetMs??xSe}async insert(e){await this.write("insert",async()=>this.db.insert(ne).values(e))}async enqueueAtomic(e){return kSe.run(this.databaseUrl,async()=>{let t=Date.now()+this.writeRetryBudgetMs;return this.attemptEnqueue(e,t,1)})}async attemptEnqueue(e,t,r){let i=await this.runEnqueueTransaction(e,t,r);if(i.retry)return this.attemptEnqueue(e,t,r+1);return i.decision}async runEnqueueTransaction(e,t,r){let i=await this.acquireWriteTransaction(e,t),n={prepared:!1},o=!1;try{let s=await this.decideEnqueue(i,e,()=>{n.prepared=!0});return o=!0,await i.commit(),{retry:!1,decision:s}}catch(s){let a=o&&this.isSerializationConflict(s)&&!i.closed,c=!0;if(!i.closed)try{await i.rollback()}catch(l){c=!1,this.logger.error("Failed to roll back atomic enqueue",{type:e.jobData.type,rollbackError:l})}if(n.prepared)e.onInsertRollback?.();if(!a||!c)throw s;return await this.waitForConflictRetry("commit",e,t,r,s),{retry:!0}}finally{i.close()}}async decideEnqueue(e,t,r){let{jobData:i,strategy:n,deduplicationKey:o,beforeInsert:s}=t,a=n??"none",c=async()=>{await s?.(),r()},l=async()=>{await c(),await this.insertJob(e,i)};if(a==="none")return await l(),{kind:"inserted",jobId:i.id};let u=await this.getActiveDeduplicationCandidates(e,i.type,o),f=this.deduplicator.findDuplicate(u,a,o);if(!f)return await l(),{kind:"inserted",jobId:i.id};if(a==="skip")return{kind:"skipped",jobId:f.id};if(a==="coalesce"){if((await e.execute({sql:"UPDATE `job_queue` SET `scheduledFor` = ? WHERE `id` = ? AND `status` = ?",args:[Date.now(),f.id,f.status]})).rowsAffected!==1)throw Error(`Atomic coalesce lost selected job ${f.id}`);return{kind:"coalesced",jobId:f.id}}await c();let p=Date.now();if((await e.execute({sql:"UPDATE `job_queue`\n SET `status` = ?,\n `lastError` = ?,\n `completedAt` = ?,\n `runtimeUpdatedAt` = max(?, coalesce((SELECT max(`runtimeUpdatedAt`) FROM `job_queue`), 0) + 1)\n WHERE `id` = ? AND `status` = ?",args:[Ue.FAILED,"Replaced by newer job",p,p,f.id,Ue.PENDING]})).rowsAffected!==1)throw Error(`Atomic replace lost selected job ${f.id}`);return await this.insertJob(e,i),{kind:"replaced",jobId:i.id,replacedJobId:f.id}}async getActiveDeduplicationCandidates(e,t,r){return(await e.execute(r?{sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ?\n AND json_extract(`metadata`, '$.deduplicationKey') = ?\n AND `status` IN (?, ?)",args:[t,r,Ue.PENDING,Ue.PROCESSING]}:{sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ? AND `status` IN (?, ?)",args:[t,Ue.PENDING,Ue.PROCESSING]})).rows.map((n)=>this.parseDeduplicationCandidate(n))}parseDeduplicationCandidate(e){let{id:t,status:r,createdAt:i,metadata:n}=e;if(typeof t!=="string"||r!==Ue.PENDING&&r!==Ue.PROCESSING||typeof i!=="number"&&typeof i!=="bigint"||typeof n!=="string")throw Error("Invalid active job row returned during atomic enqueue");let o=JSON.parse(n);return{id:t,status:r,createdAt:Number(i),metadata:o}}async insertJob(e,t){if((await e.execute({sql:"INSERT INTO `job_queue` (\n `id`, `type`, `data`, `result`, `source`, `metadata`,\n `status`, `priority`, `retryCount`, `maxRetries`,\n `lastError`, `createdAt`, `scheduledFor`, `startedAt`,\n `completedAt`\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",args:[t.id,t.type,t.data,this.serializeJson(t.result),t.source,JSON.stringify(t.metadata),t.status,t.priority,t.retryCount,t.maxRetries,t.lastError,t.createdAt,t.scheduledFor,t.startedAt,t.completedAt]})).rowsAffected!==1)throw Error(`Atomic enqueue did not insert job ${t.id}`)}serializeJson(e){if(e===void 0||e===null)return null;return JSON.stringify(e)}acquireWriteTransaction(e,t){return this.retryOnConflict("acquire",e,()=>this.transactionClient.transaction("write"),(r)=>this.isSerializationConflict(r),t)}async waitForConflictRetry(e,t,r,i,n){let o=Math.min(wSe*2**(i-1),vSe),s=o/2+Math.random()*(o/2);if(Date.now()+s>=r)throw this.transactionConflictError(e,t,i,n);await new Promise((a)=>setTimeout(a,s))}async retryOnConflict(e,t,r,i,n=Date.now()+this.writeRetryBudgetMs,o=1){try{return await r()}catch(s){if(!i(s))throw s;return await this.waitForConflictRetry(e,t,n,o,s),this.retryOnConflict(e,t,r,i,n,o+1)}}transactionConflictError(e,t,r,i){if(typeof t==="string")return Error(`Failed job queue write "${t}" within ${this.writeRetryBudgetMs}ms after ${r} attempts`,{cause:i});let n=t.strategy??"none",o=t.deduplicationKey?"present":"absent";return Error(`Failed to ${e} atomic enqueue transaction for type "${t.jobData.type}" within ${this.writeRetryBudgetMs}ms after ${r} attempts (strategy: ${n}, key: ${o})`,{cause:i})}write(e,t){return this.retryOnConflict("write",e,t,(r)=>{let i=new Set;for(let n=r;n!==void 0&&!i.has(n);){if(i.add(n),typeof n==="object"&&n!==null&&"code"in n&&/^SQLITE_(?:BUSY|LOCKED)(?:_|$)/u.test(String(n.code)))return!0;n=n instanceof Error?n.cause:void 0}return!1})}isSerializationConflict(e){for(let t=e;t!==void 0;){let r=typeof t==="object"&&t!==null&&"code"in t?String(t.code):"",i=at(t,"");if(/SQLITE_(?:BUSY|LOCKED)/u.test(r)||/SQLITE_(?:BUSY|LOCKED)|database is locked|transaction (?:busy|conflict)/iu.test(i))return!0;t=t instanceof Error?t.cause:void 0}return!1}async startWorkerSession(e,t,r=Date.now(),i=ss){let n=r+i;await this.write("start worker session",async()=>this.db.insert(pt).values({slotId:e,sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:n}).onConflictDoUpdate({target:pt.slotId,set:{sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:n}}))}async heartbeatWorkerSession(e,t,r=Date.now(),i=ss){return(await this.write("heartbeat worker session",async()=>this.db.update(pt).set({heartbeatAt:r,expiresAt:r+i}).where(It(Qe(pt.slotId,e),Qe(pt.sessionId,t))).returning({slotId:pt.slotId}))).length===1}async endWorkerSession(e,t){return(await this.write("end worker session",async()=>this.db.delete(pt).where(It(Qe(pt.slotId,e),Qe(pt.sessionId,t))).returning({slotId:pt.slotId}))).length===1}async complete(e,t,r){let i=Date.now(),o=(await this.write("complete",async()=>this.db.update(ne).set({status:Ue.COMPLETED,result:t,lastError:null,completedAt:i,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i)}).where(this.attemptWriteGuard(e,r)).returning({id:ne.id}))).length===1;if(o)this.logger.debug("Job completed",{jobId:e,hasResult:t!==void 0});return o}async update(e,t,r){let n=(await this.write("update",async()=>this.db.update(ne).set({data:JSON.stringify(t)}).where(this.attemptWriteGuard(e,r)).returning({id:ne.id}))).length===1;if(n)this.logger.debug("Job data updated",{jobId:e});return n}async recordAttemptProgress(e,t,r,i=Date.now()){return(await this.write("record progress",async()=>this.db.update(ne).set({attemptHeartbeatAt:i,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i),progress:r}).where(this.attemptWriteGuard(e,t)).returning({id:ne.id}))).length===1}async renewAttemptLease(e,t,r,i){return(await this.write("renew attempt lease",async()=>this.db.update(ne).set({attemptHeartbeatAt:r,leaseExpiresAt:r+i}).where(this.attemptWriteGuard(e,t)).returning({id:ne.id}))).length===1}async fail(e,t,r,i=Date.now()){let o=(await this.db.select({retryCount:ne.retryCount,maxRetries:ne.maxRetries,type:ne.type,scheduledFor:ne.scheduledFor,startedAt:ne.startedAt,runtimeUpdatedAt:ne.runtimeUpdatedAt}).from(ne).where(this.attemptWriteGuard(e,r)).limit(1))[0];if(!o)return!1;let s=o.retryCount<o.maxRetries,a=s?o.retryCount+1:o.retryCount,c=Math.min(1000*2**o.retryCount,60000),l=s?i+c:o.scheduledFor;if((await this.write("fail",async()=>this.db.update(ne).set({status:s?Ue.PENDING:Ue.FAILED,retryCount:a,lastError:t.message,scheduledFor:l,completedAt:s?null:i,runtimeUpdatedAt:s?o.runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i),startedAt:s?null:o.startedAt,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(It(this.attemptWriteGuard(e,r),Qe(ne.retryCount,o.retryCount))).returning({id:ne.id}))).length!==1)return!1;if(s)this.logger.debug("Job scheduled for retry",{jobId:e,retryCount:a,backoffMs:c,scheduledFor:new Date(l).toISOString()});else this.logger.error("Job failed after max retries",{jobId:e,type:o.type,retryCount:o.retryCount,error:t.message});return!0}async retireUnownedActiveJob(e){let t=e.reason.trim();if(t.length===0)throw Error("Retired job reason must not be empty");let i=(await this.write("retire unowned job",async()=>this.db.update(ne).set({status:Ue.FAILED,lastError:t,completedAt:e.now,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(e.now)}).where(It(Qe(ne.id,e.jobId),Qe(ne.type,e.expectedType),xi(Qe(ne.status,Ue.PENDING),Qe(ne.status,Ue.PROCESSING)),En(ne.attemptId),En(ne.workerSlotId),En(ne.workerSessionId),En(ne.leaseExpiresAt),En(ne.attemptHeartbeatAt),En(ne.progress),En(ne.result))).returning()))[0]??null;if(i)this.logger.warn("Retired unowned legacy job",{jobId:i.id,type:i.type,reason:t});return i}async getStatus(e){return(await this.db.select().from(ne).where(Qe(ne.id,e)).limit(1))[0]??null}async getJobsByRootJobId(e){return this.db.select().from(ne).where(U`json_extract(${ne.metadata}, '$.rootJobId') = ${e}`).orderBy(ro(ne.createdAt),ro(ne.id))}async getStatusByEntityId(e){return(await this.db.select().from(ne).where(U`json_extract(${ne.data}, '$.id') = ${e}`).orderBy(Na(ne.createdAt)).limit(1))[0]??null}async getStats(){let e=await this.db.select({status:ne.status,count:U`count(*)`}).from(ne).groupBy(ne.status),t={pending:0,processing:0,failed:0,completed:0,total:0};for(let r of e){let i=Number(r.count);t[r.status]=i,t.total+=i}return t}async getDiagnostics(e=Date.now()){let[t,r,i]=await Promise.all([this.db.select({type:ne.type,status:ne.status,count:U`count(*)`}).from(ne).groupBy(ne.type,ne.status),this.db.select({oldestPendingAt:U`min(case when ${ne.status} = ${Ue.PENDING} then ${ne.createdAt} end)`,duePending:U`coalesce(sum(case when ${ne.status} = ${Ue.PENDING} and ${ne.scheduledFor} <= ${e} then 1 else 0 end), 0)`,oldestDuePendingAt:U`min(case when ${ne.status} = ${Ue.PENDING} and ${ne.scheduledFor} <= ${e} then ${ne.scheduledFor} end)`,latestClaimAt:U`max(${ne.startedAt})`,oldestProcessingAt:U`min(case when ${ne.status} = ${Ue.PROCESSING} then ${ne.startedAt} end)`,staleLeaseCount:U`coalesce(sum(case when ${ne.status} = ${Ue.PROCESSING} and ${ne.leaseExpiresAt} is not null and ${ne.leaseExpiresAt} <= ${e} then 1 else 0 end), 0)`}).from(ne),this.db.select({total:U`count(*)`,active:U`coalesce(sum(case when ${pt.expiresAt} > ${e} then 1 else 0 end), 0)`,stale:U`coalesce(sum(case when ${pt.expiresAt} <= ${e} then 1 else 0 end), 0)`,latestHeartbeatAt:U`max(${pt.heartbeatAt})`}).from(pt)]),n={pending:0,processing:0,completed:0,failed:0},o=t.map((l)=>{let u=Number(l.count);return n[l.status]+=u,{type:l.type,status:l.status,count:u}}),s=r[0],a=i[0],c=(l)=>l===null||l===void 0?null:Math.max(0,e-Number(l));return{totals:n,byType:o,oldestPendingAgeMs:c(s?.oldestPendingAt),duePending:Number(s?.duePending??0),oldestDuePendingAgeMs:c(s?.oldestDuePendingAt),latestClaimAgeMs:c(s?.latestClaimAt),oldestProcessingAgeMs:c(s?.oldestProcessingAt),staleLeaseCount:Number(s?.staleLeaseCount??0),workerSessions:{total:Number(a?.total??0),active:Number(a?.active??0),stale:Number(a?.stale??0),latestHeartbeatAgeMs:c(a?.latestHeartbeatAt)}}}async getRuntimeUpdates(e,t){let r=_Se.parse(t);if(r===0)return[];return(await this.db.select().from(ne).where(U`(${ne.runtimeUpdatedAt}, ${ne.id}) > (${e.updatedAt}, ${e.jobId})`).orderBy(ro(ne.runtimeUpdatedAt),ro(ne.id)).limit(r)).map((n)=>({job:n,cursor:{updatedAt:n.runtimeUpdatedAt??0,jobId:n.id}}))}async cleanup(e){let t=Date.now()-e;return(await this.write("cleanup",async()=>this.db.delete(ne).where(It(xi(Qe(ne.status,Ue.COMPLETED),Qe(ne.status,Ue.FAILED)),tu(ne.completedAt,t))))).rowsAffected}async getActiveJobs(e){let t=xi(Qe(ne.status,Ue.PENDING),Qe(ne.status,Ue.PROCESSING)),r=e&&e.length>0?It(t,Ss(ne.type,e)):t;return this.db.select().from(ne).where(r).orderBy(Na(ne.createdAt))}async getRecentJobs(e,t=20){let r=e&&e.length>0?Ss(ne.type,e):void 0;return this.db.select().from(ne).where(r).orderBy(Na(ne.createdAt)).limit(t)}async getFailedJobs(e){let t=Qe(ne.status,Ue.FAILED),r=e&&e.length>0?It(t,Ss(ne.type,e)):t;return this.db.select().from(ne).where(r).orderBy(Na(ne.createdAt))}async claimNextReady(e){let{now:t,attemptId:r,workerSlotId:i,workerSessionId:n,leaseDurationMs:o,executableTypes:s,exclusiveTypes:a=[]}=e,c=this.db.select({slotId:pt.slotId}).from(pt).where(It(Qe(pt.slotId,i),Qe(pt.sessionId,n),cp(pt.expiresAt,t))),l=this.db.select({slotId:pt.slotId}).from(pt).where(It(Qe(pt.slotId,ne.workerSlotId),Qe(pt.sessionId,ne.workerSessionId))),u=It(Qe(ne.status,Ue.PROCESSING),xi(En(ne.attemptId),lp(l),tu(ne.leaseExpiresAt,t))),f=MK(ne,"running"),p=this.db.select({id:f.id}).from(f).where(It(Qe(f.type,ne.type),Qe(f.status,Ue.PROCESSING),cp(f.leaseExpiresAt,t),U`${f.id} <> ${ne.id}`)),m=a.length===0?void 0:xi(jb(ne.type,[...a]),lp(p)),y=U`${ne.status} = ${Ue.PROCESSING} AND ${ne.retryCount} + 1 > ${ne.maxRetries}`,g=this.db.select({id:ne.id}).from(ne).where(It(Ss(ne.type,s),m,xi(It(Qe(ne.status,Ue.PENDING),tu(ne.scheduledFor,t)),u))).orderBy(ro(ne.priority),ro(ne.createdAt)).limit(1),_=(await this.write("claim",async()=>this.db.update(ne).set({status:U`CASE WHEN ${y} THEN ${Ue.FAILED} ELSE ${Ue.PROCESSING} END`,retryCount:U`CASE WHEN ${ne.status} = ${Ue.PROCESSING} THEN ${ne.retryCount} + 1 ELSE ${ne.retryCount} END`,lastError:U`CASE WHEN ${ne.status} = ${Ue.PROCESSING} THEN 'Attempt lease expired' ELSE ${ne.lastError} END`,startedAt:U`CASE WHEN ${y} THEN ${ne.startedAt} ELSE ${t} END`,completedAt:U`CASE WHEN ${y} THEN ${t} ELSE NULL END`,attemptId:U`CASE WHEN ${y} THEN ${ne.attemptId} ELSE ${r} END`,workerSlotId:U`CASE WHEN ${y} THEN ${ne.workerSlotId} ELSE ${i} END`,workerSessionId:U`CASE WHEN ${y} THEN ${ne.workerSessionId} ELSE ${n} END`,leaseExpiresAt:U`CASE WHEN ${y} THEN ${ne.leaseExpiresAt} ELSE ${t+o} END`,attemptHeartbeatAt:U`CASE WHEN ${y} THEN ${ne.attemptHeartbeatAt} ELSE ${t} END`,runtimeUpdatedAt:U`CASE WHEN ${y} THEN ${this.nextRuntimeUpdatedAt(t)} ELSE ${ne.runtimeUpdatedAt} END`}).where(It(Ss(ne.id,g),Ub(c))).returning()))[0];if(!_)return null;if(_.status===Ue.FAILED)return _;return this.logger.debug("Job claimed",{jobId:_.id,attemptId:_.attemptId,workerSlotId:i,workerSessionId:n}),_}nextRuntimeUpdatedAt(e){return U`max(${e}, coalesce((select max(${ne.runtimeUpdatedAt}) from ${ne}), 0) + 1)`}attemptWriteGuard(e,t){return t?It(Qe(ne.id,e),Qe(ne.status,Ue.PROCESSING),Qe(ne.attemptId,t)):It(Qe(ne.id,e),En(ne.attemptId),xi(Qe(ne.status,Ue.PENDING),Qe(ne.status,Ue.PROCESSING)))}}var xSe=2000,wSe=5,vSe=40,_Se,kSe;var oJ=S(()=>{nR();eS();iR();Ae();as();Pf();iJ();_Se=d.number().int().min(0).max(1000),kSe=new sR});import{AsyncLocalStorage as ESe}from"async_hooks";class wp{storage=new ESe;static createFresh(){return new wp}constructor(){}current(){return this.storage.getStore()}run(e,t,r){if(t.length===0)throw Error("Operation ID must not be empty");let i=ko.parse(e),n=ISe(i);return this.storage.run(Object.freeze({provenance:n,operationId:t}),r)}}function ISe(e){if(Object.freeze(e.projectionLineage),e.sourceEntity)Object.freeze(e.sourceEntity);return Object.freeze(e)}var lR=S(()=>{ti()});class vp{client;logger;handlerRegistry;repository;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;inFlightEnqueues=0;databaseUrl;operationContext;projectionAdmission;directWorkerSlotId=`direct:${Gi()}`;directWorkerSessionId=Gi();directLeaseDurationMs;directSessionStart=null;close(){this.closeRequested=!0,this.closeClientWhenReady()}static createFresh(e,t,r){return new vp(e,t??on.getInstance(),r)}constructor(e,t,r){let{db:i,client:n,url:o}=rJ(e);this.client=n,this.databaseUrl=o,this.logger=t.child("JobQueueService"),this.operationContext=r?.operationContext??wp.createFresh(),this.projectionAdmission=r?.projectionAdmission,this.handlerRegistry=new oR(this.logger,r?.handlerRegistrationMode??"combined"),this.repository=new cR(i,n,o,this.logger),this.directLeaseDurationMs=e.claimTimeoutMs??300000}initialize(){if(this.closeRequested)return Promise.resolve();return this.walInitialization??=this.initializeWALMode(),this.walInitialization}async initializeWALMode(){try{await sS(this.client,this.databaseUrl)}catch(e){this.logger.warn("Failed to enable WAL mode (non-fatal)",e)}finally{this.walInitializationSettled=!0,this.closeClientWhenReady()}}closeClientWhenReady(){if(!this.closeRequested||this.inFlightEnqueues>0||this.walInitialization!==null&&!this.walInitializationSettled)return;this.closeClient()}closeClient(){if(this.clientClosed)return;this.clientClosed=!0,this.client.close()}registerHandler(e,t,r){this.handlerRegistry.registerHandler(e,t,r)}unregisterHandler(e){this.handlerRegistry.unregisterHandler(e)}unregisterPluginHandlers(e){this.handlerRegistry.unregisterPluginHandlers(e)}getRegisteredTypes(){return this.handlerRegistry.getRegisteredTypes()}getHandler(e){return this.handlerRegistry.getHandler(e)}getValidator(e){return this.handlerRegistry.getValidator(e)}finalizeHandlerRegistrations(){return this.handlerRegistry.finalizeRegistrations()}getExecutionRegistrations(){return this.handlerRegistry.getExecutionRegistrations()}async enqueue(e){if(this.closeRequested)throw Error("Cannot enqueue a job after the queue service is closed");this.inFlightEnqueues++;try{return await this.enqueueValidated(e)}finally{this.inFlightEnqueues--,this.closeClientWhenReady()}}async enqueueValidated(e){let{type:t,data:r,options:i}=e,n=this.handlerRegistry.getValidator(t);if(!n)throw Error(`No job type declared: ${t}`);let o=n.validateAndParse(r);if(o===null)throw Error(`Invalid job data for type: ${t}`);let s=Date.now(),a=Gi(),c=i?.rootJobId??this.operationContext.current()?.provenance.rootJobId??a,l=this.createJobProvenance(a,c,i),u=i?.metadata??{operationType:"data_processing"},{provenance:f,...p}=u,m={id:a,type:t,data:JSON.stringify(o),status:Ue.PENDING,priority:i?.priority??0,maxRetries:i?.maxRetries??3,retryCount:0,source:i?.source??null,metadata:{...p,...i?.deduplicationKey&&{deduplicationKey:i.deduplicationKey},rootJobId:c,provenance:l},createdAt:s,scheduledFor:i?.delayMs?s+i.delayMs:s,result:null,lastError:null,startedAt:null,completedAt:null},y,g=()=>{y?.rollback(),y=void 0};try{let b=await this.repository.enqueueAtomic({jobData:m,strategy:i?.deduplication,deduplicationKey:i?.deduplicationKey,beforeInsert:async()=>{y=await this.projectionAdmission?.reserveJobAdmission(l)},onInsertRollback:g});if(y?.commit(),y=void 0,b.kind==="skipped")this.logger.debug("Skipping duplicate job (already pending)",{type:t,existingJobId:b.jobId});else if(b.kind==="coalesced")this.logger.debug("Coalescing with existing job",{type:t,existingJobId:b.jobId});else{if(b.kind==="replaced")this.logger.debug("Replacing duplicate job",{type:t,oldJobId:b.replacedJobId});this.logger.debug("Job enqueued",{id:b.jobId,type:t,priority:m.priority,rootJobId:m.metadata.rootJobId})}return b.jobId}catch(b){throw g(),this.logger.error("Failed to enqueue job",{type:t,error:at(b)}),b}}createJobProvenance(e,t,r){let i=this.operationContext.current(),n=r?.metadata.provenance??i?.provenance,o=n?.rootJobId===t?n:void 0,s=i?.provenance.rootJobId===t?i.operationId:void 0,a=r?.projection,c=a?[...o?.projectionLineage??[],a.id]:[...o?.projectionLineage??[]],l=a?.id??o?.projectionId;return ko.parse({rootJobId:t,causationId:s??o?.causationId??e,...l?{projectionId:l}:{},projectionLineage:c,...a?.sourceEntity?{sourceEntity:a.sourceEntity}:o?.sourceEntity?{sourceEntity:o.sourceEntity}:{},derivationDepth:c.length})}async dequeue(e){let t=this.handlerRegistry.getRegisteredTypes();if(t.length===0)return null;let{onTerminalReclaim:r,...i}=e??await this.getDirectClaimOptions(),n=Date.now(),o=await this.repository.claimNextReady({...i,now:n,attemptId:Gi(),executableTypes:t,exclusiveTypes:this.handlerRegistry.getExclusiveTypes()});if(!o)return null;if(o.status===Ue.FAILED)return this.logger.warn("Expired attempt failed terminally on reclaim",{id:o.id,type:o.type,retryCount:o.retryCount}),await r?.(o),null;return this.logger.debug("Job dequeued",{id:o.id,type:o.type,priority:o.priority,retryCount:o.retryCount,attemptId:o.attemptId,workerSlotId:o.workerSlotId,workerSessionId:o.workerSessionId}),o}async startWorkerSession(e,t,r=ss){await this.repository.startWorkerSession(e,t,Date.now(),r)}heartbeatWorkerSession(e,t,r=ss){return this.repository.heartbeatWorkerSession(e,t,Date.now(),r)}endWorkerSession(e,t){return this.repository.endWorkerSession(e,t)}renewAttemptLease(e,t,r){return this.repository.renewAttemptLease(e,t,Date.now(),r)}recordAttemptProgress(e,t,r){return this.repository.recordAttemptProgress(e,t,r)}complete(e,t,r){return this.repository.complete(e,t,r)}update(e,t,r){return this.repository.update(e,t,r)}fail(e,t,r){return this.repository.fail(e,t,r)}retireUnownedActiveJob(e){return this.repository.retireUnownedActiveJob(e)}async getDirectClaimOptions(){return this.directSessionStart??=this.repository.startWorkerSession(this.directWorkerSlotId,this.directWorkerSessionId,Date.now(),this.directLeaseDurationMs),await this.directSessionStart,{workerSlotId:this.directWorkerSlotId,workerSessionId:this.directWorkerSessionId,leaseDurationMs:this.directLeaseDurationMs}}async getStatus(e){return this.repository.getStatus(e)}async getJobsByRootJobId(e){return this.repository.getJobsByRootJobId(e)}async getStatusByEntityId(e){return this.repository.getStatusByEntityId(e)}async getStats(){return this.repository.getStats()}getDiagnostics(e){return this.repository.getDiagnostics(e)}async waitForIdle(e={}){let t=e.quietMs??250,r=e.pollIntervalMs??25,i=Date.now()+(e.timeoutMs??30000),n=async(o)=>{e.signal?.throwIfAborted();let{totals:s}=await this.getDiagnostics(),c=s.pending===0&&s.processing===0?o??Date.now():null;if(c!==null&&Date.now()-c>=t)return;if(Date.now()>=i)throw Error(`Timed out waiting for the job queue to settle: ${s.pending} pending, ${s.processing} processing`);return await Bun.sleep(r),n(c)};return n(null)}getRuntimeUpdates(e,t=1000){return this.repository.getRuntimeUpdates(e,t)}async cleanup(e){let t=await this.repository.cleanup(e);if(t>0)this.logger.info("Cleaned up old jobs",{deletedCount:t,olderThanMs:e});return t}async getActiveJobs(e){return this.repository.getActiveJobs(e)}async getRecentJobs(e,t){return this.repository.getRecentJobs(e,t)}async getFailedJobs(e){return this.repository.getFailedJobs(e)}}var sJ=S(()=>{Rf();m$();Pf();as();rR();nJ();oJ();ti();lR()});var uR=()=>{};var aJ=S(()=>{Rf();as();Pf();as();uR();lR()});var cJ=S(()=>{as();uR()});var nWe;var lJ=S(()=>{ti();Ae();Of();nWe=d.preprocess((e)=>{if(typeof e!=="string")return e;return JSON.parse(e)},d.record(d.string(),d.unknown()))});var sWe;var uJ=S(()=>{Ae();sWe=d.record(d.string(),d.unknown())});var dJ=S(()=>{ti();Rf()});var fJ=S(()=>{sJ();aJ();cJ();lJ();uJ();Pf();as();Of();dJ()});var dR={};Ht(dR,{LEGACY_PROJECTION_JOB_TYPES:()=>mJ,LEGACY_PROJECTION_RETIREMENT_REASON:()=>gJ,legacyProjectionJobTypeSchema:()=>hJ,retireLegacyProjectionJob:()=>DSe});import{existsSync as PSe}from"fs";import{resolve as zSe}from"path";function pJ(e){return{id:e.id,type:e.type,status:e.status,retryCount:e.retryCount,maxRetries:e.maxRetries,createdAt:e.createdAt,startedAt:e.startedAt,completedAt:e.completedAt}}function NSe(e,t){if(e.type!==t)throw Error(`Job ${e.id} has type ${e.type}; expected ${t}`);if(e.status!=="pending"&&e.status!=="processing")throw Error(`Job ${e.id} is already terminal (${e.status})`);if(e.attemptId!==null||e.workerSlotId!==null||e.workerSessionId!==null||e.leaseExpiresAt!==null||e.attemptHeartbeatAt!==null)throw Error(`Job ${e.id} still has attempt ownership`);if(e.progress!==null||e.result!=null)throw Error(`Job ${e.id} contains partial progress or a result`)}async function DSe(e){let t=zSe(e.databasePath);if(!PSe(t))throw Error(`Job database does not exist: ${t}`);let r=hJ.parse(e.jobType),i=vp.createFresh({url:`file:${t}`});try{let n=await i.getStatus(e.jobId);if(!n)throw Error(`Job not found: ${e.jobId}`);if(NSe(n,r),e.dryRun){if(e.confirmation!==void 0)throw Error("Dry-run recovery must not include confirmation");return{databasePath:t,job:pJ(n),retired:!1}}let o=`retire:${n.id}`;if(e.confirmation!==o)throw Error(`Refusing to retire ${n.id}; expected --confirm ${o}`);let s=await i.retireUnownedActiveJob({jobId:n.id,expectedType:r,reason:gJ,now:e.now?.()??Date.now()});if(!s)throw Error(`Job ${n.id} changed or acquired ownership before retirement`);return{databasePath:t,job:pJ(s),retired:!0}}finally{i.close()}}var mJ,hJ,gJ="Retired legacy projection job superseded by scheduler-owned projections";var fR=S(()=>{fJ();Ae();mJ=["conversation-memory:project","skill:project","swot:derive","topic:project"],hJ=d.enum(mJ)});function Yt(e,t,r,i,n){return bJ.parse({id:e,operation:t,count:r,targetProbeCount:i,settleMs:n})}function mR(e){return kp.parse(structuredClone(USe[e]))}function Ep(e){let t=`stress:${e.handle}`;if(e.confirmation!==t)throw Error(`Directory-sync stress requires --confirm ${t}`);let r=/(^|[-_.])smoke($|[-_.])/i;if(!r.test(e.handle)||!r.test(e.domain)||!r.test(e.contentRepo))throw Error("Directory-sync stress is smoke-only; handle, domain, and content repository must all identify smoke")}async function cS(e,t={}){let r=t.fetchImpl??fetch,i=t.now??(()=>new Date),n=t.timeoutMs??20000,o=i(),s=new AbortController,a=setTimeout(()=>s.abort(),n);try{let c=await r(e,{method:"GET",signal:s.signal});return await c.arrayBuffer(),pR.parse({timestamp:o.toISOString(),endpoint:new URL(e).pathname,status:c.status,durationMs:Math.max(0,i().getTime()-o.getTime()),ok:c.ok})}catch(c){return pR.parse({timestamp:o.toISOString(),endpoint:new URL(e).pathname,status:0,durationMs:Math.max(0,i().getTime()-o.getTime()),ok:!1,error:qSe(c)})}finally{clearTimeout(a)}}async function hR(e,t){let r=kp.parse(e),i=[],n,o=await t.prepare(r),s,a;try{try{await t.startMonitoring()}catch(c){n=`monitor: ${aS(c)}`}if(!n)for(let c of r.phases)try{let l=SJ.parse(await t.executePhase(c,o));if(i.push(l),!l.success){n=`${c.id}: ${l.error??"phase failed"}`;break}}catch(l){let u=aS(l);i.push({id:c.id,operation:c.operation,count:c.count,success:!1,error:u}),n=`${c.id}: ${u}`;break}}finally{try{if(s=xJ.parse(await t.cleanup(o)),!s.success&&!n)n=s.error??"cleanup failed"}catch(c){let l=aS(c);s={success:!1,probesRemaining:0,error:l},n??=`cleanup: ${l}`}try{a=wJ.parse(await t.stopMonitoring())}catch(c){let l=aS(c);a={health:[],runtime:[]},n??=`monitor: ${l}`}}return n??=_J(a,r.maximumExternalAiCalls??0),vJ.parse({profile:r.profile,success:n===void 0&&i.length===r.phases.length&&s.success,baseline:o,phases:i,cleanup:s,metrics:a,...n?{failure:n}:{}})}function _J(e,t=0){let r=e.health.find((o)=>!o.ok);if(r)return`health: ${r.endpoint} unavailable`;let i=e.externalAiCalls??0;if(i>t)return t===0?`external AI: observed ${i} call(s)`:`external AI: observed ${i} call(s), cap ${t}`;if(e.container?.oomKilled)return"container: OOM killed";let n=e.container?.restartCount??0;if(n>0)return`container: restarted ${n} time(s)`;if(e.container&&e.container.status!=="running")return`container: ${e.container.status}`;return}function qSe(e){if(e instanceof Error)return`${e.name}: ${e.message}`;return String(e)}function aS(e){return at(e)}var _p,yJ,bJ,kp,LSe,pR,BSe,SJ,xJ,jSe,wJ,vJ,USe;var lS=S(()=>{Ae();_p=d.enum(["regression","load","stress"]),yJ=d.enum(["add","update","rename","delete"]),bJ=d.object({id:d.string().min(1),operation:yJ,count:d.number().int().positive().max(700),targetProbeCount:d.number().int().min(0).max(700),settleMs:d.number().int().nonnegative().max(300000)}),kp=d.object({profile:_p,maximumProbeCount:d.number().int().positive().max(700),maximumExternalAiCalls:d.number().int().nonnegative().max(1e4).optional(),phases:d.array(bJ).min(1)}),LSe=d.object({entities:d.number().int().nonnegative(),notes:d.number().int().nonnegative(),version:d.string().min(1)}),pR=d.object({timestamp:d.iso.datetime(),endpoint:d.string().startsWith("/"),status:d.number().int().nonnegative(),durationMs:d.number().nonnegative(),ok:d.boolean(),error:d.string().optional()}),BSe=d.object({timestamp:d.iso.datetime(),cpuPercent:d.number().nonnegative(),memoryPercent:d.number().nonnegative(),pids:d.number().int().nonnegative()}),SJ=d.object({id:d.string().min(1),operation:yJ,count:d.number().int().positive(),success:d.boolean(),commitLatencyMs:d.number().nonnegative().optional(),persistenceLatencyMs:d.number().nonnegative().optional(),error:d.string().optional()}),xJ=d.object({success:d.boolean(),probesRemaining:d.number().int().nonnegative(),finalEntities:d.number().int().nonnegative().optional(),finalNotes:d.number().int().nonnegative().optional(),contentTreeRestored:d.boolean().optional(),error:d.string().optional()}),jSe=d.object({status:d.string(),restartCount:d.number().int().nonnegative(),oomKilled:d.boolean()}),wJ=d.object({health:d.array(pR),runtime:d.array(BSe),externalAiCalls:d.number().int().nonnegative().optional(),container:jSe.optional()}),vJ=d.object({profile:_p,success:d.boolean(),baseline:LSe,phases:d.array(SJ),cleanup:xJ,metrics:wJ,failure:d.string().optional()}),USe={regression:{profile:"regression",maximumProbeCount:20,phases:[Yt("add20","add",20,20,0),Yt("update20","update",20,20,30000),Yt("delete20","delete",20,0,150000)]},load:{profile:"load",maximumProbeCount:350,phases:[Yt("add50","add",50,50,0),Yt("add150","add",100,150,0),Yt("add350","add",200,350,0),Yt("update350a","update",350,350,45000),Yt("rename100","rename",100,350,45000),Yt("update350b","update",350,350,45000),Yt("delete350","delete",350,0,150000)]},stress:{profile:"stress",maximumProbeCount:700,phases:[Yt("add50","add",50,50,0),Yt("add150","add",100,150,0),Yt("add350","add",200,350,0),Yt("add700","add",350,700,0),Yt("update700a","update",700,700,45000),Yt("rename200","rename",200,700,45000),Yt("update700b","update",700,700,45000),Yt("delete700","delete",700,0,150000)]}}});import{spawn as ZSe}from"child_process";async function kJ(e,t,r,i){let n=await e(t,r,i);if(n.exitCode!==0)throw vi(t,r,n);return n}function vi(e,t,r){let i=r.stderr.trim()||r.stdout.trim();return Error(`${e} ${t.join(" ")} exited with ${r.exitCode}${i?`: ${i}`:""}`)}var co=async(e,t,r={})=>new Promise((i,n)=>{let o=ZSe(e,[...t],{cwd:r.cwd,env:r.env?{...process.env,...r.env}:process.env,stdio:["pipe","pipe","pipe"]}),s="",a="";o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",(c)=>{s+=c}),o.stderr.on("data",(c)=>{a+=c}),o.on("error",n),o.on("close",(c)=>{i({exitCode:c??1,stdout:s,stderr:a})}),o.stdin.end(r.stdin)});var Ip=()=>{};class cu{#e;#t;dir;constructor(e,t,r){this.#e=e,this.dir=t,this.#t=r}static async clone(e,t,r,i){let n=new cu(e,r,i);return await kJ(e,"git",["-c","credential.helper=","-c",`credential.helper=${EJ}`,"clone","--branch","main","--single-branch",`https://github.com/${t}.git`,r],{env:n.environment()}),await n.run(["config","--local","credential.helper",EJ]),await n.run(["reset","--hard","origin/main"]),n}async run(e,t=!0){let r=await this.#e("git",e,{cwd:this.dir,env:this.environment()});if(t&&r.exitCode!==0)throw vi("git",e,r);return r}async output(e){return(await this.run(e)).stdout.trim()}async sync(e=!1){if(await this.run(["fetch","origin","main"]),e)await this.run(["reset","--hard","origin/main"]);else await this.run(["pull","--rebase","origin","main"])}async commitAll(e){await this.run(["add","-A"]),await this.run(["-c","user.name=brains-ops","-c","user.email=ops@rizom.ai","commit","-m",e])}async pushMainWithRebase(){for(let e=1;e<=5;e+=1){if((await this.run(["push","origin","main"],!1)).exitCode===0)return;await this.run(["pull","--rebase","origin","main"])}throw Error("Unable to push content main after five rebase attempts")}async pruneStressBackupBranches(){let t=(await this.run(["ls-remote","--heads","origin","refs/heads/ops/directory-sync-stress-backup-*"])).stdout.split(/\r?\n/).map((r)=>r.match(/\trefs\/heads\/(ops\/directory-sync-stress-backup-[^\s]+)$/)?.[1]).filter((r)=>r!==void 0).sort();for(let r of t)await this.run(["push","origin","--delete",r]);return t}environment(){return{GH_TOKEN:this.#t,GITHUB_TOKEN:this.#t}}}var EJ='!f() { test "$1" = get && echo username=x-access-token && echo "password=$GH_TOKEN"; }; f';var IJ=S(()=>{Ip()});function Tp(e){return e.entityCounts.find((t)=>t.entityType==="note")?.count??0}class gR{#e;#t=[];#r=[];#n=new Set(["/health/ready"]);#i=!0;#o;#a;#s="";#c=0;#l;constructor(e){this.#e=e}get startedAt(){return this.#s}get error(){return this.#a}get healthSamples(){return this.#t}get runtimeSamples(){return this.#r}gateHealthSamples(){return this.#t.slice(this.#c,this.#l??this.#t.length)}markGateEnd(){this.#l=this.#t.length}async discoverEndpoints(){for(let e of["/health/live","/health/operate"])if((await cS(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:5000})).status!==404)this.#n.add(e)}start(){this.#i=!1,this.#a=void 0,this.#c=this.#t.length,this.#l=void 0,this.#s=this.#e.now().toISOString(),this.#o=Promise.all([this.#f(),this.#m()]).then(()=>{return}).catch((e)=>{this.#a=e,this.#i=!0})}async stop(){this.#i=!0,await this.#o}async waitForHealthSnapshot(e){return this.waitForEntityBaseline(void 0,void 0,e)}async waitForEntityBaseline(e,t,r){let i=this.#e.now().getTime();while(this.#e.now().getTime()-i<r){let n=await this.fetchHealthPayload();if(this.#d(n,e,t))return n;await this.#e.sleep(5000)}return}async waitForStableEntityBaseline(e,t,r){let i=this.#e.now().getTime(),n=0;while(this.#e.now().getTime()-i<r){let o=await this.fetchHealthPayload();if(this.#d(o,e,t)){if(n+=1,n===2)return o}else n=0;await this.#e.sleep(5000)}return}async fetchHealthPayload(){let e=this.#e.now(),t=new AbortController,r=setTimeout(()=>t.abort(),20000);try{let i=await this.#e.fetchImpl(`https://${this.#e.domain}/health/operate`,{signal:t.signal}),n=await i.text();if(this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:i.status,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:i.ok}),!i.ok)return;return MSe.parse(JSON.parse(n)).app}catch(i){this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:0,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:!1,error:i instanceof Error?`${i.name}: ${i.message}`:String(i)});return}finally{clearTimeout(r)}}#d(e,t,r){return e!==void 0&&(t===void 0||Tp(e)===t)&&(r===void 0||e.entities===r)}async#f(){while(!this.#i){for(let e of this.#n)this.#t.push(await cS(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:20000}));await this.#e.sleep(4000)}}async#m(){while(!this.#i){let e=await this.#e.sampleRuntime();if(e)this.#r.push(e);await this.#e.sleep(1000)}}}var MSe;var TJ=S(()=>{Ae();lS();MSe=d.object({status:d.literal("ready"),operationalStatus:d.literal("operational"),app:d.object({version:d.string(),entities:d.number().int().nonnegative(),entityCounts:d.array(d.object({entityType:d.string(),count:d.number().int().nonnegative()})).default([])})})});var uS={};Ht(uS,{applyDirectorySyncStressPhase:()=>zJ,cleanupDirectorySyncStress:()=>RJ,listProbeFiles:()=>ja,parseStressRuntimeSample:()=>NJ,removeProbeFiles:()=>_R,runDeployedDirectorySyncStress:()=>$J,runStressCommand:()=>co,verifyDirectorySyncStressAccess:()=>CJ});import{chmod as FSe,mkdir as bR,mkdtemp as SR,readFile as HSe,readdir as KSe,rename as JSe,rm as $p,writeFile as Kn}from"fs/promises";import{tmpdir as xR}from"os";import{join as St,resolve as wR}from"path";async function $J(e){let t=e.now??(()=>new Date),r=t().toISOString(),i=kR(r),n=wR(e.artifactsDir??St(e.rootDir,".brains-ops","stress",i));await bR(n,{recursive:!0});let{pilot:o,user:s}=await vR(e.rootDir,e.handle);Ep({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation});let a=_p.parse(e.profile),c=e.plan?kp.parse(e.plan):mR(a);if(c.profile!==a)throw Error(`Directory-sync stress plan profile ${c.profile} does not match requested profile ${a}`);if((c.maximumExternalAiCalls??0)===0)PJ(s);let l=VSe.parse(e.env??process.env),u=new OJ({runId:i,artifactsDir:n,user:s,githubOrg:o.githubOrg,serverLabel:`${o.contentRepoPrefix}${s.handle}`,environment:l,fetchImpl:e.fetchImpl??fetch,commandRunner:e.commandRunner??co,logger:e.logger??console.info,now:t,sleep:e.sleep??Bun.sleep}),f;try{f=await hR(c,u)}finally{await u.dispose()}let p={runId:i,artifactsDir:n,target:{handle:s.handle,domain:s.domain,contentRepo:`${o.githubOrg}/${s.contentRepo}`},startedAt:r,completedAt:t().toISOString(),report:f};return await XSe(p),p}async function CJ(e){let r=(e.now??(()=>new Date))().toISOString(),i=kR(r),n=wR(e.artifactsDir??St(e.rootDir,".brains-ops","stress",`access-check-${i}`));await bR(n,{recursive:!0});let{pilot:o,user:s}=await vR(e.rootDir,e.handle);Ep({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation}),PJ(s);let a=(e.env??process.env).CONTENT_REPO_ADMIN_TOKEN;if(!a)throw Error("Missing CONTENT_REPO_ADMIN_TOKEN");let c=await SR(St(xR(),"brains-ops-directory-sync-access-check-"));try{let l=await cu.clone(e.commandRunner??co,`${o.githubOrg}/${s.contentRepo}`,St(c,"content"),a),u=await l.output(["rev-parse","HEAD"]);await l.run(["push","--dry-run","origin",`HEAD:refs/heads/ops/directory-sync-stress-access-check-${i}`]);let f={success:!0,artifactsDir:n,checkedAt:r,remoteHead:u,target:{handle:s.handle,domain:s.domain,contentRepo:`${o.githubOrg}/${s.contentRepo}`}};return await Kn(St(n,"access-check.json"),`${JSON.stringify(f,null,2)}
|
|
421
|
+
`;await t.run(n);let s=(await t.values(U`SELECT id, hash, created_at FROM ${U.identifier(i)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0;await t.transaction(async(a)=>{for(let c of e)if(!s||Number(s[2])<c.folderMillis){for(let l of c.sql)await a.run(U.raw(l));await a.run(U`INSERT INTO ${U.identifier(i)} ("hash", "created_at") VALUES(${c.hash}, ${c.folderMillis})`)}})}}});var DC;var PK=S(()=>{ze();DC=class DC{static[J]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}});function Jb(e,t){return(r,i,...n)=>{let o=[i,...n].map((s)=>({type:e,isAll:t,rightSelect:s}));for(let s of o)if(!sp(r.getSelectedFields(),s.rightSelect.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return r.addSetOperators(o)}}var Hn,zK,LC,oSe=()=>({union:sSe,unionAll:aSe,intersect:cSe,except:lSe}),sSe,aSe,cSe,lSe;var BC=S(()=>{ze();PK();no();La();ur();Mn();vr();Dr();to();nu();gp();Hn=class Hn{static[J]="SQLiteSelectBuilder";fields;session;dialect;withList;distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,this.withList=e.withList,this.distinct=e.distinct}from(e){let t=!!this.fields,r;if(this.fields)r=this.fields;else if(ae(e,vt))r=Object.fromEntries(Object.keys(e._.selectedFields).map((i)=>[i,e[i]]));else if(ae(e,ao))r=e[_t].selectedFields;else if(ae(e,Te))r={};else r=Lb(e);return new LC({table:e,fields:r,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}};zK=class zK extends DC{static[J]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:r,session:i,dialect:n,withList:o,distinct:s}){super();this.config={withList:o,table:e,fields:{...t},distinct:s,setOperators:[]},this.isPartialSelect=r,this.session=i,this.dialect=n,this._={selectedFields:t,config:this.config},this.tableName=ap(e),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let a of Fn(e))this.usedTables.add(a)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(t,r)=>{let i=this.tableName,n=ap(t);for(let o of Fn(t))this.usedTables.add(o);if(typeof n==="string"&&this.config.joins?.some((o)=>o.alias===n))throw Error(`Alias "${n}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof i==="string")this.config.fields={[i]:this.config.fields};if(typeof n==="string"&&!ae(t,Te)){let o=ae(t,vt)?t._.selectedFields:ae(t,_n)?t[_t].selectedFields:t[we.Symbol.Columns];this.config.fields[n]=o}}if(typeof r==="function")r=r(new Proxy(this.config.fields,new bt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:r,table:t,joinType:e,alias:n}),typeof n==="string")switch(e){case"left":{this.joinsNotNullableMap[n]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([o])=>[o,!1])),this.joinsNotNullableMap[n]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[n]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([o])=>[o,!1])),this.joinsNotNullableMap[n]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");crossJoin=this.createJoin("cross");createSetOperator(e,t){return(r)=>{let i=typeof r==="function"?r(oSe()):r;if(!sp(this.getSelectedFields(),i.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:e,isAll:t,rightSelect:i}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);except=this.createSetOperator("except",!1);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new bt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=e,this}having(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new bt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=e,this}groupBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.fields,new bt({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.fields,new bt({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=r;else this.config.orderBy=r}else{let t=e;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=t;else this.config.orderBy=t}return this}limit(e){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=e;else this.config.limit=e;return this}offset(e){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=e;else this.config.offset=e;return this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){let t=[];if(t.push(...Fn(this.config.table)),this.config.joins)for(let r of this.config.joins)t.push(...Fn(r.table));return new Proxy(new vt(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new bt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new bt({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}};LC=class LC extends zK{static[J]="SQLiteSelect";_prepare(e=!0){if(!this.session)throw Error("Cannot execute a query on a query builder. Please use a database instance instead.");let t=kn(this.config.fields),r=this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),t,"all",!0,void 0,{type:"select",tables:[...this.usedTables]},this.cacheConfig);return r.joinsNotNullableMap=this.joinsNotNullableMap,r}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enable:!0,autoInvalidate:!0}:e===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...e},this}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(){return this.all()}};fH(LC,[Lr]);sSe=Jb("union",!1),aSe=Jb("union",!0),cSe=Jb("intersect",!1),lSe=Jb("except",!1)});var Ba;var Vb=S(()=>{ze();La();Kb();Mn();BC();Ba=class Ba{static[J]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=ae(e,ou)?e:void 0,this.dialectConfig=ae(e,ou)?void 0:e}$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(r);return new Proxy(new np(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new bt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...e){let t=this;function r(n){return new Hn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function i(n){return new Hn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:r,selectDistinct:i}}select(e){return new Hn({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new Hn({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new zC(this.dialectConfig);return this.dialect}}});var Wb,jC;var NK=S(()=>{ze();no();ur();io();vr();Dr();nu();Vb();Wb=class Wb{constructor(e,t,r,i){this.table=e,this.session=t,this.dialect=r,this.withList=i}static[J]="SQLiteInsertBuilder";values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw Error("values() must be called with at least one value");let t=e.map((r)=>{let i={},n=this.table[we.Symbol.Columns];for(let o of Object.keys(r)){let s=r[o];i[o]=ae(s,Te)?s:new an(s,n[o])}return i});return new jC(this.table,t,this.session,this.dialect,this.withList)}select(e){let t=typeof e==="function"?e(new Ba):e;if(!ae(t,Te)&&!sp(this.table[zb],t._.selectedFields))throw Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new jC(this.table,t,this.session,this.dialect,this.withList,!0)}};jC=class jC extends Lr{constructor(e,t,r,i,n,o){super();this.session=r,this.dialect=i,this.config={table:e,values:t,withList:n,select:o}}static[J]="SQLiteInsert";config;returning(e=this.config.table[Bt.Symbol.Columns]){return this.config.returning=kn(e),this}onConflictDoNothing(e={}){if(!this.config.onConflict)this.config.onConflict=[];if(e.target===void 0)this.config.onConflict.push(U` on conflict do nothing`);else{let t=Array.isArray(e.target)?U`${e.target}`:U`${[e.target]}`,r=e.where?U` where ${e.where}`:U``;this.config.onConflict.push(U` on conflict ${t} do nothing${r}`)}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');if(!this.config.onConflict)this.config.onConflict=[];let t=e.where?U` where ${e.where}`:void 0,r=e.targetWhere?U` where ${e.targetWhere}`:void 0,i=e.setWhere?U` where ${e.setWhere}`:void 0,n=Array.isArray(e.target)?U`${e.target}`:U`${[e.target]}`,o=this.dialect.buildUpdateSet(this.config.table,Db(this.config.table,e.set));return this.config.onConflict.push(U` on conflict ${n}${r} do update set ${o}${t}${i}`),this}getSQL(){return this.dialect.buildInsertQuery(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:"insert",tables:Fn(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(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var Gb,DK;var LK=S(()=>{ze();no();La();io();Mn();vr();Dr();to();nu();gp();Gb=class Gb{constructor(e,t,r,i){this.table=e,this.session=t,this.dialect=r,this.withList=i}static[J]="SQLiteUpdateBuilder";set(e){return new DK(this.table,Db(this.table,e),this.session,this.dialect,this.withList)}};DK=class DK extends Lr{constructor(e,t,r,i,n){super();this.session=r,this.dialect=i,this.config={set:t,table:e,withList:n,joins:[]}}static[J]="SQLiteUpdate";config;from(e){return this.config.from=e,this}createJoin(e){return(t,r)=>{let i=ap(t);if(typeof i==="string"&&this.config.joins.some((n)=>n.alias===i))throw Error(`Alias "${i}" is already used in this query`);if(typeof r==="function"){let n=this.config.from?ae(t,Bt)?t[we.Symbol.Columns]:ae(t,vt)?t._.selectedFields:ae(t,ao)?t[_t].selectedFields:void 0:void 0;r=r(new Proxy(this.config.table[we.Symbol.Columns],new bt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),n&&new Proxy(n,new bt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:r,table:t,joinType:e,alias:i}),this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.table[we.Symbol.Columns],new bt({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.config.table[Bt.Symbol.Columns]){return this.config.returning=kn(e),this}getSQL(){return this.dialect.buildUpdateQuery(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:"insert",tables:Fn(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(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var UC=S(()=>{AK();NK();Vb();BC();LK()});var yp;var BK=S(()=>{ze();ur();yp=class yp extends Te{constructor(e){super(yp.buildEmbeddedCount(e.source,e.filters).queryChunks);this.params=e,this.session=e.session,this.sql=yp.buildCount(e.source,e.filters)}sql;static[J]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(e,t){return U`(select count(*) from ${e}${U.raw(" where ").if(t)}${t})`}static buildCount(e,t){return U`select count(*) from ${e}${U.raw(" where ").if(t)}${t}`}then(e,t){return Promise.resolve(this.session.count(this.sql)).then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return this.then((t)=>(e?.(),t),(t)=>{throw e?.(),t})}}});var ZC,Qb,qC;var jK=S(()=>{ze();no();dp();ZC=class ZC{constructor(e,t,r,i,n,o,s,a){this.mode=e,this.fullSchema=t,this.schema=r,this.tableNamesMap=i,this.table=n,this.tableConfig=o,this.dialect=s,this.session=a}static[J]="SQLiteAsyncRelationalQueryBuilder";findMany(e){return this.mode==="sync"?new qC(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many"):new Qb(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many")}findFirst(e){return this.mode==="sync"?new qC(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new Qb(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}};Qb=class Qb extends Lr{constructor(e,t,r,i,n,o,s,a,c){super();this.fullSchema=e,this.schema=t,this.tableNamesMap=r,this.table=i,this.tableConfig=n,this.dialect=o,this.session=s,this.config=a,this.mode=c}static[J]="SQLiteAsyncRelationalQuery";mode;getSQL(){return this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}).sql}_prepare(e=!1){let{query:t,builtQuery:r}=this._toSQL();return this.session[e?"prepareOneTimeQuery":"prepareQuery"](r,void 0,this.mode==="first"?"get":"all",!0,(i,n)=>{let o=i.map((s)=>qb(this.schema,this.tableConfig,s,t.selection,n));if(this.mode==="first")return o[0];return o})}prepare(){return this._prepare(!1)}_toSQL(){let e=this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}),t=this.dialect.sqlToQuery(e.sql);return{query:e,builtQuery:t}}toSQL(){return this._toSQL().builtQuery}executeRaw(){if(this.mode==="first")return this._prepare(!1).get();return this._prepare(!1).all()}async execute(){return this.executeRaw()}};qC=class qC extends Qb{static[J]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}});var su;var UK=S(()=>{ze();no();su=class su extends Lr{constructor(e,t,r,i,n){super();this.execute=e,this.getSQL=t,this.dialect=i,this.mapBatchResult=n,this.config={action:r}}static[J]="SQLiteRaw";config;getQuery(){return{...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult(e,t){return t?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return!1}}});var bp;var Yb=S(()=>{ze();La();ur();UC();Mn();BK();jK();UK();bp=class bp{constructor(e,t,r,i){this.resultKind=e,this.dialect=t,this.session=r,this._=i?{schema:i.schema,fullSchema:i.fullSchema,tableNamesMap:i.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let n=this.query;if(this._.schema)for(let[o,s]of Object.entries(this._.schema))n[o]=new ZC(e,i.fullSchema,this._.schema,this._.tableNamesMap,i.fullSchema[o],s,t,r);this.$cache={invalidate:async(o)=>{}}}static[J]="BaseSQLiteDatabase";query;$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(new Ba(r.dialect));return new Proxy(new np(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new bt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(e,t){return new yp({source:e,filters:t,session:this.session})}with(...e){let t=this;function r(a){return new Hn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e})}function i(a){return new Hn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function n(a){return new Gb(a,t.session,t.dialect,e)}function o(a){return new Wb(a,t.session,t.dialect,e)}function s(a){return new Fb(a,t.session,t.dialect,e)}return{select:r,selectDistinct:i,update:n,insert:o,delete:s}}select(e){return new Hn({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new Hn({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new Gb(e,this.session,this.dialect)}$cache;insert(e){return new Wb(e,this.session,this.dialect)}delete(e){return new Fb(e,this.session,this.dialect)}run(e){let t=typeof e==="string"?U.raw(e):e.getSQL();if(this.resultKind==="async")return new su(async()=>this.session.run(t),()=>t,"run",this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session));return this.session.run(t)}all(e){let t=typeof e==="string"?U.raw(e):e.getSQL();if(this.resultKind==="async")return new su(async()=>this.session.all(t),()=>t,"all",this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session));return this.session.all(t)}get(e){let t=typeof e==="string"?U.raw(e):e.getSQL();if(this.resultKind==="async")return new su(async()=>this.session.get(t),()=>t,"get",this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session));return this.session.get(t)}values(e){let t=typeof e==="string"?U.raw(e):e.getSQL();if(this.resultKind==="async")return new su(async()=>this.session.values(t),()=>t,"values",this.dialect,this.session.extractRawValuesValueFromBatchResult.bind(this.session));return this.session.values(t)}transaction(e,t){return this.session.transaction(e,t)}}});async function MC(e,t){let r=`${e}-${JSON.stringify(t)}`,n=new TextEncoder().encode(r),o=await crypto.subtle.digest("SHA-256",n);return[...new Uint8Array(o)].map((c)=>c.toString(16).padStart(2,"0")).join("")}var qK,Sp;var FC=S(()=>{ze();qK=class qK{static[J]="Cache"};Sp=class Sp extends qK{strategy(){return"all"}static[J]="NoopCache";async get(e){return}async put(e,t,r,i){}async onMutate(e){}}});var ZK=S(()=>{FC()});function MK(e,t){return new Proxy(e,new Da(t,!1))}var FK=S(()=>{mp()});var HK,HC,KC,JC;var VC=S(()=>{FC();ze();Hb();no();Yb();HK=class HK extends Lr{constructor(e){super();this.resultCb=e}static[J]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}};HC=class HC{constructor(e,t,r,i,n,o){if(this.mode=e,this.executeMethod=t,this.query=r,this.cache=i,this.queryMetadata=n,this.cacheConfig=o,i&&i.strategy()==="all"&&o===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}static[J]="PreparedQuery";joinsNotNullableMap;async queryWithCache(e,t,r){if(this.cache===void 0||ae(this.cache,Sp)||this.queryMetadata===void 0)try{return await r()}catch(i){throw new so(e,t,i)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await r()}catch(i){throw new so(e,t,i)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[i]=await Promise.all([r(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return i}catch(i){throw new so(e,t,i)}if(!this.cacheConfig)try{return await r()}catch(i){throw new so(e,t,i)}if(this.queryMetadata.type==="select"){let i=await this.cache.get(this.cacheConfig.tag??await MC(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(i===void 0){let n;try{n=await r()}catch(o){throw new so(e,t,o)}return await this.cache.put(this.cacheConfig.tag??await MC(e,t),n,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),n}return i}try{return await r()}catch(i){throw new so(e,t,i)}}getQuery(){return this.query}mapRunResult(e,t){return e}mapAllResult(e,t){throw Error("Not implemented")}mapGetResult(e,t){throw Error("Not implemented")}execute(e){if(this.mode==="async")return this[this.executeMethod](e);return new HK(()=>this[this.executeMethod](e))}mapResult(e,t){switch(this.executeMethod){case"run":return this.mapRunResult(e,t);case"all":return this.mapAllResult(e,t);case"get":return this.mapGetResult(e,t)}}};KC=class KC{constructor(e){this.dialect=e}static[J]="SQLiteSession";prepareOneTimeQuery(e,t,r,i,n,o,s){return this.prepareQuery(e,t,r,i,n,o,s)}run(e){let t=this.dialect.sqlToQuery(e);try{return this.prepareOneTimeQuery(t,void 0,"run",!1).run()}catch(r){throw new iu({cause:r,message:`Failed to run the query '${t.sql}'`})}}extractRawRunValueFromBatchResult(e){return e}all(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).all()}extractRawAllValueFromBatchResult(e){throw Error("Not implemented")}get(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).get()}extractRawGetValueFromBatchResult(e){throw Error("Not implemented")}values(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).values()}async count(e){return(await this.values(e))[0][0]}extractRawValuesValueFromBatchResult(e){throw Error("Not implemented")}};JC=class JC extends bp{constructor(e,t,r,i,n=0){super(e,t,r,i);this.schema=i,this.nestedIndex=n}static[J]="SQLiteTransaction";rollback(){throw new RC}}});var WC,uSe,dSe,Xb;var KK=S(()=>{ze();La();Dr();Vb();io();gp();WC=class WC{constructor(e){this.name=e}static[J]="SQLiteViewBuilderCore";config={}};uSe=class uSe extends WC{static[J]="SQLiteViewBuilder";as(e){if(typeof e==="function")e=e(new Ba);let t=new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}),r=e.getSelectedFields();return new Proxy(new Xb({config:{name:this.name,schema:void 0,selectedFields:r,query:e.getSQL().inlineParams()}}),t)}};dSe=class dSe extends WC{static[J]="SQLiteManualViewBuilder";columns;constructor(e,t){super(e);this.columns=Lb(hp(e,t))}existing(){return new Proxy(new Xb({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:void 0}}),new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}as(e){return new Proxy(new Xb({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:e.inlineParams()}}),new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}};Xb=class Xb extends ao{static[J]="SQLiteView";constructor({config:e}){super(e)}}});var eS=S(()=>{FK();wK();PC();Yb();Kb();xC();EK();TK();UC();VC();io();vC();nu();KK()});function JK(e){return Object.keys(e).reduce((t,r)=>{if(Object.prototype.propertyIsEnumerable.call(e,r))t[r]=e[r];return t},{})}function tS(e){if(typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer){if(typeof Buffer<"u"){if(!(e instanceof Buffer))return Buffer.from(e);return e}if(typeof TextDecoder<"u")return new TextDecoder().decode(e);throw Error("TextDecoder is not available. Please provide either Buffer or TextDecoder polyfill.")}return e}var rS,GC,VK;var QC=S(()=>{ZK();ze();Bb();ur();eS();VC();Dr();rS=class rS extends KC{constructor(e,t,r,i,n){super(t);this.client=e,this.schema=r,this.options=i,this.tx=n,this.logger=i.logger??new pC,this.cache=i.cache??new Sp}static[J]="LibSQLSession";logger;cache;prepareQuery(e,t,r,i,n,o,s){return new VK(this.client,e,this.logger,this.cache,o,s,t,this.tx,r,i,n)}async batch(e){let t=[],r=[];for(let n of e){let o=n._prepare(),s=o.getQuery();t.push(o),r.push({sql:s.sql,args:s.params})}return(await this.client.batch(r)).map((n,o)=>t[o].mapResult(n,!0))}async migrate(e){let t=[],r=[];for(let n of e){let o=n._prepare(),s=o.getQuery();t.push(o),r.push({sql:s.sql,args:s.params})}return(await this.client.migrate(r)).map((n,o)=>t[o].mapResult(n,!0))}async transaction(e,t){let r=await this.client.transaction(),i=new rS(this.client,this.dialect,this.schema,this.options,r),n=new GC("async",this.dialect,i,this.schema);try{let o=await e(n);return await r.commit(),o}catch(o){throw await r.rollback(),o}}extractRawAllValueFromBatchResult(e){return e.rows}extractRawGetValueFromBatchResult(e){return e.rows[0]}extractRawValuesValueFromBatchResult(e){return e.rows}};GC=class GC extends JC{static[J]="LibSQLTransaction";async transaction(e){let t=`sp${this.nestedIndex}`,r=new GC("async",this.dialect,this.session,this.schema,this.nestedIndex+1);await this.session.run(U.raw(`savepoint ${t}`));try{let i=await e(r);return await this.session.run(U.raw(`release savepoint ${t}`)),i}catch(i){throw await this.session.run(U.raw(`rollback to savepoint ${t}`)),i}}};VK=class VK extends HC{constructor(e,t,r,i,n,o,s,a,c,l,u){super("async",c,t,i,n,o);this.client=e,this.logger=r,this.fields=s,this.tx=a,this._isResponseInArrayMode=l,this.customResultMapper=u,this.customResultMapper=u,this.fields=s}static[J]="LibSQLPreparedQuery";async run(e){let t=op(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),await this.queryWithCache(this.query.sql,t,async()=>{let r={sql:this.query.sql,args:t};return this.tx?this.tx.execute(r):this.client.execute(r)})}async all(e){let{fields:t,logger:r,query:i,tx:n,client:o,customResultMapper:s}=this;if(!t&&!s){let c=op(i.params,e??{});return r.logQuery(i.sql,c),await this.queryWithCache(i.sql,c,async()=>{let l={sql:i.sql,args:c};return(n?n.execute(l):o.execute(l)).then(({rows:u})=>this.mapAllResult(u))})}let a=await this.values(e);return this.mapAllResult(a)}mapAllResult(e,t){if(t)e=e.rows;if(!this.fields&&!this.customResultMapper)return e.map((r)=>JK(r));if(this.customResultMapper)return this.customResultMapper(e,tS);return e.map((r)=>uC(this.fields,Array.prototype.slice.call(r).map((i)=>tS(i)),this.joinsNotNullableMap))}async get(e){let{fields:t,logger:r,query:i,tx:n,client:o,customResultMapper:s}=this;if(!t&&!s){let c=op(i.params,e??{});return r.logQuery(i.sql,c),await this.queryWithCache(i.sql,c,async()=>{let l={sql:i.sql,args:c};return(n?n.execute(l):o.execute(l)).then(({rows:u})=>this.mapGetResult(u))})}let a=await this.values(e);return this.mapGetResult(a)}mapGetResult(e,t){if(t)e=e.rows;let r=e[0];if(!this.fields&&!this.customResultMapper)return JK(r);if(!r)return;if(this.customResultMapper)return this.customResultMapper(e,tS);return uC(this.fields,Array.prototype.slice.call(r).map((i)=>tS(i)),this.joinsNotNullableMap)}async values(e){let t=op(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),await this.queryWithCache(this.query.sql,t,async()=>{let r={sql:this.query.sql,args:t};return(this.tx?this.tx.execute(r):this.client.execute(r)).then(({rows:i})=>i)})}isResponseInArrayMode(){return this._isResponseInArrayMode}}});function au(e,t={}){let r=new NC({casing:t.casing}),i;if(t.logger===!0)i=new fC;else if(t.logger!==!1)i=t.logger;let n;if(t.schema){let a=DH(t.schema,BH);n={fullSchema:t.schema,schema:a.tables,tableNamesMap:a.tableNamesMap}}let o=new rS(e,r,n,{logger:i,cache:t.cache},void 0),s=new WK("async",r,o,n);if(s.$client=e,s.$cache=t.cache,s.$cache)s.$cache.invalidate=t.cache?.onMutate;return s}var WK;var GK=S(()=>{ze();Bb();dp();Yb();Kb();QC();WK=class WK extends bp{static[J]="LibSQLDatabase";async batch(e){return this.session.batch(e)}}});function nS(...e){if(typeof e[0]==="string"){let t=Yl({url:e[0]});return au(t,e[1])}if(pH(e[0])){let{connection:t,client:r,...i}=e[0];if(r)return au(r,i);let n=typeof t==="string"?Yl({url:t}):Yl(t);return au(n,i)}return au(e[0],e[1])}var QK=S(()=>{X$();Dr();GK();((e)=>{function t(r){return au({},r)}e.mock=t})(nS||(nS={}))});var YK=S(()=>{QK();QC()});function fSe(){return new Promise((e)=>setTimeout(e,0))}function mSe(){if(YC)return;YC=!0,setTimeout(()=>{YC=!1,XC=performance.now()},0)}async function xp(e=pSe){if(mSe(),performance.now()-XC<e)return;await fSe(),XC=performance.now()}var pSe=50,XC,YC=!1;var XK=S(()=>{XC=performance.now()});function eJ(e){if(e.authToken!==void 0)return e.authToken;if(e.authTokenEnv===void 0)return;return process.env[e.authTokenEnv]}function bSe(e){return e instanceof Be&&/^SQLITE_(?:BUSY|LOCKED)$/u.test(e.code)}async function iS(e,t){let r=Date.now()+(t.budgetMs??hSe),i=async(n)=>{if(t.isClosed())throw new Be("The client is closed","CLIENT_CLOSED");try{return await e()}catch(o){if(t.isClosed()||!bSe(o))throw o;await t.afterRefusal?.();let s=Math.min(gSe*2**(n-1),ySe),a=s/2+Math.random()*(s/2);if(t.isClosed()||Date.now()+a>=r)throw o;if(await new Promise((c)=>setTimeout(c,a)),t.isClosed()||Date.now()>=r)throw o;return i(n+1)}};return i(1)}function eR(e,t={}){let r=Yl({...e,...e.url.startsWith("file:")?{timeout:0}:{}});if(e.url.startsWith("file:")&&e.syncUrl===void 0){let i=r.transaction.bind(r),n=()=>r.closed,o=t.contentionRetryBudgetMs,s=r.execute.bind(r),a=r.batch.bind(r),c=r.migrate.bind(r),l={isClosed:n,budgetMs:o,afterRefusal:async()=>{await Promise.resolve(r.reconnect())}};async function u(f,p){return await xp(),iS(()=>typeof f==="string"?s(f,p):s(f),l)}r.execute=u,r.batch=async(f,p)=>(await xp(),iS(()=>a(f,p),l)),r.migrate=async(f)=>(await xp(),iS(()=>c(f),l)),r.transaction=async(f)=>(await xp(),iS(()=>i(f),l))}return r}function oS(e){let{url:t,schema:r}=e,i=eJ(e),n={contentionRetryBudgetMs:e.contentionRetryBudgetMs},o=i?eR({url:t,authToken:i},n):eR({url:t},n);return{db:nS(o,{schema:r}),client:o,url:t}}async function sS(e,t){if(!t.startsWith("file:"))return;for(let r of["PRAGMA busy_timeout = 0","PRAGMA journal_mode = WAL"])await e.execute(r)}var hSe=5000,gSe=5,ySe=40;var tR=S(()=>{X$();YK();XK()});var tJ=S(()=>{m$();tR()});var rR=S(()=>{tR();tJ()});var nR=S(()=>{mp();Rb();Zn();ze();Hb();Bb();no();dp();OC();Mn();vr();Dr();to()});var ne,pt;var iR=S(()=>{eS();nR();Rf();ne=hp("job_queue",{id:dr("id").primaryKey().$defaultFn(()=>Gi()),type:dr("type").notNull(),data:dr("data").notNull(),result:dr("result",{mode:"json"}),progress:dr("progress",{mode:"json"}).$type(),source:dr("source"),metadata:dr("metadata",{mode:"json"}).$type().notNull(),status:dr("status",{enum:["pending","processing","completed","failed"]}).notNull().default("pending"),priority:_r("priority").notNull().default(0),retryCount:_r("retryCount").notNull().default(0),maxRetries:_r("maxRetries").notNull().default(3),lastError:dr("lastError"),createdAt:_r("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:_r("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:_r("startedAt"),completedAt:_r("completedAt"),attemptId:dr("attemptId"),workerSlotId:dr("workerSlotId"),workerSessionId:dr("workerSessionId"),leaseExpiresAt:_r("leaseExpiresAt"),attemptHeartbeatAt:_r("attemptHeartbeatAt"),runtimeUpdatedAt:_r("runtimeUpdatedAt")},(e)=>({queueReadyIdx:oo("idx_job_queue_ready").on(e.status,e.priority,e.scheduledFor),jobTypeIdx:oo("idx_job_queue_type").on(e.type,e.status),runtimeUpdatesIdx:oo("idx_job_queue_runtime_updates").on(e.runtimeUpdatedAt,e.id),jobSourceIdx:oo("idx_job_queue_source").on(e.source),rootJobIdx:oo("idx_job_queue_root_job").on(U`json_extract(${e.metadata}, '$.rootJobId')`,e.createdAt,e.id),deduplicationIdx:oo("idx_job_queue_deduplication").on(e.type,U`json_extract(${e.metadata}, '$.deduplicationKey')`,e.status)})),pt=hp("job_worker_sessions",{slotId:dr("slotId").primaryKey(),sessionId:dr("sessionId").notNull().unique(),startedAt:_r("startedAt").notNull(),heartbeatAt:_r("heartbeatAt").notNull(),expiresAt:_r("expiresAt").notNull().default(0)},(e)=>({heartbeatIdx:oo("idx_job_worker_sessions_heartbeat").on(e.heartbeatAt),expiresIdx:oo("idx_job_worker_sessions_expires").on(e.expiresAt)}))});function rJ(e){return oS({url:e.url,schema:{jobQueue:ne,jobWorkerSessions:pt},authToken:e.authToken,authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",contentionRetryBudgetMs:0})}var nJ=S(()=>{rR();iR()});class oR{declarations=new Map;handlers=new Map;validators=new Map;logger;mode;finalizedRegistrations;constructor(e,t){this.logger=e.child("HandlerRegistry"),this.mode=t}registerHandler(e,t,r){if(this.finalizedRegistrations)throw Error("Job handler registrations are finalized");if(this.declarations.has(e))throw Error(`Job handler is already registered for type: ${e}`);if(this.declarations.set(e,{handler:t,pluginId:r}),this.validators.set(e,t),this.mode!=="validation-only")this.handlers.set(e,t);this.logger.debug("Registered job execution declaration",{type:e,pluginId:r,mode:this.mode})}unregisterHandler(e){this.declarations.delete(e),this.handlers.delete(e),this.validators.delete(e),this.logger.debug("Unregistered job handler",{type:e})}unregisterPluginHandlers(e){let t=[...this.declarations.entries()].filter(([,r])=>r.pluginId===e).map(([r])=>r);for(let r of t)this.declarations.delete(r),this.handlers.delete(r),this.validators.delete(r);if(t.length>0)this.logger.debug("Unregistered plugin handlers",{pluginId:e,count:t.length,types:t})}finalizeRegistrations(){return this.finalizedRegistrations??=Object.freeze([...this.declarations.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>Object.freeze({type:e,pluginId:t.pluginId}))),this.finalizedRegistrations}getExecutionRegistrations(){return this.finalizedRegistrations}getRegisteredTypes(){return[...this.handlers.keys()]}getExclusiveTypes(){return[...this.handlers].filter(([,e])=>e.exclusive===!0).map(([e])=>e)}getHandler(e){return this.handlers.get(e)}getValidator(e){return this.validators.get(e)}}class sR{tails=new Map;async run(e,t){let r=this.tails.get(e),i=()=>{},n=new Promise((o)=>{i=o});this.tails.set(e,n),await r;try{return await t()}finally{if(i(),this.tails.get(e)===n)this.tails.delete(e)}}}class aR{findDuplicate(e,t,r){if(!t||t==="none")return null;let i=this.filterByDeduplicationKey(e,r).sort((o,s)=>s.createdAt-o.createdAt||s.id.localeCompare(o.id)),n=i.find((o)=>o.status===Ue.PENDING)??null;if(t==="skip"||t==="replace")return n;return n??i[0]??null}filterByDeduplicationKey(e,t){if(!t)return e;return e.filter((r)=>{let i=SSe.safeParse(r.metadata);return i.success&&i.data.deduplicationKey===t})}}var SSe;var iJ=S(()=>{Ae();as();SSe=d.looseObject({deduplicationKey:d.string().optional()})});class cR{db;transactionClient;databaseUrl;logger;deduplicator=new aR;writeRetryBudgetMs;constructor(e,t,r,i,n){this.db=e,this.transactionClient=t,this.databaseUrl=r,this.logger=i.child("JobQueueRepository"),this.writeRetryBudgetMs=n?.writeRetryBudgetMs??xSe}async insert(e){await this.write("insert",async()=>this.db.insert(ne).values(e))}async enqueueAtomic(e){return kSe.run(this.databaseUrl,async()=>{let t=Date.now()+this.writeRetryBudgetMs;return this.attemptEnqueue(e,t,1)})}async attemptEnqueue(e,t,r){let i=await this.runEnqueueTransaction(e,t,r);if(i.retry)return this.attemptEnqueue(e,t,r+1);return i.decision}async runEnqueueTransaction(e,t,r){let i=await this.acquireWriteTransaction(e,t),n={prepared:!1},o=!1;try{let s=await this.decideEnqueue(i,e,()=>{n.prepared=!0});return o=!0,await i.commit(),{retry:!1,decision:s}}catch(s){let a=o&&this.isSerializationConflict(s)&&!i.closed,c=!0;if(!i.closed)try{await i.rollback()}catch(l){c=!1,this.logger.error("Failed to roll back atomic enqueue",{type:e.jobData.type,rollbackError:l})}if(n.prepared)e.onInsertRollback?.();if(!a||!c)throw s;return await this.waitForConflictRetry("commit",e,t,r,s),{retry:!0}}finally{i.close()}}async decideEnqueue(e,t,r){let{jobData:i,strategy:n,deduplicationKey:o,beforeInsert:s}=t,a=n??"none",c=async()=>{await s?.(),r()},l=async()=>{await c(),await this.insertJob(e,i)};if(a==="none")return await l(),{kind:"inserted",jobId:i.id};let u=await this.getActiveDeduplicationCandidates(e,i.type,o),f=this.deduplicator.findDuplicate(u,a,o);if(!f)return await l(),{kind:"inserted",jobId:i.id};if(a==="skip")return{kind:"skipped",jobId:f.id};if(a==="coalesce"){if((await e.execute({sql:"UPDATE `job_queue` SET `scheduledFor` = ? WHERE `id` = ? AND `status` = ?",args:[Date.now(),f.id,f.status]})).rowsAffected!==1)throw Error(`Atomic coalesce lost selected job ${f.id}`);return{kind:"coalesced",jobId:f.id}}await c();let p=Date.now();if((await e.execute({sql:"UPDATE `job_queue`\n SET `status` = ?,\n `lastError` = ?,\n `completedAt` = ?,\n `runtimeUpdatedAt` = max(?, coalesce((SELECT max(`runtimeUpdatedAt`) FROM `job_queue`), 0) + 1)\n WHERE `id` = ? AND `status` = ?",args:[Ue.FAILED,"Replaced by newer job",p,p,f.id,Ue.PENDING]})).rowsAffected!==1)throw Error(`Atomic replace lost selected job ${f.id}`);return await this.insertJob(e,i),{kind:"replaced",jobId:i.id,replacedJobId:f.id}}async getActiveDeduplicationCandidates(e,t,r){return(await e.execute(r?{sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ?\n AND json_extract(`metadata`, '$.deduplicationKey') = ?\n AND `status` IN (?, ?)",args:[t,r,Ue.PENDING,Ue.PROCESSING]}:{sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ? AND `status` IN (?, ?)",args:[t,Ue.PENDING,Ue.PROCESSING]})).rows.map((n)=>this.parseDeduplicationCandidate(n))}parseDeduplicationCandidate(e){let{id:t,status:r,createdAt:i,metadata:n}=e;if(typeof t!=="string"||r!==Ue.PENDING&&r!==Ue.PROCESSING||typeof i!=="number"&&typeof i!=="bigint"||typeof n!=="string")throw Error("Invalid active job row returned during atomic enqueue");let o=JSON.parse(n);return{id:t,status:r,createdAt:Number(i),metadata:o}}async insertJob(e,t){if((await e.execute({sql:"INSERT INTO `job_queue` (\n `id`, `type`, `data`, `result`, `source`, `metadata`,\n `status`, `priority`, `retryCount`, `maxRetries`,\n `lastError`, `createdAt`, `scheduledFor`, `startedAt`,\n `completedAt`\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",args:[t.id,t.type,t.data,this.serializeJson(t.result),t.source,JSON.stringify(t.metadata),t.status,t.priority,t.retryCount,t.maxRetries,t.lastError,t.createdAt,t.scheduledFor,t.startedAt,t.completedAt]})).rowsAffected!==1)throw Error(`Atomic enqueue did not insert job ${t.id}`)}serializeJson(e){if(e===void 0||e===null)return null;return JSON.stringify(e)}acquireWriteTransaction(e,t){return this.retryOnConflict("acquire",e,()=>this.transactionClient.transaction("write"),(r)=>this.isSerializationConflict(r),t)}async waitForConflictRetry(e,t,r,i,n){let o=Math.min(wSe*2**(i-1),vSe),s=o/2+Math.random()*(o/2);if(Date.now()+s>=r)throw this.transactionConflictError(e,t,i,n);await new Promise((a)=>setTimeout(a,s))}async retryOnConflict(e,t,r,i,n=Date.now()+this.writeRetryBudgetMs,o=1){try{return await r()}catch(s){if(!i(s))throw s;return await this.waitForConflictRetry(e,t,n,o,s),this.retryOnConflict(e,t,r,i,n,o+1)}}transactionConflictError(e,t,r,i){if(typeof t==="string")return Error(`Failed job queue write "${t}" within ${this.writeRetryBudgetMs}ms after ${r} attempts`,{cause:i});let n=t.strategy??"none",o=t.deduplicationKey?"present":"absent";return Error(`Failed to ${e} atomic enqueue transaction for type "${t.jobData.type}" within ${this.writeRetryBudgetMs}ms after ${r} attempts (strategy: ${n}, key: ${o})`,{cause:i})}write(e,t){return this.retryOnConflict("write",e,t,(r)=>{let i=new Set;for(let n=r;n!==void 0&&!i.has(n);){if(i.add(n),typeof n==="object"&&n!==null&&"code"in n&&/^SQLITE_(?:BUSY|LOCKED)(?:_|$)/u.test(String(n.code)))return!0;n=n instanceof Error?n.cause:void 0}return!1})}isSerializationConflict(e){for(let t=e;t!==void 0;){let r=typeof t==="object"&&t!==null&&"code"in t?String(t.code):"",i=at(t,"");if(/SQLITE_(?:BUSY|LOCKED)/u.test(r)||/SQLITE_(?:BUSY|LOCKED)|database is locked|transaction (?:busy|conflict)/iu.test(i))return!0;t=t instanceof Error?t.cause:void 0}return!1}async startWorkerSession(e,t,r=Date.now(),i=ss){let n=r+i;await this.write("start worker session",async()=>this.db.insert(pt).values({slotId:e,sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:n}).onConflictDoUpdate({target:pt.slotId,set:{sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:n}}))}async heartbeatWorkerSession(e,t,r=Date.now(),i=ss){return(await this.write("heartbeat worker session",async()=>this.db.update(pt).set({heartbeatAt:r,expiresAt:r+i}).where(It(Qe(pt.slotId,e),Qe(pt.sessionId,t))).returning({slotId:pt.slotId}))).length===1}async endWorkerSession(e,t){return(await this.write("end worker session",async()=>this.db.delete(pt).where(It(Qe(pt.slotId,e),Qe(pt.sessionId,t))).returning({slotId:pt.slotId}))).length===1}async complete(e,t,r){let i=Date.now(),o=(await this.write("complete",async()=>this.db.update(ne).set({status:Ue.COMPLETED,result:t,lastError:null,completedAt:i,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i)}).where(this.attemptWriteGuard(e,r)).returning({id:ne.id}))).length===1;if(o)this.logger.debug("Job completed",{jobId:e,hasResult:t!==void 0});return o}async update(e,t,r){let n=(await this.write("update",async()=>this.db.update(ne).set({data:JSON.stringify(t)}).where(this.attemptWriteGuard(e,r)).returning({id:ne.id}))).length===1;if(n)this.logger.debug("Job data updated",{jobId:e});return n}async recordAttemptProgress(e,t,r,i=Date.now()){return(await this.write("record progress",async()=>this.db.update(ne).set({attemptHeartbeatAt:i,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i),progress:r}).where(this.attemptWriteGuard(e,t)).returning({id:ne.id}))).length===1}async renewAttemptLease(e,t,r,i){return(await this.write("renew attempt lease",async()=>this.db.update(ne).set({attemptHeartbeatAt:r,leaseExpiresAt:r+i}).where(this.attemptWriteGuard(e,t)).returning({id:ne.id}))).length===1}async fail(e,t,r,i=Date.now()){let o=(await this.db.select({retryCount:ne.retryCount,maxRetries:ne.maxRetries,type:ne.type,scheduledFor:ne.scheduledFor,startedAt:ne.startedAt,runtimeUpdatedAt:ne.runtimeUpdatedAt}).from(ne).where(this.attemptWriteGuard(e,r)).limit(1))[0];if(!o)return!1;let s=o.retryCount<o.maxRetries,a=s?o.retryCount+1:o.retryCount,c=Math.min(1000*2**o.retryCount,60000),l=s?i+c:o.scheduledFor;if((await this.write("fail",async()=>this.db.update(ne).set({status:s?Ue.PENDING:Ue.FAILED,retryCount:a,lastError:t.message,scheduledFor:l,completedAt:s?null:i,runtimeUpdatedAt:s?o.runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i),startedAt:s?null:o.startedAt,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(It(this.attemptWriteGuard(e,r),Qe(ne.retryCount,o.retryCount))).returning({id:ne.id}))).length!==1)return!1;if(s)this.logger.debug("Job scheduled for retry",{jobId:e,retryCount:a,backoffMs:c,scheduledFor:new Date(l).toISOString()});else this.logger.error("Job failed after max retries",{jobId:e,type:o.type,retryCount:o.retryCount,error:t.message});return!0}async retireUnownedActiveJob(e){let t=e.reason.trim();if(t.length===0)throw Error("Retired job reason must not be empty");let i=(await this.write("retire unowned job",async()=>this.db.update(ne).set({status:Ue.FAILED,lastError:t,completedAt:e.now,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(e.now)}).where(It(Qe(ne.id,e.jobId),Qe(ne.type,e.expectedType),xi(Qe(ne.status,Ue.PENDING),Qe(ne.status,Ue.PROCESSING)),En(ne.attemptId),En(ne.workerSlotId),En(ne.workerSessionId),En(ne.leaseExpiresAt),En(ne.attemptHeartbeatAt),En(ne.progress),En(ne.result))).returning()))[0]??null;if(i)this.logger.warn("Retired unowned legacy job",{jobId:i.id,type:i.type,reason:t});return i}async getStatus(e){return(await this.db.select().from(ne).where(Qe(ne.id,e)).limit(1))[0]??null}async getJobsByRootJobId(e){return this.db.select().from(ne).where(U`json_extract(${ne.metadata}, '$.rootJobId') = ${e}`).orderBy(ro(ne.createdAt),ro(ne.id))}async getStatusByEntityId(e){return(await this.db.select().from(ne).where(U`json_extract(${ne.data}, '$.id') = ${e}`).orderBy(Na(ne.createdAt)).limit(1))[0]??null}async getStats(){let e=await this.db.select({status:ne.status,count:U`count(*)`}).from(ne).groupBy(ne.status),t={pending:0,processing:0,failed:0,completed:0,total:0};for(let r of e){let i=Number(r.count);t[r.status]=i,t.total+=i}return t}async getDiagnostics(e=Date.now()){let[t,r,i]=await Promise.all([this.db.select({type:ne.type,status:ne.status,count:U`count(*)`}).from(ne).groupBy(ne.type,ne.status),this.db.select({oldestPendingAt:U`min(case when ${ne.status} = ${Ue.PENDING} then ${ne.createdAt} end)`,duePending:U`coalesce(sum(case when ${ne.status} = ${Ue.PENDING} and ${ne.scheduledFor} <= ${e} then 1 else 0 end), 0)`,oldestDuePendingAt:U`min(case when ${ne.status} = ${Ue.PENDING} and ${ne.scheduledFor} <= ${e} then ${ne.scheduledFor} end)`,latestClaimAt:U`max(${ne.startedAt})`,oldestProcessingAt:U`min(case when ${ne.status} = ${Ue.PROCESSING} then ${ne.startedAt} end)`,staleLeaseCount:U`coalesce(sum(case when ${ne.status} = ${Ue.PROCESSING} and ${ne.leaseExpiresAt} is not null and ${ne.leaseExpiresAt} <= ${e} then 1 else 0 end), 0)`}).from(ne),this.db.select({total:U`count(*)`,active:U`coalesce(sum(case when ${pt.expiresAt} > ${e} then 1 else 0 end), 0)`,stale:U`coalesce(sum(case when ${pt.expiresAt} <= ${e} then 1 else 0 end), 0)`,latestHeartbeatAt:U`max(${pt.heartbeatAt})`}).from(pt)]),n={pending:0,processing:0,completed:0,failed:0},o=t.map((l)=>{let u=Number(l.count);return n[l.status]+=u,{type:l.type,status:l.status,count:u}}),s=r[0],a=i[0],c=(l)=>l===null||l===void 0?null:Math.max(0,e-Number(l));return{totals:n,byType:o,oldestPendingAgeMs:c(s?.oldestPendingAt),duePending:Number(s?.duePending??0),oldestDuePendingAgeMs:c(s?.oldestDuePendingAt),latestClaimAgeMs:c(s?.latestClaimAt),oldestProcessingAgeMs:c(s?.oldestProcessingAt),staleLeaseCount:Number(s?.staleLeaseCount??0),workerSessions:{total:Number(a?.total??0),active:Number(a?.active??0),stale:Number(a?.stale??0),latestHeartbeatAgeMs:c(a?.latestHeartbeatAt)}}}async getRuntimeUpdates(e,t){let r=_Se.parse(t);if(r===0)return[];return(await this.db.select().from(ne).where(U`(${ne.runtimeUpdatedAt}, ${ne.id}) > (${e.updatedAt}, ${e.jobId})`).orderBy(ro(ne.runtimeUpdatedAt),ro(ne.id)).limit(r)).map((n)=>({job:n,cursor:{updatedAt:n.runtimeUpdatedAt??0,jobId:n.id}}))}async cleanup(e){let t=Date.now()-e;return(await this.write("cleanup",async()=>this.db.delete(ne).where(It(xi(Qe(ne.status,Ue.COMPLETED),Qe(ne.status,Ue.FAILED)),tu(ne.completedAt,t))))).rowsAffected}async getActiveJobs(e){let t=xi(Qe(ne.status,Ue.PENDING),Qe(ne.status,Ue.PROCESSING)),r=e&&e.length>0?It(t,Ss(ne.type,e)):t;return this.db.select().from(ne).where(r).orderBy(Na(ne.createdAt))}async getRecentJobs(e,t=20){let r=e&&e.length>0?Ss(ne.type,e):void 0;return this.db.select().from(ne).where(r).orderBy(Na(ne.createdAt)).limit(t)}async getFailedJobs(e){let t=Qe(ne.status,Ue.FAILED),r=e&&e.length>0?It(t,Ss(ne.type,e)):t;return this.db.select().from(ne).where(r).orderBy(Na(ne.createdAt))}async claimNextReady(e){let{now:t,attemptId:r,workerSlotId:i,workerSessionId:n,leaseDurationMs:o,executableTypes:s,exclusiveTypes:a=[]}=e,c=this.db.select({slotId:pt.slotId}).from(pt).where(It(Qe(pt.slotId,i),Qe(pt.sessionId,n),cp(pt.expiresAt,t))),l=this.db.select({slotId:pt.slotId}).from(pt).where(It(Qe(pt.slotId,ne.workerSlotId),Qe(pt.sessionId,ne.workerSessionId))),u=It(Qe(ne.status,Ue.PROCESSING),xi(En(ne.attemptId),lp(l),tu(ne.leaseExpiresAt,t))),f=MK(ne,"running"),p=this.db.select({id:f.id}).from(f).where(It(Qe(f.type,ne.type),Qe(f.status,Ue.PROCESSING),cp(f.leaseExpiresAt,t),U`${f.id} <> ${ne.id}`)),m=a.length===0?void 0:xi(jb(ne.type,[...a]),lp(p)),y=U`${ne.status} = ${Ue.PROCESSING} AND ${ne.retryCount} + 1 > ${ne.maxRetries}`,g=this.db.select({id:ne.id}).from(ne).where(It(Ss(ne.type,s),m,xi(It(Qe(ne.status,Ue.PENDING),tu(ne.scheduledFor,t)),u))).orderBy(ro(ne.priority),ro(ne.createdAt)).limit(1),_=(await this.write("claim",async()=>this.db.update(ne).set({status:U`CASE WHEN ${y} THEN ${Ue.FAILED} ELSE ${Ue.PROCESSING} END`,retryCount:U`CASE WHEN ${ne.status} = ${Ue.PROCESSING} THEN ${ne.retryCount} + 1 ELSE ${ne.retryCount} END`,lastError:U`CASE WHEN ${ne.status} = ${Ue.PROCESSING} THEN 'Attempt lease expired' ELSE ${ne.lastError} END`,startedAt:U`CASE WHEN ${y} THEN ${ne.startedAt} ELSE ${t} END`,completedAt:U`CASE WHEN ${y} THEN ${t} ELSE NULL END`,attemptId:U`CASE WHEN ${y} THEN ${ne.attemptId} ELSE ${r} END`,workerSlotId:U`CASE WHEN ${y} THEN ${ne.workerSlotId} ELSE ${i} END`,workerSessionId:U`CASE WHEN ${y} THEN ${ne.workerSessionId} ELSE ${n} END`,leaseExpiresAt:U`CASE WHEN ${y} THEN ${ne.leaseExpiresAt} ELSE ${t+o} END`,attemptHeartbeatAt:U`CASE WHEN ${y} THEN ${ne.attemptHeartbeatAt} ELSE ${t} END`,runtimeUpdatedAt:U`CASE WHEN ${y} THEN ${this.nextRuntimeUpdatedAt(t)} ELSE ${ne.runtimeUpdatedAt} END`}).where(It(Ss(ne.id,g),Ub(c))).returning()))[0];if(!_)return null;if(_.status===Ue.FAILED)return _;return this.logger.debug("Job claimed",{jobId:_.id,attemptId:_.attemptId,workerSlotId:i,workerSessionId:n}),_}nextRuntimeUpdatedAt(e){return U`max(${e}, coalesce((select max(${ne.runtimeUpdatedAt}) from ${ne}), 0) + 1)`}attemptWriteGuard(e,t){return t?It(Qe(ne.id,e),Qe(ne.status,Ue.PROCESSING),Qe(ne.attemptId,t)):It(Qe(ne.id,e),En(ne.attemptId),xi(Qe(ne.status,Ue.PENDING),Qe(ne.status,Ue.PROCESSING)))}}var xSe=2000,wSe=5,vSe=40,_Se,kSe;var oJ=S(()=>{nR();eS();iR();Ae();as();Pf();iJ();_Se=d.number().int().min(0).max(1000),kSe=new sR});import{AsyncLocalStorage as ESe}from"async_hooks";class wp{storage=new ESe;static createFresh(){return new wp}constructor(){}current(){return this.storage.getStore()}run(e,t,r){if(t.length===0)throw Error("Operation ID must not be empty");let i=ko.parse(e),n=ISe(i);return this.storage.run(Object.freeze({provenance:n,operationId:t}),r)}}function ISe(e){if(Object.freeze(e.projectionLineage),e.sourceEntity)Object.freeze(e.sourceEntity);return Object.freeze(e)}var lR=S(()=>{ti()});class vp{client;logger;handlerRegistry;repository;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;inFlightEnqueues=0;databaseUrl;operationContext;projectionAdmission;directWorkerSlotId=`direct:${Gi()}`;directWorkerSessionId=Gi();directLeaseDurationMs;directSessionStart=null;close(){this.closeRequested=!0,this.closeClientWhenReady()}static createFresh(e,t,r){return new vp(e,t??on.getInstance(),r)}constructor(e,t,r){let{db:i,client:n,url:o}=rJ(e);this.client=n,this.databaseUrl=o,this.logger=t.child("JobQueueService"),this.operationContext=r?.operationContext??wp.createFresh(),this.projectionAdmission=r?.projectionAdmission,this.handlerRegistry=new oR(this.logger,r?.handlerRegistrationMode??"combined"),this.repository=new cR(i,n,o,this.logger),this.directLeaseDurationMs=e.claimTimeoutMs??300000}initialize(){if(this.closeRequested)return Promise.resolve();return this.walInitialization??=this.initializeWALMode(),this.walInitialization}async initializeWALMode(){try{await sS(this.client,this.databaseUrl)}catch(e){this.logger.warn("Failed to enable WAL mode (non-fatal)",e)}finally{this.walInitializationSettled=!0,this.closeClientWhenReady()}}closeClientWhenReady(){if(!this.closeRequested||this.inFlightEnqueues>0||this.walInitialization!==null&&!this.walInitializationSettled)return;this.closeClient()}closeClient(){if(this.clientClosed)return;this.clientClosed=!0,this.client.close()}registerHandler(e,t,r){this.handlerRegistry.registerHandler(e,t,r)}unregisterHandler(e){this.handlerRegistry.unregisterHandler(e)}unregisterPluginHandlers(e){this.handlerRegistry.unregisterPluginHandlers(e)}getRegisteredTypes(){return this.handlerRegistry.getRegisteredTypes()}getHandler(e){return this.handlerRegistry.getHandler(e)}getValidator(e){return this.handlerRegistry.getValidator(e)}finalizeHandlerRegistrations(){return this.handlerRegistry.finalizeRegistrations()}getExecutionRegistrations(){return this.handlerRegistry.getExecutionRegistrations()}async enqueue(e){if(this.closeRequested)throw Error("Cannot enqueue a job after the queue service is closed");this.inFlightEnqueues++;try{return await this.enqueueValidated(e)}finally{this.inFlightEnqueues--,this.closeClientWhenReady()}}async enqueueValidated(e){let{type:t,data:r,options:i}=e,n=this.handlerRegistry.getValidator(t);if(!n)throw Error(`No job type declared: ${t}`);let o=n.validateAndParse(r);if(o===null)throw Error(`Invalid job data for type: ${t}`);let s=Date.now(),a=Gi(),c=i?.rootJobId??this.operationContext.current()?.provenance.rootJobId??a,l=this.createJobProvenance(a,c,i),u=i?.metadata??{operationType:"data_processing"},{provenance:f,...p}=u,m={id:a,type:t,data:JSON.stringify(o),status:Ue.PENDING,priority:i?.priority??0,maxRetries:i?.maxRetries??3,retryCount:0,source:i?.source??null,metadata:{...p,...i?.deduplicationKey&&{deduplicationKey:i.deduplicationKey},rootJobId:c,provenance:l},createdAt:s,scheduledFor:i?.delayMs?s+i.delayMs:s,result:null,lastError:null,startedAt:null,completedAt:null},y,g=()=>{y?.rollback(),y=void 0};try{let b=await this.repository.enqueueAtomic({jobData:m,strategy:i?.deduplication,deduplicationKey:i?.deduplicationKey,beforeInsert:async()=>{y=await this.projectionAdmission?.reserveJobAdmission(l)},onInsertRollback:g});if(y?.commit(),y=void 0,b.kind==="skipped")this.logger.debug("Skipping duplicate job (already pending)",{type:t,existingJobId:b.jobId});else if(b.kind==="coalesced")this.logger.debug("Coalescing with existing job",{type:t,existingJobId:b.jobId});else{if(b.kind==="replaced")this.logger.debug("Replacing duplicate job",{type:t,oldJobId:b.replacedJobId});this.logger.debug("Job enqueued",{id:b.jobId,type:t,priority:m.priority,rootJobId:m.metadata.rootJobId})}return b.jobId}catch(b){throw g(),this.logger.error("Failed to enqueue job",{type:t,error:at(b)}),b}}createJobProvenance(e,t,r){let i=this.operationContext.current(),n=r?.metadata.provenance??i?.provenance,o=n?.rootJobId===t?n:void 0,s=i?.provenance.rootJobId===t?i.operationId:void 0,a=r?.projection,c=a?[...o?.projectionLineage??[],a.id]:[...o?.projectionLineage??[]],l=a?.id??o?.projectionId;return ko.parse({rootJobId:t,causationId:s??o?.causationId??e,...l?{projectionId:l}:{},projectionLineage:c,...a?.sourceEntity?{sourceEntity:a.sourceEntity}:o?.sourceEntity?{sourceEntity:o.sourceEntity}:{},derivationDepth:c.length})}async dequeue(e){let t=this.handlerRegistry.getRegisteredTypes();if(t.length===0)return null;let{onTerminalReclaim:r,...i}=e??await this.getDirectClaimOptions(),n=Date.now(),o=await this.repository.claimNextReady({...i,now:n,attemptId:Gi(),executableTypes:t,exclusiveTypes:this.handlerRegistry.getExclusiveTypes()});if(!o)return null;if(o.status===Ue.FAILED)return this.logger.warn("Expired attempt failed terminally on reclaim",{id:o.id,type:o.type,retryCount:o.retryCount}),await r?.(o),null;return this.logger.debug("Job dequeued",{id:o.id,type:o.type,priority:o.priority,retryCount:o.retryCount,attemptId:o.attemptId,workerSlotId:o.workerSlotId,workerSessionId:o.workerSessionId}),o}async startWorkerSession(e,t,r=ss){await this.repository.startWorkerSession(e,t,Date.now(),r)}heartbeatWorkerSession(e,t,r=ss){return this.repository.heartbeatWorkerSession(e,t,Date.now(),r)}endWorkerSession(e,t){return this.repository.endWorkerSession(e,t)}renewAttemptLease(e,t,r){return this.repository.renewAttemptLease(e,t,Date.now(),r)}recordAttemptProgress(e,t,r){return this.repository.recordAttemptProgress(e,t,r)}complete(e,t,r){return this.repository.complete(e,t,r)}update(e,t,r){return this.repository.update(e,t,r)}fail(e,t,r){return this.repository.fail(e,t,r)}retireUnownedActiveJob(e){return this.repository.retireUnownedActiveJob(e)}async getDirectClaimOptions(){return this.directSessionStart??=this.repository.startWorkerSession(this.directWorkerSlotId,this.directWorkerSessionId,Date.now(),this.directLeaseDurationMs),await this.directSessionStart,{workerSlotId:this.directWorkerSlotId,workerSessionId:this.directWorkerSessionId,leaseDurationMs:this.directLeaseDurationMs}}async getStatus(e){return this.repository.getStatus(e)}async getJobsByRootJobId(e){return this.repository.getJobsByRootJobId(e)}async getStatusByEntityId(e){return this.repository.getStatusByEntityId(e)}async getStats(){return this.repository.getStats()}getDiagnostics(e){return this.repository.getDiagnostics(e)}async waitForIdle(e={}){let t=e.quietMs??250,r=e.pollIntervalMs??25,i=Date.now()+(e.timeoutMs??30000),n=async(o)=>{e.signal?.throwIfAborted();let{totals:s}=await this.getDiagnostics(),c=s.pending===0&&s.processing===0?o??Date.now():null;if(c!==null&&Date.now()-c>=t)return;if(Date.now()>=i)throw Error(`Timed out waiting for the job queue to settle: ${s.pending} pending, ${s.processing} processing`);return await Bun.sleep(r),n(c)};return n(null)}getRuntimeUpdates(e,t=1000){return this.repository.getRuntimeUpdates(e,t)}async cleanup(e){let t=await this.repository.cleanup(e);if(t>0)this.logger.info("Cleaned up old jobs",{deletedCount:t,olderThanMs:e});return t}async getActiveJobs(e){return this.repository.getActiveJobs(e)}async getRecentJobs(e,t){return this.repository.getRecentJobs(e,t)}async getFailedJobs(e){return this.repository.getFailedJobs(e)}}var sJ=S(()=>{Rf();m$();Pf();as();rR();nJ();oJ();ti();lR()});var uR=()=>{};var aJ=S(()=>{Rf();as();Pf();as();uR();lR()});var cJ=S(()=>{as();uR()});var iWe;var lJ=S(()=>{ti();Ae();Of();iWe=d.preprocess((e)=>{if(typeof e!=="string")return e;return JSON.parse(e)},d.record(d.string(),d.unknown()))});var aWe;var uJ=S(()=>{Ae();aWe=d.record(d.string(),d.unknown())});var dJ=S(()=>{ti();Rf()});var fJ=S(()=>{sJ();aJ();cJ();lJ();uJ();Pf();as();Of();dJ()});var dR={};Ht(dR,{LEGACY_PROJECTION_JOB_TYPES:()=>mJ,LEGACY_PROJECTION_RETIREMENT_REASON:()=>gJ,legacyProjectionJobTypeSchema:()=>hJ,retireLegacyProjectionJob:()=>DSe});import{existsSync as PSe}from"fs";import{resolve as zSe}from"path";function pJ(e){return{id:e.id,type:e.type,status:e.status,retryCount:e.retryCount,maxRetries:e.maxRetries,createdAt:e.createdAt,startedAt:e.startedAt,completedAt:e.completedAt}}function NSe(e,t){if(e.type!==t)throw Error(`Job ${e.id} has type ${e.type}; expected ${t}`);if(e.status!=="pending"&&e.status!=="processing")throw Error(`Job ${e.id} is already terminal (${e.status})`);if(e.attemptId!==null||e.workerSlotId!==null||e.workerSessionId!==null||e.leaseExpiresAt!==null||e.attemptHeartbeatAt!==null)throw Error(`Job ${e.id} still has attempt ownership`);if(e.progress!==null||e.result!=null)throw Error(`Job ${e.id} contains partial progress or a result`)}async function DSe(e){let t=zSe(e.databasePath);if(!PSe(t))throw Error(`Job database does not exist: ${t}`);let r=hJ.parse(e.jobType),i=vp.createFresh({url:`file:${t}`});try{let n=await i.getStatus(e.jobId);if(!n)throw Error(`Job not found: ${e.jobId}`);if(NSe(n,r),e.dryRun){if(e.confirmation!==void 0)throw Error("Dry-run recovery must not include confirmation");return{databasePath:t,job:pJ(n),retired:!1}}let o=`retire:${n.id}`;if(e.confirmation!==o)throw Error(`Refusing to retire ${n.id}; expected --confirm ${o}`);let s=await i.retireUnownedActiveJob({jobId:n.id,expectedType:r,reason:gJ,now:e.now?.()??Date.now()});if(!s)throw Error(`Job ${n.id} changed or acquired ownership before retirement`);return{databasePath:t,job:pJ(s),retired:!0}}finally{i.close()}}var mJ,hJ,gJ="Retired legacy projection job superseded by scheduler-owned projections";var fR=S(()=>{fJ();Ae();mJ=["conversation-memory:project","skill:project","swot:derive","topic:project"],hJ=d.enum(mJ)});function Yt(e,t,r,i,n){return bJ.parse({id:e,operation:t,count:r,targetProbeCount:i,settleMs:n})}function mR(e){return kp.parse(structuredClone(USe[e]))}function Ep(e){let t=`stress:${e.handle}`;if(e.confirmation!==t)throw Error(`Directory-sync stress requires --confirm ${t}`);let r=/(^|[-_.])smoke($|[-_.])/i;if(!r.test(e.handle)||!r.test(e.domain)||!r.test(e.contentRepo))throw Error("Directory-sync stress is smoke-only; handle, domain, and content repository must all identify smoke")}async function cS(e,t={}){let r=t.fetchImpl??fetch,i=t.now??(()=>new Date),n=t.timeoutMs??20000,o=i(),s=new AbortController,a=setTimeout(()=>s.abort(),n);try{let c=await r(e,{method:"GET",signal:s.signal});return await c.arrayBuffer(),pR.parse({timestamp:o.toISOString(),endpoint:new URL(e).pathname,status:c.status,durationMs:Math.max(0,i().getTime()-o.getTime()),ok:c.ok})}catch(c){return pR.parse({timestamp:o.toISOString(),endpoint:new URL(e).pathname,status:0,durationMs:Math.max(0,i().getTime()-o.getTime()),ok:!1,error:qSe(c)})}finally{clearTimeout(a)}}async function hR(e,t){let r=kp.parse(e),i=[],n,o=await t.prepare(r),s,a;try{try{await t.startMonitoring()}catch(c){n=`monitor: ${aS(c)}`}if(!n)for(let c of r.phases)try{let l=SJ.parse(await t.executePhase(c,o));if(i.push(l),!l.success){n=`${c.id}: ${l.error??"phase failed"}`;break}}catch(l){let u=aS(l);i.push({id:c.id,operation:c.operation,count:c.count,success:!1,error:u}),n=`${c.id}: ${u}`;break}}finally{try{if(s=xJ.parse(await t.cleanup(o)),!s.success&&!n)n=s.error??"cleanup failed"}catch(c){let l=aS(c);s={success:!1,probesRemaining:0,error:l},n??=`cleanup: ${l}`}try{a=wJ.parse(await t.stopMonitoring())}catch(c){let l=aS(c);a={health:[],runtime:[]},n??=`monitor: ${l}`}}return n??=_J(a,r.maximumExternalAiCalls??0),vJ.parse({profile:r.profile,success:n===void 0&&i.length===r.phases.length&&s.success,baseline:o,phases:i,cleanup:s,metrics:a,...n?{failure:n}:{}})}function _J(e,t=0){let r=e.health.find((o)=>!o.ok);if(r)return`health: ${r.endpoint} unavailable`;let i=e.externalAiCalls??0;if(i>t)return t===0?`external AI: observed ${i} call(s)`:`external AI: observed ${i} call(s), cap ${t}`;if(e.container?.oomKilled)return"container: OOM killed";let n=e.container?.restartCount??0;if(n>0)return`container: restarted ${n} time(s)`;if(e.container&&e.container.status!=="running")return`container: ${e.container.status}`;return}function qSe(e){if(e instanceof Error)return`${e.name}: ${e.message}`;return String(e)}function aS(e){return at(e)}var _p,yJ,bJ,kp,LSe,pR,BSe,SJ,xJ,jSe,wJ,vJ,USe;var lS=S(()=>{Ae();_p=d.enum(["regression","load","stress"]),yJ=d.enum(["add","update","rename","delete"]),bJ=d.object({id:d.string().min(1),operation:yJ,count:d.number().int().positive().max(700),targetProbeCount:d.number().int().min(0).max(700),settleMs:d.number().int().nonnegative().max(300000)}),kp=d.object({profile:_p,maximumProbeCount:d.number().int().positive().max(700),maximumExternalAiCalls:d.number().int().nonnegative().max(1e4).optional(),phases:d.array(bJ).min(1)}),LSe=d.object({entities:d.number().int().nonnegative(),notes:d.number().int().nonnegative(),version:d.string().min(1)}),pR=d.object({timestamp:d.iso.datetime(),endpoint:d.string().startsWith("/"),status:d.number().int().nonnegative(),durationMs:d.number().nonnegative(),ok:d.boolean(),error:d.string().optional()}),BSe=d.object({timestamp:d.iso.datetime(),cpuPercent:d.number().nonnegative(),memoryPercent:d.number().nonnegative(),pids:d.number().int().nonnegative()}),SJ=d.object({id:d.string().min(1),operation:yJ,count:d.number().int().positive(),success:d.boolean(),commitLatencyMs:d.number().nonnegative().optional(),persistenceLatencyMs:d.number().nonnegative().optional(),error:d.string().optional()}),xJ=d.object({success:d.boolean(),probesRemaining:d.number().int().nonnegative(),finalEntities:d.number().int().nonnegative().optional(),finalNotes:d.number().int().nonnegative().optional(),contentTreeRestored:d.boolean().optional(),error:d.string().optional()}),jSe=d.object({status:d.string(),restartCount:d.number().int().nonnegative(),oomKilled:d.boolean()}),wJ=d.object({health:d.array(pR),runtime:d.array(BSe),externalAiCalls:d.number().int().nonnegative().optional(),container:jSe.optional()}),vJ=d.object({profile:_p,success:d.boolean(),baseline:LSe,phases:d.array(SJ),cleanup:xJ,metrics:wJ,failure:d.string().optional()}),USe={regression:{profile:"regression",maximumProbeCount:20,phases:[Yt("add20","add",20,20,0),Yt("update20","update",20,20,30000),Yt("delete20","delete",20,0,150000)]},load:{profile:"load",maximumProbeCount:350,phases:[Yt("add50","add",50,50,0),Yt("add150","add",100,150,0),Yt("add350","add",200,350,0),Yt("update350a","update",350,350,45000),Yt("rename100","rename",100,350,45000),Yt("update350b","update",350,350,45000),Yt("delete350","delete",350,0,150000)]},stress:{profile:"stress",maximumProbeCount:700,phases:[Yt("add50","add",50,50,0),Yt("add150","add",100,150,0),Yt("add350","add",200,350,0),Yt("add700","add",350,700,0),Yt("update700a","update",700,700,45000),Yt("rename200","rename",200,700,45000),Yt("update700b","update",700,700,45000),Yt("delete700","delete",700,0,150000)]}}});import{spawn as ZSe}from"child_process";async function kJ(e,t,r,i){let n=await e(t,r,i);if(n.exitCode!==0)throw vi(t,r,n);return n}function vi(e,t,r){let i=r.stderr.trim()||r.stdout.trim();return Error(`${e} ${t.join(" ")} exited with ${r.exitCode}${i?`: ${i}`:""}`)}var co=async(e,t,r={})=>new Promise((i,n)=>{let o=ZSe(e,[...t],{cwd:r.cwd,env:r.env?{...process.env,...r.env}:process.env,stdio:["pipe","pipe","pipe"]}),s="",a="";o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",(c)=>{s+=c}),o.stderr.on("data",(c)=>{a+=c}),o.on("error",n),o.on("close",(c)=>{i({exitCode:c??1,stdout:s,stderr:a})}),o.stdin.end(r.stdin)});var Ip=()=>{};class cu{#e;#t;dir;constructor(e,t,r){this.#e=e,this.dir=t,this.#t=r}static async clone(e,t,r,i){let n=new cu(e,r,i);return await kJ(e,"git",["-c","credential.helper=","-c",`credential.helper=${EJ}`,"clone","--branch","main","--single-branch",`https://github.com/${t}.git`,r],{env:n.environment()}),await n.run(["config","--local","credential.helper",EJ]),await n.run(["reset","--hard","origin/main"]),n}async run(e,t=!0){let r=await this.#e("git",e,{cwd:this.dir,env:this.environment()});if(t&&r.exitCode!==0)throw vi("git",e,r);return r}async output(e){return(await this.run(e)).stdout.trim()}async sync(e=!1){if(await this.run(["fetch","origin","main"]),e)await this.run(["reset","--hard","origin/main"]);else await this.run(["pull","--rebase","origin","main"])}async commitAll(e){await this.run(["add","-A"]),await this.run(["-c","user.name=brains-ops","-c","user.email=ops@rizom.ai","commit","-m",e])}async pushMainWithRebase(){for(let e=1;e<=5;e+=1){if((await this.run(["push","origin","main"],!1)).exitCode===0)return;await this.run(["pull","--rebase","origin","main"])}throw Error("Unable to push content main after five rebase attempts")}async pruneStressBackupBranches(){let t=(await this.run(["ls-remote","--heads","origin","refs/heads/ops/directory-sync-stress-backup-*"])).stdout.split(/\r?\n/).map((r)=>r.match(/\trefs\/heads\/(ops\/directory-sync-stress-backup-[^\s]+)$/)?.[1]).filter((r)=>r!==void 0).sort();for(let r of t)await this.run(["push","origin","--delete",r]);return t}environment(){return{GH_TOKEN:this.#t,GITHUB_TOKEN:this.#t}}}var EJ='!f() { test "$1" = get && echo username=x-access-token && echo "password=$GH_TOKEN"; }; f';var IJ=S(()=>{Ip()});function Tp(e){return e.entityCounts.find((t)=>t.entityType==="note")?.count??0}class gR{#e;#t=[];#r=[];#n=new Set(["/health/ready"]);#i=!0;#o;#a;#s="";#c=0;#l;constructor(e){this.#e=e}get startedAt(){return this.#s}get error(){return this.#a}get healthSamples(){return this.#t}get runtimeSamples(){return this.#r}gateHealthSamples(){return this.#t.slice(this.#c,this.#l??this.#t.length)}markGateEnd(){this.#l=this.#t.length}async discoverEndpoints(){for(let e of["/health/live","/health/operate"])if((await cS(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:5000})).status!==404)this.#n.add(e)}start(){this.#i=!1,this.#a=void 0,this.#c=this.#t.length,this.#l=void 0,this.#s=this.#e.now().toISOString(),this.#o=Promise.all([this.#f(),this.#m()]).then(()=>{return}).catch((e)=>{this.#a=e,this.#i=!0})}async stop(){this.#i=!0,await this.#o}async waitForHealthSnapshot(e){return this.waitForEntityBaseline(void 0,void 0,e)}async waitForEntityBaseline(e,t,r){let i=this.#e.now().getTime();while(this.#e.now().getTime()-i<r){let n=await this.fetchHealthPayload();if(this.#d(n,e,t))return n;await this.#e.sleep(5000)}return}async waitForStableEntityBaseline(e,t,r){let i=this.#e.now().getTime(),n=0;while(this.#e.now().getTime()-i<r){let o=await this.fetchHealthPayload();if(this.#d(o,e,t)){if(n+=1,n===2)return o}else n=0;await this.#e.sleep(5000)}return}async fetchHealthPayload(){let e=this.#e.now(),t=new AbortController,r=setTimeout(()=>t.abort(),20000);try{let i=await this.#e.fetchImpl(`https://${this.#e.domain}/health/operate`,{signal:t.signal}),n=await i.text();if(this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:i.status,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:i.ok}),!i.ok)return;return MSe.parse(JSON.parse(n)).app}catch(i){this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:0,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:!1,error:i instanceof Error?`${i.name}: ${i.message}`:String(i)});return}finally{clearTimeout(r)}}#d(e,t,r){return e!==void 0&&(t===void 0||Tp(e)===t)&&(r===void 0||e.entities===r)}async#f(){while(!this.#i){for(let e of this.#n)this.#t.push(await cS(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:20000}));await this.#e.sleep(4000)}}async#m(){while(!this.#i){let e=await this.#e.sampleRuntime();if(e)this.#r.push(e);await this.#e.sleep(1000)}}}var MSe;var TJ=S(()=>{Ae();lS();MSe=d.object({status:d.literal("ready"),operationalStatus:d.literal("operational"),app:d.object({version:d.string(),entities:d.number().int().nonnegative(),entityCounts:d.array(d.object({entityType:d.string(),count:d.number().int().nonnegative()})).default([])})})});var uS={};Ht(uS,{applyDirectorySyncStressPhase:()=>zJ,cleanupDirectorySyncStress:()=>RJ,listProbeFiles:()=>ja,parseStressRuntimeSample:()=>NJ,removeProbeFiles:()=>_R,runDeployedDirectorySyncStress:()=>$J,runStressCommand:()=>co,verifyDirectorySyncStressAccess:()=>CJ});import{chmod as FSe,mkdir as bR,mkdtemp as SR,readFile as HSe,readdir as KSe,rename as JSe,rm as $p,writeFile as Kn}from"fs/promises";import{tmpdir as xR}from"os";import{join as St,resolve as wR}from"path";async function $J(e){let t=e.now??(()=>new Date),r=t().toISOString(),i=kR(r),n=wR(e.artifactsDir??St(e.rootDir,".brains-ops","stress",i));await bR(n,{recursive:!0});let{pilot:o,user:s}=await vR(e.rootDir,e.handle);Ep({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation});let a=_p.parse(e.profile),c=e.plan?kp.parse(e.plan):mR(a);if(c.profile!==a)throw Error(`Directory-sync stress plan profile ${c.profile} does not match requested profile ${a}`);if((c.maximumExternalAiCalls??0)===0)PJ(s);let l=VSe.parse(e.env??process.env),u=new OJ({runId:i,artifactsDir:n,user:s,githubOrg:o.githubOrg,serverLabel:`${o.contentRepoPrefix}${s.handle}`,environment:l,fetchImpl:e.fetchImpl??fetch,commandRunner:e.commandRunner??co,logger:e.logger??console.info,now:t,sleep:e.sleep??Bun.sleep}),f;try{f=await hR(c,u)}finally{await u.dispose()}let p={runId:i,artifactsDir:n,target:{handle:s.handle,domain:s.domain,contentRepo:`${o.githubOrg}/${s.contentRepo}`},startedAt:r,completedAt:t().toISOString(),report:f};return await XSe(p),p}async function CJ(e){let r=(e.now??(()=>new Date))().toISOString(),i=kR(r),n=wR(e.artifactsDir??St(e.rootDir,".brains-ops","stress",`access-check-${i}`));await bR(n,{recursive:!0});let{pilot:o,user:s}=await vR(e.rootDir,e.handle);Ep({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation}),PJ(s);let a=(e.env??process.env).CONTENT_REPO_ADMIN_TOKEN;if(!a)throw Error("Missing CONTENT_REPO_ADMIN_TOKEN");let c=await SR(St(xR(),"brains-ops-directory-sync-access-check-"));try{let l=await cu.clone(e.commandRunner??co,`${o.githubOrg}/${s.contentRepo}`,St(c,"content"),a),u=await l.output(["rev-parse","HEAD"]);await l.run(["push","--dry-run","origin",`HEAD:refs/heads/ops/directory-sync-stress-access-check-${i}`]);let f={success:!0,artifactsDir:n,checkedAt:r,remoteHead:u,target:{handle:s.handle,domain:s.domain,contentRepo:`${o.githubOrg}/${s.contentRepo}`}};return await Kn(St(n,"access-check.json"),`${JSON.stringify(f,null,2)}
|
|
422
422
|
`),f}finally{await $p(c,{recursive:!0,force:!0})}}async function RJ(e){let t=e.now??(()=>new Date),r=wR(e.artifactsDir??St(e.rootDir,".brains-ops","stress",`cleanup-${kR(t().toISOString())}`));await bR(r,{recursive:!0});let{pilot:i,user:n}=await vR(e.rootDir,e.handle);Ep({handle:n.handle,domain:n.domain,contentRepo:n.contentRepo,confirmation:e.confirmation});let o=(e.env??process.env).CONTENT_REPO_ADMIN_TOKEN;if(!o)throw Error("Missing CONTENT_REPO_ADMIN_TOKEN");let s=e.commandRunner??co,a=e.logger??console.info,c=await SR(St(xR(),"brains-ops-directory-sync-cleanup-")),l=St(c,"content");try{let u=await cu.clone(s,`${i.githubOrg}/${n.contentRepo}`,l,o),f=await _R(u.dir),p;if(f>0)await u.commitAll("test(directory-sync): clean residual stress probes"),await u.pushMainWithRebase(),p=await u.output(["rev-parse","HEAD"]),a(`Removed ${f} directory-sync stress probes`);let m=(await ja(u.dir)).length,y=m===0?await u.pruneStressBackupBranches():[],g={success:m===0,artifactsDir:r,probesRemoved:f,probesRemaining:m,backupBranchesDeleted:y,...p?{cleanupCommit:p}:{}};return await Kn(St(r,"cleanup.json"),`${JSON.stringify(g,null,2)}
|
|
423
423
|
`),g}finally{await $p(c,{recursive:!0,force:!0})}}class OJ{#e;#t;#r;#n;#i;#o;#a;#s;#c;#l;#d;constructor(e){this.#e=e,this.#t=new gR({domain:e.user.domain,fetchImpl:e.fetchImpl,now:e.now,sleep:e.sleep,sampleRuntime:()=>this.#y()})}async prepare(e){this.#r=await SR(St(xR(),"brains-ops-directory-sync-stress-"));let t=St(this.#r,"content");this.#i=St(this.#r,"id_ed25519"),this.#o=St(this.#r,"known_hosts"),this.#a=await this.#m(),await Kn(this.#i,YSe(this.#e.environment.KAMAL_SSH_PRIVATE_KEY),{mode:384}),await FSe(this.#i,384);let r=await this.#b("ssh-keyscan",["-T","10","-t","ed25519",this.#a]);if(r.exitCode!==0||!r.stdout.trim())throw Error("Unable to resolve smoke SSH host key");await Kn(this.#o,r.stdout,{mode:384});let i=await this.#h(["docker","ps","--filter","label=service=rover","--filter","label=role=web","--format","{{.Names}}"]);if(this.#s=i.stdout.trim().split(/\r?\n/)[0],!this.#s||!/^[A-Za-z0-9_.-]+$/.test(this.#s))throw Error("Unable to resolve a running smoke container");let n=await cu.clone(this.#e.commandRunner,`${this.#e.githubOrg}/${this.#e.user.contentRepo}`,t,this.#e.environment.CONTENT_REPO_ADMIN_TOKEN);if(this.#n=n,(await ja(n.dir)).length>0)throw Error("Directory-sync stress probes already exist");let o=await n.output(["rev-parse","HEAD"]);this.#l=await n.output(["rev-parse","HEAD^{tree}"]),this.#d=await this.#f();let s=await this.#t.waitForHealthSnapshot(60000);if(!s)throw Error("Smoke health was unavailable before stress testing");return this.#c=`ops/directory-sync-stress-backup-${this.#e.runId}`,await n.run(["push","origin",`HEAD:refs/heads/${this.#c}`]),await this.#t.discoverEndpoints(),await Kn(St(this.#e.artifactsDir,"state.json"),`${JSON.stringify({runId:this.#e.runId,profile:e.profile,originalHead:o,originalTree:this.#l,backupBranch:this.#c,baseline:{entities:s.entities,notes:Tp(s),version:s.version}},null,2)}
|
|
424
424
|
`),this.#e.logger(`Prepared ${e.profile} directory-sync stress run for ${this.#e.user.handle}`),{entities:s.entities,notes:Tp(s),version:s.version}}async startMonitoring(){this.#S(),this.#t.start()}async executePhase(e,t){this.#S();let r=this.#n;if(!r)throw Error("Directory-sync stress checkout is not prepared");await r.sync();let i=this.#t.healthSamples.length,n=this.#e.now().getTime(),o=await this.#g();if(o?.pending!==0||o.processing!==0)return lu(e,"health did not provide a drained queue before the phase");await zJ(r.dir,e),await r.commitAll(`test(directory-sync): stress ${e.id}`),await r.pushMainWithRebase();let s=this.#e.now().getTime(),a=await r.output(["rev-parse","HEAD"]),c=await this.#p(a,900000);if(c===void 0)return lu(e,"runtime did not pull the phase commit");let l;if(e.operation==="rename"){let m=t.notes+e.targetProbeCount;if(e.settleMs>0)await this.#e.sleep(e.settleMs);let y=await this.#t.waitForStableEntityBaseline(m,void 0,1200000);if(l=this.#e.now().getTime()-s,!y)return lu(e,`health did not stabilize at ${m} notes`,c,l)}else if(e.operation==="add"||e.operation==="delete"){let m=t.notes+e.targetProbeCount,y=this.#e.now().getTime(),g=await this.#t.waitForEntityBaseline(m,void 0,1200000);if(l=this.#e.now().getTime()-y,!g)return lu(e,`health did not reach ${m} notes`,c,l)}if(e.operation!=="rename"&&e.settleMs>0)await this.#e.sleep(e.settleMs);let u=e.operation==="delete"?0:Math.ceil(e.count/50);if(!await this.#u(o.completedImports+u,1200000))return lu(e,`health did not observe ${u} completed import job(s) with a drained queue`,c,l);let p=this.#t.healthSamples.slice(i).find((m)=>!m.ok);if(p)return lu(e,`${p.endpoint} unavailable (${p.status===0?p.error??"unknown":p.status})`,c,l);return this.#e.logger(`Completed ${e.id} in ${this.#e.now().getTime()-n}ms`),{id:e.id,operation:e.operation,count:e.count,success:!0,commitLatencyMs:c,...l===void 0?{}:{persistenceLatencyMs:l}}}async cleanup(e){let t=this.#n;if(!t)return{success:!1,probesRemaining:0,error:"stress checkout was not prepared"};try{if(await t.sync(!0),await _R(t.dir)>0)await t.commitAll("test(directory-sync): remove stress probes"),await t.pushMainWithRebase();let i=(await ja(t.dir)).length;this.#t.markGateEnd();let n=await this.#t.waitForEntityBaseline(e.notes,e.entities,1200000);await t.sync(!0);let s=await t.output(["rev-parse","HEAD^{tree}"])===this.#l,a=i===0&&n!==void 0&&s;if(a&&this.#c){if((await t.run(["push","origin","--delete",this.#c],!1)).exitCode!==0)this.#e.logger(`Warning: unable to delete backup branch ${this.#c}`)}return{success:a,probesRemaining:i,...n?{finalEntities:n.entities,finalNotes:Tp(n)}:{},contentTreeRestored:s,...!a?{error:!n?"entity baseline was not restored before cleanup timeout":!s?"content tree differs from the pre-stress baseline":"stress probes remain after cleanup"}:{}}}catch(r){return{success:!1,probesRemaining:(await ja(t.dir)).length,error:at(r)}}}async stopMonitoring(){await this.#t.stop(),await Kn(St(this.#e.artifactsDir,"health-samples.json"),`${JSON.stringify(this.#t.healthSamples,null,2)}
|
|
@@ -432,7 +432,7 @@ Update marker: ${t.id}.
|
|
|
432
432
|
`}function kR(e){return e.replace(/[-:.TZ]/g,"").slice(0,14)}async function XSe(e){await Kn(St(e.artifactsDir,"report.json"),`${JSON.stringify(e,null,2)}
|
|
433
433
|
`),await Kn(St(e.artifactsDir,"report.md"),exe(e))}function exe(e){let t=e.report.metrics.runtime,r=e.report.metrics.health,i=t.map((a)=>a.cpuPercent).sort((a,c)=>a-c),n=t.map((a)=>a.memoryPercent),o=r.filter((a)=>!a.ok),s=["# Directory-sync stress report","",`- Run: \`${e.runId}\``,`- Target: \`${e.target.handle}\` (${e.target.domain})`,`- Profile: \`${e.report.profile}\``,`- Version: \`${e.report.baseline.version}\``,`- Result: **${e.report.success?"PASS":"FAIL"}**`,`- Started: ${e.startedAt}`,`- Completed: ${e.completedAt}`,"","## Phases","","| Phase | Operation | Count | Result | Pull latency | Persistence latency |","| --- | --- | ---: | --- | ---: | ---: |",...e.report.phases.map((a)=>`| ${a.id} | ${a.operation} | ${a.count} | ${a.success?"pass":`fail: ${a.error??"unknown"}`} | ${AJ(a.commitLatencyMs)} | ${AJ(a.persistenceLatencyMs)} |`),"","## Runtime","",`- Samples: ${t.length}`,`- CPU p50/p95/p99/max: ${Ap(yR(i,0.5))} / ${Ap(yR(i,0.95))} / ${Ap(yR(i,0.99))} / ${Ap(i.at(-1))}`,`- Memory max: ${Ap(n.length?Math.max(...n):void 0)}`,`- PIDs max: ${t.length?Math.max(...t.map((a)=>a.pids)):"n/a"}`,`- Container status/restarts/OOM: ${e.report.metrics.container?`${e.report.metrics.container.status} / ${e.report.metrics.container.restartCount} / ${e.report.metrics.container.oomKilled}`:"unknown"}`,`- External AI calls: ${e.report.metrics.externalAiCalls??0}`,`- Health samples: ${r.length}`,`- Health failures: ${o.length}`,"","## Cleanup","",`- Result: ${e.report.cleanup.success?"pass":"fail"}`,`- Remaining probes: ${e.report.cleanup.probesRemaining}`,`- Final entities: ${e.report.cleanup.finalEntities??"unknown"}`,`- Final notes: ${e.report.cleanup.finalNotes??"unknown"}`,`- Content tree restored: ${e.report.cleanup.contentTreeRestored??"unknown"}`,""];if(e.report.failure)s.push("## Failure","",e.report.failure,"");return`${s.join(`
|
|
434
434
|
`)}
|
|
435
|
-
`}function yR(e,t){if(e.length===0)return;let r=Math.max(0,Math.ceil(e.length*t)-1);return e[r]}function Ap(e){return e===void 0?"n/a":`${e.toFixed(2)}%`}function AJ(e){return e===void 0?"n/a":`${(e/1000).toFixed(1)}s`}var VSe,WSe,GSe;var Cp=S(()=>{Ae();lS();un();Ip();IJ();TJ();Ip();VSe=d.object({HCLOUD_TOKEN:d.string().min(1),KAMAL_SSH_PRIVATE_KEY:d.string().min(1),CONTENT_REPO_ADMIN_TOKEN:d.string().min(1)}),WSe=d.object({servers:d.array(d.object({id:d.number().int(),status:d.string(),public_net:d.object({ipv4:d.object({ip:d.string().min(1)})})}))}),GSe=d.object({status:d.literal("ready"),operationalStatus:d.literal("operational"),resources:d.object({queue:d.object({totals:d.object({pending:d.number().int().nonnegative(),processing:d.number().int().nonnegative()}),byType:d.array(d.object({type:d.string(),status:d.string(),count:d.number().int().nonnegative()}))})})})});var DJ=S(()=>{ks()});var txe="/usr/local/sbin/brains-health-watchdog",rxe="ai.rizom.brain.watchdog",nxe="true",ER,LJ,
|
|
435
|
+
`}function yR(e,t){if(e.length===0)return;let r=Math.max(0,Math.ceil(e.length*t)-1);return e[r]}function Ap(e){return e===void 0?"n/a":`${e.toFixed(2)}%`}function AJ(e){return e===void 0?"n/a":`${(e/1000).toFixed(1)}s`}var VSe,WSe,GSe;var Cp=S(()=>{Ae();lS();un();Ip();IJ();TJ();Ip();VSe=d.object({HCLOUD_TOKEN:d.string().min(1),KAMAL_SSH_PRIVATE_KEY:d.string().min(1),CONTENT_REPO_ADMIN_TOKEN:d.string().min(1)}),WSe=d.object({servers:d.array(d.object({id:d.number().int(),status:d.string(),public_net:d.object({ipv4:d.object({ip:d.string().min(1)})})}))}),GSe=d.object({status:d.literal("ready"),operationalStatus:d.literal("operational"),resources:d.object({queue:d.object({totals:d.object({pending:d.number().int().nonnegative(),processing:d.number().int().nonnegative()}),byType:d.array(d.object({type:d.string(),status:d.string(),count:d.number().int().nonnegative()}))})})})});var DJ=S(()=>{ks()});var txe="/usr/local/sbin/brains-health-watchdog",rxe="ai.rizom.brain.watchdog",nxe="true",ER,LJ,nGe;var BJ=S(async()=>{DJ();ER=`${rxe}=${nxe}`,LJ=`#!/usr/bin/env bash
|
|
436
436
|
set -euo pipefail
|
|
437
437
|
umask 077
|
|
438
438
|
|
|
@@ -491,7 +491,7 @@ while read -r container_id; do
|
|
|
491
491
|
logger -t brains-health-watchdog "restarting unhealthy container=$container_name service=$service_name incident=$incident_path"
|
|
492
492
|
docker restart "$container_id"
|
|
493
493
|
done < <(docker ps --filter health=unhealthy --filter label=${ER} --format '{{.ID}}')
|
|
494
|
-
`,
|
|
494
|
+
`,nGe=`[Unit]
|
|
495
495
|
Description=Restart persistently unhealthy Brain containers
|
|
496
496
|
After=docker.service
|
|
497
497
|
Requires=docker.service
|
|
@@ -731,7 +731,7 @@ printf 'REMOTE_ARTIFACT_DIR=%s\\n' "$remote_dir"
|
|
|
731
731
|
`),o}async function KJ(e,t){let r=await xt(e),i=r.users.find((n)=>n.handle===t);if(!i)throw Error(`Unknown pilot user: ${t}`);return{pilot:r.pilot,user:i}}async function JJ(e){let t=await axe(_i(cxe(),"brains-ops-watchdog-smoke-")),r=_i(t,"id_ed25519"),i=_i(t,"known_hosts");try{let n=encodeURIComponent(`brain=${e.target.pilot.contentRepoPrefix}${e.target.user.handle}`),o=await e.fetchImpl(`https://api.hetzner.cloud/v1/servers?label_selector=${n}`,{headers:{Authorization:`Bearer ${e.environment.HCLOUD_TOKEN}`}});if(!o.ok)throw Error(`Hetzner server lookup failed with ${o.status}`);let s=lxe.parse(await o.json());if(s.servers.length!==1)throw Error(`Expected one smoke server, found ${s.servers.length}`);let a=s.servers[0];if(a?.status!=="running")throw Error("Smoke server is not running");await uu(r,fxe(e.environment.KAMAL_SSH_PRIVATE_KEY),{mode:384}),await sxe(r,384);let c=await e.commandRunner("ssh-keyscan",["-T","10","-t","ed25519",a.public_net.ipv4.ip]);if(c.exitCode!==0||!c.stdout.trim())throw Error("Unable to resolve watchdog smoke SSH host key");return await uu(i,c.stdout,{mode:384}),{temporaryRoot:t,sshKeyPath:r,knownHostsPath:i,serverIp:a.public_net.ipv4.ip,commandRunner:e.commandRunner}}catch(n){throw await TR(t,{recursive:!0,force:!0}),n}}async function IR(e,t,r){return e.commandRunner("ssh",[...VJ(e),`root@${e.serverIp}`,"bash","-s","--",t,r],{stdin:AR()})}async function uxe(e,t,r){return e.commandRunner("scp",[...VJ(e),"-r",`root@${e.serverIp}:${t}/.`,r])}function VJ(e){return["-i",e.sshKeyPath,"-o","BatchMode=yes","-o","IdentitiesOnly=yes","-o","ConnectTimeout=10","-o","StrictHostKeyChecking=yes","-o",`UserKnownHostsFile=${e.knownHostsPath}`]}async function dxe(e){try{return await oxe(e),!0}catch{return!1}}async function dS(e,t,r){await Promise.all([uu(_i(e,`${t}.stdout.log`),r.stdout),uu(_i(e,`${t}.stderr.log`),r.stderr)])}function fxe(e){return`${e.replace(/\r\n/g,`
|
|
732
732
|
`).replace(/\\n/g,`
|
|
733
733
|
`).trimEnd()}
|
|
734
|
-
`}var MJ,lxe;var pS=S(async()=>{Ae();jJ();un();Ip();await BJ();MJ=d.object({HCLOUD_TOKEN:d.string().min(1),KAMAL_SSH_PRIVATE_KEY:d.string().min(1)}),lxe=d.object({servers:d.array(d.object({status:d.string(),public_net:d.object({ipv4:d.object({ip:d.string().min(1)})})}))})});import{access as KN,chmod as oE,mkdir as Sh,readFile as VN,writeFile as JN}from"fs/promises";import{dirname as IG,join as Ic}from"path";import{fileURLToPath as TG}from"url";var Rp={name:"@rizom/ops",version:"0.2.0-alpha.
|
|
734
|
+
`}var MJ,lxe;var pS=S(async()=>{Ae();jJ();un();Ip();await BJ();MJ=d.object({HCLOUD_TOKEN:d.string().min(1),KAMAL_SSH_PRIVATE_KEY:d.string().min(1)}),lxe=d.object({servers:d.array(d.object({status:d.string(),public_net:d.object({ipv4:d.object({ip:d.string().min(1)})})}))})});import{access as KN,chmod as oE,mkdir as Sh,readFile as VN,writeFile as JN}from"fs/promises";import{dirname as IG,join as Ic}from"path";import{fileURLToPath as TG}from"url";var Rp={name:"@rizom/ops",version:"0.2.0-alpha.591",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/auth-service":"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"};ks();Ec();var AG=["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/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"],sE=new Set([".kamal/hooks/pre-deploy"]),$G=new Set(["cohorts/cohort-1.yaml","users/alice.yaml","docs/canonical-crossover-record.md"]),CG=TG(new URL("../templates/rover-pilot/",import.meta.url)),RG=[`service: rover
|
|
735
735
|
image: <%= ENV['IMAGE_REPOSITORY'] %>
|
|
736
736
|
|
|
737
737
|
servers:
|