@rizom/ops 0.2.0-alpha.768 → 0.2.0-alpha.769

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.
@@ -400,7 +400,7 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
400
400
  `)+1;while(t!==0)this.onNewLine(this.offset+t),t=this.source.indexOf(`
401
401
  `,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let r="end"in t.value?t.value.end:void 0;if((Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment")r?.push(this.sourceToken);else e.items.push({start:[this.sourceToken]})}else if(t.sep)t.sep.push(this.sourceToken);else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let o=e.items[e.items.length-2]?.value?.end;if(Array.isArray(o)){iy(o,t.start),o.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let r=!this.onKeyLine&&this.indent===e.indent,o=r&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",n=[];if(o&&t.sep&&!t.value){let i=[];for(let s=0;s<t.sep.length;++s){let a=t.sep[s];switch(a.type){case"newline":i.push(s);break;case"space":break;case"comment":if(a.indent>e.indent)i.length=0;break;default:i.length=0}}if(i.length>=2)n=t.sep.splice(i[1])}switch(this.type){case"anchor":case"tag":if(o||t.value)n.push(this.sourceToken),e.items.push({start:n}),this.onKeyLine=!0;else if(t.sep)t.sep.push(this.sourceToken);else t.start.push(this.sourceToken);return;case"explicit-key-ind":if(!t.sep&&!t.explicitKey)t.start.push(this.sourceToken),t.explicitKey=!0;else if(o||t.value)n.push(this.sourceToken),e.items.push({start:n,explicitKey:!0});else this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]});this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(!t.sep)if(Ui(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let i=Yc(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]})}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Ui(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]});else if(j6(t.key)&&!Ui(t.sep,"newline")){let i=Yc(t.start),s=t.key,a=t.sep;a.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:s,sep:a}]})}else if(n.length>0)t.sep=t.sep.concat(n,this.sourceToken);else t.sep.push(this.sourceToken);else if(!t.sep)Object.assign(t,{key:null,sep:[this.sourceToken]});else if(t.value||o)e.items.push({start:n,key:null,sep:[this.sourceToken]});else if(Ui(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]});else t.sep.push(this.sourceToken);this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);if(o||t.value)e.items.push({start:n,key:i,sep:[]}),this.onKeyLine=!0;else if(t.sep)this.stack.push(i);else Object.assign(t,{key:i,sep:[]}),this.onKeyLine=!0;return}default:{let i=this.startBlockValue(e);if(i){if(i.type==="block-seq"){if(!t.explicitKey&&t.sep&&!Ui(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else if(r)e.items.push({start:n});this.stack.push(i);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let r="end"in t.value?t.value.end:void 0;if((Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment")r?.push(this.sourceToken);else e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let o=e.items[e.items.length-2]?.value?.end;if(Array.isArray(o)){iy(o,t.start),o.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;if(t.value||Ui(t.start,"seq-item-ind"))e.items.push({start:[this.sourceToken]});else t.start.push(this.sourceToken);return}if(this.indent>e.indent){let r=this.startBlockValue(e);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!t||t.sep)e.items.push({start:[this.sourceToken]});else t.start.push(this.sourceToken);return;case"map-value-ind":if(!t||t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!t||t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);if(!t||t.value)e.items.push({start:[],key:o,sep:[]});else if(t.sep)this.stack.push(o);else Object.assign(t,{key:o,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let r=this.startBlockValue(e);if(r)this.stack.push(r);else yield*this.pop(),yield*this.step()}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===e.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let o=oy(r),n=Yc(o);B6(e);let i=e.end.splice(1,e.end.length);i.push(this.sourceToken);let s={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
402
402
  `)+1;while(t!==0)this.onNewLine(this.offset+t),t=this.source.indexOf(`
403
- `,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=oy(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=oy(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()}}}vle.Parser=Z6});var J6=ge(function(Tle){var U6=aR(),xle=tp(),ap=rp(),_le=yA(),Ele=qe(),Ile=yR(),M6=bR();function q6(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Ile.LineCounter||null,prettyErrors:t}}function kle(e,t={}){let{lineCounter:r,prettyErrors:o}=q6(t),n=new M6.Parser(r?.addNewLine),i=new U6.Composer(t),s=Array.from(i.compose(n.parse(e)));if(o&&r)for(let a of s)a.errors.forEach(ap.prettifyError(e,r)),a.warnings.forEach(ap.prettifyError(e,r));if(s.length>0)return s;return Object.assign([],{empty:!0},i.streamInfo())}function F6(e,t={}){let{lineCounter:r,prettyErrors:o}=q6(t),n=new M6.Parser(r?.addNewLine),i=new U6.Composer(t),s=null;for(let a of i.compose(n.parse(e),!0,e.length))if(!s)s=a;else if(s.options.logLevel!=="silent"){s.errors.push(new ap.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(o&&r)s.errors.forEach(ap.prettifyError(e,r)),s.warnings.forEach(ap.prettifyError(e,r));return s}function Ale(e,t,r){let o=void 0;if(typeof t==="function")o=t;else if(r===void 0&&t&&typeof t==="object")r=t;let n=F6(e,r);if(!n)return null;if(n.warnings.forEach((i)=>_le.warn(n.options.logLevel,i)),n.errors.length>0)if(n.options.logLevel!=="silent")throw n.errors[0];else n.errors=[];return n.toJS(Object.assign({reviver:o},r))}function Rle(e,t,r){let o=null;if(typeof t==="function"||Array.isArray(t))o=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(Ele.isDocument(e)&&!o)return e.toString(r);return new xle.Document(e,o,r).toString(r)}Tle.parse=Ale;Tle.parseAllDocuments=kle;Tle.parseDocument=F6;Tle.stringify=Rle});var zle,Nle,Dle,SR,Lle,Mi,Ble,jle,Zle,Ule,s1e,Mle,qle,Fle,sy,K6,Jle,Kle,Hle,Vle,Wle,Gle,Qle,Yle,Xle,eue,vn,Oo,tue,Co,vR,rue,nue,oue,iue,sue,aue,cue,lue,uue,tn,due,pue,fue;var Xc=v(()=>{zle=aR(),Nle=tp(),Dle=JA(),SR=rp(),Lle=Ud(),Mi=qe(),Ble=Li(),jle=It(),Zle=ji(),Ule=Zi(),s1e=ry(),Mle=gR(),qle=yR(),Fle=bR(),sy=J6(),K6=jd();Jle=zle.Composer,Kle=Nle.Document,Hle=Dle.Schema,Vle=SR.YAMLError,Wle=SR.YAMLParseError,Gle=SR.YAMLWarning,Qle=Lle.Alias,Yle=Mi.isAlias,Xle=Mi.isCollection,eue=Mi.isDocument,vn=Mi.isMap,Oo=Mi.isNode,tue=Mi.isPair,Co=Mi.isScalar,vR=Mi.isSeq,rue=Ble.Pair,nue=jle.Scalar,oue=Zle.YAMLMap,iue=Ule.YAMLSeq,sue=Mle.Lexer,aue=qle.LineCounter,cue=Fle.Parser,lue=sy.parse,uue=sy.parseAllDocuments,tn=sy.parseDocument,due=sy.stringify,pue=K6.visit,fue=K6.visitAsync});var G6={};Lt(G6,{migratePilotDeploySecrets:()=>V6,migratePilotEnvSchema:()=>W6,migratePilotRepoProviderKeys:()=>wue,migrateProviderKeyFieldsYaml:()=>_R,openaiSelectorFor:()=>ER,renameProviderKeyFields:()=>qi});import{readdir as mue,readFile as wR,writeFile as H6}from"fs/promises";import{join as Po}from"path";function _R(e){let t=tn(e,{keepSourceTokens:!0});return qi(t)?t.toString({lineWidth:0}):e}function qi(e){if(!vn(e.contents))return!1;return e.contents.items.filter((r)=>{if(!Co(r.key)||typeof r.key.value!=="string")return!1;let o=hue[r.key.value];if(!o)return!1;if(r.key.value==="aiApiKey"&&Co(r.value)&&r.value.value===cy)r.value.value=ly;return r.key.value=o,!0}).length>0}function ER(e){return e===cy?ly:e}function V6(e){return e.replace(new RegExp(`^(\\s+- )${cy}$`,"m"),`$1${ly}`)}function W6(e){return e.replace(new RegExp(`^${cy}=`,"m"),`${ly}=`)}async function ay(e){try{return(await mue(e)).filter((r)=>r.endsWith(".yaml")).sort()}catch{return[]}}async function xR(e){try{return await wR(e,"utf8")}catch{return}}async function Sue(e){let t=await ay(Po(e,"cohorts")),r=await Promise.all(t.map(async(i)=>{let s=yr(await wR(Po(e,"cohorts",i),"utf8"),yue);return s.ok&&s.data.aiApiKeyOverride?s.data.members:[]})),o=(await ay(Po(e,"users"))).filter((i)=>!i.endsWith(".secrets.yaml")),n=await Promise.all(o.map(async(i)=>{let s=yr(await wR(Po(e,"users",i),"utf8"),gue);return s.ok&&s.data.aiApiKeyOverride?[i.replace(/\.yaml$/,"")]:[]}));return[...new Set([...r.flat(),...n.flat()])]}async function vue(e,t,r,o){let n=Po(e,"users",`${t}.secrets.yaml.age`),i=await xR(n);if(i===void 0)return!1;if(!r)throw Error(`users/${t}.secrets.yaml.age may hold the legacy AI key; set AGE_SECRET_KEY or AGE_SECRET_KEY_FILE to migrate it`);let s=new Ou;s.addIdentity(r);let a=await s.decrypt(yi.decode(i),"text"),l=_R(a);if(l===a)return!1;let u=new $u;return u.addRecipient(o),await H6(n,yi.encode(await u.encrypt(l))),!0}async function wue(e,t){let r=["pilot.yaml",...(await ay(Po(e,"cohorts"))).map((l)=>`cohorts/${l}`),...(await ay(Po(e,"users"))).filter((l)=>!l.endsWith(".secrets.yaml")).map((l)=>`users/${l}`)],o=await Sue(e),n=await Promise.all([...r.map((l)=>({file:l,migrate:_R})),{file:".env.schema",migrate:W6},{file:"deploy/kamal/deploy.yml",migrate:V6}].map(async({file:l,migrate:u})=>{let d=Po(e,l),p=await xR(d);if(p===void 0)return[];let m=u(p);if(m===p)return[];return await H6(d,m),[l]})),i=yr(await xR(Po(e,"pilot.yaml"))??"",bue),s=oA(e,t,Lr(e)),a=o.length===0?[]:await Promise.all(o.map(async(l)=>{if(!i.ok)throw Error("pilot.yaml needs agePublicKey to re-encrypt secrets");return await vue(e,l,s,i.data.agePublicKey)?[`users/${l}.secrets.yaml.age`]:[]}));return[...n.flat(),...a.flat()]}var cy="AI_API_KEY",ly="OPENAI_API_KEY",hue,gue,yue,bue;var uy=v(()=>{gi();vi();Vn();de();Xc();sA();hue={aiApiKey:"openaiApiKey",aiApiKeyOverride:"openaiApiKeyOverride"};gue=c.looseObject({aiApiKeyOverride:c.string().optional()}),yue=c.looseObject({members:c.array(c.string()).default([]),aiApiKeyOverride:c.string().optional()}),bue=c.looseObject({agePublicKey:c.string()})});function eM(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:[...Eue]};return{bundles:["core","media","automation","web","chat","site","publishing","federation"],add:["obsidian-vault"]}}function Iue(e){let t=xue.parse(e);return Qs.parse({brainVersion:t.brainVersion,bundleContract:Gs,...eM(t.preset),githubOrg:t.githubOrg,contentRepoPrefix:t.contentRepoPrefix,domainSuffix:t.domainSuffix,openaiApiKey:ER(t.aiApiKey),gitSyncToken:t.gitSyncToken,contentRepoAdminToken:t.contentRepoAdminToken,agePublicKey:t.agePublicKey})}function kue(e){let t=_ue.parse(e),r=t.presetOverride?eM(t.presetOverride):void 0;return hn.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?{openaiApiKeyOverride:t.aiApiKeyOverride}:{},...t.gitSyncTokenOverride?{gitSyncTokenOverride:t.gitSyncTokenOverride}:{}})}function tM(e){let t=tn(e,{keepSourceTokens:!0});if(t.errors.length>0)throw Error(`Invalid desired-state YAML: ${t.errors[0]?.message}`);if(!vn(t.contents))throw Error("Desired-state YAML must contain a mapping");return t}function IR(e,t){if(!vn(e.contents))return;return e.contents.items.find((r)=>Co(r.key)&&r.key.value===t)}function Q6(e,t){if(!Oo(e)||!Oo(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 Y6(e,t){if(!e||!Oo(t))return;let r=[Oo(e.key)?e.key.commentBefore:void 0,Oo(e.key)?e.key.comment:void 0,Oo(e.value)?e.value.commentBefore:void 0,Oo(e.value)?e.value.comment:void 0].filter((o)=>o!==void 0);if(r.length===0)return;t.commentBefore=[t.commentBefore,...r].filter((o)=>o!==void 0).join(`
403
+ `,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=oy(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=oy(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()}}}vle.Parser=Z6});var J6=ge(function(Tle){var U6=aR(),xle=tp(),ap=rp(),_le=yA(),Ele=qe(),Ile=yR(),M6=bR();function q6(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Ile.LineCounter||null,prettyErrors:t}}function kle(e,t={}){let{lineCounter:r,prettyErrors:o}=q6(t),n=new M6.Parser(r?.addNewLine),i=new U6.Composer(t),s=Array.from(i.compose(n.parse(e)));if(o&&r)for(let a of s)a.errors.forEach(ap.prettifyError(e,r)),a.warnings.forEach(ap.prettifyError(e,r));if(s.length>0)return s;return Object.assign([],{empty:!0},i.streamInfo())}function F6(e,t={}){let{lineCounter:r,prettyErrors:o}=q6(t),n=new M6.Parser(r?.addNewLine),i=new U6.Composer(t),s=null;for(let a of i.compose(n.parse(e),!0,e.length))if(!s)s=a;else if(s.options.logLevel!=="silent"){s.errors.push(new ap.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(o&&r)s.errors.forEach(ap.prettifyError(e,r)),s.warnings.forEach(ap.prettifyError(e,r));return s}function Ale(e,t,r){let o=void 0;if(typeof t==="function")o=t;else if(r===void 0&&t&&typeof t==="object")r=t;let n=F6(e,r);if(!n)return null;if(n.warnings.forEach((i)=>_le.warn(n.options.logLevel,i)),n.errors.length>0)if(n.options.logLevel!=="silent")throw n.errors[0];else n.errors=[];return n.toJS(Object.assign({reviver:o},r))}function Rle(e,t,r){let o=null;if(typeof t==="function"||Array.isArray(t))o=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(Ele.isDocument(e)&&!o)return e.toString(r);return new xle.Document(e,o,r).toString(r)}Tle.parse=Ale;Tle.parseAllDocuments=kle;Tle.parseDocument=F6;Tle.stringify=Rle});var zle,Nle,Dle,SR,Lle,Mi,Ble,jle,Zle,Ule,s1e,Mle,qle,Fle,sy,K6,Jle,Kle,Hle,Vle,Wle,Gle,Qle,Yle,Xle,eue,vn,Oo,tue,Co,vR,rue,nue,oue,iue,sue,aue,cue,lue,uue,tn,due,pue,fue;var Xc=v(()=>{zle=aR(),Nle=tp(),Dle=JA(),SR=rp(),Lle=Ud(),Mi=qe(),Ble=Li(),jle=It(),Zle=ji(),Ule=Zi(),s1e=ry(),Mle=gR(),qle=yR(),Fle=bR(),sy=J6(),K6=jd();Jle=zle.Composer,Kle=Nle.Document,Hle=Dle.Schema,Vle=SR.YAMLError,Wle=SR.YAMLParseError,Gle=SR.YAMLWarning,Qle=Lle.Alias,Yle=Mi.isAlias,Xle=Mi.isCollection,eue=Mi.isDocument,vn=Mi.isMap,Oo=Mi.isNode,tue=Mi.isPair,Co=Mi.isScalar,vR=Mi.isSeq,rue=Ble.Pair,nue=jle.Scalar,oue=Zle.YAMLMap,iue=Ule.YAMLSeq,sue=Mle.Lexer,aue=qle.LineCounter,cue=Fle.Parser,lue=sy.parse,uue=sy.parseAllDocuments,tn=sy.parseDocument,due=sy.stringify,pue=K6.visit,fue=K6.visitAsync});var G6={};Lt(G6,{migratePilotDeploySecrets:()=>V6,migratePilotEnvSchema:()=>W6,migratePilotRepoProviderKeys:()=>wue,migrateProviderKeyFieldsYaml:()=>_R,openaiSelectorFor:()=>ER,renameProviderKeyFields:()=>qi});import{readdir as mue,readFile as wR,writeFile as H6}from"fs/promises";import{join as Po}from"path";function _R(e){let t=tn(e,{keepSourceTokens:!0});return qi(t)?t.toString({lineWidth:0}):e}function qi(e){if(!vn(e.contents))return!1;return e.contents.items.filter((r)=>{if(!Co(r.key)||typeof r.key.value!=="string")return!1;let o=hue[r.key.value];if(!o)return!1;if(r.key.value==="aiApiKey"&&Co(r.value)&&r.value.value===cy)r.value.value=ly;return r.key.value=o,!0}).length>0}function ER(e){return e===cy?ly:e}function V6(e){return e.replace(new RegExp(`^(\\s+- )${cy}$`,"m"),`$1${ly}`)}function W6(e){return e.replace(new RegExp(`^${cy}=`,"m"),`${ly}=`)}async function ay(e){try{return(await mue(e)).filter((r)=>r.endsWith(".yaml")).sort()}catch{return[]}}async function xR(e){try{return await wR(e,"utf8")}catch{return}}async function Sue(e){let t=await ay(Po(e,"cohorts")),r=await Promise.all(t.map(async(i)=>{let s=yr(await wR(Po(e,"cohorts",i),"utf8"),yue);return s.ok&&s.data.aiApiKeyOverride?s.data.members:[]})),o=(await ay(Po(e,"users"))).filter((i)=>!i.endsWith(".secrets.yaml")),n=await Promise.all(o.map(async(i)=>{let s=yr(await wR(Po(e,"users",i),"utf8"),gue);return s.ok&&s.data.aiApiKeyOverride?[i.replace(/\.yaml$/,"")]:[]}));return[...new Set([...r.flat(),...n.flat()])]}async function vue(e,t,r,o){let n=Po(e,"users",`${t}.secrets.yaml.age`),i=await xR(n);if(i===void 0)return!1;if(!r)throw Error(`users/${t}.secrets.yaml.age may hold the legacy AI key; set AGE_SECRET_KEY or AGE_SECRET_KEY_FILE to migrate it`);let s=new Ou;s.addIdentity(r);let a=await s.decrypt(yi.decode(i),"text"),l=_R(a);if(l===a)return!1;let u=new $u;return u.addRecipient(o),await H6(n,yi.encode(await u.encrypt(l))),!0}async function wue(e,t){let r=["pilot.yaml",...(await ay(Po(e,"cohorts"))).map((l)=>`cohorts/${l}`),...(await ay(Po(e,"users"))).filter((l)=>!l.endsWith(".secrets.yaml")).map((l)=>`users/${l}`)],o=await Sue(e),n=await Promise.all([...r.map((l)=>({file:l,migrate:_R})),{file:".env.schema",migrate:W6},{file:"deploy/kamal/deploy.yml",migrate:V6}].map(async({file:l,migrate:u})=>{let d=Po(e,l),p=await xR(d);if(p===void 0)return[];let m=u(p);if(m===p)return[];return await H6(d,m),[l]})),i=yr(await xR(Po(e,"pilot.yaml"))??"",bue),s=oA(e,t,Lr(e)),a=o.length===0?[]:await Promise.all(o.map(async(l)=>{if(!i.ok)throw Error("pilot.yaml needs agePublicKey to re-encrypt secrets");return await vue(e,l,s,i.data.agePublicKey)?[`users/${l}.secrets.yaml.age`]:[]}));return[...n.flat(),...a.flat()]}var cy="AI_API_KEY",ly="OPENAI_API_KEY",hue,gue,yue,bue;var uy=v(()=>{gi();vi();Vn();de();Xc();sA();hue={aiApiKey:"openaiApiKey",aiApiKeyOverride:"openaiApiKeyOverride"};gue=c.looseObject({aiApiKeyOverride:c.string().optional()}),yue=c.looseObject({members:c.array(c.string()).default([]),aiApiKeyOverride:c.string().optional()}),bue=c.looseObject({agePublicKey:c.string()})});function eM(e){if(e==="core")return{bundles:["core","media","web","chat"]};if(e==="default")return{bundles:["core","media","automation","web","chat","site","publishing","federation"],remove:[...Eue]};return{bundles:["core","media","automation","web","chat","site","publishing","federation"]}}function Iue(e){let t=xue.parse(e);return Qs.parse({brainVersion:t.brainVersion,bundleContract:Gs,...eM(t.preset),githubOrg:t.githubOrg,contentRepoPrefix:t.contentRepoPrefix,domainSuffix:t.domainSuffix,openaiApiKey:ER(t.aiApiKey),gitSyncToken:t.gitSyncToken,contentRepoAdminToken:t.contentRepoAdminToken,agePublicKey:t.agePublicKey})}function kue(e){let t=_ue.parse(e),r=t.presetOverride?eM(t.presetOverride):void 0;return hn.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?{openaiApiKeyOverride:t.aiApiKeyOverride}:{},...t.gitSyncTokenOverride?{gitSyncTokenOverride:t.gitSyncTokenOverride}:{}})}function tM(e){let t=tn(e,{keepSourceTokens:!0});if(t.errors.length>0)throw Error(`Invalid desired-state YAML: ${t.errors[0]?.message}`);if(!vn(t.contents))throw Error("Desired-state YAML must contain a mapping");return t}function IR(e,t){if(!vn(e.contents))return;return e.contents.items.find((r)=>Co(r.key)&&r.key.value===t)}function Q6(e,t){if(!Oo(e)||!Oo(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 Y6(e,t){if(!e||!Oo(t))return;let r=[Oo(e.key)?e.key.commentBefore:void 0,Oo(e.key)?e.key.comment:void 0,Oo(e.value)?e.value.commentBefore:void 0,Oo(e.value)?e.value.comment:void 0].filter((o)=>o!==void 0);if(r.length===0)return;t.commentBefore=[t.commentBefore,...r].filter((o)=>o!==void 0).join(`
404
404
  `)}function rM(e,t,r,o){if(!vn(e.contents))throw Error("Desired-state YAML must contain a mapping");let n=e.contents.items.findIndex((s)=>Co(s.key)&&s.key.value===t),i=e.createPair(r,[...o]);if(n>=0){let s=e.contents.items[n];Q6(s?.key,i.key),Q6(s?.value,i.value),e.contents.items.splice(n,1,i)}else e.contents.add(i);return i}function nM(e){let t=tM(e),r=Iue(t.toJS()),o=IR(t,"schemaVersion"),n=IR(t,"model");Y6(o,IR(t,"brainVersion")?.key),t.delete("schemaVersion"),t.set("bundleContract",Gs);let i=rM(t,"preset","bundles",r.bundles);if(Y6(n,i.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 qi(t),Qs.parse(t.toJS()),t.toString({lineWidth:0})}function oM(e){let t=tM(e),r=kue(t.toJS());if(r.bundlesOverride)rM(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 qi(t),hn.parse(t.toJS()),t.toString({lineWidth:0})}var X6,cp,xue,_ue,Eue;var iM=v(()=>{uy();Vn();de();Xc();Ao();X6=c.enum(["core","default","pro"]),cp=c.string().min(1),xue=c.strictObject({schemaVersion:c.literal(1),brainVersion:Ct,model:c.literal("rover"),githubOrg:c.string().min(1),contentRepoPrefix:c.string().min(1),domainSuffix:c.string().min(1),preset:X6,aiApiKey:cp,gitSyncToken:cp,contentRepoAdminToken:cp,agePublicKey:c.string().startsWith("age1").min(1)}),_ue=c.strictObject({members:c.array(br).min(1),brainVersionOverride:Ct.optional(),presetOverride:X6.optional(),aiApiKeyOverride:cp.optional(),gitSyncTokenOverride:cp.optional()}).superRefine((e,t)=>{if(new Set(e.members).size!==e.members.length)t.addIssue({code:c.ZodIssueCode.custom,path:["members"],message:"cohort members must be unique"})}),Eue=["series","portfolio","content-pipeline","social-media","newsletter","stock-photo"]});function aM(e,t){let r=tn(e,{keepSourceTokens:!0});if(r.errors.length>0||!vn(r.contents))throw Error(`Invalid ${t} YAML`);return r}function Oue(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function cM(e,t,r){if(!Oue(t,r.sourceBundles))throw Error(`${e} source bundles changed after review: expected [${r.sourceBundles.join(", ")}], received [${t.join(", ")}]`)}function lM(e){let t=yr(e,$ue);if(!t.ok)throw Error(`Invalid capability bundle review: ${t.error}`);return t.data}function uM(e,t){let r=aM(e,"pilot desired-state"),o=Rue.parse(r.toJS());return cM("pilot.yaml",o.bundles,t),r.set("bundleContract",Gs),r.set("bundles",t.targetBundles),qi(r),Qs.parse(r.toJS()),r.toString({lineWidth:0})}function dM(e,t,r){let o=aM(e,`cohort ${t}`),n=Tue.parse(o.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`);cM(`cohort ${t}`,n.bundlesOverride,r),o.set("bundlesOverride",r.targetBundles)}return qi(o),hn.parse(o.toJS()),o.toString({lineWidth:0})}var Aue,kR,dy,Rue,Tue,sM,$ue;var pM=v(()=>{uy();Vn();de();Xc();Ao();Aue=c.enum(["core","site","publishing","team"]),kR=c.array(Aue).min(1),dy=c.array(c.string().min(1)),Rue=c.strictObject({brainVersion:Ct,bundles:kR,add:dy.optional(),remove:dy.optional(),githubOrg:c.string().min(1),contentRepoPrefix:c.string().min(1),domainSuffix:c.string().min(1),aiApiKey:c.string().min(1),gitSyncToken:c.string().min(1),contentRepoAdminToken:c.string().min(1),agePublicKey:c.string().startsWith("age1").min(1)}),Tue=c.strictObject({members:c.array(br).min(1),brainVersionOverride:Ct.optional(),bundlesOverride:kR.optional(),addOverride:dy.optional(),removeOverride:dy.optional(),aiApiKeyOverride:c.string().min(1).optional(),gitSyncTokenOverride:c.string().min(1).optional()}),sM=c.strictObject({sourceBundles:kR,targetBundles:c.array(jk).min(1)}),$ue=c.strictObject({bundleContract:c.literal(Gs),pilot:sM,cohorts:c.record(br,sM)})});var yM={};Lt(yM,{loadCapabilityBundleReview:()=>Zue,loadReviewedSitePins:()=>jue,parseReviewedSitePins:()=>gM,stageLegacyCrossover:()=>Mue});import{access as Cue,cp as Pue,mkdir as fM,readFile as tl,readdir as hM,writeFile as el}from"fs/promises";import{basename as zue,join as Yn,relative as py,resolve as mM}from"path";import{fileURLToPath as Nue}from"url";function gM(e){let t=yr(e,Due);if(!t.ok)throw Error(`Invalid reviewed site pins: ${t.error}`);return t.data.sites}async function jue(e){return gM(await tl(e,"utf8"))}async function Zue(e){return lM(await tl(e,"utf8"))}async function Uue(e,t){let r=Yn(e,"users"),o=(await hM(r,{withFileTypes:!0})).filter((s)=>s.isFile()&&/\.ya?ml$/.test(s.name)).map((s)=>s.name).sort(),n=new Set(Object.keys(t??{})),i=[];for(let s of o){let a=Yn(r,s),l=await tl(a,"utf8"),u=tn(l,{keepSourceTokens:!0});if(u.errors.length>0||!vn(u.contents))throw Error(`Invalid user desired-state YAML: ${s}`);let d=Lue.parse(u.toJS());if(!d.siteOverride)continue;let p=t?.[d.handle];if(!p)throw Error(`User ${d.handle} has a siteOverride but no reviewed site pin`);if(n.delete(d.handle),p.package!==d.siteOverride.package||p.theme!==d.siteOverride.theme)throw Error(`Reviewed site pin identity does not match user ${d.handle}`);if(d.siteOverride.version!==void 0&&d.siteOverride.version!==p.version)throw Error(`Reviewed site version does not match the existing pin for user ${d.handle}`);if(d.siteOverride.themeVersion!==void 0&&d.siteOverride.themeVersion!==p.themeVersion)throw Error(`Reviewed theme version does not match the existing pin for user ${d.handle}`);if(u.setIn(["siteOverride","version"],p.version),p.themeVersion!==void 0)u.setIn(["siteOverride","themeVersion"],p.themeVersion);else u.deleteIn(["siteOverride","themeVersion"]);ag.parse(u.toJS());let m=u.toString({lineWidth:0});if(m!==l)await el(a,m),i.push(py(e,a))}if(n.size>0)throw Error(`Reviewed site pins do not match site users: ${[...n].sort().join(", ")}`);return i}async function Mue(e,t,r={}){let o=mM(e),n=mM(t);if(o===n||n.startsWith(`${o}/`))throw Error("Crossover output must be outside the source repository");await Pue(o,n,{recursive:!0,errorOnExist:!0,force:!1,filter:(A)=>{let O=zue(A);return O!==".git"&&O!==".operator"&&O!==".brains-ops"&&O!==".turbo"&&O!=="dist"&&O!=="node_modules"&&O!==".env"&&O!==".env.local"&&!O.endsWith(".secrets.yaml")}});let i=[],s=Yn(n,"docs","canonical-crossover-record.md");try{await Cue(s)}catch{await fM(Yn(n,"docs"),{recursive:!0}),await el(s,await tl(Bue,"utf8")),i.push("docs/canonical-crossover-record.md")}let a=Yn(n,"pilot.yaml"),l=await tl(a,"utf8"),d=tn(l).toJS();if(!Pd(d))throw Error(`${a} is not a YAML mapping`);let p=Array.isArray(d.bundles),m=r.bundleReview,h;if(p){if(!m)throw Error("Current canonical desired state requires an explicit capability bundle review manifest");h=uM(l,m.pilot)}else h=nM(l);await el(a,h),i.push("pilot.yaml");let b=Yn(n,"cohorts"),y=(await hM(b,{withFileTypes:!0})).filter((A)=>A.isFile()&&/\.ya?ml$/.test(A.name)).map((A)=>A.name).sort(),S=new Set(Object.keys(m?.cohorts??{}));for(let A of y){let O=Yn(b,A),L=await tl(O,"utf8"),z=A.replace(/\.ya?ml$/,""),K=m?.cohorts[z];if(K)S.delete(z);await el(O,p?dM(L,z,K):oM(L)),i.push(py(n,O))}if(p&&S.size>0)throw Error(`Capability bundle review names unknown cohorts: ${[...S].sort().join(", ")}`);i.push(...await Uue(n,r.sitePins));let x=await wt(n),_=dg(x.pilot.githubOrg);for(let A of x.users){let O=await _(A),L=Yn(n,"users",A.handle);if(await fM(L,{recursive:!0}),O.brainYaml){let z=Yn(L,"brain.yaml");await el(z,O.brainYaml),i.push(py(n,z))}if(O.envFile){let z=Yn(L,".env");await el(z,O.envFile),i.push(py(n,z))}}return await Pi(n,{registry:x}),i.push("views/users.md"),{outputDir:n,changedFiles:[...new Set(i)].sort()}}var Due,Lue,Bue;var bM=v(()=>{Vn();zd();de();Xc();eA();iM();pM();gn();Cd();Ao();Due=c.strictObject({sites:c.record(br,Zk)}),Lue=c.object({handle:br,siteOverride:c.object({package:c.string().min(1),version:Ct.optional(),theme:c.string().min(1).optional(),themeVersion:Ct.optional()}).optional()}).passthrough(),Bue=Nue(new URL("../templates/rover-pilot/docs/canonical-crossover-record.md",import.meta.url))});var vM,que,Fue,Jue,zo,lp,Kue,AR,Hue,Vue,SM,Wue,Gue,wM,M1e,xM;var fy=v(()=>{WI();vM=["primary","secondary"],que=c.custom((e)=>typeof e==="function","Expected a React component"),Fue=c.strictObject({show:c.boolean().optional(),label:c.string().min(1).optional(),slot:c.enum(vM).optional(),priority:c.number().optional()}),Jue=c.strictObject({id:c.string().min(1),template:c.string().min(1),content:c.unknown().optional(),dataQuery:c.looseObject({entityType:c.string().optional(),template:c.string().optional(),query:c.record(c.string(),c.unknown()).optional()}).optional(),order:c.number().optional()}),zo=c.string().regex(/^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/,{message:"must be a language tag such as en or zh-TW"}),lp=c.strictObject({title:c.string().optional(),description:c.string().optional(),navigationLabel:c.string().optional()}),Kue=c.strictObject({id:c.string().min(1),path:c.string().startsWith("/"),title:c.string().optional(),pageLabel:c.string().optional(),description:c.string().optional(),sections:c.array(Jue).optional(),layout:c.string().min(1).optional(),fullscreen:c.boolean().optional(),pluginId:c.string().optional(),sourceEntityType:c.string().optional(),external:c.boolean().optional(),navigation:Fue.optional(),translations:c.record(zo,lp).optional()}),AR=c.strictObject({label:c.string().min(1),pluralName:c.string().min(1).optional(),layout:c.string().min(1).optional(),detailTemplate:c.string().min(1).optional(),paginate:c.boolean().optional(),pageSize:c.number().int().positive().optional(),citable:c.boolean().optional(),navigation:c.strictObject({show:c.boolean().optional(),slot:c.enum(vM).optional(),priority:c.number().optional()}).optional()}),Hue=c.strictObject({schema:c.custom((e)=>e instanceof c.ZodType,"Expected a Zod schema"),component:c.custom((e)=>typeof e==="function","Expected a React component"),title:c.string().min(1),description:c.string(),requiredPermission:c.enum(["admin","trusted","public"]).optional(),fullscreen:c.boolean().optional(),dataSource:c.string().min(1).optional()}),Vue=c.custom((e)=>typeof e==="object"&&e!==null&&Reflect.get(e,"kind")==="rizom-data-source"&&typeof Reflect.get(e,"id")==="string"&&typeof Reflect.get(e,"fetch")==="function","Expected a fetching data source declared with defineDataSource"),SM=c.strictObject({namespace:c.string().min(1),sections:c.record(c.string(),Hue)}),Wue=c.record(c.string(),c.json()),Gue=c.record(c.string(),c.record(c.string(),Wue)),wM={layouts:c.record(c.string(),que).refine((e)=>typeof e.default==="function",{message:'Site layouts must include a "default" component'}),routes:c.array(Kue),content:Gue.optional(),sections:c.union([SM,c.array(SM)]).optional(),themeOverride:c.string().optional(),headScripts:c.array(c.string()).optional(),entityDisplay:c.record(c.string(),AR),staticAssets:c.record(c.string(),c.string()).optional(),languages:c.array(zo).min(1).optional(),dataSources:c.array(Vue).readonly().optional()},M1e=c.strictObject(wM).partial(),xM=c.strictObject(wM).superRefine((e,t)=>{let r=e.languages??[],o=new Set;for(let[u,d]of r.entries()){let p=d.toLowerCase();if(o.has(p))t.addIssue({code:"custom",path:["languages",u],message:`Language "${d}" is declared twice`});o.add(p)}let n=r.slice(1).map((u)=>`/${u.toLowerCase()}`),i=new Set;for(let[u,d]of e.routes.entries()){if(i.has(d.id))t.addIssue({code:"custom",path:["routes",u,"id"],message:`Duplicate route id "${d.id}"`});i.add(d.id);let p=d.path.toLowerCase(),m=n.find((b)=>p===b||p.startsWith(`${b}/`));if(m)t.addIssue({code:"custom",path:["routes",u,"path"],message:`Route path "${d.path}" is under ${m}, where another language's pages are built`});let h=d.layout??"default";if(!e.layouts[h])t.addIssue({code:"custom",path:["routes",u,"layout"],message:`Unknown layout "${h}"`});for(let[b,y]of(d.sections??[]).entries()){let S=/^([^:.\s]+)\.([^:.\s]+)$/.exec(y.template);if(S)t.addIssue({code:"custom",path:["routes",u,"sections",b,"template"],message:`Section template "${y.template}" is written "${S[1]}:${S[2]}"`})}}let s=Array.isArray(e.sections)?e.sections:e.sections?[e.sections]:[],a=new Map(s.map((u)=>[u.namespace,u]));if(a.size!==s.length)t.addIssue({code:"custom",path:["sections"],message:"Section group namespaces must be unique"});let l=new Set;for(let[u,d]of(e.dataSources??[]).entries()){if(l.has(d.id))t.addIssue({code:"custom",path:["dataSources",u],message:`Data source "${d.id}" is declared twice`});l.add(d.id)}for(let u of s)for(let[d,p]of Object.entries(u.sections))if(p.dataSource&&!l.has(p.dataSource))t.addIssue({code:"custom",path:["sections",u.namespace,d,"dataSource"],message:`Section "${u.namespace}:${d}" reads data source "${p.dataSource}", which the site does not declare`});for(let[u,d]of Object.entries(e.content??{})){let p=a.get(u);if(!p){t.addIssue({code:"custom",path:["content",u],message:`Content namespace "${u}" has no section group`});continue}for(let[m,h]of Object.entries(d)){let b=p.sections[m];if(!b){t.addIssue({code:"custom",path:["content",u,m],message:`Content section "${u}:${m}" is not defined`});continue}let y=b.schema.safeParse(h);if(!y.success)t.addIssue({code:"custom",path:["content",u,m],message:`Content does not satisfy the "${u}:${m}" schema: ${c.prettifyError(y.error)}`})}}})});var _M,EM,IM,my,kM,Yue,AM,RM,Xue,TM,$M,ede,hy;var RR=v(()=>{Ot();de();fy();fy();_M=c.object({id:c.string(),template:c.string(),content:c.unknown().optional(),dataQuery:c.looseObject({entityType:c.string().optional(),template:c.string().optional(),query:c.looseObject({id:c.string().optional(),limit:c.number().optional(),offset:c.number().optional()}).optional()}).optional(),order:c.number().optional()}),EM=["primary","secondary"],IM=c.object({show:c.boolean().default(!1),label:c.string().optional(),slot:c.enum(EM).default("primary"),priority:c.number().min(0).max(100).default(50)}).optional(),my=c.object({id:c.string(),path:c.string(),title:c.string().default(""),pageLabel:c.string().optional(),description:c.string().default(""),sections:c.array(_M).default([]),layout:c.string().default("default"),fullscreen:c.boolean().optional(),pluginId:c.string().optional(),sourceEntityType:c.string().optional(),external:c.boolean().optional(),navigation:IM,translations:c.record(zo,lp).optional(),languages:c.array(zo).optional()}),kM=c.object({routes:c.array(my),pluginId:c.string()}),Yue=ve({channel:"plugin:site-builder:route:register",request:kM,response:c.void(),delivery:"command"}),AM=c.strictObject({}),RM=c.array(my),Xue=ve({channel:"site-builder:routes:list",request:AM,response:RM,delivery:"request"}),TM=c.strictObject({}),$M=c.array(my),ede=ve({channel:"plugin:site-builder:pages",request:TM,response:$M,delivery:"collect"}),hy=c.object({label:c.string(),href:c.string(),priority:c.number()})});var OM,CM,PM,tde;var zM=v(()=>{Ot();de();OM=c.object({pluginId:c.string(),slotName:c.string(),render:c.custom((e)=>typeof e==="function"),priority:c.number().optional()}),CM=c.strictObject({}),PM=c.array(OM),tde=ve({channel:"plugin:site-builder:slots",request:CM,response:PM,delivery:"collect"})});var NM="site:metadata:updated",gy,DM,LM,rl,BM,rde,nde,ode;var TR=v(()=>{Ot();de();RR();gy=c.object({heading:c.string().describe("Main CTA heading text"),subtitle:c.string().optional().describe("A line under the CTA heading"),buttonText:c.string().describe("Call-to-action button text"),buttonLink:c.string().describe("URL or anchor for the CTA button")}),DM=c.object({title:c.string().optional(),description:c.string().optional(),copyright:c.string().optional(),cta:gy.optional()}),LM=c.object({blurb:c.string().optional().describe("Short italic subtitle under the section title")}),rl=c.object({represents:c.enum(["brain","anchor"]).default("anchor").describe("Identity represented by the site"),title:c.string().describe("The site's title"),description:c.string().describe("The site's description"),url:c.string().optional().describe("Canonical site URL"),copyright:c.string().optional().describe("Copyright notice text"),logo:c.boolean().optional().describe("Whether to display logo instead of title text in header"),themeMode:c.enum(["light","dark"]).optional().describe("Default theme mode"),analyticsScript:c.string().optional().describe("Analytics script HTML"),cta:gy.optional().describe("Call-to-action configuration"),sections:c.record(c.string(),LM).optional().describe("Optional per-section blurbs, keyed by section id (e.g. 'essays', 'presentations', 'about'). Used by homepage templates that render editorial section headers."),translations:c.record(zo,DM).optional().describe("The site's title, description, copyright and call to action in its other languages, keyed by language tag. A site is built in a language only once it has one.")}),BM=c.strictObject({}),rde=ve({channel:"site:metadata:get",request:BM,response:rl,delivery:"request"}),nde=Ci(NM,rl),ode=rl.extend({copyright:c.string(),navigation:c.object({primary:c.array(hy),secondary:c.array(hy)}),socialLinks:c.array(Bk).optional().describe("Social media links from profile metadata"),photo:c.string().optional().describe("The anchor's photo, as ![alt](entity://image/<id>)")})});var nPe;var $R=v(()=>{de();nPe=c.record(c.string(),c.unknown())});var up=v(()=>{$R()});var jM=v(()=>{Ot();up()});var ZM=v(()=>{up();Ot()});var UM=v(()=>{up();Ot()});var SPe,vPe;var OR=v(()=>{de();SPe=c.record(c.string(),c.unknown()),vPe=c.object({label:c.string().optional(),line:c.boolean().optional(),itemTitle:c.string().optional(),itemLabel:c.string().optional()}).loose()});var _Pe;var MM=v(()=>{de();Pc();_Pe=c.record(c.string(),c.unknown())});var qM=v(()=>{Pc()});var JM=v(()=>{de();OR()});var CR=v(()=>{up();jM();ZM();UM();OR();MM();qM();JM();$R()});var gde;var KM=v(()=>{de();gde=c.object({slug:c.string(),title:c.string(),type:c.string(),entityId:c.string(),contentHash:c.string()})});var PR=v(()=>{CR();KM();CR()});var HM=v(()=>{PR();de()});var zR=()=>{};var yde,bde,Sde;var Sy=v(()=>{de();Ot();yde={url:c.string(),typeLabel:c.string(),listUrl:c.string(),listLabel:c.string()},bde={url:c.string().nullable().default(null),typeLabel:c.string().nullable().default(null),listUrl:c.string().nullable().default(null),listLabel:c.string().nullable().default(null)},Sde=c.object({name:c.string(),description:c.string(),schema:c.unknown(),basePrompt:c.string().optional(),useKnowledgeContext:c.boolean().optional(),requiredPermission:c.enum(["admin","trusted","public"]),formatter:c.unknown().optional(),overlayFormatter:c.unknown().optional(),layout:c.object({component:c.unknown().optional(),fullscreen:c.boolean().optional(),formats:c.unknown().optional()}).optional(),dataSourceId:c.string().optional()})});var vy=v(()=>{Sy()});var GM=v(()=>{vy()});var NR=()=>{};var wde,xde,nl,QM,_de;var YM=v(()=>{Ot();de();NR();wde=c.enum(["admin","trusted","public"]),xde=c.enum(["create","update","delete","extract","publish"]),nl=c.enum(["never","admin","trusted","public"]),QM=c.strictObject({create:nl.optional(),update:nl.optional(),delete:nl.optional(),extract:nl.optional(),publish:nl.optional()}),_de=c.record(c.string(),QM)});var XM=v(()=>{vy();Sy()});var Ede,Ide,wy,kde,Ade,Rde;var eq=v(()=>{de();Ede=c.enum(["site-content-preview","site-content-production"]),Ide=c.enum(["web","image","pdf","epub"]),wy=c.custom((e)=>typeof e==="function"),kde=c.object({name:c.string(),schema:c.unknown(),description:c.string().optional(),pluginId:c.string(),renderers:c.object({web:c.union([wy,c.string()]).optional(),image:c.union([wy,c.string()]).optional(),pdf:c.union([wy,c.string()]).optional(),epub:c.union([wy,c.string()]).optional()})}),Ade=c.object({enableContentGeneration:c.boolean().default(!1),outputDir:c.string(),workingDir:c.string().optional(),environment:c.enum(["preview","production"]).default("preview"),siteConfig:c.object({title:c.string(),description:c.string(),url:c.string().optional()}).optional()}),Rde=c.object({success:c.boolean(),routesBuilt:c.number(),errors:c.array(c.string()).optional(),warnings:c.array(c.string()).optional()})});var tq=v(()=>{Sy();GM();vy();YM();NR();XM();eq()});var DR=ge(function($de,xy){(function(){function e(g,E){Object.defineProperty(o.prototype,g,{get:function(){console.warn("%s(...) is deprecated in plain JavaScript React classes. %s",E[0],E[1])}})}function t(g){if(g===null||typeof g!=="object")return null;return g=De&&g[De]||g["@@iterator"],typeof g==="function"?g:null}function r(g,E){g=(g=g.constructor)&&(g.displayName||g.name)||"ReactClass";var D=g+"."+E;Qe[D]||(console.error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",E,g),Qe[D]=!0)}function o(g,E,D){this.props=g,this.context=E,this.refs=Dt,this.updater=D||bt}function n(){}function i(g,E,D){this.props=g,this.context=E,this.refs=Dt,this.updater=D||bt}function s(){}function a(g){return""+g}function l(g){try{a(g);var E=!1}catch(M){E=!0}if(E){E=console;var D=E.error,J=typeof Symbol==="function"&&Symbol.toStringTag&&g[Symbol.toStringTag]||g.constructor.name||"Object";return D.call(E,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",J),a(g)}}function u(g){if(g==null)return null;if(typeof g==="function")return g.$$typeof===$n?null:g.displayName||g.name||null;if(typeof g==="string")return g;switch(g){case H:return"Fragment";case re:return"Profiler";case G:return"StrictMode";case xe:return"Suspense";case Ae:return"SuspenseList";case Ue:return"Activity"}if(typeof g==="object")switch(typeof g.tag==="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),g.$$typeof){case N:return"Portal";case me:return g.displayName||"Context";case ae:return(g._context.displayName||"Context")+".Consumer";case be:var E=g.render;return g=g.displayName,g||(g=E.displayName||E.name||"",g=g!==""?"ForwardRef("+g+")":"ForwardRef"),g;case ke:return E=g.displayName||null,E!==null?E:u(g.type)||"Memo";case _e:E=g._payload,g=g._init;try{return u(g(E))}catch(D){}}return null}function d(g){if(g===H)return"<>";if(typeof g==="object"&&g!==null&&g.$$typeof===_e)return"<...>";try{var E=u(g);return E?"<"+E+">":"<...>"}catch(D){return"<...>"}}function p(){var g=Le.A;return g===null?null:g.getOwner()}function m(){return Error("react-stack-top-frame")}function h(g){if(ao.call(g,"key")){var E=Object.getOwnPropertyDescriptor(g,"key").get;if(E&&E.isReactWarning)return!1}return g.key!==void 0}function b(g,E){function D(){ls||(ls=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",E))}D.isReactWarning=!0,Object.defineProperty(g,"key",{get:D,configurable:!0})}function y(){var g=u(this.type);return us[g]||(us[g]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),g=this.props.ref,g!==void 0?g:null}function S(g,E,D,J,M,te){var se=D.ref;return g={$$typeof:q,type:g,key:E,props:D,_owner:J},(se!==void 0?se:null)!==null?Object.defineProperty(g,"ref",{enumerable:!1,get:y}):Object.defineProperty(g,"ref",{enumerable:!1,value:null}),g._store={},Object.defineProperty(g._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(g,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(g,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:M}),Object.defineProperty(g,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:te}),Object.freeze&&(Object.freeze(g.props),Object.freeze(g)),g}function x(g,E){return E=S(g.type,E,g.props,g._owner,g._debugStack,g._debugTask),g._store&&(E._store.validated=g._store.validated),E}function _(g){A(g)?g._store&&(g._store.validated=1):typeof g==="object"&&g!==null&&g.$$typeof===_e&&(g._payload.status==="fulfilled"?A(g._payload.value)&&g._payload.value._store&&(g._payload.value._store.validated=1):g._store&&(g._store.validated=1))}function A(g){return typeof g==="object"&&g!==null&&g.$$typeof===q}function O(g){var E={"=":"=0",":":"=2"};return"$"+g.replace(/[=:]/g,function(D){return E[D]})}function L(g,E){return typeof g==="object"&&g!==null&&g.key!=null?(l(g.key),O(""+g.key)):E.toString(36)}function z(g){switch(g.status){case"fulfilled":return g.value;case"rejected":throw g.reason;default:switch(typeof g.status==="string"?g.then(s,s):(g.status="pending",g.then(function(E){g.status==="pending"&&(g.status="fulfilled",g.value=E)},function(E){g.status==="pending"&&(g.status="rejected",g.reason=E)})),g.status){case"fulfilled":return g.value;case"rejected":throw g.reason}}throw g}function K(g,E,D,J,M){var te=typeof g;if(te==="undefined"||te==="boolean")g=null;var se=!1;if(g===null)se=!0;else switch(te){case"bigint":case"string":case"number":se=!0;break;case"object":switch(g.$$typeof){case q:case N:se=!0;break;case _e:return se=g._init,K(se(g._payload),E,D,J,M)}}if(se){se=g,M=M(se);var ye=J===""?"."+L(se,0):J;return Or(M)?(D="",ye!=null&&(D=ye.replace(Ea,"$&/")+"/"),K(M,E,D,"",function(Te){return Te})):M!=null&&(A(M)&&(M.key!=null&&(se&&se.key===M.key||l(M.key)),D=x(M,D+(M.key==null||se&&se.key===M.key?"":(""+M.key).replace(Ea,"$&/")+"/")+ye),J!==""&&se!=null&&A(se)&&se.key==null&&se._store&&!se._store.validated&&(D._store.validated=2),M=D),E.push(M)),1}if(se=0,ye=J===""?".":J+":",Or(g))for(var fe=0;fe<g.length;fe++)J=g[fe],te=ye+L(J,fe),se+=K(J,E,D,te,M);else if(fe=t(g),typeof fe==="function")for(fe===g.entries&&(Go||console.warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),Go=!0),g=fe.call(g),fe=0;!(J=g.next()).done;)J=J.value,te=ye+L(J,fe++),se+=K(J,E,D,te,M);else if(te==="object"){if(typeof g.then==="function")return K(z(g),E,D,J,M);throw E=String(g),Error("Objects are not valid as a React child (found: "+(E==="[object Object]"?"object with keys {"+Object.keys(g).join(", ")+"}":E)+"). If you meant to render a collection of children, use an array instead.")}return se}function P(g,E,D){if(g==null)return g;var J=[],M=0;return K(g,J,"","",function(te){return E.call(D,te,M++)}),J}function W(g){if(g._status===-1){var E=g._ioInfo;E!=null&&(E.start=E.end=performance.now()),E=g._result;var D=E();if(D.then(function(M){if(g._status===0||g._status===-1){g._status=1,g._result=M;var te=g._ioInfo;te!=null&&(te.end=performance.now()),D.status===void 0&&(D.status="fulfilled",D.value=M)}},function(M){if(g._status===0||g._status===-1){g._status=2,g._result=M;var te=g._ioInfo;te!=null&&(te.end=performance.now()),D.status===void 0&&(D.status="rejected",D.reason=M)}}),E=g._ioInfo,E!=null){E.value=D;var J=D.displayName;typeof J==="string"&&(E.name=J)}g._status===-1&&(g._status=0,g._result=D)}if(g._status===1)return E=g._result,E===void 0&&console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
405
405
 
406
406
  Your code should look like:
@@ -741,7 +741,7 @@ printf 'REMOTE_ARTIFACT_DIR=%s\\n' "$remote_dir"
741
741
  `).replace(/\\n/g,`
742
742
  `).trimEnd()}
743
743
  `}var Y8,Ege;var nO=v(async()=>{de();V8();gn();nf();Ys();await H8();Y8=c.object({HCLOUD_TOKEN:c.string().min(1),KAMAL_SSH_PRIVATE_KEY:c.string().min(1)}),Ege=c.object({servers:c.array(c.object({status:c.string(),public_net:c.object({ipv4:c.object({ip:c.string().min(1)})})}))})});import{parseArgs as ZJ}from"util";function nt(e){return e}class lf extends Error{constructor(e){super(e);this.name="CliUsageError"}}function UJ(e,t){let r={...t};for(let o of e)for(let[n,i]of Object.entries(o.flags??{})){let s=r[n];if(s===void 0){r[n]=i;continue}if(s.type!==i.type||s.short!==i.short||s.default!==i.default)throw Error(`Conflicting definitions for flag --${n}: commands must agree on type, short, and default`)}return r}function MJ(e){let t={};for(let[r,o]of Object.entries(e))t[r]={type:o.type,...o.short!==void 0?{short:o.short}:{},...o.default!==void 0?{default:o.default}:{}};return t}function qJ(e){if(!(e instanceof Error)||!("code"in e))return!1;return e.code==="ERR_PARSE_ARGS_UNKNOWN_OPTION"||e.code==="ERR_PARSE_ARGS_INVALID_OPTION_VALUE"}function sO(e,t){let r=UJ(t.commands,t.globalFlags??{}),o,n;try{({values:o,positionals:n}=ZJ({args:e,options:MJ(r),allowPositionals:!0,strict:t.strict??!0}))}catch(s){if(qJ(s))throw new lf(s.message.split(". ")[0]??s.message);throw s}if("help"in r&&o.help===!0)return{command:"help",args:[],flags:{help:!0}};if("version"in r&&o.version===!0)return{command:"version",args:[],flags:{version:!0}};let i={};for(let[s,a]of Object.entries(r)){let l=o[s];if(typeof l==="string"&&a.type==="string")i[s]=l;else if(typeof l==="boolean"&&a.type==="boolean")i[s]=l}return{command:n[0]??"help",args:n.slice(1),flags:i}}function aO(e){let t=e.reduce((r,o)=>Math.max(r,o.label.length),0);return e.map((r)=>` ${r.label.padEnd(t)} ${r.description}`)}function FJ(e){return aO(e.map((t)=>({label:t.usage?`${t.name} ${t.usage}`:t.name,description:t.description})))}function JJ(e,t){let r=t.type==="string"?` ${t.placeholder??"<value>"}`:"",o=t.short!==void 0?`, -${t.short}`:"";return`--${e}${r}${o}`}function cO(e){return aO(Object.entries(e).map(([t,r])=>({label:JJ(t,r),description:r.description})))}function lO(e,t){return`Usage: ${e} ${t.name}${t.usage?` ${t.usage}`:""}`}function KJ(e){return JSON.stringify(Object.entries(e).map(([t,r])=>[t,r.type,r.short??"",r.description,r.placeholder??"",r.default??""]).sort((t,r)=>String(t[0]).localeCompare(String(r[0]))))}function HJ(e){let t=[],r=new Map;for(let n of e){let i=n.flags??{};if(Object.keys(i).length===0)continue;let s=KJ(i),a=r.get(s);if(a){a.names.push(n.name);continue}let l={names:[n.name],flags:i};r.set(s,l),t.push(l)}let o=[];for(let n of t)o.push("",`${n.names.join(" / ")} options:`),o.push(...cO(n.flags));return o}function uO(e){let t=[e.intro,"",`Usage: ${e.cliName} ${e.usage??"<command> [args]"}`,"","Commands:",...FJ(e.commands)];if(e.globalFlags&&Object.keys(e.globalFlags).length>0)t.push("","Options:",...cO(e.globalFlags));return t.push(...HJ(e.commands)),t.join(`
744
- `)}function dO(e){let t=new Map;for(let r of e){if(t.has(r.name))throw Error(`Duplicate command name: ${r.name}`);t.set(r.name,r)}return t}function ot(e,t){let r=e[t];return typeof r==="string"?r:void 0}function ps(e,t){let r=e[t];return typeof r==="boolean"?r:void 0}var uf={name:"@rizom/ops",version:"0.2.0-alpha.768",description:"Operator CLI for managing private brain fleet registry repos",keywords:["brains","ops","cli","deploy","fleet","operator"],license:"AGPL-3.0-only",author:"Yeehaa <yeehaa@rizom.ai> (https://rizom.ai)",bin:{"brains-ops":"./dist/brains-ops.js"},bugs:"https://github.com/rizom-ai/brains/issues",dependencies:{"@libsql/client":"^0.17.4","age-encryption":"^0.3.0",yaml:"^2.9.0"},devDependencies:{"@brains/contracts":"workspace:*","@brains/deploy-support":"workspace:*","@brains/eslint-config":"workspace:*","@brains/job-queue":"workspace:*","@brains/profile":"workspace:*","@brains/site-composition":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@brains/utils":"workspace:*","@types/bun":"^1.4.0",typescript:"^7.0.2"},engines:{bun:">=1.3.3"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./deploy":{types:"./dist/deploy.d.ts",import:"./dist/deploy.js",bun:"./dist/deploy.js"}},files:["dist","templates"],homepage:"https://github.com/rizom-ai/brains/tree/main/packages/brains-ops#readme",main:"./dist/index.js",publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/rizom-ai/brains.git",directory:"packages/brains-ops"},scripts:{build:"bun scripts/build.ts",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",prepublishOnly:"bun scripts/build.ts",test:"bun test --timeout 20000","test:smoke":"bun run build && RUN_SMOKE_TESTS=1 bun test --timeout 60000",typecheck:"tsc --noEmit"},type:"module",types:"./dist/index.d.ts"};Cv();vi();import{writeFile as dX}from"fs/promises";import{join as Rj}from"path";import{createSign as NW,generateKeyPairSync as DW}from"crypto";import{mkdir as LW,writeFile as dD}from"fs/promises";import{join as pD}from"path";async function JV(e){let t=await e.text();if(!t.trim())return;try{return JSON.parse(t)}catch{return t}}async function Qa(e,t,r){let o=await JV(e),n=t.safeParse(o);if(!e.ok||!n.success){let i=r.formatError??KV;throw Error(`${r.label}${i(e,o)}`)}return n.data}function KV(e,t){let r=t===void 0?"":`: ${typeof t==="string"?t:JSON.stringify(t)}`;return` (${e.status} ${e.statusText}${r})`}de();var BW="2.5.4.3",jW="1.2.840.113549.1.1.11",hD="https://api.cloudflare.com/client/v4",ZW="origin-rsa",UW=5475,gD=15000;function yD(e){return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}var fD=c.looseObject({message:c.string().optional()}),MW=c.looseObject({errors:c.array(fD).optional(),messages:c.array(fD).optional()}),qW=c.looseObject({certificate:c.string().min(1),expires_on:c.string().optional()}),FW=c.looseObject({success:c.literal(!0),result:qW}),JW=c.looseObject({success:c.literal(!0)});function KW(){let{privateKey:e,publicKey:t}=DW("rsa",{modulusLength:2048,privateKeyEncoding:{type:"pkcs8",format:"pem"},publicKeyEncoding:{type:"spki",format:"der"}});return{privateKeyPem:e,publicKeyDer:Buffer.from(t)}}function HW(e,t){let r=wd(eG(wd(mD(BW),QW(e)))),o=wd(GW(0),r,Buffer.from(t.publicKeyDer),tG(0,Buffer.alloc(0))),n=NW("sha256").update(o).sign(t.privateKeyPem),i=wd(o,wd(mD(jW),XW()),YW(n));return{csrPem:WW("CERTIFICATE REQUEST",i),certificationRequestInfoDer:o,signature:n}}async function VW(e,t,r,o){let n=await e(`${hD}/certificates`,{method:"POST",headers:yD(t),body:JSON.stringify({hostnames:[o,`*.${o}`],requested_validity:UW,request_type:ZW,csr:r}),signal:AbortSignal.timeout(gD)}),i=await Qa(n,FW,{label:"Cloudflare Origin CA request failed",formatError:SD}),a={certificatePem:`${i.result.certificate.trim()}
744
+ `)}function dO(e){let t=new Map;for(let r of e){if(t.has(r.name))throw Error(`Duplicate command name: ${r.name}`);t.set(r.name,r)}return t}function ot(e,t){let r=e[t];return typeof r==="string"?r:void 0}function ps(e,t){let r=e[t];return typeof r==="boolean"?r:void 0}var uf={name:"@rizom/ops",version:"0.2.0-alpha.769",description:"Operator CLI for managing private brain fleet registry repos",keywords:["brains","ops","cli","deploy","fleet","operator"],license:"AGPL-3.0-only",author:"Yeehaa <yeehaa@rizom.ai> (https://rizom.ai)",bin:{"brains-ops":"./dist/brains-ops.js"},bugs:"https://github.com/rizom-ai/brains/issues",dependencies:{"@libsql/client":"^0.17.4","age-encryption":"^0.3.0",yaml:"^2.9.0"},devDependencies:{"@brains/contracts":"workspace:*","@brains/deploy-support":"workspace:*","@brains/eslint-config":"workspace:*","@brains/job-queue":"workspace:*","@brains/profile":"workspace:*","@brains/site-composition":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@brains/utils":"workspace:*","@types/bun":"^1.4.0",typescript:"^7.0.2"},engines:{bun:">=1.3.3"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./deploy":{types:"./dist/deploy.d.ts",import:"./dist/deploy.js",bun:"./dist/deploy.js"}},files:["dist","templates"],homepage:"https://github.com/rizom-ai/brains/tree/main/packages/brains-ops#readme",main:"./dist/index.js",publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/rizom-ai/brains.git",directory:"packages/brains-ops"},scripts:{build:"bun scripts/build.ts",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",prepublishOnly:"bun scripts/build.ts",test:"bun test --timeout 20000","test:smoke":"bun run build && RUN_SMOKE_TESTS=1 bun test --timeout 60000",typecheck:"tsc --noEmit"},type:"module",types:"./dist/index.d.ts"};Cv();vi();import{writeFile as dX}from"fs/promises";import{join as Rj}from"path";import{createSign as NW,generateKeyPairSync as DW}from"crypto";import{mkdir as LW,writeFile as dD}from"fs/promises";import{join as pD}from"path";async function JV(e){let t=await e.text();if(!t.trim())return;try{return JSON.parse(t)}catch{return t}}async function Qa(e,t,r){let o=await JV(e),n=t.safeParse(o);if(!e.ok||!n.success){let i=r.formatError??KV;throw Error(`${r.label}${i(e,o)}`)}return n.data}function KV(e,t){let r=t===void 0?"":`: ${typeof t==="string"?t:JSON.stringify(t)}`;return` (${e.status} ${e.statusText}${r})`}de();var BW="2.5.4.3",jW="1.2.840.113549.1.1.11",hD="https://api.cloudflare.com/client/v4",ZW="origin-rsa",UW=5475,gD=15000;function yD(e){return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}var fD=c.looseObject({message:c.string().optional()}),MW=c.looseObject({errors:c.array(fD).optional(),messages:c.array(fD).optional()}),qW=c.looseObject({certificate:c.string().min(1),expires_on:c.string().optional()}),FW=c.looseObject({success:c.literal(!0),result:qW}),JW=c.looseObject({success:c.literal(!0)});function KW(){let{privateKey:e,publicKey:t}=DW("rsa",{modulusLength:2048,privateKeyEncoding:{type:"pkcs8",format:"pem"},publicKeyEncoding:{type:"spki",format:"der"}});return{privateKeyPem:e,publicKeyDer:Buffer.from(t)}}function HW(e,t){let r=wd(eG(wd(mD(BW),QW(e)))),o=wd(GW(0),r,Buffer.from(t.publicKeyDer),tG(0,Buffer.alloc(0))),n=NW("sha256").update(o).sign(t.privateKeyPem),i=wd(o,wd(mD(jW),XW()),YW(n));return{csrPem:WW("CERTIFICATE REQUEST",i),certificationRequestInfoDer:o,signature:n}}async function VW(e,t,r,o){let n=await e(`${hD}/certificates`,{method:"POST",headers:yD(t),body:JSON.stringify({hostnames:[o,`*.${o}`],requested_validity:UW,request_type:ZW,csr:r}),signal:AbortSignal.timeout(gD)}),i=await Qa(n,FW,{label:"Cloudflare Origin CA request failed",formatError:SD}),a={certificatePem:`${i.result.certificate.trim()}
745
745
  `};if(i.result.expires_on)a.expiresOn=i.result.expires_on;return a}async function bD(e,t,r){let o=await e(`${hD}/zones/${r}/settings/ssl`,{method:"PATCH",headers:yD(t),body:JSON.stringify({value:"strict"}),signal:AbortSignal.timeout(gD)});await Qa(o,JW,{label:"Cloudflare zone SSL update failed",formatError:SD})}function WW(e,t){let o=t.toString("base64").match(/.{1,64}/g)??[];return[`-----BEGIN ${e}-----`,...o,`-----END ${e}-----`,""].join(`
746
746
  `)}function GW(e){if(e!==0)throw Error("Only zero-valued INTEGER encoding is currently supported");return Buffer.from([2,1,0])}function mD(e){let t=e.split(".").map((s)=>Number(s));if(t.length<2||t.some((s)=>Number.isNaN(s)))throw Error(`Invalid OID: ${e}`);let r=t[0],o=t[1];if(r===void 0||o===void 0)throw Error(`Invalid OID: ${e}`);let i=[r*40+o];for(let s of t.slice(2)){let a=nG(s);i.push(...a)}return Tc(6,Buffer.from(i))}function QW(e){return Tc(12,Buffer.from(e,"utf8"))}function YW(e){return Tc(3,Buffer.concat([Buffer.from([0]),e]))}function XW(){return Buffer.from([5,0])}function wd(...e){return Tc(48,Buffer.concat(e))}function eG(...e){return Tc(49,Buffer.concat(e))}function tG(e,t){return Tc(160+e,t)}function Tc(e,t){return Buffer.concat([Buffer.from([e]),rG(t.length),t])}function rG(e){if(e<128)return Buffer.from([e]);let t=[],r=e;while(r>0)t.unshift(r&255),r>>=8;return Buffer.from([128|t.length,...t])}function nG(e){if(!Number.isInteger(e)||e<0)throw Error(`Invalid OID component: ${e}`);if(e===0)return[0];let t=[],r=e;while(r>0)t.unshift(r&127),r>>=7;for(let o=0;o<t.length-1;o+=1)t[o]=(t[o]??0)|128;return t}function SD(e,t){let r=oG(t),o=r.length>0?`: ${r.join("; ")}`:"";return` (${e.status} ${e.statusText}${o})`}function oG(e){let t=MW.safeParse(e);if(!t.success)return[];return[...t.data.errors??[],...t.data.messages??[]].map((r)=>r.message).filter((r)=>typeof r==="string"&&r.length>0)}async function vD(e,t,r){let o=KW(),{csrPem:n}=HW(r,o),i=await VW(e,t,n,r);return{certificatePem:i.certificatePem,privateKeyPem:o.privateKeyPem,...i.expiresOn!==void 0&&{expiresOn:i.expiresOn}}}async function wD(e,t){let r=pD(e,"origin.pem"),o=pD(e,"origin.key");return await LW(e,{recursive:!0}),await Promise.all([dD(r,t.certificatePem,"utf-8"),dD(o,t.privateKeyPem,{encoding:"utf-8",mode:384})]),{certificatePath:r,privateKeyPath:o}}gn();Cu();Mn();async function $j(e,t={}){try{return await pX(e,t),{success:!0}}catch(r){return{success:!1,message:Ve(r,"Certificate bootstrap failed")}}}async function pX(e,t={}){let r=await wt(e),o=mX(r,t.handle),n=o.domain,i=t.env??process.env,s=Lr(e),a=t.cfApiToken??jt("CF_API_TOKEN",i,s),l=t.cfZoneId??o.cloudflareZoneId??jt("CF_ZONE_ID",i,s);if(!a)throw Error("Missing CF_API_TOKEN");if(!l)throw Error("Missing CF_ZONE_ID");let u=t.fetchImpl??fetch,d=t.logger??console.log,p=await vD(u,a,n),m=Rj(e,".brains-ops","certs",o.id),{certificatePath:h,privateKeyPath:b}=await wD(m,p),y=Rj(m,"secrets.yaml");await dX(y,fX(p.certificatePem,p.privateKeyPem),"utf-8"),await bD(u,a,l);let S=Wa(t.pushTo);if(S)await bi([["CERTIFICATE_PEM",p.certificatePem],["PRIVATE_KEY_PEM",p.privateKeyPem]],{logger:d,runCommand:t.runCommand??tr});if(d(`Issued ${o.id} Origin CA cert for ${n} and *.${n}`),d(`Wrote ${h}`),d(`Wrote ${b}`),d(`Wrote ${y}`),p.expiresOn)d(`Expires on ${p.expiresOn}`);if(d("Cloudflare zone SSL mode set to Full (strict)"),S)d(`Pushed CERTIFICATE_PEM and PRIVATE_KEY_PEM to ${S}`);return{domain:n,certificatePath:h,privateKeyPath:b,certificatePem:p.certificatePem,secretsSnippetPath:y}}function fX(e,t){return[`certificatePem: ${Tj(e)}`,`privateKeyPem: ${Tj(t)}`,""].join(`
747
747
  `)}function Tj(e){return`"${e.replace(/"/g,"\\\"").replace(/\n/g,"\\n")}"`}function mX(e,t){if(!t)return{id:"shared",domain:hX(e.pilot.domainSuffix)};let r=e.users.find((o)=>o.handle===t);if(!r)throw Error(`Unknown user handle: ${t}`);return{id:t,domain:r.domain,...r.cloudflareZoneId?{cloudflareZoneId:r.cloudflareZoneId}:{}}}function hX(e){let t=e.trim().replace(/^\./,"").replace(/\.$/,"");if(!t||t.includes("*"))throw Error(`Invalid pilot domainSuffix: ${e}`);return t}import{chmod as qk,mkdir as cg,readFile as Pj,writeFile as Cj}from"fs/promises";import{dirname as vX,join as jc}from"path";import{fileURLToPath as wX}from"url";vi();Cd();Ys();var xX=["pilot.yaml","package.json",".env.schema",".gitignore","cohorts/cohort-1.yaml","users/alice.yaml",".github/actions/varlock-env/action.yml",".github/workflows/build.yml",".github/workflows/deploy.yml",".github/workflows/directory-sync-stress.yml",".github/workflows/health-watchdog-smoke.yml",".github/workflows/offboard.yml",".github/workflows/reconcile.yml",".github/workflows/upgrade.yml","deploy/Dockerfile","deploy/kamal/deploy.yml","deploy/scripts/helpers.ts","deploy/scripts/create-predeploy-backup.ts","deploy/scripts/install-health-watchdog.ts","deploy/scripts/provision-server.ts","deploy/scripts/pull-local-models.ts","deploy/scripts/update-dns.ts","deploy/scripts/write-ssh-key.ts","deploy/scripts/decrypt-user-secrets.ts","deploy/scripts/validate-secrets.ts","deploy/scripts/write-kamal-secrets.ts","deploy/scripts/resolve-user-config.ts","deploy/scripts/resolve-missing-images.ts","deploy/scripts/verify-runtime-image.ts","deploy/scripts/resolve-deploy-handles.ts","deploy/scripts/sync-content-repo.ts",".kamal/hooks/pre-deploy","docs/onboarding-checklist.md","docs/canonical-crossover-record.md","docs/operator-playbook.md","docs/user-onboarding.md","README.md"],Fk=new Set([".kamal/hooks/pre-deploy"]),_X=new Set(["cohorts/cohort-1.yaml","users/alice.yaml","docs/canonical-crossover-record.md"]),EX=wX(new URL("../templates/rover-pilot/",import.meta.url));function Ro(e){return(t)=>t.includes(e)}function IX(e){return XP.find((t)=>e===`deploy/scripts/${t}`)}function Jk(e){return e.replace(/\n {2}secret:\n(?: {4}- .*\n)+\nvolumes:\n/,`
package/dist/index.js CHANGED
@@ -423,7 +423,7 @@ agePublicKey: ${t}
423
423
  `;ZR(e,i,"utf8")}function nl(e){let t=e.split(/\r?\n/).map((r)=>r.trim()).find((r)=>r.startsWith("AGE-SECRET-KEY-"));if(!t)throw Error("Missing AGE-SECRET-KEY in age identity file");return t}function oue(e,t){return["# generated by brains-ops age-key:bootstrap",`# public key: ${t}`,e,""].join(`
424
424
  `)}var wy=v(()=>{Mi();lp();Un()});function MM(e){return Object.keys(e)}import{readFileSync as fp}from"fs";import{rm as Xue,writeFile as JM}from"fs/promises";import{join as FR,relative as qM}from"path";async function HR(e,t,r={}){let{registry:o,user:n}=await $h(e,t),i=r.env??process.env,s=r.logger??console.log,a=Cr(e),l=FR(e,"users",`${t}.secrets.yaml.age`),u=FR(e,"users",`${t}.secrets.yaml`),d=pc(qM(e,l)),p=pc(qM(e,u)),m=rde(u),h=await nde(l,e,i,a),b=await Er(u),y={sharedOpenaiApiKeySelector:o.pilot.openaiApiKey,sharedGitSyncTokenSelector:o.pilot.gitSyncToken,effectiveOpenaiApiKeySelector:n.effectiveOpenaiApiKey,effectiveGitSyncTokenSelector:n.effectiveGitSyncToken,discordEnabled:n.discordEnabled},S;try{S=ede(e,i,a,m,h,y)}catch(z){if(!r.dryRun&&m===void 0&&z instanceof Error){let J=ide(y);if(J.length>0)throw await sde(u,J),Error(`Missing required secrets for ${t}. Created ${p}; fill it in and rerun secrets:encrypt. ${z.message}`,{cause:z})}throw z}let x=`${Oa(S).trimEnd()}
425
425
  `;ode(x,S);let _=MM(S);if(r.dryRun){if(s(`Dry run: would encrypt ${_.length} secrets to ${d}.`),s(_.length>0?`Keys: ${_.join(", ")}`:"Keys: (none \u2014 shared defaults only)"),b)s(`Would remove plaintext file ${p}.`);return{encryptedPath:d,plaintextPath:p,deletedPlaintext:b,encryptedKeys:_,dryRun:!0}}let A=new ap;A.addRecipient(o.pilot.agePublicKey);let O=await A.encrypt(x),L=qi.encode(O);if(await JM(l,L),await Xue(u,{force:!0}),s(`Encrypted ${_.length} secrets to ${d}.`),b)s(`Removed plaintext file ${p}.`);return{encryptedPath:d,plaintextPath:p,deletedPlaintext:b,encryptedKeys:_}}function ede(e,t,r,o,n,i){let s=FM(e,t,r,o,n,"openaiApiKey",i.effectiveOpenaiApiKeySelector,i.sharedOpenaiApiKeySelector),a=FM(e,t,r,o,n,"gitSyncToken",i.effectiveGitSyncTokenSelector,i.sharedGitSyncTokenSelector),l=i.discordEnabled?xy(e,t,r,o,n,"discordBotToken","DISCORD_BOT_TOKEN"):void 0,u=i.discordEnabled?xy(e,t,r,o,n,"discordPublicKey","DISCORD_PUBLIC_KEY"):void 0,d=i.discordEnabled?xy(e,t,r,o,n,"discordApplicationId","DISCORD_APPLICATION_ID"):void 0,p=_y(e,t,r,o,n,"atprotoAppPassword","ATPROTO_APP_PASSWORD"),m=HM(_y(e,t,r,o,n,"certificatePem","CERTIFICATE_PEM")),h=HM(_y(e,t,r,o,n,"privateKeyPem","PRIVATE_KEY_PEM"));return KM.parse({...s?{openaiApiKey:s}:{},...a?{gitSyncToken:a}:{},...l?{discordBotToken:l}:{},...u?{discordPublicKey:u}:{},...d?{discordApplicationId:d}:{},...p?{atprotoAppPassword:p}:{},...m?{certificatePem:m}:{},...h?{privateKeyPem:h}:{}})}function FM(e,t,r,o,n,i,s,a){if(s===a)return;return xy(e,t,r,o,n,i,s)}function xy(e,t,r,o,n,i,s){let a=_y(e,t,r,o,n,i,s);if(a===void 0||a.trim().length===0)throw Error(`Missing required secret value for ${String(i)}. Set it in users/<handle>.secrets.yaml or fall back to ${s}/${s}_FILE before running secrets:encrypt.`);return a}function HM(e){return e?.replace(/\r\n?|\n/g,"\\n")}function _y(e,t,r,o,n,i,s){return tde(o,n,i,s,t,r,e)}function tde(e,t,r,o,n,i,s){let a=e?.[r];if(a!==void 0&&a.trim().length>0)return a;let l=Bt(`${o}_FILE`,n,i);if(l&&l.trim().length>0)return fp(Yo(l,s),"utf8");let u=Bt(o,n,i);if(u!==void 0&&u.trim().length>0)return u;let d=t?.[r];if(d!==void 0&&d.trim().length>0)return d;return}function rde(e){let t;try{t=fp(e,"utf8")}catch{return}try{return KR(t)}catch(r){throw Error(`Unable to parse plaintext secrets file ${e}: ${Ve(r)}`,{cause:r})}}async function nde(e,t,r,o){if(!await Er(e))return;let n=JR(t,r,o);if(!n)return;let i;try{let s=fp(e,"utf8"),a=qi.decode(s),l=new cp;l.addIdentity(n),i=await l.decrypt(a,"text")}catch{return}try{return KR(i)}catch(s){throw Error(`Unable to parse decrypted secrets from ${e}: ${Ve(s)}`,{cause:s})}}function JR(e,t,r){let o=Bt("AGE_SECRET_KEY_FILE",t,r);if(o&&o.trim().length>0)return nl(fp(Yo(o,e),"utf8"));let n=Bt("AGE_SECRET_KEY",t,r);if(n&&n.trim().length>0)return nl(n);try{return nl(fp(FR(e,".brains-ops","age","identity.txt"),"utf8"))}catch{return}}function KR(e){let t=_C(e),r={};if(t!==null&&typeof t==="object"&&!Array.isArray(t)){for(let[o,n]of Object.entries(t))if(typeof n==="string")r[o]=n}return KM.partial().parse(r)}function ode(e,t){let r={...t},o={...KR(e)},n=new Set([...Object.keys(r),...Object.keys(o)]);for(let i of n)if(r[i]!==o[i])throw Error(`secrets:encrypt round-trip verification failed for ${i}; refusing to write a corrupted encrypted payload`)}function ide(e){return[...e.effectiveOpenaiApiKeySelector!==e.sharedOpenaiApiKeySelector?["openaiApiKey"]:[],...e.effectiveGitSyncTokenSelector!==e.sharedGitSyncTokenSelector?["gitSyncToken"]:[],...e.discordEnabled?["discordBotToken","discordPublicKey","discordApplicationId"]:[]]}async function sde(e,t){let r=["# local per-user secret staging file","# fill values, run `bunx brains-ops secrets:encrypt . <handle>`, then the plaintext file will be removed",...t.map((o)=>`${o}: `),""].join(`
426
- `);await JM(e,r,{flag:"wx"})}var KM;var Ey=v(()=>{Mi();Xo();Pn();de();wy();Gu();Rs();KM=c.strictObject({gitSyncToken:c.string().min(1).optional(),discordBotToken:c.string().min(1).optional(),discordPublicKey:c.string().min(1).optional(),discordApplicationId:c.string().min(1).optional(),openaiApiKey:c.string().min(1).optional(),atprotoAppPassword:c.string().min(1).optional(),certificatePem:c.string().min(1).optional(),privateKeyPem:c.string().min(1).optional()})});var XM={};Lt(XM,{upgradePilotRepo:()=>Ode});import{readFile as Ade}from"fs/promises";import{join as Rde}from"path";async function YM(e){let t=Rde(e,"package.json"),o=Tde.parse(JSON.parse(await Ade(t,"utf8"))).devDependencies?.["@rizom/ops"];if(!o)throw Error(`${t} does not pin @rizom/ops as a devDependency`);return o}async function $de(e,t){let o=await Bun.spawn(e,{cwd:t,stdout:"inherit",stderr:"inherit"}).exited;if(o!==0)throw Error(`${e.join(" ")} failed with exit ${o}`)}async function Ode(e,t={}){let r=t.exec??$de,o=await YM(e),n=t.version??"latest";await r(["bun","add","--dev","--exact",`@rizom/ops@${n}`],e);let i=await YM(e);return await r(["bun","x","brains-ops","init","."],e),{from:o,to:i}}var Tde;var eq=v(()=>{de();Tde=c.object({devDependencies:c.record(c.string(),c.string()).optional()})});var oq={};Lt(oq,{migratePilotDeploySecrets:()=>rq,migratePilotEnvSchema:()=>nq,migratePilotRepoProviderKeys:()=>jde,migrateProviderKeyFieldsYaml:()=>eT,openaiSelectorFor:()=>tT,renameProviderKeyFields:()=>Hi});import{readdir as Cde,readFile as YR,writeFile as tq}from"fs/promises";import{join as Do}from"path";function eT(e){let t=Gr(e,{keepSourceTokens:!0});return Hi(t)?t.toString({lineWidth:0}):e}function Hi(e){if(!hn(e.contents))return!1;return e.contents.items.filter((r)=>{if(!vo(r.key)||typeof r.key.value!=="string")return!1;let o=Pde[r.key.value];if(!o)return!1;if(r.key.value==="aiApiKey"&&vo(r.value)&&r.value.value===Ry)r.value.value=Ty;return r.key.value=o,!0}).length>0}function tT(e){return e===Ry?Ty:e}function rq(e){return e.replace(new RegExp(`^(\\s+- )${Ry}$`,"m"),`$1${Ty}`)}function nq(e){return e.replace(new RegExp(`^${Ry}=`,"m"),`${Ty}=`)}async function Ay(e){try{return(await Cde(e)).filter((r)=>r.endsWith(".yaml")).sort()}catch{return[]}}async function XR(e){try{return await YR(e,"utf8")}catch{return}}async function Lde(e){let t=await Ay(Do(e,"cohorts")),r=await Promise.all(t.map(async(i)=>{let s=lr(await YR(Do(e,"cohorts",i),"utf8"),Nde);return s.ok&&s.data.aiApiKeyOverride?s.data.members:[]})),o=(await Ay(Do(e,"users"))).filter((i)=>!i.endsWith(".secrets.yaml")),n=await Promise.all(o.map(async(i)=>{let s=lr(await YR(Do(e,"users",i),"utf8"),zde);return s.ok&&s.data.aiApiKeyOverride?[i.replace(/\.yaml$/,"")]:[]}));return[...new Set([...r.flat(),...n.flat()])]}async function Bde(e,t,r,o){let n=Do(e,"users",`${t}.secrets.yaml.age`),i=await XR(n);if(i===void 0)return!1;if(!r)throw Error(`users/${t}.secrets.yaml.age may hold the legacy AI key; set AGE_SECRET_KEY or AGE_SECRET_KEY_FILE to migrate it`);let s=new cp;s.addIdentity(r);let a=await s.decrypt(qi.decode(i),"text"),l=eT(a);if(l===a)return!1;let u=new ap;return u.addRecipient(o),await tq(n,qi.encode(await u.encrypt(l))),!0}async function jde(e,t){let r=["pilot.yaml",...(await Ay(Do(e,"cohorts"))).map((l)=>`cohorts/${l}`),...(await Ay(Do(e,"users"))).filter((l)=>!l.endsWith(".secrets.yaml")).map((l)=>`users/${l}`)],o=await Lde(e),n=await Promise.all([...r.map((l)=>({file:l,migrate:eT})),{file:".env.schema",migrate:nq},{file:"deploy/kamal/deploy.yml",migrate:rq}].map(async({file:l,migrate:u})=>{let d=Do(e,l),p=await XR(d);if(p===void 0)return[];let m=u(p);if(m===p)return[];return await tq(d,m),[l]})),i=lr(await XR(Do(e,"pilot.yaml"))??"",Dde),s=JR(e,t,Cr(e)),a=o.length===0?[]:await Promise.all(o.map(async(l)=>{if(!i.ok)throw Error("pilot.yaml needs agePublicKey to re-encrypt secrets");return await Bde(e,l,s,i.data.agePublicKey)?[`users/${l}.secrets.yaml.age`]:[]}));return[...n.flat(),...a.flat()]}var Ry="AI_API_KEY",Ty="OPENAI_API_KEY",Pde,zde,Nde,Dde;var $y=v(()=>{Mi();Xo();Pn();de();$c();Ey();Pde={aiApiKey:"openaiApiKey",aiApiKeyOverride:"openaiApiKeyOverride"};zde=c.looseObject({aiApiKeyOverride:c.string().optional()}),Nde=c.looseObject({members:c.array(c.string()).default([]),aiApiKeyOverride:c.string().optional()}),Dde=c.looseObject({agePublicKey:c.string()})});function cq(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:[...Mde]};return{bundles:["core","media","automation","web","chat","site","publishing","federation"],add:["obsidian-vault"]}}function qde(e){let t=Zde.parse(e);return fi.parse({brainVersion:t.brainVersion,bundleContract:pi,...cq(t.preset),githubOrg:t.githubOrg,contentRepoPrefix:t.contentRepoPrefix,domainSuffix:t.domainSuffix,openaiApiKey:tT(t.aiApiKey),gitSyncToken:t.gitSyncToken,contentRepoAdminToken:t.contentRepoAdminToken,agePublicKey:t.agePublicKey})}function Fde(e){let t=Ude.parse(e),r=t.presetOverride?cq(t.presetOverride):void 0;return Jr.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?{openaiApiKeyOverride:t.aiApiKeyOverride}:{},...t.gitSyncTokenOverride?{gitSyncTokenOverride:t.gitSyncTokenOverride}:{}})}function lq(e){let t=Gr(e,{keepSourceTokens:!0});if(t.errors.length>0)throw Error(`Invalid desired-state YAML: ${t.errors[0]?.message}`);if(!hn(t.contents))throw Error("Desired-state YAML must contain a mapping");return t}function rT(e,t){if(!hn(e.contents))return;return e.contents.items.find((r)=>vo(r.key)&&r.key.value===t)}function iq(e,t){if(!So(e)||!So(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 sq(e,t){if(!e||!So(t))return;let r=[So(e.key)?e.key.commentBefore:void 0,So(e.key)?e.key.comment:void 0,So(e.value)?e.value.commentBefore:void 0,So(e.value)?e.value.comment:void 0].filter((o)=>o!==void 0);if(r.length===0)return;t.commentBefore=[t.commentBefore,...r].filter((o)=>o!==void 0).join(`
426
+ `);await JM(e,r,{flag:"wx"})}var KM;var Ey=v(()=>{Mi();Xo();Pn();de();wy();Gu();Rs();KM=c.strictObject({gitSyncToken:c.string().min(1).optional(),discordBotToken:c.string().min(1).optional(),discordPublicKey:c.string().min(1).optional(),discordApplicationId:c.string().min(1).optional(),openaiApiKey:c.string().min(1).optional(),atprotoAppPassword:c.string().min(1).optional(),certificatePem:c.string().min(1).optional(),privateKeyPem:c.string().min(1).optional()})});var XM={};Lt(XM,{upgradePilotRepo:()=>Ode});import{readFile as Ade}from"fs/promises";import{join as Rde}from"path";async function YM(e){let t=Rde(e,"package.json"),o=Tde.parse(JSON.parse(await Ade(t,"utf8"))).devDependencies?.["@rizom/ops"];if(!o)throw Error(`${t} does not pin @rizom/ops as a devDependency`);return o}async function $de(e,t){let o=await Bun.spawn(e,{cwd:t,stdout:"inherit",stderr:"inherit"}).exited;if(o!==0)throw Error(`${e.join(" ")} failed with exit ${o}`)}async function Ode(e,t={}){let r=t.exec??$de,o=await YM(e),n=t.version??"latest";await r(["bun","add","--dev","--exact",`@rizom/ops@${n}`],e);let i=await YM(e);return await r(["bun","x","brains-ops","init","."],e),{from:o,to:i}}var Tde;var eq=v(()=>{de();Tde=c.object({devDependencies:c.record(c.string(),c.string()).optional()})});var oq={};Lt(oq,{migratePilotDeploySecrets:()=>rq,migratePilotEnvSchema:()=>nq,migratePilotRepoProviderKeys:()=>jde,migrateProviderKeyFieldsYaml:()=>eT,openaiSelectorFor:()=>tT,renameProviderKeyFields:()=>Hi});import{readdir as Cde,readFile as YR,writeFile as tq}from"fs/promises";import{join as Do}from"path";function eT(e){let t=Gr(e,{keepSourceTokens:!0});return Hi(t)?t.toString({lineWidth:0}):e}function Hi(e){if(!hn(e.contents))return!1;return e.contents.items.filter((r)=>{if(!vo(r.key)||typeof r.key.value!=="string")return!1;let o=Pde[r.key.value];if(!o)return!1;if(r.key.value==="aiApiKey"&&vo(r.value)&&r.value.value===Ry)r.value.value=Ty;return r.key.value=o,!0}).length>0}function tT(e){return e===Ry?Ty:e}function rq(e){return e.replace(new RegExp(`^(\\s+- )${Ry}$`,"m"),`$1${Ty}`)}function nq(e){return e.replace(new RegExp(`^${Ry}=`,"m"),`${Ty}=`)}async function Ay(e){try{return(await Cde(e)).filter((r)=>r.endsWith(".yaml")).sort()}catch{return[]}}async function XR(e){try{return await YR(e,"utf8")}catch{return}}async function Lde(e){let t=await Ay(Do(e,"cohorts")),r=await Promise.all(t.map(async(i)=>{let s=lr(await YR(Do(e,"cohorts",i),"utf8"),Nde);return s.ok&&s.data.aiApiKeyOverride?s.data.members:[]})),o=(await Ay(Do(e,"users"))).filter((i)=>!i.endsWith(".secrets.yaml")),n=await Promise.all(o.map(async(i)=>{let s=lr(await YR(Do(e,"users",i),"utf8"),zde);return s.ok&&s.data.aiApiKeyOverride?[i.replace(/\.yaml$/,"")]:[]}));return[...new Set([...r.flat(),...n.flat()])]}async function Bde(e,t,r,o){let n=Do(e,"users",`${t}.secrets.yaml.age`),i=await XR(n);if(i===void 0)return!1;if(!r)throw Error(`users/${t}.secrets.yaml.age may hold the legacy AI key; set AGE_SECRET_KEY or AGE_SECRET_KEY_FILE to migrate it`);let s=new cp;s.addIdentity(r);let a=await s.decrypt(qi.decode(i),"text"),l=eT(a);if(l===a)return!1;let u=new ap;return u.addRecipient(o),await tq(n,qi.encode(await u.encrypt(l))),!0}async function jde(e,t){let r=["pilot.yaml",...(await Ay(Do(e,"cohorts"))).map((l)=>`cohorts/${l}`),...(await Ay(Do(e,"users"))).filter((l)=>!l.endsWith(".secrets.yaml")).map((l)=>`users/${l}`)],o=await Lde(e),n=await Promise.all([...r.map((l)=>({file:l,migrate:eT})),{file:".env.schema",migrate:nq},{file:"deploy/kamal/deploy.yml",migrate:rq}].map(async({file:l,migrate:u})=>{let d=Do(e,l),p=await XR(d);if(p===void 0)return[];let m=u(p);if(m===p)return[];return await tq(d,m),[l]})),i=lr(await XR(Do(e,"pilot.yaml"))??"",Dde),s=JR(e,t,Cr(e)),a=o.length===0?[]:await Promise.all(o.map(async(l)=>{if(!i.ok)throw Error("pilot.yaml needs agePublicKey to re-encrypt secrets");return await Bde(e,l,s,i.data.agePublicKey)?[`users/${l}.secrets.yaml.age`]:[]}));return[...n.flat(),...a.flat()]}var Ry="AI_API_KEY",Ty="OPENAI_API_KEY",Pde,zde,Nde,Dde;var $y=v(()=>{Mi();Xo();Pn();de();$c();Ey();Pde={aiApiKey:"openaiApiKey",aiApiKeyOverride:"openaiApiKeyOverride"};zde=c.looseObject({aiApiKeyOverride:c.string().optional()}),Nde=c.looseObject({members:c.array(c.string()).default([]),aiApiKeyOverride:c.string().optional()}),Dde=c.looseObject({agePublicKey:c.string()})});function cq(e){if(e==="core")return{bundles:["core","media","web","chat"]};if(e==="default")return{bundles:["core","media","automation","web","chat","site","publishing","federation"],remove:[...Mde]};return{bundles:["core","media","automation","web","chat","site","publishing","federation"]}}function qde(e){let t=Zde.parse(e);return fi.parse({brainVersion:t.brainVersion,bundleContract:pi,...cq(t.preset),githubOrg:t.githubOrg,contentRepoPrefix:t.contentRepoPrefix,domainSuffix:t.domainSuffix,openaiApiKey:tT(t.aiApiKey),gitSyncToken:t.gitSyncToken,contentRepoAdminToken:t.contentRepoAdminToken,agePublicKey:t.agePublicKey})}function Fde(e){let t=Ude.parse(e),r=t.presetOverride?cq(t.presetOverride):void 0;return Jr.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?{openaiApiKeyOverride:t.aiApiKeyOverride}:{},...t.gitSyncTokenOverride?{gitSyncTokenOverride:t.gitSyncTokenOverride}:{}})}function lq(e){let t=Gr(e,{keepSourceTokens:!0});if(t.errors.length>0)throw Error(`Invalid desired-state YAML: ${t.errors[0]?.message}`);if(!hn(t.contents))throw Error("Desired-state YAML must contain a mapping");return t}function rT(e,t){if(!hn(e.contents))return;return e.contents.items.find((r)=>vo(r.key)&&r.key.value===t)}function iq(e,t){if(!So(e)||!So(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 sq(e,t){if(!e||!So(t))return;let r=[So(e.key)?e.key.commentBefore:void 0,So(e.key)?e.key.comment:void 0,So(e.value)?e.value.commentBefore:void 0,So(e.value)?e.value.comment:void 0].filter((o)=>o!==void 0);if(r.length===0)return;t.commentBefore=[t.commentBefore,...r].filter((o)=>o!==void 0).join(`
427
427
  `)}function uq(e,t,r,o){if(!hn(e.contents))throw Error("Desired-state YAML must contain a mapping");let n=e.contents.items.findIndex((s)=>vo(s.key)&&s.key.value===t),i=e.createPair(r,[...o]);if(n>=0){let s=e.contents.items[n];iq(s?.key,i.key),iq(s?.value,i.value),e.contents.items.splice(n,1,i)}else e.contents.add(i);return i}function dq(e){let t=lq(e),r=qde(t.toJS()),o=rT(t,"schemaVersion"),n=rT(t,"model");sq(o,rT(t,"brainVersion")?.key),t.delete("schemaVersion"),t.set("bundleContract",pi);let i=uq(t,"preset","bundles",r.bundles);if(sq(n,i.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 Hi(t),fi.parse(t.toJS()),t.toString({lineWidth:0})}function pq(e){let t=lq(e),r=Fde(t.toJS());if(r.bundlesOverride)uq(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 Hi(t),Jr.parse(t.toJS()),t.toString({lineWidth:0})}var aq,mp,Zde,Ude,Mde;var fq=v(()=>{$y();Pn();de();$c();Zn();aq=c.enum(["core","default","pro"]),mp=c.string().min(1),Zde=c.strictObject({schemaVersion:c.literal(1),brainVersion:$t,model:c.literal("rover"),githubOrg:c.string().min(1),contentRepoPrefix:c.string().min(1),domainSuffix:c.string().min(1),preset:aq,aiApiKey:mp,gitSyncToken:mp,contentRepoAdminToken:mp,agePublicKey:c.string().startsWith("age1").min(1)}),Ude=c.strictObject({members:c.array(mr).min(1),brainVersionOverride:$t.optional(),presetOverride:aq.optional(),aiApiKeyOverride:mp.optional(),gitSyncTokenOverride:mp.optional()}).superRefine((e,t)=>{if(new Set(e.members).size!==e.members.length)t.addIssue({code:c.ZodIssueCode.custom,path:["members"],message:"cohort members must be unique"})}),Mde=["series","portfolio","content-pipeline","social-media","newsletter","stock-photo"]});function hq(e,t){let r=Gr(e,{keepSourceTokens:!0});if(r.errors.length>0||!hn(r.contents))throw Error(`Invalid ${t} YAML`);return r}function Wde(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function gq(e,t,r){if(!Wde(t,r.sourceBundles))throw Error(`${e} source bundles changed after review: expected [${r.sourceBundles.join(", ")}], received [${t.join(", ")}]`)}function yq(e){let t=lr(e,Vde);if(!t.ok)throw Error(`Invalid capability bundle review: ${t.error}`);return t.data}function bq(e,t){let r=hq(e,"pilot desired-state"),o=Jde.parse(r.toJS());return gq("pilot.yaml",o.bundles,t),r.set("bundleContract",pi),r.set("bundles",t.targetBundles),Hi(r),fi.parse(r.toJS()),r.toString({lineWidth:0})}function Sq(e,t,r){let o=hq(e,`cohort ${t}`),n=Kde.parse(o.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`);gq(`cohort ${t}`,n.bundlesOverride,r),o.set("bundlesOverride",r.targetBundles)}return Hi(o),Jr.parse(o.toJS()),o.toString({lineWidth:0})}var Hde,nT,Oy,Jde,Kde,mq,Vde;var vq=v(()=>{$y();Pn();de();$c();Zn();Hde=c.enum(["core","site","publishing","team"]),nT=c.array(Hde).min(1),Oy=c.array(c.string().min(1)),Jde=c.strictObject({brainVersion:$t,bundles:nT,add:Oy.optional(),remove:Oy.optional(),githubOrg:c.string().min(1),contentRepoPrefix:c.string().min(1),domainSuffix:c.string().min(1),aiApiKey:c.string().min(1),gitSyncToken:c.string().min(1),contentRepoAdminToken:c.string().min(1),agePublicKey:c.string().startsWith("age1").min(1)}),Kde=c.strictObject({members:c.array(mr).min(1),brainVersionOverride:$t.optional(),bundlesOverride:nT.optional(),addOverride:Oy.optional(),removeOverride:Oy.optional(),aiApiKeyOverride:c.string().min(1).optional(),gitSyncTokenOverride:c.string().min(1).optional()}),mq=c.strictObject({sourceBundles:nT,targetBundles:c.array(dh).min(1)}),Vde=c.strictObject({bundleContract:c.literal(pi),pilot:mq,cohorts:c.record(mr,mq)})});var Iq={};Lt(Iq,{loadCapabilityBundleReview:()=>ope,loadReviewedSitePins:()=>npe,parseReviewedSitePins:()=>Eq,stageLegacyCrossover:()=>spe});import{access as Gde,cp as Qde,mkdir as wq,readFile as al,readdir as _q,writeFile as sl}from"fs/promises";import{basename as Yde,join as Xn,relative as Cy,resolve as xq}from"path";import{fileURLToPath as Xde}from"url";function Eq(e){let t=lr(e,epe);if(!t.ok)throw Error(`Invalid reviewed site pins: ${t.error}`);return t.data.sites}async function npe(e){return Eq(await al(e,"utf8"))}async function ope(e){return yq(await al(e,"utf8"))}async function ipe(e,t){let r=Xn(e,"users"),o=(await _q(r,{withFileTypes:!0})).filter((s)=>s.isFile()&&/\.ya?ml$/.test(s.name)).map((s)=>s.name).sort(),n=new Set(Object.keys(t??{})),i=[];for(let s of o){let a=Xn(r,s),l=await al(a,"utf8"),u=Gr(l,{keepSourceTokens:!0});if(u.errors.length>0||!hn(u.contents))throw Error(`Invalid user desired-state YAML: ${s}`);let d=tpe.parse(u.toJS());if(!d.siteOverride)continue;let p=t?.[d.handle];if(!p)throw Error(`User ${d.handle} has a siteOverride but no reviewed site pin`);if(n.delete(d.handle),p.package!==d.siteOverride.package||p.theme!==d.siteOverride.theme)throw Error(`Reviewed site pin identity does not match user ${d.handle}`);if(d.siteOverride.version!==void 0&&d.siteOverride.version!==p.version)throw Error(`Reviewed site version does not match the existing pin for user ${d.handle}`);if(d.siteOverride.themeVersion!==void 0&&d.siteOverride.themeVersion!==p.themeVersion)throw Error(`Reviewed theme version does not match the existing pin for user ${d.handle}`);if(u.setIn(["siteOverride","version"],p.version),p.themeVersion!==void 0)u.setIn(["siteOverride","themeVersion"],p.themeVersion);else u.deleteIn(["siteOverride","themeVersion"]);ph.parse(u.toJS());let m=u.toString({lineWidth:0});if(m!==l)await sl(a,m),i.push(Cy(e,a))}if(n.size>0)throw Error(`Reviewed site pins do not match site users: ${[...n].sort().join(", ")}`);return i}async function spe(e,t,r={}){let o=xq(e),n=xq(t);if(o===n||n.startsWith(`${o}/`))throw Error("Crossover output must be outside the source repository");await Qde(o,n,{recursive:!0,errorOnExist:!0,force:!1,filter:(A)=>{let O=Yde(A);return O!==".git"&&O!==".operator"&&O!==".brains-ops"&&O!==".turbo"&&O!=="dist"&&O!=="node_modules"&&O!==".env"&&O!==".env.local"&&!O.endsWith(".secrets.yaml")}});let i=[],s=Xn(n,"docs","canonical-crossover-record.md");try{await Gde(s)}catch{await wq(Xn(n,"docs"),{recursive:!0}),await sl(s,await al(rpe,"utf8")),i.push("docs/canonical-crossover-record.md")}let a=Xn(n,"pilot.yaml"),l=await al(a,"utf8"),d=Gr(l).toJS();if(!Hu(d))throw Error(`${a} is not a YAML mapping`);let p=Array.isArray(d.bundles),m=r.bundleReview,h;if(p){if(!m)throw Error("Current canonical desired state requires an explicit capability bundle review manifest");h=bq(l,m.pilot)}else h=dq(l);await sl(a,h),i.push("pilot.yaml");let b=Xn(n,"cohorts"),y=(await _q(b,{withFileTypes:!0})).filter((A)=>A.isFile()&&/\.ya?ml$/.test(A.name)).map((A)=>A.name).sort(),S=new Set(Object.keys(m?.cohorts??{}));for(let A of y){let O=Xn(b,A),L=await al(O,"utf8"),z=A.replace(/\.ya?ml$/,""),J=m?.cohorts[z];if(J)S.delete(z);await sl(O,p?Sq(L,z,J):pq(L)),i.push(Cy(n,O))}if(p&&S.size>0)throw Error(`Capability bundle review names unknown cohorts: ${[...S].sort().join(", ")}`);i.push(...await ipe(n,r.sitePins));let x=await ut(n),_=Th(x.pilot.githubOrg);for(let A of x.users){let O=await _(A),L=Xn(n,"users",A.handle);if(await wq(L,{recursive:!0}),O.brainYaml){let z=Xn(L,"brain.yaml");await sl(z,O.brainYaml),i.push(Cy(n,z))}if(O.envFile){let z=Xn(L,".env");await sl(z,O.envFile),i.push(Cy(n,z))}}return await mo(n,{registry:x}),i.push("views/users.md"),{outputDir:n,changedFiles:[...new Set(i)].sort()}}var epe,tpe,rpe;var kq=v(()=>{Pn();Ju();de();$c();RI();fq();vq();Kr();fc();Zn();epe=c.strictObject({sites:c.record(mr,eI)}),tpe=c.object({handle:mr,siteOverride:c.object({package:c.string().min(1),version:$t.optional(),theme:c.string().min(1).optional(),themeVersion:$t.optional()}).optional()}).passthrough(),rpe=Xde(new URL("../templates/rover-pilot/docs/canonical-crossover-record.md",import.meta.url))});var Aq="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";import{webcrypto as Rq}from"crypto";function cpe(e){if(e<0)throw RangeError("Wrong ID size");try{if(!Ji||Ji.length<e)Ji=Buffer.allocUnsafe(e*ape),Rq.getRandomValues(Ji),cl=0;else if(cl+e>Ji.length)Rq.getRandomValues(Ji),cl=0}catch(t){throw Ji=void 0,t}cl+=e}function Tq(e=21){cpe(e|=0);let t="";for(let r=cl-e;r<cl;r++)t+=Aq[Ji[r]&63];return t}var ape=128,Ji,cl;var $q=()=>{};function Lo(e=12){return Tq(e)}var hp=v(()=>{$q()});import{openSync as lpe,writeSync as upe}from"fs";function dpe(e){return ll?`[${ll}] ${e}`:e}class Rr{static instance=null;level;context;useStderr;format;logFile;fileHandle;constructor(e={},t){if(this.level=e.level??aa.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=lpe(this.logFile,"a")}catch{}}static getInstance(e){if(!Rr.instance)Rr.instance=new Rr(e);else{if(e?.useStderr!==void 0)Rr.instance.useStderr=e.useStderr;if(e?.level!==void 0)Rr.instance.level=e.level}return Rr.instance}static resetInstance(){Rr.instance=null,ll=void 0}static setProcessRole(e){ll=e}static createFresh(e){return new Rr(e)}formatEntry(e,t,r){if(this.format==="json")return this.formatJsonEntry(e,t,r);return dpe([`[${new Date().toISOString()}]`,...this.context?[`[${this.context}]`]:[],t].join(" "))}write(e,t,r,o){if(this.format==="json")e(this.formatEntry(t,r,o));else if(o.length>0)e(this.formatEntry(t,r,[]),...o);else e(this.formatEntry(t,r,[]));if(this.fileHandle!==void 0){let n=this.formatJsonEntry(t,r,o);try{upe(this.fileHandle,n+`
428
428
  `)}catch{}}}formatJsonEntry(e,t,r){let o={ts:new Date().toISOString(),level:e,...ll&&{role:ll},msg:t};if(this.context)o.ctx=this.context;if(r.length>0)o.data=r;return JSON.stringify(o)}debugStream(){return this.useStderr?console.error.bind(console):console.debug.bind(console)}silly(e,...t){if(this.level<=aa.SILLY)this.write(this.debugStream(),"silly",e,t)}verbose(e,...t){if(this.level<=aa.VERBOSE)this.write(this.debugStream(),"verbose",e,t)}debug(e,...t){if(this.level<=aa.DEBUG)this.write(this.debugStream(),"debug",e,t)}info(e,...t){if(this.level<=aa.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<=aa.WARN)this.write(console.warn.bind(console),"warn",e,t)}error(e,...t){if(this.level<=aa.ERROR)this.write(console.error.bind(console),"error",e,t)}child(e){return new Rr({level:this.level,context:e,useStderr:this.useStderr,format:this.format},this.fileHandle)}setUseStderr(e){this.useStderr=e}}var aa,ll,F2e;var oT=v(()=>{aa={SILLY:0,VERBOSE:1,DEBUG:2,INFO:3,WARN:4,ERROR:5,NONE:6};F2e=Rr.getInstance()});var iT,ppe,ul,V2e;var gp=v(()=>{Tt();de();iT=c.enum(["file_operations","content_operations","data_processing","batch_processing"]),ppe=c.looseObject({pluginId:c.string().optional(),progressToken:c.union([c.string(),c.number()]).optional(),operationType:iT,operationTarget:c.string().optional(),interfaceType:c.string().optional(),interfaceId:c.string().optional(),conversationId:c.string().optional(),channelId:c.string().optional(),requestedByActor:jn.optional(),requestedByUserId:c.string().optional(),requestedByInterface:c.string().optional(),silent:c.boolean().optional(),provenance:fo.optional()}),ul=c.looseObject({pluginId:c.string().optional(),progressToken:c.union([c.string(),c.number()]).optional(),operationType:iT,operationTarget:c.string().optional(),interfaceType:c.string().optional(),interfaceId:c.string().optional(),conversationId:c.string().optional(),channelId:c.string().optional(),requestedByActor:jn.optional(),requestedByUserId:c.string().optional(),requestedByInterface:c.string().optional(),silent:c.boolean().optional(),provenance:fo.optional(),rootJobId:c.string()}),V2e=c.enum(["none","skip","replace","coalesce"])});var fpe,Ki=15000;var yp=v(()=>{gp();de();fpe=c.object({id:c.string(),type:c.string(),data:c.string(),status:c.enum(["pending","processing","completed","failed"]),source:c.string().nullable(),priority:c.number(),retryCount:c.number(),maxRetries:c.number(),lastError:c.string().nullable(),lastErrorPublic:c.unknown(),createdAt:c.number(),scheduledFor:c.number(),startedAt:c.number().nullable(),completedAt:c.number().nullable(),attemptId:c.string().nullable(),workerSlotId:c.string().nullable(),workerSessionId:c.string().nullable(),leaseExpiresAt:c.number().nullable(),attemptHeartbeatAt:c.number().nullable(),runtimeUpdatedAt:c.number().nullable(),metadata:ul,progress:c.custom((e)=>typeof e==="object"&&e!==null&&("progress"in e)&&typeof e.progress==="number").nullable(),result:c.unknown().nullable().optional()})});var sT,Oq,Oe,mpe,hpe,Cq,Pq,zq;var Bo=v(()=>{Tt();de();gp();sT=c.enum(["pending","processing","completed","failed"]),Oq=c.enum(["completed","failed"]),Oe={PENDING:"pending",PROCESSING:"processing",COMPLETED:"completed",FAILED:"failed"},mpe=c.object({id:c.string(),type:c.string(),status:sT,data:c.unknown(),result:c.unknown().optional(),lastError:c.string().optional().nullable(),attempts:c.number(),maxRetries:c.number(),priority:c.number(),createdAt:c.date(),updatedAt:c.date(),processedAt:c.date().optional().nullable(),completedAt:c.date().optional().nullable(),failedAt:c.date().optional().nullable()}),hpe=c.object({jobId:c.string(),type:c.string(),status:Oq,result:c.unknown().optional(),error:c.string().optional()}),Cq=c.object({success:c.literal(!1),error:c.string().optional()}),Pq=c.object({id:c.string(),type:c.enum(["job","batch"]),status:sT,message:c.string().optional(),progress:c.object({current:c.number(),total:c.number(),percentage:c.number()}).optional(),aggregationKey:c.string().optional(),batchDetails:c.object({totalOperations:c.number(),completedOperations:c.number(),failedOperations:c.number(),currentOperation:c.string().optional(),errors:c.array(c.string()).optional()}).optional(),jobDetails:c.object({jobType:c.string(),priority:c.number(),retryCount:c.number()}).optional(),metadata:ul}),zq=di(WE.progress,Pq)});var Ce,Gt;var wn=v(()=>{Ce=class Ce extends Error{code;extendedCode;rawCode;constructor(e,t,r,o,n){if(t!==void 0)e=`${t}: ${e}`;super(e,{cause:n});this.code=t,this.extendedCode=r,this.rawCode=o,this.name="LibsqlError"}};Gt=class Gt extends Ce{statementIndex;constructor(e,t,r,o,n,i){super(e,r,o,n,i);this.statementIndex=t,this.name="LibsqlBatchError"}}});function Nq(e){let t=gpe.exec(e);if(t===null)throw new Ce(`The URL '${e}' is not in a valid format`,"URL_INVALID");let r=t.groups,o=r.scheme,n=r.authority!==void 0?ype(r.authority):void 0,i=ca(r.path),s=r.query!==void 0?Spe(r.query):void 0,a=r.fragment!==void 0?ca(r.fragment):void 0;return{scheme:o,authority:n,path:i,query:s,fragment:a}}function ype(e){let t=bpe.exec(e);if(t===null)throw new Ce("The authority part of the URL is not in a valid format","URL_INVALID");let r=t.groups,o=ca(r.host_br??r.host),n=r.port?parseInt(r.port,10):void 0,i=r.username!==void 0?{username:ca(r.username),password:r.password!==void 0?ca(r.password):void 0}:void 0;return{host:o,port:n,userinfo:i}}function Spe(e){let t=e.split("&"),r=[];for(let o of t){if(o==="")continue;let n,i,s=o.indexOf("=");if(s<0)n=o,i="";else n=o.substring(0,s),i=o.substring(s+1);r.push({key:ca(n.replaceAll("+"," ")),value:ca(i.replaceAll("+"," "))})}return{pairs:r}}function ca(e){try{return decodeURIComponent(e)}catch(t){if(t instanceof URIError)throw new Ce(`URL component has invalid percent encoding: ${t}`,"URL_INVALID",void 0,void 0,t);throw t}}function bp(e,t,r){if(t===void 0)throw new Ce(`URL with scheme ${JSON.stringify(e+":")} requires authority (the "//" part)`,"URL_INVALID");let o=`${e}:`,n=vpe(t.host),i=wpe(t.port),a=`//${xpe(t.userinfo)}${n}${i}`,l=r.split("/").map(encodeURIComponent).join("/");if(l!==""&&!l.startsWith("/"))l="/"+l;return new URL(`${o}${a}${l}`)}function vpe(e){return e.includes(":")?`[${encodeURI(e)}]`:encodeURI(e)}function wpe(e){return e!==void 0?`:${e}`:""}function xpe(e){if(e===void 0)return"";let t=encodeURIComponent(e.username),r=e.password!==void 0?`:${encodeURIComponent(e.password)}`:"";return`${t}${r}@`}var gpe,bpe;var Py=v(()=>{wn();gpe=(()=>new RegExp("^(?<scheme>[A-Za-z][A-Za-z.+-]*):(//(?<authority>[^/?#]*))?(?<path>[^?#]*)(\\?(?<query>[^#]*))?(#(?<fragment>.*))?$","su"))();bpe=(()=>new RegExp("^((?<username>[^:]*)(:(?<password>.*))?@)?((?<host>[^:\\[\\]]*)|(\\[(?<host_br>[^\\[\\]]*)\\]))(:(?<port>[0-9]*))?$","su"))()});var pl,Dq,Lq,Sp,zy,_pe,Qt,Bq,Uq=(e)=>e.replace(/=/g,"").replace(/[+\/]/g,(t)=>t=="+"?"-":"_"),Mq=(e)=>e.replace(/[^A-Za-z0-9\+\/]/g,""),qq=(e)=>{let t,r,o,n,i="",s=e.length%3;for(let a=0;a<e.length;){if((r=e.charCodeAt(a++))>255||(o=e.charCodeAt(a++))>255||(n=e.charCodeAt(a++))>255)throw TypeError("invalid character found");t=r<<16|o<<8|n,i+=Sp[t>>18&63]+Sp[t>>12&63]+Sp[t>>6&63]+Sp[t&63]}return s?i.slice(0,s-3)+"===".substring(s):i},lT,aT,Ny=(e,t=!1)=>t?Uq(aT(e)):aT(e),Epe=(e)=>{if(e.length<2){var t=e.charCodeAt(0);return t<128?e:t<2048?Qt(192|t>>>6)+Qt(128|t&63):Qt(224|t>>>12&15)+Qt(128|t>>>6&63)+Qt(128|t&63)}else{var t=65536+(e.charCodeAt(0)-55296)*1024+(e.charCodeAt(1)-56320);return Qt(240|t>>>18&7)+Qt(128|t>>>12&63)+Qt(128|t>>>6&63)+Qt(128|t&63)}},Ipe,Fq=(e)=>e.replace(Ipe,Epe),jq,dl=(e,t=!1)=>t?Uq(jq(e)):jq(e),Zq=(e)=>dl(e,!0),kpe,Ape=(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 Qt((r>>>10)+55296)+Qt((r&1023)+56320);case 3:return Qt((15&e.charCodeAt(0))<<12|(63&e.charCodeAt(1))<<6|63&e.charCodeAt(2));default:return Qt((31&e.charCodeAt(0))<<6|63&e.charCodeAt(1))}},Hq=(e)=>e.replace(kpe,Ape),Jq=(e)=>{if(e=e.replace(/\s+/g,""),!_pe.test(e))throw TypeError("malformed base64.");e+="==".slice(2-(e.length&3));let t,r,o,n=[];for(let i=0;i<e.length;)if(t=zy[e.charAt(i++)]<<18|zy[e.charAt(i++)]<<12|(r=zy[e.charAt(i++)])<<6|(o=zy[e.charAt(i++)]),r===64)n.push(Qt(t>>16&255));else if(o===64)n.push(Qt(t>>16&255,t>>8&255));else n.push(Qt(t>>16&255,t>>8&255,t&255));return n.join("")},uT,Kq,Vq=(e)=>Kq(Wq(e)),Rpe,Wq=(e)=>Mq(e.replace(/[-_]/g,(t)=>t=="-"?"+":"/")),cT=(e)=>Rpe(Wq(e)),Tpe=(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)},Gq=(e)=>({value:e,enumerable:!1,writable:!0,configurable:!0}),Qq=function(){let e=(t,r)=>Object.defineProperty(String.prototype,t,Gq(r));e("fromBase64",function(){return cT(this)}),e("toBase64",function(t){return dl(this,t)}),e("toBase64URI",function(){return dl(this,!0)}),e("toBase64URL",function(){return dl(this,!0)}),e("toUint8Array",function(){return Vq(this)})},Yq=function(){let e=(t,r)=>Object.defineProperty(Uint8Array.prototype,t,Gq(r));e("toBase64",function(t){return Ny(this,t)}),e("toBase64URI",function(){return Ny(this,!0)}),e("toBase64URL",function(){return Ny(this,!0)})},$pe=()=>{Qq(),Yq()},fl;var Dy=v(()=>{pl=typeof Buffer==="function",Dq=typeof TextDecoder==="function"?new TextDecoder("utf-8",{ignoreBOM:!0}):void 0,Lq=typeof TextEncoder==="function"?new TextEncoder:void 0,Sp=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),zy=((e)=>{let t={};return e.forEach((r,o)=>t[r]=o),t})(Sp),_pe=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,Qt=String.fromCharCode.bind(String),Bq=typeof Uint8Array.from==="function"?Uint8Array.from.bind(Uint8Array):(e)=>new Uint8Array(Array.prototype.slice.call(e,0)),lT=typeof btoa==="function"?(e)=>btoa(e):pl?(e)=>Buffer.from(e,"binary").toString("base64"):qq,aT=pl?(e)=>Buffer.from(e).toString("base64"):(e)=>{let r=[];for(let o=0,n=e.length;o<n;o+=4096)r.push(Qt.apply(null,e.subarray(o,o+4096)));return lT(r.join(""))},Ipe=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,jq=pl?(e)=>Buffer.from(e,"utf8").toString("base64"):Lq?(e)=>aT(Lq.encode(e)):(e)=>lT(Fq(e)),kpe=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,uT=typeof atob==="function"?(e)=>atob(Mq(e)):pl?(e)=>Buffer.from(e,"base64").toString("binary"):Jq,Kq=pl?(e)=>Bq(Buffer.from(e,"base64")):(e)=>Bq(uT(e).split("").map((t)=>t.charCodeAt(0))),Rpe=pl?(e)=>Buffer.from(e,"base64").toString("utf8"):Dq?(e)=>Dq.decode(Kq(e)):(e)=>Hq(uT(e)),fl={version:"3.8.0",VERSION:"3.8.0",atob:uT,atobPolyfill:Jq,btoa:lT,btoaPolyfill:qq,fromBase64:cT,toBase64:dl,encode:dl,encodeURI:Zq,encodeURL:Zq,utob:Fq,btou:Hq,decode:cT,isValid:Tpe,fromUint8Array:Ny,toUint8Array:Vq,extendString:Qq,extendUint8Array:Yq,extendBuiltins:$pe}});function Vi(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 ml{columns;columnTypes;rows;rowsAffected;lastInsertRowid;constructor(e,t,r,o,n){this.columns=e,this.columnTypes=t,this.rows=r,this.rowsAffected=o,this.lastInsertRowid=n}toJSON(){return{columns:this.columns,columnTypes:this.columnTypes,rows:this.rows.map(Ope),rowsAffected:this.rowsAffected,lastInsertRowid:this.lastInsertRowid!==void 0?""+this.lastInsertRowid:null}}}function Ope(e){return Array.prototype.map.call(e,Cpe)}function Cpe(e){if(typeof e==="bigint")return""+e;else if(e instanceof ArrayBuffer)return fl.fromUint8Array(new Uint8Array(e));else return e}var eo="https://github.com/libsql/libsql-client-ts#supported-urls";var hl=v(()=>{Dy()});function e4(e){return e.scheme==="file"&&(e.path===":memory:"||e.path.startsWith(":memory:?"))}function vp(e,t){if(typeof e!=="object")throw TypeError(`Expected client configuration as object, got ${typeof e}`);let{url:r,authToken:o,tls:n,intMode:i,concurrency:s}=e;s=Math.max(0,s||20),i??="number";let a=[];if(r===Xq)r="file::memory:";let l=Nq(r),u=l.scheme.toLowerCase(),d=u==="file"&&l.path===Xq&&l.authority===void 0,p;if(d)p={cache:{values:["shared","private"],update:(y,S)=>a.push(`${y}=${S}`)}};else p={tls:{values:["0","1"],update:(y,S)=>n=S==="1"},authToken:{update:(y,S)=>o=S}};for(let{key:y,value:S}of l.query?.pairs??[]){if(!Object.hasOwn(p,y))throw new Ce(`Unsupported URL query parameter ${JSON.stringify(y)}`,"URL_PARAM_NOT_SUPPORTED");let x=p[y];if(x.values!==void 0&&!x.values.includes(S))throw new Ce(`Unknown value for the "${y}" query argument: ${JSON.stringify(S)}. Supported values are: [${x.values.map((_)=>'"'+_+'"').join(", ")}]`,"URL_INVALID");if(x.update!==void 0)x?.update(y,S)}let m=a.length===0?"":`?${a.join("&")}`,h=l.path+m,b;if(u==="libsql")if(n===!1){if(l.authority?.port===void 0)throw new Ce('A "libsql:" URL with ?tls=0 must specify an explicit port',"URL_INVALID");b=t?"http":"ws"}else b=t?"https":"wss";else b=u;if(b==="http"||b==="ws")n??=!1;else n??=!0;if(b!=="http"&&b!=="ws"&&b!=="https"&&b!=="wss"&&b!=="file")throw new Ce(`The client supports only "libsql:", "wss:", "ws:", "https:", "http:" and "file:" URLs, got ${JSON.stringify(l.scheme+":")}. For more information, please read ${eo}`,"URL_SCHEME_NOT_SUPPORTED");if(i!=="number"&&i!=="bigint"&&i!=="string")throw TypeError(`Invalid value for intMode, expected "number", "bigint" or "string", got ${JSON.stringify(i)}`);if(l.fragment!==void 0)throw new Ce(`URL fragments are not supported: ${JSON.stringify("#"+l.fragment)}`,"URL_INVALID");if(d)return{scheme:"file",tls:!1,path:h,intMode:i,concurrency:s,syncUrl:e.syncUrl,syncInterval:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,fetch:e.fetch,timeout:e.timeout,authToken:void 0,encryptionKey:void 0,remoteEncryptionKey:void 0,authority:void 0};return{scheme:b,tls:n,authority:l.authority,path:h,authToken:o,intMode:i,concurrency:s,encryptionKey:e.encryptionKey,remoteEncryptionKey:e.remoteEncryptionKey,syncUrl:e.syncUrl,syncInterval:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,fetch:e.fetch,timeout:e.timeout}}var Xq=":memory:";var wp=v(()=>{wn();Py();hl()});var r4=ge(function(on){var Ppe=on&&on.__createBinding||(Object.create?function(e,t,r,o){if(o===void 0)o=r;var n=Object.getOwnPropertyDescriptor(t,r);if(!n||("get"in n?!t.__esModule:n.writable||n.configurable))n={enumerable:!0,get:function(){return t[r]}};Object.defineProperty(e,o,n)}:function(e,t,r,o){if(o===void 0)o=r;e[o]=t[r]}),zpe=on&&on.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),t4=on&&on.__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))Ppe(t,e,r)}return zpe(t,e),t};Object.defineProperty(on,"__esModule",{value:!0});on.load=on.currentTarget=void 0;var Npe=t4(Fr("path")),Dpe=t4(Fr("fs"));function Lpe(){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 Bpe()?`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}`)}on.currentTarget=Lpe;function Bpe(){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 jpe(e){let t=Npe.join(e,"index.node");return Dpe.existsSync(t)?Fr(t):null}on.load=jpe});var i4=ge(function(hDe,o4){var n4=()=>process.platform==="linux",dT=null,Zpe=()=>{if(!dT)dT=n4()&&process.report?process.report.getReport():{};return dT};o4.exports={isLinux:n4,getReport:Zpe}});var c4=ge(function(gDe,a4){var s4=Fr("fs"),Upe=(e)=>s4.readFileSync(e,"utf-8"),Mpe=(e)=>new Promise((t,r)=>{s4.readFile(e,"utf-8",(o,n)=>{if(o)r(o);else t(n)})});a4.exports={LDD_PATH:"/usr/bin/ldd",readFileSync:Upe,readFile:Mpe}});var I4=ge(function(yDe,E4){var u4=Fr("child_process"),{isLinux:gl,getReport:d4}=i4(),{LDD_PATH:Ly,readFile:p4,readFileSync:f4}=c4(),to,ro,Wi="",m4=()=>{if(!Wi)return new Promise((e)=>{u4.exec("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",(t,r)=>{Wi=t?" ":r,e(Wi)})});return Wi},h4=()=>{if(!Wi)try{Wi=u4.execSync("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",{encoding:"utf8"})}catch(e){Wi=" "}return Wi},jo="glibc",g4=/GLIBC\s(\d+\.\d+)/,la="musl",qpe=jo.toUpperCase(),Fpe=la.toLowerCase(),Hpe=(e)=>e.includes("libc.musl-")||e.includes("ld-musl-"),y4=()=>{let e=d4();if(e.header&&e.header.glibcVersionRuntime)return jo;if(Array.isArray(e.sharedObjects)){if(e.sharedObjects.some(Hpe))return la}return null},b4=(e)=>{let[t,r]=e.split(/[\r\n]+/);if(t&&t.includes(jo))return jo;if(r&&r.includes(la))return la;return null},S4=(e)=>{if(e.includes(Fpe))return la;if(e.includes(qpe))return jo;return null},Jpe=async()=>{if(to!==void 0)return to;to=null;try{let e=await p4(Ly);to=S4(e)}catch(e){}return to},Kpe=()=>{if(to!==void 0)return to;to=null;try{let e=f4(Ly);to=S4(e)}catch(e){}return to},v4=async()=>{let e=null;if(gl()){if(e=await Jpe(),!e)e=y4();if(!e){let t=await m4();e=b4(t)}}return e},w4=()=>{let e=null;if(gl()){if(e=Kpe(),!e)e=y4();if(!e){let t=h4();e=b4(t)}}return e},Vpe=async()=>gl()&&await v4()!==jo,Wpe=()=>gl()&&w4()!==jo,Gpe=async()=>{if(ro!==void 0)return ro;ro=null;try{let t=(await p4(Ly)).match(g4);if(t)ro=t[1]}catch(e){}return ro},Qpe=()=>{if(ro!==void 0)return ro;ro=null;try{let t=f4(Ly).match(g4);if(t)ro=t[1]}catch(e){}return ro},x4=()=>{let e=d4();if(e.header&&e.header.glibcVersionRuntime)return e.header.glibcVersionRuntime;return null},l4=(e)=>e.trim().split(/\s+/)[1],_4=(e)=>{let[t,r,o]=e.split(/[\r\n]+/);if(t&&t.includes(jo))return l4(t);if(r&&o&&r.includes(la))return l4(o);return null},Ype=async()=>{let e=null;if(gl()){if(e=await Gpe(),!e)e=x4();if(!e){let t=await m4();e=_4(t)}}return e},Xpe=()=>{let e=null;if(gl()){if(e=Qpe(),!e)e=x4();if(!e){let t=h4();e=_4(t)}}return e};E4.exports={GLIBC:jo,MUSL:la,family:v4,familySync:w4,isNonGlibcLinux:Vpe,isNonGlibcLinuxSync:Wpe,version:Ype,versionSync:Xpe}});var A4=ge(function(bDe,k4){var efe={ALLOW:0,DENY:1};k4.exports=efe});var T4=ge(function(SDe,R4){var pT={value:"SqliteError",writable:!0,enumerable:!1,configurable:!0};function ua(e,t,r){if(new.target!==ua)return new ua(e,t);if(typeof t!=="string")throw TypeError("Expected second argument to be a string");Error.call(this,e),pT.value=""+e,Object.defineProperty(this,"message",pT),Error.captureStackTrace(this,ua),this.code=t,this.rawCode=r}Object.setPrototypeOf(ua,Error);Object.setPrototypeOf(ua.prototype,Error.prototype);Object.defineProperty(ua.prototype,"name",pT);R4.exports=ua});var L4=ge(function(vDe,By){var __dirname="/home/runner/work/brains/brains/node_modules/libsql",{load:tfe,currentTarget:rfe}=r4(),{familySync:$4,GLIBC:nfe,MUSL:ofe}=I4();function ife(){if(process.env.LIBSQL_JS_DEV)return tfe(__dirname);let e=rfe();if($4()==nfe)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"&&$4()==ofe)e="linux-arm-musleabihf";return Fr(`@libsql/${e}`)}var{databaseOpen:sfe,databaseOpenWithSync:afe,databaseInTransaction:cfe,databaseInterrupt:lfe,databaseClose:ufe,databaseSyncSync:dfe,databaseSyncUntilSync:pfe,databaseExecSync:ffe,databasePrepareSync:mfe,databaseDefaultSafeIntegers:hfe,databaseAuthorizer:gfe,databaseLoadExtension:yfe,databaseMaxWriteReplicationIndex:bfe,statementRaw:Sfe,statementIsReader:vfe,statementGet:O4,statementRun:C4,statementInterrupt:wfe,statementRowsSync:P4,statementColumns:xfe,statementSafeIntegers:_fe,rowsNext:Efe}=ife(),Ife=A4(),z4=T4();function yl(e){if(e.libsqlError)return new z4(e.message,e.code,e.rawCode);return e}class N4{constructor(e,t){let r=t?.encryptionCipher??"aes256cbc";if(t&&t.syncUrl){var o="";if(t.syncAuth)console.warn("Warning: The `syncAuth` option is deprecated, please use `authToken` option instead."),o=t.syncAuth;else if(t.authToken)o=t.authToken;let i=t?.encryptionKey??"",s=t?.syncPeriod??0,a=t?.readYourWrites??!0,l=t?.offline??!1,u=t?.remoteEncryptionKey??"";this.db=afe(e,t.syncUrl,o,r,i,s,a,l,u)}else{let i=t?.authToken??"",s=t?.encryptionKey??"",a=t?.timeout??0,l=t?.remoteEncryptionKey??"";this.db=sfe(e,i,r,s,a,l)}this.memory=e===":memory:",this.readonly=!1,this.name="",this.open=!0;let n=this.db;Object.defineProperties(this,{inTransaction:{get(){return cfe(n)}}})}sync(){return dfe.call(this.db)}syncUntil(e){return pfe.call(this.db,e)}prepare(e){try{let t=mfe.call(this.db,e);return new D4(t)}catch(t){throw yl(t)}}transaction(e){if(typeof e!=="function")throw TypeError("Expected first argument to be a function");let t=this,r=(n)=>(...i)=>{t.exec("BEGIN "+n);try{let s=e(...i);return t.exec("COMMIT"),s}catch(s){throw t.exec("ROLLBACK"),s}},o={default:{value:r("")},deferred:{value:r("DEFERRED")},immediate:{value:r("IMMEDIATE")},exclusive:{value:r("EXCLUSIVE")},database:{value:this,enumerable:!0}};return Object.defineProperties(o.default.value,o),Object.defineProperties(o.deferred.value,o),Object.defineProperties(o.immediate.value,o),Object.defineProperties(o.exclusive.value,o),o.default.value}pragma(e,t){if(t==null)t={};if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof t!=="object")throw TypeError("Expected second argument to be an options object");let r=t.simple,o=this.prepare(`PRAGMA ${e}`,this,!0);return r?o.pluck().get():o.all()}backup(e,t){throw Error("not implemented")}serialize(e){throw Error("not implemented")}function(e,t,r){if(t==null)t={};if(typeof t==="function")r=t,t={};if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof r!=="function")throw TypeError("Expected last argument to be a function");if(typeof t!=="object")throw TypeError("Expected second argument to be an options object");if(!e)throw TypeError("User-defined function name cannot be an empty string");throw Error("not implemented")}aggregate(e,t){if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof t!=="object"||t===null)throw TypeError("Expected second argument to be an options object");if(!e)throw TypeError("User-defined function name cannot be an empty string");throw Error("not implemented")}table(e,t){if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(!e)throw TypeError("Virtual table module name cannot be an empty string");throw Error("not implemented")}authorizer(e){gfe.call(this.db,e)}loadExtension(...e){yfe.call(this.db,...e)}maxWriteReplicationIndex(){return bfe.call(this.db)}exec(e){try{ffe.call(this.db,e)}catch(t){throw yl(t)}}interrupt(){lfe.call(this.db)}close(){ufe.call(this.db),this.open=!1}defaultSafeIntegers(e){return hfe.call(this.db,e??!0),this}unsafeMode(...e){throw Error("not implemented")}}class D4{constructor(e){this.stmt=e,this.pluckMode=!1}raw(e){return Sfe.call(this.stmt,e??!0),this}pluck(e){return this.pluckMode=e??!0,this}get reader(){return vfe.call(this.stmt)}run(...e){try{if(e.length==1&&typeof e[0]==="object")return C4.call(this.stmt,e[0]);else return C4.call(this.stmt,e.flat())}catch(t){throw yl(t)}}get(...e){try{if(e.length==1&&typeof e[0]==="object")return O4.call(this.stmt,e[0]);else return O4.call(this.stmt,e.flat())}catch(t){throw yl(t)}}iterate(...e){var t=void 0;if(e.length==1&&typeof e[0]==="object")t=P4.call(this.stmt,e[0]);else t=P4.call(this.stmt,e.flat());return{nextRows:Array(100),nextRowIndex:100,next(){try{if(this.nextRowIndex===100)Efe.call(t,this.nextRows),this.nextRowIndex=0;let o=this.nextRows[this.nextRowIndex];if(this.nextRows[this.nextRowIndex]=void 0,!o)return{done:!0};return this.nextRowIndex++,{value:o,done:!1}}catch(o){throw yl(o)}},[Symbol.iterator](){return this}}}all(...e){try{let t=[];for(let r of this.iterate(...e))if(this.pluckMode)t.push(r[Object.keys(r)[0]]);else t.push(r);return t}catch(t){throw yl(t)}}interrupt(){wfe.call(this.stmt)}columns(){return xfe.call(this.stmt)}safeIntegers(e){return _fe.call(this.stmt,e??!0),this}}By.exports=N4;By.exports.Authorization=Ife;By.exports.SqliteError=z4});import{Buffer as j4}from"buffer";function Z4(e){if(e.scheme!=="file")throw new Ce(`URL scheme ${JSON.stringify(e.scheme+":")} is not supported by the local sqlite3 client. For more information, please read ${eo}`,"URL_SCHEME_NOT_SUPPORTED");let t=e.authority;if(t!==void 0){let s=t.host.toLowerCase();if(s!==""&&s!=="localhost")throw new Ce(`Invalid host in file URL: ${JSON.stringify(t.host)}. A "file:" URL with an absolute path should start with one slash ("file:/absolute/path.db") or with three slashes ("file:///absolute/path.db"). For more information, please read ${eo}`,"URL_INVALID");if(t.port!==void 0)throw new Ce("File URL cannot have a port","URL_INVALID");if(t.userinfo!==void 0)throw new Ce("File URL cannot have username and password","URL_INVALID")}let r=e4(e);if(r&&e.syncUrl)throw new Ce(`Embedded replica must use file for local db but URI with in-memory mode were provided instead: ${e.path}`,"URL_INVALID");let o=e.path;if(r)o=`${e.scheme}:${e.path}`;let n={authToken:e.authToken,encryptionKey:e.encryptionKey,remoteEncryptionKey:e.remoteEncryptionKey,syncUrl:e.syncUrl,syncPeriod:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,timeout:e.timeout},i=new xp.default(o,n);return zt(i,"SELECT 1 AS checkThatTheDatabaseCanBeOpened",e.intMode),new U4(o,n,i,e.intMode)}class U4{#e;#t;#r;#n;closed;protocol;constructor(e,t,r,o){this.#e=e,this.#t=t,this.#r=r,this.#n=o,this.closed=!1,this.protocol="file"}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.#o(),zt(this.#i(),r,this.#n)}async batch(e,t="deferred"){this.#o();let r=this.#i();try{zt(r,Vi(t),this.#n);let o=[];for(let n=0;n<e.length;n++)try{if(!r.inTransaction)throw new Gt("The transaction has been rolled back",n,"TRANSACTION_CLOSED");let i=e[n],s=Array.isArray(i)?{sql:i[0],args:i[1]||[]}:i;o.push(zt(r,s,this.#n))}catch(i){if(i instanceof Gt)throw i;if(i instanceof Ce)throw new Gt(i.message,n,i.code,i.extendedCode,i.rawCode,i.cause instanceof Error?i.cause:void 0);throw i}return zt(r,"COMMIT",this.#n),o}finally{if(r.inTransaction)zt(r,"ROLLBACK",this.#n)}}async migrate(e){this.#o();let t=this.#i();try{zt(t,"PRAGMA foreign_keys=off",this.#n),zt(t,Vi("deferred"),this.#n);let r=[];for(let o=0;o<e.length;o++)try{if(!t.inTransaction)throw new Gt("The transaction has been rolled back",o,"TRANSACTION_CLOSED");r.push(zt(t,e[o],this.#n))}catch(n){if(n instanceof Gt)throw n;if(n instanceof Ce)throw new Gt(n.message,o,n.code,n.extendedCode,n.rawCode,n.cause instanceof Error?n.cause:void 0);throw n}return zt(t,"COMMIT",this.#n),r}finally{if(t.inTransaction)zt(t,"ROLLBACK",this.#n);zt(t,"PRAGMA foreign_keys=on",this.#n)}}async transaction(e="write"){let t=this.#i();return zt(t,Vi(e),this.#n),this.#r=null,new M4(t,this.#n)}async executeMultiple(e){this.#o();let t=this.#i();try{return q4(t,e)}finally{if(t.inTransaction)zt(t,"ROLLBACK",this.#n)}}async sync(){this.#o();let e=await this.#i().sync();return{frames_synced:e.frames_synced,frame_no:e.frame_no}}async reconnect(){try{if(!this.closed&&this.#r!==null)this.#r.close()}finally{this.#r=new xp.default(this.#e,this.#t),this.closed=!1}}close(){if(this.closed=!0,this.#r!==null)this.#r.close(),this.#r=null}#o(){if(this.closed)throw new Ce("The client is closed","CLIENT_CLOSED")}#i(){if(this.#r===null)this.#r=new xp.default(this.#e,this.#t);return this.#r}}class M4{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.#r(),zt(this.#e,r,this.#t)}async batch(e){let t=[];for(let r=0;r<e.length;r++)try{this.#r();let o=e[r],n=Array.isArray(o)?{sql:o[0],args:o[1]||[]}:o;t.push(zt(this.#e,n,this.#t))}catch(o){if(o instanceof Gt)throw o;if(o instanceof Ce)throw new Gt(o.message,r,o.code,o.extendedCode,o.rawCode,o.cause instanceof Error?o.cause:void 0);throw o}return t}async executeMultiple(e){return this.#r(),q4(this.#e,e)}async rollback(){if(!this.#e.open)return;this.#r(),zt(this.#e,"ROLLBACK",this.#t)}async commit(){this.#r(),zt(this.#e,"COMMIT",this.#t)}close(){if(this.#e.inTransaction)zt(this.#e,"ROLLBACK",this.#t)}get closed(){return!this.#e.inTransaction}#r(){if(this.closed)throw new Ce("The transaction is closed","TRANSACTION_CLOSED")}}function zt(e,t,r){let o,n;if(typeof t==="string")o=t,n=[];else if(o=t.sql,Array.isArray(t.args))n=t.args.map((i)=>B4(i,r));else{n={};for(let i in t.args){let s=i[0]==="@"||i[0]==="$"||i[0]===":"?i.substring(1):i;n[s]=B4(t.args[i],r)}}try{let i=e.prepare(o);i.safeIntegers(!0);let s=!0;try{i.raw(!0)}catch{s=!1}if(s){let a=Array.from(i.columns().map((m)=>m.name)),l=Array.from(i.columns().map((m)=>m.type??"")),u=i.all(n).map((m)=>kfe(m,a,r)),d=0,p=void 0;return new ml(a,l,u,0,void 0)}else{let a=i.run(n),l=a.changes,u=BigInt(a.lastInsertRowid);return new ml([],[],[],l,u)}}catch(i){throw F4(i)}}function kfe(e,t,r){let o={};Object.defineProperty(o,"length",{value:e.length});for(let n=0;n<e.length;++n){let i=Afe(e[n],r);Object.defineProperty(o,n,{value:i});let s=t[n];if(!Object.hasOwn(o,s))Object.defineProperty(o,s,{value:i,enumerable:!0,configurable:!0,writable:!0})}return o}function Afe(e,t){if(typeof e==="bigint")if(t==="number"){if(e<Rfe||e>Tfe)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 j4)return e.buffer;return e}function B4(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<$fe||e>Ofe)throw RangeError("bigint is too large to be represented as a 64-bit integer and passed as argument");return e}else if(typeof e==="boolean")switch(t){case"bigint":return e?1n:0n;case"string":return e?"1":"0";default:return e?1:0}else if(e instanceof ArrayBuffer)return j4.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 q4(e,t){try{e.exec(t)}catch(r){throw F4(r)}}function F4(e){if(e instanceof xp.default.SqliteError){let t=e.code,r=Cfe(e.rawCode);return new Ce(e.message,r,t,e.rawCode,e)}return e}function Cfe(e){if(e===void 0)return"SQLITE_UNKNOWN";let t=e&255;return Pfe[t]??`SQLITE_UNKNOWN_${t.toString()}`}var xp,Rfe,Tfe=9007199254740991n,$fe,Ofe=9223372036854775807n,Pfe;var H4=v(()=>{wn();wp();hl();xp=Kl(L4(),1);wn();Rfe=-9007199254740991n;$fe=-9223372036854775808n;Pfe={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 Gi;var fT=v(()=>{if(typeof WebSocket<"u")Gi=WebSocket;else if(typeof global<"u")Gi=global.WebSocket;else if(typeof window<"u")Gi=window.WebSocket;else if(typeof self<"u")Gi=self.WebSocket});class bl{constructor(){this.intMode="number"}intMode}var Ge,Pe,_p,xt,Ep,Sl,da,xn,or,no;var _t=v(()=>{Ge=class Ge extends Error{constructor(e){super(e);this.name="ClientError"}};Pe=class Pe extends Ge{constructor(e){super(e);this.name="ProtoError"}};_p=class _p extends Ge{code;proto;constructor(e,t){super(e);this.name="ResponseError",this.code=t.code,this.proto=t,this.stack=void 0}};xt=class xt extends Ge{constructor(e,t){if(t!==void 0){super(`${e}: ${t}`);this.cause=t}else super(e);this.name="ClosedError"}};Ep=class Ep extends Ge{constructor(e){super(e);this.name="WebSocketUnsupportedError"}};Sl=class Sl extends Ge{constructor(e){super(e);this.name="WebSocketError"}};da=class da extends Ge{status;constructor(e,t){super(e);this.status=t,this.name="HttpServerError"}};xn=class xn extends Ge{constructor(e){super(e);this.name="ProtocolVersionError"}};or=class or extends Ge{constructor(e){super(e);this.name="InternalError"}};no=class no extends Ge{constructor(e){super(e);this.name="MisuseError"}}});function Tr(e){if(typeof e==="string")return e;throw vl(e,"string")}function Ur(e){if(e===null||e===void 0)return;else if(typeof e==="string")return e;throw vl(e,"string or null")}function Zo(e){if(typeof e==="number")return e;throw vl(e,"number")}function Qi(e){if(typeof e==="boolean")return e;throw vl(e,"boolean")}function Ip(e){if(Array.isArray(e))return e;throw vl(e,"array")}function kt(e){if(e!==null&&typeof e==="object"&&!Array.isArray(e))return e;throw vl(e,"object")}function _n(e,t){return Ip(e).map((r)=>t(kt(r)))}function vl(e,t){if(e===void 0)return new Pe(`Expected ${t}, but the property was missing`);let r=typeof e;if(e===null)r="null";else if(Array.isArray(e))r="array";return new Pe(`Expected ${t}, received ${r}`)}function pa(e,t){return t(kt(e))}var wl=v(()=>{_t()});class J4{#e;#t;constructor(e){this.#e=e,this.#t=!1}begin(){this.#e.push("{"),this.#t=!0}end(){this.#e.push("}"),this.#t=!1}#r(e){if(this.#t)this.#e.push('"'),this.#t=!1;else this.#e.push(',"');this.#e.push(e),this.#e.push('":')}string(e,t){this.#r(e),this.#e.push(JSON.stringify(t))}stringRaw(e,t){this.#r(e),this.#e.push('"'),this.#e.push(t),this.#e.push('"')}number(e,t){this.#r(e),this.#e.push(""+t)}boolean(e,t){this.#r(e),this.#e.push(t?"true":"false")}object(e,t,r){this.#r(e),this.begin(),r(this,t),this.end()}arrayObjects(e,t,r){this.#r(e),this.#e.push("[");for(let o=0;o<t.length;++o){if(o!==0)this.#e.push(",");this.begin(),r(this,t[o]),this.end()}this.#e.push("]")}}function kp(e,t){let r=[],o=new J4(r);return o.begin(),t(o,e),o.end(),r.join("")}var fa=0,Ap=1,Rp=2,K4=5;class V4{#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 W4{#e;#t;constructor(e){this.#e=e,this.#t=-1}setup(e){this.#t=e}#r(e){if(this.#t!==e)throw new Pe(`Expected wire type ${e}, got ${this.#t}`);this.#t=-1}bytes(){this.#r(Rp);let e=this.#e.varint();return this.#e.bytes(e)}string(){return new TextDecoder().decode(this.bytes())}message(e){return Yi(this.bytes(),e)}int32(){return this.#r(fa),this.#e.varint()}uint32(){return this.int32()}bool(){return this.int32()!==0}uint64(){return this.#r(fa),this.#e.varintBig()}sint64(){let e=this.uint64();return e>>1n^-(e&1n)}double(){return this.#r(Ap),this.#e.double()}maybeSkip(){if(this.#t<0)return;else if(this.#t===fa)this.#e.skipVarint();else if(this.#t===Ap)this.#e.skip(8);else if(this.#t===Rp){let e=this.#e.varint();this.#e.skip(e)}else if(this.#t===K4)this.#e.skip(4);else throw new Pe(`Unexpected wire type ${this.#t}`);this.#t=-1}}function Yi(e,t){let r=new V4(e),o=new W4(r),n=t.default();while(!r.eof()){let i=r.varint(),s=i>>3,a=i&7;o.setup(a);let l=t[s];if(l!==void 0){let u=l(o,n);if(u!==void 0)n=u}o.maybeSkip()}return n}var mT=v(()=>{_t()});class hT{#e;#t;#r;#n;constructor(){this.#e=new ArrayBuffer(256),this.#t=new Uint8Array(this.#e),this.#r=new DataView(this.#e),this.#n=0}#o(e){if(this.#n+e<=this.#e.byteLength)return;let t=this.#e.byteLength;while(t<this.#n+e)t*=2;let r=new ArrayBuffer(t),o=new Uint8Array(r),n=new DataView(r);o.set(new Uint8Array(this.#e,0,this.#n)),this.#e=r,this.#t=o,this.#r=n}#i(e){this.#o(5),e=0|e;do{let t=e&127;e>>>=7,t|=e?128:0,this.#t[this.#n++]=t}while(e)}#a(e){this.#o(10),e=e&0xffffffffffffffffn;do{let t=Number(e&0x7fn);e>>=7n,t|=e?128:0,this.#t[this.#n++]=t}while(e)}#s(e,t){this.#i(e<<3|t)}bytes(e,t){this.#s(e,Rp),this.#i(t.byteLength),this.#o(t.byteLength),this.#t.set(t,this.#n),this.#n+=t.byteLength}string(e,t){this.bytes(e,new TextEncoder().encode(t))}message(e,t,r){let o=new hT;r(o,t),this.bytes(e,o.data())}int32(e,t){this.#s(e,fa),this.#i(t)}uint32(e,t){this.int32(e,t)}bool(e,t){this.int32(e,t?1:0)}sint64(e,t){this.#s(e,fa),this.#a(t<<1n^t>>63n)}double(e,t){this.#s(e,Ap),this.#o(8),this.#r.setFloat64(this.#n,t,!0),this.#n+=8}data(){return new Uint8Array(this.#e,0,this.#n)}}function Tp(e,t){let r=new hT;return t(r,e),r.data()}var G4=()=>{};var gT=v(()=>{wl();mT();G4()});class Xi{#e;#t;constructor(){this.#e=new Set,this.#t=new Set}alloc(){for(let t of this.#t){if(this.#t.delete(t),this.#e.add(t),!this.#e.has(this.#e.size-1))this.#t.add(this.#e.size-1);return t}let e=this.#e.size;return this.#e.add(e),e}free(e){if(!this.#e.delete(e))throw new or("Freeing an id that is not allocated");if(this.#t.delete(this.#e.size),e<this.#e.size)this.#t.add(e)}}var yT=v(()=>{_t()});function Je(e,t){throw new or(t)}var sn=v(()=>{_t()});function xl(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<Nfe||e>Dfe)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 bT(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 no("Invalid value for IntMode");else if(e instanceof Uint8Array)return e.slice().buffer;else if(e===void 0)throw new Pe("Received unrecognized type of Value");else throw Je(e,"Impossible type of Value")}var Nfe,Dfe=9223372036854775807n;var ST=v(()=>{_t();sn();Nfe=-9223372036854775808n});function ma(e){return{affectedRowCount:e.affectedRowCount,lastInsertRowid:e.lastInsertRowid,columnNames:e.cols.map((t)=>t.name),columnDecltypes:e.cols.map((t)=>t.decltype)}}function Zy(e,t){let r=ma(e),o=e.rows.map((n)=>Q4(r.columnNames,n,t));return{...r,rows:o}}function Uy(e,t){let r=ma(e),o;if(e.rows.length>0)o=Q4(r.columnNames,e.rows[0],t);return{...r,row:o}}function My(e,t){let r=ma(e),o;if(e.rows.length>0&&r.columnNames.length>0)o=bT(e.rows[0][0],t);return{...r,value:o}}function Q4(e,t,r){let o={};Object.defineProperty(o,"length",{value:t.length});for(let n=0;n<t.length;++n){let i=bT(t[n],r);Object.defineProperty(o,n,{value:i});let s=e[n];if(s!==void 0&&!Object.hasOwn(o,s))Object.defineProperty(o,s,{value:i,enumerable:!0,configurable:!0,writable:!0})}return o}function Uo(e){return new _p(e.message,e)}var $p=v(()=>{_t();ST()});class ha{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}_getSqlId(e){if(this.#e!==e)throw new no("Attempted to use SQL text opened with other object");else if(this.#r!==void 0)throw new xt("SQL text is closed",this.#r);return this.#t}close(){this._setClosed(new Ge("SQL text was manually closed"))}_setClosed(e){if(this.#r===void 0)this.#r=e,this.#e._closeSql(this.#t)}get closed(){return this.#r!==void 0}}function Op(e,t){if(t instanceof ha)return{sqlId:t._getSqlId(e)};else return{sql:""+t}}var _l=v(()=>{_t()});class es{#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 Cp{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(xl(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]=xl(t),this}bindName(e,t){return this._namedArgs.set(e,xl(t)),this}unbindAll(){return this._args.length=0,this._namedArgs.clear(),this}}function qy(e,t,r){let o,n=[],i=[];if(t instanceof Cp){o=t.sql,n=t._args;for(let[l,u]of t._namedArgs.entries())i.push({name:l,value:u})}else if(Array.isArray(t))if(o=t[0],Array.isArray(t[1]))n=t[1].map((l)=>xl(l));else i=Object.entries(t[1]).map(([l,u])=>({name:l,value:xl(u)}));else o=t;let{sql:s,sqlId:a}=Op(e,o);return{sql:s,sqlId:a,args:n,namedArgs:i,wantRows:r}}var Fy=v(()=>{_l();ST()});class Hy{_stream;#e;_steps;#t;constructor(e,t){this._stream=e,this.#e=t,this._steps=[],this.#t=!1}step(){return new vT(this)}execute(){if(this.#t)throw new no("This batch has already been executed");this.#t=!0;let e={steps:this._steps.map((t)=>t.proto)};if(this.#e)return Bfe(this._stream,this._steps,e);else return Lfe(this._stream,this._steps,e)}}function Lfe(e,t,r){return e._batch(r).then((o)=>{for(let n=0;n<t.length;++n){let i=o.stepResults.get(n),s=o.stepErrors.get(n);t[n].callback(i,s)}})}async function Bfe(e,t,r){let o=await e._openCursor(r);try{let n=0,i=void 0,s=[];for(;;){let a=await o.next();if(a===void 0)break;if(a.type==="step_begin"){if(a.step<n||a.step>=t.length)throw new Pe("Server produced StepBeginEntry for unexpected step");else if(i!==void 0)throw new Pe("Server produced StepBeginEntry before terminating previous step");for(let l=n;l<a.step;++l)t[l].callback(void 0,void 0);n=a.step+1,i=a,s=[]}else if(a.type==="step_end"){if(i===void 0)throw new Pe("Server produced StepEndEntry but no step is active");let l={cols:i.cols,rows:s,affectedRowCount:a.affectedRowCount,lastInsertRowid:a.lastInsertRowid};t[i.step].callback(l,void 0),i=void 0,s=[]}else if(a.type==="step_error"){if(i===void 0){if(a.step>=t.length)throw new Pe("Server produced StepErrorEntry for unexpected step");for(let l=n;l<a.step;++l)t[l].callback(void 0,void 0)}else{if(a.step!==i.step)throw new Pe("Server produced StepErrorEntry for unexpected step");i=void 0,s=[]}t[a.step].callback(void 0,a.error),n=a.step+1}else if(a.type==="row"){if(i===void 0)throw new Pe("Server produced RowEntry but no step is active");s.push(a.row)}else if(a.type==="error")throw Uo(a.error);else if(a.type==="none")throw new Pe("Server produced unrecognized CursorEntry");else throw Je(a,"Impossible CursorEntry")}if(i!==void 0)throw new Pe("Server closed Cursor before terminating active step");for(let a=n;a<t.length;++a)t[a].callback(void 0,void 0)}finally{o.close()}}class vT{_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,Zy)}queryRow(e){return this.#t(e,!0,Uy)}queryValue(e){return this.#t(e,!0,My)}run(e){return this.#t(e,!1,ma)}#t(e,t,r){if(this._index!==void 0)throw new no("This BatchStep has already been added to the batch");let o=qy(this._batch._stream._sqlOwner(),e,t),n;if(this.#e.length===0)n=void 0;else if(this.#e.length===1)n=this.#e[0];else n={type:"and",conds:this.#e.slice()};let i={stmt:o,condition:n};return new Promise((s,a)=>{let l=(u,d)=>{if(u!==void 0&&d!==void 0)a(new Pe("Server returned both result and error"));else if(d!==void 0)a(Uo(d));else if(u!==void 0)s(r(u,this._batch._stream.intMode));else s(void 0)};this._index=this._batch._steps.length,this._batch._steps.push({proto:i,callback:l})})}}class dt{_batch;_proto;constructor(e,t){this._batch=e,this._proto=t}static ok(e){return new dt(e._batch,{type:"ok",step:Y4(e)})}static error(e){return new dt(e._batch,{type:"error",step:Y4(e)})}static not(e){return new dt(e._batch,{type:"not",cond:e._proto})}static and(e,t){for(let r of t)X4(e,r);return new dt(e,{type:"and",conds:t.map((r)=>r._proto)})}static or(e,t){for(let r of t)X4(e,r);return new dt(e,{type:"or",conds:t.map((r)=>r._proto)})}static isAutocommit(e){return e._stream.client()._ensureVersion(3,"BatchCond.isAutocommit()"),new dt(e,{type:"is_autocommit"})}}function Y4(e){if(e._index===void 0)throw new no("Cannot add a condition referencing a step that has not been added to the batch");return e._index}function X4(e,t){if(t._batch!==e)throw new no("Cannot mix BatchCond objects for different Batch objects")}var wT=v(()=>{_t();$p();Fy();sn()});function eF(e){return{paramNames:e.params.map((t)=>t.name),columns:e.cols,isExplain:e.isExplain,isReadonly:e.isReadonly}}class El{constructor(e){this.intMode=e}query(e){return this.#e(e,!0,Zy)}queryRow(e){return this.#e(e,!0,Uy)}queryValue(e){return this.#e(e,!0,My)}run(e){return this.#e(e,!1,ma)}#e(e,t,r){let o=qy(this._sqlOwner(),e,t);return this._execute(o).then((n)=>r(n,this.intMode))}batch(e=!1){return new Hy(this,e)}describe(e){let t=Op(this._sqlOwner(),e);return this._describe(t).then(eF)}sequence(e){let t=Op(this._sqlOwner(),e);return this._sequence(t)}intMode}var Jy=v(()=>{wT();$p();_l();Fy()});class Pp{}var jfe=1000,Zfe=10,xT;var tF=v(()=>{_t();xT=class xT extends Pp{#e;#t;#r;#n;#o;#i;#a;constructor(e,t,r){super();this.#e=e,this.#t=t,this.#r=r,this.#n=new es,this.#o=new es,this.#i=void 0,this.#a=!1}async next(){for(;;){if(this.#i!==void 0)throw new xt("Cursor is closed",this.#i);while(!this.#a&&this.#o.length<Zfe)this.#o.push(this.#s());let e=this.#n.shift();if(this.#a||e!==void 0)return e;await this.#o.shift().then((t)=>{if(t===void 0)return;for(let r of t.entries)this.#n.push(r);this.#a||=t.done})}}#s(){return this.#t._sendCursorRequest(this,{type:"fetch_cursor",cursorId:this.#r,maxCount:jfe}).then((e)=>e,(e)=>{this._setClosed(e);return})}_setClosed(e){if(this.#i!==void 0)return;this.#i=e,this.#t._sendCursorRequest(this,{type:"close_cursor",cursorId:this.#r}).catch(()=>{return}),this.#t._cursorClosed(this)}close(){this._setClosed(new Ge("Cursor was manually closed"))}get closed(){return this.#i!==void 0}}});var zp;var _T=v(()=>{_t();Jy();tF();zp=class zp extends El{#e;#t;#r;#n;#o;#i;static open(e){let t=e._streamIdAlloc.alloc(),r=new zp(e,t),o=()=>{return},n=(s)=>r.#l(s),i={type:"open_stream",streamId:t};return e._sendRequest(i,{responseCallback:o,errorCallback:n}),r}constructor(e,t){super(e.intMode);this.#e=e,this.#t=t,this.#r=new es,this.#n=void 0,this.#o=!1,this.#i=void 0}client(){return this.#e}_sqlOwner(){return this.#e}_execute(e){return this.#a({type:"execute",streamId:this.#t,stmt:e}).then((t)=>t.result)}_batch(e){return this.#a({type:"batch",streamId:this.#t,batch:e}).then((t)=>t.result)}_describe(e){return this.#e._ensureVersion(2,"describe()"),this.#a({type:"describe",streamId:this.#t,sql:e.sql,sqlId:e.sqlId}).then((t)=>t.result)}_sequence(e){return this.#e._ensureVersion(2,"sequence()"),this.#a({type:"sequence",streamId:this.#t,sql:e.sql,sqlId:e.sqlId}).then((t)=>{return})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#a({type:"get_autocommit",streamId:this.#t}).then((e)=>e.isAutocommit)}#a(e){return new Promise((t,r)=>{this.#s({type:"request",request:e,responseCallback:t,errorCallback:r})})}_openCursor(e){return this.#e._ensureVersion(3,"cursor"),new Promise((t,r)=>{this.#s({type:"cursor",batch:e,cursorCallback:t,errorCallback:r})})}_sendCursorRequest(e,t){if(e!==this.#n)throw new or("Cursor not associated with the stream attempted to execute a request");return new Promise((r,o)=>{if(this.#i!==void 0)o(new xt("Stream is closed",this.#i));else this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})})}_cursorClosed(e){if(e!==this.#n)throw new or("Cursor was closed, but it was not associated with the stream");this.#n=void 0,this.#c()}#s(e){if(this.#i!==void 0)e.errorCallback(new xt("Stream is closed",this.#i));else if(this.#o)e.errorCallback(new xt("Stream is closing",void 0));else this.#r.push(e),this.#c()}#c(){for(;;){let e=this.#r.first();if(e===void 0&&this.#n===void 0&&this.#o){this.#l(new Ge("Stream was gracefully closed"));break}else if(e?.type==="request"&&this.#n===void 0){let{request:t,responseCallback:r,errorCallback:o}=e;this.#r.shift(),this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})}else if(e?.type==="cursor"&&this.#n===void 0){let{batch:t,cursorCallback:r}=e;this.#r.shift();let o=this.#e._cursorIdAlloc.alloc(),n=new xT(this.#e,this,o),i={type:"open_cursor",streamId:this.#t,cursorId:o,batch:t},s=()=>{return},a=(l)=>n._setClosed(l);this.#e._sendRequest(i,{responseCallback:s,errorCallback:a}),this.#n=n,r(n)}else break}}#l(e){if(this.#i!==void 0)return;if(this.#i=e,this.#n!==void 0)this.#n._setClosed(e);for(;;){let n=this.#r.shift();if(n!==void 0)n.errorCallback(e);else break}let t={type:"close_stream",streamId:this.#t},r=()=>this.#e._streamIdAlloc.free(this.#t),o=()=>{return};this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})}close(){this.#l(new Ge("Stream was manually closed"))}closeGracefully(){this.#o=!0,this.#c()}get closed(){return this.#i!==void 0||this.#o}}});function Np(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,rF),e.arrayObjects("named_args",t.namedArgs,Ufe),e.boolean("want_rows",t.wantRows)}function Ufe(e,t){e.string("name",t.name),e.object("value",t.value,rF)}function Il(e,t){e.arrayObjects("steps",t.steps,Mfe)}function Mfe(e,t){if(t.condition!==void 0)e.object("condition",t.condition,ET);e.object("stmt",t.stmt,Np)}function ET(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,ET);else if(t.type==="and"||t.type==="or")e.arrayObjects("conds",t.conds,ET);else if(t.type==="is_autocommit");else throw Je(t,"Impossible type of BatchCond")}function rF(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",fl.fromUint8Array(t));else if(t===void 0);else throw Je(t,"Impossible type of Value")}var IT=v(()=>{Dy();sn()});function nF(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,qfe);else throw Je(t,"Impossible type of ClientMsg")}function qfe(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,Np);else if(t.type==="batch")e.number("stream_id",t.streamId),e.object("batch",t.batch,Il);else if(t.type==="open_cursor")e.number("stream_id",t.streamId),e.number("cursor_id",t.cursorId),e.object("batch",t.batch,Il);else if(t.type==="close_cursor")e.number("cursor_id",t.cursorId);else if(t.type==="fetch_cursor")e.number("cursor_id",t.cursorId),e.number("max_count",t.maxCount);else if(t.type==="sequence"){if(e.number("stream_id",t.streamId),t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="describe"){if(e.number("stream_id",t.streamId),t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="store_sql")e.number("sql_id",t.sqlId),e.string("sql",t.sql);else if(t.type==="close_sql")e.number("sql_id",t.sqlId);else if(t.type==="get_autocommit")e.number("stream_id",t.streamId);else throw Je(t,"Impossible type of Request")}var oF=v(()=>{IT();sn()});function Dp(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,sF);for(let r of t.namedArgs)e.message(4,r,Ffe);e.bool(5,t.wantRows)}function Ffe(e,t){e.string(1,t.name),e.message(2,t.value,sF)}function kl(e,t){for(let r of t.steps)e.message(1,r,Hfe)}function Hfe(e,t){if(t.condition!==void 0)e.message(1,t.condition,kT);e.message(2,t.stmt,Dp)}function kT(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,kT);else if(t.type==="and")e.message(4,t.conds,iF);else if(t.type==="or")e.message(5,t.conds,iF);else if(t.type==="is_autocommit")e.message(6,void 0,aF);else throw Je(t,"Impossible type of BatchCond")}function iF(e,t){for(let r of t)e.message(1,r,kT)}function sF(e,t){if(t===null)e.message(1,void 0,aF);else if(typeof t==="bigint")e.sint64(2,t);else if(typeof t==="number")e.double(3,t);else if(typeof t==="string")e.string(4,t);else if(t instanceof Uint8Array)e.bytes(5,t);else if(t===void 0);else throw Je(t,"Impossible type of Value")}function aF(e,t){}var AT=v(()=>{sn()});function cF(e,t){if(t.type==="hello")e.message(1,t,Jfe);else if(t.type==="request")e.message(2,t,Kfe);else throw Je(t,"Impossible type of ClientMsg")}function Jfe(e,t){if(t.jwt!==void 0)e.string(1,t.jwt)}function Kfe(e,t){e.int32(1,t.requestId);let r=t.request;if(r.type==="open_stream")e.message(2,r,Vfe);else if(r.type==="close_stream")e.message(3,r,Wfe);else if(r.type==="execute")e.message(4,r,Gfe);else if(r.type==="batch")e.message(5,r,Qfe);else if(r.type==="open_cursor")e.message(6,r,Yfe);else if(r.type==="close_cursor")e.message(7,r,Xfe);else if(r.type==="fetch_cursor")e.message(8,r,eme);else if(r.type==="sequence")e.message(9,r,tme);else if(r.type==="describe")e.message(10,r,rme);else if(r.type==="store_sql")e.message(11,r,nme);else if(r.type==="close_sql")e.message(12,r,ome);else if(r.type==="get_autocommit")e.message(13,r,ime);else throw Je(r,"Impossible type of Request")}function Vfe(e,t){e.int32(1,t.streamId)}function Wfe(e,t){e.int32(1,t.streamId)}function Gfe(e,t){e.int32(1,t.streamId),e.message(2,t.stmt,Dp)}function Qfe(e,t){e.int32(1,t.streamId),e.message(2,t.batch,kl)}function Yfe(e,t){e.int32(1,t.streamId),e.int32(2,t.cursorId),e.message(3,t.batch,kl)}function Xfe(e,t){e.int32(1,t.cursorId)}function eme(e,t){e.int32(1,t.cursorId),e.uint32(2,t.maxCount)}function tme(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 rme(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 nme(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function ome(e,t){e.int32(1,t.sqlId)}function ime(e,t){e.int32(1,t.streamId)}var lF=v(()=>{AT();sn()});function ts(e){let t=Tr(e.message),r=Ur(e.code);return{message:t,code:r}}function Lp(e){let t=_n(e.cols,uF),r=Ip(e.rows).map((s)=>_n(s,dF)),o=Zo(e.affected_row_count),n=Ur(e.last_insert_rowid),i=n!==void 0?BigInt(n):void 0;return{cols:t,rows:r,affectedRowCount:o,lastInsertRowid:i}}function uF(e){let t=Ur(e.name),r=Ur(e.decltype);return{name:t,decltype:r}}function Ky(e){let t=new Map;Ip(e.step_results).forEach((o,n)=>{if(o!==null)t.set(n,Lp(kt(o)))});let r=new Map;return Ip(e.step_errors).forEach((o,n)=>{if(o!==null)r.set(n,ts(kt(o)))}),{stepResults:t,stepErrors:r}}function Vy(e){let t=Tr(e.type);if(t==="step_begin"){let r=Zo(e.step),o=_n(e.cols,uF);return{type:"step_begin",step:r,cols:o}}else if(t==="step_end"){let r=Zo(e.affected_row_count),o=Ur(e.last_insert_rowid),n=o!==void 0?BigInt(o):void 0;return{type:"step_end",affectedRowCount:r,lastInsertRowid:n}}else if(t==="step_error"){let r=Zo(e.step),o=ts(kt(e.error));return{type:"step_error",step:r,error:o}}else if(t==="row")return{type:"row",row:_n(e.row,dF)};else if(t==="error")return{type:"error",error:ts(kt(e.error))};else throw new Pe("Unexpected type of CursorEntry")}function Wy(e){let t=_n(e.params,sme),r=_n(e.cols,ame),o=Qi(e.is_explain),n=Qi(e.is_readonly);return{params:t,cols:r,isExplain:o,isReadonly:n}}function sme(e){return{name:Ur(e.name)}}function ame(e){let t=Tr(e.name),r=Ur(e.decltype);return{name:t,decltype:r}}function dF(e){let t=Tr(e.type);if(t==="null")return null;else if(t==="integer"){let r=Tr(e.value);return BigInt(r)}else if(t==="float")return Zo(e.value);else if(t==="text")return Tr(e.value);else if(t==="blob")return fl.toUint8Array(Tr(e.base64));else throw new Pe("Unexpected type of Value")}var Gy=v(()=>{Dy();_t();wl()});function pF(e){let t=Tr(e.type);if(t==="hello_ok")return{type:"hello_ok"};else if(t==="hello_error")return{type:"hello_error",error:ts(kt(e.error))};else if(t==="response_ok"){let r=Zo(e.request_id),o=cme(kt(e.response));return{type:"response_ok",requestId:r,response:o}}else if(t==="response_error"){let r=Zo(e.request_id),o=ts(kt(e.error));return{type:"response_error",requestId:r,error:o}}else throw new Pe("Unexpected type of ServerMsg")}function cme(e){let t=Tr(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:Lp(kt(e.result))};else if(t==="batch")return{type:"batch",result:Ky(kt(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=_n(e.entries,Vy),o=Qi(e.done);return{type:"fetch_cursor",entries:r,done:o}}else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:Wy(kt(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:Qi(e.is_autocommit)};else throw new Pe("Unexpected type of Response")}var fF=v(()=>{_t();wl();Gy()});var an,rs,mF,hF,Al,lme,ume,Qy,dme,pme,fme,Rl,mme,hme,gme;var Yy=v(()=>{an={default(){return{message:"",code:void 0}},1(e,t){t.message=e.string()},2(e,t){t.code=e.string()}},rs={default(){return{cols:[],rows:[],affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.cols.push(e.message(mF))},2(e,t){t.rows.push(e.message(hF))},3(e,t){t.affectedRowCount=Number(e.uint64())},4(e,t){t.lastInsertRowid=e.sint64()}},mF={default(){return{name:void 0,decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},hF={default(){return[]},1(e,t){t.push(e.message(gme))}},Al={default(){return{stepResults:new Map,stepErrors:new Map}},1(e,t){let[r,o]=e.message(lme);t.stepResults.set(r,o)},2(e,t){let[r,o]=e.message(ume);t.stepErrors.set(r,o)}},lme={default(){return[0,rs.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(rs)}},ume={default(){return[0,an.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(an)}},Qy={default(){return{type:"none"}},1(e){return e.message(dme)},2(e){return e.message(pme)},3(e){return e.message(fme)},4(e){return{type:"row",row:e.message(hF)}},5(e){return{type:"error",error:e.message(an)}}},dme={default(){return{type:"step_begin",step:0,cols:[]}},1(e,t){t.step=e.uint32()},2(e,t){t.cols.push(e.message(mF))}},pme={default(){return{type:"step_end",affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.affectedRowCount=e.uint32()},2(e,t){t.lastInsertRowid=e.uint64()}},fme={default(){return{type:"step_error",step:0,error:an.default()}},1(e,t){t.step=e.uint32()},2(e,t){t.error=e.message(an)}},Rl={default(){return{params:[],cols:[],isExplain:!1,isReadonly:!1}},1(e,t){t.params.push(e.message(mme))},2(e,t){t.cols.push(e.message(hme))},3(e,t){t.isExplain=e.bool()},4(e,t){t.isReadonly=e.bool()}},mme={default(){return{name:void 0}},1(e,t){t.name=e.string()}},hme={default(){return{name:"",decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},gme={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 gF,yme,bme,Sme,vme,wme,xme,_me,Eme;var yF=v(()=>{Yy();gF={default(){return{type:"none"}},1(e){return{type:"hello_ok"}},2(e){return e.message(yme)},3(e){return e.message(Sme)},4(e){return e.message(bme)}},yme={default(){return{type:"hello_error",error:an.default()}},1(e,t){t.error=e.message(an)}},bme={default(){return{type:"response_error",requestId:0,error:an.default()}},1(e,t){t.requestId=e.int32()},2(e,t){t.error=e.message(an)}},Sme={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(vme)},5(e,t){t.response=e.message(wme)},6(e,t){t.response={type:"open_cursor"}},7(e,t){t.response={type:"close_cursor"}},8(e,t){t.response=e.message(xme)},9(e,t){t.response={type:"sequence"}},10(e,t){t.response=e.message(_me)},11(e,t){t.response={type:"store_sql"}},12(e,t){t.response={type:"close_sql"}},13(e,t){t.response=e.message(Eme)}},vme={default(){return{type:"execute",result:rs.default()}},1(e,t){t.result=e.message(rs)}},wme={default(){return{type:"batch",result:Al.default()}},1(e,t){t.result=e.message(Al)}},xme={default(){return{type:"fetch_cursor",entries:[],done:!1}},1(e,t){t.entries.push(e.message(Qy))},2(e,t){t.done=e.bool()}},_me={default(){return{type:"describe",result:Rl.default()}},1(e,t){t.result=e.message(Rl)}},Eme={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}}});var bF,RT,Xy;var eb=v(()=>{gT();_t();yT();$p();_l();sn();_T();oF();lF();fF();yF();bF=new Map([["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]),RT=new Map([["hrana3-protobuf",{version:3,encoding:"protobuf"}],["hrana3",{version:3,encoding:"json"}],["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]);Xy=class Xy extends bl{#e;#t;#r;#n;#o;#i;#a;#s;#c;_streamIdAlloc;_cursorIdAlloc;#l;constructor(e,t){super();this.#e=e,this.#t=[],this.#r=!1,this.#n=void 0,this.#o=!1,this.#i=void 0,this.#a=!1,this.#s=new Map,this.#c=new Xi,this._streamIdAlloc=new Xi,this._cursorIdAlloc=new Xi,this.#l=new Xi,this.#e.binaryType="arraybuffer",this.#e.addEventListener("open",()=>this.#p()),this.#e.addEventListener("close",(r)=>this.#g(r)),this.#e.addEventListener("error",(r)=>this.#f(r)),this.#e.addEventListener("message",(r)=>this.#y(r)),this.#d({type:"hello",jwt:t})}#d(e){if(this.#n!==void 0)throw new or("Trying to send a message on a closed client");if(this.#r)this.#m(e);else{let t=()=>this.#m(e),r=()=>{return};this.#t.push({openCallback:t,errorCallback:r})}}#p(){let e=this.#e.protocol;if(e===void 0){this.#u(new Ge("The `WebSocket.protocol` property is undefined. This most likely means that the WebSocket implementation provided by the environment is broken. If you are using Miniflare 2, please update to Miniflare 3, which fixes this problem."));return}else if(e==="")this.#i={version:1,encoding:"json"};else if(this.#i=RT.get(e),this.#i===void 0){this.#u(new Pe(`Unrecognized WebSocket subprotocol: ${JSON.stringify(e)}`));return}for(let t of this.#t)t.openCallback();this.#t.length=0,this.#r=!0}#m(e){let t=this.#i.encoding;if(t==="json"){let r=kp(e,nF);this.#e.send(r)}else if(t==="protobuf"){let r=Tp(e,cF);this.#e.send(r)}else throw Je(t,"Impossible encoding")}getVersion(){return new Promise((e,t)=>{if(this.#a=!0,this.#n!==void 0)t(this.#n);else if(!this.#r){let r=()=>e(this.#i.version);this.#t.push({openCallback:r,errorCallback:t})}else e(this.#i.version)})}_ensureVersion(e,t){if(this.#i===void 0||!this.#a)throw new xn(`${t} is supported only on protocol version ${e} and higher, but the version supported by the WebSocket server is not yet known. Use Client.getVersion() to wait until the version is available.`);else if(this.#i.version<e)throw new xn(`${t} is supported on protocol version ${e} and higher, but the WebSocket server only supports version ${this.#i.version}`)}_sendRequest(e,t){if(this.#n!==void 0){t.errorCallback(new xt("Client is closed",this.#n));return}let r=this.#c.alloc();this.#s.set(r,{...t,type:e.type}),this.#d({type:"request",requestId:r,request:e})}#f(e){let r=e.message??"WebSocket was closed due to an error";this.#u(new Sl(r))}#g(e){let t=`WebSocket was closed with code ${e.code}`;if(e.reason)t+=`: ${e.reason}`;this.#u(new Sl(t))}#u(e){if(this.#n!==void 0)return;this.#n=e;for(let t of this.#t)t.errorCallback(e);this.#t.length=0;for(let[t,r]of this.#s.entries())r.errorCallback(e),this.#c.free(t);this.#s.clear(),this.#e.close()}#y(e){if(this.#n!==void 0)return;try{let t,r=this.#i.encoding;if(r==="json"){if(typeof e.data!=="string"){this.#e.close(3003,"Only text messages are accepted with JSON encoding"),this.#u(new Pe("Received non-text message from server with JSON encoding"));return}t=pa(JSON.parse(e.data),pF)}else if(r==="protobuf"){if(!(e.data instanceof ArrayBuffer)){this.#e.close(3003,"Only binary messages are accepted with Protobuf encoding"),this.#u(new Pe("Received non-binary message from server with Protobuf encoding"));return}t=Yi(new Uint8Array(e.data),gF)}else throw Je(r,"Impossible encoding");this.#b(t)}catch(t){this.#e.close(3007,"Could not handle message"),this.#u(t)}}#b(e){if(e.type==="none")throw new Pe("Received an unrecognized ServerMsg");else if(e.type==="hello_ok"||e.type==="hello_error"){if(this.#o)throw new Pe("Received a duplicated hello response");if(this.#o=!0,e.type==="hello_error")throw Uo(e.error);return}else if(!this.#o)throw new Pe("Received a non-hello message before a hello response");if(e.type==="response_ok"){let t=e.requestId,r=this.#s.get(t);if(this.#s.delete(t),r===void 0)throw new Pe("Received unexpected OK response");this.#c.free(t);try{if(r.type!==e.response.type)throw console.dir({responseState:r,msg:e}),new Pe("Received unexpected type of response");r.responseCallback(e.response)}catch(o){throw r.errorCallback(o),o}}else if(e.type==="response_error"){let t=e.requestId,r=this.#s.get(t);if(this.#s.delete(t),r===void 0)throw new Pe("Received unexpected error response");this.#c.free(t),r.errorCallback(Uo(e.error))}else throw Je(e,"Impossible ServerMsg type")}openStream(){return zp.open(this)}storeSql(e){this._ensureVersion(2,"storeSql()");let t=this.#l.alloc(),r=new ha(this,t),o=()=>{return},n=(s)=>r._setClosed(s),i={type:"store_sql",sqlId:t,sql:e};return this._sendRequest(i,{responseCallback:o,errorCallback:n}),r}_closeSql(e){if(this.#n!==void 0)return;let t=()=>this.#l.free(e),r=(n)=>this.#u(n),o={type:"close_sql",sqlId:e};this._sendRequest(o,{responseCallback:t,errorCallback:r})}close(){this.#u(new Ge("Client was manually closed"))}get closed(){return this.#n!==void 0}}});var ga;var SF=v(()=>{if(typeof queueMicrotask<"u")ga=queueMicrotask;else{let e=Promise.resolve();ga=(t)=>{e.then(t)}}});class TT{#e;#t;#r;constructor(e){this.#e=new Uint8Array(new ArrayBuffer(e)),this.#t=0,this.#r=0}get length(){return this.#r-this.#t}data(){return this.#e.slice(this.#t,this.#r)}push(e){this.#n(e.byteLength),this.#e.set(e,this.#r),this.#r+=e.byteLength}#n(e){if(this.#r+e<=this.#e.byteLength)return;let t=this.#r-this.#t;if(t+e<=this.#e.byteLength&&2*this.#r>=this.#e.byteLength)this.#e.copyWithin(0,this.#t,this.#r);else{let r=this.#e.byteLength;do r*=2;while(t+e>r);let o=new Uint8Array(new ArrayBuffer(r));o.set(this.#e.slice(this.#t,this.#r),0),this.#e=o}this.#r=t,this.#t=0}shift(e){this.#t+=e}}function vF(e){let t=Ur(e.baton),r=Ur(e.base_url),o=_n(e.results,Ime);return{baton:t,baseUrl:r,results:o}}function Ime(e){let t=Tr(e.type);if(t==="ok")return{type:"ok",response:kme(kt(e.response))};else if(t==="error")return{type:"error",error:ts(kt(e.error))};else throw new Pe("Unexpected type of StreamResult")}function kme(e){let t=Tr(e.type);if(t==="close")return{type:"close"};else if(t==="execute")return{type:"execute",result:Lp(kt(e.result))};else if(t==="batch")return{type:"batch",result:Ky(kt(e.result))};else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:Wy(kt(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:Qi(e.is_autocommit)};else throw new Pe("Unexpected type of StreamResponse")}function wF(e){let t=Ur(e.baton),r=Ur(e.base_url);return{baton:t,baseUrl:r}}var $T=v(()=>{_t();wl();Gy()});var xF,Ame,Rme,Tme,$me,Ome,Cme,_F;var OT=v(()=>{Yy();xF={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(Ame))}},Ame={default(){return{type:"none"}},1(e){return{type:"ok",response:e.message(Rme)}},2(e){return{type:"error",error:e.message(an)}}},Rme={default(){return{type:"none"}},1(e){return{type:"close"}},2(e){return e.message(Tme)},3(e){return e.message($me)},4(e){return{type:"sequence"}},5(e){return e.message(Ome)},6(e){return{type:"store_sql"}},7(e){return{type:"close_sql"}},8(e){return e.message(Cme)}},Tme={default(){return{type:"execute",result:rs.default()}},1(e,t){t.result=e.message(rs)}},$me={default(){return{type:"batch",result:Al.default()}},1(e,t){t.result=e.message(Al)}},Ome={default(){return{type:"describe",result:Rl.default()}},1(e,t){t.result=e.message(Rl)}},Cme={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}},_F={default(){return{baton:void 0,baseUrl:void 0}},1(e,t){t.baton=e.string()},2(e,t){t.baseUrl=e.string()}}});var CT;var EF=v(()=>{wl();mT();_t();sn();$T();OT();Gy();Yy();CT=class CT extends Pp{#e;#t;#r;#n;#o;#i;constructor(e,t){super();this.#e=e,this.#t=t,this.#r=void 0,this.#n=new TT(16384),this.#o=void 0,this.#i=!1}async open(e){if(e.body===null)throw new Pe("No response body for cursor request");this.#r=e.body[Symbol.asyncIterator]();let t=await this.#a(wF,_F);if(t===void 0)throw new Pe("Empty response to cursor request");return t}next(){return this.#a(Vy,Qy)}close(){this._setClosed(new Ge("Cursor was manually closed"))}_setClosed(e){if(this.#o!==void 0)return;if(this.#o=e,this.#e._cursorClosed(this),this.#r!==void 0)this.#r.return()}get closed(){return this.#o!==void 0}async#a(e,t){for(;;){if(this.#i)return;else if(this.#o!==void 0)throw new xt("Cursor is closed",this.#o);if(this.#t==="json"){let n=this.#s();if(n!==void 0){let i=new TextDecoder().decode(n),s=JSON.parse(i);return pa(s,e)}}else if(this.#t==="protobuf"){let n=this.#c();if(n!==void 0)return Yi(n,t)}else throw Je(this.#t,"Impossible encoding");if(this.#r===void 0)throw new or("Attempted to read from HTTP cursor before it was opened");let{value:r,done:o}=await this.#r.next();if(o&&this.#n.length===0)this.#i=!0;else if(o)throw new Pe("Unexpected end of cursor stream");else this.#n.push(r)}}#s(){let e=this.#n.data(),t=10,r=e.indexOf(10);if(r<0)return;let o=e.slice(0,r);return this.#n.shift(r+1),o}#c(){let e=this.#n.data(),t=0,r=0;for(;;){if(r>=e.byteLength)return;let n=e[r];if(t|=(n&127)<<7*r,r+=1,!(n&128))break}if(e.byteLength<r+t)return;let o=e.slice(r,r+t);return this.#n.shift(r+t),o}}});function IF(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.arrayObjects("requests",t.requests,Pme)}function Pme(e,t){if(e.stringRaw("type",t.type),t.type==="close");else if(t.type==="execute")e.object("stmt",t.stmt,Np);else if(t.type==="batch")e.object("batch",t.batch,Il);else if(t.type==="sequence"){if(t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="describe"){if(t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="store_sql")e.number("sql_id",t.sqlId),e.string("sql",t.sql);else if(t.type==="close_sql")e.number("sql_id",t.sqlId);else if(t.type==="get_autocommit");else throw Je(t,"Impossible type of StreamRequest")}function kF(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.object("batch",t.batch,Il)}var PT=v(()=>{IT();sn()});function AF(e,t){if(t.baton!==void 0)e.string(1,t.baton);for(let r of t.requests)e.message(2,r,zme)}function zme(e,t){if(t.type==="close")e.message(1,t,Nme);else if(t.type==="execute")e.message(2,t,Dme);else if(t.type==="batch")e.message(3,t,Lme);else if(t.type==="sequence")e.message(4,t,Bme);else if(t.type==="describe")e.message(5,t,jme);else if(t.type==="store_sql")e.message(6,t,Zme);else if(t.type==="close_sql")e.message(7,t,Ume);else if(t.type==="get_autocommit")e.message(8,t,Mme);else throw Je(t,"Impossible type of StreamRequest")}function Nme(e,t){}function Dme(e,t){e.message(1,t.stmt,Dp)}function Lme(e,t){e.message(1,t.batch,kl)}function Bme(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function jme(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function Zme(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function Ume(e,t){e.int32(1,t.sqlId)}function Mme(e,t){}function RF(e,t){if(t.baton!==void 0)e.string(1,t.baton);e.message(2,t.batch,kl)}var zT=v(()=>{AT();sn()});function qme(e,t){if(t.results.length!==e.length)throw new Pe("Server returned unexpected number of pipeline results");for(let r=0;r<e.length;++r){let o=t.results[r],n=e[r];if(o.type==="ok"){if(o.response.type!==n.request.type)throw new Pe("Received unexpected type of response");n.responseCallback(o.response)}else if(o.type==="error")n.errorCallback(Uo(o.error));else if(o.type==="none")throw new Pe("Received unrecognized type of StreamResult");else throw Je(o,"Received impossible type of StreamResult")}}async function Fme(e,t){if(t==="json"){let r=await e.json();return pa(r,vF)}if(t==="protobuf"){let r=await e.arrayBuffer();return Yi(new Uint8Array(r),xF)}throw await e.body?.cancel(),Je(t,"Impossible encoding")}async function Hme(e){let t=e.headers.get("content-type")??"text/plain",r=`Server returned HTTP status ${e.status}`;if(t==="application/json"){let o=await e.json();if("message"in o)return Uo(o);return new da(r,e.status)}if(t==="text/plain"){let o=(await e.text()).trim();if(o!=="")r+=`: ${o}`;return new da(r,e.status)}return await e.body?.cancel(),new da(r,e.status)}var tb;var NT=v(()=>{_t();gT();yT();SF();$p();_l();Jy();sn();EF();PT();zT();PT();zT();$T();OT();tb=class tb extends El{#e;#t;#r;#n;#o;#i;#a;#s;#c;#l;#d;#p;#m;constructor(e,t,r,o,n){super(e.intMode);this.#e=e,this.#t=t.toString(),this.#r=r,this.#n=o,this.#o=n,this.#i=void 0,this.#a=new es,this.#s=!1,this.#l=!1,this.#d=!1,this.#p=void 0,this.#m=new Xi}client(){return this.#e}_sqlOwner(){return this}storeSql(e){let t=this.#m.alloc();return this.#f({type:"store_sql",sqlId:t,sql:e}).then(()=>{return},(r)=>this._setClosed(r)),new ha(this,t)}_closeSql(e){if(this.#p!==void 0)return;this.#f({type:"close_sql",sqlId:e}).then(()=>this.#m.free(e),(t)=>this._setClosed(t))}_execute(e){return this.#f({type:"execute",stmt:e}).then((t)=>t.result)}_batch(e){return this.#f({type:"batch",batch:e}).then((t)=>t.result)}_describe(e){return this.#f({type:"describe",sql:e.sql,sqlId:e.sqlId}).then((t)=>t.result)}_sequence(e){return this.#f({type:"sequence",sql:e.sql,sqlId:e.sqlId}).then((t)=>{return})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#f({type:"get_autocommit"}).then((e)=>e.isAutocommit)}#f(e){return new Promise((t,r)=>{this.#g({type:"pipeline",request:e,responseCallback:t,errorCallback:r})})}_openCursor(e){return new Promise((t,r)=>{this.#g({type:"cursor",batch:e,cursorCallback:t,errorCallback:r})})}_cursorClosed(e){if(e!==this.#c)throw new or("Cursor was closed, but it was not associated with the stream");this.#c=void 0,ga(()=>this.#u())}close(){this._setClosed(new Ge("Stream was manually closed"))}closeGracefully(){this.#l=!0,ga(()=>this.#u())}get closed(){return this.#p!==void 0||this.#l}_setClosed(e){if(this.#p!==void 0)return;if(this.#p=e,this.#c!==void 0)this.#c._setClosed(e);this.#e._streamClosed(this);for(;;){let t=this.#a.shift();if(t!==void 0)t.errorCallback(e);else break}if((this.#i!==void 0||this.#s)&&!this.#d)this.#a.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0,ga(()=>this.#u())}#g(e){if(this.#p!==void 0)throw new xt("Stream is closed",this.#p);else if(this.#l)throw new xt("Stream is closing",void 0);else this.#a.push(e),ga(()=>this.#u())}#u(){if(this.#s||this.#c!==void 0)return;if(this.#l&&this.#a.length===0){this._setClosed(new Ge("Stream was gracefully closed"));return}let e=this.#e._endpoint;if(e===void 0){this.#e._endpointPromise.then(()=>this.#u(),(r)=>this._setClosed(r));return}let t=this.#a.shift();if(t===void 0)return;else if(t.type==="pipeline"){let r=[t];for(;;){let o=this.#a.first();if(o!==void 0&&o.type==="pipeline")r.push(o),this.#a.shift();else if(o===void 0&&this.#l&&!this.#d){r.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0;break}else break}this.#y(e,r)}else if(t.type==="cursor")this.#b(e,t);else throw Je(t,"Impossible type of QueueEntry")}#y(e,t){this.#h(()=>this.#S(t,e),(r)=>Fme(r,e.encoding),(r)=>r.baton,(r)=>r.baseUrl,(r)=>qme(t,r),(r)=>t.forEach((o)=>o.errorCallback(r)))}#b(e,t){let r=new CT(this,e.encoding);this.#c=r,this.#h(()=>this.#v(t,e),(o)=>r.open(o),(o)=>o.baton,(o)=>o.baseUrl,(o)=>t.cursorCallback(r),(o)=>t.errorCallback(o))}#h(e,t,r,o,n,i){let s;try{let a=e(),l=this.#n;s=l(a)}catch(a){s=Promise.reject(a)}this.#s=!0,s.then((a)=>{if(!a.ok)return Hme(a).then((l)=>{throw l});return t(a)}).then((a)=>{this.#i=r(a),this.#t=o(a)??this.#t,n(a)}).catch((a)=>{this._setClosed(a),i(a)}).finally(()=>{this.#s=!1,this.#u()})}#S(e,t){return this.#w(new URL(t.pipelinePath,this.#t),{baton:this.#i,requests:e.map((r)=>r.request)},t.encoding,IF,AF)}#v(e,t){if(t.cursorPath===void 0)throw new xn(`Cursors are supported only on protocol version 3 and higher, but the HTTP server only supports version ${t.version}.`);return this.#w(new URL(t.cursorPath,this.#t),{baton:this.#i,batch:e.batch},t.encoding,kF,RF)}#w(e,t,r,o,n){let i,s;if(r==="json")i=kp(t,o),s="application/json";else if(r==="protobuf")i=Tp(t,n),s="application/x-protobuf";else throw Je(r,"Impossible encoding");let a=new Headers;if(a.set("content-type",s),this.#r!==void 0)a.set("authorization",`Bearer ${this.#r}`);if(this.#o!==void 0)a.set("x-turso-encryption-key",this.#o);return new Request(e.toString(),{method:"POST",headers:a,body:i})}}});async function Kme(e,t){let r=e;for(let o of Jme){let n=new URL(o.versionPath,t),i=new Request(n.toString(),{method:"GET"}),s=await r(i);if(await s.arrayBuffer(),s.ok)return o}return DT}var Jme,DT,rb;var LT=v(()=>{_t();NT();Jme=[{versionPath:"v3-protobuf",pipelinePath:"v3-protobuf/pipeline",cursorPath:"v3-protobuf/cursor",version:3,encoding:"protobuf"}],DT={versionPath:"v2",pipelinePath:"v2/pipeline",cursorPath:void 0,version:2,encoding:"json"};rb=class rb extends bl{#e;#t;#r;#n;#o;#i;_endpointPromise;_endpoint;constructor(e,t,r,o,n=2){super();if(this.#e=e,this.#t=t,this.#r=r??globalThis.fetch,this.#n=o,this.#o=void 0,this.#i=new Set,n==3)this._endpointPromise=Kme(this.#r,this.#e),this._endpointPromise.then((i)=>this._endpoint=i,(i)=>this.#a(i));else this._endpointPromise=Promise.resolve(DT),this._endpointPromise.then((i)=>this._endpoint=i,(i)=>this.#a(i))}async getVersion(){if(this._endpoint!==void 0)return this._endpoint.version;return(await this._endpointPromise).version}_ensureVersion(e,t){if(e<=DT.version)return;else if(this._endpoint===void 0)throw new xn(`${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 xn(`${t} is supported only on protocol version ${e} and higher, but the HTTP server only supports version ${this._endpoint.version}.`)}openStream(){if(this.#o!==void 0)throw new xt("Client is closed",this.#o);let e=new tb(this,this.#e,this.#t,this.#r,this.#n);return this.#i.add(e),e}_streamClosed(e){this.#i.delete(e)}close(){this.#a(new Ge("Client was manually closed"))}get closed(){return this.#o!==void 0}#a(e){if(this.#o!==void 0)return;this.#o=e;for(let t of Array.from(this.#i))t._setClosed(new xt("Client was closed",e))}}});var TF=v(()=>{_t()});function BT(e,t,r=2){if(typeof Gi>"u")throw new Ep("WebSockets are not supported in this environment");var o=void 0;if(r==3)o=Array.from(RT.keys());else o=Array.from(bF.keys());let n=new Gi(e,o);return new Xy(n,t)}function jT(e,t,r,o,n=2){return new rb(e instanceof URL?e:new URL(e),t,r,o,n)}var nb=v(()=>{fT();eb();_t();LT();eb();fT();wT();TF();_l();Fy();Jy();LT();NT();eb();_T();_t()});class Bp{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}execute(e){return this.batch([e]).then((t)=>t[0])}async batch(e){let t=this._getStream();if(t.closed)throw new Ce("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{let r=e.map(Mo),o;if(this.#r===void 0){this._getSqlCache().apply(r);let i=t.batch(this.#t>=3),s=i.step(),a=s.run(Vi(this.#e)),l=s;o=r.map((u)=>{let d=i.step().condition(dt.ok(l));if(this.#t>=3)d.condition(dt.not(dt.isAutocommit(i)));let p=d.query(u);return p.catch(()=>{return}),l=d,p}),this.#r=i.execute().then(()=>a).then(()=>{return});try{await this.#r}catch(u){throw this.close(),u}}else{if(this.#t<3)await this.#r;this._getSqlCache().apply(r);let i=t.batch(this.#t>=3),s=void 0;o=r.map((a)=>{let l=i.step();if(s!==void 0)l.condition(dt.ok(s));if(this.#t>=3)l.condition(dt.not(dt.isAutocommit(i)));let u=l.query(a);return u.catch(()=>{return}),s=l,u}),await i.execute()}let n=[];for(let i=0;i<o.length;i++)try{let s=await o[i];if(s===void 0)throw new Gt("Statement in a transaction was not executed, probably because the transaction has been rolled back",i,"TRANSACTION_CLOSED");n.push($l(s))}catch(s){if(s instanceof Gt)throw s;let a=st(s);if(a instanceof Ce)throw new Gt(a.message,i,a.code,a.extendedCode,a.rawCode,a.cause instanceof Error?a.cause:void 0);throw a}return n}catch(r){throw st(r)}}async executeMultiple(e){let t=this._getStream();if(t.closed)throw new Ce("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{if(this.#r===void 0){this.#r=t.run(Vi(this.#e)).then(()=>{return});try{await this.#r}catch(r){throw this.close(),r}}else await this.#r;await t.sequence(e)}catch(r){throw st(r)}}async rollback(){try{let e=this._getStream();if(e.closed)return;if(this.#r!==void 0);else return;let t=e.run("ROLLBACK").catch((r)=>{throw st(r)});e.closeGracefully(),await t}catch(e){throw st(e)}finally{this.close()}}async commit(){try{let e=this._getStream();if(e.closed)throw new Ce("Cannot commit the transaction because it is already closed","TRANSACTION_CLOSED");if(this.#r!==void 0)await this.#r;else return;let t=e.run("COMMIT").catch((r)=>{throw st(r)});e.closeGracefully(),await t}catch(e){throw st(e)}finally{this.close()}}}async function Tl(e,t,r,o,n=!1){if(n)r.step().run("PRAGMA foreign_keys=off");let i=r.step(),s=i.run(Vi(e)),a=i,l=o.map((h)=>{let b=r.step().condition(dt.ok(a));if(t>=3)b.condition(dt.not(dt.isAutocommit(r)));let y=b.query(h);return a=b,y}),u=r.step().condition(dt.ok(a));if(t>=3)u.condition(dt.not(dt.isAutocommit(r)));let d=u.run("COMMIT");if(r.step().condition(dt.not(dt.ok(u))).run("ROLLBACK").catch((h)=>{return}),n)r.step().run("PRAGMA foreign_keys=on");await r.execute();let m=[];await s;for(let h=0;h<l.length;h++)try{let b=await l[h];if(b===void 0)throw new Gt("Statement in a batch was not executed, probably because the transaction has been rolled back",h,"TRANSACTION_CLOSED");m.push($l(b))}catch(b){if(b instanceof Gt)throw b;let y=st(b);if(y instanceof Ce)throw new Gt(y.message,h,y.code,y.extendedCode,y.rawCode,y.cause instanceof Error?y.cause:void 0);throw y}return await d,m}function Mo(e){let t,r;if(Array.isArray(e))[t,r]=e;else if(typeof e==="string")t=e;else t=e.sql,r=e.args;let o=new Cp(t);if(r)if(Array.isArray(r))o.bindIndexes(r);else for(let[n,i]of Object.entries(r))o.bindName(n,i);return o}function $l(e){let t=e.columnNames.map((s)=>s??""),r=e.columnDecltypes.map((s)=>s??""),o=e.rows,n=e.affectedRowCount,i=e.lastInsertRowid!==void 0?e.lastInsertRowid:void 0;return new ml(t,r,o,n,i)}function st(e){if(e instanceof Ge){let t=$F(e);return new Ce(e.message,t,void 0,void 0,e)}return e}function $F(e){if(e instanceof _p&&e.code!==void 0)return e.code;else if(e instanceof Pe)return"HRANA_PROTO_ERROR";else if(e instanceof xt)return e.cause instanceof Ge?$F(e.cause):"HRANA_CLOSED_ERROR";else if(e instanceof Sl)return"HRANA_WEBSOCKET_ERROR";else if(e instanceof da)return"SERVER_ERROR";else if(e instanceof xn)return"PROTOCOL_VERSION_ERROR";else if(e instanceof or)return"INTERNAL_ERROR";else return"UNKNOWN"}var UT=v(()=>{nb();wn();hl()});class Ol{#e;#t;capacity;constructor(e,t){this.#e=e,this.#t=new OF,this.capacity=t}apply(e){if(this.capacity<=0)return;let t=new Set;for(let r of e){if(typeof r.sql!=="string")continue;let o=r.sql;if(o.length>=5000)continue;let n=this.#t.get(o);if(n===void 0){while(this.#t.size+1>this.capacity){let[i,s]=this.#t.peekLru();if(t.has(s))break;s.close(),this.#t.delete(i)}if(this.#t.size+1<=this.capacity)n=this.#e.storeSql(o),this.#t.set(o,n)}if(n!==void 0)r.sql=n,t.add(n)}}}class OF{#e;constructor(){this.#e=new Map}get(e){let t=this.#e.get(e);if(t!==void 0)this.#e.delete(e),this.#e.set(e,t);return t}set(e,t){this.#e.set(e,t)}peekLru(){for(let e of this.#e.entries())return e;return}delete(e){this.#e.delete(e)}get size(){return this.#e.size}}var MT=ge(function(vje,PF){function Vme(e){var t=0,r=[];function o(){if(t--,t<e)n()}function n(){var l=r.shift();if(a.queue=r.length,l)s(l.fn).then(l.resolve).catch(l.reject)}function i(l){return new Promise(function(u,d){r.push({fn:l,resolve:u,reject:d}),a.queue=r.length})}function s(l){t++;try{return Promise.resolve(l()).then(function(u){return o(),u},function(u){throw o(),u})}catch(u){return o(),Promise.reject(u)}}var a=function(l){if(t>=e)return i(l);else return s(l)};return a}function Wme(e,t){var r=!1,o=this;return Promise.all(e.map(function(){var n=arguments;return o(function(){if(!r)return t.apply(void 0,n).catch(function(i){throw r=!0,i})})}))}function CF(e){return e.queue=0,e.map=Wme,e}PF.exports=function(e){if(e)return CF(Vme(e));else return CF(function(t){return t()})}});function DF(e){if(e.scheme!=="wss"&&e.scheme!=="ws")throw new Ce(`The WebSocket client supports only "libsql:", "wss:" and "ws:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${eo}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Ce("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="ws"&&e.tls)throw new Ce('A "ws:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="wss"&&!e.tls)throw new Ce('A "wss:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=bp(e.scheme,e.authority,e.path),r;try{r=BT(t,e.authToken)}catch(o){if(o instanceof Ep){let n=e.scheme==="wss"?"https":"http",i=bp(n,e.authority,e.path);throw new Ce(`This environment does not support WebSockets, please switch to the HTTP client by using a "${n}:" URL (${JSON.stringify(i)}). For more information, please read ${eo}`,"WEBSOCKETS_NOT_SUPPORTED")}throw st(o)}return new LF(r,t,e.authToken,e.intMode,e.concurrency)}class LF{#e;#t;#r;#n;#o;closed;protocol;#i;#a;constructor(e,t,r,o,n){this.#e=t,this.#t=r,this.#r=o,this.#n=this.#c(e),this.#o=void 0,this.closed=!1,this.protocol="ws",this.#a=NF.default(n)}async limit(e){return this.#a(e)}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.limit(async()=>{let o=await this.#s();try{let n=Mo(r);o.conn.sqlCache.apply([n]);let i=o.stream.query(n);o.stream.closeGracefully();let s=await i;return $l(s)}catch(n){throw st(n)}finally{this._closeStream(o)}})}async batch(e,t="deferred"){return this.limit(async()=>{let r=await this.#s();try{let n=e.map((u)=>{if(Array.isArray(u))return{sql:u[0],args:u[1]||[]};return u}).map(Mo),i=await r.conn.client.getVersion();r.conn.sqlCache.apply(n);let s=r.stream.batch(i>=3);return await Tl(t,i,s,n)}catch(o){throw st(o)}finally{this._closeStream(r)}})}async migrate(e){return this.limit(async()=>{let t=await this.#s();try{let r=e.map(Mo),o=await t.conn.client.getVersion(),n=t.stream.batch(o>=3);return await Tl("deferred",o,n,r,!0)}catch(r){throw st(r)}finally{this._closeStream(t)}})}async transaction(e="write"){return this.limit(async()=>{let t=await this.#s();try{let r=await t.conn.client.getVersion();return new BF(this,t,e,r)}catch(r){throw this._closeStream(t),st(r)}})}async executeMultiple(e){return this.limit(async()=>{let t=await this.#s();try{let r=t.stream.sequence(e);t.stream.closeGracefully(),await r}catch(r){throw st(r)}finally{this._closeStream(t)}})}sync(){throw new Ce("sync not supported in ws mode","SYNC_NOT_SUPPORTED")}async#s(){if(this.closed)throw new Ce("The client is closed","CLIENT_CLOSED");if(new Date().valueOf()-this.#n.openTime.valueOf()>Gme&&this.#o===void 0){let o=this.#c();this.#o=o,o.client.getVersion().then((n)=>{if(this.#n!==o){if(this.#n.streamStates.size===0)this.#n.client.close()}this.#n=o,this.#o=void 0},(n)=>{this.#o=void 0})}if(this.#n.client.closed)try{if(this.#o!==void 0)this.#n=this.#o;else this.#n=this.#c()}catch(o){throw st(o)}let r=this.#n;try{if(r.useSqlCache===void 0){if(r.useSqlCache=await r.client.getVersion()>=2,r.useSqlCache)r.sqlCache.capacity=zF}let o=r.client.openStream();o.intMode=this.#r;let n={conn:r,stream:o};return r.streamStates.add(n),n}catch(o){throw st(o)}}#c(e){try{return e??=BT(this.#e,this.#t),{client:e,useSqlCache:void 0,sqlCache:new Ol(e,0),openTime:new Date,streamStates:new Set}}catch(t){throw st(t)}}async reconnect(){try{for(let r of Array.from(this.#n.streamStates))try{r.stream.close()}catch{}this.#n.client.close()}catch{}if(this.#o){try{this.#o.client.close()}catch{}this.#o=void 0}let e=this.#c(),t=await e.client.getVersion();if(e.useSqlCache=t>=2,e.useSqlCache)e.sqlCache.capacity=zF;this.#n=e,this.closed=!1}_closeStream(e){e.stream.close();let t=e.conn;if(t.streamStates.delete(e),t.streamStates.size===0&&t!==this.#n)t.client.close()}close(){if(this.#n.client.close(),this.closed=!0,this.#o){try{this.#o.client.close()}catch{}this.#o=void 0}this.closed=!0}}var NF,Gme=60000,zF=100,BF;var jF=v(()=>{nb();wn();wp();UT();Py();hl();NF=Kl(MT(),1);wn();BF=class BF extends Bp{#e;#t;constructor(e,t,r,o){super(r,o);this.#e=e,this.#t=t}_getStream(){return this.#t.stream}_getSqlCache(){return this.#t.conn.sqlCache}close(){this.#e._closeStream(this.#t)}get closed(){return this.#t.stream.closed}}});function UF(e){if(e.scheme!=="https"&&e.scheme!=="http")throw new Ce(`The HTTP client supports only "libsql:", "https:" and "http:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${eo}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Ce("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="http"&&e.tls)throw new Ce('A "http:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="https"&&!e.tls)throw new Ce('A "https:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=bp(e.scheme,e.authority,e.path);return new qF(t,e.authToken,e.intMode,e.fetch,e.concurrency,e.remoteEncryptionKey)}class qF{#e;protocol;#t;#r;#n;#o;#i;#a;#s;constructor(e,t,r,o,n,i){this.#t=e,this.#i=t,this.#r=r,this.#n=o,this.#o=n,this.#a=i,this.#e=jT(this.#t,this.#i,this.#n,i),this.#e.intMode=this.#r,this.protocol="http",this.#s=ZF.default(this.#o)}async limit(e){return this.#s(e)}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.limit(async()=>{try{let o=Mo(r),n,i=this.#e.openStream();try{n=i.query(o)}finally{i.closeGracefully()}let s=await n;return $l(s)}catch(o){throw st(o)}})}async batch(e,t="deferred"){return this.limit(async()=>{try{let o=e.map((l)=>{if(Array.isArray(l))return{sql:l[0],args:l[1]||[]};return l}).map(Mo),n=await this.#e.getVersion(),i,s=this.#e.openStream();try{new Ol(s,MF).apply(o);let u=s.batch(!1);i=Tl(t,n,u,o)}finally{s.closeGracefully()}return await i}catch(r){throw st(r)}})}async migrate(e){return this.limit(async()=>{try{let t=e.map(Mo),r=await this.#e.getVersion(),o,n=this.#e.openStream();try{let s=n.batch(!1);o=Tl("deferred",r,s,t,!0)}finally{n.closeGracefully()}return await o}catch(t){throw st(t)}})}async transaction(e="write"){return this.limit(async()=>{try{let t=await this.#e.getVersion();return new FF(this.#e.openStream(),e,t)}catch(t){throw st(t)}})}async executeMultiple(e){return this.limit(async()=>{try{let t,r=this.#e.openStream();try{t=r.sequence(e)}finally{r.closeGracefully()}await t}catch(t){throw st(t)}})}sync(){throw new Ce("sync not supported in http mode","SYNC_NOT_SUPPORTED")}close(){this.#e.close()}async reconnect(){try{if(!this.closed)this.#e.close()}finally{this.#e=jT(this.#t,this.#i,this.#n,this.#a),this.#e.intMode=this.#r}}get closed(){return this.#e.closed}}var ZF,MF=30,FF;var HF=v(()=>{nb();wn();wp();UT();Py();hl();ZF=Kl(MT(),1);wn();FF=class FF extends Bp{#e;#t;constructor(e,t,r){super(t,r);this.#e=e,this.#t=new Ol(e,MF)}_getStream(){return this.#e}_getSqlCache(){return this.#t}close(){this.#e.close()}get closed(){return this.#e.closed}}});function Cl(e){return Qme(vp(e,!0))}function Qme(e){if(e.scheme==="wss"||e.scheme==="ws")return DF(e);else if(e.scheme==="https"||e.scheme==="http")return UF(e);else return Z4(e)}var qT=v(()=>{wp();H4();jF();HF();wn()});function oe(e,t){if(!e||typeof e!=="object")return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,F))throw Error(`Class "${t.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let r=Object.getPrototypeOf(e).constructor;if(r)while(r){if(F in r&&r[F]===t[F])return!0;r=Object.getPrototypeOf(r)}return!1}var F;var $e=v(()=>{F=Symbol.for("drizzle:entityKind")});var Ke;var En=v(()=>{$e();Ke=class Ke{constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.keyAsName=t.keyAsName,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.onUpdateFn=t.onUpdateFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType,this.generated=t.generated,this.generatedIdentity=t.generatedIdentity}static[F]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(e){return e}mapToDriverValue(e){return e}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}});var jp;var ob=v(()=>{$e();jp=class jp{static[F]="ColumnBuilder";config;constructor(e,t,r){this.config={name:e,keyAsName:e==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:t,columnType:r,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e){if(this.config.name!=="")return;this.config.name=e}}});var ir;var Pl=v(()=>{ir=Symbol.for("drizzle:Name")});var FT,JF;var KF=v(()=>{$e();Pl();FT=class FT{static[F]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,t){if(this.reference=()=>{let{name:r,columns:o,foreignColumns:n}=e();return{name:r,columns:o,foreignTable:n[0].table,foreignColumns:n}},t)this._onUpdate=t.onUpdate,this._onDelete=t.onDelete}onUpdate(e){return this._onUpdate=e===void 0?"no action":e,this}onDelete(e){return this._onDelete=e===void 0?"no action":e,this}build(e){return new JF(e,this)}};JF=class JF{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[F]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),o=t.map((s)=>s.name),n=r.map((s)=>s.name),i=[this.table[ir],...o,r[0].table[ir],...n];return e??`${i.join("_")}_fk`}}});function ib(e,...t){return e(...t)}var HT=()=>{};function JT(e,t){return`${e[ir]}_${t.join("_")}_unique`}var VF,Yme,WF;var GF=v(()=>{$e();Pl();VF=class VF{constructor(e,t){this.name=t,this.columns=e}static[F]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new WF(e,this.columns,this.nullsNotDistinctConfig,this.name)}};Yme=class Yme{static[F]="PgUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new VF(e,this.name)}};WF=class WF{constructor(e,t,r,o){this.table=e,this.columns=t,this.name=o??JT(this.table,this.columns.map((n)=>n.name)),this.nullsNotDistinct=r}static[F]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}}});function QF(e,t,r){for(let o=t;o<e.length;o++){let n=e[o];if(n==="\\"){o++;continue}if(n==='"')return[e.slice(t,o).replace(/\\/g,""),o+1];if(r)continue;if(n===","||n==="}")return[e.slice(t,o).replace(/\\/g,""),o]}return[e.slice(t).replace(/\\/g,""),e.length]}function YF(e,t=0){let r=[],o=t,n=!1;while(o<e.length){let i=e[o];if(i===","){if(n||o===t)r.push("");n=!0,o++;continue}if(n=!1,i==="\\"){o+=2;continue}if(i==='"'){let[l,u]=QF(e,o+1,!0);r.push(l),o=u;continue}if(i==="}")return[r,o+1];if(i==="{"){let[l,u]=YF(e,o+1);r.push(l),o=u;continue}let[s,a]=QF(e,o,!1);r.push(s),o=a}return[r,o]}function XF(e){let[t]=YF(e,1);return t}function KT(e){return`{${e.map((t)=>{if(Array.isArray(t))return KT(t);if(typeof t==="string")return`"${t.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${t}`}).join(",")}}`}var e3=()=>{};var Zp,zl,t3,Xme,r3,VT;var n3=v(()=>{ob();En();$e();KF();HT();GF();e3();Zp=class Zp extends jp{foreignKeyConfigs=[];static[F]="PgColumnBuilder";array(e){return new r3(this.config.name,this,e)}references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e,t){return this.config.isUnique=!0,this.config.uniqueName=e,this.config.uniqueType=t?.nulls,this}generatedAlwaysAs(e){return this.config.generated={as:e,type:"always",mode:"stored"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:r,actions:o})=>ib((n,i)=>{let s=new FT(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(i.onUpdate)s.onUpdate(i.onUpdate);if(i.onDelete)s.onDelete(i.onDelete);return s.build(t)},r,o))}buildExtraConfigColumn(e){return new t3(e,this.config)}};zl=class zl extends Ke{constructor(e,t){if(!t.uniqueName)t.uniqueName=JT(e,[t.name]);super(e,t);this.table=e}static[F]="PgColumn"};t3=class t3 extends zl{static[F]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(e){return this.indexConfig.opClass=e,this}};Xme=class Xme{static[F]="IndexedColumn";constructor(e,t,r,o){this.name=e,this.keyAsName=t,this.type=r,this.indexConfig=o}name;keyAsName;type;indexConfig};r3=class r3 extends Zp{static[F]="PgArrayBuilder";constructor(e,t,r){super(e,"array","PgArray");this.config.baseBuilder=t,this.config.size=r}build(e){let t=this.config.baseBuilder.build(e);return new VT(e,this.config,t)}};VT=class VT extends zl{constructor(e,t,r,o){super(e,t);this.baseColumn=r,this.range=o,this.size=t.size}size;static[F]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(e){if(typeof e==="string")e=XF(e);return e.map((t)=>this.baseColumn.mapFromDriverValue(t))}mapToDriverValue(e,t=!1){let r=e.map((o)=>o===null?null:oe(this.baseColumn,VT)?this.baseColumn.mapToDriverValue(o,!0):this.baseColumn.mapToDriverValue(o));if(t)return r;return KT(r)}}});function s3(e){return!!e&&typeof e==="function"&&o3 in e&&e[o3]===!0}var ehe,i3,o3,the,a3;var c3=v(()=>{$e();n3();ehe=class ehe extends Zp{static[F]="PgEnumObjectColumnBuilder";constructor(e,t){super(e,"string","PgEnumObjectColumn");this.config.enum=t}build(e){return new i3(e,this.config)}};i3=class i3 extends zl{static[F]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}};o3=Symbol.for("drizzle:isPgEnum");the=class the extends Zp{static[F]="PgEnumColumnBuilder";constructor(e,t){super(e,"string","PgEnumColumn");this.config.enum=t}build(e){return new a3(e,this.config)}};a3=class a3 extends zl{static[F]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}}});var pt,Up;var In=v(()=>{$e();pt=class pt{static[F]="Subquery";constructor(e,t,r,o=!1,n=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:r,isWith:o,usedTables:n}}};Up=class Up extends pt{static[F]="WithSubquery"}});var l3="0.45.2";var u3=()=>{};var WT,GT,d3;var p3=v(()=>{HT();u3();d3={startActiveSpan(e,t){if(!WT)return t();if(!GT)GT=WT.trace.getTracer("drizzle-orm",l3);return ib((r,o)=>o.startActiveSpan(e,(n)=>{try{return t(n)}catch(i){throw n.setStatus({code:r.SpanStatusCode.ERROR,message:i instanceof Error?i.message:"Unknown error"}),i}finally{n.end()}}),WT,GT)}}});var ft;var qo=v(()=>{ft=Symbol.for("drizzle:ViewBaseConfig")});function ns(e){return e[ir]}function ya(e){return`${e[sb]??"public"}.${e[ir]}`}var sb,ab,f3,QT,YT,Mp,m3,rhe,he;var sr=v(()=>{$e();Pl();sb=Symbol.for("drizzle:Schema"),ab=Symbol.for("drizzle:Columns"),f3=Symbol.for("drizzle:ExtraConfigColumns"),QT=Symbol.for("drizzle:OriginalName"),YT=Symbol.for("drizzle:BaseName"),Mp=Symbol.for("drizzle:IsAlias"),m3=Symbol.for("drizzle:ExtraConfigBuilder"),rhe=Symbol.for("drizzle:IsDrizzleTable");he=class he{static[F]="Table";static Symbol={Name:ir,Schema:sb,OriginalName:QT,Columns:ab,ExtraConfigColumns:f3,BaseName:YT,IsAlias:Mp,ExtraConfigBuilder:m3};[ir];[QT];[sb];[ab];[f3];[YT];[Mp]=!1;[rhe]=!0;[m3]=void 0;constructor(e,t,r){this[ir]=this[QT]=e,this[sb]=t,this[YT]=r}}});function XT(e){return e!==null&&e!==void 0&&typeof e.getSQL==="function"}function ohe(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 h3(e){return typeof e==="object"&&e!==null&&"mapToDriverValue"in e&&typeof e.mapToDriverValue==="function"}function C(e,...t){let r=[];if(t.length>0||e.length>0&&e[0]!=="")r.push(new Nt(e[0]));for(let[o,n]of t.entries())r.push(n,new Nt(e[o+1]));return new Ee(r)}function qp(e,t){return e.map((r)=>{if(oe(r,os)){if(!(r.name in t))throw Error(`No value for placeholder "${r.name}" was provided`);return t[r.name]}if(oe(r,Mr)&&oe(r.value,os)){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 nhe,Nt,Ee,cb,g3,y3,OZe,Mr,os,ihe,cn;var Yt=v(()=>{$e();c3();In();p3();qo();En();sr();nhe=class nhe{static[F]="FakePrimitiveParam"};Nt=class Nt{static[F]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new Ee([this])}};Ee=class Ee{constructor(e){this.queryChunks=e;for(let t of e)if(oe(t,he)){let r=t[he.Symbol.Schema];this.usedTables.push(r===void 0?t[he.Symbol.Name]:r+"."+t[he.Symbol.Name])}}static[F]="SQL";decoder=g3;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return d3.startActiveSpan("drizzle.buildSQL",(t)=>{let r=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":r.sql,"drizzle.query.params":JSON.stringify(r.params)}),r})}buildQueryFromSourceParams(e,t){let r=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{casing:o,escapeName:n,escapeParam:i,prepareTyping:s,inlineParams:a,paramStartIndex:l}=r;return ohe(e.map((u)=>{if(oe(u,Nt))return{sql:u.value.join(""),params:[]};if(oe(u,cb))return{sql:n(u.value),params:[]};if(u===void 0)return{sql:"",params:[]};if(Array.isArray(u)){let d=[new Nt("(")];for(let[p,m]of u.entries())if(d.push(m),p<u.length-1)d.push(new Nt(", "));return d.push(new Nt(")")),this.buildQueryFromSourceParams(d,r)}if(oe(u,Ee))return this.buildQueryFromSourceParams(u.queryChunks,{...r,inlineParams:a||u.shouldInlineParams});if(oe(u,he)){let d=u[he.Symbol.Schema],p=u[he.Symbol.Name];return{sql:d===void 0||u[Mp]?n(p):n(d)+"."+n(p),params:[]}}if(oe(u,Ke)){let d=o.getColumnCasing(u);if(t.invokeSource==="indexes")return{sql:n(d),params:[]};let p=u.table[he.Symbol.Schema];return{sql:u.table[Mp]||p===void 0?n(u.table[he.Symbol.Name])+"."+n(d):n(p)+"."+n(u.table[he.Symbol.Name])+"."+n(d),params:[]}}if(oe(u,cn)){let d=u[ft].schema,p=u[ft].name;return{sql:d===void 0||u[ft].isAlias?n(p):n(d)+"."+n(p),params:[]}}if(oe(u,Mr)){if(oe(u.value,os))return{sql:i(l.value++,u),params:[u],typings:["none"]};let d=u.value===null?null:u.encoder.mapToDriverValue(u.value);if(oe(d,Ee))return this.buildQueryFromSourceParams([d],r);if(a)return{sql:this.mapInlineParam(d,r),params:[]};let p=["none"];if(s)p=[s(u.encoder)];return{sql:i(l.value++,d),params:[d],typings:p}}if(oe(u,os))return{sql:i(l.value++,u),params:[u],typings:["none"]};if(oe(u,Ee.Aliased)&&u.fieldAlias!==void 0)return{sql:n(u.fieldAlias),params:[]};if(oe(u,pt)){if(u._.isWith)return{sql:n(u._.alias),params:[]};return this.buildQueryFromSourceParams([new Nt("("),u._.sql,new Nt(") "),new cb(u._.alias)],r)}if(s3(u)){if(u.schema)return{sql:n(u.schema)+"."+n(u.enumName),params:[]};return{sql:n(u.enumName),params:[]}}if(XT(u)){if(u.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([u.getSQL()],r);return this.buildQueryFromSourceParams([new Nt("("),u.getSQL(),new Nt(")")],r)}if(a)return{sql:this.mapInlineParam(u,r),params:[]};return{sql:i(l.value++,u),params:[u],typings:["none"]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return"null";if(typeof e==="number"||typeof e==="boolean")return e.toString();if(typeof e==="string")return t(e);if(typeof e==="object"){let r=e.toString();if(r==="[object Object]")return t(JSON.stringify(e));return t(r)}throw Error("Unexpected param value: "+e)}getSQL(){return this}as(e){if(e===void 0)return this;return new Ee.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}};cb=class cb{constructor(e){this.value=e}static[F]="Name";brand;getSQL(){return new Ee([this])}};g3={mapFromDriverValue:(e)=>e},y3={mapToDriverValue:(e)=>e},OZe={...g3,...y3};Mr=class Mr{constructor(e,t=y3){this.value=e,this.encoder=t}static[F]="Param";brand;getSQL(){return new Ee([this])}};((e)=>{function t(){return new Ee([])}e.empty=t;function r(l){return new Ee(l)}e.fromList=r;function o(l){return new Ee([new Nt(l)])}e.raw=o;function n(l,u){let d=[];for(let[p,m]of l.entries()){if(p>0&&u!==void 0)d.push(u);d.push(m)}return new Ee(d)}e.join=n;function i(l){return new cb(l)}e.identifier=i;function s(l){return new os(l)}e.placeholder=s;function a(l,u){return new Mr(l,u)}e.param=a})(C||(C={}));((e)=>{class t{constructor(r,o){this.sql=r,this.fieldAlias=o}static[F]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new t(this.sql,this.fieldAlias)}}e.Aliased=t})(Ee||(Ee={}));os=class os{constructor(e){this.name=e}static[F]="Placeholder";getSQL(){return new Ee([this])}};ihe=Symbol.for("drizzle:IsDrizzleView");cn=class cn{static[F]="View";[ft];[ihe]=!0;constructor({name:e,schema:t,selectedFields:r,query:o}){this[ft]={name:e,originalName:e,schema:t,selectedFields:r,query:o,isExisting:!o,isAlias:!1}}getSQL(){return new Ee([this])}};Ke.prototype.getSQL=function(){return new Ee([this])};he.prototype.getSQL=function(){return new Ee([this])};pt.prototype.getSQL=function(){return new Ee([this])}});function e$(e,t,r){let o={},n=e.reduce((i,{path:s,field:a},l)=>{let u;if(oe(a,Ke))u=a;else if(oe(a,Ee))u=a.decoder;else if(oe(a,pt))u=a._.sql.decoder;else u=a.sql.decoder;let d=i;for(let[p,m]of s.entries())if(p<s.length-1){if(!(m in d))d[m]={};d=d[m]}else{let h=t[l],b=d[m]=h===null?null:u.mapFromDriverValue(h);if(r&&oe(a,Ke)&&s.length===2){let y=s[0];if(!(y in o))o[y]=b===null?ns(a.table):!1;else if(typeof o[y]==="string"&&o[y]!==ns(a.table))o[y]=!1}}return i},{});if(r&&Object.keys(o).length>0){for(let[i,s]of Object.entries(o))if(typeof s==="string"&&!r[s])n[i]=null}return n}function ln(e,t){return Object.entries(e).reduce((r,[o,n])=>{if(typeof o!=="string")return r;let i=t?[...t,o]:[o];if(oe(n,Ke)||oe(n,Ee)||oe(n,Ee.Aliased)||oe(n,pt))r.push({path:i,field:n});else if(oe(n,he))r.push(...ln(n[he.Symbol.Columns],i));else r.push(...ln(n,i));return r},[])}function Fp(e,t){let r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return!1;for(let[n,i]of r.entries())if(i!==o[n])return!1;return!0}function lb(e,t){let r=Object.entries(t).filter(([,o])=>o!==void 0).map(([o,n])=>{if(oe(n,Ee)||oe(n,Ke))return[o,n];else return[o,new Mr(n,e[he.Symbol.Columns][o])]});if(r.length===0)throw Error("No values to set");return Object.fromEntries(r)}function b3(e,t){for(let r of t)for(let o of Object.getOwnPropertyNames(r.prototype)){if(o==="constructor")continue;Object.defineProperty(e.prototype,o,Object.getOwnPropertyDescriptor(r.prototype,o)||Object.create(null))}}function ub(e){return e[he.Symbol.Columns]}function Hp(e){return oe(e,pt)?e._.alias:oe(e,cn)?e[ft].name:oe(e,Ee)?void 0:e[he.Symbol.IsAlias]?e[he.Symbol.Name]:e[he.Symbol.BaseName]}function oo(e,t){return{name:typeof e==="string"&&e.length>0?e:"",config:typeof e==="object"?e:t}}function S3(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 t$;var Sr=v(()=>{En();$e();Yt();In();sr();qo();t$=typeof TextDecoder>"u"?null:new TextDecoder});var v3,r$,n$;var db=v(()=>{$e();v3=class v3{static[F]="ConsoleLogWriter";write(e){console.log(e)}};r$=class r${static[F]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new v3}logQuery(e,t){let r=t.map((n)=>{try{return JSON.stringify(n)}catch{return String(n)}}),o=r.length?` -- params: [${r.join(", ")}]`:"";this.writer.write(`Query: ${e}${o}`)}};n$=class n${static[F]="NoopLogger";logQuery(){}}});var w3,x3,o$;var _3=v(()=>{$e();sr();w3=Symbol.for("drizzle:PgInlineForeignKeys"),x3=Symbol.for("drizzle:EnableRLS");o$=class o$ extends he{static[F]="PgTable";static Symbol=Object.assign({},he.Symbol,{InlineForeignKeys:w3,EnableRLS:x3});[w3]=[];[x3]=!1;[he.Symbol.ExtraConfigBuilder]=void 0;[he.Symbol.ExtraConfigColumns]={}}});var i$,E3;var I3=v(()=>{$e();_3();i$=class i${static[F]="PgPrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new E3(e,this.columns,this.name)}};E3=class E3{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[F]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[o$.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function $r(e,t){if(h3(t)&&!XT(e)&&!oe(e,Mr)&&!oe(e,os)&&!oe(e,Ke)&&!oe(e,he)&&!oe(e,cn))return new Mr(e,t);return e}function tt(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new Ee(t);return new Ee([new Nt("("),C.join(t,new Nt(" and ")),new Nt(")")])}function un(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new Ee(t);return new Ee([new Nt("("),C.join(t,new Nt(" or ")),new Nt(")")])}function A3(e){return C`not ${e}`}function ss(e,t){if(Array.isArray(t)){if(t.length===0)return C`false`;return C`${e} in ${t.map((r)=>$r(r,e))}`}return C`${e} in ${$r(t,e)}`}function pb(e,t){if(Array.isArray(t)){if(t.length===0)return C`true`;return C`${e} not in ${t.map((r)=>$r(r,e))}`}return C`${e} not in ${$r(t,e)}`}function qr(e){return C`${e} is null`}function $3(e){return C`${e} is not null`}function fb(e){return C`exists ${e}`}function as(e){return C`not exists ${e}`}function O3(e,t,r){return C`${e} between ${$r(t,e)} and ${$r(r,e)}`}function C3(e,t,r){return C`${e} not between ${$r(t,e)} and ${$r(r,e)}`}function P3(e,t){return C`${e} like ${t}`}function z3(e,t){return C`${e} not like ${t}`}function N3(e,t){return C`${e} ilike ${t}`}function D3(e,t){return C`${e} not ilike ${t}`}var je=(e,t)=>C`${e} = ${$r(t,e)}`,k3=(e,t)=>C`${e} <> ${$r(t,e)}`,kn=(e,t)=>C`${e} > ${$r(t,e)}`,R3=(e,t)=>C`${e} >= ${$r(t,e)}`,T3=(e,t)=>C`${e} < ${$r(t,e)}`,is=(e,t)=>C`${e} <= ${$r(t,e)}`;var L3=v(()=>{En();$e();sr();Yt()});function Fo(e){return C`${e} asc`}function ba(e){return C`${e} desc`}var B3=v(()=>{Yt()});var s$=v(()=>{L3();B3()});function Z3(){return{and:tt,between:O3,eq:je,exists:fb,gt:kn,gte:R3,ilike:N3,inArray:ss,isNull:qr,isNotNull:$3,like:P3,lt:T3,lte:is,ne:k3,not:A3,notBetween:C3,notExists:as,notLike:z3,notIlike:D3,notInArray:pb,or:un,sql:C}}function U3(){return{sql:C,asc:Fo,desc:ba}}function M3(e,t){if(Object.keys(e).length===1&&"default"in e&&!oe(e.default,he))e=e.default;let r={},o={},n={};for(let[i,s]of Object.entries(e))if(oe(s,he)){let a=ya(s),l=o[a];r[a]=i,n[i]={tsName:i,dbName:s[he.Symbol.Name],schema:s[he.Symbol.Schema],columns:s[he.Symbol.Columns],relations:l?.relations??{},primaryKey:l?.primaryKey??[]};for(let d of Object.values(s[he.Symbol.Columns]))if(d.primary)n[i].primaryKey.push(d);let u=s[he.Symbol.ExtraConfigBuilder]?.(s[he.Symbol.ExtraConfigColumns]);if(u){for(let d of Object.values(u))if(oe(d,i$))n[i].primaryKey.push(...d.columns)}}else if(oe(s,j3)){let a=ya(s.table),l=r[a],u=s.config(t(s.table)),d;for(let[p,m]of Object.entries(u))if(l){let h=n[l];if(h.relations[p]=m,d)h.primaryKey.push(...d)}else{if(!(a in o))o[a]={relations:{},primaryKey:d};o[a].relations[p]=m}}return{tables:n,tableNamesMap:r}}function she(e){return function(r,o){return new cs(e,r,o,o?.fields.reduce((n,i)=>n&&i.notNull,!0)??!1)}}function ahe(e){return function(r,o){return new Jp(e,r,o)}}function q3(e,t,r){if(oe(r,cs)&&r.config)return{fields:r.config.fields,references:r.config.references};let o=t[ya(r.referencedTable)];if(!o)throw Error(`Table "${r.referencedTable[he.Symbol.Name]}" not found in schema`);let n=e[o];if(!n)throw Error(`Table "${o}" not found in schema`);let i=r.sourceTable,s=t[ya(i)];if(!s)throw Error(`Table "${i[he.Symbol.Name]}" not found in schema`);let a=[];for(let l of Object.values(n.relations))if(r.relationName&&r!==l&&l.relationName===r.relationName||!r.relationName&&l.referencedTable===r.sourceTable)a.push(l);if(a.length>1)throw r.relationName?Error(`There are multiple relations with name "${r.relationName}" in table "${o}"`):Error(`There are multiple relations between "${o}" and "${r.sourceTable[he.Symbol.Name]}". Please specify relation name`);if(a[0]&&oe(a[0],cs)&&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 F3(e){return{one:she(e),many:ahe(e)}}function mb(e,t,r,o,n=(i)=>i){let i={};for(let[s,a]of o.entries())if(a.isJson){let l=t.relations[a.tsKey],u=r[s],d=typeof u==="string"?JSON.parse(u):u;i[a.tsKey]=oe(l,cs)?d&&mb(e,e[a.relationTableTsKey],d,a.selection,n):d.map((p)=>mb(e,e[a.relationTableTsKey],p,a.selection,n))}else{let l=n(r[s]),u=a.field,d;if(oe(u,Ke))d=u;else if(oe(u,Ee))d=u.decoder;else d=u.sql.decoder;i[a.tsKey]=l===null?null:d.mapFromDriverValue(l)}return i}var a$,j3,cs,Jp;var Kp=v(()=>{sr();En();$e();I3();s$();Yt();a$=class a${constructor(e,t,r){this.sourceTable=e,this.referencedTable=t,this.relationName=r,this.referencedTableName=t[he.Symbol.Name]}static[F]="Relation";referencedTableName;fieldName};j3=class j3{constructor(e,t){this.table=e,this.config=t}static[F]="Relations"};cs=class cs extends a${constructor(e,t,r,o){super(e,t,r?.relationName);this.config=r,this.isNullable=o}static[F]="One";withFieldName(e){let t=new cs(this.sourceTable,this.referencedTable,this.config,this.isNullable);return t.fieldName=e,t}};Jp=class Jp extends a${constructor(e,t,r){super(e,t,r?.relationName);this.config=r}static[F]="Many";withFieldName(e){let t=new Jp(this.sourceTable,this.referencedTable,this.config);return t.fieldName=e,t}}});function Vp(e,t){return new Proxy(e,new Sa(t,!1))}function io(e,t){return new Proxy(e,new Nl(new Proxy(e.table,new Sa(t,!1))))}function c$(e,t){return new Ee.Aliased(Wp(e.sql,t),e.fieldAlias)}function Wp(e,t){return C.join(e.queryChunks.map((r)=>{if(oe(r,Ke))return io(r,t);if(oe(r,Ee))return Wp(r,t);if(oe(r,Ee.Aliased))return c$(r,t);return r}))}var Nl,Sa,che;var Gp=v(()=>{En();$e();Yt();sr();qo();Nl=class Nl{constructor(e){this.table=e}static[F]="ColumnAliasProxyHandler";get(e,t){if(t==="table")return this.table;return e[t]}};Sa=class Sa{constructor(e,t){this.alias=e,this.replaceOriginalName=t}static[F]="TableAliasProxyHandler";get(e,t){if(t===he.Symbol.IsAlias)return!0;if(t===he.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===he.Symbol.OriginalName)return this.alias;if(t===ft)return{...e[ft],name:this.alias,isAlias:!0};if(t===he.Symbol.Columns){let o=e[he.Symbol.Columns];if(!o)return o;let n={};return Object.keys(o).map((i)=>{n[i]=new Proxy(o[i],new Nl(new Proxy(e,this)))}),n}let r=e[t];if(oe(r,Ke))return new Proxy(r,new Nl(new Proxy(e,this)));return r}};che=class che{constructor(e){this.alias=e}static[F]="RelationTableAliasProxyHandler";get(e,t){if(t==="sourceTable")return Vp(e.sourceTable,this.alias);return e[t]}}});var at;var va=v(()=>{Gp();En();$e();Yt();In();qo();at=class at{static[F]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t==="_")return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(t===ft)return{...e[ft],selectedFields:new Proxy(e[ft].selectedFields,this)};if(typeof t==="symbol")return e[t];let o=(oe(e,pt)?e._.selectedFields:oe(e,cn)?e[ft].selectedFields:e)[t];if(oe(o,Ee.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!o.isSelectionField)return o.sql;let n=o.clone();return n.isSelectionField=!0,n}if(oe(o,Ee)){if(this.config.sqlBehavior==="sql")return o;throw Error(`You tried to reference "${t}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(oe(o,Ke)){if(this.config.alias)return new Proxy(o,new Nl(new Proxy(o.table,new Sa(this.config.alias,this.config.replaceOriginalName??!1))));return o}if(typeof o!=="object"||o===null)return o;return new Proxy(o,new at(this.config))}}});var vr;var Ho=v(()=>{$e();vr=class vr{static[F]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then((t)=>(e?.(),t),(t)=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}}});var l$,H3;var u$=v(()=>{$e();Pl();l$=class l${static[F]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(e,t){if(this.reference=()=>{let{name:r,columns:o,foreignColumns:n}=e();return{name:r,columns:o,foreignTable:n[0].table,foreignColumns:n}},t)this._onUpdate=t.onUpdate,this._onDelete=t.onDelete}onUpdate(e){return this._onUpdate=e,this}onDelete(e){return this._onDelete=e,this}build(e){return new H3(e,this)}};H3=class H3{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[F]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),o=t.map((s)=>s.name),n=r.map((s)=>s.name),i=[this.table[ir],...o,r[0].table[ir],...n];return e??`${i.join("_")}_fk`}}});function d$(e,t){return`${e[ir]}_${t.join("_")}_unique`}var J3,lhe,K3;var p$=v(()=>{$e();Pl();J3=class J3{constructor(e,t){this.name=t,this.columns=e}static[F]="SQLiteUniqueConstraintBuilder";columns;build(e){return new K3(e,this.columns,this.name)}};lhe=class lhe{static[F]="SQLiteUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new J3(e,this.name)}};K3=class K3{constructor(e,t,r){this.table=e,this.columns=t,this.name=r??d$(this.table,this.columns.map((o)=>o.name))}static[F]="SQLiteUniqueConstraint";columns;name;getName(){return this.name}}});var Ut,bt;var ls=v(()=>{ob();En();$e();u$();p$();Ut=class Ut extends jp{static[F]="SQLiteColumnBuilder";foreignKeyConfigs=[];references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e){return this.config.isUnique=!0,this.config.uniqueName=e,this}generatedAlwaysAs(e,t){return this.config.generated={as:e,type:"always",mode:t?.mode??"virtual"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:r,actions:o})=>((n,i)=>{let s=new l$(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(i.onUpdate)s.onUpdate(i.onUpdate);if(i.onDelete)s.onDelete(i.onDelete);return s.build(t)})(r,o))}};bt=class bt extends Ke{constructor(e,t){if(!t.uniqueName)t.uniqueName=d$(e,[t.name]);super(e,t);this.table=e}static[F]="SQLiteColumn"}});function e5(e,t){let{name:r,config:o}=oo(e,t);if(o?.mode==="json")return new G3(r);if(o?.mode==="bigint")return new V3(r);return new Y3(r)}var V3,W3,G3,Q3,Y3,X3;var f$=v(()=>{$e();Sr();ls();V3=class V3 extends Ut{static[F]="SQLiteBigIntBuilder";constructor(e){super(e,"bigint","SQLiteBigInt")}build(e){return new W3(e,this.config)}};W3=class W3 extends bt{static[F]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){let t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return BigInt(t.toString("utf8"))}return BigInt(t$.decode(e))}mapToDriverValue(e){return Buffer.from(e.toString())}};G3=class G3 extends Ut{static[F]="SQLiteBlobJsonBuilder";constructor(e){super(e,"json","SQLiteBlobJson")}build(e){return new Q3(e,this.config)}};Q3=class Q3 extends bt{static[F]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){let t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return JSON.parse(t.toString("utf8"))}return JSON.parse(t$.decode(e))}mapToDriverValue(e){return Buffer.from(JSON.stringify(e))}};Y3=class Y3 extends Ut{static[F]="SQLiteBlobBufferBuilder";constructor(e){super(e,"buffer","SQLiteBlobBuffer")}build(e){return new X3(e,this.config)}};X3=class X3 extends bt{static[F]="SQLiteBlobBuffer";mapFromDriverValue(e){if(Buffer.isBuffer(e))return e;return Buffer.from(e)}getSQLType(){return"blob"}}});function n5(e){return(t,r)=>{let{name:o,config:n}=oo(t,r);return new t5(o,n,e)}}var t5,r5;var m$=v(()=>{$e();Sr();ls();t5=class t5 extends Ut{static[F]="SQLiteCustomColumnBuilder";constructor(e,t,r){super(e,"custom","SQLiteCustomColumn");this.config.fieldConfig=t,this.config.customTypeParams=r}build(e){return new r5(e,this.config)}};r5=class r5 extends bt{static[F]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;constructor(e,t){super(e,t);this.sqlName=t.customTypeParams.dataType(t.fieldConfig),this.mapTo=t.customTypeParams.toDriver,this.mapFrom=t.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(e){return typeof this.mapFrom==="function"?this.mapFrom(e):e}mapToDriverValue(e){return typeof this.mapTo==="function"?this.mapTo(e):e}}});function ar(e,t){let{name:r,config:o}=oo(e,t);if(o?.mode==="timestamp"||o?.mode==="timestamp_ms")return new s5(r,o.mode);if(o?.mode==="boolean")return new c5(r,o.mode);return new o5(r)}var hb,gb,o5,i5,s5,a5,c5,l5;var h$=v(()=>{$e();Yt();Sr();ls();hb=class hb extends Ut{static[F]="SQLiteBaseIntegerBuilder";constructor(e,t,r){super(e,t,r);this.config.autoIncrement=!1}primaryKey(e){if(e?.autoIncrement)this.config.autoIncrement=!0;return this.config.hasDefault=!0,super.primaryKey()}};gb=class gb extends bt{static[F]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}};o5=class o5 extends hb{static[F]="SQLiteIntegerBuilder";constructor(e){super(e,"number","SQLiteInteger")}build(e){return new i5(e,this.config)}};i5=class i5 extends gb{static[F]="SQLiteInteger"};s5=class s5 extends hb{static[F]="SQLiteTimestampBuilder";constructor(e,t){super(e,"date","SQLiteTimestamp");this.config.mode=t}defaultNow(){return this.default(C`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new a5(e,this.config)}};a5=class a5 extends gb{static[F]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue(e){if(this.config.mode==="timestamp")return new Date(e*1000);return new Date(e)}mapToDriverValue(e){let t=e.getTime();if(this.config.mode==="timestamp")return Math.floor(t/1000);return t}};c5=class c5 extends hb{static[F]="SQLiteBooleanBuilder";constructor(e,t){super(e,"boolean","SQLiteBoolean");this.config.mode=t}build(e){return new l5(e,this.config)}};l5=class l5 extends gb{static[F]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue(e){return Number(e)===1}mapToDriverValue(e){return e?1:0}}});function g5(e,t){let{name:r,config:o}=oo(e,t),n=o?.mode;return n==="number"?new p5(r):n==="bigint"?new m5(r):new u5(r)}var u5,d5,p5,f5,m5,h5;var g$=v(()=>{$e();Sr();ls();u5=class u5 extends Ut{static[F]="SQLiteNumericBuilder";constructor(e){super(e,"string","SQLiteNumeric")}build(e){return new d5(e,this.config)}};d5=class d5 extends bt{static[F]="SQLiteNumeric";mapFromDriverValue(e){if(typeof e==="string")return e;return String(e)}getSQLType(){return"numeric"}};p5=class p5 extends Ut{static[F]="SQLiteNumericNumberBuilder";constructor(e){super(e,"number","SQLiteNumericNumber")}build(e){return new f5(e,this.config)}};f5=class f5 extends bt{static[F]="SQLiteNumericNumber";mapFromDriverValue(e){if(typeof e==="number")return e;return Number(e)}mapToDriverValue=String;getSQLType(){return"numeric"}};m5=class m5 extends Ut{static[F]="SQLiteNumericBigIntBuilder";constructor(e){super(e,"bigint","SQLiteNumericBigInt")}build(e){return new h5(e,this.config)}};h5=class h5 extends bt{static[F]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}});function S5(e){return new y5(e??"")}var y5,b5;var y$=v(()=>{$e();ls();y5=class y5 extends Ut{static[F]="SQLiteRealBuilder";constructor(e){super(e,"number","SQLiteReal")}build(e){return new b5(e,this.config)}};b5=class b5 extends bt{static[F]="SQLiteReal";getSQLType(){return"real"}}});function mt(e,t={}){let{name:r,config:o}=oo(e,t);if(o.mode==="json")return new x5(r);return new v5(r,o)}var v5,w5,x5,_5;var b$=v(()=>{$e();Sr();ls();v5=class v5 extends Ut{static[F]="SQLiteTextBuilder";constructor(e,t){super(e,"string","SQLiteText");this.config.enumValues=t.enum,this.config.length=t.length}build(e){return new w5(e,this.config)}};w5=class w5 extends bt{static[F]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor(e,t){super(e,t)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}};x5=class x5 extends Ut{static[F]="SQLiteTextJsonBuilder";constructor(e){super(e,"json","SQLiteTextJson")}build(e){return new _5(e,this.config)}};_5=class _5 extends bt{static[F]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue(e){return JSON.parse(e)}mapToDriverValue(e){return JSON.stringify(e)}}});function E5(){return{blob:e5,customType:n5,integer:ar,numeric:g5,real:S5,text:mt}}var I5=v(()=>{f$();m$();h$();g$();y$();b$()});function uhe(e,t,r,o,n=e){let i=new At(e,o,n),s=typeof t==="function"?t(E5()):t,a=Object.fromEntries(Object.entries(s).map(([u,d])=>{let p=d;p.setName(u);let m=p.build(i);return i[S$].push(...p.buildForeignKeys(m,i)),[u,m]})),l=Object.assign(i,a);if(l[he.Symbol.Columns]=a,l[he.Symbol.ExtraConfigColumns]=a,r)l[At.Symbol.ExtraConfigBuilder]=r;return l}var S$,At,Qp=(e,t,r)=>uhe(e,t,r);var Jo=v(()=>{$e();sr();I5();S$=Symbol.for("drizzle:SQLiteInlineForeignKeys");At=class At extends he{static[F]="SQLiteTable";static Symbol=Object.assign({},he.Symbol,{InlineForeignKeys:S$});[he.Symbol.Columns];[S$]=[];[he.Symbol.ExtraConfigBuilder]=void 0}});var dhe,k5;var A5=v(()=>{$e();dhe=class dhe{constructor(e,t){this.name=e,this.value=t}static[F]="SQLiteCheckBuilder";brand;build(e){return new k5(e,this)}};k5=class k5{constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}static[F]="SQLiteCheck";name;value}});function Ko(e){return new R5(e,!1)}var R5,T5,$5;var O5=v(()=>{$e();R5=class R5{constructor(e,t){this.name=e,this.unique=t}static[F]="SQLiteIndexBuilderOn";on(...e){return new T5(this.name,e,this.unique)}};T5=class T5{static[F]="SQLiteIndexBuilder";config;constructor(e,t,r){this.config={name:e,columns:t,unique:r,where:void 0}}where(e){return this.config.where=e,this}build(e){return new $5(this.config,e)}};$5=class $5{static[F]="SQLiteIndex";config;constructor(e,t){this.config={...e,table:t}}}});var phe,C5;var P5=v(()=>{$e();Jo();phe=class phe{static[F]="SQLitePrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new C5(e,this.columns,this.name)}};C5=class C5{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[F]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[At.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function An(e){if(oe(e,At))return[`${e[he.Symbol.BaseName]}`];if(oe(e,pt))return e._.usedTables??[];if(oe(e,Ee))return e.usedTables??[];return[]}var Dl=v(()=>{$e();Yt();In();sr();Jo()});var yb;var z5=v(()=>{$e();Ho();va();Jo();sr();Sr();Dl();yb=class yb extends vr{constructor(e,t,r,o){super();this.table=e,this.session=t,this.dialect=r,this.config={table:e,withList:o}}static[F]="SQLiteDelete";config;where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.table[he.Symbol.Columns],new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];this.config.orderBy=r}else{let t=e;this.config.orderBy=t}return this}limit(e){return this.config.limit=e,this}returning(e=this.table[At.Symbol.Columns]){return this.config.returning=ln(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:An(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 fhe(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((r)=>r.toLowerCase()).join("_")}function mhe(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((r,o,n)=>{let i=n===0?o.toLowerCase():`${o[0].toUpperCase()}${o.slice(1)}`;return r+i},"")}function hhe(e){return e}var v$;var N5=v(()=>{$e();sr();v$=class v${static[F]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert=e==="snake_case"?fhe:e==="camelCase"?mhe:hhe}getColumnCasing(e){if(!e.keyAsName)return e.name;let t=e.table[he.Symbol.Schema]??"public",r=e.table[he.Symbol.OriginalName],o=`${t}.${r}.${e.name}`;if(!this.cache[o])this.cacheTable(e.table);return this.cache[o]}cacheTable(e){let t=e[he.Symbol.Schema]??"public",r=e[he.Symbol.OriginalName],o=`${t}.${r}`;if(!this.cachedTables[o]){for(let n of Object.values(e[he.Symbol.Columns])){let i=`${o}.${n.name}`;this.cache[i]=this.convert(n.name)}this.cachedTables[o]=!0}}clearCache(){this.cache={},this.cachedTables={}}}});var Ll,Vo,w$;var bb=v(()=>{$e();Ll=class Ll extends Error{static[F]="DrizzleError";constructor({message:e,cause:t}){super(e);this.name="DrizzleError",this.cause=t}};Vo=class Vo extends Error{constructor(e,t,r){super(`Failed query: ${e}
429
429
  params: ${t}`);if(this.query=e,this.params=t,this.cause=r,Error.captureStackTrace(this,Vo),r)this.cause=r}};w$=class w$ extends Ll{static[F]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}});var D5=()=>{};var L5=()=>{};var B5=v(()=>{D5();L5()});var x$=v(()=>{s$();B5();Yt()});var _$=v(()=>{f$();ls();m$();h$();g$();y$();b$()});var Wo;var Yp=v(()=>{$e();Yt();Wo=class Wo extends cn{static[F]="SQLiteViewBase"}});var Bl,E$,I$;var Sb=v(()=>{Gp();N5();En();$e();bb();Kp();x$();Yt();_$();Jo();In();sr();Sr();qo();Yp();Bl=class Bl{static[F]="SQLiteDialect";casing;constructor(e){this.casing=new v$(e?.casing)}escapeName(e){return`"${e.replace(/"/g,'""')}"`}escapeParam(e){return"?"}escapeString(e){return`'${e.replace(/'/g,"''")}'`}buildWithCTE(e){if(!e?.length)return;let t=[C`with `];for(let[r,o]of e.entries())if(t.push(C`${C.identifier(o._.alias)} as (${o._.sql})`),r<e.length-1)t.push(C`, `);return t.push(C` `),C.join(t)}buildDeleteQuery({table:e,where:t,returning:r,withList:o,limit:n,orderBy:i}){let s=this.buildWithCTE(o),a=r?C` returning ${this.buildSelection(r,{isSingleTable:!0})}`:void 0,l=t?C` where ${t}`:void 0,u=this.buildOrderBy(i),d=this.buildLimit(n);return C`${s}delete from ${e}${l}${a}${u}${d}`}buildUpdateSet(e,t){let r=e[he.Symbol.Columns],o=Object.keys(r).filter((i)=>t[i]!==void 0||r[i]?.onUpdateFn!==void 0),n=o.length;return C.join(o.flatMap((i,s)=>{let a=r[i],l=a.onUpdateFn?.(),u=t[i]??(oe(l,Ee)?l:C.param(l,a)),d=C`${C.identifier(this.casing.getColumnCasing(a))} = ${u}`;if(s<n-1)return[d,C.raw(", ")];return[d]}))}buildUpdateQuery({table:e,set:t,where:r,returning:o,withList:n,joins:i,from:s,limit:a,orderBy:l}){let u=this.buildWithCTE(n),d=this.buildUpdateSet(e,t),p=s&&C.join([C.raw(" from "),this.buildFromTable(s)]),m=this.buildJoins(i),h=o?C` returning ${this.buildSelection(o,{isSingleTable:!0})}`:void 0,b=r?C` where ${r}`:void 0,y=this.buildOrderBy(l),S=this.buildLimit(a);return C`${u}update ${e} set ${d}${p}${m}${b}${h}${y}${S}`}buildSelection(e,{isSingleTable:t=!1}={}){let r=e.length,o=e.flatMap(({field:n},i)=>{let s=[];if(oe(n,Ee.Aliased)&&n.isSelectionField)s.push(C.identifier(n.fieldAlias));else if(oe(n,Ee.Aliased)||oe(n,Ee)){let a=oe(n,Ee.Aliased)?n.sql:n;if(t)s.push(new Ee(a.queryChunks.map((l)=>{if(oe(l,Ke))return C.identifier(this.casing.getColumnCasing(l));return l})));else s.push(a);if(oe(n,Ee.Aliased))s.push(C` as ${C.identifier(n.fieldAlias)}`)}else if(oe(n,Ke)){let a=n.table[he.Symbol.Name];if(n.columnType==="SQLiteNumericBigInt")if(t)s.push(C`cast(${C.identifier(this.casing.getColumnCasing(n))} as text)`);else s.push(C`cast(${C.identifier(a)}.${C.identifier(this.casing.getColumnCasing(n))} as text)`);else if(t)s.push(C.identifier(this.casing.getColumnCasing(n)));else s.push(C`${C.identifier(a)}.${C.identifier(this.casing.getColumnCasing(n))}`)}else if(oe(n,pt)){let a=Object.entries(n._.selectedFields);if(a.length===1){let l=a[0][1],u=oe(l,Ee)?l.decoder:oe(l,Ke)?{mapFromDriverValue:(d)=>l.mapFromDriverValue(d)}:l.sql.decoder;if(u)n._.sql.decoder=u}s.push(n)}if(i<r-1)s.push(C`, `);return s});return C.join(o)}buildJoins(e){if(!e||e.length===0)return;let t=[];if(e)for(let[r,o]of e.entries()){if(r===0)t.push(C` `);let n=o.table,i=o.on?C` on ${o.on}`:void 0;if(oe(n,At)){let s=n[At.Symbol.Name],a=n[At.Symbol.Schema],l=n[At.Symbol.OriginalName],u=s===l?void 0:o.alias;t.push(C`${C.raw(o.joinType)} join ${a?C`${C.identifier(a)}.`:void 0}${C.identifier(l)}${u&&C` ${C.identifier(u)}`}${i}`)}else t.push(C`${C.raw(o.joinType)} join ${n}${i}`);if(r<e.length-1)t.push(C` `)}return C.join(t)}buildLimit(e){return typeof e==="object"||typeof e==="number"&&e>=0?C` limit ${e}`:void 0}buildOrderBy(e){let t=[];if(e){for(let[r,o]of e.entries())if(t.push(o),r<e.length-1)t.push(C`, `)}return t.length>0?C` order by ${C.join(t)}`:void 0}buildFromTable(e){if(oe(e,he)&&e[he.Symbol.IsAlias])return C`${C`${C.identifier(e[he.Symbol.Schema]??"")}.`.if(e[he.Symbol.Schema])}${C.identifier(e[he.Symbol.OriginalName])} ${C.identifier(e[he.Symbol.Name])}`;return e}buildSelectQuery({withList:e,fields:t,fieldsFlat:r,where:o,having:n,table:i,joins:s,orderBy:a,groupBy:l,limit:u,offset:d,distinct:p,setOperators:m}){let h=r??ln(t);for(let T of h)if(oe(T.field,Ke)&&ns(T.field.table)!==(oe(i,pt)?i._.alias:oe(i,Wo)?i[ft].name:oe(i,Ee)?void 0:ns(i))&&!((B)=>s?.some(({alias:I})=>I===(B[he.Symbol.IsAlias]?ns(B):B[he.Symbol.BaseName])))(T.field.table)){let B=ns(T.field.table);throw Error(`Your "${T.path.join("->")}" field references a column "${B}"."${T.field.name}", but the table "${B}" is not part of the query! Did you forget to join it?`)}let b=!s||s.length===0,y=this.buildWithCTE(e),S=p?C` distinct`:void 0,x=this.buildSelection(h,{isSingleTable:b}),_=this.buildFromTable(i),A=this.buildJoins(s),O=o?C` where ${o}`:void 0,L=n?C` having ${n}`:void 0,z=[];if(l){for(let[T,B]of l.entries())if(z.push(B),T<l.length-1)z.push(C`, `)}let J=z.length>0?C` group by ${C.join(z)}`:void 0,P=this.buildOrderBy(a),W=this.buildLimit(u),ee=d?C` offset ${d}`:void 0,j=C`${y}select${S} ${x} from ${_}${A}${O}${J}${L}${P}${W}${ee}`;if(m.length>0)return this.buildSetOperations(j,m);return j}buildSetOperations(e,t){let[r,...o]=t;if(!r)throw Error("Cannot pass undefined values to any set operator");if(o.length===0)return this.buildSetOperationQuery({leftSelect:e,setOperator:r});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:e,setOperator:r}),o)}buildSetOperationQuery({leftSelect:e,setOperator:{type:t,isAll:r,rightSelect:o,limit:n,orderBy:i,offset:s}}){let a=C`${e.getSQL()} `,l=C`${o.getSQL()}`,u;if(i&&i.length>0){let h=[];for(let b of i)if(oe(b,bt))h.push(C.identifier(b.name));else if(oe(b,Ee)){for(let y=0;y<b.queryChunks.length;y++){let S=b.queryChunks[y];if(oe(S,bt))b.queryChunks[y]=C.identifier(this.casing.getColumnCasing(S))}h.push(C`${b}`)}else h.push(C`${b}`);u=C` order by ${C.join(h,C`, `)}`}let d=typeof n==="object"||typeof n==="number"&&n>=0?C` limit ${n}`:void 0,p=C.raw(`${t} ${r?"all ":""}`),m=s?C` offset ${s}`:void 0;return C`${a}${p}${l}${u}${d}${m}`}buildInsertQuery({table:e,values:t,onConflict:r,returning:o,withList:n,select:i}){let s=[],a=e[he.Symbol.Columns],l=Object.entries(a).filter(([b,y])=>!y.shouldDisableInsert()),u=l.map(([,b])=>C.identifier(this.casing.getColumnCasing(b)));if(i){let b=t;if(oe(b,Ee))s.push(b);else s.push(b.getSQL())}else{let b=t;s.push(C.raw("values "));for(let[y,S]of b.entries()){let x=[];for(let[_,A]of l){let O=S[_];if(O===void 0||oe(O,Mr)&&O.value===void 0){let L;if(A.default!==null&&A.default!==void 0)L=oe(A.default,Ee)?A.default:C.param(A.default,A);else if(A.defaultFn!==void 0){let z=A.defaultFn();L=oe(z,Ee)?z:C.param(z,A)}else if(!A.default&&A.onUpdateFn!==void 0){let z=A.onUpdateFn();L=oe(z,Ee)?z:C.param(z,A)}else L=C`null`;x.push(L)}else x.push(O)}if(s.push(x),y<b.length-1)s.push(C`, `)}}let d=this.buildWithCTE(n),p=C.join(s),m=o?C` returning ${this.buildSelection(o,{isSingleTable:!0})}`:void 0,h=r?.length?C.join(r):void 0;return C`${d}insert into ${e} ${u} ${p}${h}${m}`}sqlToQuery(e,t){return e.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,invokeSource:t})}buildRelationalQuery({fullSchema:e,schema:t,tableNamesMap:r,table:o,tableConfig:n,queryConfig:i,tableAlias:s,nestedQueryRelation:a,joinOn:l}){let u=[],d,p,m=[],h,b=[];if(i===!0)u=Object.entries(n.columns).map(([x,_])=>({dbKey:_.name,tsKey:x,field:io(_,s),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let S=Object.fromEntries(Object.entries(n.columns).map(([z,J])=>[z,io(J,s)]));if(i.where){let z=typeof i.where==="function"?i.where(S,Z3()):i.where;h=z&&Wp(z,s)}let x=[],_=[];if(i.columns){let z=!1;for(let[J,P]of Object.entries(i.columns)){if(P===void 0)continue;if(J in n.columns){if(!z&&P===!0)z=!0;_.push(J)}}if(_.length>0)_=z?_.filter((J)=>i.columns?.[J]===!0):Object.keys(n.columns).filter((J)=>!_.includes(J))}else _=Object.keys(n.columns);for(let z of _){let J=n.columns[z];x.push({tsKey:z,value:J})}let A=[];if(i.with)A=Object.entries(i.with).filter((z)=>!!z[1]).map(([z,J])=>({tsKey:z,queryConfig:J,relation:n.relations[z]}));let O;if(i.extras){O=typeof i.extras==="function"?i.extras(S,{sql:C}):i.extras;for(let[z,J]of Object.entries(O))x.push({tsKey:z,value:c$(J,s)})}for(let{tsKey:z,value:J}of x)u.push({dbKey:oe(J,Ee.Aliased)?J.fieldAlias:n.columns[z].name,tsKey:z,field:oe(J,Ke)?io(J,s):J,relationTableTsKey:void 0,isJson:!1,selection:[]});let L=typeof i.orderBy==="function"?i.orderBy(S,U3()):i.orderBy??[];if(!Array.isArray(L))L=[L];m=L.map((z)=>{if(oe(z,Ke))return io(z,s);return Wp(z,s)}),d=i.limit,p=i.offset;for(let{tsKey:z,queryConfig:J,relation:P}of A){let W=q3(t,r,P),ee=ya(P.referencedTable),j=r[ee],T=`${s}_${z}`,B=tt(...W.fields.map((k,q)=>je(io(W.references[q],T),io(k,s)))),I=this.buildRelationalQuery({fullSchema:e,schema:t,tableNamesMap:r,table:e[j],tableConfig:t[j],queryConfig:oe(P,cs)?J===!0?{limit:1}:{...J,limit:1}:J,tableAlias:T,joinOn:B,nestedQueryRelation:P}),R=C`(${I.sql})`.as(z);u.push({dbKey:z,tsKey:z,field:R,relationTableTsKey:j,isJson:!0,selection:I.selection})}}if(u.length===0)throw new Ll({message:`No fields selected for table "${n.tsName}" ("${s}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.`});let y;if(h=tt(l,h),a){let S=C`json_array(${C.join(u.map(({field:A})=>oe(A,bt)?C.identifier(this.casing.getColumnCasing(A)):oe(A,Ee.Aliased)?A.sql:A),C`, `)})`;if(oe(a,Jp))S=C`coalesce(json_group_array(${S}), json_array())`;let x=[{dbKey:"data",tsKey:"data",field:S.as("data"),isJson:!0,relationTableTsKey:n.tsName,selection:u}];if(d!==void 0||p!==void 0||m.length>0)y=this.buildSelectQuery({table:Vp(o,s),fields:{},fieldsFlat:[{path:[],field:C.raw("*")}],where:h,limit:d,offset:p,orderBy:m,setOperators:[]}),h=void 0,d=void 0,p=void 0,m=void 0;else y=Vp(o,s);y=this.buildSelectQuery({table:oe(y,At)?y:new pt(y,{},s),fields:{},fieldsFlat:x.map(({field:A})=>({path:[],field:oe(A,Ke)?io(A,s):A})),joins:b,where:h,limit:d,offset:p,orderBy:m,setOperators:[]})}else y=this.buildSelectQuery({table:Vp(o,s),fields:{},fieldsFlat:u.map(({field:S})=>({path:[],field:oe(S,Ke)?io(S,s):S})),joins:b,where:h,limit:d,offset:p,orderBy:m,setOperators:[]});return{tableTsKey:n.tsName,sql:y,selection:u}}};E$=class E$ extends Bl{static[F]="SQLiteSyncDialect";migrate(e,t,r){let o=r===void 0?"__drizzle_migrations":typeof r==="string"?"__drizzle_migrations":r.migrationsTable??"__drizzle_migrations",n=C`
@@ -751,7 +751,7 @@ printf 'REMOTE_ARTIFACT_DIR=%s\\n' "$remote_dir"
751
751
  `),i}async function dH(e,t){let r=await ut(e),o=r.users.find((n)=>n.handle===t);if(!o)throw Error(`Unknown pilot user: ${t}`);return{pilot:r.pilot,user:o}}async function pH(e){let t=await Ige(ao(kge(),"brains-ops-watchdog-smoke-")),r=ao(t,"id_ed25519"),o=ao(t,"known_hosts");try{let n=encodeURIComponent(`brain=${e.target.pilot.contentRepoPrefix}${e.target.user.handle}`),i=await e.fetchImpl(`https://api.hetzner.cloud/v1/servers?label_selector=${n}`,{headers:{Authorization:`Bearer ${e.environment.HCLOUD_TOKEN}`}});if(!i.ok)throw Error(`Hetzner server lookup failed with ${i.status}`);let s=Age.parse(await i.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 Fl(r,Tge(e.environment.KAMAL_SSH_PRIVATE_KEY),{mode:384}),await Ege(r,384);let l=await e.commandRunner("ssh-keyscan",["-T","10","-t","ed25519",a.public_net.ipv4.ip]);if(l.exitCode!==0||!l.stdout.trim())throw Error("Unable to resolve watchdog smoke SSH host key");return await Fl(o,l.stdout,{mode:384}),{temporaryRoot:t,sshKeyPath:r,knownHostsPath:o,serverIp:a.public_net.ipv4.ip,commandRunner:e.commandRunner}}catch(n){throw await SO(t,{recursive:!0,force:!0}),n}}async function bO(e,t,r){return e.commandRunner("ssh",[...fH(e),`root@${e.serverIp}`,"bash","-s","--",t,r],{stdin:vO()})}async function Rge(e,t,r){return e.commandRunner("scp",[...fH(e),"-r",`root@${e.serverIp}:${t}/.`,r])}function fH(e){return["-i",e.sshKeyPath,"-o","BatchMode=yes","-o","IdentitiesOnly=yes","-o","ConnectTimeout=10","-o","StrictHostKeyChecking=yes","-o",`UserKnownHostsFile=${e.knownHostsPath}`]}async function Mb(e,t,r){await Promise.all([Fl(ao(e,`${t}.stdout.log`),r.stdout),Fl(ao(e,`${t}.stderr.log`),r.stderr)])}function Tge(e){return`${e.replace(/\r\n/g,`
752
752
  `).replace(/\\n/g,`
753
753
  `).trimEnd()}
754
- `}var cH,Age;var Fb=v(async()=>{de();oH();Kr();lf();Rs();await nH();cH=c.object({HCLOUD_TOKEN:c.string().min(1),KAMAL_SSH_PRIVATE_KEY:c.string().min(1)}),Age=c.object({servers:c.array(c.object({status:c.string(),public_net:c.object({ipv4:c.object({ip:c.string().min(1)})})}))})});import{chmod as nI,mkdir as fh,readFile as W2,writeFile as V2}from"fs/promises";import{dirname as dG,join as mc}from"path";import{fileURLToPath as pG}from"url";var mf={name:"@rizom/ops",version:"0.2.0-alpha.768",description:"Operator CLI for managing private brain fleet registry repos",keywords:["brains","ops","cli","deploy","fleet","operator"],license:"AGPL-3.0-only",author:"Yeehaa <yeehaa@rizom.ai> (https://rizom.ai)",bin:{"brains-ops":"./dist/brains-ops.js"},bugs:"https://github.com/rizom-ai/brains/issues",dependencies:{"@libsql/client":"^0.17.4","age-encryption":"^0.3.0",yaml:"^2.9.0"},devDependencies:{"@brains/contracts":"workspace:*","@brains/deploy-support":"workspace:*","@brains/eslint-config":"workspace:*","@brains/job-queue":"workspace:*","@brains/profile":"workspace:*","@brains/site-composition":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@brains/utils":"workspace:*","@types/bun":"^1.4.0",typescript:"^7.0.2"},engines:{bun:">=1.3.3"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./deploy":{types:"./dist/deploy.d.ts",import:"./dist/deploy.js",bun:"./dist/deploy.js"}},files:["dist","templates"],homepage:"https://github.com/rizom-ai/brains/tree/main/packages/brains-ops#readme",main:"./dist/index.js",publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/rizom-ai/brains.git",directory:"packages/brains-ops"},scripts:{build:"bun scripts/build.ts",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",prepublishOnly:"bun scripts/build.ts",test:"bun test --timeout 20000","test:smoke":"bun run build && RUN_SMOKE_TESTS=1 bun test --timeout 60000",typecheck:"tsc --noEmit"},type:"module",types:"./dist/index.d.ts"};Xo();fc();Rs();var fG=["pilot.yaml","package.json",".env.schema",".gitignore","cohorts/cohort-1.yaml","users/alice.yaml",".github/actions/varlock-env/action.yml",".github/workflows/build.yml",".github/workflows/deploy.yml",".github/workflows/directory-sync-stress.yml",".github/workflows/health-watchdog-smoke.yml",".github/workflows/offboard.yml",".github/workflows/reconcile.yml",".github/workflows/upgrade.yml","deploy/Dockerfile","deploy/kamal/deploy.yml","deploy/scripts/helpers.ts","deploy/scripts/create-predeploy-backup.ts","deploy/scripts/install-health-watchdog.ts","deploy/scripts/provision-server.ts","deploy/scripts/pull-local-models.ts","deploy/scripts/update-dns.ts","deploy/scripts/write-ssh-key.ts","deploy/scripts/decrypt-user-secrets.ts","deploy/scripts/validate-secrets.ts","deploy/scripts/write-kamal-secrets.ts","deploy/scripts/resolve-user-config.ts","deploy/scripts/resolve-missing-images.ts","deploy/scripts/verify-runtime-image.ts","deploy/scripts/resolve-deploy-handles.ts","deploy/scripts/sync-content-repo.ts",".kamal/hooks/pre-deploy","docs/onboarding-checklist.md","docs/canonical-crossover-record.md","docs/operator-playbook.md","docs/user-onboarding.md","README.md"],oI=new Set([".kamal/hooks/pre-deploy"]),mG=new Set(["cohorts/cohort-1.yaml","users/alice.yaml","docs/canonical-crossover-record.md"]),hG=pG(new URL("../templates/rover-pilot/",import.meta.url));function ho(e){return(t)=>t.includes(e)}function gG(e){return TO.find((t)=>e===`deploy/scripts/${t}`)}function iI(e){return e.replace(/\n {2}secret:\n(?: {4}- .*\n)+\nvolumes:\n/,`
754
+ `}var cH,Age;var Fb=v(async()=>{de();oH();Kr();lf();Rs();await nH();cH=c.object({HCLOUD_TOKEN:c.string().min(1),KAMAL_SSH_PRIVATE_KEY:c.string().min(1)}),Age=c.object({servers:c.array(c.object({status:c.string(),public_net:c.object({ipv4:c.object({ip:c.string().min(1)})})}))})});import{chmod as nI,mkdir as fh,readFile as W2,writeFile as V2}from"fs/promises";import{dirname as dG,join as mc}from"path";import{fileURLToPath as pG}from"url";var mf={name:"@rizom/ops",version:"0.2.0-alpha.769",description:"Operator CLI for managing private brain fleet registry repos",keywords:["brains","ops","cli","deploy","fleet","operator"],license:"AGPL-3.0-only",author:"Yeehaa <yeehaa@rizom.ai> (https://rizom.ai)",bin:{"brains-ops":"./dist/brains-ops.js"},bugs:"https://github.com/rizom-ai/brains/issues",dependencies:{"@libsql/client":"^0.17.4","age-encryption":"^0.3.0",yaml:"^2.9.0"},devDependencies:{"@brains/contracts":"workspace:*","@brains/deploy-support":"workspace:*","@brains/eslint-config":"workspace:*","@brains/job-queue":"workspace:*","@brains/profile":"workspace:*","@brains/site-composition":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@brains/utils":"workspace:*","@types/bun":"^1.4.0",typescript:"^7.0.2"},engines:{bun:">=1.3.3"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./deploy":{types:"./dist/deploy.d.ts",import:"./dist/deploy.js",bun:"./dist/deploy.js"}},files:["dist","templates"],homepage:"https://github.com/rizom-ai/brains/tree/main/packages/brains-ops#readme",main:"./dist/index.js",publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/rizom-ai/brains.git",directory:"packages/brains-ops"},scripts:{build:"bun scripts/build.ts",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",prepublishOnly:"bun scripts/build.ts",test:"bun test --timeout 20000","test:smoke":"bun run build && RUN_SMOKE_TESTS=1 bun test --timeout 60000",typecheck:"tsc --noEmit"},type:"module",types:"./dist/index.d.ts"};Xo();fc();Rs();var fG=["pilot.yaml","package.json",".env.schema",".gitignore","cohorts/cohort-1.yaml","users/alice.yaml",".github/actions/varlock-env/action.yml",".github/workflows/build.yml",".github/workflows/deploy.yml",".github/workflows/directory-sync-stress.yml",".github/workflows/health-watchdog-smoke.yml",".github/workflows/offboard.yml",".github/workflows/reconcile.yml",".github/workflows/upgrade.yml","deploy/Dockerfile","deploy/kamal/deploy.yml","deploy/scripts/helpers.ts","deploy/scripts/create-predeploy-backup.ts","deploy/scripts/install-health-watchdog.ts","deploy/scripts/provision-server.ts","deploy/scripts/pull-local-models.ts","deploy/scripts/update-dns.ts","deploy/scripts/write-ssh-key.ts","deploy/scripts/decrypt-user-secrets.ts","deploy/scripts/validate-secrets.ts","deploy/scripts/write-kamal-secrets.ts","deploy/scripts/resolve-user-config.ts","deploy/scripts/resolve-missing-images.ts","deploy/scripts/verify-runtime-image.ts","deploy/scripts/resolve-deploy-handles.ts","deploy/scripts/sync-content-repo.ts",".kamal/hooks/pre-deploy","docs/onboarding-checklist.md","docs/canonical-crossover-record.md","docs/operator-playbook.md","docs/user-onboarding.md","README.md"],oI=new Set([".kamal/hooks/pre-deploy"]),mG=new Set(["cohorts/cohort-1.yaml","users/alice.yaml","docs/canonical-crossover-record.md"]),hG=pG(new URL("../templates/rover-pilot/",import.meta.url));function ho(e){return(t)=>t.includes(e)}function gG(e){return TO.find((t)=>e===`deploy/scripts/${t}`)}function iI(e){return e.replace(/\n {2}secret:\n(?: {4}- .*\n)+\nvolumes:\n/,`
755
755
  secret:
756
756
  - __DYNAMIC_SECRETS__
757
757
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rizom/ops",
3
- "version": "0.2.0-alpha.768",
3
+ "version": "0.2.0-alpha.769",
4
4
  "description": "Operator CLI for managing private brain fleet registry repos",
5
5
  "keywords": [
6
6
  "brains",