@supabase/lite 0.7.1-next.1 → 0.7.1-next.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import qn,{statSync,readFileSync}from'node:fs';import*as Me from'node:path';import Me__default,{join}from'node:path';import {parse}from'dotenv';import*as pe from'node:fs/promises';import pe__default,{stat as stat$1,constants}from'node:fs/promises';import {fileURLToPath}from'node:url';import {createConnection}from'@supabase/lite/sqlite';import Kw from'node:os';import {createClient}from'@supabase/supabase-js';import W_,{createHash}from'node:crypto';import {DataLossError,isEqual,measureTime,splitSqlStatements,ensureVar,App,cloud}from'@supabase/lite';import {createRequire}from'module';import {resolve,posix,isAbsolute,sep,basename,dirname,normalize,relative}from'path';import*as ub from'fs';import {statSync as statSync$1,stat,realpathSync,realpath,readdirSync,readdir}from'fs';import {fileURLToPath as fileURLToPath$1}from'url';import {Deparser,QuoteUtils}from'pgsql-deparser';import JE from'chokidar';import {styleText,promisify}from'node:util';import Ge,{stdout,stdin}from'node:process';import*as _t from'node:readline';import _t__default from'node:readline';import {ReadStream}from'node:tty';import {DeparserContext}from'pgsql-deparser/visitors/base.js';import {SqlFormatter}from'pgsql-deparser/utils/sql-formatter.js';import {Buffer as Buffer$1}from'node:buffer';import k_ from'node:net';import {Command as Command$1}from'@commander-js/extra-typings';import g$,{execFile}from'node:child_process';import {Command}from'commander';try {
2
+ import Hn,{statSync,readFileSync}from'node:fs';import*as Me from'node:path';import Me__default,{join}from'node:path';import {parse}from'dotenv';import*as pe from'node:fs/promises';import pe__default,{stat as stat$1,constants}from'node:fs/promises';import {fileURLToPath}from'node:url';import {createConnection}from'@supabase/lite/sqlite';import Yw from'node:os';import {createClient}from'@supabase/supabase-js';import G_,{createHash}from'node:crypto';import {DataLossError,isEqual,measureTime,splitSqlStatements,ensureVar,App,cloud}from'@supabase/lite';import {createRequire}from'module';import {resolve,posix,isAbsolute,sep,basename,dirname,normalize,relative}from'path';import*as mb from'fs';import {statSync as statSync$1,stat,realpathSync,realpath,readdirSync,readdir}from'fs';import {fileURLToPath as fileURLToPath$1}from'url';import {Deparser,QuoteUtils}from'pgsql-deparser';import ZE from'chokidar';import {styleText,promisify}from'node:util';import Ge,{stdout,stdin}from'node:process';import*as _t from'node:readline';import _t__default from'node:readline';import {ReadStream}from'node:tty';import {DeparserContext}from'pgsql-deparser/visitors/base.js';import {SqlFormatter}from'pgsql-deparser/utils/sql-formatter.js';import {Buffer as Buffer$1}from'node:buffer';import P_ from'node:net';import {Command as Command$1}from'@commander-js/extra-typings';import y$,{execFile}from'node:child_process';import {Command}from'commander';try {
3
3
  /**
4
4
  * Adding this to avoid warnings from node:sqlite being experimental
5
5
  */
@@ -10,39 +10,39 @@ import qn,{statSync,readFileSync}from'node:fs';import*as Me from'node:path';impo
10
10
  };
11
11
  } catch {}
12
12
 
13
- var dg=Object.create;var ji=Object.defineProperty;var hg=Object.getOwnPropertyDescriptor;var gg=Object.getOwnPropertyNames;var yg=Object.getPrototypeOf,wg=Object.prototype.hasOwnProperty;var g=(e,t)=>()=>(e&&(t=e(e=0)),t);var ft=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),de=(e,t)=>{for(var r in t)ji(e,r,{get:t[r],enumerable:true});},bg=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of gg(t))!wg.call(e,s)&&s!==r&&ji(e,s,{get:()=>t[s],enumerable:!(n=hg(t,s))||n.enumerable});return e};var te=(e,t,r)=>(r=e!=null?dg(yg(e)):{},bg(ji(r,"default",{value:e,enumerable:true}),e));var Fi,Mi=g(()=>{Fi=process.stdin.isTTY?null:(async()=>{let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")})();});var ae=ft((t1,Ui)=>{var Un=process||{},mc=Un.argv||[],Mn=Un.env||{},Sg=!(Mn.NO_COLOR||mc.includes("--no-color"))&&(!!Mn.FORCE_COLOR||mc.includes("--color")||Un.platform==="win32"||(Un.stdout||{}).isTTY&&Mn.TERM!=="dumb"||!!Mn.CI),Eg=(e,t,r=e)=>n=>{let s=""+n,i=s.indexOf(t,e.length);return ~i?e+xg(s,t,r,i)+t:e+s+t},xg=(e,t,r,n)=>{let s="",i=0;do s+=e.substring(i,n)+r,i=n+t.length,n=e.indexOf(t,i);while(~n);return s+e.substring(i)},dc=(e=Sg)=>{let t=e?Eg:()=>String;return {isColorSupported:e,reset:t("\x1B[0m","\x1B[0m"),bold:t("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:t("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:t("\x1B[3m","\x1B[23m"),underline:t("\x1B[4m","\x1B[24m"),inverse:t("\x1B[7m","\x1B[27m"),hidden:t("\x1B[8m","\x1B[28m"),strikethrough:t("\x1B[9m","\x1B[29m"),black:t("\x1B[30m","\x1B[39m"),red:t("\x1B[31m","\x1B[39m"),green:t("\x1B[32m","\x1B[39m"),yellow:t("\x1B[33m","\x1B[39m"),blue:t("\x1B[34m","\x1B[39m"),magenta:t("\x1B[35m","\x1B[39m"),cyan:t("\x1B[36m","\x1B[39m"),white:t("\x1B[37m","\x1B[39m"),gray:t("\x1B[90m","\x1B[39m"),bgBlack:t("\x1B[40m","\x1B[49m"),bgRed:t("\x1B[41m","\x1B[49m"),bgGreen:t("\x1B[42m","\x1B[49m"),bgYellow:t("\x1B[43m","\x1B[49m"),bgBlue:t("\x1B[44m","\x1B[49m"),bgMagenta:t("\x1B[45m","\x1B[49m"),bgCyan:t("\x1B[46m","\x1B[49m"),bgWhite:t("\x1B[47m","\x1B[49m"),blackBright:t("\x1B[90m","\x1B[39m"),redBright:t("\x1B[91m","\x1B[39m"),greenBright:t("\x1B[92m","\x1B[39m"),yellowBright:t("\x1B[93m","\x1B[39m"),blueBright:t("\x1B[94m","\x1B[39m"),magentaBright:t("\x1B[95m","\x1B[39m"),cyanBright:t("\x1B[96m","\x1B[39m"),whiteBright:t("\x1B[97m","\x1B[39m"),bgBlackBright:t("\x1B[100m","\x1B[49m"),bgRedBright:t("\x1B[101m","\x1B[49m"),bgGreenBright:t("\x1B[102m","\x1B[49m"),bgYellowBright:t("\x1B[103m","\x1B[49m"),bgBlueBright:t("\x1B[104m","\x1B[49m"),bgMagentaBright:t("\x1B[105m","\x1B[49m"),bgCyanBright:t("\x1B[106m","\x1B[49m"),bgWhiteBright:t("\x1B[107m","\x1B[49m")}};Ui.exports=dc();Ui.exports.createColors=dc;});function $g(e){let t=typeof process<"u"&&process.env||void 0;return t?t.NODE_ENV==="test"?true:t[_g[e]]==="1":false}function yc(e){return gc[e]}function Bi(){return hc.filter(e=>gc[e])}function Bn(){let e=Bi();if(e.length===0)return null;let t=e.includes("storage")?" Cloud sync (lite cloud deploy) is disabled.":"";return `EXPERIMENTAL FEATURES ENABLED: ${e.join(", ")} - not supported, do not use in production.${t}`}var _g,hc,gc,Yt=g(()=>{_g={storage:"EXPERIMENTAL_STORAGE",cloud:"EXPERIMENTAL_CLOUD"},hc=["storage","cloud"],gc=Object.fromEntries(hc.map(e=>[e,$g(e)]));});function ke(e,t){qn.existsSync(e)||(qn.mkdirSync(e,{recursive:true}),t?.());}function vt(e,t,r){qn.existsSync(e)||(qn.writeFileSync(e,t),r?.());}async function qi(){if(!Fi)throw new Error("No input given \u2014 pass it as an argument or pipe it via stdin.");return Fi}var Tt=g(()=>{Mi();});function Tg(e,t){let r=e.slice(0,t).split(/\r\n|\n|\r/g);return [r.length,r.pop().length+1]}function Ag(e,t,r){let n=e.split(/\r\n|\n|\r/g),s="",i=(Math.log10(t+1)|0)+1;for(let o=t-1;o<=t+1;o++){let a=n[o-1];a&&(s+=o.toString().padEnd(i," "),s+=": ",s+=a,s+=`
13
+ var dg=Object.create;var Fi=Object.defineProperty;var hg=Object.getOwnPropertyDescriptor;var gg=Object.getOwnPropertyNames;var yg=Object.getPrototypeOf,wg=Object.prototype.hasOwnProperty;var g=(e,t)=>()=>(e&&(t=e(e=0)),t);var ft=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),de=(e,t)=>{for(var r in t)Fi(e,r,{get:t[r],enumerable:true});},bg=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of gg(t))!wg.call(e,s)&&s!==r&&Fi(e,s,{get:()=>t[s],enumerable:!(n=hg(t,s))||n.enumerable});return e};var te=(e,t,r)=>(r=e!=null?dg(yg(e)):{},bg(Fi(r,"default",{value:e,enumerable:true}),e));var Mi,Ui=g(()=>{Mi=process.stdin.isTTY?null:(async()=>{let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")})();});var ae=ft((r1,Bi)=>{var Bn=process||{},hc=Bn.argv||[],Un=Bn.env||{},Sg=!(Un.NO_COLOR||hc.includes("--no-color"))&&(!!Un.FORCE_COLOR||hc.includes("--color")||Bn.platform==="win32"||(Bn.stdout||{}).isTTY&&Un.TERM!=="dumb"||!!Un.CI),Eg=(e,t,r=e)=>n=>{let s=""+n,i=s.indexOf(t,e.length);return ~i?e+xg(s,t,r,i)+t:e+s+t},xg=(e,t,r,n)=>{let s="",i=0;do s+=e.substring(i,n)+r,i=n+t.length,n=e.indexOf(t,i);while(~n);return s+e.substring(i)},gc=(e=Sg)=>{let t=e?Eg:()=>String;return {isColorSupported:e,reset:t("\x1B[0m","\x1B[0m"),bold:t("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:t("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:t("\x1B[3m","\x1B[23m"),underline:t("\x1B[4m","\x1B[24m"),inverse:t("\x1B[7m","\x1B[27m"),hidden:t("\x1B[8m","\x1B[28m"),strikethrough:t("\x1B[9m","\x1B[29m"),black:t("\x1B[30m","\x1B[39m"),red:t("\x1B[31m","\x1B[39m"),green:t("\x1B[32m","\x1B[39m"),yellow:t("\x1B[33m","\x1B[39m"),blue:t("\x1B[34m","\x1B[39m"),magenta:t("\x1B[35m","\x1B[39m"),cyan:t("\x1B[36m","\x1B[39m"),white:t("\x1B[37m","\x1B[39m"),gray:t("\x1B[90m","\x1B[39m"),bgBlack:t("\x1B[40m","\x1B[49m"),bgRed:t("\x1B[41m","\x1B[49m"),bgGreen:t("\x1B[42m","\x1B[49m"),bgYellow:t("\x1B[43m","\x1B[49m"),bgBlue:t("\x1B[44m","\x1B[49m"),bgMagenta:t("\x1B[45m","\x1B[49m"),bgCyan:t("\x1B[46m","\x1B[49m"),bgWhite:t("\x1B[47m","\x1B[49m"),blackBright:t("\x1B[90m","\x1B[39m"),redBright:t("\x1B[91m","\x1B[39m"),greenBright:t("\x1B[92m","\x1B[39m"),yellowBright:t("\x1B[93m","\x1B[39m"),blueBright:t("\x1B[94m","\x1B[39m"),magentaBright:t("\x1B[95m","\x1B[39m"),cyanBright:t("\x1B[96m","\x1B[39m"),whiteBright:t("\x1B[97m","\x1B[39m"),bgBlackBright:t("\x1B[100m","\x1B[49m"),bgRedBright:t("\x1B[101m","\x1B[49m"),bgGreenBright:t("\x1B[102m","\x1B[49m"),bgYellowBright:t("\x1B[103m","\x1B[49m"),bgBlueBright:t("\x1B[104m","\x1B[49m"),bgMagentaBright:t("\x1B[105m","\x1B[49m"),bgCyanBright:t("\x1B[106m","\x1B[49m"),bgWhiteBright:t("\x1B[107m","\x1B[49m")}};Bi.exports=gc();Bi.exports.createColors=gc;});function $g(e){let t=typeof process<"u"&&process.env||void 0;return t?t.NODE_ENV==="test"?true:t[_g[e]]==="1":false}function bc(e){return wc[e]}function qi(){return yc.filter(e=>wc[e])}function qn(){let e=qi();if(e.length===0)return null;let t=e.includes("storage")?" Cloud sync (lite cloud deploy) is disabled.":"";return `EXPERIMENTAL FEATURES ENABLED: ${e.join(", ")} - not supported, do not use in production.${t}`}var _g,yc,wc,Yt=g(()=>{_g={storage:"EXPERIMENTAL_STORAGE",cloud:"EXPERIMENTAL_CLOUD"},yc=["storage","cloud"],wc=Object.fromEntries(yc.map(e=>[e,$g(e)]));});function ke(e,t){Hn.existsSync(e)||(Hn.mkdirSync(e,{recursive:true}),t?.());}function vt(e,t,r){Hn.existsSync(e)||(Hn.writeFileSync(e,t),r?.());}async function Hi(){if(!Mi)throw new Error("No input given \u2014 pass it as an argument or pipe it via stdin.");return Mi}var Tt=g(()=>{Ui();});function Tg(e,t){let r=e.slice(0,t).split(/\r\n|\n|\r/g);return [r.length,r.pop().length+1]}function Ag(e,t,r){let n=e.split(/\r\n|\n|\r/g),s="",i=(Math.log10(t+1)|0)+1;for(let o=t-1;o<=t+1;o++){let a=n[o-1];a&&(s+=o.toString().padEnd(i," "),s+=": ",s+=a,s+=`
14
14
  `,o===t&&(s+=" ".repeat(i+r+2),s+=`^
15
15
  `));}return s}var H,At=g(()=>{H=class extends Error{line;column;codeblock;constructor(t,r){let[n,s]=Tg(r.toml,r.ptr),i=Ag(r.toml,n,s);super(`Invalid TOML document: ${t}
16
16
 
17
- ${i}`,r),this.line=n,this.column=s,this.codeblock=i;}};});function Cg(e,t){let r=0;for(;e[t-++r]==="\\";);return --r&&r%2}function Hn(e,t=0,r=e.length){let n=e.indexOf(`
17
+ ${i}`,r),this.line=n,this.column=s,this.codeblock=i;}};});function Cg(e,t){let r=0;for(;e[t-++r]==="\\";);return --r&&r%2}function Wn(e,t=0,r=e.length){let n=e.indexOf(`
18
18
  `,t);return e[n-1]==="\r"&&n--,n<=r?n:-1}function Qt(e,t){for(let r=t;r<e.length;r++){let n=e[r];if(n===`
19
19
  `)return r;if(n==="\r"&&e[r+1]===`
20
20
  `)return r+1;if(n<" "&&n!==" "||n==="\x7F")throw new H("control characters are not allowed in comments",{toml:e,ptr:t})}return e.length}function Pe(e,t,r,n){let s;for(;(s=e[t])===" "||s===" "||!r&&(s===`
21
21
  `||s==="\r"&&e[t+1]===`
22
- `);)t++;return n||s!=="#"?t:Pe(e,Qt(e,t),r)}function bc(e,t,r,n,s=false){if(!n)return t=Hn(e,t),t<0?e.length:t;for(let i=t;i<e.length;i++){let o=e[i];if(o==="#")i=Hn(e,i);else {if(o===r)return i+1;if(o===n||s&&(o===`
22
+ `);)t++;return n||s!=="#"?t:Pe(e,Qt(e,t),r)}function Ec(e,t,r,n,s=false){if(!n)return t=Wn(e,t),t<0?e.length:t;for(let i=t;i<e.length;i++){let o=e[i];if(o==="#")i=Wn(e,i);else {if(o===r)return i+1;if(o===n||s&&(o===`
23
23
  `||o==="\r"&&e[i+1]===`
24
- `))return i}}throw new H("cannot find end of structure",{toml:e,ptr:t})}function Wn(e,t){let r=e[t],n=r===e[t+1]&&e[t+1]===e[t+2]?e.slice(t,t+3):r;t+=n.length-1;do t=e.indexOf(n,++t);while(t>-1&&r!=="'"&&Cg(e,t));return t>-1&&(t+=n.length,n.length>1&&(e[t]===r&&t++,e[t]===r&&t++)),t}var vr=g(()=>{At();});var Rg,Tr,Hi=g(()=>{Rg=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,Tr=class e extends Date{#e=false;#t=false;#r=null;constructor(t){let r=true,n=true,s="Z";if(typeof t=="string"){let i=t.match(Rg);i?(i[1]||(r=false,t=`0000-01-01T${t}`),n=!!i[2],n&&t[10]===" "&&(t=t.replace(" ","T")),i[2]&&+i[2]>23?t="":(s=i[3]||null,t=t.toUpperCase(),!s&&n&&(t+="Z"))):t="";}super(t),isNaN(this.getTime())||(this.#e=r,this.#t=n,this.#r=s);}isDateTime(){return this.#e&&this.#t}isLocal(){return !this.#e||!this.#t||!this.#r}isDate(){return this.#e&&!this.#t}isTime(){return this.#t&&!this.#e}isValid(){return this.#e||this.#t}toISOString(){let t=super.toISOString();if(this.isDate())return t.slice(0,10);if(this.isTime())return t.slice(11,23);if(this.#r===null)return t.slice(0,-1);if(this.#r==="Z")return t;let r=+this.#r.slice(1,3)*60+ +this.#r.slice(4,6);return r=this.#r[0]==="-"?r:-r,new Date(this.getTime()-r*6e4).toISOString().slice(0,-1)+this.#r}static wrapAsOffsetDateTime(t,r="Z"){let n=new e(t);return n.#r=r,n}static wrapAsLocalDateTime(t){let r=new e(t);return r.#r=null,r}static wrapAsLocalDate(t){let r=new e(t);return r.#t=false,r.#r=null,r}static wrapAsLocalTime(t){let r=new e(t);return r.#e=false,r.#r=null,r}};});function Gn(e,t=0,r=e.length){let n=e[t]==="'",s=e[t++]===e[t]&&e[t]===e[t+1];s&&(r-=2,e[t+=2]==="\r"&&t++,e[t]===`
24
+ `))return i}}throw new H("cannot find end of structure",{toml:e,ptr:t})}function Gn(e,t){let r=e[t],n=r===e[t+1]&&e[t+1]===e[t+2]?e.slice(t,t+3):r;t+=n.length-1;do t=e.indexOf(n,++t);while(t>-1&&r!=="'"&&Cg(e,t));return t>-1&&(t+=n.length,n.length>1&&(e[t]===r&&t++,e[t]===r&&t++)),t}var vr=g(()=>{At();});var Rg,Tr,Wi=g(()=>{Rg=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,Tr=class e extends Date{#e=false;#t=false;#r=null;constructor(t){let r=true,n=true,s="Z";if(typeof t=="string"){let i=t.match(Rg);i?(i[1]||(r=false,t=`0000-01-01T${t}`),n=!!i[2],n&&t[10]===" "&&(t=t.replace(" ","T")),i[2]&&+i[2]>23?t="":(s=i[3]||null,t=t.toUpperCase(),!s&&n&&(t+="Z"))):t="";}super(t),isNaN(this.getTime())||(this.#e=r,this.#t=n,this.#r=s);}isDateTime(){return this.#e&&this.#t}isLocal(){return !this.#e||!this.#t||!this.#r}isDate(){return this.#e&&!this.#t}isTime(){return this.#t&&!this.#e}isValid(){return this.#e||this.#t}toISOString(){let t=super.toISOString();if(this.isDate())return t.slice(0,10);if(this.isTime())return t.slice(11,23);if(this.#r===null)return t.slice(0,-1);if(this.#r==="Z")return t;let r=+this.#r.slice(1,3)*60+ +this.#r.slice(4,6);return r=this.#r[0]==="-"?r:-r,new Date(this.getTime()-r*6e4).toISOString().slice(0,-1)+this.#r}static wrapAsOffsetDateTime(t,r="Z"){let n=new e(t);return n.#r=r,n}static wrapAsLocalDateTime(t){let r=new e(t);return r.#r=null,r}static wrapAsLocalDate(t){let r=new e(t);return r.#t=false,r.#r=null,r}static wrapAsLocalTime(t){let r=new e(t);return r.#e=false,r.#r=null,r}};});function zn(e,t=0,r=e.length){let n=e[t]==="'",s=e[t++]===e[t]&&e[t]===e[t+1];s&&(r-=2,e[t+=2]==="\r"&&t++,e[t]===`
25
25
  `&&t++);let i=0,o,a="",l=t;for(;t<r-1;){let c=e[t++];if(c===`
26
26
  `||c==="\r"&&e[t]===`
27
27
  `){if(!s)throw new H("newlines are not allowed in strings",{toml:e,ptr:t-1})}else if(c<" "&&c!==" "||c==="\x7F")throw new H("control characters are not allowed in strings",{toml:e,ptr:t-1});if(o){if(o=false,c==="x"||c==="u"||c==="U"){let p=e.slice(t,t+=c==="x"?2:c==="u"?4:8);if(!Ng.test(p))throw new H("invalid unicode escape",{toml:e,ptr:i});try{a+=String.fromCodePoint(parseInt(p,16));}catch{throw new H("invalid unicode escape",{toml:e,ptr:i})}}else if(s&&(c===`
28
28
  `||c===" "||c===" "||c==="\r")){if(t=Pe(e,t-1,true),e[t]!==`
29
- `&&e[t]!=="\r")throw new H("invalid escape: only line-ending whitespace may be escaped",{toml:e,ptr:i});t=Pe(e,t);}else if(c in Sc)a+=Sc[c];else throw new H("unrecognized escape sequence",{toml:e,ptr:i});l=t;}else !n&&c==="\\"&&(i=t-1,o=true,a+=e.slice(l,i));}return a+e.slice(l,r-1)}function Ec(e,t,r,n){if(e==="true")return true;if(e==="false")return false;if(e==="-inf")return -1/0;if(e==="inf"||e==="+inf")return 1/0;if(e==="nan"||e==="+nan"||e==="-nan")return NaN;if(e==="-0")return n?0n:0;let s=kg.test(e);if(s||Pg.test(e)){if(Og.test(e))throw new H("leading zeroes are not allowed",{toml:t,ptr:r});e=e.replace(/_/g,"");let o=+e;if(isNaN(o))throw new H("invalid number",{toml:t,ptr:r});if(s){if((s=!Number.isSafeInteger(o))&&!n)throw new H("integer value cannot be represented losslessly",{toml:t,ptr:r});(s||n===true)&&(o=BigInt(e));}return o}let i=new Tr(e);if(!i.isValid())throw new H("invalid value",{toml:t,ptr:r});return i}var kg,Pg,Og,Ng,Sc,Wi=g(()=>{vr();Hi();At();kg=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,Pg=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,Og=/^[+-]?0[0-9_]/,Ng=/^[0-9a-f]{2,8}$/i,Sc={b:"\b",t:" ",n:`
30
- `,f:"\f",r:"\r",e:"\x1B",'"':'"',"\\":"\\"};});function Ig(e,t,r){let n=e.slice(t,r),s=n.indexOf("#");return s>-1&&(Qt(e,s),n=n.slice(0,s)),[n.trimEnd(),s]}function Ar(e,t,r,n,s){if(n===0)throw new H("document contains excessively nested structures. aborting.",{toml:e,ptr:t});let i=e[t];if(i==="["||i==="{"){let[l,c]=i==="["?_c(e,t,n,s):xc(e,t,n,s);if(r){if(c=Pe(e,c),e[c]===",")c++;else if(e[c]!==r)throw new H("expected comma or end of structure",{toml:e,ptr:c})}return [l,c]}let o;if(i==='"'||i==="'"){o=Wn(e,t);let l=Gn(e,t,o);if(r){if(o=Pe(e,o),e[o]&&e[o]!==","&&e[o]!==r&&e[o]!==`
31
- `&&e[o]!=="\r")throw new H("unexpected character encountered",{toml:e,ptr:o});o+=+(e[o]===",");}return [l,o]}o=bc(e,t,",",r);let a=Ig(e,t,o-+(e[o-1]===","));if(!a[0])throw new H("incomplete key-value declaration: no value specified",{toml:e,ptr:t});return r&&a[1]>-1&&(o=Pe(e,t+a[1]),o+=+(e[o]===",")),[Ec(a[0],e,t,s),o]}var Gi=g(()=>{Wi();zi();vr();At();});function zn(e,t,r="="){let n=t-1,s=[],i=e.indexOf(r,t);if(i<0)throw new H("incomplete key-value: cannot find end of key",{toml:e,ptr:t});do{let o=e[t=++n];if(o!==" "&&o!==" ")if(o==='"'||o==="'"){if(o===e[t+1]&&o===e[t+2])throw new H("multiline strings are not allowed in keys",{toml:e,ptr:t});let a=Wn(e,t);if(a<0)throw new H("unfinished string encountered",{toml:e,ptr:t});n=e.indexOf(".",a);let l=e.slice(a,n<0||n>i?i:n),c=Hn(l);if(c>-1)throw new H("newlines are not allowed in keys",{toml:e,ptr:t+n+c});if(l.trimStart())throw new H("found extra tokens after the string part",{toml:e,ptr:a});if(i<a&&(i=e.indexOf(r,a),i<0))throw new H("incomplete key-value: cannot find end of key",{toml:e,ptr:t});s.push(Gn(e,t,a));}else {n=e.indexOf(".",t);let a=e.slice(t,n<0||n>i?i:n);if(!Lg.test(a))throw new H("only letter, numbers, dashes and underscores are allowed in keys",{toml:e,ptr:t});s.push(a.trimEnd());}}while(n+1&&n<i);return [s,Pe(e,i+1,true,true)]}function xc(e,t,r,n){let s={},i=new Set,o;for(t++;(o=e[t++])!=="}"&&o;){if(o===",")throw new H("expected value, found comma",{toml:e,ptr:t-1});if(o==="#")t=Qt(e,t);else if(o!==" "&&o!==" "&&o!==`
32
- `&&o!=="\r"){let a,l=s,c=false,[p,u]=zn(e,t-1);for(let d=0;d<p.length;d++){if(d&&(l=c?l[a]:l[a]={}),a=p[d],(c=Object.hasOwn(l,a))&&(typeof l[a]!="object"||i.has(l[a])))throw new H("trying to redefine an already defined value",{toml:e,ptr:t});!c&&a==="__proto__"&&Object.defineProperty(l,a,{enumerable:true,configurable:true,writable:true});}if(c)throw new H("trying to redefine an already defined value",{toml:e,ptr:t});let[f,h]=Ar(e,u,"}",r-1,n);i.add(f),l[a]=f,t=h;}}if(!o)throw new H("unfinished table encountered",{toml:e,ptr:t});return [s,t]}function _c(e,t,r,n){let s=[],i;for(t++;(i=e[t++])!=="]"&&i;){if(i===",")throw new H("expected value, found comma",{toml:e,ptr:t-1});if(i==="#")t=Qt(e,t);else if(i!==" "&&i!==" "&&i!==`
33
- `&&i!=="\r"){let o=Ar(e,t-1,"]",r-1,n);s.push(o[0]),t=o[1];}}if(!i)throw new H("unfinished array encountered",{toml:e,ptr:t});return [s,t]}var Lg,zi=g(()=>{Wi();Gi();vr();At();Lg=/^[a-zA-Z0-9-_]+[ \t]*$/;});function $c(e,t,r,n){let s=t,i=r,o,a=false,l;for(let c=0;c<e.length;c++){if(c){if(s=a?s[o]:s[o]={},i=(l=i[o]).c,n===0&&(l.t===1||l.t===2))return null;if(l.t===2){let p=s.length-1;s=s[p],i=i[p].c;}}if(o=e[c],(a=Object.hasOwn(s,o))&&i[o]?.t===0&&i[o]?.d)return null;a||(o==="__proto__"&&(Object.defineProperty(s,o,{enumerable:true,configurable:true,writable:true}),Object.defineProperty(i,o,{enumerable:true,configurable:true,writable:true})),i[o]={t:c<e.length-1&&n===2?3:n,d:false,i:0,c:{}});}if(l=i[o],l.t!==n&&!(n===1&&l.t===3)||(n===2&&(l.d||(l.d=true,s[o]=[]),s[o].push(s={}),l.c[l.i++]=l={t:1,d:false,i:0,c:{}}),l.d))return null;if(l.d=true,n===1)s=a?s[o]:s[o]={};else if(n===0&&a)return null;return [o,s,l.c]}function Ct(e,{maxDepth:t=1e3,integersAsBigInt:r}={}){let n={},s={},i=n,o=s;for(let a=Pe(e,0);a<e.length;){if(e[a]==="["){let l=e[++a]==="[",c=zn(e,a+=+l,"]");if(l){if(e[c[1]-1]!=="]")throw new H("expected end of table declaration",{toml:e,ptr:c[1]-1});c[1]++;}let p=$c(c[0],n,s,l?2:1);if(!p)throw new H("trying to redefine an already defined table or value",{toml:e,ptr:a});o=p[2],i=p[1],a=c[1];}else {let l=zn(e,a),c=$c(l[0],i,o,0);if(!c)throw new H("trying to redefine an already defined table or value",{toml:e,ptr:a});let p=Ar(e,l[1],void 0,t,r);c[1][c[0]]=p[0],a=p[1];}if(a=Pe(e,a,true),e[a]&&e[a]!==`
34
- `&&e[a]!=="\r")throw new H("each key-value declaration must be followed by an end-of-line",{toml:e,ptr:a});a=Pe(e,a);}return n}var vc=g(()=>{zi();Gi();vr();At();});function Cr(e){let t=typeof e;if(t==="object"){if(Array.isArray(e))return "array";if(e instanceof Date)return "date"}return t}function Dg(e){for(let t=0;t<e.length;t++)if(Cr(e[t])!=="object")return false;return e.length!=0}function Vi(e){return JSON.stringify(e).replace(/\x7f/g,"\\u007f")}function Ki(e,t,r,n){if(r===0)throw new Error("Could not stringify the object: maximum object depth exceeded");if(t==="number")return isNaN(e)?"nan":e===1/0?"inf":e===-1/0?"-inf":n&&Number.isInteger(e)?e.toFixed(1):e.toString();if(t==="bigint"||t==="boolean")return e.toString();if(t==="string")return Vi(e);if(t==="date"){if(isNaN(e.getTime()))throw new TypeError("cannot serialize invalid date");return e.toISOString()}if(t==="object")return jg(e,r,n);if(t==="array")return Fg(e,r,n)}function jg(e,t,r){let n=Object.keys(e);if(n.length===0)return "{}";let s="{ ";for(let i=0;i<n.length;i++){let o=n[i];i&&(s+=", "),s+=Tc.test(o)?o:Vi(o),s+=" = ",s+=Ki(e[o],Cr(e[o]),t-1,r);}return s+" }"}function Fg(e,t,r){if(e.length===0)return "[]";let n="[ ";for(let s=0;s<e.length;s++){if(s&&(n+=", "),e[s]===null||e[s]===void 0)throw new TypeError("arrays cannot contain null or undefined values");n+=Ki(e[s],Cr(e[s]),t-1,r);}return n+" ]"}function Mg(e,t,r,n){if(r===0)throw new Error("Could not stringify the object: maximum object depth exceeded");let s="";for(let i=0;i<e.length;i++)s+=`${s&&`
29
+ `&&e[t]!=="\r")throw new H("invalid escape: only line-ending whitespace may be escaped",{toml:e,ptr:i});t=Pe(e,t);}else if(c in xc)a+=xc[c];else throw new H("unrecognized escape sequence",{toml:e,ptr:i});l=t;}else !n&&c==="\\"&&(i=t-1,o=true,a+=e.slice(l,i));}return a+e.slice(l,r-1)}function _c(e,t,r,n){if(e==="true")return true;if(e==="false")return false;if(e==="-inf")return -1/0;if(e==="inf"||e==="+inf")return 1/0;if(e==="nan"||e==="+nan"||e==="-nan")return NaN;if(e==="-0")return n?0n:0;let s=kg.test(e);if(s||Pg.test(e)){if(Og.test(e))throw new H("leading zeroes are not allowed",{toml:t,ptr:r});e=e.replace(/_/g,"");let o=+e;if(isNaN(o))throw new H("invalid number",{toml:t,ptr:r});if(s){if((s=!Number.isSafeInteger(o))&&!n)throw new H("integer value cannot be represented losslessly",{toml:t,ptr:r});(s||n===true)&&(o=BigInt(e));}return o}let i=new Tr(e);if(!i.isValid())throw new H("invalid value",{toml:t,ptr:r});return i}var kg,Pg,Og,Ng,xc,Gi=g(()=>{vr();Wi();At();kg=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,Pg=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,Og=/^[+-]?0[0-9_]/,Ng=/^[0-9a-f]{2,8}$/i,xc={b:"\b",t:" ",n:`
30
+ `,f:"\f",r:"\r",e:"\x1B",'"':'"',"\\":"\\"};});function Ig(e,t,r){let n=e.slice(t,r),s=n.indexOf("#");return s>-1&&(Qt(e,s),n=n.slice(0,s)),[n.trimEnd(),s]}function Ar(e,t,r,n,s){if(n===0)throw new H("document contains excessively nested structures. aborting.",{toml:e,ptr:t});let i=e[t];if(i==="["||i==="{"){let[l,c]=i==="["?vc(e,t,n,s):$c(e,t,n,s);if(r){if(c=Pe(e,c),e[c]===",")c++;else if(e[c]!==r)throw new H("expected comma or end of structure",{toml:e,ptr:c})}return [l,c]}let o;if(i==='"'||i==="'"){o=Gn(e,t);let l=zn(e,t,o);if(r){if(o=Pe(e,o),e[o]&&e[o]!==","&&e[o]!==r&&e[o]!==`
31
+ `&&e[o]!=="\r")throw new H("unexpected character encountered",{toml:e,ptr:o});o+=+(e[o]===",");}return [l,o]}o=Ec(e,t,",",r);let a=Ig(e,t,o-+(e[o-1]===","));if(!a[0])throw new H("incomplete key-value declaration: no value specified",{toml:e,ptr:t});return r&&a[1]>-1&&(o=Pe(e,t+a[1]),o+=+(e[o]===",")),[_c(a[0],e,t,s),o]}var zi=g(()=>{Gi();Vi();vr();At();});function Vn(e,t,r="="){let n=t-1,s=[],i=e.indexOf(r,t);if(i<0)throw new H("incomplete key-value: cannot find end of key",{toml:e,ptr:t});do{let o=e[t=++n];if(o!==" "&&o!==" ")if(o==='"'||o==="'"){if(o===e[t+1]&&o===e[t+2])throw new H("multiline strings are not allowed in keys",{toml:e,ptr:t});let a=Gn(e,t);if(a<0)throw new H("unfinished string encountered",{toml:e,ptr:t});n=e.indexOf(".",a);let l=e.slice(a,n<0||n>i?i:n),c=Wn(l);if(c>-1)throw new H("newlines are not allowed in keys",{toml:e,ptr:t+n+c});if(l.trimStart())throw new H("found extra tokens after the string part",{toml:e,ptr:a});if(i<a&&(i=e.indexOf(r,a),i<0))throw new H("incomplete key-value: cannot find end of key",{toml:e,ptr:t});s.push(zn(e,t,a));}else {n=e.indexOf(".",t);let a=e.slice(t,n<0||n>i?i:n);if(!Lg.test(a))throw new H("only letter, numbers, dashes and underscores are allowed in keys",{toml:e,ptr:t});s.push(a.trimEnd());}}while(n+1&&n<i);return [s,Pe(e,i+1,true,true)]}function $c(e,t,r,n){let s={},i=new Set,o;for(t++;(o=e[t++])!=="}"&&o;){if(o===",")throw new H("expected value, found comma",{toml:e,ptr:t-1});if(o==="#")t=Qt(e,t);else if(o!==" "&&o!==" "&&o!==`
32
+ `&&o!=="\r"){let a,l=s,c=false,[p,u]=Vn(e,t-1);for(let d=0;d<p.length;d++){if(d&&(l=c?l[a]:l[a]={}),a=p[d],(c=Object.hasOwn(l,a))&&(typeof l[a]!="object"||i.has(l[a])))throw new H("trying to redefine an already defined value",{toml:e,ptr:t});!c&&a==="__proto__"&&Object.defineProperty(l,a,{enumerable:true,configurable:true,writable:true});}if(c)throw new H("trying to redefine an already defined value",{toml:e,ptr:t});let[f,h]=Ar(e,u,"}",r-1,n);i.add(f),l[a]=f,t=h;}}if(!o)throw new H("unfinished table encountered",{toml:e,ptr:t});return [s,t]}function vc(e,t,r,n){let s=[],i;for(t++;(i=e[t++])!=="]"&&i;){if(i===",")throw new H("expected value, found comma",{toml:e,ptr:t-1});if(i==="#")t=Qt(e,t);else if(i!==" "&&i!==" "&&i!==`
33
+ `&&i!=="\r"){let o=Ar(e,t-1,"]",r-1,n);s.push(o[0]),t=o[1];}}if(!i)throw new H("unfinished array encountered",{toml:e,ptr:t});return [s,t]}var Lg,Vi=g(()=>{Gi();zi();vr();At();Lg=/^[a-zA-Z0-9-_]+[ \t]*$/;});function Tc(e,t,r,n){let s=t,i=r,o,a=false,l;for(let c=0;c<e.length;c++){if(c){if(s=a?s[o]:s[o]={},i=(l=i[o]).c,n===0&&(l.t===1||l.t===2))return null;if(l.t===2){let p=s.length-1;s=s[p],i=i[p].c;}}if(o=e[c],(a=Object.hasOwn(s,o))&&i[o]?.t===0&&i[o]?.d)return null;a||(o==="__proto__"&&(Object.defineProperty(s,o,{enumerable:true,configurable:true,writable:true}),Object.defineProperty(i,o,{enumerable:true,configurable:true,writable:true})),i[o]={t:c<e.length-1&&n===2?3:n,d:false,i:0,c:{}});}if(l=i[o],l.t!==n&&!(n===1&&l.t===3)||(n===2&&(l.d||(l.d=true,s[o]=[]),s[o].push(s={}),l.c[l.i++]=l={t:1,d:false,i:0,c:{}}),l.d))return null;if(l.d=true,n===1)s=a?s[o]:s[o]={};else if(n===0&&a)return null;return [o,s,l.c]}function Ct(e,{maxDepth:t=1e3,integersAsBigInt:r}={}){let n={},s={},i=n,o=s;for(let a=Pe(e,0);a<e.length;){if(e[a]==="["){let l=e[++a]==="[",c=Vn(e,a+=+l,"]");if(l){if(e[c[1]-1]!=="]")throw new H("expected end of table declaration",{toml:e,ptr:c[1]-1});c[1]++;}let p=Tc(c[0],n,s,l?2:1);if(!p)throw new H("trying to redefine an already defined table or value",{toml:e,ptr:a});o=p[2],i=p[1],a=c[1];}else {let l=Vn(e,a),c=Tc(l[0],i,o,0);if(!c)throw new H("trying to redefine an already defined table or value",{toml:e,ptr:a});let p=Ar(e,l[1],void 0,t,r);c[1][c[0]]=p[0],a=p[1];}if(a=Pe(e,a,true),e[a]&&e[a]!==`
34
+ `&&e[a]!=="\r")throw new H("each key-value declaration must be followed by an end-of-line",{toml:e,ptr:a});a=Pe(e,a);}return n}var Ac=g(()=>{Vi();zi();vr();At();});function Cr(e){let t=typeof e;if(t==="object"){if(Array.isArray(e))return "array";if(e instanceof Date)return "date"}return t}function Dg(e){for(let t=0;t<e.length;t++)if(Cr(e[t])!=="object")return false;return e.length!=0}function Ki(e){return JSON.stringify(e).replace(/\x7f/g,"\\u007f")}function Xi(e,t,r,n){if(r===0)throw new Error("Could not stringify the object: maximum object depth exceeded");if(t==="number")return isNaN(e)?"nan":e===1/0?"inf":e===-1/0?"-inf":n&&Number.isInteger(e)?e.toFixed(1):e.toString();if(t==="bigint"||t==="boolean")return e.toString();if(t==="string")return Ki(e);if(t==="date"){if(isNaN(e.getTime()))throw new TypeError("cannot serialize invalid date");return e.toISOString()}if(t==="object")return jg(e,r,n);if(t==="array")return Fg(e,r,n)}function jg(e,t,r){let n=Object.keys(e);if(n.length===0)return "{}";let s="{ ";for(let i=0;i<n.length;i++){let o=n[i];i&&(s+=", "),s+=Cc.test(o)?o:Ki(o),s+=" = ",s+=Xi(e[o],Cr(e[o]),t-1,r);}return s+" }"}function Fg(e,t,r){if(e.length===0)return "[]";let n="[ ";for(let s=0;s<e.length;s++){if(s&&(n+=", "),e[s]===null||e[s]===void 0)throw new TypeError("arrays cannot contain null or undefined values");n+=Xi(e[s],Cr(e[s]),t-1,r);}return n+" ]"}function Mg(e,t,r,n){if(r===0)throw new Error("Could not stringify the object: maximum object depth exceeded");let s="";for(let i=0;i<e.length;i++)s+=`${s&&`
35
35
  `}[[${t}]]
36
- `,s+=Xi(0,e[i],t,r,n);return s}function Xi(e,t,r,n,s){if(n===0)throw new Error("Could not stringify the object: maximum object depth exceeded");let i="",o="",a=Object.keys(t);for(let l=0;l<a.length;l++){let c=a[l];if(t[c]!==null&&t[c]!==void 0){let p=Cr(t[c]);if(p==="symbol"||p==="function")throw new TypeError(`cannot serialize values of type '${p}'`);let u=Tc.test(c)?c:Vi(c);if(p==="array"&&Dg(t[c]))o+=(o&&`
36
+ `,s+=Ji(0,e[i],t,r,n);return s}function Ji(e,t,r,n,s){if(n===0)throw new Error("Could not stringify the object: maximum object depth exceeded");let i="",o="",a=Object.keys(t);for(let l=0;l<a.length;l++){let c=a[l];if(t[c]!==null&&t[c]!==void 0){let p=Cr(t[c]);if(p==="symbol"||p==="function")throw new TypeError(`cannot serialize values of type '${p}'`);let u=Cc.test(c)?c:Ki(c);if(p==="array"&&Dg(t[c]))o+=(o&&`
37
37
  `)+Mg(t[c],r?`${r}.${u}`:u,n-1,s);else if(p==="object"){let f=r?`${r}.${u}`:u;o+=(o&&`
38
- `)+Xi(f,t[c],f,n-1,s);}else i+=u,i+=" = ",i+=Ki(t[c],p,n,s),i+=`
38
+ `)+Ji(f,t[c],f,n-1,s);}else i+=u,i+=" = ",i+=Xi(t[c],p,n,s),i+=`
39
39
  `;}}return e&&(i||!o)&&(i=i?`[${e}]
40
40
  ${i}`:`[${e}]`),i&&o?`${i}
41
- ${o}`:i||o}function Ji(e,{maxDepth:t=1e3,numbersAsFloat:r=false}={}){if(Cr(e)!=="object")throw new TypeError("stringify can only be called with an object");let n=Xi(0,e,"",t,r);return n[n.length-1]!==`
41
+ ${o}`:i||o}function Yi(e,{maxDepth:t=1e3,numbersAsFloat:r=false}={}){if(Cr(e)!=="object")throw new TypeError("stringify can only be called with an object");let n=Ji(0,e,"",t,r);return n[n.length-1]!==`
42
42
  `?n+`
43
- `:n}var Tc,Ac=g(()=>{Tc=/^[a-z0-9-_]+$/i;});var Rr=g(()=>{vc();Ac();Hi();At();});var ye,Zt=g(()=>{ye={config_dir:"supabase",default_api_port:54321,default_config_format:"toml",default_config_path:"config.toml",default_db_url:"file:supabase/.temp/data.db",default_db_dir:"supabase/.temp/data"};});function Vn(e,t={}){let r=Me__default.resolve(t.cwd??process.cwd()),n=t.env??process.env,s=process.env.SUPABASE_ENV||"development",i=[`.env.${s}.local`,s==="test"?null:".env.local",`.env.${s}`,".env"].filter(a=>a!==null),o=qg(Me__default.resolve(e),r);for(let a of o)for(let l of i){let c=Me__default.join(a,l),p;try{p=qn.readFileSync(c,"utf-8");}catch{continue}let u;try{u=parse(p);}catch(f){throw new Error(`Failed to parse ${c}: ${f.message}`)}for(let[f,h]of Object.entries(u))n[f]===void 0&&(n[f]=h);}}function qg(e,t){let r=[],n=e,s=Me__default.parse(n).root;for(;r.push(n),!(n===t||n===s);){let i=Me__default.dirname(n);if(i===n)break;n=i;}return r}var Yi=g(()=>{});function Kn(e,t=process.env){return Qi(e,t)}function Qi(e,t){if(typeof e=="string"){let r=e.match(Hg);return r?t[r[1]]??"":e}if(Array.isArray(e))return e.map(r=>Qi(r,t));if(e&&typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)return e;let n={};for(let[s,i]of Object.entries(e))n[s]=Qi(i,t);return n}return e}var Hg,Zi=g(()=>{Hg=/^env\((\w+)\)$/;});function Rc(e){Cc=e||process.env.LITE_VERBOSE==="1";}function Ze(...e){Cc&&console.error(...e);}var Cc,er=g(()=>{Cc=process.env.LITE_VERBOSE==="1";});async function Gg(e=""){try{let t=Me__default.resolve(Qn(),Me__default.join(e,"package.json")),r=await pe__default.readFile(t,"utf-8");if(r)return JSON.parse(r)}catch{}return {}}async function Yn(e=""){let t=await Gg(e);return t?{name:t.name,version:t.version??"unknown"}:{name:"unknown",version:"unknown"}}function Qn(){let e=Me__default.dirname(fileURLToPath(import.meta.url));return Me__default.resolve(e,process.env.LOCAL?"../../../":"../../")}function eo(){return Me__default.resolve(Qn(),"dist")}function Zn(){return Me__default.relative(process.cwd(),eo())}async function Pr(e){let t=Me__default.relative(process.cwd(),ye.config_dir);if(!e)for(let r of zg){let n=Me__default.join(t,`config.${r}`);if(await pe__default.access(n).then(()=>true).catch(()=>false)){e=n;break}}return e}async function Q(e){await Pr(e)||(console.error(Jn.default.red("No project found. Run `lite init` first.")),process.exit(1));}async function Vg(e){let t=await Pr(e);if(!t)return {};switch(Ze(Jn.default.dim(`Using config file: ${Jn.default.cyan(`./${t}`)}`)),t.split(".").pop()){case "toml":return Ct(await pe__default.readFile(t,"utf-8"));case "json":return JSON.parse(await pe__default.readFile(t,"utf-8"));case "ts":case "mts":case "js":case "mjs":case "cjs":try{return (await import(Me__default.join(process.cwd(),t))).default}catch(n){throw console.error("Failed to import config file",n),n}default:throw new Error(`Unsupported config file type: ${t}`)}}function Kg(e){if(!e||e===":memory:")return;let t=e;if(t.startsWith("file://")?t=t.slice(7):t.startsWith("file:")&&(t=t.slice(5)),!(!t||t===":memory:"))return Me__default.resolve(process.cwd(),t)}async function es(e){let t=await Pr(e);t&&Vn(Me__default.dirname(Me__default.resolve(t)));let r=Kn(await Vg(e));if("connection"in r)return;let n=r?.db?.driver;if(n==="postgres")return;let s=r?.db?.url??(n==="pglite"?ye.default_db_dir:ye.default_db_url);return Kg(s)}var Jn,zg,$e=g(()=>{Rr();Zt();Yi();Zi();Jn=te(ae());er();zg=["toml","json","ts","mts","js","mjs","cjs"];});async function ts(e={}){let t=process.cwd();if(e.recreate){console.log(ro.default.dim("Recreating database..."));try{let n=await es();n&&qn.existsSync(n)&&(qn.rmSync(n,{recursive:!0,force:!0}),console.log(ro.default.dim(` \u279C removed ${Me__default.relative(t,n)}`)));}catch{}try{qn.rmSync(Me__default.join(t,"supabase",".temp"),{recursive:!0,force:!0});}catch{}}if(ke(Me__default.join(t,"supabase")),!await Pr()){let n={api:{port:54321},db:{driver:"sqlite-postgres",url:"file:./supabase/.temp/data.db",migrations:{schema_paths:["./schemas/schema.sql"]},seed:{sql_paths:["./seed.sql"]}},auth:{enabled:true,jwt_secret:"dev-secret-change-me",jwt_expiry:3600,enable_signup:true,email:{enable_confirmations:false}}};e.driver==="pglite"&&(n.db.driver="pglite",n.db.url=Me__default.relative(process.cwd(),Me__default.join(t,"supabase",".temp","data")));let s=e.configFormat??"toml",i=Me__default.join(t,"supabase",`config.${s}`);s==="json"?vt(i,JSON.stringify(n)):vt(i,Ji(n));}ke(Me__default.join(t,"supabase",".temp")),ke(Me__default.join(t,"supabase","schemas"),()=>{vt(Me__default.join(t,"supabase","schemas","schema.sql"),e.template?Xg:`-- This is a schema file for the database
43
+ `:n}var Cc,Rc=g(()=>{Cc=/^[a-z0-9-_]+$/i;});var Rr=g(()=>{Ac();Rc();Wi();At();});var ye,Zt=g(()=>{ye={config_dir:"supabase",default_api_port:54321,default_config_format:"toml",default_config_path:"config.toml",default_db_url:"file:supabase/.temp/data.db",default_db_dir:"supabase/.temp/data"};});function Kn(e,t={}){let r=Me__default.resolve(t.cwd??process.cwd()),n=t.env??process.env,s=process.env.SUPABASE_ENV||"development",i=[`.env.${s}.local`,s==="test"?null:".env.local",`.env.${s}`,".env"].filter(a=>a!==null),o=qg(Me__default.resolve(e),r);for(let a of o)for(let l of i){let c=Me__default.join(a,l),p;try{p=Hn.readFileSync(c,"utf-8");}catch{continue}let u;try{u=parse(p);}catch(f){throw new Error(`Failed to parse ${c}: ${f.message}`)}for(let[f,h]of Object.entries(u))n[f]===void 0&&(n[f]=h);}}function qg(e,t){let r=[],n=e,s=Me__default.parse(n).root;for(;r.push(n),!(n===t||n===s);){let i=Me__default.dirname(n);if(i===n)break;n=i;}return r}var Qi=g(()=>{});function Xn(e,t=process.env){return Zi(e,t)}function Zi(e,t){if(typeof e=="string"){let r=e.match(Hg);return r?t[r[1]]??"":e}if(Array.isArray(e))return e.map(r=>Zi(r,t));if(e&&typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)return e;let n={};for(let[s,i]of Object.entries(e))n[s]=Zi(i,t);return n}return e}var Hg,eo=g(()=>{Hg=/^env\((\w+)\)$/;});function Pc(e){kc=e||process.env.LITE_VERBOSE==="1";}function Ze(...e){kc&&console.error(...e);}var kc,er=g(()=>{kc=process.env.LITE_VERBOSE==="1";});async function Gg(e=""){try{let t=Me__default.resolve(Zn(),Me__default.join(e,"package.json")),r=await pe__default.readFile(t,"utf-8");if(r)return JSON.parse(r)}catch{}return {}}async function Qn(e=""){let t=await Gg(e);return t?{name:t.name,version:t.version??"unknown"}:{name:"unknown",version:"unknown"}}function Zn(){let e=Me__default.dirname(fileURLToPath(import.meta.url));return Me__default.resolve(e,process.env.LOCAL?"../../../":"../../")}function to(){return Me__default.resolve(Zn(),"dist")}function es(){return Me__default.relative(process.cwd(),to())}async function Pr(e){let t=Me__default.relative(process.cwd(),ye.config_dir);if(!e)for(let r of zg){let n=Me__default.join(t,`config.${r}`);if(await pe__default.access(n).then(()=>true).catch(()=>false)){e=n;break}}return e}async function Q(e){await Pr(e)||(console.error(Yn.default.red("No project found. Run `lite init` first.")),process.exit(1));}async function Vg(e){let t=await Pr(e);if(!t)return {};switch(Ze(Yn.default.dim(`Using config file: ${Yn.default.cyan(`./${t}`)}`)),t.split(".").pop()){case "toml":return Ct(await pe__default.readFile(t,"utf-8"));case "json":return JSON.parse(await pe__default.readFile(t,"utf-8"));case "ts":case "mts":case "js":case "mjs":case "cjs":try{return (await import(Me__default.join(process.cwd(),t))).default}catch(n){throw console.error("Failed to import config file",n),n}default:throw new Error(`Unsupported config file type: ${t}`)}}function Kg(e){if(!e||e===":memory:")return;let t=e;if(t.startsWith("file://")?t=t.slice(7):t.startsWith("file:")&&(t=t.slice(5)),!(!t||t===":memory:"))return Me__default.resolve(process.cwd(),t)}async function ts(e){let t=await Pr(e);t&&Kn(Me__default.dirname(Me__default.resolve(t)));let r=Xn(await Vg(e));if("connection"in r)return;let n=r?.db?.driver;if(n==="postgres")return;let s=r?.db?.url??(n==="pglite"?ye.default_db_dir:ye.default_db_url);return Kg(s)}var Yn,zg,$e=g(()=>{Rr();Zt();Qi();eo();Yn=te(ae());er();zg=["toml","json","ts","mts","js","mjs","cjs"];});async function rs(e={}){let t=process.cwd();if(e.recreate){console.log(no.default.dim("Recreating database..."));try{let n=await ts();n&&Hn.existsSync(n)&&(Hn.rmSync(n,{recursive:!0,force:!0}),console.log(no.default.dim(` \u279C removed ${Me__default.relative(t,n)}`)));}catch{}try{Hn.rmSync(Me__default.join(t,"supabase",".temp"),{recursive:!0,force:!0});}catch{}}if(ke(Me__default.join(t,"supabase")),!await Pr()){let n={api:{port:54321},db:{driver:"sqlite-postgres",url:"file:./supabase/.temp/data.db",migrations:{schema_paths:["./schemas/schema.sql"]},seed:{sql_paths:["./seed.sql"]}},auth:{enabled:true,jwt_secret:"dev-secret-change-me",jwt_expiry:3600,enable_signup:true,email:{enable_confirmations:false}}};e.driver==="pglite"&&(n.db.driver="pglite",n.db.url=Me__default.relative(process.cwd(),Me__default.join(t,"supabase",".temp","data")));let s=e.configFormat??"toml",i=Me__default.join(t,"supabase",`config.${s}`);s==="json"?vt(i,JSON.stringify(n)):vt(i,Yi(n));}ke(Me__default.join(t,"supabase",".temp")),ke(Me__default.join(t,"supabase","schemas"),()=>{vt(Me__default.join(t,"supabase","schemas","schema.sql"),e.template?Xg:`-- This is a schema file for the database
44
44
  `);}),vt(Me__default.join(t,"supabase","seed.sql"),e.template?Jg:`-- This is a seed file for the database
45
- `);}var ro,Xg,Jg,no=g(()=>{Tt();ro=te(ae());Rr();$e();Xg=`
45
+ `);}var no,Xg,Jg,so=g(()=>{Tt();no=te(ae());Rr();$e();Xg=`
46
46
  create table todos (
47
47
  id serial primary key,
48
48
  title text not null,
@@ -55,11 +55,13 @@ create table todos (
55
55
  create table test (
56
56
  id serial primary key,
57
57
  name text not null
58
- )`,Jg="insert into todos (`id`, `title`, `description`, `completed`) values (1, 'test', 'test', false);\ninsert into todos (`id`, `title`, `description`, `completed`) values (2, 'test2', 'test2', true);\ninsert into test (`id`, `name`) values (1, 'test');\n";});var Pc={};de(Pc,{init:()=>Yg});var so,Yg,Oc=g(()=>{so=te(ae());no();Yg=e=>{e.command("init").description("Initialize a new project").helpGroup("Local Development:").option("--pglite","Use pglite as database",false).option("--recreate","Recreate everything",false).option("--format","Format to use","toml").action(async t=>{await ts({configFormat:t.format,recreate:t.recreate,driver:t.pglite?"pglite":void 0}),console.log(),console.log(so.default.green(" \u279C"),"Project initialized",so.default.cyan("./"+Me__default.relative(process.cwd(),Me__default.join(process.cwd(),"supabase"))));});};});var Nc=g(()=>{});var Ic=g(()=>{});function io(e,t,r=void 0){let n=typeof t=="string"?t.split(/[.[\]"]+/).filter(s=>s):t;if(n.length===0)return e;try{let[s,...i]=n;return !s||!(s in e)?r:io(e[s],i,r)}catch{if(typeof r<"u")return r;throw new Error(`Invalid path: ${n.join(".")}`)}}var Lc=g(()=>{});var Dc=g(()=>{});function rs(){try{return !Or()&&global?.process?.release?.name==="node"}catch{return false}}function Or(){try{return typeof Bun<"u"}catch{return false}}async function ns(e,t){let r=performance.now();await e();let n=performance.now();t(n-r);}var jc=g(()=>{});function Mc(e,t={}){return e.split(`
58
+ )`,Jg="insert into todos (`id`, `title`, `description`, `completed`) values (1, 'test', 'test', false);\ninsert into todos (`id`, `title`, `description`, `completed`) values (2, 'test2', 'test2', true);\ninsert into test (`id`, `name`) values (1, 'test');\n";});var Nc={};de(Nc,{init:()=>Yg});var io,Yg,Ic=g(()=>{io=te(ae());so();Yg=e=>{e.command("init").description("Initialize a new project").helpGroup("Local Development:").option("--pglite","Use pglite as database",false).option("--recreate","Recreate everything",false).option("--format","Format to use","toml").action(async t=>{await rs({configFormat:t.format,recreate:t.recreate,driver:t.pglite?"pglite":void 0}),console.log(),console.log(io.default.green(" \u279C"),"Project initialized",io.default.cyan("./"+Me__default.relative(process.cwd(),Me__default.join(process.cwd(),"supabase"))));});};});var Lc=g(()=>{});var Dc=g(()=>{});function oo(e,t,r=void 0){let n=typeof t=="string"?t.split(/[.[\]"]+/).filter(s=>s):t;if(n.length===0)return e;try{let[s,...i]=n;return !s||!(s in e)?r:oo(e[s],i,r)}catch{if(typeof r<"u")return r;throw new Error(`Invalid path: ${n.join(".")}`)}}var jc=g(()=>{});var Fc=g(()=>{});function ns(){try{return !Or()&&global?.process?.release?.name==="node"}catch{return false}}function Or(){try{return typeof Bun<"u"}catch{return false}}async function ss(e,t){let r=performance.now();await e();let n=performance.now();t(n-r);}var Mc=g(()=>{});function Bc(e,t={}){return e.split(`
59
59
  `).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>!r.startsWith(t.comments??"--")).join(`
60
- `)}function mt(e){let t=[],r="",n=0,s=e.length,i=false,o=false,a=0,l=/^create(\s+or\s+replace)?(\s+temp(orary)?)?$/i,c=u=>{Fc(u).length>0&&t.push(u.trim());},p=()=>{i=false,o=false,a=0;};for(;n<s;){let u=e[n],f=e[n+1];if(u==="-"&&f==="-"){for(;n<s&&e[n]!==`
61
- `;)r+=e[n],n++;continue}if(u==="/"&&f==="*"){for(r+="/*",n+=2;n<s&&!(e[n]==="*"&&e[n+1]==="/");)r+=e[n],n++;n<s&&(r+="*/",n+=2);continue}if(u==="'"){for(r+=u,n++;n<s;){if(e[n]==="'"&&e[n+1]==="'"){r+="''",n+=2;continue}if(r+=e[n],e[n]==="'"){n++;break}n++;}continue}if(u==='"'){for(r+=u,n++;n<s;){if(e[n]==='"'&&e[n+1]==='"'){r+='""',n+=2;continue}if(r+=e[n],e[n]==='"'){n++;break}n++;}continue}if(u==="$"){let h=e.indexOf("$",n+1);if(h!==-1){let d=e.slice(n,h+1);if(/^\$[A-Za-z_][A-Za-z0-9_]*\$$|^\$\$$/.test(d)){r+=d,n=h+1;let w=e.indexOf(d,n);w===-1?(r+=e.slice(n),n=s):(r+=e.slice(n,w+d.length),n=w+d.length);continue}}}if(/[A-Za-z_]/.test(u)){let h=n;for(;h<s&&/[A-Za-z0-9_]/.test(e[h]);)h++;let d=e.slice(n,h),m=d.toLowerCase();if(m==="trigger"&&l.test(Fc(r))?i=true:i&&m==="begin"?(o=true,a++):i&&o&&m==="case"?a++:i&&o&&m==="end"&&a>0&&a--,r+=d,n=h,i&&o&&a===0){let w=n;for(;w<s&&/\s/.test(e[w]);)w++;e[w]===";"&&(n=w+1),c(r),r="",p();}continue}if(u===";"){if(i&&o&&a>0){r+=u,n++;continue}c(r),r="",p(),n++;continue}r+=u,n++;}return c(r),t}function Fc(e){let t="",r=0,n=e.length;for(;r<n;){let s=e[r],i=e[r+1];if(s==="-"&&i==="-"){for(;r<n&&e[r]!==`
62
- `;)r++;continue}if(s==="/"&&i==="*"){for(r+=2;r<n&&!(e[r]==="*"&&e[r+1]==="/");)r++;r+=2;continue}t+=s,r++;}return t.trim()}function oo(e){return (e??"").trim().toLowerCase()}function ao(e){return (e??"").replace(/\s+/g," ").replace(/"/g,"").trim().toLowerCase()}function lo(e){if(e==null)return null;let t=e.trim();for(;t.startsWith("(")&&t.endsWith(")");)t=t.slice(1,-1).trim();return (t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"'))&&(t=t.slice(1,-1)),t}var Rt=g(()=>{});function Qg(e,t,r=void 0){let n=typeof t=="string"?Hc(t):po(t);return os(e,n,r)}function os(e,t,r=void 0){let n=typeof t=="string"?t.split(/[.\[\]\"]+/).filter(s=>s):t;if(n.length===0)return e;try{let[s,...i]=n;return !s||!(s in e)?r:os(e[s],i,r)}catch{if(typeof r<"u")return r;throw new Error(`Invalid path: ${n.join(".")}`)}}function ty(e){return e===null}function he(e){return !Array.isArray(e)&&typeof e=="object"&&e!==null}function ry(e){return Object.prototype.toString.call(e)==="[object Object]"}function Je(e){return typeof e=="string"}function et(e){return typeof e=="number"}function ny(e){return typeof e=="number"&&Number.isInteger(e)}function ho(e){return typeof e=="boolean"}function dt(e){return Array.isArray(e)}function sy(e){return typeof e!="boolean"}function iy(e){return e!==void 0&&sy(e)&&"type"in e}function Ae(e){return e!==void 0&&he(e)&&Te in e}function oy(e){return Ae(e)&&typeof e.toJSON()=="boolean"}function ay(e,t,r){if(!e)throw new ey(t,r)}function Wc(e){return Je(e)?e.normalize("NFC"):e}function Nr(e,t){let r=typeof e;if(r!==typeof t)return false;if(Array.isArray(e)){if(!Array.isArray(t))return false;let n=e.length;if(n!==t.length)return false;for(let s=0;s<n;s++)if(!Nr(e[s],t[s]))return false;return true}if(r==="object"){if(!e||!t)return e===t;let n=Object.keys(e),s=Object.keys(t);if(n.length!==s.length)return false;for(let i of n)if(!Nr(e[i],t[i]))return false;return true}return e===t}function ly(e,t){return t.reduce((r,n)=>(n in e&&(r[n]=e[n]),r),{})}function Gc(e){try{return structuredClone(e)}catch{return e}}function cy(e,t,r={}){let n=t;try{n=structuredClone(t);}catch{n=JSON.parse(JSON.stringify(t));}let s={resolver:r.resolver||new go(e),depth:r.depth||0,dropUnknown:r.dropUnknown??false};return s.resolver.hasRef(e,n)?s.resolver.resolve(e.$ref).coerce(n,{...s,depth:s.depth+1}):n}function as(e,t,r={}){return e.map(n=>n.validate(t,is(r)).valid?n:void 0).filter(Boolean)}function qy(e,t,r={}){let n={keywordPath:r.keywordPath||[],instancePath:r.instancePath||[],coerce:r.coerce||false,errors:r.errors||[],shortCircuit:r.shortCircuit||false,ignoreUnsupported:r.ignoreUnsupported||false,resolver:r.resolver||e.getResolver?.()||new go(e),depth:r.depth?r.depth+1:0,skipClone:r.skipClone||false},s;if(r?.coerce&&e.coerce){let i=e.coerce(t,{resolver:n.resolver,depth:n.depth});s=n.skipClone?i:structuredClone(i);}else s=n.skipClone?t:structuredClone(t);if(r.ignoreUnsupported!==true){let i=["$defs"];for(let o of i)if(e[o])throw new Error(`${o} not implemented`)}if(n.resolver.hasRef(e,s)){let i=n.resolver.resolve(e.$ref).validate(s,{...n,errors:[]});i.valid||n.errors.push(...i.errors);}else {let i={keywordPath:n.keywordPath,instancePath:n.instancePath,coerce:n.coerce,errors:[],shortCircuit:n.shortCircuit,ignoreUnsupported:n.ignoreUnsupported,resolver:n.resolver,depth:n.depth};for(let o in e)if(o==="type"&&e.type!==void 0){if(s!==void 0){let a=co[o];if(a){i.errors=[];let l=a(e,s,i);if(!l.valid){if(r.shortCircuit)return l;n.errors.push(...l.errors);}}}}else if(o in co&&e[o]!==void 0){if(s===void 0)continue;let a=co[o];if(a){i.errors=[];let l=a(e,s,i);if(!l.valid){if(r.shortCircuit)return l;n.errors.push(...l.errors);}}}}return {valid:n.errors.length===0,errors:n.errors}}function ls(e,t,r){return new class extends tt{type=e}(t,r)}function fo(e){return new Hy(e)}function Bc(e,t){return Array.isArray(e)?e.map(t):e!==void 0?[t(e)]:[]}function qc(e,t,r=n=>n){return Object.fromEntries(Object.entries(e).map(([n,s])=>[n,r(t(s,n),n)]))}function tr(e){if(ho(e))return fo(e);let t=structuredClone(e);if(!he(t))throw new Zg("non-object schemas cannot be converted to a schema",t);"properties"in t&&t.properties&&(t.properties=qc(t.properties,(i,o)=>{try{return tr(i)}catch(a){throw new Error(`Couldn't schemaize property "${o}": ${String(a)}`)}},(i,o)=>"required"in t&&Array.isArray(t.required)&&t.required.includes(o)?i:i.optional()));let r=["patternProperties","dependentSchemas","$defs"];for(let i of r)i in t&&t[i]&&(t[i]=qc(t[i],tr));let n=["additionalProperties","items","prefixItems","propertyNames","contains","not","if","then","else"];for(let i of n)i in t&&typeof t[i]<"u"&&(dt(t[i])?t[i]=Bc(t[i],tr):t[i]=tr(t[i]));let s=["anyOf","oneOf","allOf"];for(let i of s)if(i in t){let{[i]:o}=t;t[i]=Bc(o,tr);}if(iy(t))switch(t.type){case "string":return Vc(t);case "number":return Xc(t);case "integer":return Jc(t);case "boolean":return Qc(t);case "object":{let{properties:i,...o}=t;return cs(i,o)}case "array":{let{items:i,...o}=t;return Yc(i,o)}}return zc(t)}function rw(){return {type(e){let t=e.map(r=>Array.isArray(r)?new Set(r):new Set([r])).reduce((r,n)=>r?new Set([...r].filter(s=>n.has(s))):new Set(n));if(!t.size)throw new Error('Incompatible "type" in allOf');return t.size===1?[...t][0]:[...t]},enum(e){let t=e.map(r=>new Set(r)).reduce((r,n)=>new Set([...r].filter(s=>n.has(s))));if(!t.size)throw new Error('Incompatible "enum" in allOf');return [...t]},required(e){return [...new Set(e.flat())]},properties(e,t,r){return e.reduce((n,s)=>r(n,s),{})},patternProperties(e,t,r){return e.reduce((n,s)=>r(n,s),{})},$defs(e,t,r){return e.reduce((n,s)=>r(n,s),{})},definitions(e,t,r){return e.reduce((n,s)=>r(n,s),{})},...Object.fromEntries(ew.map(e=>[e,t=>Math.min(...t)])),...Object.fromEntries(tw.map(e=>[e,t=>Math.max(...t)]))}}function nw(e){let t={...rw(),...e.resolvers};function r(n,s){if(Array.isArray(n)&&Array.isArray(s))return [...new Set([...n,...s])];if(mo(n)&&mo(s)){let i={...n};for(let[o,a]of Object.entries(s))if(o in i){let l=t[o];i[o]=l?l([i[o],a],o,r):uo(a);}else i[o]=uo(a);return i}return uo(s)}return r}function iw(e,t={}){let r=t.deep!==false,n=nw(t);function s(i){if(Array.isArray(i))return i.map(s);if(!mo(i))return i;if(Array.isArray(i.allOf)){let a=i.allOf.map(s);if(a.some(h=>h===false))return false;let l=a.filter(h=>h!==true);if(!l.length)return true;let c=l.reduce((h,d)=>n(h,d),{}),p=sw(c);if(p!==null)return p;let u={...i};delete u.allOf;let f=n(c,r?s(u):u);return r?s(f):f}let o={};for(let[a,l]of Object.entries(i))o[a]=s(l);return o}return s(e)}var po,Hc,Z,L,rr,is,kt,Zg,ey,Te,go,uy,py,fy,my,dy,hy,gy,yy,wy,by,Sy,Ey,xy,_y,$y,vy,Ty,Ay,Cy,Ry,ky,Py,Oy,Ny,Iy,Ly,Dy,jy,Fy,My,Uy,Uc,By,co,tt,Ir,Hy,zc,Wy,Gy,cs,zy,Vy,Ky,Xy,Jy,Vc,Kc,Xc,Jc,Yy,Yc,Qc,ss,Zc,Qy,Zy,mo,uo,ew,tw,sw,ow,eu,aw,lw,cw,tu,ru=g(()=>{po=(e=[],t="")=>"/"+[t,...e.map(r=>String(r).replace(/\./g,"/"))].filter(Boolean).join("/"),Hc=e=>e.split("/").slice(1);Z=(e={},t,r,n)=>({valid:false,errors:[...e.errors??[],{keywordLocation:po([...e.keywordPath??[],t]),instanceLocation:po(e.instancePath),error:typeof r=="string"?r:`Invalid value for ${t}`,data:n}]}),L=()=>({valid:true,errors:[]}),rr=(e,t,r)=>{let n=Array.isArray(t)?t:[t],s=r?Array.isArray(r)?r:[r]:[];return {...e,keywordPath:[...e.keywordPath??[],...n],instancePath:s?[...e.instancePath??[],...s]:e.instancePath}},is=(e={})=>({...e,errors:[]}),kt=class extends Error{constructor(e){super(`Expected ${e}`);}},Zg=class extends Error{constructor(e,t){super(`${e??"Invalid raw schema"}: ${JSON.stringify(t)}`),this.schema=t;}},ey=class extends Error{constructor(e,t){super(`${e}, got: 'type "${typeof t}": ${JSON.stringify(t)}'`),this.value=t;}},Te=Symbol.for("jsonv-ts:schema");go=class{constructor(e){this.root=e,this.cache=new Map;}cache;hasRef(e,t){return t!==void 0&&"$ref"in e&&Je(e.$ref)}resolve(e){let t=this.cache.get(e);if(!t){if(t=Qg(this.root,e),!Ae(t))throw new Error(`ref not found: ${e}`);if("$ref"in t&&t.$ref===e)throw new Error(`ref loop: ${e}`);this.cache.set(e,t);}return t}};uy=({type:e},t,r={})=>{if(e===void 0||t===void 0)return L();let n,s={string:Je,number:et,integer:ny,object:he,array:dt,boolean:ho,null:ty};if(Array.isArray(e)){for(let i of e){if(!(i in s))throw new kt(`Unknown type: ${i}`);if(s[i](t))return L()}n=`Expected one of: ${e.join(", ")}`;}else {if(!(e in s))throw new kt(`Unknown type: ${e}`);s[e](t)||(n=`Expected ${e}`);}return n?Z(r,"type",n,t):L()},py=({const:e},t,r={})=>Nr(e,t)?L():Z(r,"const",`Expected const: ${e}`,t),fy=({enum:e=[]},t,r={})=>e.some(n=>Nr(n,t))?L():Z(r,"enum",`Expected enum: ${JSON.stringify(e)}`,t);my=({anyOf:e=[]},t,r={})=>as(e,t,r).length>0?L():Z(r,"anyOf","Expected at least one to match",t),dy=({oneOf:e=[]},t,r={})=>as(e,t).length===1?L():Z(r,"oneOf","Expected exactly one to match",t),hy=({allOf:e=[]},t,r={})=>as(e,t,r).length===e.length?L():Z(r,"allOf","Expected all to match",t),gy=({not:e},t,r={})=>t===void 0?L():Ae(e)&&e.validate(t,r).valid?Z(r,"not","Expected not to match",t):L(),yy=({if:e,then:t,else:r},n,s={})=>{if(e&&(t||r)){if(e.validate(n,is(s)).valid)return t?t.validate(n,is(s)):L();if(r)return r.validate(n,is(s))}return L()},wy=({pattern:e=""},t,r={})=>{if(!Je(t))return L();if(e instanceof RegExp){if(e.test(t))return L()}else if(new RegExp(e,"u").test(t))return L();return Z(r,"pattern",`Expected string matching pattern ${e}`,t)},by=({minLength:e=0},t,r={})=>Je(t)?[...Wc(t)].length>=e?L():Z(r,"minLength",`Expected string with minimum length of ${e}`,t):L(),Sy=({maxLength:e=0},t,r={})=>Je(t)?[...Wc(t)].length<=e?L():Z(r,"maxLength",`Expected string with maximum length of ${e}`,t):L(),Ey=({multipleOf:e=0},t,r={})=>{if(!et(t))return L();if(!(Number.isFinite(t)&&Number.isFinite(e))||e<=0)throw new kt("number");let n=t/e,s=Number.EPSILON*Math.max(1,Math.abs(n));return Math.abs(n-Math.round(n))<=s?L():Z(r,"multipleOf",`Expected number being a multiple of ${e}`,t)},xy=({maximum:e=0},t,r={})=>!et(t)||t<=e?L():Z(r,"maximum",`Expected number less than or equal to ${e}`,t),_y=({exclusiveMaximum:e=0},t,r={})=>!et(t)||t<e?L():Z(r,"exclusiveMaximum",`Expected number less than ${e}`,t),$y=({minimum:e=0},t,r={})=>!et(t)||t>=e?L():Z(r,"minimum",`Expected number greater than or equal to ${e}`,t),vy=({exclusiveMinimum:e=0},t,r={})=>!et(t)||t>e?L():Z(r,"exclusiveMinimum",`Expected number greater than ${e}`,t),Ty=({properties:e={}},t,r={})=>{if(!he(t))return L();for(let[n,s]of Object.entries(t)){let i=e[n];if(!Ae(i))continue;let o=i.validate(s,rr(r,["properties",n],n));if(!o.valid)return o}return L()},Ay=({properties:e={},additionalProperties:t,patternProperties:r},n,s={})=>{if(!he(n))return L();if(!Ae(t))throw new kt("additionalProperties must be a boolean or a managed schema");let i=Object.keys(e),o=he(r)?Object.keys(n).filter(l=>Object.keys(r).some(c=>new RegExp(c).test(l))):[],a=Object.keys(n).filter(l=>!i.includes(l)&&!o.includes(l));if(a.length>0){if(oy(t)){if(t.toJSON()===true)return L();let l=a.reduce((c,p)=>(c[p]=n[p],c),{});return Z(s,"additionalProperties","Additional properties are not allowed",l)}else if(Ae(t))for(let l of a){let c=t.validate(n[l],rr(s,["additionalProperties"],l));if(!c.valid)return c}}return L()},Cy=({dependentRequired:e},t,r={})=>{if(!he(t))return L();let n=Object.keys(t).filter(s=>typeof t[s]!="function");if(he(e)){for(let[s,i]of Object.entries(e))if(n.includes(s)){for(let o of i)if(!n.includes(o))return Z(r,"dependentRequired",`Expected dependent required property ${o}`,t)}}return L()},Ry=({required:e=[]},t,r={})=>{if(!he(t))return L();let n=Object.keys(t).filter(s=>typeof t[s]!="function");return e.every(s=>n.includes(s))?L():Z(r,"required",`Expected object with required properties ${e.join(", ")}`,t)},ky=({dependentSchemas:e},t,r={})=>{if(!he(t))return L();let n=Object.keys(t).filter(s=>typeof t[s]!="function");if(he(e)){for(let[s,i]of Object.entries(e))if(n.includes(s)){let o=i.validate(t,r);if(!o.valid)return o}}return L()},Py=({minProperties:e=0},t,r={})=>he(t)?Object.keys(t).length>=e?L():Z(r,"minProperties",`Expected object with at least ${e} properties`,t):L(),Oy=({maxProperties:e=0},t,r={})=>!he(t)||Object.keys(t).length<=e?L():Z(r,"maxProperties",`Expected object with at most ${e} properties`,t),Ny=({patternProperties:e={}},t,r={})=>{if(!he(t))return L();if(!he(e))throw new kt("patternProperties must be an object");for(let[n,s]of Object.entries(t))for(let[i,o]of Object.entries(e))if(new RegExp(i,"u").test(n)){let a=o.validate(s,rr(r,["patternProperties"],n));if(!a.valid)return a}return L()},Iy=({propertyNames:e},t,r={})=>{if(!he(t)||e===void 0)return L();if(!Ae(e))throw new kt("propertyNames must be a managed schema");for(let n of Object.keys(t)){let s=e.validate(n,rr(r,["propertyNames"],n));if(!s.valid)return s}return L()},Ly=({items:e,prefixItems:t=[]},r,n={})=>{if(!dt(r)||e===void 0)return L();if(!Ae(e))throw new kt("items must be a managed schema");for(let[s,i]of r.slice(t.length).entries()){let o=e.validate(i,rr(n,["items"],String(s)));if(!o.valid)return o}return L()},Dy=({minItems:e=0},t,r={})=>!dt(t)||t.length>=e?L():Z(r,"minItems",`Expected array with at least ${e} items`,t),jy=({maxItems:e=0},t,r={})=>!dt(t)||t.length<=e?L():Z(r,"maxItems",`Expected array with at most ${e} items`,t),Fy=({uniqueItems:e=false},t,r={})=>{if(!dt(t)||!e)return L();for(let n=0;n<t.length;n++){let s=t[n];for(let i=0;i<t.length;i++){if(n===i)continue;let o=t[i];if(Nr(s,o))return Z(r,"uniqueItems",`Duplicated items at index ${n} and ${i}`,t)}}return L()},My=({contains:e,minContains:t,maxContains:r},n,s={})=>{if(!Ae(e))throw new Error("contains must be a managed schema");if(!dt(n))return L();let i=n.filter(o=>e.validate(o).valid).length;return i<(t??1)?Z(s,t?"minContains":"contains",`Expected array to contain at least ${t??1}, but found ${i}`,n):r!==void 0&&i>r?Z(s,"maxContains",`Expected array to contain at most ${r}, but found ${i}`,n):L()},Uy=({prefixItems:e=[]},t,r={})=>{if(!dt(t))return L();for(let n=0;n<t.length;n++){let s=e[n]?.validate(t[n],rr(r,String(n),String(n)));if(s&&s?.valid!==true)return s}return L()},Uc={email:e=>{if(e.length>318)return false;if(/^[a-z0-9!#$%&'*+/=?^_`{|}~-]{1,20}(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]{1,21}){0,2}@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,60}[a-z0-9])?){0,3}$/i.test(e))return true;if(!e.includes("@")||/(^\.|^"|\.@|\.\.)/.test(e))return false;let[t,r,...n]=e.split("@");return !t||!r||n.length!==0||t.length>64||r.length>253||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?false:r.split(".").every(s=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(s))},hostname:e=>e.length>(e.endsWith(".")?254:253)?false:/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*\.?$/i.test(e),date:e=>{if(e.length!==10)return false;if(e[5]==="0"&&e[6]==="2"){if(/^\d\d\d\d-02-(?:[012][1-8]|[12]0|[01]9)$/.test(e))return true;let t=e.match(/^(\d\d\d\d)-02-29$/);if(!t)return false;let r=Number(t[1]);return r%16===0||r%4===0&&r%25!==0}return e.endsWith("31")?/^\d\d\d\d-(?:0[13578]|1[02])-31$/.test(e):/^\d\d\d\d-(?:0[13-9]|1[012])-(?:[012][1-9]|[123]0)$/.test(e)},time:e=>{if(e.length>27||!/^(?:2[0-3]|[0-1]\d):[0-5]\d:(?:[0-5]\d|60)(?:\.\d+)?(?:z|[+-](?:2[0-3]|[0-1]\d)(?::?[0-5]\d)?)?$/i.test(e))return false;if(!/:60/.test(e))return true;let t=e.match(/([0-9.]+|[^0-9.])/g);if(!t)return false;let r=Number(t[0])*60+Number(t[2]);return t[5]==="+"?r+=1440-Number(t[6]||0)*60-Number(t[8]||0):t[5]==="-"&&(r+=Number(t[6]||0)*60+Number(t[8]||0)),r%1440===1439},"date-time":e=>{if(e.length>38)return false;let t=/^\d\d\d\d-(?:0[1-9]|1[0-2])-(?:[0-2]\d|3[01])[t\s](?:2[0-3]|[0-1]\d):[0-5]\d:(?:[0-5]\d|60)(?:\.\d+)?(?:z|[+-](?:2[0-3]|[0-1]\d)(?::?[0-5]\d)?)$/i,r=e[5]==="0"&&e[6]==="2";if(r&&e[8]==="3"||!t.test(e))return false;if(e[17]==="6"){let n=e.slice(11).match(/([0-9.]+|[^0-9.])/g);if(!n)return false;let s=Number(n[0])*60+Number(n[2]);if(n[5]==="+"?s+=1440-Number(n[6]||0)*60-Number(n[8]||0):n[5]==="-"&&(s+=Number(n[6]||0)*60+Number(n[8]||0)),s%1440!==1439)return false}if(r){if(/^\d\d\d\d-02-(?:[012][1-8]|[12]0|[01]9)/.test(e))return true;let n=e.match(/^(\d\d\d\d)-02-29/);if(!n)return false;let s=Number(n[1]??0);return s%16===0||s%4===0&&s%25!==0}return e[8]==="3"&&e[9]==="1"?/^\d\d\d\d-(?:0[13578]|1[02])-31/.test(e):/^\d\d\d\d-(?:0[13-9]|1[012])-(?:[012][1-9]|[123]0)/.test(e)},ipv4:e=>e.length<=15&&/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)$/.test(e),ipv6:e=>{if(e.length>45||e.length<2)return false;let t=0,r=0,n=0,s=false,i=false,o=0,a=true;for(let c=0;c<e.length;c++){let p=e.charCodeAt(c);if(c===1&&o===58&&p!==58)return false;if(p>=48&&p<=57){if(++n>4)return false}else if(p===46){if(t>6||r>=3||n===0||i)return false;r++,n=0;}else if(p===58){if(r>0||t>=7)return false;if(o===58){if(s)return false;s=true;}else c===0&&(a=false);t++,n=0,i=false;}else if(p>=97&&p<=102||p>=65&&p<=70){if(r>0||++n>4)return false;i=true;}else return false;o=p;}if(t<2||r>0&&(r!==3||n===0))return false;if(s&&e.length===2)return true;if(r>0&&!/(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/.test(e))return false;let l=r>0?6:7;return s?(a||n>0)&&t<l:t===l&&a&&n>0},uri:e=>/^[a-z][a-z0-9+\-.]*:(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/?(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i.test(e),"uri-reference":e=>/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/?(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?)?(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i.test(e),"uri-template":e=>/^(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2}|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i.test(e),"json-pointer":e=>/^(?:|\/(?:[^~]|~0|~1)*)$/.test(e),"relative-json-pointer":e=>/^(?:0|[1-9][0-9]*)(?:|#|\/(?:[^~]|~0|~1)*)$/.test(e),uuid:e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),duration:e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e)),regex:e=>{if(/[^\\]\\Z/.test(e))return false;try{return new RegExp(e,"u"),!0}catch{return false}},binary:()=>true,password:()=>true},By=({format:e},t,r={})=>!Je(t)||!e?L():Uc[e]?Uc[e](t)?L():Z(r,"format",`Expected format: ${e}`,t):L(),co={type:uy,const:py,enum:fy,allOf:hy,anyOf:my,oneOf:dy,not:gy,minLength:by,maxLength:Sy,pattern:wy,format:By,minimum:$y,exclusiveMinimum:vy,maximum:xy,exclusiveMaximum:_y,multipleOf:Ey,required:Ry,dependentRequired:Cy,dependentSchemas:ky,minProperties:Py,maxProperties:Oy,propertyNames:Iy,properties:Ty,patternProperties:Ny,additionalProperties:Ay,minItems:Dy,maxItems:jy,uniqueItems:Fy,contains:My,prefixItems:Uy,items:Ly,if:yy};tt=class{"~standard";[Te];_resolver;type;$id;$ref;$schema;title;description;readOnly;writeOnly;$comment;examples;constructor(e,t){let{type:r,validate:n,coerce:s,template:i,...o}=e||{};Object.assign(this,{type:r},o),this[Te]={raw:e,optional:false,overrides:t},this["~standard"]={version:1,vendor:"jsonv-ts",validate:a=>{let l=this.validate(a);return l.valid?{value:a}:{issues:l.errors.map(c=>({message:c.error,path:Hc(c.instanceLocation)}))}}};}template(e,t){let r=this,n=e;if(r.const!==void 0?n=r.const:n===void 0&&(r.default!==void 0&&(n=r.default),t?.withExtendedOptional&&r.enum!==void 0&&(n=r.enum[0])),t?.withOptional!==true&&n===void 0&&this.isOptional())return n;if(this[Te].raw?.template){let i=this[Te].raw.template(n,t);i!==void 0&&(n=i);}let s=this[Te].overrides?.template?.(n,t);return s!==void 0&&(n=s),n}validate(e,t){let r={keywordPath:t?.keywordPath||[],instancePath:t?.instancePath||[],coerce:t?.coerce||false,errors:t?.errors||[],shortCircuit:t?.shortCircuit||false,ignoreUnsupported:t?.ignoreUnsupported||false,resolver:t?.resolver||this.getResolver(),depth:t?.depth?t.depth+1:0,skipClone:t?.skipClone??true},n=this[Te].raw?.validate;if(n!==void 0){let s=n(e,r);if(!s.valid)return s}return qy(this,e,r)}coerce(e,t){let r={...t,resolver:t?.resolver||this.getResolver(),depth:t?.depth?t.depth+1:0,dropUnknown:t?.dropUnknown??false},n=this[Te].raw?.coerce;if(n!==void 0)return n(e,r);let s=this[Te].overrides?.coerce?.(e,r)??e;return cy(this,s,r)}optional(){return this[Te].optional=true,this}isOptional(){return this[Te].optional}getResolver(){return this._resolver||(this._resolver=new go(this)),this._resolver}children(e){return []}*walk({instancePath:e=[],keywordPath:t=[],data:r,maxDepth:n=Number.POSITIVE_INFINITY,...s}={}){let i=e.length===0&&r?Gc(r):r;if(s.includeSelf!==false&&(yield new Ir(this,{instancePath:e,keywordPath:t,data:i,...s})),!(e.length>=n))for(let o of this.children(s)){let a=[...e,...o.instancePath];yield*o.schema.walk({...s,data:i,maxDepth:n,instancePath:a,keywordPath:[...t,...o.keywordPath]});}}*[Symbol.iterator](e){for(let t of this.walk(e))yield t;}toJSON(){let{toJSON:e,"~standard":t,_resolver:r,...n}=this;return JSON.parse(JSON.stringify(n))}},Ir=class{constructor(e,t={}){this.schema=e,this.instancePath=t.instancePath||[],this.keywordPath=t.keywordPath||[],this.depth=this.instancePath.length;try{if(t.data!==void 0){let r=os(t.data,this.instancePath);e.validate(r).valid&&(this.data=r);}}catch{}}instancePath;keywordPath;data;depth;appendInstancePath(e){return this.instancePath=[...this.instancePath,...e],this}appendKeywordPath(e){return this.keywordPath=[...this.keywordPath,...e],this}setData(e){return this.data=e,this}};Hy=class extends tt{constructor(e){super(),this.bool=e;}toJSON(){return this.bool}validate(e,t){return this.bool?L():Z(t,"","Always fails",e)}};zc=e=>ls(e?.type,e),Wy=(e,t)=>ls(void 0,{...t,const:e}),Gy=class extends tt{type="object";properties;required;constructor(e,t){let r=[];for(let[s,i]of Object.entries(e||{}))ay(Ae(i),"properties must be managed schemas",i),i[Te].optional||r.push(s);let n=t?.additionalProperties===false?fo(false):t?.additionalProperties;r=r.length>0?r:void 0,super({...t,additionalProperties:n,properties:e,required:r},{template:(s,i)=>{let o=structuredClone(he(s)?s:{}),a={...o};if(this.properties)for(let[l,c]of Object.entries(this.properties)){let p=os(o,l);if(c.isOptional()&&i?.withOptional!==true&&p===void 0&&s===void 0)continue;let u=c.template(p,i);u!==void 0&&(a[l]=u);}if(!(Object.keys(a).length===0&&!i?.withExtendedOptional))return a},coerce:(s,i)=>{let o=Object.keys(this.properties),a=Gc(s),l=o.length>0&&Object.values(this.properties).every(p=>!p[Te].optional);if(ry(a)&&(i?.dropUnknown===true||l)&&(a=ly(a,o)),typeof a=="string"&&a.match(/^\{/)&&(a=JSON.parse(a)),typeof a!="object"||a===null)return;if(this.properties)for(let[p,u]of Object.entries(this.properties)){let f=a[p];f!==void 0&&(a[p]=u.coerce(f,i));}let c=this.additionalProperties;if(i?.dropUnknown!==true&&(!c||c.validate(null).valid)){let p=he(s)?s:{},u=Object.keys(p).filter(f=>!o.includes(f));for(let f of u)a[f]=c?c.coerce(p[f],i):p[f];}return a}}),this.properties=e,this.required=r;}strict(){return this.additionalProperties=fo(false),this[Te].raw.additionalProperties=false,this}partial(){for(let[,e]of Object.entries(this.properties))e[Te].optional=true;return this.required=void 0,this}children(e){let t=[];for(let[r,n]of Object.entries(this.properties)){let s=new Ir(n,e);s.appendInstancePath([r]),s.appendKeywordPath(["properties",r]),t.push(s);}return t}},cs=(e,t)=>new Gy(e,t),zy=(e,t)=>cs(e,t).strict(),Vy=(e,t)=>cs(e,t).partial(),Ky=class extends tt{type="object";additionalProperties;constructor(e,t){super({...t,additionalProperties:e},{template:(r,n)=>n?.withExtendedOptional&&(r===void 0||!he(r))?{}:r}),this.additionalProperties=e;}children(e){let t=[],r=new Ir(this.additionalProperties,e);return r.appendKeywordPath(["additionalProperties"]),t.push(r),t}},Xy=(e,t)=>new Ky(e,t),Jy=class extends tt{type="string";constructor(e){super(e,{template:(t,r)=>r?.withExtendedOptional&&(t===void 0||!Je(t))?"":t,coerce:t=>et(t)?String(t):t});}toJSON(){let{pattern:e,"~standard":t,_resolver:r,...n}=this;return JSON.parse(JSON.stringify({...n,pattern:e instanceof RegExp?e.source:e}))}},Vc=e=>new Jy(e),Kc=(e,t,r)=>ls(e,r,{template:(n,s)=>s?.withExtendedOptional&&(n===void 0||!et(n))?r?.minimum??0:n,coerce:n=>{if(Je(n)){let s=t.parseFn(n);if(!Number.isNaN(s))return s}return n}}),Xc=e=>Kc("number",{parseFn:Number},e),Jc=e=>Kc("integer",{parseFn:Number.parseInt},e),Yy=class extends tt{constructor(e,t={}){super({...t,items:e},{template:r=>r===void 0||!Array.isArray(r)?[]:r,coerce:(r,n)=>{try{let s=typeof r=="string"?JSON.parse(r):r;if(!Array.isArray(s))return;if(Ae(this.items))for(let[i,o]of s.entries())s[i]=this.items.coerce(o,n);return s}catch{}return r}}),this.items=e,this.items=e;}type="array";children(e){let t=[];if(this.items){let r=new Ir(this.items,e);r.appendKeywordPath(["items"]),t.push(r);}return t}},Yc=(e,t)=>new Yy(e,t),Qc=e=>ls("boolean",e,{template:(t,r)=>r?.withExtendedOptional&&(t===void 0||!ho(t))?false:t,coerce:t=>{if(Je(t)&&["true","false","1","0"].includes(t))return t==="true"||t==="1";if(et(t)){if(t===1)return true;if(t===0)return false}return t}}),ss=Symbol.for("unionType"),Zc=class extends tt{[ss];constructor(e,t,r){super({...r,[t]:e},{coerce:(n,s)=>{let i=r?.coerce;if(i!==void 0)return i.bind(this)(n,s);let o=as(e,n,{ignoreUnsupported:true,resolver:s?.resolver,coerce:true});return o.length>0?o[0].coerce(n,s):n}}),this[ss]=t;}get schemas(){return this[this[ss]]}children(e){let t=[];for(let[r,n]of this.schemas.entries()){let s=new Ir(n,e);s.appendKeywordPath([this[ss],r]),t.push(s);}return t}},Qy=(e,t)=>new Zc(e,"anyOf",t),Zy=(e,t)=>new Zc(e,"oneOf",t);mo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),uo=e=>typeof globalThis.structuredClone=="function"?globalThis.structuredClone(e):JSON.parse(JSON.stringify(e)),ew=["maximum","exclusiveMaximum","maxLength","maxItems","maxProperties"],tw=["minimum","exclusiveMinimum","minLength","minItems","minProperties"];sw=e=>e===true||e===false?e:null;ow=(e,t)=>{let r=JSON.parse(JSON.stringify({...t,allOf:e}));return tr(iw(r))},eu=class extends tt{$ref;constructor(e,t){if(!t&&!Ae(e))throw new Error("Ref not set");if(Ae(e)&&!e.$id)throw new Error("Ref must have an $id");let r=t??e?.$id;super({$ref:r},{coerce:(n,s)=>{let i=s?.resolver?.resolve(this.$ref);if(!Ae(i))throw new Error(`Ref not found: ${this.$ref}`);return i.coerce(n,s)}}),this.$ref=r;}},aw=(e,t)=>new eu(e,t),lw=e=>new eu(void 0,e),cw=e=>e(new tt({$ref:"#",coerce:(t,r)=>{let n=r?.resolver?.resolve("#");if(!Ae(n))throw new Error("Ref not found: #");return n.coerce(t,r)}})),tu={boolean:Qc,any:zc,literal:Wy,object:cs,strictObject:zy,partialObject:Vy,record:Xy,string:Vc,number:Xc,integer:Jc,array:Yc,anyOf:Qy,oneOf:Zy,allOf:ow,ref:aw,refId:lw,recursive:cw};});function nu(e,t){if(typeof e!="string"){throw new Error("Email must be a string");}if(!tu.string({format:"email"}).validate(e).valid){throw new Error("Invalid email");}if(t?.domains?.length&&!t.domains.includes(e.split("@")[1])){throw new Error("Email domain not allowed");}return true}function su(e,{panic:t=true,length:r=8,numbers:n=0,special:s=0}={}){try{if(typeof e!="string"){if(t)throw new Error("Password must be a string");return !1}if(e.length<r){if(t)throw new Error(`Password must be at least ${r} characters long`);return !1}if((e.match(/[0-9]/g)?.length??0)<n){if(t)throw new Error(`Password must contain at least ${n} numbers`);return !1}if((e.match(/[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/g)?.length??0)<s){if(t)throw new Error(`Password must contain at least ${s} special characters`);return !1}return !0}catch(i){if(t)throw i;return false}}function U(e,t='"'){return `${t}${e}${t}`}function iu(e,t,r){if(t instanceof RegExp)return t.test(e);if(typeof t=="string")switch(!r&&t.startsWith("/")&&(r="regex"),r){case "regex":return new RegExp(t).test(e);case "sql":return new RegExp(t.replace("%",".*").replace("_",".")).test(e);case "wildcard":return new RegExp(t.replace("*",".*")).test(e);default:return e.includes(t)}return false}var Lr=g(()=>{ru();});function yo(e){return typeof e=="number"?e:Number.parseInt(String(e),10)}var ou=g(()=>{});var au=g(()=>{});var ht=g(()=>{Nc();Ic();Lc();Dc();jc();Rt();Lr();ou();au();});var wo,lu=g(()=>{wo=(e,t,r)=>(n,s)=>{let i=-1;return o(0);async function o(a){if(a<=i)throw new Error("next() called multiple times");i=a;let l,c=false,p;if(e[a]?(p=e[a][0][0],n.req.routeIndex=a):p=a===e.length&&s||void 0,p)try{l=await p(n,()=>o(a+1));}catch(u){if(u instanceof Error&&t)n.error=u,l=await t(u,n),c=true;else throw u}else n.finalized===false&&r&&(l=await r(n));return l&&(n.finalized===false||c)&&(n.res=l),n}};});var cu=g(()=>{});var uu,pu=g(()=>{uu=Symbol();});async function uw(e,t){let r=await e.formData();return r?pw(r,t):{}}function pw(e,t){let r=Object.create(null);return e.forEach((n,s)=>{t.all||s.endsWith("[]")?fw(r,s,n):r[s]=n;}),t.dot&&Object.entries(r).forEach(([n,s])=>{n.includes(".")&&(mw(r,n,s),delete r[n]);}),r}var fu,fw,mw,mu=g(()=>{bo();fu=async(e,t=Object.create(null))=>{let{all:r=false,dot:n=false}=t,i=(e instanceof us?e.raw.headers:e.headers).get("Content-Type");return i?.startsWith("multipart/form-data")||i?.startsWith("application/x-www-form-urlencoded")?uw(e,{all:r,dot:n}):{}};fw=(e,t,r)=>{e[t]!==void 0?Array.isArray(e[t])?e[t].push(r):e[t]=[e[t],r]:t.endsWith("[]")?e[t]=[r]:e[t]=r;},mw=(e,t,r)=>{let n=e,s=t.split(".");s.forEach((i,o)=>{o===s.length-1?n[i]=r:((!n[i]||typeof n[i]!="object"||Array.isArray(n[i])||n[i]instanceof File)&&(n[i]=Object.create(null)),n=n[i]);});};});var Eo,du,dw,hw,ps,hu,fs,gw,xo,gu,Pt,ms,So,yu,wu,bu,_o,nr=g(()=>{Eo=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},du=e=>{let{groups:t,path:r}=dw(e),n=Eo(r);return hw(n,t)},dw=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let s=`@${n}`;return t.push([s,r]),s}),{groups:t,path:e}},hw=(e,t)=>{for(let r=t.length-1;r>=0;r--){let[n]=t[r];for(let s=e.length-1;s>=0;s--)if(e[s].includes(n)){e[s]=e[s].replace(n,t[r][1]);break}}return e},ps={},hu=(e,t)=>{if(e==="*")return "*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${e}#${t}`;return ps[n]||(r[2]?ps[n]=t&&t[0]!==":"&&t[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)]:ps[n]=[e,r[1],true]),ps[n]}return null},fs=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return t(r)}catch{return r}})}},gw=e=>fs(e,decodeURI),xo=e=>{let t=e.url,r=t.indexOf("/",t.indexOf(":")+4),n=r;for(;n<t.length;n++){let s=t.charCodeAt(n);if(s===37){let i=t.indexOf("?",n),o=t.indexOf("#",n),a=i===-1?o===-1?void 0:o:o===-1?i:Math.min(i,o),l=t.slice(r,a);return gw(l.includes("%25")?l.replace(/%25/g,"%2525"):l)}else if(s===63||s===35)break}return t.slice(r,n)},gu=e=>{let t=xo(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},Pt=(e,t,...r)=>(r.length&&(t=Pt(t,...r)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),ms=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),r=[],n="";return t.forEach(s=>{if(s!==""&&!/\:/.test(s))n+="/"+s;else if(/\:/.test(s))if(/\?/.test(s)){r.length===0&&n===""?r.push("/"):r.push(n);let i=s.replace("?","");n+="/"+i,r.push(n);}else n+="/"+s;}),r.filter((s,i,o)=>o.indexOf(s)===i)},So=e=>/[%+]/.test(e)?(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),e.indexOf("%")!==-1?fs(e,_o):e):e,yu=(e,t,r)=>{let n;if(!r&&t&&!/[%+]/.test(t)){let o=e.indexOf("?",8);if(o===-1)return;for(e.startsWith(t,o+1)||(o=e.indexOf(`&${t}`,o+1));o!==-1;){let a=e.charCodeAt(o+t.length+1);if(a===61){let l=o+t.length+2,c=e.indexOf("&",l);return So(e.slice(l,c===-1?void 0:c))}else if(a==38||isNaN(a))return "";o=e.indexOf(`&${t}`,o+1);}if(n=/[%+]/.test(e),!n)return}let s={};n??=/[%+]/.test(e);let i=e.indexOf("?",8);for(;i!==-1;){let o=e.indexOf("&",i+1),a=e.indexOf("=",i);a>o&&o!==-1&&(a=-1);let l=e.slice(i+1,a===-1?o===-1?void 0:o:a);if(n&&(l=So(l)),i=o,l==="")continue;let c;a===-1?c="":(c=e.slice(a+1,o===-1?void 0:o),n&&(c=So(c))),r?(s[l]&&Array.isArray(s[l])||(s[l]=[]),s[l].push(c)):s[l]??=c;}return t?s[t]:s},wu=yu,bu=(e,t)=>yu(e,t,true),_o=decodeURIComponent;});var Su,us,bo=g(()=>{cu();pu();mu();nr();Su=e=>fs(e,_o),us=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(e,t="/",r=[[]]){this.raw=e,this.path=t,this.#t=r,this.#e={};}param(e){return e?this.#r(e):this.#i()}#r(e){let t=this.#t[0][this.routeIndex][1][e],r=this.#s(t);return r&&/\%/.test(r)?Su(r):r}#i(){let e={},t=Object.keys(this.#t[0][this.routeIndex][1]);for(let r of t){let n=this.#s(this.#t[0][this.routeIndex][1][r]);n!==void 0&&(e[r]=/\%/.test(n)?Su(n):n);}return e}#s(e){return this.#t[1]?this.#t[1][e]:e}query(e){return wu(this.url,e)}queries(e){return bu(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((r,n)=>{t[n]=r;}),t}async parseBody(e){return this.bodyCache.parsedBody??=await fu(this,e)}#n=e=>{let{bodyCache:t,raw:r}=this,n=t[e];if(n)return n;let s=Object.keys(t)[0];return s?t[s].then(i=>(s==="json"&&(i=JSON.stringify(i)),new Response(i)[e]())):t[e]=r[e]()};json(){return this.#n("text").then(e=>JSON.parse(e))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(e,t){this.#e[e]=t;}valid(e){return this.#e[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[uu](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,e]])=>e)}get routePath(){return this.#t[0].map(([[,e]])=>e)[this.routeIndex].path}};});var Eu,xu,$o,vo=g(()=>{Eu={Stringify:1,BeforeStream:2,Stream:3},xu=(e,t)=>{let r=new String(e);return r.isEscaped=true,r.callbacks=t,r},$o=async(e,t,r,n,s)=>{typeof e=="object"&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let i=e.callbacks;if(!i?.length)return Promise.resolve(e);s?s[0]+=e:s=[e];let o=Promise.all(i.map(a=>a({phase:t,buffer:s,context:n}))).then(a=>Promise.all(a.filter(Boolean).map(l=>$o(l,t,false,n,s))).then(()=>s[0]));return r?xu(await o,i):o};});var yw,To,Dr,_u,$u=g(()=>{bo();vo();yw="text/plain; charset=UTF-8",To=(e,t)=>({"Content-Type":e,...t}),Dr=(e,t)=>new Response(e,t),_u=class{#e;#t;env={};#r;finalized=false;error;#i;#s;#n;#u;#l;#c;#a;#p;#f;constructor(e,t){this.#e=e,t&&(this.#s=t.executionCtx,this.env=t.env,this.#c=t.notFoundHandler,this.#f=t.path,this.#p=t.matchResult);}get req(){return this.#t??=new us(this.#e,this.#f,this.#p),this.#t}get event(){if(this.#s&&"respondWith"in this.#s)return this.#s;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#s)return this.#s;throw Error("This context has no ExecutionContext")}get res(){return this.#n||=Dr(null,{headers:this.#a??=new Headers})}set res(e){if(this.#n&&e){e=Dr(e.body,e);for(let[t,r]of this.#n.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let n=this.#n.headers.getSetCookie();e.headers.delete("set-cookie");for(let s of n)e.headers.append("set-cookie",s);}else e.headers.set(t,r);}this.#n=e,this.finalized=true;}render=(...e)=>(this.#l??=t=>this.html(t),this.#l(...e));setLayout=e=>this.#u=e;getLayout=()=>this.#u;setRenderer=e=>{this.#l=e;};header=(e,t,r)=>{this.finalized&&(this.#n=Dr(this.#n.body,this.#n));let n=this.#n?this.#n.headers:this.#a??=new Headers;t===void 0?n.delete(e):r?.append?n.append(e,t):n.set(e,t);};status=e=>{this.#i=e;};set=(e,t)=>{this.#r??=new Map,this.#r.set(e,t);};get=e=>this.#r?this.#r.get(e):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#o(e,t,r){let n=this.#n?new Headers(this.#n.headers):this.#a??new Headers;if(typeof t=="object"&&"headers"in t){let i=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[o,a]of i)o.toLowerCase()==="set-cookie"?n.append(o,a):n.set(o,a);}if(r)for(let[i,o]of Object.entries(r))if(typeof o=="string")n.set(i,o);else {n.delete(i);for(let a of o)n.append(i,a);}let s=typeof t=="number"?t:t?.status??this.#i;return Dr(e,{status:s,headers:n})}newResponse=(...e)=>this.#o(...e);body=(e,t,r)=>this.#o(e,t,r);text=(e,t,r)=>!this.#a&&!this.#i&&!t&&!r&&!this.finalized?new Response(e):this.#o(e,t,To(yw,r));json=(e,t,r)=>this.#o(JSON.stringify(e),t,To("application/json",r));html=(e,t,r)=>{let n=s=>this.#o(s,t,To("text/html; charset=UTF-8",r));return typeof e=="object"?$o(e,Eu.Stringify,false,{}).then(n):n(e)};redirect=(e,t)=>{let r=String(e);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,t??302)};notFound=()=>(this.#c??=()=>Dr(),this.#c(this))};});var re,vu,Tu,ds,hs,gt=g(()=>{re="ALL",vu="all",Tu=["get","post","put","delete","options","patch"],ds="Can not add a route since the matcher is already built.",hs=class extends Error{};});var jr,Ao=g(()=>{jr="__COMPOSED_HANDLER";});var ww,Au,Cu,ku=g(()=>{lu();$u();gt();Ao();nr();ww=e=>e.text("404 Not Found",404),Au=(e,t)=>{if("getResponse"in e){let r=e.getResponse();return t.newResponse(r.body,r)}return console.error(e),t.text("Internal Server Error",500)},Cu=class Ru{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(t={}){[...Tu,vu].forEach(i=>{this[i]=(o,...a)=>(typeof o=="string"?this.#e=o:this.#i(i,this.#e,o),a.forEach(l=>{this.#i(i,this.#e,l);}),this);}),this.on=(i,o,...a)=>{for(let l of [o].flat()){this.#e=l;for(let c of [i].flat())a.map(p=>{this.#i(c.toUpperCase(),this.#e,p);});}return this},this.use=(i,...o)=>(typeof i=="string"?this.#e=i:(this.#e="*",o.unshift(i)),o.forEach(a=>{this.#i(re,this.#e,a);}),this);let{strict:n,...s}=t;Object.assign(this,s),this.getPath=n??true?t.getPath??xo:gu;}#t(){let t=new Ru({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=ww;errorHandler=Au;route(t,r){let n=this.basePath(t);return r.routes.map(s=>{let i;r.errorHandler===Au?i=s.handler:(i=async(o,a)=>(await wo([],r.errorHandler)(o,()=>s.handler(o,a))).res,i[jr]=s.handler),n.#i(s.method,s.path,i);}),this}basePath(t){let r=this.#t();return r._basePath=Pt(this._basePath,t),r}onError=t=>(this.errorHandler=t,this);notFound=t=>(this.#r=t,this);mount(t,r,n){let s,i;n&&(typeof n=="function"?i=n:(i=n.optionHandler,n.replaceRequest===false?s=l=>l:s=n.replaceRequest));let o=i?l=>{let c=i(l);return Array.isArray(c)?c:[c]}:l=>{let c;try{c=l.executionCtx;}catch{}return [l.env,c]};s||=(()=>{let l=Pt(this._basePath,t),c=l==="/"?0:l.length;return p=>{let u=new URL(p.url);return u.pathname=u.pathname.slice(c)||"/",new Request(u,p)}})();let a=async(l,c)=>{let p=await r(s(l.req.raw),...o(l));if(p)return p;await c();};return this.#i(re,Pt(t,"*"),a),this}#i(t,r,n){t=t.toUpperCase(),r=Pt(this._basePath,r);let s={basePath:this._basePath,path:r,method:t,handler:n};this.router.add(t,r,[n,s]),this.routes.push(s);}#s(t,r){if(t instanceof Error)return this.errorHandler(t,r);throw t}#n(t,r,n,s){if(s==="HEAD")return (async()=>new Response(null,await this.#n(t,r,n,"GET")))();let i=this.getPath(t,{env:n}),o=this.router.match(s,i),a=new _u(t,{path:i,matchResult:o,env:n,executionCtx:r,notFoundHandler:this.#r});if(o[0].length===1){let c;try{c=o[0][0][0][0](a,async()=>{a.res=await this.#r(a);});}catch(p){return this.#s(p,a)}return c instanceof Promise?c.then(p=>p||(a.finalized?a.res:this.#r(a))).catch(p=>this.#s(p,a)):c??this.#r(a)}let l=wo(o[0],this.errorHandler,this.#r);return (async()=>{try{let c=await l(a);if(!c.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return c.res}catch(c){return this.#s(c,a)}})()}fetch=(t,...r)=>this.#n(t,r[1],r[0],t.method);request=(t,r,n,s)=>t instanceof Request?this.fetch(r?new Request(t,r):t,n,s):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${Pt("/",t)}`,r),n,s));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method));});}};});function Co(e,t){let r=this.buildAllMatchers(),n=((s,i)=>{let o=r[s]||r[re],a=o[2][i];if(a)return a;let l=i.match(o[0]);if(!l)return [[],gs];let c=l.indexOf("",1);return [o[1][c],l]});return this.match=n,n(e,t)}var gs,Ro=g(()=>{gt();gs=[];});function Sw(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===Fr||e===Mr?1:t===Fr||t===Mr?-1:e===ys?1:t===ys?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var ys,Fr,Mr,Ot,bw,Pu,Po=g(()=>{ys="[^/]+",Fr=".*",Mr="(?:|/.*)",Ot=Symbol(),bw=new Set(".\\+*[^]$()");Pu=class ko{#e;#t;#r=Object.create(null);insert(t,r,n,s,i){if(t.length===0){if(this.#e!==void 0)throw Ot;if(i)return;this.#e=r;return}let[o,...a]=t,l=o==="*"?a.length===0?["","",Fr]:["","",ys]:o==="/*"?["","",Mr]:o.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(l){let p=l[1],u=l[2]||ys;if(p&&l[2]&&(u===".*"||(u=u.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(u))))throw Ot;if(c=this.#r[u],!c){if(Object.keys(this.#r).some(f=>f!==Fr&&f!==Mr))throw Ot;if(i)return;c=this.#r[u]=new ko,p!==""&&(c.#t=s.varIndex++);}!i&&p!==""&&n.push([p,c.#t]);}else if(c=this.#r[o],!c){if(Object.keys(this.#r).some(p=>p.length>1&&p!==Fr&&p!==Mr))throw Ot;if(i)return;c=this.#r[o]=new ko;}c.insert(a,r,n,s,i);}buildRegExpStr(){let r=Object.keys(this.#r).sort(Sw).map(n=>{let s=this.#r[n];return (typeof s.#t=="number"?`(${n})@${s.#t}`:bw.has(n)?`\\${n}`:n)+s.buildRegExpStr()});return typeof this.#e=="number"&&r.unshift(`#${this.#e}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};});var Ou,Nu=g(()=>{Po();Ou=class{#e={varIndex:0};#t=new Pu;insert(e,t,r){let n=[],s=[];for(let o=0;;){let a=false;if(e=e.replace(/\{[^}]+\}/g,l=>{let c=`@\\${o}`;return s[o]=[c,l],o++,a=true,c}),!a)break}let i=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let o=s.length-1;o>=0;o--){let[a]=s[o];for(let l=i.length-1;l>=0;l--)if(i[l].indexOf(a)!==-1){i[l]=i[l].replace(a,s[o][1]);break}}return this.#t.insert(i,t,n,this.#e,r),n}buildRegExp(){let e=this.#t.buildRegExpStr();if(e==="")return [/^$/,[],[]];let t=0,r=[],n=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(s,i,o)=>i!==void 0?(r[++t]=Number(i),"$()"):(o!==void 0&&(n[Number(o)]=++t),"")),[new RegExp(`^${e}`),r,n]}};});function Lu(e){return Iu[e]??=new RegExp(e==="*"?"":`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(t,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function xw(){Iu=Object.create(null);}function _w(e){let t=new Ou,r=[];if(e.length===0)return Ew;let n=e.map(c=>[!/\*|\/:/.test(c[0]),...c]).sort(([c,p],[u,f])=>c?1:u?-1:p.length-f.length),s=Object.create(null);for(let c=0,p=-1,u=n.length;c<u;c++){let[f,h,d]=n[c];f?s[h]=[d.map(([w])=>[w,Object.create(null)]),gs]:p++;let m;try{m=t.insert(h,p,f);}catch(w){throw w===Ot?new hs(h):w}f||(r[p]=d.map(([w,y])=>{let E=Object.create(null);for(y-=1;y>=0;y--){let[T,v]=m[y];E[T]=v;}return [w,E]}));}let[i,o,a]=t.buildRegExp();for(let c=0,p=r.length;c<p;c++)for(let u=0,f=r[c].length;u<f;u++){let h=r[c][u]?.[1];if(!h)continue;let d=Object.keys(h);for(let m=0,w=d.length;m<w;m++)h[d[m]]=a[h[d[m]]];}let l=[];for(let c in o)l[c]=r[o[c]];return [i,l,s]}function sr(e,t){if(e){for(let r of Object.keys(e).sort((n,s)=>s.length-n.length))if(Lu(r).test(t))return [...e[r]]}}var Ew,Iu,ws,Oo=g(()=>{gt();nr();Ro();Po();Nu();Ew=[/^$/,[],Object.create(null)],Iu=Object.create(null);ws=class{name="RegExpRouter";#e;#t;constructor(){this.#e={[re]:Object.create(null)},this.#t={[re]:Object.create(null)};}add(e,t,r){let n=this.#e,s=this.#t;if(!n||!s)throw new Error(ds);n[e]||[n,s].forEach(a=>{a[e]=Object.create(null),Object.keys(a[re]).forEach(l=>{a[e][l]=[...a[re][l]];});}),t==="/*"&&(t="*");let i=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let a=Lu(t);e===re?Object.keys(n).forEach(l=>{n[l][t]||=sr(n[l],t)||sr(n[re],t)||[];}):n[e][t]||=sr(n[e],t)||sr(n[re],t)||[],Object.keys(n).forEach(l=>{(e===re||e===l)&&Object.keys(n[l]).forEach(c=>{a.test(c)&&n[l][c].push([r,i]);});}),Object.keys(s).forEach(l=>{(e===re||e===l)&&Object.keys(s[l]).forEach(c=>a.test(c)&&s[l][c].push([r,i]));});return}let o=ms(t)||[t];for(let a=0,l=o.length;a<l;a++){let c=o[a];Object.keys(s).forEach(p=>{(e===re||e===p)&&(s[p][c]||=[...sr(n[p],c)||sr(n[re],c)||[]],s[p][c].push([r,i-l+a+1]));});}}match=Co;buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#t).concat(Object.keys(this.#e)).forEach(t=>{e[t]||=this.#r(t);}),this.#e=this.#t=void 0,xw(),e}#r(e){let t=[],r=e===re;return [this.#e,this.#t].forEach(n=>{let s=n[e]?Object.keys(n[e]).map(i=>[i,n[e][i]]):[];s.length!==0?(r||=true,t.push(...s)):e!==re&&t.push(...Object.keys(n[re]).map(i=>[i,n[re][i]]));}),r?_w(t):null}};});var Du=g(()=>{gt();Ro();Oo();});var ju=g(()=>{Oo();Du();});var No,Fu=g(()=>{gt();No=class{name="SmartRouter";#e=[];#t=[];constructor(e){this.#e=e.routers;}add(e,t,r){if(!this.#t)throw new Error(ds);this.#t.push([e,t,r]);}match(e,t){if(!this.#t)throw new Error("Fatal error");let r=this.#e,n=this.#t,s=r.length,i=0,o;for(;i<s;i++){let a=r[i];try{for(let l=0,c=n.length;l<c;l++)a.add(...n[l]);o=a.match(e,t);}catch(l){if(l instanceof hs)continue;throw l}this.match=a.match.bind(a),this.#e=[a],this.#t=void 0;break}if(i===s)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#t||this.#e.length!==1)throw new Error("No active router has been determined yet.");return this.#e[0]}};});var Mu=g(()=>{Fu();});var Ur,$w,Uu,qu=g(()=>{gt();nr();Ur=Object.create(null),$w=e=>{for(let t in e)return true;return false},Uu=class Bu{#e;#t;#r;#i=0;#s=Ur;constructor(t,r,n){if(this.#t=n||Object.create(null),this.#e=[],t&&r){let s=Object.create(null);s[t]={handler:r,possibleKeys:[],score:0},this.#e=[s];}this.#r=[];}insert(t,r,n){this.#i=++this.#i;let s=this,i=du(r),o=[];for(let a=0,l=i.length;a<l;a++){let c=i[a],p=i[a+1],u=hu(c,p),f=Array.isArray(u)?u[0]:c;if(f in s.#t){s=s.#t[f],u&&o.push(u[1]);continue}s.#t[f]=new Bu,u&&(s.#r.push(u),o.push(u[1])),s=s.#t[f];}return s.#e.push({[t]:{handler:n,possibleKeys:o.filter((a,l,c)=>c.indexOf(a)===l),score:this.#i}}),s}#n(t,r,n,s,i){for(let o=0,a=r.#e.length;o<a;o++){let l=r.#e[o],c=l[n]||l[re],p={};if(c!==void 0&&(c.params=Object.create(null),t.push(c),s!==Ur||i&&i!==Ur))for(let u=0,f=c.possibleKeys.length;u<f;u++){let h=c.possibleKeys[u],d=p[c.score];c.params[h]=i?.[h]&&!d?i[h]:s[h]??i?.[h],p[c.score]=true;}}}search(t,r){let n=[];this.#s=Ur;let i=[this],o=Eo(r),a=[],l=o.length,c=null;for(let p=0;p<l;p++){let u=o[p],f=p===l-1,h=[];for(let m=0,w=i.length;m<w;m++){let y=i[m],E=y.#t[u];E&&(E.#s=y.#s,f?(E.#t["*"]&&this.#n(n,E.#t["*"],t,y.#s),this.#n(n,E,t,y.#s)):h.push(E));for(let T=0,v=y.#r.length;T<v;T++){let C=y.#r[T],A=y.#s===Ur?{}:{...y.#s};if(C==="*"){let D=y.#t["*"];D&&(this.#n(n,D,t,y.#s),D.#s=A,h.push(D));continue}let[$,_,I]=C;if(!u&&!(I instanceof RegExp))continue;let b=y.#t[$];if(I instanceof RegExp){if(c===null){c=new Array(l);let F=r[0]==="/"?1:0;for(let S=0;S<l;S++)c[S]=F,F+=o[S].length+1;}let D=r.substring(c[p]),O=I.exec(D);if(O){if(A[_]=O[0],this.#n(n,b,t,y.#s,A),$w(b.#t)){b.#s=A;let F=O[0].match(/\//)?.length??0;(a[F]||=[]).push(b);}continue}}(I===true||I.test(u))&&(A[_]=u,f?(this.#n(n,b,t,A,y.#s),b.#t["*"]&&this.#n(n,b.#t["*"],t,A,y.#s)):(b.#s=A,h.push(b)));}}let d=a.shift();i=d?h.concat(d):h;}return n.length>1&&n.sort((p,u)=>p.score-u.score),[n.map(({handler:p,params:u})=>[p,u])]}};});var Io,Hu=g(()=>{nr();qu();Io=class{name="TrieRouter";#e;constructor(){this.#e=new Uu;}add(e,t,r){let n=ms(t);if(n){for(let s=0,i=n.length;s<i;s++)this.#e.insert(e,n[s],r);return}this.#e.insert(e,t,r);}match(e,t){return this.#e.search(e,t)}};});var Wu=g(()=>{Hu();});var Lo,Gu=g(()=>{ku();ju();Mu();Wu();Lo=class extends Cu{constructor(e={}){super(e),this.router=e.router??new No({routers:[new ws,new Io]});}};});var zu=g(()=>{Gu();});function Do(e){return !e||typeof e!="object"?false:e.code==="EADDRINUSE"}function Vu(e,t){return new Promise((r,n)=>{let s=o=>{e.off("listening",i),n(o);},i=()=>{e.off("error",s),r();};e.once("error",s),e.once("listening",i),e.listen(t);})}function jo(e){console.error(),console.error(Br.default.red(`Cannot start server: Port ${Br.default.bold(String(e))} is already in use.`)),console.error(Br.default.red(`Stop the process using that port, or set a different ${Br.default.bold("api.port")} in your config.`)),console.error(),process.exit(1);}var Br,Ku=g(()=>{Br=te(ae());});var Xu,Ju=g(()=>{Xu=/^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;});var Mo,Yu,vw,Fo,Uo=g(()=>{Mo=(e,t=Fo)=>{let r=/\.([a-zA-Z0-9]+?)$/,n=e.match(r);if(!n)return;let s=t[n[1]];return s&&s.startsWith("text")&&(s+="; charset=utf-8"),s},Yu=e=>{for(let t in Fo)if(Fo[t]===e)return t},vw={aac:"audio/aac",avi:"video/x-msvideo",avif:"image/avif",av1:"video/av1",bin:"application/octet-stream",bmp:"image/bmp",css:"text/css",csv:"text/csv",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gif:"image/gif",gz:"application/gzip",htm:"text/html",html:"text/html",ico:"image/x-icon",ics:"text/calendar",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript",json:"application/json",jsonld:"application/ld+json",map:"application/json",mid:"audio/x-midi",midi:"audio/x-midi",mjs:"text/javascript",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",pdf:"application/pdf",png:"image/png",rtf:"application/rtf",svg:"image/svg+xml",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain",wasm:"application/wasm",webm:"video/webm",weba:"audio/webm",webmanifest:"application/manifest+json",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xml:"application/xml",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2",gltf:"model/gltf+json",glb:"model/gltf-binary"},Fo=vw;});var Qu,Zu=g(()=>{Qu=(...e)=>{let t=e.filter(s=>s!=="").join("/");t=t.replace(/(?<=\/)\/+/g,"");let r=t.split("/"),n=[];for(let s of r)s===".."&&n.length>0&&n.at(-1)!==".."?n.pop():s!=="."&&n.push(s);return n.join("/")||"."};});var ep,Tw,Aw,tp,rp=g(()=>{Ju();Uo();Zu();ep={br:".br",zstd:".zst",gzip:".gz"},Tw=Object.keys(ep),Aw="index.html",tp=e=>{let t=e.root??"./",r=e.path,n=e.join??Qu;return async(s,i)=>{if(s.finalized)return i();let o;if(e.path)o=e.path;else try{if(o=decodeURIComponent(s.req.path),/(?:^|[\/\\])\.\.(?:$|[\/\\])/.test(o))throw new Error}catch{return await e.onNotFound?.(s.req.path,s),i()}let a=n(t,!r&&e.rewriteRequestPath?e.rewriteRequestPath(o):o);e.isDir&&await e.isDir(a)&&(a=n(a,Aw));let l=e.getContent,c=await l(a,s);if(c instanceof Response)return s.newResponse(c.body,c);if(c){let p=e.mimes&&Mo(a,e.mimes)||Mo(a);if(s.header("Content-Type",p||"application/octet-stream"),e.precompressed&&(!p||Xu.test(p))){let u=new Set(s.req.header("Accept-Encoding")?.split(",").map(f=>f.trim()));for(let f of Tw){if(!u.has(f))continue;let h=await l(a+ep[f],s);if(h){c=h,s.header("Content-Encoding",f),s.header("Vary","Accept-Encoding",{append:true});break}}}return await e.onFound?.(a,s),s.body(c)}await e.onNotFound?.(a,s),await i();}};});var np,sp=g(()=>{rp();np=e=>async function(r,n){return tp({...e,getContent:async o=>{let a=Bun.file(o);return await a.exists()?a:null},join:join,isDir:async o=>{let a;try{a=(await stat$1(o)).isDirectory();}catch{}return a}})(r,n)};});var ip=g(()=>{});var op,ap=g(()=>{ip();op=(e,t)=>{for(let[r,n]of Object.entries(t)){let s=new RegExp("/:"+r+"(?:{[^/]+})?\\??");e=e.replace(s,n?`/${n}`:"");}return e};});var kw,lp,cp=g(()=>{kw=1024,lp=({concurrency:e,interval:t}={})=>{if(e||=kw,e===1/0)return {run:async s=>s()};let r=new Set,n=async(s,i,o)=>{if(r.size>=e)return i||=new Promise(c=>o=c),setTimeout(()=>n(s,i,o)),i;let a={};r.add(a);let l=await s();return t?setTimeout(()=>r.delete(a),t):r.delete(a),o?(o(l),i):l};return {run:n}};});var up,Bo,pp=g(()=>{Ao();up=e=>e.length>1,Bo=e=>e[jr]?Bo(e[jr]):e;});var fp,Pw,Ow,Nw,Iw,qr,mp,qo,Ho=g(()=>{gt();pp();fp=e=>e.split(/[\/\\]/).slice(0,-1).join("/"),Pw=e=>e.replace(/(\\)/g,"/").replace(/\/$/g,""),Ow=(e,t)=>{e.length===0||t?e.push(".."):e.pop();},Nw=(e,t)=>{e=e.replace(/^\.(?!.)/,""),e!==""&&t.push(e);},Iw=(e,t)=>{let r=false;for(let n of e)n===".."?(Ow(t,r),r=true):(Nw(n,t),r=false);},qr=(...e)=>{e=e.map(Pw);let t=[];return Iw(e.join("/").split("/"),t),(e[0][0]==="/"?"/":"")+t.join("/")},mp=e=>e.routes.reduce((t,{method:r,handler:n,path:s})=>{let i=Bo(n);return ["GET",re].includes(r)&&!up(i)&&t.push({path:s}),t},[]),qo=e=>e.split("/").some(t=>t.startsWith(":")||t.includes("*"));});var dp,bs,Wo=g(()=>{Ho();dp="HONO_SSG_CONTEXT",bs="x-hono-disable-ssg",(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[bs]:"true"}})}catch{return null}})();});var hp=g(()=>{vo();});var Go,zo=g(()=>{hp();Go=()=>({afterResponseHook:e=>e.status!==200?false:e});});var Lw,Dw,jw,Fw,Mw,Uw,Bw,qw,Hw,Ww,Gw,gp,zw,yp,wp=g(()=>{ap();cp();Uo();Wo();zo();Ho();Lw=2,Dw="text/plain",jw="./static",Fw=(e,t,r,n)=>{let s=Bw(r,n);return e.endsWith(`.${s}`)?qr(t,e):e==="/"?qr(t,`index.${s}`):e.endsWith("/")?qr(t,e,`index.${s}`):qr(t,`${e}.${s}`)},Mw=async e=>{let t=e.headers.get("Content-Type");try{return t?.includes("text")||t?.includes("json")?await e.text():await e.arrayBuffer()}catch(r){throw new Error(`Error processing response: ${r instanceof Error?r.message:"Unknown error"}`)}},Uw={"text/html":"html","text/xml":"xml","application/xml":"xml","application/yaml":"yaml"},Bw=(e,t)=>{let r=t||Uw;return e in r?r[e]:Yu(e)||"html"},qw=e=>Array.isArray(e)?async t=>{let r=t;for(let n of e){let s=await n(r);if(s===false)return false;s instanceof Request&&(r=s);}return r}:e,Hw=e=>Array.isArray(e)?async t=>{let r=t;for(let n of e){let s=await n(r);if(s===false)return false;s instanceof Response&&(r=s);}return r}:e,Ww=(e,t,r)=>Array.isArray(e)?async n=>{for(let s of e)await s(n,t,r);}:e,Gw=function*(e,t,r,n){let s="http://localhost",i=lp({concurrency:n});for(let o of mp(e)){let a=new URL(o.path,s).toString(),l=new Request(a);yield new Promise(async(c,p)=>{try{if(t){let f=await t(l);if(!f){c(void 0);return}l=f;}if(await i.run(()=>e.fetch(l)),!l.ssgParams){if(qo(o.path)){c(void 0);return}l.ssgParams=[{}];}let u={method:l.method,headers:l.headers};c((function*(){for(let f of l.ssgParams)yield new Promise(async(h,d)=>{try{let m=op(o.path,f),w=await i.run(()=>e.request(m,u,{[dp]:!0}));if(w.headers.get(bs)){h(void 0);return}if(r){let T=await r(w);if(!T){h(void 0);return}w=T;}let y=w.headers.get("Content-Type")?.split(";")[0]||Dw,E=await Mw(w);h({routePath:m,mimeType:y,content:E});}catch(m){d(m);}});})());}catch(u){p(u);}});}},gp=new Set,zw=async(e,t,r,n)=>{let s=await e;if(!s)return;let{routePath:i,content:o,mimeType:a}=s,l=Fw(i,r,a,n),c=fp(l);return gp.has(c)||(await t.mkdir(c,{recursive:true}),gp.add(c)),typeof o=="string"?await t.writeFile(l,o):o instanceof ArrayBuffer&&await t.writeFile(l,new Uint8Array(o)),l},yp=async(e,t,r)=>{let n,s=[],i=[],o=r?.plugins||[Go()],a=[],l=[],c=[];r?.beforeRequestHook&&a.push(...Array.isArray(r.beforeRequestHook)?r.beforeRequestHook:[r.beforeRequestHook]),r?.afterResponseHook&&l.push(...Array.isArray(r.afterResponseHook)?r.afterResponseHook:[r.afterResponseHook]),r?.afterGenerateHook&&c.push(...Array.isArray(r.afterGenerateHook)?r.afterGenerateHook:[r.afterGenerateHook]);for(let p of o)p.beforeRequestHook&&a.push(...Array.isArray(p.beforeRequestHook)?p.beforeRequestHook:[p.beforeRequestHook]),p.afterResponseHook&&l.push(...Array.isArray(p.afterResponseHook)?p.afterResponseHook:[p.afterResponseHook]),p.afterGenerateHook&&c.push(...Array.isArray(p.afterGenerateHook)?p.afterGenerateHook:[p.afterGenerateHook]);try{let p=r?.dir??jw,u=r?.concurrency??Lw,f=qw(a.length>0?a:[w=>w]),h=Hw(l.length>0?l:[w=>w]),d=Gw(e,f,h,u);for(let w of d)s.push(w.then(y=>{if(y)for(let E of y)i.push(zw(E,t,p,r?.extensionMap).catch(T=>T));}));await Promise.all(s);let m=[];for(let w of i){let y=await w;if(typeof y=="string")m.push(y);else if(y)throw y}n={success:!0,files:m};}catch(p){let u=p instanceof Error?p:new Error(String(p));n={success:false,files:[],error:u};}return c.length>0&&await Ww(c,t,r)(n,t,r),n};});var bp=g(()=>{wp();Wo();zo();});var Vw,Vo,Sp,Ep=g(()=>{bp();(({write:Vw}=Bun)),Vo={writeFile:async(e,t)=>{await Vw(e,t);},mkdir:async()=>{}},Sp=async(e,t)=>yp(e,Vo,t);});var xp,_p,$p,vp=g(()=>{xp=class{#e;constructor(e){this.#e=e,this.raw=e.raw,this.url=e.url?new URL(e.url):null,this.protocol=e.protocol??null;}send(e,t){this.#e.send(e,t??{});}raw;binaryType="arraybuffer";get readyState(){return this.#e.readyState}url;protocol;close(e,t){this.#e.close(e,t);}},_p=e=>new MessageEvent("message",{data:e}),$p=e=>((...t)=>{if(typeof t[0]=="function"){let[r,n]=t;return async function(i,o){let a=await r(i),l=await e(i,a,n);if(l)return l;await o();}}else {let[r,n,s]=t;return (async()=>{let i=await e(r,n,s);if(!i)throw new Error("Failed to upgrade WebSocket");return i})()}});});var ir,Ss=g(()=>{ir=e=>"server"in e.env?e.env.server:e.env;});var Ko,Xo,Jo,Tp,Ap=g(()=>{vp();Ss();Ko=e=>new xp({send:(t,r)=>{e.send(t,r?.compress);},raw:e,readyState:e.readyState,url:e.data.url,protocol:e.data.protocol,close(t,r){e.close(t,r);}}),Xo=$p((e,t)=>{let r=ir(e);if(!r)throw new TypeError("env has to include the 2nd argument of fetch.");if(r.upgrade(e.req.raw,{data:{events:t,url:new URL(e.req.url),protocol:e.req.url}}))return new Response(null)}),Jo={open(e){let t=e.data.events;t.onOpen&&t.onOpen(new Event("open"),Ko(e));},close(e,t,r){let n=e.data.events;n.onClose&&n.onClose(new CloseEvent("close",{code:t,reason:r}),Ko(e));},message(e,t){let r=e.data.events;if(r.onMessage){let n=typeof t=="string"?t:t.buffer;r.onMessage(_p(n),Ko(e));}}},Tp=()=>({upgradeWebSocket:Xo,websocket:Jo});});var Cp,Rp=g(()=>{Ss();Cp=e=>{let t=ir(e);if(!t)throw new TypeError("env has to include the 2nd argument of fetch.");if(typeof t.requestIP!="function")throw new TypeError("server.requestIP is not a function.");let r=t.requestIP(e.req.raw);return r?{remote:{address:r.address,addressType:r.family==="IPv6"||r.family==="IPv4"?r.family:void 0,port:r.port}}:{remote:{}}};});var kp={};de(kp,{bunFileSystemModule:()=>Vo,createBunWebSocket:()=>Tp,getBunServer:()=>ir,getConnInfo:()=>Cp,serveStatic:()=>np,toSSG:()=>Sp,upgradeWebSocket:()=>Xo,websocket:()=>Jo});var Pp=g(()=>{sp();Ep();Ap();Rp();Ss();});async function Es(e,t={port:3e3}){let r=Zn(),n=t.port??3e3;if(Or()){let s=await Promise.resolve().then(()=>(Pp(),kp)).then(o=>o.serveStatic),i;try{i=Bun.serve({fetch:Np(e,r,s).fetch,port:n});}catch(o){throw Do(o)&&jo(n),o}return async()=>{await i.stop();}}else {let{createAdaptorServer:s}=await import('@hono/node-server'),i=await import('@hono/node-server/serve-static').then(a=>a.serveStatic),o=s({fetch:Np(e,r,i).fetch});try{await Vu(o,n);}catch(a){throw Do(a)&&jo(n),a}return ()=>new Promise(a=>{o.close(()=>{a(void 0);});})}}function Np(e,t,r){return new Lo().use("/favicon.ico",r({path:Me__default.join(t,"static","favicon.ico")})).use("/fonts/*",r({root:Me__default.join(t,"static"),onNotFound:n=>{console.log("fonts not found",n,process.cwd());}})).use("/static/*",r({root:t,onNotFound(n){console.log("not found",n,process.cwd());}})).all("*",async n=>e.fetch(n.req.raw))}var Yo=g(()=>{ht();zu();Ku();$e();});var nt,Qo=g(()=>{Tt();nt=class e{root;constructor(t,r){let n=r??e.projectDir();this.root=Me__default.join(n,t??"");}ensureRoot(){ke(this.root);}static homeDir(){return Me__default.join(Kw.homedir(),".lite")}static projectDir(){return Me__default.join(process.cwd(),"supabase")}deleteAll(t=false){try{qn.rmSync(this.root,{recursive:!0});}catch(r){if(!t)throw r}this.ensureRoot();}delete(t,r=false){try{qn.unlinkSync(Me__default.join(this.root,t));}catch(n){if(!r)throw n}}write(t,r,n=false){try{this.ensureRoot(),qn.writeFileSync(Me__default.join(this.root,t),r);}catch(s){if(!n)throw s}}read(t,r=false){try{return qn.readFileSync(Me__default.join(this.root,t),"utf8")}catch(n){if(!r)throw n}}relativePath(t){return t?Me__default.relative(process.cwd(),Me__default.join(this.root,t)):this.root}path(t){return t?Me__default.join(this.root,t):this.root}};});var Hr,Zo=g(()=>{Hr=process.env.SUPALITE_CLOUD_URL??(process.env.LOCAL?"http://localhost:2000":"https://www.lite.dev");});var $s,Ip=g(()=>{Tt();$s=class{root;constructor(t){this.root=t??Me__default.join(Kw.homedir(),".lite","auth"),ke(this.root);}async getItem(t){try{return qn.readFileSync(Me__default.join(this.root,t+".json"),"utf8")}catch{return null}}async setItem(t,r){qn.writeFileSync(Me__default.join(this.root,t+".json"),r);}async removeItem(t){try{qn.unlinkSync(Me__default.join(this.root,t+".json"));}catch{return}}};});var or,ta=g(()=>{Zo();Qo();Ip();or=class{constructor(t){this.config=t;this.tempFs=new nt(".temp",this.config.root),this.projectFs=new nt("supabase",this.config.root),this.schemaFs=new nt("schemas",this.config.root),this.authStorage=this.config.authStorage??new $s(Me__default.join(nt.homeDir(),"auth")),this._client=this.config.withSupabaseClient!==false?this.config.client??createClient(this.config.host??Hr,process.env.SUPALITE_CLOUD_ANON_KEY??"...",{auth:{storage:this.authStorage}}):void 0;}tempFs;projectFs;schemaFs;_client;authStorage;async fetch(t,r){if(!this.config.token)throw new Error("Not authenticated, sign in first.");let n=t instanceof URL?t:new URL(t,this.config.host??Hr);return await fetch(n,{...r,headers:{...r?.headers,Authorization:`Bearer ${this.config.token}`}})}};});var ar,ra=g(()=>{ta();ar=class extends or{constructor(r){super(r);this.config=r;}get client(){if(!this._client)throw new Error("Supabase client not initialized");return this._client}projectRef(){return this.tempFs.read("project-ref",true)}projectUrl(r){let n=new URL(this.config.host),s=n.hostname==="localhost"?"supalite.local":n.hostname,i=s.split(".").filter(a=>a!=="www"),o=i.length>=2?i.slice(-2).join("."):s;return `${n.protocol}//${r}.${o}${n.port?`:${n.port}`:""}`}};});function Qw(e){let t=Me.extname(e).toLowerCase();return {".html":"text/html",".css":"text/css",".js":"application/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".webp":"image/webp",".avif":"image/avif",".pdf":"application/pdf",".txt":"text/plain",".xml":"application/xml",".zip":"application/zip",".mp4":"video/mp4",".webm":"video/webm",".mp3":"audio/mpeg",".wav":"audio/wav",".woff":"font/woff",".woff2":"font/woff2"}[t]??"application/octet-stream"}var Ts,Lp=g(()=>{ht();Ts=class{driver=pe;basePath;constructor(t){this.basePath=Me.resolve(t.basePath);}filePath(t,r){return Me.join(this.basePath,t,r)}async ensureDir(t){await pe.mkdir(Me.dirname(t),{recursive:true});}async getObject(t,r,n,s){let i=this.filePath(t,r),o=await pe.stat(i),a=`"${createHash("md5").update(`${i}:${o.mtimeMs}`).digest("hex")}"`;if(s?.ifNoneMatch===a)return {httpStatusCode:304,metadata:this.buildMetadata(o,a,r)};if(s?.ifModifiedSince){let f=new Date(s.ifModifiedSince);if(o.mtime<=f)return {httpStatusCode:304,metadata:this.buildMetadata(o,a,r)}}let l,c,p=o.size,u=200;if(s?.range){let f=s.range.match(/^bytes=(\d+)-(\d*)$/);if(f){let h=Number.parseInt(f[1],10),d=f[2]?Number.parseInt(f[2],10):o.size-1;p=d-h+1,c=`bytes ${h}-${d}/${o.size}`,u=206,l=(await pe.open(i,"r")).readableWebStream();}else l=(await pe.open(i,"r")).readableWebStream();}else l=(await pe.open(i,"r")).readableWebStream();return {httpStatusCode:u,metadata:{...this.buildMetadata(o,a,r),contentLength:p,contentRange:c},body:l}}async uploadObject(t,r,n,s,i,o){let a=this.filePath(t,r);await this.ensureDir(a);let l;if(s instanceof Uint8Array||Buffer.isBuffer(s))l=s;else {let u=[],f=s.getReader();for(;;){let{done:h,value:d}=await f.read();if(h)break;u.push(d);}l=Buffer.concat(u);}await pe.writeFile(a,l);let c=await pe.stat(a),p=`"${createHash("md5").update(l).digest("hex")}"`;return {cacheControl:o,contentLength:c.size,size:c.size,mimetype:i,lastModified:c.mtime,eTag:p}}async deleteObject(t,r,n){let s=this.filePath(t,r);await pe.unlink(s).catch(i=>{if(i.code!=="ENOENT")throw i});}async deleteObjects(t,r){for(let n of r)await this.deleteObject(t,n,void 0);}async copyObject(t,r,n,s,i){let o=this.filePath(t,r),a=this.filePath(t,s);await this.ensureDir(a),await pe.copyFile(o,a);let l=await pe.stat(a),c=await pe.readFile(a);return {httpStatusCode:200,eTag:`"${createHash("md5").update(c).digest("hex")}"`,lastModified:l.mtime}}async headObject(t,r,n){let s=this.filePath(t,r),i=await pe.stat(s),o=`"${createHash("md5").update(`${s}:${i.mtimeMs}`).digest("hex")}"`;return this.buildMetadata(i,o,r)}async privateAssetUrl(t,r,n){return `file://${this.filePath(t,r)}`}buildMetadata(t,r,n){return {cacheControl:"no-cache",contentLength:yo(t.size),size:yo(t.size),mimetype:Qw(n),lastModified:t.mtime,eTag:r}}};});async function We(e,t,r){try{return await Zw(e)}catch(n){throw n?.code==="ERR_MODULE_NOT_FOUND"||/Cannot find package/.test(String(n?.message))?new Error(`Driver '${t}' selected but '${r}' is not installed. Run: bun add ${r}`):n}}var Zw,lr=g(()=>{Zw=new Function("spec","return import(spec)");});var Wr,tb,As,jp=g(()=>{ra();Zt();Wr=te(ae());Rr();Yt();Lp();lr();Yi();Zi();er();tb=["toml","json","ts","mts","js","mjs","cjs"],As=class extends ar{ref(){return this.projectRef()}setRef(t){return this.tempFs.write("project-ref",t),this}link(t){return this.setRef(t.id),t}unlink(){return this.tempFs.delete("project-ref"),this}url(){let t=this.ref();if(!t)throw new Error("No project linked");return this.projectUrl(t)}async getConfigPath(t){let r=Me__default.relative(process.cwd(),ye.config_dir);if(!t)for(let n of tb){let s=Me__default.join(r,`config.${n}`);if(await pe__default.access(s).then(()=>true).catch(()=>false)){t=s;break}}return t}async readConfig(t){let r=await this.getConfigPath(t);if(!r)return {};Ze(Wr.default.dim(`Using config file: ${Wr.default.cyan(`./${r}`)}`));let n=Me__default.dirname(Me__default.resolve(r));Vn(n);let s=r.split(".").pop(),i;switch(s){case "toml":i=Ct(await pe__default.readFile(r,"utf-8"));break;case "json":i=JSON.parse(await pe__default.readFile(r,"utf-8"));break;case "ts":case "mts":case "js":case "mjs":case "cjs":try{i=(await import(Me__default.join(process.cwd(),r))).default;break}catch(o){throw console.error("Failed to import config file",o),o}default:throw new Error(`Unsupported config file type: ${r}`)}return Kn(i)}async createConnection(){throw new Error("Not implemented")}async getConfig(t){let r=await this.readConfig(t);if("connection"in r)return {...r,connection:await r.connection};let n,s;switch(r.db?.driver){case "sqlite":s=r.db?.url??ye.default_db_url,n=await createConnection({url:s,ddlDialect:"sqlite"});break;case "pglite":{s=r.db?.url??Me__default.join(process.cwd(),ye.default_db_dir);let{createPgliteConnection:i}=await We("@supabase/lite/pglite","pglite","@electric-sql/pglite");n=await i({url:s});break}case "postgres":{s=r.db?.url??"";let{createPostgresConnection:i}=await We("@supabase/lite/postgres","postgres","postgres");n=await i({url:s});break}default:s=r.db?.url??ye.default_db_url,n=await createConnection({url:s,ddlDialect:"postgres"});break}if(!n)throw new Error("Failed to create connection");return Ze(Wr.default.green(" \u279C"),"Database located at",Wr.default.cyan(s??"in-memory")),{...r,connection:n}}async createApp(t){let r=await this.getConfig(t),n=new App(r);return n.config.storage?.enabled&&process.env.EXPERIMENTAL_STORAGE==="1"&&!n._storageAdapter&&(n._storageAdapter=new Ts({basePath:Me__default.join(process.cwd(),ye.config_dir,".temp/storage")})),await n.init()}};});var Cs,Fp=g(()=>{ra();Cs=class extends ar{url(t){return this.projectUrl(t)}async ping(){return (await this.fetch("/v1/system/ping")).ok}async list(){let t=await this.fetch("/v1/projects");if(!t.ok)throw new Error("Failed to list projects");let r=await t.json();if(!r||!r.data)throw new Error("Failed to list projects");return r.data}async get(t){if(t=t??this.projectRef(),!t)throw new Error("No project ref found");let r=await this.fetch(`/v1/projects/${t}`);if(!r.ok)throw new Error(`Failed to get project: ${r.status} ${r.statusText}`);let n=await r.json();if(!n||!n.id)throw new Error("Failed to get project");return n}async create(t={}){let r=await this.fetch("/v1/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok)throw new Error(`Failed to create project: ${r.status} ${r.statusText}`);let n=await r.json();if(!n.data||!n.data.id)throw new Error("Failed to create project");return n.data}async getConfig(t){let r=await this.fetch(`/v1/projects/${t}/config`);if(!r.ok)throw new Error(`Failed to get project config: ${r.status} ${r.statusText}`);let n=await r.json();if(!n)throw new Error("Failed to get project config");return n}async setConfig(t,r){let n=await this.fetch(`/v1/projects/${t}/config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!n.ok)throw new Error(`Failed to set project config: ${n.status} ${n.statusText}`);return true}async createApp(t){if(!this.config.host)throw new Error("No host specified");let{data:r,error:n}=await this.client.auth.getSession();if(n)throw n;if(!r?.session?.access_token)throw new Error("Not authenticated, sign in first.");let s=await this.getConfig(t);return await new App({...s.config,connection:cloud({projectRef:t,token:r.session.access_token,host:this.config.host})}).init()}};});var Rs,Mp=g(()=>{ta();jp();Fp();Rs=class extends or{project;get client(){if(!this._client)throw new Error("Supabase client not initialized");return this._client}async getSession(){return await this.client.auth.getSession()}async getAccessToken(){let{data:t,error:r}=await this.getSession();if(r)throw r;return t?.session?.access_token}async requireSession(){let t=await this.getAccessToken();if(!t)throw new Error("Not authenticated, sign in first.");return t}async init(){let t={...this.config};return this.config.withSupabaseClient!==false&&(t.client=this.client,t.token=await this.getAccessToken()),this.project={local:new As(t),remote:new Cs(t)},this}};});async function z(e={}){return await new Rs({host:Hr,root:nt.projectDir(),...e}).init()}var Ce=g(()=>{Qo();Zo();Mp();});var Up={};de(Up,{start:()=>sb});var Gr,sb,Bp=g(()=>{Yo();ht();Gr=te(ae());Zt();Ce();$e();Yt();sb=e=>{e.command("start").option("--config <config>","Path to the config file").description("Start the development server").helpGroup("Local Development:").action(async t=>{await Q(t.config),await ns(async()=>{let n=await(await z({withSupabaseClient:false})).project.local.createApp(t.config),s=n.config.api?.port??ye.default_api_port;await Es(n,{port:s});console.log(Gr.default.green(" \u279C"),"Server running on ",Gr.default.cyan(`http://localhost:${s}`));let o=Bn();o&&console.log(Gr.default.yellow(` \u26A0 ${o}`)),await n.connection.ping();},r=>{console.log(),console.log(Gr.default.green(`Ready in ${r.toFixed(2)}ms`));});});};});function pb(e){let t=normalize(e);return t.length>1&&t[t.length-1]===sep&&(t=t.substring(0,t.length-1)),t}function Gp(e,t){return e.replace(fb,t)}function db(e){return e==="/"||mb.test(e)}function sa(e,t){let{resolvePaths:r,normalizePath:n,pathSeparator:s}=t,i=process.platform==="win32"&&e.includes("/")||e.startsWith(".");if(r&&(e=resolve(e)),(n||i)&&(e=pb(e)),e===".")return "";let o=e[e.length-1]!==s;return Gp(o?e+s:e,s)}function zp(e,t){return t+e}function hb(e,t){return function(r,n){return n.startsWith(e)?n.slice(e.length)+r:Gp(relative(e,n),t.pathSeparator)+t.pathSeparator+r}}function gb(e){return e}function yb(e,t,r){return t+e+r}function wb(e,t){let{relativePaths:r,includeBasePath:n}=t;return r&&e?hb(e,t):n?zp:gb}function bb(e){return function(t,r){r.push(t.substring(e.length)||".");}}function Sb(e){return function(t,r,n){let s=t.substring(e.length)||".";n.every(i=>i(s,true))&&r.push(s);}}function $b(e,t){let{includeDirs:r,filters:n,relativePaths:s}=t;return r?s?n&&n.length?Sb(e):bb(e):n&&n.length?xb:Eb:_b}function kb(e){let{excludeFiles:t,filters:r,onlyCounts:n}=e;return t?Rb:r&&r.length?n?vb:Tb:n?Ab:Cb}function Nb(e){return e.group?Ob:Pb}function Db(e){return e.group?Ib:Lb}function Mb(e,t){return !e.resolveSymlinks||e.excludeSymlinks?null:t?Fb:jb}function Vp(e,t,r){if(r.options.useRealPaths)return Ub(t,r);let n=dirname(e),s=1;for(;n!==r.root&&s<2;){let i=r.symlinks.get(n);!!i&&(i===t||i.startsWith(t)||t.startsWith(i))?s++:n=dirname(n);}return r.symlinks.set(e,t),s>1}function Ub(e,t){return t.visited.includes(e+t.options.pathSeparator)}function ks(e,t,r,n){t(e&&!n?e:null,r);}function Xb(e,t){let{onlyCounts:r,group:n,maxFiles:s}=e;return r?t?Bb:Gb:n?t?qb:Kb:s?t?Wb:Vb:t?Hb:zb}function Qb(e){return e?Yb:Jb}function rS(e,t){return new Promise((r,n)=>{Jp(e,t,(s,i)=>{if(s)return n(s);r(i);});})}function Jp(e,t,r){new Xp(e,t,r).start();}function nS(e,t){return new Xp(e,t).start()}var qp,fb,mb,Eb,xb,_b,vb,Tb,Ab,Cb,Rb,Pb,Ob,Ib,Lb,jb,Fb,Bb,qb,Hb,Wb,Gb,zb,Vb,Kb,Kp,Jb,Yb,Zb,eS,tS,Xp,Hp,Yp,Qp,Zp=g(()=>{qp=createRequire(import.meta.url);fb=/[\\/]/g;mb=/^[a-z]:[\\/]$/i;Eb=(e,t)=>{t.push(e||".");},xb=(e,t,r)=>{let n=e||".";r.every(s=>s(n,true))&&t.push(n);},_b=()=>{};vb=(e,t,r,n)=>{n.every(s=>s(e,false))&&r.files++;},Tb=(e,t,r,n)=>{n.every(s=>s(e,false))&&t.push(e);},Ab=(e,t,r,n)=>{r.files++;},Cb=(e,t)=>{t.push(e);},Rb=()=>{};Pb=e=>e,Ob=()=>[""].slice(0,0);Ib=(e,t,r)=>{e.push({directory:t,files:r,dir:t});},Lb=()=>{};jb=function(e,t,r){let{queue:n,fs:s,options:{suppressErrors:i}}=t;n.enqueue(),s.realpath(e,(o,a)=>{if(o)return n.dequeue(i?null:o,t);s.stat(a,(l,c)=>{if(l)return n.dequeue(i?null:l,t);if(c.isDirectory()&&Vp(e,a,t))return n.dequeue(null,t);r(c,a),n.dequeue(null,t);});});},Fb=function(e,t,r){let{queue:n,fs:s,options:{suppressErrors:i}}=t;n.enqueue();try{let o=s.realpathSync(e),a=s.statSync(o);if(a.isDirectory()&&Vp(e,o,t))return;r(a,o);}catch(o){if(!i)throw o}};Bb=e=>e.counts,qb=e=>e.groups,Hb=e=>e.paths,Wb=e=>e.paths.slice(0,e.options.maxFiles),Gb=(e,t,r)=>(ks(t,r,e.counts,e.options.suppressErrors),null),zb=(e,t,r)=>(ks(t,r,e.paths,e.options.suppressErrors),null),Vb=(e,t,r)=>(ks(t,r,e.paths.slice(0,e.options.maxFiles),e.options.suppressErrors),null),Kb=(e,t,r)=>(ks(t,r,e.groups,e.options.suppressErrors),null);Kp={withFileTypes:true},Jb=(e,t,r,n,s)=>{if(e.queue.enqueue(),n<0)return e.queue.dequeue(null,e);let{fs:i}=e;e.visited.push(t),e.counts.directories++,i.readdir(t||".",Kp,(o,a=[])=>{s(a,r,n),e.queue.dequeue(e.options.suppressErrors?null:o,e);});},Yb=(e,t,r,n,s)=>{let{fs:i}=e;if(n<0)return;e.visited.push(t),e.counts.directories++;let o=[];try{o=i.readdirSync(t||".",Kp);}catch(a){if(!e.options.suppressErrors)throw a}s(o,r,n);};Zb=class{count=0;constructor(e){this.onQueueEmpty=e;}enqueue(){return this.count++,this.count}dequeue(e,t){this.onQueueEmpty&&(--this.count<=0||e)&&(this.onQueueEmpty(e,t),e&&(t.controller.abort(),this.onQueueEmpty=void 0));}},eS=class{_files=0;_directories=0;set files(e){this._files=e;}get files(){return this._files}set directories(e){this._directories=e;}get directories(){return this._directories}get dirs(){return this._directories}},tS=class{aborted=false;abort(){this.aborted=true;}},Xp=class{root;isSynchronous;state;joinPath;pushDirectory;pushFile;getArray;groupFiles;resolveSymlink;walkDirectory;callbackInvoker;constructor(e,t,r){this.isSynchronous=!r,this.callbackInvoker=Xb(t,this.isSynchronous),this.root=sa(e,t),this.state={root:db(this.root)?this.root:this.root.slice(0,-1),paths:[""].slice(0,0),groups:[],counts:new eS,options:t,queue:new Zb((n,s)=>this.callbackInvoker(s,n,r)),symlinks:new Map,visited:[""].slice(0,0),controller:new tS,fs:t.fs||ub},this.joinPath=wb(this.root,t),this.pushDirectory=$b(this.root,t),this.pushFile=kb(t),this.getArray=Nb(t),this.groupFiles=Db(t),this.resolveSymlink=Mb(t,this.isSynchronous),this.walkDirectory=Qb(this.isSynchronous);}start(){return this.pushDirectory(this.root,this.state.paths,this.state.options.filters),this.walkDirectory(this.state,this.root,this.root,this.state.options.maxDepth,this.walk),this.isSynchronous?this.callbackInvoker(this.state,null):null}walk=(e,t,r)=>{let{paths:n,options:{filters:s,resolveSymlinks:i,excludeSymlinks:o,exclude:a,maxFiles:l,signal:c,useRealPaths:p,pathSeparator:u},controller:f}=this.state;if(f.aborted||c&&c.aborted||l&&n.length>l)return;let h=this.getArray(this.state.paths);for(let d=0;d<e.length;++d){let m=e[d];if(m.isFile()||m.isSymbolicLink()&&!i&&!o){let w=this.joinPath(m.name,t);this.pushFile(w,h,this.state.counts,s);}else if(m.isDirectory()){let w=yb(m.name,t,this.state.options.pathSeparator);if(a&&a(m.name,w))continue;this.pushDirectory(w,n,s),this.walkDirectory(this.state,w,w,r-1,this.walk);}else if(this.resolveSymlink&&m.isSymbolicLink()){let w=zp(m.name,t);this.resolveSymlink(w,this.state,(y,E)=>{if(y.isDirectory()){if(E=sa(E,this.state.options),a&&a(m.name,p?E:w+u))return;this.walkDirectory(this.state,E,p?E:w+u,r-1,this.walk);}else {E=p?E:w;let T=basename(E),v=sa(dirname(E),this.state.options);E=this.joinPath(T,v),this.pushFile(E,h,this.state.counts,s);}});}}this.groupFiles(this.state.groups,t,h);}};Hp=class{constructor(e,t){this.root=e,this.options=t;}withPromise(){return rS(this.root,this.options)}withCallback(e){Jp(this.root,this.options,e);}sync(){return nS(this.root,this.options)}},Yp=null;try{qp.resolve("picomatch"),Yp=qp("picomatch");}catch{}Qp=class{globCache={};options={maxDepth:1/0,suppressErrors:true,pathSeparator:sep,filters:[]};globFunction;constructor(e){this.options={...this.options,...e},this.globFunction=this.options.globFunction;}group(){return this.options.group=true,this}withPathSeparator(e){return this.options.pathSeparator=e,this}withBasePath(){return this.options.includeBasePath=true,this}withRelativePaths(){return this.options.relativePaths=true,this}withDirs(){return this.options.includeDirs=true,this}withMaxDepth(e){return this.options.maxDepth=e,this}withMaxFiles(e){return this.options.maxFiles=e,this}withFullPaths(){return this.options.resolvePaths=true,this.options.includeBasePath=true,this}withErrors(){return this.options.suppressErrors=false,this}withSymlinks({resolvePaths:e=true}={}){return this.options.resolveSymlinks=true,this.options.useRealPaths=e,this.withFullPaths()}withAbortSignal(e){return this.options.signal=e,this}normalize(){return this.options.normalizePath=true,this}filter(e){return this.options.filters.push(e),this}onlyDirs(){return this.options.excludeFiles=true,this.options.includeDirs=true,this}exclude(e){return this.options.exclude=e,this}onlyCounts(){return this.options.onlyCounts=true,this}crawl(e){return new Hp(e||".",this.options)}withGlobFunction(e){return this.globFunction=e,this}crawlWithOptions(e,t){return this.options={...this.options,...t},new Hp(e||".",this.options)}glob(...e){return this.globFunction?this.globWithOptions(e):this.globWithOptions(e,{dot:true})}globWithOptions(e,...t){let r=this.globFunction||Yp;if(!r)throw new Error("Please specify a glob function to use glob matching.");var n=this.globCache[e.join("\0")];return n||(n=r(e,...t),this.globCache[e.join("\0")]=n),this.options.filters.push(s=>n(s)),this}};});var zr=ft((NR,sf)=>{var ef="[^\\\\/]",sS="(?=.)",tf="[^/]",oa="(?:\\/|$)",rf="(?:^|\\/)",aa=`\\.{1,2}${oa}`,iS="(?!\\.)",oS=`(?!${rf}${aa})`,aS=`(?!\\.{0,1}${oa})`,lS=`(?!${aa})`,cS="[^.\\/]",uS=`${tf}*?`,pS="/",nf={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:sS,QMARK:tf,END_ANCHOR:oa,DOTS_SLASH:aa,NO_DOT:iS,NO_DOTS:oS,NO_DOT_SLASH:aS,NO_DOTS_SLASH:lS,QMARK_NO_DOT:cS,STAR:uS,START_ANCHOR:rf,SEP:pS},fS={...nf,SLASH_LITERAL:"[\\\\/]",QMARK:ef,STAR:`${ef}*?`,DOTS_SLASH:"\\.{1,2}(?:[\\\\/]|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:[\\\\/]|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:[\\\\/]|$))",QMARK_NO_DOT:"[^.\\\\/]",START_ANCHOR:"(?:^|[\\\\/])",END_ANCHOR:"(?:[\\\\/]|$)",SEP:"\\"},mS={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};sf.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:mS,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars(e){return {"!":{type:"negate",open:"(?:(?!(?:",close:`))${e.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(e){return e===true?fS:nf}};});var Vr=ft(Oe=>{var{REGEX_BACKSLASH:dS,REGEX_REMOVE_BACKSLASH:hS,REGEX_SPECIAL_CHARS:gS,REGEX_SPECIAL_CHARS_GLOBAL:yS}=zr();Oe.isObject=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);Oe.hasRegexChars=e=>gS.test(e);Oe.isRegexChar=e=>e.length===1&&Oe.hasRegexChars(e);Oe.escapeRegex=e=>e.replace(yS,"\\$1");Oe.toPosixSlashes=e=>e.replace(dS,"/");Oe.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let e=navigator.platform.toLowerCase();return e==="win32"||e==="windows"}return typeof process<"u"&&process.platform?process.platform==="win32":false};Oe.removeBackslashes=e=>e.replace(hS,t=>t==="\\"?"":t);Oe.escapeLast=(e,t,r)=>{let n=e.lastIndexOf(t,r);return n===-1?e:e[n-1]==="\\"?Oe.escapeLast(e,t,n-1):`${e.slice(0,n)}\\${e.slice(n)}`};Oe.removePrefix=(e,t={})=>{let r=e;return r.startsWith("./")&&(r=r.slice(2),t.prefix="./"),r};Oe.wrapOutput=(e,t={},r={})=>{let n=r.contains?"":"^",s=r.contains?"":"$",i=`${n}(?:${e})${s}`;return t.negated===true&&(i=`(?:^(?!${i}).*$)`),i};Oe.basename=(e,{windows:t}={})=>{let r=e.split(t?/[\\/]/:"/"),n=r[r.length-1];return n===""?r[r.length-2]:n};});var mf=ft((LR,ff)=>{var of=Vr(),{CHAR_ASTERISK:la,CHAR_AT:wS,CHAR_BACKWARD_SLASH:Kr,CHAR_COMMA:bS,CHAR_DOT:ca,CHAR_EXCLAMATION_MARK:ua,CHAR_FORWARD_SLASH:pf,CHAR_LEFT_CURLY_BRACE:pa,CHAR_LEFT_PARENTHESES:fa,CHAR_LEFT_SQUARE_BRACKET:SS,CHAR_PLUS:ES,CHAR_QUESTION_MARK:af,CHAR_RIGHT_CURLY_BRACE:xS,CHAR_RIGHT_PARENTHESES:lf,CHAR_RIGHT_SQUARE_BRACKET:_S}=zr(),cf=e=>e===pf||e===Kr,uf=e=>{e.isPrefix!==true&&(e.depth=e.isGlobstar?1/0:1);},$S=(e,t)=>{let r=t||{},n=e.length-1,s=r.parts===true||r.scanToEnd===true,i=[],o=[],a=[],l=e,c=-1,p=0,u=0,f=false,h=false,d=false,m=false,w=false,y=false,E=false,T=false,v=false,C=false,A=0,$,_,I={value:"",depth:0,isGlob:false},b=()=>c>=n,D=()=>l.charCodeAt(c+1),O=()=>($=_,l.charCodeAt(++c));for(;c<n;){_=O();let q;if(_===Kr){E=I.backslashes=true,_=O(),_===pa&&(y=true);continue}if(y===true||_===pa){for(A++;b()!==true&&(_=O());){if(_===Kr){E=I.backslashes=true,O();continue}if(_===pa){A++;continue}if(y!==true&&_===ca&&(_=O())===ca){if(f=I.isBrace=true,d=I.isGlob=true,C=true,s===true)continue;break}if(y!==true&&_===bS){if(f=I.isBrace=true,d=I.isGlob=true,C=true,s===true)continue;break}if(_===xS&&(A--,A===0)){y=false,f=I.isBrace=true,C=true;break}}if(s===true)continue;break}if(_===pf){if(i.push(c),o.push(I),I={value:"",depth:0,isGlob:false},C===true)continue;if($===ca&&c===p+1){p+=2;continue}u=c+1;continue}if(r.noext!==true&&(_===ES||_===wS||_===la||_===af||_===ua)===true&&D()===fa){if(d=I.isGlob=true,m=I.isExtglob=true,C=true,_===ua&&c===p&&(v=true),s===true){for(;b()!==true&&(_=O());){if(_===Kr){E=I.backslashes=true,_=O();continue}if(_===lf){d=I.isGlob=true,C=true;break}}continue}break}if(_===la){if($===la&&(w=I.isGlobstar=true),d=I.isGlob=true,C=true,s===true)continue;break}if(_===af){if(d=I.isGlob=true,C=true,s===true)continue;break}if(_===SS){for(;b()!==true&&(q=O());){if(q===Kr){E=I.backslashes=true,O();continue}if(q===_S){h=I.isBracket=true,d=I.isGlob=true,C=true;break}}if(s===true)continue;break}if(r.nonegate!==true&&_===ua&&c===p){T=I.negated=true,p++;continue}if(r.noparen!==true&&_===fa){if(d=I.isGlob=true,s===true){for(;b()!==true&&(_=O());){if(_===fa){E=I.backslashes=true,_=O();continue}if(_===lf){C=true;break}}continue}break}if(d===true){if(C=true,s===true)continue;break}}r.noext===true&&(m=false,d=false);let F=l,S="",x="";p>0&&(S=l.slice(0,p),l=l.slice(p),u-=p),F&&d===true&&u>0?(F=l.slice(0,u),x=l.slice(u)):d===true?(F="",x=l):F=l,F&&F!==""&&F!=="/"&&F!==l&&cf(F.charCodeAt(F.length-1))&&(F=F.slice(0,-1)),r.unescape===true&&(x&&(x=of.removeBackslashes(x)),F&&E===true&&(F=of.removeBackslashes(F)));let Y={prefix:S,input:e,start:p,base:F,glob:x,isBrace:f,isBracket:h,isGlob:d,isExtglob:m,isGlobstar:w,negated:T,negatedExtglob:v};if(r.tokens===true&&(Y.maxDepth=0,cf(_)||o.push(I),Y.tokens=o),r.parts===true||r.tokens===true){let q;for(let j=0;j<i.length;j++){let ie=q?q+1:p,ce=i[j],ut=e.slice(ie,ce);r.tokens&&(j===0&&p!==0?(o[j].isPrefix=true,o[j].value=S):o[j].value=ut,uf(o[j]),Y.maxDepth+=o[j].depth),(j!==0||ut!=="")&&a.push(ut),q=ce;}if(q&&q+1<e.length){let j=e.slice(q+1);a.push(j),r.tokens&&(o[o.length-1].value=j,uf(o[o.length-1]),Y.maxDepth+=o[o.length-1].depth);}Y.slashes=i,Y.parts=a;}return Y};ff.exports=$S;});var wf=ft((DR,yf)=>{var Xr=zr(),Ie=Vr(),{MAX_LENGTH:Ps,POSIX_REGEX_SOURCE:vS,REGEX_NON_SPECIAL_CHARS:TS,REGEX_SPECIAL_CHARS_BACKREF:AS,REPLACEMENTS:df}=Xr,CS=(e,t)=>{if(typeof t.expandRange=="function")return t.expandRange(...e,t);e.sort();let r=`[${e.join("-")}]`;try{new RegExp(r);}catch{return e.map(s=>Ie.escapeRegex(s)).join("..")}return r},cr=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`,hf=e=>{let t=[],r=0,n=0,s=0,i="",o=false;for(let a of e){if(o===true){i+=a,o=false;continue}if(a==="\\"){i+=a,o=true;continue}if(a==='"'){s=s===1?0:1,i+=a;continue}if(s===0){if(a==="[")r++;else if(a==="]"&&r>0)r--;else if(r===0){if(a==="(")n++;else if(a===")"&&n>0)n--;else if(a==="|"&&n===0){t.push(i),i="";continue}}}i+=a;}return t.push(i),t},RS=e=>{let t=false;for(let r of e){if(t===true){t=false;continue}if(r==="\\"){t=true;continue}if(/[?*+@!()[\]{}]/.test(r))return false}return true},gf=e=>{let t=e.trim(),r=true;for(;r===true;)r=false,/^@\([^\\()[\]{}|]+\)$/.test(t)&&(t=t.slice(2,-1),r=true);if(RS(t))return t.replace(/\\(.)/g,"$1")},kS=e=>{let t=e.map(gf).filter(Boolean);for(let r=0;r<t.length;r++)for(let n=r+1;n<t.length;n++){let s=t[r],i=t[n],o=s[0];if(!(!o||s!==o.repeat(s.length)||i!==o.repeat(i.length))&&(s===i||s.startsWith(i)||i.startsWith(s)))return true}return false},ma=(e,t=true)=>{if(e[0]!=="+"&&e[0]!=="*"||e[1]!=="(")return;let r=0,n=0,s=0,i=false;for(let o=1;o<e.length;o++){let a=e[o];if(i===true){i=false;continue}if(a==="\\"){i=true;continue}if(a==='"'){s=s===1?0:1;continue}if(s!==1){if(a==="["){r++;continue}if(a==="]"&&r>0){r--;continue}if(!(r>0)){if(a==="("){n++;continue}if(a===")"&&(n--,n===0))return t===true&&o!==e.length-1?void 0:{type:e[0],body:e.slice(2,o),end:o}}}}},PS=e=>{let t=0,r=[];for(;t<e.length;){let s=ma(e.slice(t),false);if(!s||s.type!=="*")return;let i=hf(s.body).map(a=>a.trim());if(i.length!==1)return;let o=gf(i[0]);if(!o||o.length!==1)return;r.push(o),t+=s.end+1;}return r.length<1?void 0:`${r.length===1?Ie.escapeRegex(r[0]):`[${r.map(s=>Ie.escapeRegex(s)).join("")}]`}*`},OS=e=>{let t=0,r=e.trim(),n=ma(r);for(;n;)t++,r=n.body.trim(),n=ma(r);return t},NS=(e,t)=>{if(t.maxExtglobRecursion===false)return {risky:false};let r=typeof t.maxExtglobRecursion=="number"?t.maxExtglobRecursion:Xr.DEFAULT_MAX_EXTGLOB_RECURSION,n=hf(e).map(s=>s.trim());if(n.length>1&&(n.some(s=>s==="")||n.some(s=>/^[*?]+$/.test(s))||kS(n)))return {risky:true};for(let s of n){let i=PS(s);if(i)return {risky:true,safeOutput:i};if(OS(s)>r)return {risky:true}}return {risky:false}},da=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a string");e=df[e]||e;let r={...t},n=typeof r.maxLength=="number"?Math.min(Ps,r.maxLength):Ps,s=e.length;if(s>n)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${n}`);let i={type:"bos",value:"",output:r.prepend||""},o=[i],a=r.capture?"":"?:",l=Xr.globChars(r.windows),c=Xr.extglobChars(l),{DOT_LITERAL:p,PLUS_LITERAL:u,SLASH_LITERAL:f,ONE_CHAR:h,DOTS_SLASH:d,NO_DOT:m,NO_DOT_SLASH:w,NO_DOTS_SLASH:y,QMARK:E,QMARK_NO_DOT:T,STAR:v,START_ANCHOR:C}=l,A=P=>`(${a}(?:(?!${C}${P.dot?d:p}).)*?)`,$=r.dot?"":m,_=r.dot?E:T,I=r.bash===true?A(r):v;r.capture&&(I=`(${I})`),typeof r.noext=="boolean"&&(r.noextglob=r.noext);let b={input:e,index:-1,start:0,dot:r.dot===true,consumed:"",output:"",prefix:"",backtrack:false,negated:false,brackets:0,braces:0,parens:0,quotes:0,globstar:false,tokens:o};e=Ie.removePrefix(e,b),s=e.length;let D=[],O=[],F=[],S=i,x,Y=()=>b.index===s-1,q=b.peek=(P=1)=>e[b.index+P],j=b.advance=()=>e[++b.index]||"",ie=()=>e.slice(b.index+1),ce=(P="",oe=0)=>{b.consumed+=P,b.index+=oe;},ut=P=>{b.output+=P.output!=null?P.output:P.value,ce(P.value);},fg=()=>{let P=1;for(;q()==="!"&&(q(2)!=="("||q(3)==="?");)j(),b.start++,P++;return P%2===0?false:(b.negated=true,b.start++,true)},jn=P=>{b[P]++,F.push(P);},pt=P=>{b[P]--,F.pop();},W=P=>{if(S.type==="globstar"){let oe=b.braces>0&&(P.type==="comma"||P.type==="brace"),R=P.extglob===true||D.length&&(P.type==="pipe"||P.type==="paren");P.type!=="slash"&&P.type!=="paren"&&!oe&&!R&&(b.output=b.output.slice(0,-S.output.length),S.type="star",S.value="*",S.output=I,b.output+=S.output);}if(D.length&&P.type!=="paren"&&(D[D.length-1].inner+=P.value),(P.value||P.output)&&ut(P),S&&S.type==="text"&&P.type==="text"){S.output=(S.output||S.value)+P.value,S.value+=P.value;return}P.prev=S,o.push(P),S=P;},Fn=(P,oe)=>{let R={...c[oe],conditions:1,inner:""};R.prev=S,R.parens=b.parens,R.output=b.output,R.startIndex=b.index,R.tokensIndex=o.length;let G=(r.capture?"(":"")+R.open;jn("parens"),W({type:P,value:oe,output:b.output?"":h}),W({type:"paren",extglob:true,value:j(),output:G}),D.push(R);},mg=P=>{let oe=e.slice(P.startIndex,b.index+1),R=e.slice(P.startIndex+2,b.index),G=NS(R,r);if((P.type==="plus"||P.type==="star")&&G.risky){let ee=G.safeOutput?(P.output?"":h)+(r.capture?`(${G.safeOutput})`:G.safeOutput):void 0,Ve=o[P.tokensIndex];Ve.type="text",Ve.value=oe,Ve.output=ee||Ie.escapeRegex(oe);for(let Ke=P.tokensIndex+1;Ke<o.length;Ke++)o[Ke].value="",o[Ke].output="",delete o[Ke].suffix;b.output=P.output+Ve.output,b.backtrack=true,W({type:"paren",extglob:true,value:x,output:""}),pt("parens");return}let ne=P.close+(r.capture?")":""),me;if(P.type==="negate"){let ee=I;if(P.inner&&P.inner.length>1&&P.inner.includes("/")&&(ee=A(r)),(ee!==I||Y()||/^\)+$/.test(ie()))&&(ne=P.close=`)$))${ee}`),P.inner.includes("*")&&(me=ie())&&/^\.[^\\/.]+$/.test(me)){let Ve=da(me,{...t,fastpaths:false}).output;ne=P.close=`)${Ve})${ee})`;}P.prev.type==="bos"&&(b.negatedExtglob=true);}W({type:"paren",extglob:true,value:x,output:ne}),pt("parens");};if(r.fastpaths!==false&&!/(^[*!]|[/()[\]{}"])/.test(e)){let P=false,oe=e.replace(AS,(R,G,ne,me,ee,Ve)=>me==="\\"?(P=true,R):me==="?"?G?G+me+(ee?E.repeat(ee.length):""):Ve===0?_+(ee?E.repeat(ee.length):""):E.repeat(ne.length):me==="."?p.repeat(ne.length):me==="*"?G?G+me+(ee?I:""):I:G?R:`\\${R}`);return P===true&&(r.unescape===true?oe=oe.replace(/\\/g,""):oe=oe.replace(/\\+/g,R=>R.length%2===0?"\\\\":R?"\\":"")),oe===e&&r.contains===true?(b.output=e,b):(b.output=Ie.wrapOutput(oe,b,t),b)}for(;!Y();){if(x=j(),x==="\0")continue;if(x==="\\"){let R=q();if(R==="/"&&r.bash!==true||R==="."||R===";")continue;if(!R){x+="\\",W({type:"text",value:x});continue}let G=/^\\+/.exec(ie()),ne=0;if(G&&G[0].length>2&&(ne=G[0].length,b.index+=ne,ne%2!==0&&(x+="\\")),r.unescape===true?x=j():x+=j(),b.brackets===0){W({type:"text",value:x});continue}}if(b.brackets>0&&(x!=="]"||S.value==="["||S.value==="[^")){if(r.posix!==false&&x===":"){let R=S.value.slice(1);if(R.includes("[")&&(S.posix=true,R.includes(":"))){let G=S.value.lastIndexOf("["),ne=S.value.slice(0,G),me=S.value.slice(G+2),ee=vS[me];if(ee){S.value=ne+ee,b.backtrack=true,j(),!i.output&&o.indexOf(S)===1&&(i.output=h);continue}}}(x==="["&&q()!==":"||x==="-"&&q()==="]")&&(x=`\\${x}`),x==="]"&&(S.value==="["||S.value==="[^")&&(x=`\\${x}`),r.posix===true&&x==="!"&&S.value==="["&&(x="^"),S.value+=x,ut({value:x});continue}if(b.quotes===1&&x!=='"'){x=Ie.escapeRegex(x),S.value+=x,ut({value:x});continue}if(x==='"'){b.quotes=b.quotes===1?0:1,r.keepQuotes===true&&W({type:"text",value:x});continue}if(x==="("){jn("parens"),W({type:"paren",value:x});continue}if(x===")"){if(b.parens===0&&r.strictBrackets===true)throw new SyntaxError(cr("opening","("));let R=D[D.length-1];if(R&&b.parens===R.parens+1){mg(D.pop());continue}W({type:"paren",value:x,output:b.parens?")":"\\)"}),pt("parens");continue}if(x==="["){if(r.nobracket===true||!ie().includes("]")){if(r.nobracket!==true&&r.strictBrackets===true)throw new SyntaxError(cr("closing","]"));x=`\\${x}`;}else jn("brackets");W({type:"bracket",value:x});continue}if(x==="]"){if(r.nobracket===true||S&&S.type==="bracket"&&S.value.length===1){W({type:"text",value:x,output:`\\${x}`});continue}if(b.brackets===0){if(r.strictBrackets===true)throw new SyntaxError(cr("opening","["));W({type:"text",value:x,output:`\\${x}`});continue}pt("brackets");let R=S.value.slice(1);if(S.posix!==true&&R[0]==="^"&&!R.includes("/")&&(x=`/${x}`),S.value+=x,ut({value:x}),r.literalBrackets===false||Ie.hasRegexChars(R))continue;let G=Ie.escapeRegex(S.value);if(b.output=b.output.slice(0,-S.value.length),r.literalBrackets===true){b.output+=G,S.value=G;continue}S.value=`(${a}${G}|${S.value})`,b.output+=S.value;continue}if(x==="{"&&r.nobrace!==true){jn("braces");let R={type:"brace",value:x,output:"(",outputIndex:b.output.length,tokensIndex:b.tokens.length};O.push(R),W(R);continue}if(x==="}"){let R=O[O.length-1];if(r.nobrace===true||!R){W({type:"text",value:x,output:x});continue}let G=")";if(R.dots===true){let ne=o.slice(),me=[];for(let ee=ne.length-1;ee>=0&&(o.pop(),ne[ee].type!=="brace");ee--)ne[ee].type!=="dots"&&me.unshift(ne[ee].value);G=CS(me,r),b.backtrack=true;}if(R.comma!==true&&R.dots!==true){let ne=b.output.slice(0,R.outputIndex),me=b.tokens.slice(R.tokensIndex);R.value=R.output="\\{",x=G="\\}",b.output=ne;for(let ee of me)b.output+=ee.output||ee.value;}W({type:"brace",value:x,output:G}),pt("braces"),O.pop();continue}if(x==="|"){D.length>0&&D[D.length-1].conditions++,W({type:"text",value:x});continue}if(x===","){let R=x,G=O[O.length-1];G&&F[F.length-1]==="braces"&&(G.comma=true,R="|"),W({type:"comma",value:x,output:R});continue}if(x==="/"){if(S.type==="dot"&&b.index===b.start+1){b.start=b.index+1,b.consumed="",b.output="",o.pop(),S=i;continue}W({type:"slash",value:x,output:f});continue}if(x==="."){if(b.braces>0&&S.type==="dot"){S.value==="."&&(S.output=p);let R=O[O.length-1];S.type="dots",S.output+=x,S.value+=x,R.dots=true;continue}if(b.braces+b.parens===0&&S.type!=="bos"&&S.type!=="slash"){W({type:"text",value:x,output:p});continue}W({type:"dot",value:x,output:p});continue}if(x==="?"){if(!(S&&S.value==="(")&&r.noextglob!==true&&q()==="("&&q(2)!=="?"){Fn("qmark",x);continue}if(S&&S.type==="paren"){let G=q(),ne=x;(S.value==="("&&!/[!=<:]/.test(G)||G==="<"&&!/<([!=]|\w+>)/.test(ie()))&&(ne=`\\${x}`),W({type:"text",value:x,output:ne});continue}if(r.dot!==true&&(S.type==="slash"||S.type==="bos")){W({type:"qmark",value:x,output:T});continue}W({type:"qmark",value:x,output:E});continue}if(x==="!"){if(r.noextglob!==true&&q()==="("&&(q(2)!=="?"||!/[!=<:]/.test(q(3)))){Fn("negate",x);continue}if(r.nonegate!==true&&b.index===0){fg();continue}}if(x==="+"){if(r.noextglob!==true&&q()==="("&&q(2)!=="?"){Fn("plus",x);continue}if(S&&S.value==="("||r.regex===false){W({type:"plus",value:x,output:u});continue}if(S&&(S.type==="bracket"||S.type==="paren"||S.type==="brace")||b.parens>0){W({type:"plus",value:x});continue}W({type:"plus",value:u});continue}if(x==="@"){if(r.noextglob!==true&&q()==="("&&q(2)!=="?"){W({type:"at",extglob:true,value:x,output:""});continue}W({type:"text",value:x});continue}if(x!=="*"){(x==="$"||x==="^")&&(x=`\\${x}`);let R=TS.exec(ie());R&&(x+=R[0],b.index+=R[0].length),W({type:"text",value:x});continue}if(S&&(S.type==="globstar"||S.star===true)){S.type="star",S.star=true,S.value+=x,S.output=I,b.backtrack=true,b.globstar=true,ce(x);continue}let P=ie();if(r.noextglob!==true&&/^\([^?]/.test(P)){Fn("star",x);continue}if(S.type==="star"){if(r.noglobstar===true){ce(x);continue}let R=S.prev,G=R.prev,ne=R.type==="slash"||R.type==="bos",me=G&&(G.type==="star"||G.type==="globstar");if(r.bash===true&&(!ne||P[0]&&P[0]!=="/")){W({type:"star",value:x,output:""});continue}let ee=b.braces>0&&(R.type==="comma"||R.type==="brace"),Ve=D.length&&(R.type==="pipe"||R.type==="paren");if(!ne&&R.type!=="paren"&&!ee&&!Ve){W({type:"star",value:x,output:""});continue}for(;P.slice(0,3)==="/**";){let Ke=e[b.index+4];if(Ke&&Ke!=="/")break;P=P.slice(3),ce("/**",3);}if(R.type==="bos"&&Y()){S.type="globstar",S.value+=x,S.output=A(r),b.output=S.output,b.globstar=true,ce(x);continue}if(R.type==="slash"&&R.prev.type!=="bos"&&!me&&Y()){b.output=b.output.slice(0,-(R.output+S.output).length),R.output=`(?:${R.output}`,S.type="globstar",S.output=A(r)+(r.strictSlashes?")":"|$)"),S.value+=x,b.globstar=true,b.output+=R.output+S.output,ce(x);continue}if(R.type==="slash"&&R.prev.type!=="bos"&&P[0]==="/"){let Ke=P[1]!==void 0?"|$":"";b.output=b.output.slice(0,-(R.output+S.output).length),R.output=`(?:${R.output}`,S.type="globstar",S.output=`${A(r)}${f}|${f}${Ke})`,S.value+=x,b.output+=R.output+S.output,b.globstar=true,ce(x+j()),W({type:"slash",value:"/",output:""});continue}if(R.type==="bos"&&P[0]==="/"){S.type="globstar",S.value+=x,S.output=`(?:^|${f}|${A(r)}${f})`,b.output=S.output,b.globstar=true,ce(x+j()),W({type:"slash",value:"/",output:""});continue}b.output=b.output.slice(0,-S.output.length),S.type="globstar",S.output=A(r),S.value+=x,b.output+=S.output,b.globstar=true,ce(x);continue}let oe={type:"star",value:x,output:I};if(r.bash===true){oe.output=".*?",(S.type==="bos"||S.type==="slash")&&(oe.output=$+oe.output),W(oe);continue}if(S&&(S.type==="bracket"||S.type==="paren")&&r.regex===true){oe.output=x,W(oe);continue}(b.index===b.start||S.type==="slash"||S.type==="dot")&&(S.type==="dot"?(b.output+=w,S.output+=w):r.dot===true?(b.output+=y,S.output+=y):(b.output+=$,S.output+=$),q()!=="*"&&(b.output+=h,S.output+=h)),W(oe);}for(;b.brackets>0;){if(r.strictBrackets===true)throw new SyntaxError(cr("closing","]"));b.output=Ie.escapeLast(b.output,"["),pt("brackets");}for(;b.parens>0;){if(r.strictBrackets===true)throw new SyntaxError(cr("closing",")"));b.output=Ie.escapeLast(b.output,"("),pt("parens");}for(;b.braces>0;){if(r.strictBrackets===true)throw new SyntaxError(cr("closing","}"));b.output=Ie.escapeLast(b.output,"{"),pt("braces");}if(r.strictSlashes!==true&&(S.type==="star"||S.type==="bracket")&&W({type:"maybe_slash",value:"",output:`${f}?`}),b.backtrack===true){b.output="";for(let P of b.tokens)b.output+=P.output!=null?P.output:P.value,P.suffix&&(b.output+=P.suffix);}return b};da.fastpaths=(e,t)=>{let r={...t},n=typeof r.maxLength=="number"?Math.min(Ps,r.maxLength):Ps,s=e.length;if(s>n)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${n}`);e=df[e]||e;let{DOT_LITERAL:i,SLASH_LITERAL:o,ONE_CHAR:a,DOTS_SLASH:l,NO_DOT:c,NO_DOTS:p,NO_DOTS_SLASH:u,STAR:f,START_ANCHOR:h}=Xr.globChars(r.windows),d=r.dot?p:c,m=r.dot?u:c,w=r.capture?"":"?:",y={negated:false,prefix:""},E=r.bash===true?".*?":f;r.capture&&(E=`(${E})`);let T=$=>$.noglobstar===true?E:`(${w}(?:(?!${h}${$.dot?l:i}).)*?)`,v=$=>{switch($){case "*":return `${d}${a}${E}`;case ".*":return `${i}${a}${E}`;case "*.*":return `${d}${E}${i}${a}${E}`;case "*/*":return `${d}${E}${o}${a}${m}${E}`;case "**":return d+T(r);case "**/*":return `(?:${d}${T(r)}${o})?${m}${a}${E}`;case "**/*.*":return `(?:${d}${T(r)}${o})?${m}${E}${i}${a}${E}`;case "**/.*":return `(?:${d}${T(r)}${o})?${i}${a}${E}`;default:{let _=/^(.*?)\.(\w+)$/.exec($);if(!_)return;let I=v(_[1]);return I?I+i+_[2]:void 0}}},C=Ie.removePrefix(e,y),A=v(C);return A&&r.strictSlashes!==true&&(A+=`${o}?`),A};yf.exports=da;});var Ef=ft((jR,Sf)=>{var IS=mf(),ha=wf(),bf=Vr(),LS=zr(),DS=e=>e&&typeof e=="object"&&!Array.isArray(e),ue=(e,t,r=false)=>{if(Array.isArray(e)){let p=e.map(f=>ue(f,t,r));return f=>{for(let h of p){let d=h(f);if(d)return d}return false}}let n=DS(e)&&e.tokens&&e.input;if(e===""||typeof e!="string"&&!n)throw new TypeError("Expected pattern to be a non-empty string");let s=t||{},i=s.windows,o=n?ue.compileRe(e,t):ue.makeRe(e,t,false,true),a=o.state;delete o.state;let l=()=>false;if(s.ignore){let p={...t,ignore:null,onMatch:null,onResult:null};l=ue(s.ignore,p,r);}let c=(p,u=false)=>{let{isMatch:f,match:h,output:d}=ue.test(p,o,t,{glob:e,posix:i}),m={glob:e,state:a,regex:o,posix:i,input:p,output:d,match:h,isMatch:f};return typeof s.onResult=="function"&&s.onResult(m),f===false?(m.isMatch=false,u?m:false):l(p)?(typeof s.onIgnore=="function"&&s.onIgnore(m),m.isMatch=false,u?m:false):(typeof s.onMatch=="function"&&s.onMatch(m),u?m:true)};return r&&(c.state=a),c};ue.test=(e,t,r,{glob:n,posix:s}={})=>{if(typeof e!="string")throw new TypeError("Expected input to be a string");if(e==="")return {isMatch:false,output:""};let i=r||{},o=i.format||(s?bf.toPosixSlashes:null),a=e===n,l=a&&o?o(e):e;return a===false&&(l=o?o(e):e,a=l===n),(a===false||i.capture===true)&&(i.matchBase===true||i.basename===true?a=ue.matchBase(e,t,r,s):a=t.exec(l)),{isMatch:!!a,match:a,output:l}};ue.matchBase=(e,t,r)=>(t instanceof RegExp?t:ue.makeRe(t,r)).test(bf.basename(e));ue.isMatch=(e,t,r)=>ue(t,r)(e);ue.parse=(e,t)=>Array.isArray(e)?e.map(r=>ue.parse(r,t)):ha(e,{...t,fastpaths:false});ue.scan=(e,t)=>IS(e,t);ue.compileRe=(e,t,r=false,n=false)=>{if(r===true)return e.output;let s=t||{},i=s.contains?"":"^",o=s.contains?"":"$",a=`${i}(?:${e.output})${o}`;e&&e.negated===true&&(a=`^(?!${a}).*$`);let l=ue.toRegex(a,t);return n===true&&(l.state=e),l};ue.makeRe=(e,t={},r=false,n=false)=>{if(!e||typeof e!="string")throw new TypeError("Expected a non-empty string");let s={negated:false,fastpaths:true};return t.fastpaths!==false&&(e[0]==="."||e[0]==="*")&&(s.output=ha.fastpaths(e,t)),s.output||(s=ha(e,t)),ue.compileRe(s,t,r,n)};ue.toRegex=(e,t)=>{try{let r=t||{};return new RegExp(e,r.flags||(r.nocase?"i":""))}catch(r){if(t&&t.debug===true)throw r;return /$^/}};ue.constants=LS;Sf.exports=ue;});var vf=ft((FR,$f)=>{var xf=Ef(),jS=Vr();function _f(e,t,r=false){return t&&(t.windows===null||t.windows===void 0)&&(t={...t,windows:jS.isWindows()}),xf(e,t,r)}Object.assign(_f,xf);$f.exports=_f;});function JS(e,t={}){let r=e.length,n=Array(r),s=Array(r),i,o;for(i=0;i<r;i++){let a=Pf(e[i]);n[i]=a;let l=a.length,c=Array(l);for(o=0;o<l;o++)c[o]=(0, ur.default)(a[o],t);s[i]=c;}return a=>{let l=a.split("/");if(l[0]===".."&&XS.test(a))return true;for(i=0;i<r;i++){let c=n[i],p=s[i],u=l.length,f=Math.min(u,c.length);for(o=0;o<f;){let h=c[o];if(h.includes("/"))return true;if(!p[o](l[o]))break;if(!t.noglobstar&&h==="**")return true;o++;}if(o===u)return true}return false}}function Tf(e,t,r){if(e===t||t.startsWith(`${e}/`)){if(r){let s=e.length+ +!QS(e);return (i,o)=>i.slice(s,o?-1:void 0)||"."}let n=t.slice(e.length+1);return n?(s,i)=>{if(s===".")return n;let o=`${n}/${s}`;return i?o.slice(0,-1):o}:(s,i)=>i&&s!=="."?s.slice(0,-1):s}return r?n=>posix.relative(e,n)||".":n=>posix.relative(e,`${t}/${n}`)||"."}function ZS(e,t){if(t.startsWith(`${e}/`)){let r=t.slice(e.length+1);return n=>`${r}/${n}`}return r=>{let n=posix.relative(e,`${t}/${r}`);return r[r.length-1]==="/"&&n!==""?`${n}/`:n||"."}}function Af(e){return e.replace(KS,t=>`${t}/`)}function Pf(e){var t;let r=ur.default.scan(e,eE);return !((t=r.parts)===null||t===void 0)&&t.length?r.parts:[e]}function oE(e,t){let r=ur.default.scan(e);return r.isGlob||r.negated}function Jr(...e){console.log(`[tinyglobby ${new Date().toLocaleTimeString("es")}]`,...e);}function Of(e){return typeof e=="string"?[e]:e??[]}function ga(e,t,r,n){var s;let i=t.cwd,o=e;e[e.length-1]==="/"&&(o=e.slice(0,-1)),o[o.length-1]!=="*"&&t.expandDirectories&&(o+="/**");let a=iE(i);o=isAbsolute(o.replace(lE,""))?posix.relative(a,o):posix.normalize(o);let l=(s=aE.exec(o))===null||s===void 0?void 0:s[0],c=Pf(o);if(l){let u=(l.length+1)/3,f=0,h=a.split("/");for(;f<u&&c[f+u]===h[h.length+f-u];)o=o.slice(0,(u-f-1)*3)+o.slice((u-f)*3+c[f+u].length+1)||".",f++;let d=posix.join(i,l.slice(f*3));d[0]!=="."&&r.root.length>d.length&&(r.root=Af(d),r.depthOffset=-u+f);}if(!n&&r.depthOffset>=0){var p;(p=r.commonPath)!==null&&p!==void 0||(r.commonPath=c);let u=[],f=Math.min(r.commonPath.length,c.length);for(let h=0;h<f;h++){let d=c[h];if(d==="**"&&!c[h+1]){u.pop();break}if(h===c.length-1||d!==r.commonPath[h]||oE(d))break;u.push(d);}r.depthOffset=u.length,r.commonPath=u,r.root=Af(u.length>0?posix.join(i,...u):i);}return o}function cE(e,t,r){let n=[],s=[];for(let i of e.ignore)i&&(i[0]!=="!"||i[1]==="(")&&s.push(ga(i,e,r,true));for(let i of t)i&&(i[0]!=="!"||i[1]==="("?n.push(ga(i,e,r,false)):(i[1]!=="!"||i[2]==="(")&&s.push(ga(i.slice(1),e,r,true)));return {match:n,ignore:s}}function uE(e,t){let r=e.cwd,n={root:r,depthOffset:0},s=cE(e,t,n);e.debug&&Jr("internal processing patterns:",s);let{absolute:i,caseSensitiveMatch:o,debug:a,dot:l,followSymbolicLinks:c,onlyDirectories:p}=e,u=n.root.replace(Rf,""),f={dot:l,nobrace:e.braceExpansion===false,nocase:!o,noextglob:e.extglob===false,noglobstar:e.globstar===false,posix:true},h=(0, ur.default)(s.match,f),d=(0, ur.default)(s.ignore,f),m=JS(s.match,f),w=Tf(r,u,i),y=i?w:Tf(r,u,true),E=(C,A)=>{let $=y(A,true);return $!=="."&&!m($)||d($)},T;e.deep!==void 0&&(T=Math.round(e.deep-n.depthOffset));let v=new Qp({filters:[a?(C,A)=>{let $=w(C,A),_=h($)&&!d($);return _&&Jr(`matched ${$}`),_}:(C,A)=>{let $=w(C,A);return h($)&&!d($)}],exclude:a?(C,A)=>{let $=E(C,A);return Jr(`${$?"skipped":"crawling"} ${A}`),$}:E,fs:e.fs,pathSeparator:"/",relativePaths:!i,resolvePaths:i,includeBasePath:i,resolveSymlinks:c,excludeSymlinks:!c,excludeFiles:p,includeDirs:p||!e.onlyFiles,maxDepth:T,signal:e.signal}).crawl(u);return e.debug&&Jr("internal properties:",{...n,root:u}),[v,r!==u&&!i&&ZS(r,u)]}function pE(e,t){if(t)for(let r=e.length-1;r>=0;r--)e[r]=t(e[r]);return e}function fE(e){let t=Object.assign({},e);for(let r in Cf)t[r]===void 0&&Object.assign(t,{[r]:Cf[r]});return t.cwd=(t.cwd instanceof URL?fileURLToPath$1(t.cwd):resolve(t.cwd||process.cwd())).replace(Rf,"/"),t.ignore=Of(t.ignore),t.fs&&(t.fs={readdir:t.fs.readdir||readdir,readdirSync:t.fs.readdirSync||readdirSync,realpath:t.fs.realpath||realpath,realpathSync:t.fs.realpathSync||realpathSync,stat:t.fs.stat||stat,statSync:t.fs.statSync||statSync$1}),t.debug&&Jr("globbing with options:",t),t}function mE(e,t={}){var r;if(e&&t?.patterns)throw new Error("Cannot pass patterns as both an argument and an option");let n=VS(e)||typeof e=="string",s=Of((r=n?e:e.patterns)!==null&&r!==void 0?r:"**/*"),i=fE(n?t:e);return s.length>0?uE(i,s):[]}async function Yr(e,t){let[r,n]=mE(e,t);return r?pE(await r.withPromise(),n):[]}var ur,VS,Rf,KS,kf,XS,YS,QS,eE,tE,rE,nE,sE,iE,aE,lE,Cf,ya=g(()=>{Zp();ur=te(vf()),VS=Array.isArray,Rf=/\\/g,KS=/^[A-Za-z]:$/,kf=process.platform==="win32",XS=/^(\/?\.\.)+$/;YS=/^[A-Z]:\/$/i,QS=kf?e=>YS.test(e):e=>e==="/";eE={parts:true};tE=/(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g,rE=/(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g,nE=e=>e.replace(tE,"\\$&"),sE=e=>e.replace(rE,"\\$&"),iE=kf?sE:nE;aE=/^(\/?\.\.)+/,lE=/\\(?=[()[\]{}!*+?@|])/g;Cf={caseSensitiveMatch:true,debug:!!process.env.TINYGLOBBY_DEBUG,expandDirectories:true,followSymbolicLinks:true,onlyFiles:true};});function Le(e){return e.dialect==="postgres"?"pg":e.config?.ddlDialect==="sqlite"?"sqlite":"pg-flat"}function Os(e){return e==="sqlite"?{schema_migrations:"migrations",seed_files:"seed_files"}:e==="pg-flat"?{schema_migrations:'"supabase_migrations.schema_migrations"',seed_files:'"supabase_migrations.seed_files"'}:{schema_migrations:"supabase_migrations.schema_migrations",seed_files:"supabase_migrations.seed_files"}}function Qr(e){return `'${e.replace(/'/g,"''")}'`}function dE(e){return `'${`{${e.map(n=>`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`).join(",")}}`.replace(/'/g,"''")}'`}function hE(e){return e==="sqlite"?[`CREATE TABLE IF NOT EXISTS migrations (
60
+ `)}function mt(e){let t=[],r="",n=0,s=e.length,i=false,o=false,a=0,l=/^create(\s+or\s+replace)?(\s+temp(orary)?)?$/i,c=u=>{Uc(u).length>0&&t.push(u.trim());},p=()=>{i=false,o=false,a=0;};for(;n<s;){let u=e[n],f=e[n+1];if(u==="-"&&f==="-"){for(;n<s&&e[n]!==`
61
+ `;)r+=e[n],n++;continue}if(u==="/"&&f==="*"){for(r+="/*",n+=2;n<s&&!(e[n]==="*"&&e[n+1]==="/");)r+=e[n],n++;n<s&&(r+="*/",n+=2);continue}if(u==="'"){for(r+=u,n++;n<s;){if(e[n]==="'"&&e[n+1]==="'"){r+="''",n+=2;continue}if(r+=e[n],e[n]==="'"){n++;break}n++;}continue}if(u==='"'){for(r+=u,n++;n<s;){if(e[n]==='"'&&e[n+1]==='"'){r+='""',n+=2;continue}if(r+=e[n],e[n]==='"'){n++;break}n++;}continue}if(u==="$"){let h=e.indexOf("$",n+1);if(h!==-1){let d=e.slice(n,h+1);if(/^\$[A-Za-z_][A-Za-z0-9_]*\$$|^\$\$$/.test(d)){r+=d,n=h+1;let w=e.indexOf(d,n);w===-1?(r+=e.slice(n),n=s):(r+=e.slice(n,w+d.length),n=w+d.length);continue}}}if(/[A-Za-z_]/.test(u)){let h=n;for(;h<s&&/[A-Za-z0-9_]/.test(e[h]);)h++;let d=e.slice(n,h),m=d.toLowerCase();if(m==="trigger"&&l.test(Uc(r))?i=true:i&&m==="begin"?(o=true,a++):i&&o&&m==="case"?a++:i&&o&&m==="end"&&a>0&&a--,r+=d,n=h,i&&o&&a===0){let w=n;for(;w<s&&/\s/.test(e[w]);)w++;e[w]===";"&&(n=w+1),c(r),r="",p();}continue}if(u===";"){if(i&&o&&a>0){r+=u,n++;continue}c(r),r="",p(),n++;continue}r+=u,n++;}return c(r),t}function Uc(e){let t="",r=0,n=e.length;for(;r<n;){let s=e[r],i=e[r+1];if(s==="-"&&i==="-"){for(;r<n&&e[r]!==`
62
+ `;)r++;continue}if(s==="/"&&i==="*"){for(r+=2;r<n&&!(e[r]==="*"&&e[r+1]==="/");)r++;r+=2;continue}t+=s,r++;}return t.trim()}function ao(e){return (e??"").trim().toLowerCase()}function lo(e){return (e??"").replace(/\s+/g," ").replace(/"/g,"").trim().toLowerCase()}function co(e){if(e==null)return null;let t=e.trim();for(;t.startsWith("(")&&t.endsWith(")");)t=t.slice(1,-1).trim();return (t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"'))&&(t=t.slice(1,-1)),t}var Rt=g(()=>{});function Qg(e,t,r=void 0){let n=typeof t=="string"?Gc(t):fo(t);return as(e,n,r)}function as(e,t,r=void 0){let n=typeof t=="string"?t.split(/[.\[\]\"]+/).filter(s=>s):t;if(n.length===0)return e;try{let[s,...i]=n;return !s||!(s in e)?r:as(e[s],i,r)}catch{if(typeof r<"u")return r;throw new Error(`Invalid path: ${n.join(".")}`)}}function ty(e){return e===null}function he(e){return !Array.isArray(e)&&typeof e=="object"&&e!==null}function ry(e){return Object.prototype.toString.call(e)==="[object Object]"}function Je(e){return typeof e=="string"}function et(e){return typeof e=="number"}function ny(e){return typeof e=="number"&&Number.isInteger(e)}function go(e){return typeof e=="boolean"}function dt(e){return Array.isArray(e)}function sy(e){return typeof e!="boolean"}function iy(e){return e!==void 0&&sy(e)&&"type"in e}function Ae(e){return e!==void 0&&he(e)&&Te in e}function oy(e){return Ae(e)&&typeof e.toJSON()=="boolean"}function ay(e,t,r){if(!e)throw new ey(t,r)}function zc(e){return Je(e)?e.normalize("NFC"):e}function Nr(e,t){let r=typeof e;if(r!==typeof t)return false;if(Array.isArray(e)){if(!Array.isArray(t))return false;let n=e.length;if(n!==t.length)return false;for(let s=0;s<n;s++)if(!Nr(e[s],t[s]))return false;return true}if(r==="object"){if(!e||!t)return e===t;let n=Object.keys(e),s=Object.keys(t);if(n.length!==s.length)return false;for(let i of n)if(!Nr(e[i],t[i]))return false;return true}return e===t}function ly(e,t){return t.reduce((r,n)=>(n in e&&(r[n]=e[n]),r),{})}function Vc(e){try{return structuredClone(e)}catch{return e}}function cy(e,t,r={}){let n=t;try{n=structuredClone(t);}catch{n=JSON.parse(JSON.stringify(t));}let s={resolver:r.resolver||new yo(e),depth:r.depth||0,dropUnknown:r.dropUnknown??false};return s.resolver.hasRef(e,n)?s.resolver.resolve(e.$ref).coerce(n,{...s,depth:s.depth+1}):n}function ls(e,t,r={}){return e.map(n=>n.validate(t,os(r)).valid?n:void 0).filter(Boolean)}function qy(e,t,r={}){let n={keywordPath:r.keywordPath||[],instancePath:r.instancePath||[],coerce:r.coerce||false,errors:r.errors||[],shortCircuit:r.shortCircuit||false,ignoreUnsupported:r.ignoreUnsupported||false,resolver:r.resolver||e.getResolver?.()||new yo(e),depth:r.depth?r.depth+1:0,skipClone:r.skipClone||false},s;if(r?.coerce&&e.coerce){let i=e.coerce(t,{resolver:n.resolver,depth:n.depth});s=n.skipClone?i:structuredClone(i);}else s=n.skipClone?t:structuredClone(t);if(r.ignoreUnsupported!==true){let i=["$defs"];for(let o of i)if(e[o])throw new Error(`${o} not implemented`)}if(n.resolver.hasRef(e,s)){let i=n.resolver.resolve(e.$ref).validate(s,{...n,errors:[]});i.valid||n.errors.push(...i.errors);}else {let i={keywordPath:n.keywordPath,instancePath:n.instancePath,coerce:n.coerce,errors:[],shortCircuit:n.shortCircuit,ignoreUnsupported:n.ignoreUnsupported,resolver:n.resolver,depth:n.depth};for(let o in e)if(o==="type"&&e.type!==void 0){if(s!==void 0){let a=uo[o];if(a){i.errors=[];let l=a(e,s,i);if(!l.valid){if(r.shortCircuit)return l;n.errors.push(...l.errors);}}}}else if(o in uo&&e[o]!==void 0){if(s===void 0)continue;let a=uo[o];if(a){i.errors=[];let l=a(e,s,i);if(!l.valid){if(r.shortCircuit)return l;n.errors.push(...l.errors);}}}}return {valid:n.errors.length===0,errors:n.errors}}function cs(e,t,r){return new class extends tt{type=e}(t,r)}function mo(e){return new Hy(e)}function Hc(e,t){return Array.isArray(e)?e.map(t):e!==void 0?[t(e)]:[]}function Wc(e,t,r=n=>n){return Object.fromEntries(Object.entries(e).map(([n,s])=>[n,r(t(s,n),n)]))}function tr(e){if(go(e))return mo(e);let t=structuredClone(e);if(!he(t))throw new Zg("non-object schemas cannot be converted to a schema",t);"properties"in t&&t.properties&&(t.properties=Wc(t.properties,(i,o)=>{try{return tr(i)}catch(a){throw new Error(`Couldn't schemaize property "${o}": ${String(a)}`)}},(i,o)=>"required"in t&&Array.isArray(t.required)&&t.required.includes(o)?i:i.optional()));let r=["patternProperties","dependentSchemas","$defs"];for(let i of r)i in t&&t[i]&&(t[i]=Wc(t[i],tr));let n=["additionalProperties","items","prefixItems","propertyNames","contains","not","if","then","else"];for(let i of n)i in t&&typeof t[i]<"u"&&(dt(t[i])?t[i]=Hc(t[i],tr):t[i]=tr(t[i]));let s=["anyOf","oneOf","allOf"];for(let i of s)if(i in t){let{[i]:o}=t;t[i]=Hc(o,tr);}if(iy(t))switch(t.type){case "string":return Xc(t);case "number":return Yc(t);case "integer":return Qc(t);case "boolean":return eu(t);case "object":{let{properties:i,...o}=t;return us(i,o)}case "array":{let{items:i,...o}=t;return Zc(i,o)}}return Kc(t)}function rw(){return {type(e){let t=e.map(r=>Array.isArray(r)?new Set(r):new Set([r])).reduce((r,n)=>r?new Set([...r].filter(s=>n.has(s))):new Set(n));if(!t.size)throw new Error('Incompatible "type" in allOf');return t.size===1?[...t][0]:[...t]},enum(e){let t=e.map(r=>new Set(r)).reduce((r,n)=>new Set([...r].filter(s=>n.has(s))));if(!t.size)throw new Error('Incompatible "enum" in allOf');return [...t]},required(e){return [...new Set(e.flat())]},properties(e,t,r){return e.reduce((n,s)=>r(n,s),{})},patternProperties(e,t,r){return e.reduce((n,s)=>r(n,s),{})},$defs(e,t,r){return e.reduce((n,s)=>r(n,s),{})},definitions(e,t,r){return e.reduce((n,s)=>r(n,s),{})},...Object.fromEntries(ew.map(e=>[e,t=>Math.min(...t)])),...Object.fromEntries(tw.map(e=>[e,t=>Math.max(...t)]))}}function nw(e){let t={...rw(),...e.resolvers};function r(n,s){if(Array.isArray(n)&&Array.isArray(s))return [...new Set([...n,...s])];if(ho(n)&&ho(s)){let i={...n};for(let[o,a]of Object.entries(s))if(o in i){let l=t[o];i[o]=l?l([i[o],a],o,r):po(a);}else i[o]=po(a);return i}return po(s)}return r}function iw(e,t={}){let r=t.deep!==false,n=nw(t);function s(i){if(Array.isArray(i))return i.map(s);if(!ho(i))return i;if(Array.isArray(i.allOf)){let a=i.allOf.map(s);if(a.some(h=>h===false))return false;let l=a.filter(h=>h!==true);if(!l.length)return true;let c=l.reduce((h,d)=>n(h,d),{}),p=sw(c);if(p!==null)return p;let u={...i};delete u.allOf;let f=n(c,r?s(u):u);return r?s(f):f}let o={};for(let[a,l]of Object.entries(i))o[a]=s(l);return o}return s(e)}var fo,Gc,Z,L,rr,os,kt,Zg,ey,Te,yo,uy,py,fy,my,dy,hy,gy,yy,wy,by,Sy,Ey,xy,_y,$y,vy,Ty,Ay,Cy,Ry,ky,Py,Oy,Ny,Iy,Ly,Dy,jy,Fy,My,Uy,qc,By,uo,tt,Ir,Hy,Kc,Wy,Gy,us,zy,Vy,Ky,Xy,Jy,Xc,Jc,Yc,Qc,Yy,Zc,eu,is,tu,Qy,Zy,ho,po,ew,tw,sw,ow,ru,aw,lw,cw,nu,su=g(()=>{fo=(e=[],t="")=>"/"+[t,...e.map(r=>String(r).replace(/\./g,"/"))].filter(Boolean).join("/"),Gc=e=>e.split("/").slice(1);Z=(e={},t,r,n)=>({valid:false,errors:[...e.errors??[],{keywordLocation:fo([...e.keywordPath??[],t]),instanceLocation:fo(e.instancePath),error:typeof r=="string"?r:`Invalid value for ${t}`,data:n}]}),L=()=>({valid:true,errors:[]}),rr=(e,t,r)=>{let n=Array.isArray(t)?t:[t],s=r?Array.isArray(r)?r:[r]:[];return {...e,keywordPath:[...e.keywordPath??[],...n],instancePath:s?[...e.instancePath??[],...s]:e.instancePath}},os=(e={})=>({...e,errors:[]}),kt=class extends Error{constructor(e){super(`Expected ${e}`);}},Zg=class extends Error{constructor(e,t){super(`${e??"Invalid raw schema"}: ${JSON.stringify(t)}`),this.schema=t;}},ey=class extends Error{constructor(e,t){super(`${e}, got: 'type "${typeof t}": ${JSON.stringify(t)}'`),this.value=t;}},Te=Symbol.for("jsonv-ts:schema");yo=class{constructor(e){this.root=e,this.cache=new Map;}cache;hasRef(e,t){return t!==void 0&&"$ref"in e&&Je(e.$ref)}resolve(e){let t=this.cache.get(e);if(!t){if(t=Qg(this.root,e),!Ae(t))throw new Error(`ref not found: ${e}`);if("$ref"in t&&t.$ref===e)throw new Error(`ref loop: ${e}`);this.cache.set(e,t);}return t}};uy=({type:e},t,r={})=>{if(e===void 0||t===void 0)return L();let n,s={string:Je,number:et,integer:ny,object:he,array:dt,boolean:go,null:ty};if(Array.isArray(e)){for(let i of e){if(!(i in s))throw new kt(`Unknown type: ${i}`);if(s[i](t))return L()}n=`Expected one of: ${e.join(", ")}`;}else {if(!(e in s))throw new kt(`Unknown type: ${e}`);s[e](t)||(n=`Expected ${e}`);}return n?Z(r,"type",n,t):L()},py=({const:e},t,r={})=>Nr(e,t)?L():Z(r,"const",`Expected const: ${e}`,t),fy=({enum:e=[]},t,r={})=>e.some(n=>Nr(n,t))?L():Z(r,"enum",`Expected enum: ${JSON.stringify(e)}`,t);my=({anyOf:e=[]},t,r={})=>ls(e,t,r).length>0?L():Z(r,"anyOf","Expected at least one to match",t),dy=({oneOf:e=[]},t,r={})=>ls(e,t).length===1?L():Z(r,"oneOf","Expected exactly one to match",t),hy=({allOf:e=[]},t,r={})=>ls(e,t,r).length===e.length?L():Z(r,"allOf","Expected all to match",t),gy=({not:e},t,r={})=>t===void 0?L():Ae(e)&&e.validate(t,r).valid?Z(r,"not","Expected not to match",t):L(),yy=({if:e,then:t,else:r},n,s={})=>{if(e&&(t||r)){if(e.validate(n,os(s)).valid)return t?t.validate(n,os(s)):L();if(r)return r.validate(n,os(s))}return L()},wy=({pattern:e=""},t,r={})=>{if(!Je(t))return L();if(e instanceof RegExp){if(e.test(t))return L()}else if(new RegExp(e,"u").test(t))return L();return Z(r,"pattern",`Expected string matching pattern ${e}`,t)},by=({minLength:e=0},t,r={})=>Je(t)?[...zc(t)].length>=e?L():Z(r,"minLength",`Expected string with minimum length of ${e}`,t):L(),Sy=({maxLength:e=0},t,r={})=>Je(t)?[...zc(t)].length<=e?L():Z(r,"maxLength",`Expected string with maximum length of ${e}`,t):L(),Ey=({multipleOf:e=0},t,r={})=>{if(!et(t))return L();if(!(Number.isFinite(t)&&Number.isFinite(e))||e<=0)throw new kt("number");let n=t/e,s=Number.EPSILON*Math.max(1,Math.abs(n));return Math.abs(n-Math.round(n))<=s?L():Z(r,"multipleOf",`Expected number being a multiple of ${e}`,t)},xy=({maximum:e=0},t,r={})=>!et(t)||t<=e?L():Z(r,"maximum",`Expected number less than or equal to ${e}`,t),_y=({exclusiveMaximum:e=0},t,r={})=>!et(t)||t<e?L():Z(r,"exclusiveMaximum",`Expected number less than ${e}`,t),$y=({minimum:e=0},t,r={})=>!et(t)||t>=e?L():Z(r,"minimum",`Expected number greater than or equal to ${e}`,t),vy=({exclusiveMinimum:e=0},t,r={})=>!et(t)||t>e?L():Z(r,"exclusiveMinimum",`Expected number greater than ${e}`,t),Ty=({properties:e={}},t,r={})=>{if(!he(t))return L();for(let[n,s]of Object.entries(t)){let i=e[n];if(!Ae(i))continue;let o=i.validate(s,rr(r,["properties",n],n));if(!o.valid)return o}return L()},Ay=({properties:e={},additionalProperties:t,patternProperties:r},n,s={})=>{if(!he(n))return L();if(!Ae(t))throw new kt("additionalProperties must be a boolean or a managed schema");let i=Object.keys(e),o=he(r)?Object.keys(n).filter(l=>Object.keys(r).some(c=>new RegExp(c).test(l))):[],a=Object.keys(n).filter(l=>!i.includes(l)&&!o.includes(l));if(a.length>0){if(oy(t)){if(t.toJSON()===true)return L();let l=a.reduce((c,p)=>(c[p]=n[p],c),{});return Z(s,"additionalProperties","Additional properties are not allowed",l)}else if(Ae(t))for(let l of a){let c=t.validate(n[l],rr(s,["additionalProperties"],l));if(!c.valid)return c}}return L()},Cy=({dependentRequired:e},t,r={})=>{if(!he(t))return L();let n=Object.keys(t).filter(s=>typeof t[s]!="function");if(he(e)){for(let[s,i]of Object.entries(e))if(n.includes(s)){for(let o of i)if(!n.includes(o))return Z(r,"dependentRequired",`Expected dependent required property ${o}`,t)}}return L()},Ry=({required:e=[]},t,r={})=>{if(!he(t))return L();let n=Object.keys(t).filter(s=>typeof t[s]!="function");return e.every(s=>n.includes(s))?L():Z(r,"required",`Expected object with required properties ${e.join(", ")}`,t)},ky=({dependentSchemas:e},t,r={})=>{if(!he(t))return L();let n=Object.keys(t).filter(s=>typeof t[s]!="function");if(he(e)){for(let[s,i]of Object.entries(e))if(n.includes(s)){let o=i.validate(t,r);if(!o.valid)return o}}return L()},Py=({minProperties:e=0},t,r={})=>he(t)?Object.keys(t).length>=e?L():Z(r,"minProperties",`Expected object with at least ${e} properties`,t):L(),Oy=({maxProperties:e=0},t,r={})=>!he(t)||Object.keys(t).length<=e?L():Z(r,"maxProperties",`Expected object with at most ${e} properties`,t),Ny=({patternProperties:e={}},t,r={})=>{if(!he(t))return L();if(!he(e))throw new kt("patternProperties must be an object");for(let[n,s]of Object.entries(t))for(let[i,o]of Object.entries(e))if(new RegExp(i,"u").test(n)){let a=o.validate(s,rr(r,["patternProperties"],n));if(!a.valid)return a}return L()},Iy=({propertyNames:e},t,r={})=>{if(!he(t)||e===void 0)return L();if(!Ae(e))throw new kt("propertyNames must be a managed schema");for(let n of Object.keys(t)){let s=e.validate(n,rr(r,["propertyNames"],n));if(!s.valid)return s}return L()},Ly=({items:e,prefixItems:t=[]},r,n={})=>{if(!dt(r)||e===void 0)return L();if(!Ae(e))throw new kt("items must be a managed schema");for(let[s,i]of r.slice(t.length).entries()){let o=e.validate(i,rr(n,["items"],String(s)));if(!o.valid)return o}return L()},Dy=({minItems:e=0},t,r={})=>!dt(t)||t.length>=e?L():Z(r,"minItems",`Expected array with at least ${e} items`,t),jy=({maxItems:e=0},t,r={})=>!dt(t)||t.length<=e?L():Z(r,"maxItems",`Expected array with at most ${e} items`,t),Fy=({uniqueItems:e=false},t,r={})=>{if(!dt(t)||!e)return L();for(let n=0;n<t.length;n++){let s=t[n];for(let i=0;i<t.length;i++){if(n===i)continue;let o=t[i];if(Nr(s,o))return Z(r,"uniqueItems",`Duplicated items at index ${n} and ${i}`,t)}}return L()},My=({contains:e,minContains:t,maxContains:r},n,s={})=>{if(!Ae(e))throw new Error("contains must be a managed schema");if(!dt(n))return L();let i=n.filter(o=>e.validate(o).valid).length;return i<(t??1)?Z(s,t?"minContains":"contains",`Expected array to contain at least ${t??1}, but found ${i}`,n):r!==void 0&&i>r?Z(s,"maxContains",`Expected array to contain at most ${r}, but found ${i}`,n):L()},Uy=({prefixItems:e=[]},t,r={})=>{if(!dt(t))return L();for(let n=0;n<t.length;n++){let s=e[n]?.validate(t[n],rr(r,String(n),String(n)));if(s&&s?.valid!==true)return s}return L()},qc={email:e=>{if(e.length>318)return false;if(/^[a-z0-9!#$%&'*+/=?^_`{|}~-]{1,20}(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]{1,21}){0,2}@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,60}[a-z0-9])?){0,3}$/i.test(e))return true;if(!e.includes("@")||/(^\.|^"|\.@|\.\.)/.test(e))return false;let[t,r,...n]=e.split("@");return !t||!r||n.length!==0||t.length>64||r.length>253||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?false:r.split(".").every(s=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(s))},hostname:e=>e.length>(e.endsWith(".")?254:253)?false:/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*\.?$/i.test(e),date:e=>{if(e.length!==10)return false;if(e[5]==="0"&&e[6]==="2"){if(/^\d\d\d\d-02-(?:[012][1-8]|[12]0|[01]9)$/.test(e))return true;let t=e.match(/^(\d\d\d\d)-02-29$/);if(!t)return false;let r=Number(t[1]);return r%16===0||r%4===0&&r%25!==0}return e.endsWith("31")?/^\d\d\d\d-(?:0[13578]|1[02])-31$/.test(e):/^\d\d\d\d-(?:0[13-9]|1[012])-(?:[012][1-9]|[123]0)$/.test(e)},time:e=>{if(e.length>27||!/^(?:2[0-3]|[0-1]\d):[0-5]\d:(?:[0-5]\d|60)(?:\.\d+)?(?:z|[+-](?:2[0-3]|[0-1]\d)(?::?[0-5]\d)?)?$/i.test(e))return false;if(!/:60/.test(e))return true;let t=e.match(/([0-9.]+|[^0-9.])/g);if(!t)return false;let r=Number(t[0])*60+Number(t[2]);return t[5]==="+"?r+=1440-Number(t[6]||0)*60-Number(t[8]||0):t[5]==="-"&&(r+=Number(t[6]||0)*60+Number(t[8]||0)),r%1440===1439},"date-time":e=>{if(e.length>38)return false;let t=/^\d\d\d\d-(?:0[1-9]|1[0-2])-(?:[0-2]\d|3[01])[t\s](?:2[0-3]|[0-1]\d):[0-5]\d:(?:[0-5]\d|60)(?:\.\d+)?(?:z|[+-](?:2[0-3]|[0-1]\d)(?::?[0-5]\d)?)$/i,r=e[5]==="0"&&e[6]==="2";if(r&&e[8]==="3"||!t.test(e))return false;if(e[17]==="6"){let n=e.slice(11).match(/([0-9.]+|[^0-9.])/g);if(!n)return false;let s=Number(n[0])*60+Number(n[2]);if(n[5]==="+"?s+=1440-Number(n[6]||0)*60-Number(n[8]||0):n[5]==="-"&&(s+=Number(n[6]||0)*60+Number(n[8]||0)),s%1440!==1439)return false}if(r){if(/^\d\d\d\d-02-(?:[012][1-8]|[12]0|[01]9)/.test(e))return true;let n=e.match(/^(\d\d\d\d)-02-29/);if(!n)return false;let s=Number(n[1]??0);return s%16===0||s%4===0&&s%25!==0}return e[8]==="3"&&e[9]==="1"?/^\d\d\d\d-(?:0[13578]|1[02])-31/.test(e):/^\d\d\d\d-(?:0[13-9]|1[012])-(?:[012][1-9]|[123]0)/.test(e)},ipv4:e=>e.length<=15&&/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)$/.test(e),ipv6:e=>{if(e.length>45||e.length<2)return false;let t=0,r=0,n=0,s=false,i=false,o=0,a=true;for(let c=0;c<e.length;c++){let p=e.charCodeAt(c);if(c===1&&o===58&&p!==58)return false;if(p>=48&&p<=57){if(++n>4)return false}else if(p===46){if(t>6||r>=3||n===0||i)return false;r++,n=0;}else if(p===58){if(r>0||t>=7)return false;if(o===58){if(s)return false;s=true;}else c===0&&(a=false);t++,n=0,i=false;}else if(p>=97&&p<=102||p>=65&&p<=70){if(r>0||++n>4)return false;i=true;}else return false;o=p;}if(t<2||r>0&&(r!==3||n===0))return false;if(s&&e.length===2)return true;if(r>0&&!/(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/.test(e))return false;let l=r>0?6:7;return s?(a||n>0)&&t<l:t===l&&a&&n>0},uri:e=>/^[a-z][a-z0-9+\-.]*:(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/?(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i.test(e),"uri-reference":e=>/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/?(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?)?(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i.test(e),"uri-template":e=>/^(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2}|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i.test(e),"json-pointer":e=>/^(?:|\/(?:[^~]|~0|~1)*)$/.test(e),"relative-json-pointer":e=>/^(?:0|[1-9][0-9]*)(?:|#|\/(?:[^~]|~0|~1)*)$/.test(e),uuid:e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),duration:e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e)),regex:e=>{if(/[^\\]\\Z/.test(e))return false;try{return new RegExp(e,"u"),!0}catch{return false}},binary:()=>true,password:()=>true},By=({format:e},t,r={})=>!Je(t)||!e?L():qc[e]?qc[e](t)?L():Z(r,"format",`Expected format: ${e}`,t):L(),uo={type:uy,const:py,enum:fy,allOf:hy,anyOf:my,oneOf:dy,not:gy,minLength:by,maxLength:Sy,pattern:wy,format:By,minimum:$y,exclusiveMinimum:vy,maximum:xy,exclusiveMaximum:_y,multipleOf:Ey,required:Ry,dependentRequired:Cy,dependentSchemas:ky,minProperties:Py,maxProperties:Oy,propertyNames:Iy,properties:Ty,patternProperties:Ny,additionalProperties:Ay,minItems:Dy,maxItems:jy,uniqueItems:Fy,contains:My,prefixItems:Uy,items:Ly,if:yy};tt=class{"~standard";[Te];_resolver;type;$id;$ref;$schema;title;description;readOnly;writeOnly;$comment;examples;constructor(e,t){let{type:r,validate:n,coerce:s,template:i,...o}=e||{};Object.assign(this,{type:r},o),this[Te]={raw:e,optional:false,overrides:t},this["~standard"]={version:1,vendor:"jsonv-ts",validate:a=>{let l=this.validate(a);return l.valid?{value:a}:{issues:l.errors.map(c=>({message:c.error,path:Gc(c.instanceLocation)}))}}};}template(e,t){let r=this,n=e;if(r.const!==void 0?n=r.const:n===void 0&&(r.default!==void 0&&(n=r.default),t?.withExtendedOptional&&r.enum!==void 0&&(n=r.enum[0])),t?.withOptional!==true&&n===void 0&&this.isOptional())return n;if(this[Te].raw?.template){let i=this[Te].raw.template(n,t);i!==void 0&&(n=i);}let s=this[Te].overrides?.template?.(n,t);return s!==void 0&&(n=s),n}validate(e,t){let r={keywordPath:t?.keywordPath||[],instancePath:t?.instancePath||[],coerce:t?.coerce||false,errors:t?.errors||[],shortCircuit:t?.shortCircuit||false,ignoreUnsupported:t?.ignoreUnsupported||false,resolver:t?.resolver||this.getResolver(),depth:t?.depth?t.depth+1:0,skipClone:t?.skipClone??true},n=this[Te].raw?.validate;if(n!==void 0){let s=n(e,r);if(!s.valid)return s}return qy(this,e,r)}coerce(e,t){let r={...t,resolver:t?.resolver||this.getResolver(),depth:t?.depth?t.depth+1:0,dropUnknown:t?.dropUnknown??false},n=this[Te].raw?.coerce;if(n!==void 0)return n(e,r);let s=this[Te].overrides?.coerce?.(e,r)??e;return cy(this,s,r)}optional(){return this[Te].optional=true,this}isOptional(){return this[Te].optional}getResolver(){return this._resolver||(this._resolver=new yo(this)),this._resolver}children(e){return []}*walk({instancePath:e=[],keywordPath:t=[],data:r,maxDepth:n=Number.POSITIVE_INFINITY,...s}={}){let i=e.length===0&&r?Vc(r):r;if(s.includeSelf!==false&&(yield new Ir(this,{instancePath:e,keywordPath:t,data:i,...s})),!(e.length>=n))for(let o of this.children(s)){let a=[...e,...o.instancePath];yield*o.schema.walk({...s,data:i,maxDepth:n,instancePath:a,keywordPath:[...t,...o.keywordPath]});}}*[Symbol.iterator](e){for(let t of this.walk(e))yield t;}toJSON(){let{toJSON:e,"~standard":t,_resolver:r,...n}=this;return JSON.parse(JSON.stringify(n))}},Ir=class{constructor(e,t={}){this.schema=e,this.instancePath=t.instancePath||[],this.keywordPath=t.keywordPath||[],this.depth=this.instancePath.length;try{if(t.data!==void 0){let r=as(t.data,this.instancePath);e.validate(r).valid&&(this.data=r);}}catch{}}instancePath;keywordPath;data;depth;appendInstancePath(e){return this.instancePath=[...this.instancePath,...e],this}appendKeywordPath(e){return this.keywordPath=[...this.keywordPath,...e],this}setData(e){return this.data=e,this}};Hy=class extends tt{constructor(e){super(),this.bool=e;}toJSON(){return this.bool}validate(e,t){return this.bool?L():Z(t,"","Always fails",e)}};Kc=e=>cs(e?.type,e),Wy=(e,t)=>cs(void 0,{...t,const:e}),Gy=class extends tt{type="object";properties;required;constructor(e,t){let r=[];for(let[s,i]of Object.entries(e||{}))ay(Ae(i),"properties must be managed schemas",i),i[Te].optional||r.push(s);let n=t?.additionalProperties===false?mo(false):t?.additionalProperties;r=r.length>0?r:void 0,super({...t,additionalProperties:n,properties:e,required:r},{template:(s,i)=>{let o=structuredClone(he(s)?s:{}),a={...o};if(this.properties)for(let[l,c]of Object.entries(this.properties)){let p=as(o,l);if(c.isOptional()&&i?.withOptional!==true&&p===void 0&&s===void 0)continue;let u=c.template(p,i);u!==void 0&&(a[l]=u);}if(!(Object.keys(a).length===0&&!i?.withExtendedOptional))return a},coerce:(s,i)=>{let o=Object.keys(this.properties),a=Vc(s),l=o.length>0&&Object.values(this.properties).every(p=>!p[Te].optional);if(ry(a)&&(i?.dropUnknown===true||l)&&(a=ly(a,o)),typeof a=="string"&&a.match(/^\{/)&&(a=JSON.parse(a)),typeof a!="object"||a===null)return;if(this.properties)for(let[p,u]of Object.entries(this.properties)){let f=a[p];f!==void 0&&(a[p]=u.coerce(f,i));}let c=this.additionalProperties;if(i?.dropUnknown!==true&&(!c||c.validate(null).valid)){let p=he(s)?s:{},u=Object.keys(p).filter(f=>!o.includes(f));for(let f of u)a[f]=c?c.coerce(p[f],i):p[f];}return a}}),this.properties=e,this.required=r;}strict(){return this.additionalProperties=mo(false),this[Te].raw.additionalProperties=false,this}partial(){for(let[,e]of Object.entries(this.properties))e[Te].optional=true;return this.required=void 0,this}children(e){let t=[];for(let[r,n]of Object.entries(this.properties)){let s=new Ir(n,e);s.appendInstancePath([r]),s.appendKeywordPath(["properties",r]),t.push(s);}return t}},us=(e,t)=>new Gy(e,t),zy=(e,t)=>us(e,t).strict(),Vy=(e,t)=>us(e,t).partial(),Ky=class extends tt{type="object";additionalProperties;constructor(e,t){super({...t,additionalProperties:e},{template:(r,n)=>n?.withExtendedOptional&&(r===void 0||!he(r))?{}:r}),this.additionalProperties=e;}children(e){let t=[],r=new Ir(this.additionalProperties,e);return r.appendKeywordPath(["additionalProperties"]),t.push(r),t}},Xy=(e,t)=>new Ky(e,t),Jy=class extends tt{type="string";constructor(e){super(e,{template:(t,r)=>r?.withExtendedOptional&&(t===void 0||!Je(t))?"":t,coerce:t=>et(t)?String(t):t});}toJSON(){let{pattern:e,"~standard":t,_resolver:r,...n}=this;return JSON.parse(JSON.stringify({...n,pattern:e instanceof RegExp?e.source:e}))}},Xc=e=>new Jy(e),Jc=(e,t,r)=>cs(e,r,{template:(n,s)=>s?.withExtendedOptional&&(n===void 0||!et(n))?r?.minimum??0:n,coerce:n=>{if(Je(n)){let s=t.parseFn(n);if(!Number.isNaN(s))return s}return n}}),Yc=e=>Jc("number",{parseFn:Number},e),Qc=e=>Jc("integer",{parseFn:Number.parseInt},e),Yy=class extends tt{constructor(e,t={}){super({...t,items:e},{template:r=>r===void 0||!Array.isArray(r)?[]:r,coerce:(r,n)=>{try{let s=typeof r=="string"?JSON.parse(r):r;if(!Array.isArray(s))return;if(Ae(this.items))for(let[i,o]of s.entries())s[i]=this.items.coerce(o,n);return s}catch{}return r}}),this.items=e,this.items=e;}type="array";children(e){let t=[];if(this.items){let r=new Ir(this.items,e);r.appendKeywordPath(["items"]),t.push(r);}return t}},Zc=(e,t)=>new Yy(e,t),eu=e=>cs("boolean",e,{template:(t,r)=>r?.withExtendedOptional&&(t===void 0||!go(t))?false:t,coerce:t=>{if(Je(t)&&["true","false","1","0"].includes(t))return t==="true"||t==="1";if(et(t)){if(t===1)return true;if(t===0)return false}return t}}),is=Symbol.for("unionType"),tu=class extends tt{[is];constructor(e,t,r){super({...r,[t]:e},{coerce:(n,s)=>{let i=r?.coerce;if(i!==void 0)return i.bind(this)(n,s);let o=ls(e,n,{ignoreUnsupported:true,resolver:s?.resolver,coerce:true});return o.length>0?o[0].coerce(n,s):n}}),this[is]=t;}get schemas(){return this[this[is]]}children(e){let t=[];for(let[r,n]of this.schemas.entries()){let s=new Ir(n,e);s.appendKeywordPath([this[is],r]),t.push(s);}return t}},Qy=(e,t)=>new tu(e,"anyOf",t),Zy=(e,t)=>new tu(e,"oneOf",t);ho=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),po=e=>typeof globalThis.structuredClone=="function"?globalThis.structuredClone(e):JSON.parse(JSON.stringify(e)),ew=["maximum","exclusiveMaximum","maxLength","maxItems","maxProperties"],tw=["minimum","exclusiveMinimum","minLength","minItems","minProperties"];sw=e=>e===true||e===false?e:null;ow=(e,t)=>{let r=JSON.parse(JSON.stringify({...t,allOf:e}));return tr(iw(r))},ru=class extends tt{$ref;constructor(e,t){if(!t&&!Ae(e))throw new Error("Ref not set");if(Ae(e)&&!e.$id)throw new Error("Ref must have an $id");let r=t??e?.$id;super({$ref:r},{coerce:(n,s)=>{let i=s?.resolver?.resolve(this.$ref);if(!Ae(i))throw new Error(`Ref not found: ${this.$ref}`);return i.coerce(n,s)}}),this.$ref=r;}},aw=(e,t)=>new ru(e,t),lw=e=>new ru(void 0,e),cw=e=>e(new tt({$ref:"#",coerce:(t,r)=>{let n=r?.resolver?.resolve("#");if(!Ae(n))throw new Error("Ref not found: #");return n.coerce(t,r)}})),nu={boolean:eu,any:Kc,literal:Wy,object:us,strictObject:zy,partialObject:Vy,record:Xy,string:Xc,number:Yc,integer:Qc,array:Zc,anyOf:Qy,oneOf:Zy,allOf:ow,ref:aw,refId:lw,recursive:cw};});function iu(e,t){if(typeof e!="string"){throw new Error("Email must be a string");}if(!nu.string({format:"email"}).validate(e).valid){throw new Error("Invalid email");}if(t?.domains?.length&&!t.domains.includes(e.split("@")[1])){throw new Error("Email domain not allowed");}return true}function ou(e,{panic:t=true,length:r=8,numbers:n=0,special:s=0}={}){try{if(typeof e!="string"){if(t)throw new Error("Password must be a string");return !1}if(e.length<r){if(t)throw new Error(`Password must be at least ${r} characters long`);return !1}if((e.match(/[0-9]/g)?.length??0)<n){if(t)throw new Error(`Password must contain at least ${n} numbers`);return !1}if((e.match(/[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/g)?.length??0)<s){if(t)throw new Error(`Password must contain at least ${s} special characters`);return !1}return !0}catch(i){if(t)throw i;return false}}function U(e,t='"'){return `${t}${e}${t}`}function au(e,t,r){if(t instanceof RegExp)return t.test(e);if(typeof t=="string")switch(!r&&t.startsWith("/")&&(r="regex"),r){case "regex":return new RegExp(t).test(e);case "sql":return new RegExp(t.replace("%",".*").replace("_",".")).test(e);case "wildcard":return new RegExp(t.replace("*",".*")).test(e);default:return e.includes(t)}return false}var Lr=g(()=>{su();});function wo(e){return typeof e=="number"?e:Number.parseInt(String(e),10)}var lu=g(()=>{});var cu=g(()=>{});var ht=g(()=>{Lc();Dc();jc();Fc();Mc();Rt();Lr();lu();cu();});var bo,uu=g(()=>{bo=(e,t,r)=>(n,s)=>{let i=-1;return o(0);async function o(a){if(a<=i)throw new Error("next() called multiple times");i=a;let l,c=false,p;if(e[a]?(p=e[a][0][0],n.req.routeIndex=a):p=a===e.length&&s||void 0,p)try{l=await p(n,()=>o(a+1));}catch(u){if(u instanceof Error&&t)n.error=u,l=await t(u,n),c=true;else throw u}else n.finalized===false&&r&&(l=await r(n));return l&&(n.finalized===false||c)&&(n.res=l),n}};});var pu=g(()=>{});var fu,mu=g(()=>{fu=Symbol();});async function uw(e,t){let r=await e.formData();return r?pw(r,t):{}}function pw(e,t){let r=Object.create(null);return e.forEach((n,s)=>{t.all||s.endsWith("[]")?fw(r,s,n):r[s]=n;}),t.dot&&Object.entries(r).forEach(([n,s])=>{n.includes(".")&&(mw(r,n,s),delete r[n]);}),r}var du,fw,mw,hu=g(()=>{So();du=async(e,t=Object.create(null))=>{let{all:r=false,dot:n=false}=t,i=(e instanceof ps?e.raw.headers:e.headers).get("Content-Type");return i?.startsWith("multipart/form-data")||i?.startsWith("application/x-www-form-urlencoded")?uw(e,{all:r,dot:n}):{}};fw=(e,t,r)=>{e[t]!==void 0?Array.isArray(e[t])?e[t].push(r):e[t]=[e[t],r]:t.endsWith("[]")?e[t]=[r]:e[t]=r;},mw=(e,t,r)=>{let n=e,s=t.split(".");s.forEach((i,o)=>{o===s.length-1?n[i]=r:((!n[i]||typeof n[i]!="object"||Array.isArray(n[i])||n[i]instanceof File)&&(n[i]=Object.create(null)),n=n[i]);});};});var xo,gu,dw,hw,fs,yu,ms,gw,_o,wu,Pt,ds,Eo,bu,Su,Eu,$o,nr=g(()=>{xo=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},gu=e=>{let{groups:t,path:r}=dw(e),n=xo(r);return hw(n,t)},dw=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let s=`@${n}`;return t.push([s,r]),s}),{groups:t,path:e}},hw=(e,t)=>{for(let r=t.length-1;r>=0;r--){let[n]=t[r];for(let s=e.length-1;s>=0;s--)if(e[s].includes(n)){e[s]=e[s].replace(n,t[r][1]);break}}return e},fs={},yu=(e,t)=>{if(e==="*")return "*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${e}#${t}`;return fs[n]||(r[2]?fs[n]=t&&t[0]!==":"&&t[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)]:fs[n]=[e,r[1],true]),fs[n]}return null},ms=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return t(r)}catch{return r}})}},gw=e=>ms(e,decodeURI),_o=e=>{let t=e.url,r=t.indexOf("/",t.indexOf(":")+4),n=r;for(;n<t.length;n++){let s=t.charCodeAt(n);if(s===37){let i=t.indexOf("?",n),o=t.indexOf("#",n),a=i===-1?o===-1?void 0:o:o===-1?i:Math.min(i,o),l=t.slice(r,a);return gw(l.includes("%25")?l.replace(/%25/g,"%2525"):l)}else if(s===63||s===35)break}return t.slice(r,n)},wu=e=>{let t=_o(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},Pt=(e,t,...r)=>(r.length&&(t=Pt(t,...r)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),ds=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),r=[],n="";return t.forEach(s=>{if(s!==""&&!/\:/.test(s))n+="/"+s;else if(/\:/.test(s))if(/\?/.test(s)){r.length===0&&n===""?r.push("/"):r.push(n);let i=s.replace("?","");n+="/"+i,r.push(n);}else n+="/"+s;}),r.filter((s,i,o)=>o.indexOf(s)===i)},Eo=e=>/[%+]/.test(e)?(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),e.indexOf("%")!==-1?ms(e,$o):e):e,bu=(e,t,r)=>{let n;if(!r&&t&&!/[%+]/.test(t)){let o=e.indexOf("?",8);if(o===-1)return;for(e.startsWith(t,o+1)||(o=e.indexOf(`&${t}`,o+1));o!==-1;){let a=e.charCodeAt(o+t.length+1);if(a===61){let l=o+t.length+2,c=e.indexOf("&",l);return Eo(e.slice(l,c===-1?void 0:c))}else if(a==38||isNaN(a))return "";o=e.indexOf(`&${t}`,o+1);}if(n=/[%+]/.test(e),!n)return}let s={};n??=/[%+]/.test(e);let i=e.indexOf("?",8);for(;i!==-1;){let o=e.indexOf("&",i+1),a=e.indexOf("=",i);a>o&&o!==-1&&(a=-1);let l=e.slice(i+1,a===-1?o===-1?void 0:o:a);if(n&&(l=Eo(l)),i=o,l==="")continue;let c;a===-1?c="":(c=e.slice(a+1,o===-1?void 0:o),n&&(c=Eo(c))),r?(s[l]&&Array.isArray(s[l])||(s[l]=[]),s[l].push(c)):s[l]??=c;}return t?s[t]:s},Su=bu,Eu=(e,t)=>bu(e,t,true),$o=decodeURIComponent;});var xu,ps,So=g(()=>{pu();mu();hu();nr();xu=e=>ms(e,$o),ps=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(e,t="/",r=[[]]){this.raw=e,this.path=t,this.#t=r,this.#e={};}param(e){return e?this.#r(e):this.#i()}#r(e){let t=this.#t[0][this.routeIndex][1][e],r=this.#s(t);return r&&/\%/.test(r)?xu(r):r}#i(){let e={},t=Object.keys(this.#t[0][this.routeIndex][1]);for(let r of t){let n=this.#s(this.#t[0][this.routeIndex][1][r]);n!==void 0&&(e[r]=/\%/.test(n)?xu(n):n);}return e}#s(e){return this.#t[1]?this.#t[1][e]:e}query(e){return Su(this.url,e)}queries(e){return Eu(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((r,n)=>{t[n]=r;}),t}async parseBody(e){return this.bodyCache.parsedBody??=await du(this,e)}#n=e=>{let{bodyCache:t,raw:r}=this,n=t[e];if(n)return n;let s=Object.keys(t)[0];return s?t[s].then(i=>(s==="json"&&(i=JSON.stringify(i)),new Response(i)[e]())):t[e]=r[e]()};json(){return this.#n("text").then(e=>JSON.parse(e))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(e,t){this.#e[e]=t;}valid(e){return this.#e[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[fu](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,e]])=>e)}get routePath(){return this.#t[0].map(([[,e]])=>e)[this.routeIndex].path}};});var _u,$u,vo,To=g(()=>{_u={Stringify:1,BeforeStream:2,Stream:3},$u=(e,t)=>{let r=new String(e);return r.isEscaped=true,r.callbacks=t,r},vo=async(e,t,r,n,s)=>{typeof e=="object"&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let i=e.callbacks;if(!i?.length)return Promise.resolve(e);s?s[0]+=e:s=[e];let o=Promise.all(i.map(a=>a({phase:t,buffer:s,context:n}))).then(a=>Promise.all(a.filter(Boolean).map(l=>vo(l,t,false,n,s))).then(()=>s[0]));return r?$u(await o,i):o};});var yw,Ao,Dr,vu,Tu=g(()=>{So();To();yw="text/plain; charset=UTF-8",Ao=(e,t)=>({"Content-Type":e,...t}),Dr=(e,t)=>new Response(e,t),vu=class{#e;#t;env={};#r;finalized=false;error;#i;#s;#n;#u;#l;#c;#a;#p;#f;constructor(e,t){this.#e=e,t&&(this.#s=t.executionCtx,this.env=t.env,this.#c=t.notFoundHandler,this.#f=t.path,this.#p=t.matchResult);}get req(){return this.#t??=new ps(this.#e,this.#f,this.#p),this.#t}get event(){if(this.#s&&"respondWith"in this.#s)return this.#s;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#s)return this.#s;throw Error("This context has no ExecutionContext")}get res(){return this.#n||=Dr(null,{headers:this.#a??=new Headers})}set res(e){if(this.#n&&e){e=Dr(e.body,e);for(let[t,r]of this.#n.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let n=this.#n.headers.getSetCookie();e.headers.delete("set-cookie");for(let s of n)e.headers.append("set-cookie",s);}else e.headers.set(t,r);}this.#n=e,this.finalized=true;}render=(...e)=>(this.#l??=t=>this.html(t),this.#l(...e));setLayout=e=>this.#u=e;getLayout=()=>this.#u;setRenderer=e=>{this.#l=e;};header=(e,t,r)=>{this.finalized&&(this.#n=Dr(this.#n.body,this.#n));let n=this.#n?this.#n.headers:this.#a??=new Headers;t===void 0?n.delete(e):r?.append?n.append(e,t):n.set(e,t);};status=e=>{this.#i=e;};set=(e,t)=>{this.#r??=new Map,this.#r.set(e,t);};get=e=>this.#r?this.#r.get(e):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#o(e,t,r){let n=this.#n?new Headers(this.#n.headers):this.#a??new Headers;if(typeof t=="object"&&"headers"in t){let i=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[o,a]of i)o.toLowerCase()==="set-cookie"?n.append(o,a):n.set(o,a);}if(r)for(let[i,o]of Object.entries(r))if(typeof o=="string")n.set(i,o);else {n.delete(i);for(let a of o)n.append(i,a);}let s=typeof t=="number"?t:t?.status??this.#i;return Dr(e,{status:s,headers:n})}newResponse=(...e)=>this.#o(...e);body=(e,t,r)=>this.#o(e,t,r);text=(e,t,r)=>!this.#a&&!this.#i&&!t&&!r&&!this.finalized?new Response(e):this.#o(e,t,Ao(yw,r));json=(e,t,r)=>this.#o(JSON.stringify(e),t,Ao("application/json",r));html=(e,t,r)=>{let n=s=>this.#o(s,t,Ao("text/html; charset=UTF-8",r));return typeof e=="object"?vo(e,_u.Stringify,false,{}).then(n):n(e)};redirect=(e,t)=>{let r=String(e);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,t??302)};notFound=()=>(this.#c??=()=>Dr(),this.#c(this))};});var re,Au,Cu,hs,gs,gt=g(()=>{re="ALL",Au="all",Cu=["get","post","put","delete","options","patch"],hs="Can not add a route since the matcher is already built.",gs=class extends Error{};});var jr,Co=g(()=>{jr="__COMPOSED_HANDLER";});var ww,Ru,ku,Ou=g(()=>{uu();Tu();gt();Co();nr();ww=e=>e.text("404 Not Found",404),Ru=(e,t)=>{if("getResponse"in e){let r=e.getResponse();return t.newResponse(r.body,r)}return console.error(e),t.text("Internal Server Error",500)},ku=class Pu{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(t={}){[...Cu,Au].forEach(i=>{this[i]=(o,...a)=>(typeof o=="string"?this.#e=o:this.#i(i,this.#e,o),a.forEach(l=>{this.#i(i,this.#e,l);}),this);}),this.on=(i,o,...a)=>{for(let l of [o].flat()){this.#e=l;for(let c of [i].flat())a.map(p=>{this.#i(c.toUpperCase(),this.#e,p);});}return this},this.use=(i,...o)=>(typeof i=="string"?this.#e=i:(this.#e="*",o.unshift(i)),o.forEach(a=>{this.#i(re,this.#e,a);}),this);let{strict:n,...s}=t;Object.assign(this,s),this.getPath=n??true?t.getPath??_o:wu;}#t(){let t=new Pu({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=ww;errorHandler=Ru;route(t,r){let n=this.basePath(t);return r.routes.map(s=>{let i;r.errorHandler===Ru?i=s.handler:(i=async(o,a)=>(await bo([],r.errorHandler)(o,()=>s.handler(o,a))).res,i[jr]=s.handler),n.#i(s.method,s.path,i);}),this}basePath(t){let r=this.#t();return r._basePath=Pt(this._basePath,t),r}onError=t=>(this.errorHandler=t,this);notFound=t=>(this.#r=t,this);mount(t,r,n){let s,i;n&&(typeof n=="function"?i=n:(i=n.optionHandler,n.replaceRequest===false?s=l=>l:s=n.replaceRequest));let o=i?l=>{let c=i(l);return Array.isArray(c)?c:[c]}:l=>{let c;try{c=l.executionCtx;}catch{}return [l.env,c]};s||=(()=>{let l=Pt(this._basePath,t),c=l==="/"?0:l.length;return p=>{let u=new URL(p.url);return u.pathname=u.pathname.slice(c)||"/",new Request(u,p)}})();let a=async(l,c)=>{let p=await r(s(l.req.raw),...o(l));if(p)return p;await c();};return this.#i(re,Pt(t,"*"),a),this}#i(t,r,n){t=t.toUpperCase(),r=Pt(this._basePath,r);let s={basePath:this._basePath,path:r,method:t,handler:n};this.router.add(t,r,[n,s]),this.routes.push(s);}#s(t,r){if(t instanceof Error)return this.errorHandler(t,r);throw t}#n(t,r,n,s){if(s==="HEAD")return (async()=>new Response(null,await this.#n(t,r,n,"GET")))();let i=this.getPath(t,{env:n}),o=this.router.match(s,i),a=new vu(t,{path:i,matchResult:o,env:n,executionCtx:r,notFoundHandler:this.#r});if(o[0].length===1){let c;try{c=o[0][0][0][0](a,async()=>{a.res=await this.#r(a);});}catch(p){return this.#s(p,a)}return c instanceof Promise?c.then(p=>p||(a.finalized?a.res:this.#r(a))).catch(p=>this.#s(p,a)):c??this.#r(a)}let l=bo(o[0],this.errorHandler,this.#r);return (async()=>{try{let c=await l(a);if(!c.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return c.res}catch(c){return this.#s(c,a)}})()}fetch=(t,...r)=>this.#n(t,r[1],r[0],t.method);request=(t,r,n,s)=>t instanceof Request?this.fetch(r?new Request(t,r):t,n,s):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${Pt("/",t)}`,r),n,s));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method));});}};});function Ro(e,t){let r=this.buildAllMatchers(),n=((s,i)=>{let o=r[s]||r[re],a=o[2][i];if(a)return a;let l=i.match(o[0]);if(!l)return [[],ys];let c=l.indexOf("",1);return [o[1][c],l]});return this.match=n,n(e,t)}var ys,ko=g(()=>{gt();ys=[];});function Sw(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===Fr||e===Mr?1:t===Fr||t===Mr?-1:e===ws?1:t===ws?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var ws,Fr,Mr,Ot,bw,Nu,Oo=g(()=>{ws="[^/]+",Fr=".*",Mr="(?:|/.*)",Ot=Symbol(),bw=new Set(".\\+*[^]$()");Nu=class Po{#e;#t;#r=Object.create(null);insert(t,r,n,s,i){if(t.length===0){if(this.#e!==void 0)throw Ot;if(i)return;this.#e=r;return}let[o,...a]=t,l=o==="*"?a.length===0?["","",Fr]:["","",ws]:o==="/*"?["","",Mr]:o.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(l){let p=l[1],u=l[2]||ws;if(p&&l[2]&&(u===".*"||(u=u.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(u))))throw Ot;if(c=this.#r[u],!c){if(Object.keys(this.#r).some(f=>f!==Fr&&f!==Mr))throw Ot;if(i)return;c=this.#r[u]=new Po,p!==""&&(c.#t=s.varIndex++);}!i&&p!==""&&n.push([p,c.#t]);}else if(c=this.#r[o],!c){if(Object.keys(this.#r).some(p=>p.length>1&&p!==Fr&&p!==Mr))throw Ot;if(i)return;c=this.#r[o]=new Po;}c.insert(a,r,n,s,i);}buildRegExpStr(){let r=Object.keys(this.#r).sort(Sw).map(n=>{let s=this.#r[n];return (typeof s.#t=="number"?`(${n})@${s.#t}`:bw.has(n)?`\\${n}`:n)+s.buildRegExpStr()});return typeof this.#e=="number"&&r.unshift(`#${this.#e}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};});var Iu,Lu=g(()=>{Oo();Iu=class{#e={varIndex:0};#t=new Nu;insert(e,t,r){let n=[],s=[];for(let o=0;;){let a=false;if(e=e.replace(/\{[^}]+\}/g,l=>{let c=`@\\${o}`;return s[o]=[c,l],o++,a=true,c}),!a)break}let i=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let o=s.length-1;o>=0;o--){let[a]=s[o];for(let l=i.length-1;l>=0;l--)if(i[l].indexOf(a)!==-1){i[l]=i[l].replace(a,s[o][1]);break}}return this.#t.insert(i,t,n,this.#e,r),n}buildRegExp(){let e=this.#t.buildRegExpStr();if(e==="")return [/^$/,[],[]];let t=0,r=[],n=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(s,i,o)=>i!==void 0?(r[++t]=Number(i),"$()"):(o!==void 0&&(n[Number(o)]=++t),"")),[new RegExp(`^${e}`),r,n]}};});function ju(e){return Du[e]??=new RegExp(e==="*"?"":`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(t,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function xw(){Du=Object.create(null);}function _w(e){let t=new Iu,r=[];if(e.length===0)return Ew;let n=e.map(c=>[!/\*|\/:/.test(c[0]),...c]).sort(([c,p],[u,f])=>c?1:u?-1:p.length-f.length),s=Object.create(null);for(let c=0,p=-1,u=n.length;c<u;c++){let[f,h,d]=n[c];f?s[h]=[d.map(([w])=>[w,Object.create(null)]),ys]:p++;let m;try{m=t.insert(h,p,f);}catch(w){throw w===Ot?new gs(h):w}f||(r[p]=d.map(([w,y])=>{let E=Object.create(null);for(y-=1;y>=0;y--){let[T,v]=m[y];E[T]=v;}return [w,E]}));}let[i,o,a]=t.buildRegExp();for(let c=0,p=r.length;c<p;c++)for(let u=0,f=r[c].length;u<f;u++){let h=r[c][u]?.[1];if(!h)continue;let d=Object.keys(h);for(let m=0,w=d.length;m<w;m++)h[d[m]]=a[h[d[m]]];}let l=[];for(let c in o)l[c]=r[o[c]];return [i,l,s]}function sr(e,t){if(e){for(let r of Object.keys(e).sort((n,s)=>s.length-n.length))if(ju(r).test(t))return [...e[r]]}}var Ew,Du,bs,No=g(()=>{gt();nr();ko();Oo();Lu();Ew=[/^$/,[],Object.create(null)],Du=Object.create(null);bs=class{name="RegExpRouter";#e;#t;constructor(){this.#e={[re]:Object.create(null)},this.#t={[re]:Object.create(null)};}add(e,t,r){let n=this.#e,s=this.#t;if(!n||!s)throw new Error(hs);n[e]||[n,s].forEach(a=>{a[e]=Object.create(null),Object.keys(a[re]).forEach(l=>{a[e][l]=[...a[re][l]];});}),t==="/*"&&(t="*");let i=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let a=ju(t);e===re?Object.keys(n).forEach(l=>{n[l][t]||=sr(n[l],t)||sr(n[re],t)||[];}):n[e][t]||=sr(n[e],t)||sr(n[re],t)||[],Object.keys(n).forEach(l=>{(e===re||e===l)&&Object.keys(n[l]).forEach(c=>{a.test(c)&&n[l][c].push([r,i]);});}),Object.keys(s).forEach(l=>{(e===re||e===l)&&Object.keys(s[l]).forEach(c=>a.test(c)&&s[l][c].push([r,i]));});return}let o=ds(t)||[t];for(let a=0,l=o.length;a<l;a++){let c=o[a];Object.keys(s).forEach(p=>{(e===re||e===p)&&(s[p][c]||=[...sr(n[p],c)||sr(n[re],c)||[]],s[p][c].push([r,i-l+a+1]));});}}match=Ro;buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#t).concat(Object.keys(this.#e)).forEach(t=>{e[t]||=this.#r(t);}),this.#e=this.#t=void 0,xw(),e}#r(e){let t=[],r=e===re;return [this.#e,this.#t].forEach(n=>{let s=n[e]?Object.keys(n[e]).map(i=>[i,n[e][i]]):[];s.length!==0?(r||=true,t.push(...s)):e!==re&&t.push(...Object.keys(n[re]).map(i=>[i,n[re][i]]));}),r?_w(t):null}};});var Fu=g(()=>{gt();ko();No();});var Mu=g(()=>{No();Fu();});var Io,Uu=g(()=>{gt();Io=class{name="SmartRouter";#e=[];#t=[];constructor(e){this.#e=e.routers;}add(e,t,r){if(!this.#t)throw new Error(hs);this.#t.push([e,t,r]);}match(e,t){if(!this.#t)throw new Error("Fatal error");let r=this.#e,n=this.#t,s=r.length,i=0,o;for(;i<s;i++){let a=r[i];try{for(let l=0,c=n.length;l<c;l++)a.add(...n[l]);o=a.match(e,t);}catch(l){if(l instanceof gs)continue;throw l}this.match=a.match.bind(a),this.#e=[a],this.#t=void 0;break}if(i===s)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#t||this.#e.length!==1)throw new Error("No active router has been determined yet.");return this.#e[0]}};});var Bu=g(()=>{Uu();});var Ur,$w,qu,Wu=g(()=>{gt();nr();Ur=Object.create(null),$w=e=>{for(let t in e)return true;return false},qu=class Hu{#e;#t;#r;#i=0;#s=Ur;constructor(t,r,n){if(this.#t=n||Object.create(null),this.#e=[],t&&r){let s=Object.create(null);s[t]={handler:r,possibleKeys:[],score:0},this.#e=[s];}this.#r=[];}insert(t,r,n){this.#i=++this.#i;let s=this,i=gu(r),o=[];for(let a=0,l=i.length;a<l;a++){let c=i[a],p=i[a+1],u=yu(c,p),f=Array.isArray(u)?u[0]:c;if(f in s.#t){s=s.#t[f],u&&o.push(u[1]);continue}s.#t[f]=new Hu,u&&(s.#r.push(u),o.push(u[1])),s=s.#t[f];}return s.#e.push({[t]:{handler:n,possibleKeys:o.filter((a,l,c)=>c.indexOf(a)===l),score:this.#i}}),s}#n(t,r,n,s,i){for(let o=0,a=r.#e.length;o<a;o++){let l=r.#e[o],c=l[n]||l[re],p={};if(c!==void 0&&(c.params=Object.create(null),t.push(c),s!==Ur||i&&i!==Ur))for(let u=0,f=c.possibleKeys.length;u<f;u++){let h=c.possibleKeys[u],d=p[c.score];c.params[h]=i?.[h]&&!d?i[h]:s[h]??i?.[h],p[c.score]=true;}}}search(t,r){let n=[];this.#s=Ur;let i=[this],o=xo(r),a=[],l=o.length,c=null;for(let p=0;p<l;p++){let u=o[p],f=p===l-1,h=[];for(let m=0,w=i.length;m<w;m++){let y=i[m],E=y.#t[u];E&&(E.#s=y.#s,f?(E.#t["*"]&&this.#n(n,E.#t["*"],t,y.#s),this.#n(n,E,t,y.#s)):h.push(E));for(let T=0,v=y.#r.length;T<v;T++){let C=y.#r[T],A=y.#s===Ur?{}:{...y.#s};if(C==="*"){let D=y.#t["*"];D&&(this.#n(n,D,t,y.#s),D.#s=A,h.push(D));continue}let[$,_,I]=C;if(!u&&!(I instanceof RegExp))continue;let b=y.#t[$];if(I instanceof RegExp){if(c===null){c=new Array(l);let F=r[0]==="/"?1:0;for(let S=0;S<l;S++)c[S]=F,F+=o[S].length+1;}let D=r.substring(c[p]),O=I.exec(D);if(O){if(A[_]=O[0],this.#n(n,b,t,y.#s,A),$w(b.#t)){b.#s=A;let F=O[0].match(/\//)?.length??0;(a[F]||=[]).push(b);}continue}}(I===true||I.test(u))&&(A[_]=u,f?(this.#n(n,b,t,A,y.#s),b.#t["*"]&&this.#n(n,b.#t["*"],t,A,y.#s)):(b.#s=A,h.push(b)));}}let d=a.shift();i=d?h.concat(d):h;}return n.length>1&&n.sort((p,u)=>p.score-u.score),[n.map(({handler:p,params:u})=>[p,u])]}};});var Lo,Gu=g(()=>{nr();Wu();Lo=class{name="TrieRouter";#e;constructor(){this.#e=new qu;}add(e,t,r){let n=ds(t);if(n){for(let s=0,i=n.length;s<i;s++)this.#e.insert(e,n[s],r);return}this.#e.insert(e,t,r);}match(e,t){return this.#e.search(e,t)}};});var zu=g(()=>{Gu();});var Do,Vu=g(()=>{Ou();Mu();Bu();zu();Do=class extends ku{constructor(e={}){super(e),this.router=e.router??new Io({routers:[new bs,new Lo]});}};});var Ku=g(()=>{Vu();});function jo(e){return !e||typeof e!="object"?false:e.code==="EADDRINUSE"}function Xu(e,t){return new Promise((r,n)=>{let s=o=>{e.off("listening",i),n(o);},i=()=>{e.off("error",s),r();};e.once("error",s),e.once("listening",i),e.listen(t);})}function Fo(e){console.error(),console.error(Br.default.red(`Cannot start server: Port ${Br.default.bold(String(e))} is already in use.`)),console.error(Br.default.red(`Stop the process using that port, or set a different ${Br.default.bold("api.port")} in your config.`)),console.error(),process.exit(1);}var Br,Ju=g(()=>{Br=te(ae());});function qr(e){let t=[],r=e??"",n=r.toLowerCase(),s=new TextEncoder().encode(r).length;if(!r)return t.push("auth.jwt_secret is empty"),{strong:false,reasons:t};vw.has(r)&&t.push(`matches Supalite development default "${r}"`),s<32&&t.push(`is ${s} bytes; use at least 32 bytes for production secrets`),[/[a-z]/.test(r),/[A-Z]/.test(r),/[0-9]/.test(r),/[^A-Za-z0-9]/.test(r)].filter(Boolean).length<3&&t.push("uses too little character variety"),/^(.)\1{7,}$/.test(r)?t.push("is one repeated character"):Aw(r)&&t.push("contains an obvious repeated pattern");let o=Tw.find(a=>n.includes(a));return o&&t.push(`contains placeholder term "${o}"`),{strong:t.length===0,reasons:t}}function Aw(e){if(e.length<8)return false;for(let t=2;t<=Math.floor(e.length/2);t++){if(e.length%t!==0)continue;if(e.slice(0,t).repeat(e.length/t)===e)return true}return false}var vw,Tw,Mo=g(()=>{vw=new Set(["unsafe-secret-change-me","dev-secret-change-me"]),Tw=["change-me","changeme","secret","password","passwd","test","dev"];});var Yu,Qu=g(()=>{Yu=/^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;});var Bo,Zu,Cw,Uo,qo=g(()=>{Bo=(e,t=Uo)=>{let r=/\.([a-zA-Z0-9]+?)$/,n=e.match(r);if(!n)return;let s=t[n[1]];return s&&s.startsWith("text")&&(s+="; charset=utf-8"),s},Zu=e=>{for(let t in Uo)if(Uo[t]===e)return t},Cw={aac:"audio/aac",avi:"video/x-msvideo",avif:"image/avif",av1:"video/av1",bin:"application/octet-stream",bmp:"image/bmp",css:"text/css",csv:"text/csv",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gif:"image/gif",gz:"application/gzip",htm:"text/html",html:"text/html",ico:"image/x-icon",ics:"text/calendar",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript",json:"application/json",jsonld:"application/ld+json",map:"application/json",mid:"audio/x-midi",midi:"audio/x-midi",mjs:"text/javascript",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",pdf:"application/pdf",png:"image/png",rtf:"application/rtf",svg:"image/svg+xml",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain",wasm:"application/wasm",webm:"video/webm",weba:"audio/webm",webmanifest:"application/manifest+json",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xml:"application/xml",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2",gltf:"model/gltf+json",glb:"model/gltf-binary"},Uo=Cw;});var ep,tp=g(()=>{ep=(...e)=>{let t=e.filter(s=>s!=="").join("/");t=t.replace(/(?<=\/)\/+/g,"");let r=t.split("/"),n=[];for(let s of r)s===".."&&n.length>0&&n.at(-1)!==".."?n.pop():s!=="."&&n.push(s);return n.join("/")||"."};});var rp,Rw,kw,np,sp=g(()=>{Qu();qo();tp();rp={br:".br",zstd:".zst",gzip:".gz"},Rw=Object.keys(rp),kw="index.html",np=e=>{let t=e.root??"./",r=e.path,n=e.join??ep;return async(s,i)=>{if(s.finalized)return i();let o;if(e.path)o=e.path;else try{if(o=decodeURIComponent(s.req.path),/(?:^|[\/\\])\.\.(?:$|[\/\\])/.test(o))throw new Error}catch{return await e.onNotFound?.(s.req.path,s),i()}let a=n(t,!r&&e.rewriteRequestPath?e.rewriteRequestPath(o):o);e.isDir&&await e.isDir(a)&&(a=n(a,kw));let l=e.getContent,c=await l(a,s);if(c instanceof Response)return s.newResponse(c.body,c);if(c){let p=e.mimes&&Bo(a,e.mimes)||Bo(a);if(s.header("Content-Type",p||"application/octet-stream"),e.precompressed&&(!p||Yu.test(p))){let u=new Set(s.req.header("Accept-Encoding")?.split(",").map(f=>f.trim()));for(let f of Rw){if(!u.has(f))continue;let h=await l(a+rp[f],s);if(h){c=h,s.header("Content-Encoding",f),s.header("Vary","Accept-Encoding",{append:true});break}}}return await e.onFound?.(a,s),s.body(c)}await e.onNotFound?.(a,s),await i();}};});var ip,op=g(()=>{sp();ip=e=>async function(r,n){return np({...e,getContent:async o=>{let a=Bun.file(o);return await a.exists()?a:null},join:join,isDir:async o=>{let a;try{a=(await stat$1(o)).isDirectory();}catch{}return a}})(r,n)};});var ap=g(()=>{});var lp,cp=g(()=>{ap();lp=(e,t)=>{for(let[r,n]of Object.entries(t)){let s=new RegExp("/:"+r+"(?:{[^/]+})?\\??");e=e.replace(s,n?`/${n}`:"");}return e};});var Nw,up,pp=g(()=>{Nw=1024,up=({concurrency:e,interval:t}={})=>{if(e||=Nw,e===1/0)return {run:async s=>s()};let r=new Set,n=async(s,i,o)=>{if(r.size>=e)return i||=new Promise(c=>o=c),setTimeout(()=>n(s,i,o)),i;let a={};r.add(a);let l=await s();return t?setTimeout(()=>r.delete(a),t):r.delete(a),o?(o(l),i):l};return {run:n}};});var fp,Ho,mp=g(()=>{Co();fp=e=>e.length>1,Ho=e=>e[jr]?Ho(e[jr]):e;});var dp,Iw,Lw,Dw,jw,Hr,hp,Wo,Go=g(()=>{gt();mp();dp=e=>e.split(/[\/\\]/).slice(0,-1).join("/"),Iw=e=>e.replace(/(\\)/g,"/").replace(/\/$/g,""),Lw=(e,t)=>{e.length===0||t?e.push(".."):e.pop();},Dw=(e,t)=>{e=e.replace(/^\.(?!.)/,""),e!==""&&t.push(e);},jw=(e,t)=>{let r=false;for(let n of e)n===".."?(Lw(t,r),r=true):(Dw(n,t),r=false);},Hr=(...e)=>{e=e.map(Iw);let t=[];return jw(e.join("/").split("/"),t),(e[0][0]==="/"?"/":"")+t.join("/")},hp=e=>e.routes.reduce((t,{method:r,handler:n,path:s})=>{let i=Ho(n);return ["GET",re].includes(r)&&!fp(i)&&t.push({path:s}),t},[]),Wo=e=>e.split("/").some(t=>t.startsWith(":")||t.includes("*"));});var gp,Ss,zo=g(()=>{Go();gp="HONO_SSG_CONTEXT",Ss="x-hono-disable-ssg",(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[Ss]:"true"}})}catch{return null}})();});var yp=g(()=>{To();});var Vo,Ko=g(()=>{yp();Vo=()=>({afterResponseHook:e=>e.status!==200?false:e});});var Fw,Mw,Uw,Bw,qw,Hw,Ww,Gw,zw,Vw,Kw,wp,Xw,bp,Sp=g(()=>{cp();pp();qo();zo();Ko();Go();Fw=2,Mw="text/plain",Uw="./static",Bw=(e,t,r,n)=>{let s=Ww(r,n);return e.endsWith(`.${s}`)?Hr(t,e):e==="/"?Hr(t,`index.${s}`):e.endsWith("/")?Hr(t,e,`index.${s}`):Hr(t,`${e}.${s}`)},qw=async e=>{let t=e.headers.get("Content-Type");try{return t?.includes("text")||t?.includes("json")?await e.text():await e.arrayBuffer()}catch(r){throw new Error(`Error processing response: ${r instanceof Error?r.message:"Unknown error"}`)}},Hw={"text/html":"html","text/xml":"xml","application/xml":"xml","application/yaml":"yaml"},Ww=(e,t)=>{let r=t||Hw;return e in r?r[e]:Zu(e)||"html"},Gw=e=>Array.isArray(e)?async t=>{let r=t;for(let n of e){let s=await n(r);if(s===false)return false;s instanceof Request&&(r=s);}return r}:e,zw=e=>Array.isArray(e)?async t=>{let r=t;for(let n of e){let s=await n(r);if(s===false)return false;s instanceof Response&&(r=s);}return r}:e,Vw=(e,t,r)=>Array.isArray(e)?async n=>{for(let s of e)await s(n,t,r);}:e,Kw=function*(e,t,r,n){let s="http://localhost",i=up({concurrency:n});for(let o of hp(e)){let a=new URL(o.path,s).toString(),l=new Request(a);yield new Promise(async(c,p)=>{try{if(t){let f=await t(l);if(!f){c(void 0);return}l=f;}if(await i.run(()=>e.fetch(l)),!l.ssgParams){if(Wo(o.path)){c(void 0);return}l.ssgParams=[{}];}let u={method:l.method,headers:l.headers};c((function*(){for(let f of l.ssgParams)yield new Promise(async(h,d)=>{try{let m=lp(o.path,f),w=await i.run(()=>e.request(m,u,{[gp]:!0}));if(w.headers.get(Ss)){h(void 0);return}if(r){let T=await r(w);if(!T){h(void 0);return}w=T;}let y=w.headers.get("Content-Type")?.split(";")[0]||Mw,E=await qw(w);h({routePath:m,mimeType:y,content:E});}catch(m){d(m);}});})());}catch(u){p(u);}});}},wp=new Set,Xw=async(e,t,r,n)=>{let s=await e;if(!s)return;let{routePath:i,content:o,mimeType:a}=s,l=Bw(i,r,a,n),c=dp(l);return wp.has(c)||(await t.mkdir(c,{recursive:true}),wp.add(c)),typeof o=="string"?await t.writeFile(l,o):o instanceof ArrayBuffer&&await t.writeFile(l,new Uint8Array(o)),l},bp=async(e,t,r)=>{let n,s=[],i=[],o=r?.plugins||[Vo()],a=[],l=[],c=[];r?.beforeRequestHook&&a.push(...Array.isArray(r.beforeRequestHook)?r.beforeRequestHook:[r.beforeRequestHook]),r?.afterResponseHook&&l.push(...Array.isArray(r.afterResponseHook)?r.afterResponseHook:[r.afterResponseHook]),r?.afterGenerateHook&&c.push(...Array.isArray(r.afterGenerateHook)?r.afterGenerateHook:[r.afterGenerateHook]);for(let p of o)p.beforeRequestHook&&a.push(...Array.isArray(p.beforeRequestHook)?p.beforeRequestHook:[p.beforeRequestHook]),p.afterResponseHook&&l.push(...Array.isArray(p.afterResponseHook)?p.afterResponseHook:[p.afterResponseHook]),p.afterGenerateHook&&c.push(...Array.isArray(p.afterGenerateHook)?p.afterGenerateHook:[p.afterGenerateHook]);try{let p=r?.dir??Uw,u=r?.concurrency??Fw,f=Gw(a.length>0?a:[w=>w]),h=zw(l.length>0?l:[w=>w]),d=Kw(e,f,h,u);for(let w of d)s.push(w.then(y=>{if(y)for(let E of y)i.push(Xw(E,t,p,r?.extensionMap).catch(T=>T));}));await Promise.all(s);let m=[];for(let w of i){let y=await w;if(typeof y=="string")m.push(y);else if(y)throw y}n={success:!0,files:m};}catch(p){let u=p instanceof Error?p:new Error(String(p));n={success:false,files:[],error:u};}return c.length>0&&await Vw(c,t,r)(n,t,r),n};});var Ep=g(()=>{Sp();zo();Ko();});var Jw,Xo,xp,_p=g(()=>{Ep();(({write:Jw}=Bun)),Xo={writeFile:async(e,t)=>{await Jw(e,t);},mkdir:async()=>{}},xp=async(e,t)=>bp(e,Xo,t);});var $p,vp,Tp,Ap=g(()=>{$p=class{#e;constructor(e){this.#e=e,this.raw=e.raw,this.url=e.url?new URL(e.url):null,this.protocol=e.protocol??null;}send(e,t){this.#e.send(e,t??{});}raw;binaryType="arraybuffer";get readyState(){return this.#e.readyState}url;protocol;close(e,t){this.#e.close(e,t);}},vp=e=>new MessageEvent("message",{data:e}),Tp=e=>((...t)=>{if(typeof t[0]=="function"){let[r,n]=t;return async function(i,o){let a=await r(i),l=await e(i,a,n);if(l)return l;await o();}}else {let[r,n,s]=t;return (async()=>{let i=await e(r,n,s);if(!i)throw new Error("Failed to upgrade WebSocket");return i})()}});});var ir,Es=g(()=>{ir=e=>"server"in e.env?e.env.server:e.env;});var Jo,Yo,Qo,Cp,Rp=g(()=>{Ap();Es();Jo=e=>new $p({send:(t,r)=>{e.send(t,r?.compress);},raw:e,readyState:e.readyState,url:e.data.url,protocol:e.data.protocol,close(t,r){e.close(t,r);}}),Yo=Tp((e,t)=>{let r=ir(e);if(!r)throw new TypeError("env has to include the 2nd argument of fetch.");if(r.upgrade(e.req.raw,{data:{events:t,url:new URL(e.req.url),protocol:e.req.url}}))return new Response(null)}),Qo={open(e){let t=e.data.events;t.onOpen&&t.onOpen(new Event("open"),Jo(e));},close(e,t,r){let n=e.data.events;n.onClose&&n.onClose(new CloseEvent("close",{code:t,reason:r}),Jo(e));},message(e,t){let r=e.data.events;if(r.onMessage){let n=typeof t=="string"?t:t.buffer;r.onMessage(vp(n),Jo(e));}}},Cp=()=>({upgradeWebSocket:Yo,websocket:Qo});});var kp,Pp=g(()=>{Es();kp=e=>{let t=ir(e);if(!t)throw new TypeError("env has to include the 2nd argument of fetch.");if(typeof t.requestIP!="function")throw new TypeError("server.requestIP is not a function.");let r=t.requestIP(e.req.raw);return r?{remote:{address:r.address,addressType:r.family==="IPv6"||r.family==="IPv4"?r.family:void 0,port:r.port}}:{remote:{}}};});var Op={};de(Op,{bunFileSystemModule:()=>Xo,createBunWebSocket:()=>Cp,getBunServer:()=>ir,getConnInfo:()=>kp,serveStatic:()=>ip,toSSG:()=>xp,upgradeWebSocket:()=>Yo,websocket:()=>Qo});var Np=g(()=>{op();_p();Rp();Pp();Es();});async function xs(e,t={port:3e3}){if(e.config.auth?.enabled){let s=qr(e.config.auth.jwt_secret);s.strong||console.warn(`[auth] auth.jwt_secret is weak \u2014 do not use it in production:
63
+ `+s.reasons.map(i=>` - it ${i}`).join(`
64
+ `));}let r=es(),n=t.port??3e3;if(Or()){let s=await Promise.resolve().then(()=>(Np(),Op)).then(o=>o.serveStatic),i;try{i=Bun.serve({fetch:Lp(e,r,s).fetch,port:n});}catch(o){throw jo(o)&&Fo(n),o}return async()=>{await i.stop();}}else {let{createAdaptorServer:s}=await import('@hono/node-server'),i=await import('@hono/node-server/serve-static').then(a=>a.serveStatic),o=s({fetch:Lp(e,r,i).fetch});try{await Xu(o,n);}catch(a){throw jo(a)&&Fo(n),a}return ()=>new Promise(a=>{o.close(()=>{a(void 0);});})}}function Lp(e,t,r){return new Do().use("/favicon.ico",r({path:Me__default.join(t,"static","favicon.ico")})).use("/fonts/*",r({root:Me__default.join(t,"static"),onNotFound:n=>{console.log("fonts not found",n,process.cwd());}})).use("/static/*",r({root:t,onNotFound(n){console.log("not found",n,process.cwd());}})).all("*",async n=>e.fetch(n.req.raw))}var Zo=g(()=>{ht();Ku();Ju();$e();Mo();});var nt,ea=g(()=>{Tt();nt=class e{root;constructor(t,r){let n=r??e.projectDir();this.root=Me__default.join(n,t??"");}ensureRoot(){ke(this.root);}static homeDir(){return Me__default.join(Yw.homedir(),".lite")}static projectDir(){return Me__default.join(process.cwd(),"supabase")}deleteAll(t=false){try{Hn.rmSync(this.root,{recursive:!0});}catch(r){if(!t)throw r}this.ensureRoot();}delete(t,r=false){try{Hn.unlinkSync(Me__default.join(this.root,t));}catch(n){if(!r)throw n}}write(t,r,n=false){try{this.ensureRoot(),Hn.writeFileSync(Me__default.join(this.root,t),r);}catch(s){if(!n)throw s}}read(t,r=false){try{return Hn.readFileSync(Me__default.join(this.root,t),"utf8")}catch(n){if(!r)throw n}}relativePath(t){return t?Me__default.relative(process.cwd(),Me__default.join(this.root,t)):this.root}path(t){return t?Me__default.join(this.root,t):this.root}};});var Wr,ta=g(()=>{Wr=process.env.SUPALITE_CLOUD_URL??(process.env.LOCAL?"http://localhost:2000":"https://www.lite.dev");});var vs,Dp=g(()=>{Tt();vs=class{root;constructor(t){this.root=t??Me__default.join(Yw.homedir(),".lite","auth"),ke(this.root);}async getItem(t){try{return Hn.readFileSync(Me__default.join(this.root,t+".json"),"utf8")}catch{return null}}async setItem(t,r){Hn.writeFileSync(Me__default.join(this.root,t+".json"),r);}async removeItem(t){try{Hn.unlinkSync(Me__default.join(this.root,t+".json"));}catch{return}}};});var or,na=g(()=>{ta();ea();Dp();or=class{constructor(t){this.config=t;this.tempFs=new nt(".temp",this.config.root),this.projectFs=new nt("supabase",this.config.root),this.schemaFs=new nt("schemas",this.config.root),this.authStorage=this.config.authStorage??new vs(Me__default.join(nt.homeDir(),"auth")),this._client=this.config.withSupabaseClient!==false?this.config.client??createClient(this.config.host??Wr,process.env.SUPALITE_CLOUD_ANON_KEY??"...",{auth:{storage:this.authStorage}}):void 0;}tempFs;projectFs;schemaFs;_client;authStorage;async fetch(t,r){if(!this.config.token)throw new Error("Not authenticated, sign in first.");let n=t instanceof URL?t:new URL(t,this.config.host??Wr);return await fetch(n,{...r,headers:{...r?.headers,Authorization:`Bearer ${this.config.token}`}})}};});var ar,sa=g(()=>{na();ar=class extends or{constructor(r){super(r);this.config=r;}get client(){if(!this._client)throw new Error("Supabase client not initialized");return this._client}projectRef(){return this.tempFs.read("project-ref",true)}projectUrl(r){let n=new URL(this.config.host),s=n.hostname==="localhost"?"supalite.local":n.hostname,i=s.split(".").filter(a=>a!=="www"),o=i.length>=2?i.slice(-2).join("."):s;return `${n.protocol}//${r}.${o}${n.port?`:${n.port}`:""}`}};});function tb(e){let t=Me.extname(e).toLowerCase();return {".html":"text/html",".css":"text/css",".js":"application/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".webp":"image/webp",".avif":"image/avif",".pdf":"application/pdf",".txt":"text/plain",".xml":"application/xml",".zip":"application/zip",".mp4":"video/mp4",".webm":"video/webm",".mp3":"audio/mpeg",".wav":"audio/wav",".woff":"font/woff",".woff2":"font/woff2"}[t]??"application/octet-stream"}var As,jp=g(()=>{ht();As=class{driver=pe;basePath;constructor(t){this.basePath=Me.resolve(t.basePath);}filePath(t,r){return Me.join(this.basePath,t,r)}async ensureDir(t){await pe.mkdir(Me.dirname(t),{recursive:true});}async getObject(t,r,n,s){let i=this.filePath(t,r),o=await pe.stat(i),a=`"${createHash("md5").update(`${i}:${o.mtimeMs}`).digest("hex")}"`;if(s?.ifNoneMatch===a)return {httpStatusCode:304,metadata:this.buildMetadata(o,a,r)};if(s?.ifModifiedSince){let f=new Date(s.ifModifiedSince);if(o.mtime<=f)return {httpStatusCode:304,metadata:this.buildMetadata(o,a,r)}}let l,c,p=o.size,u=200;if(s?.range){let f=s.range.match(/^bytes=(\d+)-(\d*)$/);if(f){let h=Number.parseInt(f[1],10),d=f[2]?Number.parseInt(f[2],10):o.size-1;p=d-h+1,c=`bytes ${h}-${d}/${o.size}`,u=206,l=(await pe.open(i,"r")).readableWebStream();}else l=(await pe.open(i,"r")).readableWebStream();}else l=(await pe.open(i,"r")).readableWebStream();return {httpStatusCode:u,metadata:{...this.buildMetadata(o,a,r),contentLength:p,contentRange:c},body:l}}async uploadObject(t,r,n,s,i,o){let a=this.filePath(t,r);await this.ensureDir(a);let l;if(s instanceof Uint8Array||Buffer.isBuffer(s))l=s;else {let u=[],f=s.getReader();for(;;){let{done:h,value:d}=await f.read();if(h)break;u.push(d);}l=Buffer.concat(u);}await pe.writeFile(a,l);let c=await pe.stat(a),p=`"${createHash("md5").update(l).digest("hex")}"`;return {cacheControl:o,contentLength:c.size,size:c.size,mimetype:i,lastModified:c.mtime,eTag:p}}async deleteObject(t,r,n){let s=this.filePath(t,r);await pe.unlink(s).catch(i=>{if(i.code!=="ENOENT")throw i});}async deleteObjects(t,r){for(let n of r)await this.deleteObject(t,n,void 0);}async copyObject(t,r,n,s,i){let o=this.filePath(t,r),a=this.filePath(t,s);await this.ensureDir(a),await pe.copyFile(o,a);let l=await pe.stat(a),c=await pe.readFile(a);return {httpStatusCode:200,eTag:`"${createHash("md5").update(c).digest("hex")}"`,lastModified:l.mtime}}async headObject(t,r,n){let s=this.filePath(t,r),i=await pe.stat(s),o=`"${createHash("md5").update(`${s}:${i.mtimeMs}`).digest("hex")}"`;return this.buildMetadata(i,o,r)}async privateAssetUrl(t,r,n){return `file://${this.filePath(t,r)}`}buildMetadata(t,r,n){return {cacheControl:"no-cache",contentLength:wo(t.size),size:wo(t.size),mimetype:tb(n),lastModified:t.mtime,eTag:r}}};});async function We(e,t,r){try{return await rb(e)}catch(n){throw n?.code==="ERR_MODULE_NOT_FOUND"||/Cannot find package/.test(String(n?.message))?new Error(`Driver '${t}' selected but '${r}' is not installed. Run: bun add ${r}`):n}}var rb,lr=g(()=>{rb=new Function("spec","return import(spec)");});var Gr,sb,Cs,Mp=g(()=>{sa();Zt();Gr=te(ae());Rr();Yt();jp();lr();Qi();eo();er();sb=["toml","json","ts","mts","js","mjs","cjs"],Cs=class extends ar{ref(){return this.projectRef()}setRef(t){return this.tempFs.write("project-ref",t),this}link(t){return this.setRef(t.id),t}unlink(){return this.tempFs.delete("project-ref"),this}url(){let t=this.ref();if(!t)throw new Error("No project linked");return this.projectUrl(t)}async getConfigPath(t){let r=Me__default.relative(process.cwd(),ye.config_dir);if(!t)for(let n of sb){let s=Me__default.join(r,`config.${n}`);if(await pe__default.access(s).then(()=>true).catch(()=>false)){t=s;break}}return t}async readConfig(t){let r=await this.getConfigPath(t);if(!r)return {};Ze(Gr.default.dim(`Using config file: ${Gr.default.cyan(`./${r}`)}`));let n=Me__default.dirname(Me__default.resolve(r));Kn(n);let s=r.split(".").pop(),i;switch(s){case "toml":i=Ct(await pe__default.readFile(r,"utf-8"));break;case "json":i=JSON.parse(await pe__default.readFile(r,"utf-8"));break;case "ts":case "mts":case "js":case "mjs":case "cjs":try{i=(await import(Me__default.join(process.cwd(),r))).default;break}catch(o){throw console.error("Failed to import config file",o),o}default:throw new Error(`Unsupported config file type: ${r}`)}return Xn(i)}async createConnection(){throw new Error("Not implemented")}async getConfig(t){let r=await this.readConfig(t);if("connection"in r)return {...r,connection:await r.connection};let n,s;switch(r.db?.driver){case "sqlite":s=r.db?.url??ye.default_db_url,n=await createConnection({url:s,ddlDialect:"sqlite"});break;case "pglite":{s=r.db?.url??Me__default.join(process.cwd(),ye.default_db_dir);let{createPgliteConnection:i}=await We("@supabase/lite/pglite","pglite","@electric-sql/pglite");n=await i({url:s});break}case "postgres":{s=r.db?.url??"";let{createPostgresConnection:i}=await We("@supabase/lite/postgres","postgres","postgres");n=await i({url:s});break}default:s=r.db?.url??ye.default_db_url,n=await createConnection({url:s,ddlDialect:"postgres"});break}if(!n)throw new Error("Failed to create connection");return Ze(Gr.default.green(" \u279C"),"Database located at",Gr.default.cyan(s??"in-memory")),{...r,connection:n}}async createApp(t){let r=await this.getConfig(t),n=new App(r);return n.config.storage?.enabled&&process.env.EXPERIMENTAL_STORAGE==="1"&&!n._storageAdapter&&(n._storageAdapter=new As({basePath:Me__default.join(process.cwd(),ye.config_dir,".temp/storage")})),await n.init()}};});var Rs,Up=g(()=>{sa();Rs=class extends ar{url(t){return this.projectUrl(t)}async ping(){return (await this.fetch("/v1/system/ping")).ok}async list(){let t=await this.fetch("/v1/projects");if(!t.ok)throw new Error("Failed to list projects");let r=await t.json();if(!Array.isArray(r))throw new Error("Failed to list projects");return r}async get(t){if(t=t??this.projectRef(),!t)throw new Error("No project ref found");let r=await this.fetch(`/v1/projects/${t}`);if(!r.ok)throw new Error(`Failed to get project: ${r.status} ${r.statusText}`);let n=await r.json();if(!n||!n.id)throw new Error("Failed to get project");return n}async create(t={}){let r=await this.fetch("/v1/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok)throw new Error(`Failed to create project: ${r.status} ${r.statusText}`);let n=await r.json();if(!n||!n.id)throw new Error("Failed to create project");return n}async getConfig(t){let r=await this.fetch(`/v1/projects/${t}/config`);if(!r.ok)throw new Error(`Failed to get project config: ${r.status} ${r.statusText}`);let n=await r.json();if(!n)throw new Error("Failed to get project config");return n}async setConfig(t,r){let n=await this.fetch(`/v1/projects/${t}/config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!n.ok)throw new Error(`Failed to set project config: ${n.status} ${n.statusText}`);return true}async createApp(t){if(!this.config.host)throw new Error("No host specified");let{data:r,error:n}=await this.client.auth.getSession();if(n)throw n;if(!r?.session?.access_token)throw new Error("Not authenticated, sign in first.");let s=await this.getConfig(t);return await new App({...s.config,connection:cloud({projectRef:t,token:r.session.access_token,host:this.config.host})}).init()}};});var ks,Bp=g(()=>{na();Mp();Up();ks=class extends or{project;get client(){if(!this._client)throw new Error("Supabase client not initialized");return this._client}async getSession(){return await this.client.auth.getSession()}async getAccessToken(){let{data:t,error:r}=await this.getSession();if(r)throw r;return t?.session?.access_token}async requireSession(){let t=await this.getAccessToken();if(!t)throw new Error("Not authenticated, sign in first.");return t}async init(){let t={...this.config};return this.config.withSupabaseClient!==false&&(t.client=this.client,t.token=await this.getAccessToken()),this.project={local:new Cs(t),remote:new Rs(t)},this}};});async function z(e={}){return await new ks({host:Wr,root:nt.projectDir(),...e}).init()}var Ce=g(()=>{ea();ta();Bp();});var qp={};de(qp,{start:()=>ab});var zr,ab,Hp=g(()=>{Zo();ht();zr=te(ae());Zt();Ce();$e();Yt();ab=e=>{e.command("start").option("--config <config>","Path to the config file").description("Start the development server").helpGroup("Local Development:").action(async t=>{await Q(t.config),await ss(async()=>{let n=await(await z({withSupabaseClient:false})).project.local.createApp(t.config),s=n.config.api?.port??ye.default_api_port;await xs(n,{port:s});console.log(zr.default.green(" \u279C"),"Server running on ",zr.default.cyan(`http://localhost:${s}`));let o=qn();o&&console.log(zr.default.yellow(` \u26A0 ${o}`)),await n.connection.ping();},r=>{console.log(),console.log(zr.default.green(`Ready in ${r.toFixed(2)}ms`));});});};});function db(e){let t=normalize(e);return t.length>1&&t[t.length-1]===sep&&(t=t.substring(0,t.length-1)),t}function Vp(e,t){return e.replace(hb,t)}function yb(e){return e==="/"||gb.test(e)}function oa(e,t){let{resolvePaths:r,normalizePath:n,pathSeparator:s}=t,i=process.platform==="win32"&&e.includes("/")||e.startsWith(".");if(r&&(e=resolve(e)),(n||i)&&(e=db(e)),e===".")return "";let o=e[e.length-1]!==s;return Vp(o?e+s:e,s)}function Kp(e,t){return t+e}function wb(e,t){return function(r,n){return n.startsWith(e)?n.slice(e.length)+r:Vp(relative(e,n),t.pathSeparator)+t.pathSeparator+r}}function bb(e){return e}function Sb(e,t,r){return t+e+r}function Eb(e,t){let{relativePaths:r,includeBasePath:n}=t;return r&&e?wb(e,t):n?Kp:bb}function xb(e){return function(t,r){r.push(t.substring(e.length)||".");}}function _b(e){return function(t,r,n){let s=t.substring(e.length)||".";n.every(i=>i(s,true))&&r.push(s);}}function Ab(e,t){let{includeDirs:r,filters:n,relativePaths:s}=t;return r?s?n&&n.length?_b(e):xb(e):n&&n.length?vb:$b:Tb}function Nb(e){let{excludeFiles:t,filters:r,onlyCounts:n}=e;return t?Ob:r&&r.length?n?Cb:Rb:n?kb:Pb}function Db(e){return e.group?Lb:Ib}function Mb(e){return e.group?jb:Fb}function qb(e,t){return !e.resolveSymlinks||e.excludeSymlinks?null:t?Bb:Ub}function Xp(e,t,r){if(r.options.useRealPaths)return Hb(t,r);let n=dirname(e),s=1;for(;n!==r.root&&s<2;){let i=r.symlinks.get(n);!!i&&(i===t||i.startsWith(t)||t.startsWith(i))?s++:n=dirname(n);}return r.symlinks.set(e,t),s>1}function Hb(e,t){return t.visited.includes(e+t.options.pathSeparator)}function Ps(e,t,r,n){t(e&&!n?e:null,r);}function Qb(e,t){let{onlyCounts:r,group:n,maxFiles:s}=e;return r?t?Wb:Kb:n?t?Gb:Yb:s?t?Vb:Jb:t?zb:Xb}function tS(e){return e?eS:Zb}function iS(e,t){return new Promise((r,n)=>{Qp(e,t,(s,i)=>{if(s)return n(s);r(i);});})}function Qp(e,t,r){new Yp(e,t,r).start();}function oS(e,t){return new Yp(e,t).start()}var Wp,hb,gb,$b,vb,Tb,Cb,Rb,kb,Pb,Ob,Ib,Lb,jb,Fb,Ub,Bb,Wb,Gb,zb,Vb,Kb,Xb,Jb,Yb,Jp,Zb,eS,rS,nS,sS,Yp,Gp,Zp,ef,tf=g(()=>{Wp=createRequire(import.meta.url);hb=/[\\/]/g;gb=/^[a-z]:[\\/]$/i;$b=(e,t)=>{t.push(e||".");},vb=(e,t,r)=>{let n=e||".";r.every(s=>s(n,true))&&t.push(n);},Tb=()=>{};Cb=(e,t,r,n)=>{n.every(s=>s(e,false))&&r.files++;},Rb=(e,t,r,n)=>{n.every(s=>s(e,false))&&t.push(e);},kb=(e,t,r,n)=>{r.files++;},Pb=(e,t)=>{t.push(e);},Ob=()=>{};Ib=e=>e,Lb=()=>[""].slice(0,0);jb=(e,t,r)=>{e.push({directory:t,files:r,dir:t});},Fb=()=>{};Ub=function(e,t,r){let{queue:n,fs:s,options:{suppressErrors:i}}=t;n.enqueue(),s.realpath(e,(o,a)=>{if(o)return n.dequeue(i?null:o,t);s.stat(a,(l,c)=>{if(l)return n.dequeue(i?null:l,t);if(c.isDirectory()&&Xp(e,a,t))return n.dequeue(null,t);r(c,a),n.dequeue(null,t);});});},Bb=function(e,t,r){let{queue:n,fs:s,options:{suppressErrors:i}}=t;n.enqueue();try{let o=s.realpathSync(e),a=s.statSync(o);if(a.isDirectory()&&Xp(e,o,t))return;r(a,o);}catch(o){if(!i)throw o}};Wb=e=>e.counts,Gb=e=>e.groups,zb=e=>e.paths,Vb=e=>e.paths.slice(0,e.options.maxFiles),Kb=(e,t,r)=>(Ps(t,r,e.counts,e.options.suppressErrors),null),Xb=(e,t,r)=>(Ps(t,r,e.paths,e.options.suppressErrors),null),Jb=(e,t,r)=>(Ps(t,r,e.paths.slice(0,e.options.maxFiles),e.options.suppressErrors),null),Yb=(e,t,r)=>(Ps(t,r,e.groups,e.options.suppressErrors),null);Jp={withFileTypes:true},Zb=(e,t,r,n,s)=>{if(e.queue.enqueue(),n<0)return e.queue.dequeue(null,e);let{fs:i}=e;e.visited.push(t),e.counts.directories++,i.readdir(t||".",Jp,(o,a=[])=>{s(a,r,n),e.queue.dequeue(e.options.suppressErrors?null:o,e);});},eS=(e,t,r,n,s)=>{let{fs:i}=e;if(n<0)return;e.visited.push(t),e.counts.directories++;let o=[];try{o=i.readdirSync(t||".",Jp);}catch(a){if(!e.options.suppressErrors)throw a}s(o,r,n);};rS=class{count=0;constructor(e){this.onQueueEmpty=e;}enqueue(){return this.count++,this.count}dequeue(e,t){this.onQueueEmpty&&(--this.count<=0||e)&&(this.onQueueEmpty(e,t),e&&(t.controller.abort(),this.onQueueEmpty=void 0));}},nS=class{_files=0;_directories=0;set files(e){this._files=e;}get files(){return this._files}set directories(e){this._directories=e;}get directories(){return this._directories}get dirs(){return this._directories}},sS=class{aborted=false;abort(){this.aborted=true;}},Yp=class{root;isSynchronous;state;joinPath;pushDirectory;pushFile;getArray;groupFiles;resolveSymlink;walkDirectory;callbackInvoker;constructor(e,t,r){this.isSynchronous=!r,this.callbackInvoker=Qb(t,this.isSynchronous),this.root=oa(e,t),this.state={root:yb(this.root)?this.root:this.root.slice(0,-1),paths:[""].slice(0,0),groups:[],counts:new nS,options:t,queue:new rS((n,s)=>this.callbackInvoker(s,n,r)),symlinks:new Map,visited:[""].slice(0,0),controller:new sS,fs:t.fs||mb},this.joinPath=Eb(this.root,t),this.pushDirectory=Ab(this.root,t),this.pushFile=Nb(t),this.getArray=Db(t),this.groupFiles=Mb(t),this.resolveSymlink=qb(t,this.isSynchronous),this.walkDirectory=tS(this.isSynchronous);}start(){return this.pushDirectory(this.root,this.state.paths,this.state.options.filters),this.walkDirectory(this.state,this.root,this.root,this.state.options.maxDepth,this.walk),this.isSynchronous?this.callbackInvoker(this.state,null):null}walk=(e,t,r)=>{let{paths:n,options:{filters:s,resolveSymlinks:i,excludeSymlinks:o,exclude:a,maxFiles:l,signal:c,useRealPaths:p,pathSeparator:u},controller:f}=this.state;if(f.aborted||c&&c.aborted||l&&n.length>l)return;let h=this.getArray(this.state.paths);for(let d=0;d<e.length;++d){let m=e[d];if(m.isFile()||m.isSymbolicLink()&&!i&&!o){let w=this.joinPath(m.name,t);this.pushFile(w,h,this.state.counts,s);}else if(m.isDirectory()){let w=Sb(m.name,t,this.state.options.pathSeparator);if(a&&a(m.name,w))continue;this.pushDirectory(w,n,s),this.walkDirectory(this.state,w,w,r-1,this.walk);}else if(this.resolveSymlink&&m.isSymbolicLink()){let w=Kp(m.name,t);this.resolveSymlink(w,this.state,(y,E)=>{if(y.isDirectory()){if(E=oa(E,this.state.options),a&&a(m.name,p?E:w+u))return;this.walkDirectory(this.state,E,p?E:w+u,r-1,this.walk);}else {E=p?E:w;let T=basename(E),v=oa(dirname(E),this.state.options);E=this.joinPath(T,v),this.pushFile(E,h,this.state.counts,s);}});}}this.groupFiles(this.state.groups,t,h);}};Gp=class{constructor(e,t){this.root=e,this.options=t;}withPromise(){return iS(this.root,this.options)}withCallback(e){Qp(this.root,this.options,e);}sync(){return oS(this.root,this.options)}},Zp=null;try{Wp.resolve("picomatch"),Zp=Wp("picomatch");}catch{}ef=class{globCache={};options={maxDepth:1/0,suppressErrors:true,pathSeparator:sep,filters:[]};globFunction;constructor(e){this.options={...this.options,...e},this.globFunction=this.options.globFunction;}group(){return this.options.group=true,this}withPathSeparator(e){return this.options.pathSeparator=e,this}withBasePath(){return this.options.includeBasePath=true,this}withRelativePaths(){return this.options.relativePaths=true,this}withDirs(){return this.options.includeDirs=true,this}withMaxDepth(e){return this.options.maxDepth=e,this}withMaxFiles(e){return this.options.maxFiles=e,this}withFullPaths(){return this.options.resolvePaths=true,this.options.includeBasePath=true,this}withErrors(){return this.options.suppressErrors=false,this}withSymlinks({resolvePaths:e=true}={}){return this.options.resolveSymlinks=true,this.options.useRealPaths=e,this.withFullPaths()}withAbortSignal(e){return this.options.signal=e,this}normalize(){return this.options.normalizePath=true,this}filter(e){return this.options.filters.push(e),this}onlyDirs(){return this.options.excludeFiles=true,this.options.includeDirs=true,this}exclude(e){return this.options.exclude=e,this}onlyCounts(){return this.options.onlyCounts=true,this}crawl(e){return new Gp(e||".",this.options)}withGlobFunction(e){return this.globFunction=e,this}crawlWithOptions(e,t){return this.options={...this.options,...t},new Gp(e||".",this.options)}glob(...e){return this.globFunction?this.globWithOptions(e):this.globWithOptions(e,{dot:true})}globWithOptions(e,...t){let r=this.globFunction||Zp;if(!r)throw new Error("Please specify a glob function to use glob matching.");var n=this.globCache[e.join("\0")];return n||(n=r(e,...t),this.globCache[e.join("\0")]=n),this.options.filters.push(s=>n(s)),this}};});var Vr=ft((DR,af)=>{var rf="[^\\\\/]",aS="(?=.)",nf="[^/]",la="(?:\\/|$)",sf="(?:^|\\/)",ca=`\\.{1,2}${la}`,lS="(?!\\.)",cS=`(?!${sf}${ca})`,uS=`(?!\\.{0,1}${la})`,pS=`(?!${ca})`,fS="[^.\\/]",mS=`${nf}*?`,dS="/",of={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:aS,QMARK:nf,END_ANCHOR:la,DOTS_SLASH:ca,NO_DOT:lS,NO_DOTS:cS,NO_DOT_SLASH:uS,NO_DOTS_SLASH:pS,QMARK_NO_DOT:fS,STAR:mS,START_ANCHOR:sf,SEP:dS},hS={...of,SLASH_LITERAL:"[\\\\/]",QMARK:rf,STAR:`${rf}*?`,DOTS_SLASH:"\\.{1,2}(?:[\\\\/]|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:[\\\\/]|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:[\\\\/]|$))",QMARK_NO_DOT:"[^.\\\\/]",START_ANCHOR:"(?:^|[\\\\/])",END_ANCHOR:"(?:[\\\\/]|$)",SEP:"\\"},gS={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};af.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:gS,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars(e){return {"!":{type:"negate",open:"(?:(?!(?:",close:`))${e.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(e){return e===true?hS:of}};});var Kr=ft(Oe=>{var{REGEX_BACKSLASH:yS,REGEX_REMOVE_BACKSLASH:wS,REGEX_SPECIAL_CHARS:bS,REGEX_SPECIAL_CHARS_GLOBAL:SS}=Vr();Oe.isObject=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);Oe.hasRegexChars=e=>bS.test(e);Oe.isRegexChar=e=>e.length===1&&Oe.hasRegexChars(e);Oe.escapeRegex=e=>e.replace(SS,"\\$1");Oe.toPosixSlashes=e=>e.replace(yS,"/");Oe.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let e=navigator.platform.toLowerCase();return e==="win32"||e==="windows"}return typeof process<"u"&&process.platform?process.platform==="win32":false};Oe.removeBackslashes=e=>e.replace(wS,t=>t==="\\"?"":t);Oe.escapeLast=(e,t,r)=>{let n=e.lastIndexOf(t,r);return n===-1?e:e[n-1]==="\\"?Oe.escapeLast(e,t,n-1):`${e.slice(0,n)}\\${e.slice(n)}`};Oe.removePrefix=(e,t={})=>{let r=e;return r.startsWith("./")&&(r=r.slice(2),t.prefix="./"),r};Oe.wrapOutput=(e,t={},r={})=>{let n=r.contains?"":"^",s=r.contains?"":"$",i=`${n}(?:${e})${s}`;return t.negated===true&&(i=`(?:^(?!${i}).*$)`),i};Oe.basename=(e,{windows:t}={})=>{let r=e.split(t?/[\\/]/:"/"),n=r[r.length-1];return n===""?r[r.length-2]:n};});var hf=ft((FR,df)=>{var lf=Kr(),{CHAR_ASTERISK:ua,CHAR_AT:ES,CHAR_BACKWARD_SLASH:Xr,CHAR_COMMA:xS,CHAR_DOT:pa,CHAR_EXCLAMATION_MARK:fa,CHAR_FORWARD_SLASH:mf,CHAR_LEFT_CURLY_BRACE:ma,CHAR_LEFT_PARENTHESES:da,CHAR_LEFT_SQUARE_BRACKET:_S,CHAR_PLUS:$S,CHAR_QUESTION_MARK:cf,CHAR_RIGHT_CURLY_BRACE:vS,CHAR_RIGHT_PARENTHESES:uf,CHAR_RIGHT_SQUARE_BRACKET:TS}=Vr(),pf=e=>e===mf||e===Xr,ff=e=>{e.isPrefix!==true&&(e.depth=e.isGlobstar?1/0:1);},AS=(e,t)=>{let r=t||{},n=e.length-1,s=r.parts===true||r.scanToEnd===true,i=[],o=[],a=[],l=e,c=-1,p=0,u=0,f=false,h=false,d=false,m=false,w=false,y=false,E=false,T=false,v=false,C=false,A=0,$,_,I={value:"",depth:0,isGlob:false},b=()=>c>=n,D=()=>l.charCodeAt(c+1),O=()=>($=_,l.charCodeAt(++c));for(;c<n;){_=O();let q;if(_===Xr){E=I.backslashes=true,_=O(),_===ma&&(y=true);continue}if(y===true||_===ma){for(A++;b()!==true&&(_=O());){if(_===Xr){E=I.backslashes=true,O();continue}if(_===ma){A++;continue}if(y!==true&&_===pa&&(_=O())===pa){if(f=I.isBrace=true,d=I.isGlob=true,C=true,s===true)continue;break}if(y!==true&&_===xS){if(f=I.isBrace=true,d=I.isGlob=true,C=true,s===true)continue;break}if(_===vS&&(A--,A===0)){y=false,f=I.isBrace=true,C=true;break}}if(s===true)continue;break}if(_===mf){if(i.push(c),o.push(I),I={value:"",depth:0,isGlob:false},C===true)continue;if($===pa&&c===p+1){p+=2;continue}u=c+1;continue}if(r.noext!==true&&(_===$S||_===ES||_===ua||_===cf||_===fa)===true&&D()===da){if(d=I.isGlob=true,m=I.isExtglob=true,C=true,_===fa&&c===p&&(v=true),s===true){for(;b()!==true&&(_=O());){if(_===Xr){E=I.backslashes=true,_=O();continue}if(_===uf){d=I.isGlob=true,C=true;break}}continue}break}if(_===ua){if($===ua&&(w=I.isGlobstar=true),d=I.isGlob=true,C=true,s===true)continue;break}if(_===cf){if(d=I.isGlob=true,C=true,s===true)continue;break}if(_===_S){for(;b()!==true&&(q=O());){if(q===Xr){E=I.backslashes=true,O();continue}if(q===TS){h=I.isBracket=true,d=I.isGlob=true,C=true;break}}if(s===true)continue;break}if(r.nonegate!==true&&_===fa&&c===p){T=I.negated=true,p++;continue}if(r.noparen!==true&&_===da){if(d=I.isGlob=true,s===true){for(;b()!==true&&(_=O());){if(_===da){E=I.backslashes=true,_=O();continue}if(_===uf){C=true;break}}continue}break}if(d===true){if(C=true,s===true)continue;break}}r.noext===true&&(m=false,d=false);let F=l,S="",x="";p>0&&(S=l.slice(0,p),l=l.slice(p),u-=p),F&&d===true&&u>0?(F=l.slice(0,u),x=l.slice(u)):d===true?(F="",x=l):F=l,F&&F!==""&&F!=="/"&&F!==l&&pf(F.charCodeAt(F.length-1))&&(F=F.slice(0,-1)),r.unescape===true&&(x&&(x=lf.removeBackslashes(x)),F&&E===true&&(F=lf.removeBackslashes(F)));let Y={prefix:S,input:e,start:p,base:F,glob:x,isBrace:f,isBracket:h,isGlob:d,isExtglob:m,isGlobstar:w,negated:T,negatedExtglob:v};if(r.tokens===true&&(Y.maxDepth=0,pf(_)||o.push(I),Y.tokens=o),r.parts===true||r.tokens===true){let q;for(let j=0;j<i.length;j++){let ie=q?q+1:p,ce=i[j],ut=e.slice(ie,ce);r.tokens&&(j===0&&p!==0?(o[j].isPrefix=true,o[j].value=S):o[j].value=ut,ff(o[j]),Y.maxDepth+=o[j].depth),(j!==0||ut!=="")&&a.push(ut),q=ce;}if(q&&q+1<e.length){let j=e.slice(q+1);a.push(j),r.tokens&&(o[o.length-1].value=j,ff(o[o.length-1]),Y.maxDepth+=o[o.length-1].depth);}Y.slashes=i,Y.parts=a;}return Y};df.exports=AS;});var Sf=ft((MR,bf)=>{var Jr=Vr(),Ie=Kr(),{MAX_LENGTH:Os,POSIX_REGEX_SOURCE:CS,REGEX_NON_SPECIAL_CHARS:RS,REGEX_SPECIAL_CHARS_BACKREF:kS,REPLACEMENTS:gf}=Jr,PS=(e,t)=>{if(typeof t.expandRange=="function")return t.expandRange(...e,t);e.sort();let r=`[${e.join("-")}]`;try{new RegExp(r);}catch{return e.map(s=>Ie.escapeRegex(s)).join("..")}return r},cr=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`,yf=e=>{let t=[],r=0,n=0,s=0,i="",o=false;for(let a of e){if(o===true){i+=a,o=false;continue}if(a==="\\"){i+=a,o=true;continue}if(a==='"'){s=s===1?0:1,i+=a;continue}if(s===0){if(a==="[")r++;else if(a==="]"&&r>0)r--;else if(r===0){if(a==="(")n++;else if(a===")"&&n>0)n--;else if(a==="|"&&n===0){t.push(i),i="";continue}}}i+=a;}return t.push(i),t},OS=e=>{let t=false;for(let r of e){if(t===true){t=false;continue}if(r==="\\"){t=true;continue}if(/[?*+@!()[\]{}]/.test(r))return false}return true},wf=e=>{let t=e.trim(),r=true;for(;r===true;)r=false,/^@\([^\\()[\]{}|]+\)$/.test(t)&&(t=t.slice(2,-1),r=true);if(OS(t))return t.replace(/\\(.)/g,"$1")},NS=e=>{let t=e.map(wf).filter(Boolean);for(let r=0;r<t.length;r++)for(let n=r+1;n<t.length;n++){let s=t[r],i=t[n],o=s[0];if(!(!o||s!==o.repeat(s.length)||i!==o.repeat(i.length))&&(s===i||s.startsWith(i)||i.startsWith(s)))return true}return false},ha=(e,t=true)=>{if(e[0]!=="+"&&e[0]!=="*"||e[1]!=="(")return;let r=0,n=0,s=0,i=false;for(let o=1;o<e.length;o++){let a=e[o];if(i===true){i=false;continue}if(a==="\\"){i=true;continue}if(a==='"'){s=s===1?0:1;continue}if(s!==1){if(a==="["){r++;continue}if(a==="]"&&r>0){r--;continue}if(!(r>0)){if(a==="("){n++;continue}if(a===")"&&(n--,n===0))return t===true&&o!==e.length-1?void 0:{type:e[0],body:e.slice(2,o),end:o}}}}},IS=e=>{let t=0,r=[];for(;t<e.length;){let s=ha(e.slice(t),false);if(!s||s.type!=="*")return;let i=yf(s.body).map(a=>a.trim());if(i.length!==1)return;let o=wf(i[0]);if(!o||o.length!==1)return;r.push(o),t+=s.end+1;}return r.length<1?void 0:`${r.length===1?Ie.escapeRegex(r[0]):`[${r.map(s=>Ie.escapeRegex(s)).join("")}]`}*`},LS=e=>{let t=0,r=e.trim(),n=ha(r);for(;n;)t++,r=n.body.trim(),n=ha(r);return t},DS=(e,t)=>{if(t.maxExtglobRecursion===false)return {risky:false};let r=typeof t.maxExtglobRecursion=="number"?t.maxExtglobRecursion:Jr.DEFAULT_MAX_EXTGLOB_RECURSION,n=yf(e).map(s=>s.trim());if(n.length>1&&(n.some(s=>s==="")||n.some(s=>/^[*?]+$/.test(s))||NS(n)))return {risky:true};for(let s of n){let i=IS(s);if(i)return {risky:true,safeOutput:i};if(LS(s)>r)return {risky:true}}return {risky:false}},ga=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a string");e=gf[e]||e;let r={...t},n=typeof r.maxLength=="number"?Math.min(Os,r.maxLength):Os,s=e.length;if(s>n)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${n}`);let i={type:"bos",value:"",output:r.prepend||""},o=[i],a=r.capture?"":"?:",l=Jr.globChars(r.windows),c=Jr.extglobChars(l),{DOT_LITERAL:p,PLUS_LITERAL:u,SLASH_LITERAL:f,ONE_CHAR:h,DOTS_SLASH:d,NO_DOT:m,NO_DOT_SLASH:w,NO_DOTS_SLASH:y,QMARK:E,QMARK_NO_DOT:T,STAR:v,START_ANCHOR:C}=l,A=P=>`(${a}(?:(?!${C}${P.dot?d:p}).)*?)`,$=r.dot?"":m,_=r.dot?E:T,I=r.bash===true?A(r):v;r.capture&&(I=`(${I})`),typeof r.noext=="boolean"&&(r.noextglob=r.noext);let b={input:e,index:-1,start:0,dot:r.dot===true,consumed:"",output:"",prefix:"",backtrack:false,negated:false,brackets:0,braces:0,parens:0,quotes:0,globstar:false,tokens:o};e=Ie.removePrefix(e,b),s=e.length;let D=[],O=[],F=[],S=i,x,Y=()=>b.index===s-1,q=b.peek=(P=1)=>e[b.index+P],j=b.advance=()=>e[++b.index]||"",ie=()=>e.slice(b.index+1),ce=(P="",oe=0)=>{b.consumed+=P,b.index+=oe;},ut=P=>{b.output+=P.output!=null?P.output:P.value,ce(P.value);},fg=()=>{let P=1;for(;q()==="!"&&(q(2)!=="("||q(3)==="?");)j(),b.start++,P++;return P%2===0?false:(b.negated=true,b.start++,true)},Fn=P=>{b[P]++,F.push(P);},pt=P=>{b[P]--,F.pop();},W=P=>{if(S.type==="globstar"){let oe=b.braces>0&&(P.type==="comma"||P.type==="brace"),R=P.extglob===true||D.length&&(P.type==="pipe"||P.type==="paren");P.type!=="slash"&&P.type!=="paren"&&!oe&&!R&&(b.output=b.output.slice(0,-S.output.length),S.type="star",S.value="*",S.output=I,b.output+=S.output);}if(D.length&&P.type!=="paren"&&(D[D.length-1].inner+=P.value),(P.value||P.output)&&ut(P),S&&S.type==="text"&&P.type==="text"){S.output=(S.output||S.value)+P.value,S.value+=P.value;return}P.prev=S,o.push(P),S=P;},Mn=(P,oe)=>{let R={...c[oe],conditions:1,inner:""};R.prev=S,R.parens=b.parens,R.output=b.output,R.startIndex=b.index,R.tokensIndex=o.length;let G=(r.capture?"(":"")+R.open;Fn("parens"),W({type:P,value:oe,output:b.output?"":h}),W({type:"paren",extglob:true,value:j(),output:G}),D.push(R);},mg=P=>{let oe=e.slice(P.startIndex,b.index+1),R=e.slice(P.startIndex+2,b.index),G=DS(R,r);if((P.type==="plus"||P.type==="star")&&G.risky){let ee=G.safeOutput?(P.output?"":h)+(r.capture?`(${G.safeOutput})`:G.safeOutput):void 0,Ve=o[P.tokensIndex];Ve.type="text",Ve.value=oe,Ve.output=ee||Ie.escapeRegex(oe);for(let Ke=P.tokensIndex+1;Ke<o.length;Ke++)o[Ke].value="",o[Ke].output="",delete o[Ke].suffix;b.output=P.output+Ve.output,b.backtrack=true,W({type:"paren",extglob:true,value:x,output:""}),pt("parens");return}let ne=P.close+(r.capture?")":""),me;if(P.type==="negate"){let ee=I;if(P.inner&&P.inner.length>1&&P.inner.includes("/")&&(ee=A(r)),(ee!==I||Y()||/^\)+$/.test(ie()))&&(ne=P.close=`)$))${ee}`),P.inner.includes("*")&&(me=ie())&&/^\.[^\\/.]+$/.test(me)){let Ve=ga(me,{...t,fastpaths:false}).output;ne=P.close=`)${Ve})${ee})`;}P.prev.type==="bos"&&(b.negatedExtglob=true);}W({type:"paren",extglob:true,value:x,output:ne}),pt("parens");};if(r.fastpaths!==false&&!/(^[*!]|[/()[\]{}"])/.test(e)){let P=false,oe=e.replace(kS,(R,G,ne,me,ee,Ve)=>me==="\\"?(P=true,R):me==="?"?G?G+me+(ee?E.repeat(ee.length):""):Ve===0?_+(ee?E.repeat(ee.length):""):E.repeat(ne.length):me==="."?p.repeat(ne.length):me==="*"?G?G+me+(ee?I:""):I:G?R:`\\${R}`);return P===true&&(r.unescape===true?oe=oe.replace(/\\/g,""):oe=oe.replace(/\\+/g,R=>R.length%2===0?"\\\\":R?"\\":"")),oe===e&&r.contains===true?(b.output=e,b):(b.output=Ie.wrapOutput(oe,b,t),b)}for(;!Y();){if(x=j(),x==="\0")continue;if(x==="\\"){let R=q();if(R==="/"&&r.bash!==true||R==="."||R===";")continue;if(!R){x+="\\",W({type:"text",value:x});continue}let G=/^\\+/.exec(ie()),ne=0;if(G&&G[0].length>2&&(ne=G[0].length,b.index+=ne,ne%2!==0&&(x+="\\")),r.unescape===true?x=j():x+=j(),b.brackets===0){W({type:"text",value:x});continue}}if(b.brackets>0&&(x!=="]"||S.value==="["||S.value==="[^")){if(r.posix!==false&&x===":"){let R=S.value.slice(1);if(R.includes("[")&&(S.posix=true,R.includes(":"))){let G=S.value.lastIndexOf("["),ne=S.value.slice(0,G),me=S.value.slice(G+2),ee=CS[me];if(ee){S.value=ne+ee,b.backtrack=true,j(),!i.output&&o.indexOf(S)===1&&(i.output=h);continue}}}(x==="["&&q()!==":"||x==="-"&&q()==="]")&&(x=`\\${x}`),x==="]"&&(S.value==="["||S.value==="[^")&&(x=`\\${x}`),r.posix===true&&x==="!"&&S.value==="["&&(x="^"),S.value+=x,ut({value:x});continue}if(b.quotes===1&&x!=='"'){x=Ie.escapeRegex(x),S.value+=x,ut({value:x});continue}if(x==='"'){b.quotes=b.quotes===1?0:1,r.keepQuotes===true&&W({type:"text",value:x});continue}if(x==="("){Fn("parens"),W({type:"paren",value:x});continue}if(x===")"){if(b.parens===0&&r.strictBrackets===true)throw new SyntaxError(cr("opening","("));let R=D[D.length-1];if(R&&b.parens===R.parens+1){mg(D.pop());continue}W({type:"paren",value:x,output:b.parens?")":"\\)"}),pt("parens");continue}if(x==="["){if(r.nobracket===true||!ie().includes("]")){if(r.nobracket!==true&&r.strictBrackets===true)throw new SyntaxError(cr("closing","]"));x=`\\${x}`;}else Fn("brackets");W({type:"bracket",value:x});continue}if(x==="]"){if(r.nobracket===true||S&&S.type==="bracket"&&S.value.length===1){W({type:"text",value:x,output:`\\${x}`});continue}if(b.brackets===0){if(r.strictBrackets===true)throw new SyntaxError(cr("opening","["));W({type:"text",value:x,output:`\\${x}`});continue}pt("brackets");let R=S.value.slice(1);if(S.posix!==true&&R[0]==="^"&&!R.includes("/")&&(x=`/${x}`),S.value+=x,ut({value:x}),r.literalBrackets===false||Ie.hasRegexChars(R))continue;let G=Ie.escapeRegex(S.value);if(b.output=b.output.slice(0,-S.value.length),r.literalBrackets===true){b.output+=G,S.value=G;continue}S.value=`(${a}${G}|${S.value})`,b.output+=S.value;continue}if(x==="{"&&r.nobrace!==true){Fn("braces");let R={type:"brace",value:x,output:"(",outputIndex:b.output.length,tokensIndex:b.tokens.length};O.push(R),W(R);continue}if(x==="}"){let R=O[O.length-1];if(r.nobrace===true||!R){W({type:"text",value:x,output:x});continue}let G=")";if(R.dots===true){let ne=o.slice(),me=[];for(let ee=ne.length-1;ee>=0&&(o.pop(),ne[ee].type!=="brace");ee--)ne[ee].type!=="dots"&&me.unshift(ne[ee].value);G=PS(me,r),b.backtrack=true;}if(R.comma!==true&&R.dots!==true){let ne=b.output.slice(0,R.outputIndex),me=b.tokens.slice(R.tokensIndex);R.value=R.output="\\{",x=G="\\}",b.output=ne;for(let ee of me)b.output+=ee.output||ee.value;}W({type:"brace",value:x,output:G}),pt("braces"),O.pop();continue}if(x==="|"){D.length>0&&D[D.length-1].conditions++,W({type:"text",value:x});continue}if(x===","){let R=x,G=O[O.length-1];G&&F[F.length-1]==="braces"&&(G.comma=true,R="|"),W({type:"comma",value:x,output:R});continue}if(x==="/"){if(S.type==="dot"&&b.index===b.start+1){b.start=b.index+1,b.consumed="",b.output="",o.pop(),S=i;continue}W({type:"slash",value:x,output:f});continue}if(x==="."){if(b.braces>0&&S.type==="dot"){S.value==="."&&(S.output=p);let R=O[O.length-1];S.type="dots",S.output+=x,S.value+=x,R.dots=true;continue}if(b.braces+b.parens===0&&S.type!=="bos"&&S.type!=="slash"){W({type:"text",value:x,output:p});continue}W({type:"dot",value:x,output:p});continue}if(x==="?"){if(!(S&&S.value==="(")&&r.noextglob!==true&&q()==="("&&q(2)!=="?"){Mn("qmark",x);continue}if(S&&S.type==="paren"){let G=q(),ne=x;(S.value==="("&&!/[!=<:]/.test(G)||G==="<"&&!/<([!=]|\w+>)/.test(ie()))&&(ne=`\\${x}`),W({type:"text",value:x,output:ne});continue}if(r.dot!==true&&(S.type==="slash"||S.type==="bos")){W({type:"qmark",value:x,output:T});continue}W({type:"qmark",value:x,output:E});continue}if(x==="!"){if(r.noextglob!==true&&q()==="("&&(q(2)!=="?"||!/[!=<:]/.test(q(3)))){Mn("negate",x);continue}if(r.nonegate!==true&&b.index===0){fg();continue}}if(x==="+"){if(r.noextglob!==true&&q()==="("&&q(2)!=="?"){Mn("plus",x);continue}if(S&&S.value==="("||r.regex===false){W({type:"plus",value:x,output:u});continue}if(S&&(S.type==="bracket"||S.type==="paren"||S.type==="brace")||b.parens>0){W({type:"plus",value:x});continue}W({type:"plus",value:u});continue}if(x==="@"){if(r.noextglob!==true&&q()==="("&&q(2)!=="?"){W({type:"at",extglob:true,value:x,output:""});continue}W({type:"text",value:x});continue}if(x!=="*"){(x==="$"||x==="^")&&(x=`\\${x}`);let R=RS.exec(ie());R&&(x+=R[0],b.index+=R[0].length),W({type:"text",value:x});continue}if(S&&(S.type==="globstar"||S.star===true)){S.type="star",S.star=true,S.value+=x,S.output=I,b.backtrack=true,b.globstar=true,ce(x);continue}let P=ie();if(r.noextglob!==true&&/^\([^?]/.test(P)){Mn("star",x);continue}if(S.type==="star"){if(r.noglobstar===true){ce(x);continue}let R=S.prev,G=R.prev,ne=R.type==="slash"||R.type==="bos",me=G&&(G.type==="star"||G.type==="globstar");if(r.bash===true&&(!ne||P[0]&&P[0]!=="/")){W({type:"star",value:x,output:""});continue}let ee=b.braces>0&&(R.type==="comma"||R.type==="brace"),Ve=D.length&&(R.type==="pipe"||R.type==="paren");if(!ne&&R.type!=="paren"&&!ee&&!Ve){W({type:"star",value:x,output:""});continue}for(;P.slice(0,3)==="/**";){let Ke=e[b.index+4];if(Ke&&Ke!=="/")break;P=P.slice(3),ce("/**",3);}if(R.type==="bos"&&Y()){S.type="globstar",S.value+=x,S.output=A(r),b.output=S.output,b.globstar=true,ce(x);continue}if(R.type==="slash"&&R.prev.type!=="bos"&&!me&&Y()){b.output=b.output.slice(0,-(R.output+S.output).length),R.output=`(?:${R.output}`,S.type="globstar",S.output=A(r)+(r.strictSlashes?")":"|$)"),S.value+=x,b.globstar=true,b.output+=R.output+S.output,ce(x);continue}if(R.type==="slash"&&R.prev.type!=="bos"&&P[0]==="/"){let Ke=P[1]!==void 0?"|$":"";b.output=b.output.slice(0,-(R.output+S.output).length),R.output=`(?:${R.output}`,S.type="globstar",S.output=`${A(r)}${f}|${f}${Ke})`,S.value+=x,b.output+=R.output+S.output,b.globstar=true,ce(x+j()),W({type:"slash",value:"/",output:""});continue}if(R.type==="bos"&&P[0]==="/"){S.type="globstar",S.value+=x,S.output=`(?:^|${f}|${A(r)}${f})`,b.output=S.output,b.globstar=true,ce(x+j()),W({type:"slash",value:"/",output:""});continue}b.output=b.output.slice(0,-S.output.length),S.type="globstar",S.output=A(r),S.value+=x,b.output+=S.output,b.globstar=true,ce(x);continue}let oe={type:"star",value:x,output:I};if(r.bash===true){oe.output=".*?",(S.type==="bos"||S.type==="slash")&&(oe.output=$+oe.output),W(oe);continue}if(S&&(S.type==="bracket"||S.type==="paren")&&r.regex===true){oe.output=x,W(oe);continue}(b.index===b.start||S.type==="slash"||S.type==="dot")&&(S.type==="dot"?(b.output+=w,S.output+=w):r.dot===true?(b.output+=y,S.output+=y):(b.output+=$,S.output+=$),q()!=="*"&&(b.output+=h,S.output+=h)),W(oe);}for(;b.brackets>0;){if(r.strictBrackets===true)throw new SyntaxError(cr("closing","]"));b.output=Ie.escapeLast(b.output,"["),pt("brackets");}for(;b.parens>0;){if(r.strictBrackets===true)throw new SyntaxError(cr("closing",")"));b.output=Ie.escapeLast(b.output,"("),pt("parens");}for(;b.braces>0;){if(r.strictBrackets===true)throw new SyntaxError(cr("closing","}"));b.output=Ie.escapeLast(b.output,"{"),pt("braces");}if(r.strictSlashes!==true&&(S.type==="star"||S.type==="bracket")&&W({type:"maybe_slash",value:"",output:`${f}?`}),b.backtrack===true){b.output="";for(let P of b.tokens)b.output+=P.output!=null?P.output:P.value,P.suffix&&(b.output+=P.suffix);}return b};ga.fastpaths=(e,t)=>{let r={...t},n=typeof r.maxLength=="number"?Math.min(Os,r.maxLength):Os,s=e.length;if(s>n)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${n}`);e=gf[e]||e;let{DOT_LITERAL:i,SLASH_LITERAL:o,ONE_CHAR:a,DOTS_SLASH:l,NO_DOT:c,NO_DOTS:p,NO_DOTS_SLASH:u,STAR:f,START_ANCHOR:h}=Jr.globChars(r.windows),d=r.dot?p:c,m=r.dot?u:c,w=r.capture?"":"?:",y={negated:false,prefix:""},E=r.bash===true?".*?":f;r.capture&&(E=`(${E})`);let T=$=>$.noglobstar===true?E:`(${w}(?:(?!${h}${$.dot?l:i}).)*?)`,v=$=>{switch($){case "*":return `${d}${a}${E}`;case ".*":return `${i}${a}${E}`;case "*.*":return `${d}${E}${i}${a}${E}`;case "*/*":return `${d}${E}${o}${a}${m}${E}`;case "**":return d+T(r);case "**/*":return `(?:${d}${T(r)}${o})?${m}${a}${E}`;case "**/*.*":return `(?:${d}${T(r)}${o})?${m}${E}${i}${a}${E}`;case "**/.*":return `(?:${d}${T(r)}${o})?${i}${a}${E}`;default:{let _=/^(.*?)\.(\w+)$/.exec($);if(!_)return;let I=v(_[1]);return I?I+i+_[2]:void 0}}},C=Ie.removePrefix(e,y),A=v(C);return A&&r.strictSlashes!==true&&(A+=`${o}?`),A};bf.exports=ga;});var _f=ft((UR,xf)=>{var jS=hf(),ya=Sf(),Ef=Kr(),FS=Vr(),MS=e=>e&&typeof e=="object"&&!Array.isArray(e),ue=(e,t,r=false)=>{if(Array.isArray(e)){let p=e.map(f=>ue(f,t,r));return f=>{for(let h of p){let d=h(f);if(d)return d}return false}}let n=MS(e)&&e.tokens&&e.input;if(e===""||typeof e!="string"&&!n)throw new TypeError("Expected pattern to be a non-empty string");let s=t||{},i=s.windows,o=n?ue.compileRe(e,t):ue.makeRe(e,t,false,true),a=o.state;delete o.state;let l=()=>false;if(s.ignore){let p={...t,ignore:null,onMatch:null,onResult:null};l=ue(s.ignore,p,r);}let c=(p,u=false)=>{let{isMatch:f,match:h,output:d}=ue.test(p,o,t,{glob:e,posix:i}),m={glob:e,state:a,regex:o,posix:i,input:p,output:d,match:h,isMatch:f};return typeof s.onResult=="function"&&s.onResult(m),f===false?(m.isMatch=false,u?m:false):l(p)?(typeof s.onIgnore=="function"&&s.onIgnore(m),m.isMatch=false,u?m:false):(typeof s.onMatch=="function"&&s.onMatch(m),u?m:true)};return r&&(c.state=a),c};ue.test=(e,t,r,{glob:n,posix:s}={})=>{if(typeof e!="string")throw new TypeError("Expected input to be a string");if(e==="")return {isMatch:false,output:""};let i=r||{},o=i.format||(s?Ef.toPosixSlashes:null),a=e===n,l=a&&o?o(e):e;return a===false&&(l=o?o(e):e,a=l===n),(a===false||i.capture===true)&&(i.matchBase===true||i.basename===true?a=ue.matchBase(e,t,r,s):a=t.exec(l)),{isMatch:!!a,match:a,output:l}};ue.matchBase=(e,t,r)=>(t instanceof RegExp?t:ue.makeRe(t,r)).test(Ef.basename(e));ue.isMatch=(e,t,r)=>ue(t,r)(e);ue.parse=(e,t)=>Array.isArray(e)?e.map(r=>ue.parse(r,t)):ya(e,{...t,fastpaths:false});ue.scan=(e,t)=>jS(e,t);ue.compileRe=(e,t,r=false,n=false)=>{if(r===true)return e.output;let s=t||{},i=s.contains?"":"^",o=s.contains?"":"$",a=`${i}(?:${e.output})${o}`;e&&e.negated===true&&(a=`^(?!${a}).*$`);let l=ue.toRegex(a,t);return n===true&&(l.state=e),l};ue.makeRe=(e,t={},r=false,n=false)=>{if(!e||typeof e!="string")throw new TypeError("Expected a non-empty string");let s={negated:false,fastpaths:true};return t.fastpaths!==false&&(e[0]==="."||e[0]==="*")&&(s.output=ya.fastpaths(e,t)),s.output||(s=ya(e,t)),ue.compileRe(s,t,r,n)};ue.toRegex=(e,t)=>{try{let r=t||{};return new RegExp(e,r.flags||(r.nocase?"i":""))}catch(r){if(t&&t.debug===true)throw r;return /$^/}};ue.constants=FS;xf.exports=ue;});var Af=ft((BR,Tf)=>{var $f=_f(),US=Kr();function vf(e,t,r=false){return t&&(t.windows===null||t.windows===void 0)&&(t={...t,windows:US.isWindows()}),$f(e,t,r)}Object.assign(vf,$f);Tf.exports=vf;});function ZS(e,t={}){let r=e.length,n=Array(r),s=Array(r),i,o;for(i=0;i<r;i++){let a=Nf(e[i]);n[i]=a;let l=a.length,c=Array(l);for(o=0;o<l;o++)c[o]=(0, ur.default)(a[o],t);s[i]=c;}return a=>{let l=a.split("/");if(l[0]===".."&&QS.test(a))return true;for(i=0;i<r;i++){let c=n[i],p=s[i],u=l.length,f=Math.min(u,c.length);for(o=0;o<f;){let h=c[o];if(h.includes("/"))return true;if(!p[o](l[o]))break;if(!t.noglobstar&&h==="**")return true;o++;}if(o===u)return true}return false}}function Cf(e,t,r){if(e===t||t.startsWith(`${e}/`)){if(r){let s=e.length+ +!tE(e);return (i,o)=>i.slice(s,o?-1:void 0)||"."}let n=t.slice(e.length+1);return n?(s,i)=>{if(s===".")return n;let o=`${n}/${s}`;return i?o.slice(0,-1):o}:(s,i)=>i&&s!=="."?s.slice(0,-1):s}return r?n=>posix.relative(e,n)||".":n=>posix.relative(e,`${t}/${n}`)||"."}function rE(e,t){if(t.startsWith(`${e}/`)){let r=t.slice(e.length+1);return n=>`${r}/${n}`}return r=>{let n=posix.relative(e,`${t}/${r}`);return r[r.length-1]==="/"&&n!==""?`${n}/`:n||"."}}function Rf(e){return e.replace(YS,t=>`${t}/`)}function Nf(e){var t;let r=ur.default.scan(e,nE);return !((t=r.parts)===null||t===void 0)&&t.length?r.parts:[e]}function cE(e,t){let r=ur.default.scan(e);return r.isGlob||r.negated}function Yr(...e){console.log(`[tinyglobby ${new Date().toLocaleTimeString("es")}]`,...e);}function If(e){return typeof e=="string"?[e]:e??[]}function wa(e,t,r,n){var s;let i=t.cwd,o=e;e[e.length-1]==="/"&&(o=e.slice(0,-1)),o[o.length-1]!=="*"&&t.expandDirectories&&(o+="/**");let a=lE(i);o=isAbsolute(o.replace(pE,""))?posix.relative(a,o):posix.normalize(o);let l=(s=uE.exec(o))===null||s===void 0?void 0:s[0],c=Nf(o);if(l){let u=(l.length+1)/3,f=0,h=a.split("/");for(;f<u&&c[f+u]===h[h.length+f-u];)o=o.slice(0,(u-f-1)*3)+o.slice((u-f)*3+c[f+u].length+1)||".",f++;let d=posix.join(i,l.slice(f*3));d[0]!=="."&&r.root.length>d.length&&(r.root=Rf(d),r.depthOffset=-u+f);}if(!n&&r.depthOffset>=0){var p;(p=r.commonPath)!==null&&p!==void 0||(r.commonPath=c);let u=[],f=Math.min(r.commonPath.length,c.length);for(let h=0;h<f;h++){let d=c[h];if(d==="**"&&!c[h+1]){u.pop();break}if(h===c.length-1||d!==r.commonPath[h]||cE(d))break;u.push(d);}r.depthOffset=u.length,r.commonPath=u,r.root=Rf(u.length>0?posix.join(i,...u):i);}return o}function fE(e,t,r){let n=[],s=[];for(let i of e.ignore)i&&(i[0]!=="!"||i[1]==="(")&&s.push(wa(i,e,r,true));for(let i of t)i&&(i[0]!=="!"||i[1]==="("?n.push(wa(i,e,r,false)):(i[1]!=="!"||i[2]==="(")&&s.push(wa(i.slice(1),e,r,true)));return {match:n,ignore:s}}function mE(e,t){let r=e.cwd,n={root:r,depthOffset:0},s=fE(e,t,n);e.debug&&Yr("internal processing patterns:",s);let{absolute:i,caseSensitiveMatch:o,debug:a,dot:l,followSymbolicLinks:c,onlyDirectories:p}=e,u=n.root.replace(Pf,""),f={dot:l,nobrace:e.braceExpansion===false,nocase:!o,noextglob:e.extglob===false,noglobstar:e.globstar===false,posix:true},h=(0, ur.default)(s.match,f),d=(0, ur.default)(s.ignore,f),m=ZS(s.match,f),w=Cf(r,u,i),y=i?w:Cf(r,u,true),E=(C,A)=>{let $=y(A,true);return $!=="."&&!m($)||d($)},T;e.deep!==void 0&&(T=Math.round(e.deep-n.depthOffset));let v=new ef({filters:[a?(C,A)=>{let $=w(C,A),_=h($)&&!d($);return _&&Yr(`matched ${$}`),_}:(C,A)=>{let $=w(C,A);return h($)&&!d($)}],exclude:a?(C,A)=>{let $=E(C,A);return Yr(`${$?"skipped":"crawling"} ${A}`),$}:E,fs:e.fs,pathSeparator:"/",relativePaths:!i,resolvePaths:i,includeBasePath:i,resolveSymlinks:c,excludeSymlinks:!c,excludeFiles:p,includeDirs:p||!e.onlyFiles,maxDepth:T,signal:e.signal}).crawl(u);return e.debug&&Yr("internal properties:",{...n,root:u}),[v,r!==u&&!i&&rE(r,u)]}function dE(e,t){if(t)for(let r=e.length-1;r>=0;r--)e[r]=t(e[r]);return e}function hE(e){let t=Object.assign({},e);for(let r in kf)t[r]===void 0&&Object.assign(t,{[r]:kf[r]});return t.cwd=(t.cwd instanceof URL?fileURLToPath$1(t.cwd):resolve(t.cwd||process.cwd())).replace(Pf,"/"),t.ignore=If(t.ignore),t.fs&&(t.fs={readdir:t.fs.readdir||readdir,readdirSync:t.fs.readdirSync||readdirSync,realpath:t.fs.realpath||realpath,realpathSync:t.fs.realpathSync||realpathSync,stat:t.fs.stat||stat,statSync:t.fs.statSync||statSync$1}),t.debug&&Yr("globbing with options:",t),t}function gE(e,t={}){var r;if(e&&t?.patterns)throw new Error("Cannot pass patterns as both an argument and an option");let n=JS(e)||typeof e=="string",s=If((r=n?e:e.patterns)!==null&&r!==void 0?r:"**/*"),i=hE(n?t:e);return s.length>0?mE(i,s):[]}async function Qr(e,t){let[r,n]=gE(e,t);return r?dE(await r.withPromise(),n):[]}var ur,JS,Pf,YS,Of,QS,eE,tE,nE,sE,iE,oE,aE,lE,uE,pE,kf,ba=g(()=>{tf();ur=te(Af()),JS=Array.isArray,Pf=/\\/g,YS=/^[A-Za-z]:$/,Of=process.platform==="win32",QS=/^(\/?\.\.)+$/;eE=/^[A-Z]:\/$/i,tE=Of?e=>eE.test(e):e=>e==="/";nE={parts:true};sE=/(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g,iE=/(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g,oE=e=>e.replace(sE,"\\$&"),aE=e=>e.replace(iE,"\\$&"),lE=Of?aE:oE;uE=/^(\/?\.\.)+/,pE=/\\(?=[()[\]{}!*+?@|])/g;kf={caseSensitiveMatch:true,debug:!!process.env.TINYGLOBBY_DEBUG,expandDirectories:true,followSymbolicLinks:true,onlyFiles:true};});function Le(e){return e.dialect==="postgres"?"pg":e.config?.ddlDialect==="sqlite"?"sqlite":"pg-flat"}function Ns(e){return e==="sqlite"?{schema_migrations:"migrations",seed_files:"seed_files"}:e==="pg-flat"?{schema_migrations:'"supabase_migrations.schema_migrations"',seed_files:'"supabase_migrations.seed_files"'}:{schema_migrations:"supabase_migrations.schema_migrations",seed_files:"supabase_migrations.seed_files"}}function Zr(e){return `'${e.replace(/'/g,"''")}'`}function yE(e){return `'${`{${e.map(n=>`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`).join(",")}}`.replace(/'/g,"''")}'`}function wE(e){return e==="sqlite"?[`CREATE TABLE IF NOT EXISTS migrations (
63
65
  version TEXT NOT NULL PRIMARY KEY,
64
66
  statements TEXT,
65
67
  name TEXT
@@ -73,21 +75,21 @@ create table test (
73
75
  )`,`CREATE TABLE IF NOT EXISTS supabase_migrations.seed_files (
74
76
  path text NOT NULL PRIMARY KEY,
75
77
  hash text NOT NULL
76
- )`]}function Nf(e,t){let{schema_migrations:r}=Os(e),n=t.name===null?"NULL":Qr(t.name),s=e==="pg"?dE(t.statements):Qr(JSON.stringify(t.statements));return `INSERT INTO ${r} (version, statements, name) VALUES (${Qr(t.version)}, ${s}, ${n})`}function gE(e){let{schema_migrations:t}=Os(e);return `SELECT version FROM ${t} ORDER BY version ASC`}function yE(e){let{seed_files:t}=Os(e);return t?`SELECT path, hash FROM ${t}`:null}function If(e,t){let{seed_files:r}=Os(e);return r?`INSERT INTO ${r} (path, hash) VALUES (${Qr(t.path)}, ${Qr(t.hash)}) ON CONFLICT (path) DO UPDATE SET hash = EXCLUDED.hash`:null}async function wE(e,t){if(e.dialect==="postgres"||e.config.ddlDialect==="sqlite")return t;let n=await e.translateDdl(t);return typeof n=="string"?n:n.ddl??t}function bE(e){return e.split(/;\s*(?:\n|$)/).map(t=>t.trim()).filter(t=>t.length>0)}async function Lt(e){let t=Le(e),n=hE(t).map(i=>i.trim()).join(`;
77
- `)+";",s=await wE(e,n);for(let i of bE(s))await e.exec(i);}async function Zr(e){let t=Le(e);return ((await e.exec(gE(t)))?.rows??[]).map(n=>n.version)}async function Lf(e){let t=Le(e),r=yE(t);return r?((await e.exec(r))?.rows??[]).map(s=>({path:s.path,hash:s.hash})):[]}var Dt=g(()=>{});function jf(e){return Le(e.connection)==="sqlite"?"./sqlite-migrations/*.sql":"./migrations/*.sql"}function jt(e){return Me__default.posix.dirname(jf(e))}async function Ue(e){let t=Me__default.join(process.cwd(),"supabase"),r=await Yr([jf(e)],{cwd:t,absolute:true}),n=[];for(let s of r){let i=Me__default.basename(s),o=SE.exec(i);if(!o)continue;let a=await pe__default.readFile(s,"utf-8");n.push({version:o[1],name:o[2]??null,filename:i,path:s,sql:a});}return n.sort((s,i)=>s.version.localeCompare(i.version))}async function Ns(e){return (await Ue(e)).map(r=>r.sql).join(`
78
- `)}function wa(e=new Date){return e.getUTCFullYear().toString().padStart(4,"0")+(e.getUTCMonth()+1).toString().padStart(2,"0")+e.getUTCDate().toString().padStart(2,"0")+e.getUTCHours().toString().padStart(2,"0")+e.getUTCMinutes().toString().padStart(2,"0")+e.getUTCSeconds().toString().padStart(2,"0")}function ba(e,t=wa()){let r=e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"");return r.length>0?`${t}_${r}.sql`:`${t}.sql`}async function Ff(e,t,r){let n=Me__default.join(process.cwd(),"supabase",jt(e));ke(n);let s=ba(t,r?.ts),i=Me__default.join(n,s);return await pe__default.writeFile(i,"",{flag:"wx"}),i}var SE,wt=g(()=>{ya();Dt();Tt();SE=/^(\d{14})(?:_([^.]+))?\.sql$/;});function tn(e){if("String"in e)return e.String.sval}function bt(e){return e.map(tn).filter(t=>t!=null)}function Ft(e){return e==null?[]:e.List!==void 0?e.List.items||[]:Array.isArray(e)?e:[e]}function Is(e){return QuoteUtils.quoteIdentifier(e)}function pr(e){return Object.keys(e)[0]}function Mf(e){if("A_Const"in e){if(e.A_Const.ival)return e.A_Const.ival.ival;if(e.A_Const.fval)return e.A_Const.fval.fval;if(e.A_Const.sval)return e.A_Const.sval.sval;if(e.A_Const.boolval)return e.A_Const.boolval.boolval;if(e.A_Const.isnull)return null}}var Mt=g(()=>{});function Bf(e){let t=e.toLowerCase().trim();if(t.startsWith("_")||t.endsWith("[]"))return "TEXT";let r=_E[t];if(!r)throw new Ut(`Unsupported PostgreSQL type: "${e}"`);return r}function Ls(e){let t=e.toLowerCase();return ["serial","serial4","bigserial","serial8","smallserial","serial2"].includes(t)}function Ds(e){let t=e.toLowerCase();return ["varchar","character varying","char","character","bpchar"].includes(t)}function js(e){let t=e.toLowerCase();return ["numeric","decimal"].includes(t)}var Ut,B,_E,Uf,$E,Fs,fr=g(()=>{Mt();Ut=class extends Error{},B=class extends Ut{constructor(r,n){super(n??`Unsupported node type: ${pr(r)}`);this.node=r;}},_E={int2:"INTEGER",smallint:"INTEGER",int4:"INTEGER",integer:"INTEGER",int:"INTEGER",int8:"INTEGER",bigint:"INTEGER",serial:"INTEGER",serial4:"INTEGER",bigserial:"INTEGER",serial8:"INTEGER",smallserial:"INTEGER",serial2:"INTEGER",float4:"REAL",real:"REAL",float8:"REAL","double precision":"REAL",numeric:"REAL",decimal:"REAL",text:"TEXT",varchar:"TEXT","character varying":"TEXT",char:"TEXT",character:"TEXT",bpchar:"TEXT",name:"TEXT",bytea:"BLOB",bool:"INTEGER",boolean:"INTEGER",date:"TEXT",time:"TEXT","time without time zone":"TEXT",timetz:"TEXT","time with time zone":"TEXT",timestamp:"TEXT","timestamp without time zone":"TEXT",timestamptz:"TEXT","timestamp with time zone":"TEXT",interval:"TEXT",json:"TEXT",jsonb:"TEXT",uuid:"TEXT",inet:"TEXT"},Uf=["<",">","<=",">=","=","<>","!=","+","-","*","/","%","&","|","<<",">>","||","BETWEEN","NOT BETWEEN","IN","NOT IN","LIKE","NOT LIKE","IS NULL","IS NOT NULL","IS TRUE","IS NOT TRUE","IS FALSE","IS NOT FALSE","IS UNKNOWN","IS NOT UNKNOWN","AND","OR","NOT","->>"];$E={CreateEnumStmt:{react:"ignore"},CreateDomainStmt:{react:"warn"},CreateSeqStmt:{react:"ignore"},AlterSeqStmt:{react:"ignore"},CreateSchemaStmt:{react:"warn"},CreatePolicyStmt:{react:"ignore"},AlterPolicyStmt:{react:"ignore"},PartitionElem:{react:"error"},PartitionCmd:{react:"error"},VariableSetStmt:{react:"ignore"},CompositeTypeStmt:{react:"error"},AlterEnumStmt:{react:"error"},AlterObjectSchemaStmt:{react:"error"},AlterOwnerStmt:{react:"error"},AlterTypeStmt:{react:"error"},AlterFunctionStmt:{react:"error"},AlterDefaultPrivilegesStmt:{react:"error"},GrantStmt:{react:"error"},GrantRoleStmt:{react:"error"},CopyStmt:{react:"error"},CreateCastStmt:{react:"error"},AlterOpFamilyStmt:{react:"error"},AlterOperatorStmt:{react:"error"},TruncateStmt:{react:"error"},A_Indirection:{react:"error"},XmlExpr:{react:"error"},XmlSerialize:{react:"error"},RangeTableSample:{react:"error"},GroupingSet:{react:"error"}},Fs=new Map(Object.entries($E));});var Be,rn,Sa=g(()=>{Mt();fr();Be=class extends B{constructor(t,r){super(t,`Unsupported expression: ${r}`);}},rn=class{deparse(t){if("A_Const"in t){let s=t.A_Const;if(s.boolval!==void 0)return s.boolval.boolval?{}:{$always:false}}let r=Object.keys(t)[0],n=this[r];if(!n)throw new Be({[r]:t},`Unsupported expression: ${r}`);return n.call(this,t[r])}deparseValue(t){if("A_Const"in t)return this.A_Const(t.A_Const);if("ColumnRef"in t)return this.ColumnRef(t.ColumnRef);if("FuncCall"in t)return this.FuncCall(t.FuncCall);if("SubLink"in t)return this.SubLink(t.SubLink);if("TypeCast"in t)return this.TypeCast(t.TypeCast);if("A_Expr"in t){let n=this.isJwtAccessor(t.A_Expr);return n||this.A_Expr(t.A_Expr)}if("BoolExpr"in t)return this.BoolExpr(t.BoolExpr);let r=Object.keys(t)[0];throw new Be({[r]:t},`deparseValue: ${r}`)}A_Expr(t){if(t.kind==="AEXPR_OP"){let r=t.name?.[0],n=r?tn(r):void 0;if(!n)throw new Be({A_Expr:t},"A_Expr missing operator");let s=this.isJwtAccessor(t);if(s)return {[s]:{}};let i=t.lexpr?this.deparseValue(t.lexpr):void 0,o=t.rexpr?this.deparseValue(t.rexpr):void 0,a=this.mapOperator(n);if(!a)throw new Be({A_Expr:t},`Unsupported operator: ${n}`);let l=t.rexpr!=null&&"ColumnRef"in t.rexpr;if(typeof i=="string"&&i.startsWith("{{")&&l)return {[o]:{[a]:i}};let c=l&&typeof o=="string"?{$ref:o}:o;return {[i]:{[a]:c}}}if(t.kind==="AEXPR_LIKE"||t.kind==="AEXPR_ILIKE"){let r=t.lexpr?this.deparseValue(t.lexpr):void 0,n=t.rexpr?this.deparseValue(t.rexpr):void 0,i=(t.name?.[0]?tn(t.name[0]):"~~")==="!~~"?"$notLike":"$like";return {[r]:{[i]:n}}}if(t.kind==="AEXPR_IN"){let r=t.lexpr?this.deparseValue(t.lexpr):void 0,n=t.rexpr&&"List"in t.rexpr&&t.rexpr.List.items?t.rexpr.List.items.map(s=>this.deparseValue(s)):[];return {[r]:{$in:n}}}throw new Be({A_Expr:t},`A_Expr kind: ${t.kind}`)}BoolExpr(t){let r=t.args??[];switch(t.boolop){case "AND_EXPR":return {$and:r.map(n=>this.deparse(n))};case "OR_EXPR":return {$or:r.map(n=>this.deparse(n))};case "NOT_EXPR":return {$not:this.deparse(r[0])};default:throw new Be({BoolExpr:t},`BoolExpr op: ${t.boolop}`)}}NullTest(t){let r=t.arg?this.deparseValue(t.arg):void 0;return t.nulltesttype==="IS_NULL"?{[r]:{$is:null}}:{[r]:{$isNot:null}}}SubLink(t){if(t.subLinkType==="ANY_SUBLINK"){let r=t.testexpr?this.deparseValue(t.testexpr):void 0,n=t.subselect?this.SelectStmt(t.subselect.SelectStmt):void 0;return {[r]:{$in:n}}}if(t.subLinkType==="EXISTS_SUBLINK")return {$exists:t.subselect?this.SelectStmt(t.subselect.SelectStmt):void 0};if(t.subLinkType==="EXPR_SUBLINK"){let r=t.subselect?t.subselect.SelectStmt:void 0;if(r?.fromClause?.length)return this.SelectStmt(r);if(r?.targetList?.[0]){let n=r.targetList[0],s="ResTarget"in n?n.ResTarget:void 0;if(s?.val){let i=this.deparseValue(s.val);return i}}}throw new Be({SubLink:t},`SubLink type: ${t.subLinkType}`)}SelectStmt(t){let{from:r,schema:n,join:s}=this.deparseFromClause(t.fromClause??[]),i=[];for(let f of t.targetList??[]){let h="ResTarget"in f?f.ResTarget:void 0;if(h?.val){let d=this.deparseValue(h.val);Array.isArray(d)?i.push(...d.map(String)):d!=null&&d!==""&&i.push(String(d));}}let o=t.whereClause?this.deparse(t.whereClause):void 0,a=this.deparseSortClause(t.sortClause),l=this.deparseLimit(t.limitCount),c=this.deparseLimit(t.limitOffset),p=this.deparseGroupClause(t.groupClause),u={type:"query",from:r,select:i};return n&&(u.schema=n),Object.keys(s).length>0&&(u.join=s),o&&(u.where=o),a.length>0&&(u.order=a),l!==void 0&&(u.limit=l),c!==void 0&&(u.offset=c),p.length>0&&(u.group=p),u}FuncCall(t){let r=this.isAuthFunc(t.funcname??[]);if(r)return r;throw new Be({FuncCall:t},`FuncCall: ${bt(t.funcname??[]).join(".")}`)}ColumnRef(t){let r=bt(t.fields??[]);return r.length===1?r[0]:r.join(".")}A_Const(t){if(t.boolval!==void 0)return t.boolval.boolval;if(t.ival!==void 0)return t.ival.ival??0;if(t.fval!==void 0)return parseFloat(t.fval.fval??"0");if(t.sval!==void 0)return t.sval.sval??"";if(t.isnull)return null;throw new Be({A_Const:t},"A_Const: unknown variant")}TypeCast(t){if(!t.arg)throw new Be({TypeCast:t},"TypeCast: missing arg");return this.deparseValue(t.arg)}BooleanTest(t){let r=t.arg?this.deparseValue(t.arg):void 0;return t.booltesttype==="IS_TRUE"?{[r]:{$eq:true}}:{[r]:{$eq:false}}}deparseFromClause(t){let r={};if(t.length===0)return {from:"",join:r};let n=t[0];if("RangeVar"in n){let s=n.RangeVar;return {from:s.relname??"",schema:s.schemaname,join:r}}if("JoinExpr"in n){let{from:s,schema:i}=this.walkJoinExpr(n.JoinExpr,r);return {from:s,schema:i,join:r}}return {from:"",join:r}}walkJoinExpr(t,r){let n={from:""};if(t.larg)if("RangeVar"in t.larg){let s=t.larg.RangeVar;n={from:s.relname??"",schema:s.schemaname};}else "JoinExpr"in t.larg&&(n=this.walkJoinExpr(t.larg.JoinExpr,r));if(t.rarg&&"RangeVar"in t.rarg){let s=t.rarg.RangeVar,i=s.relname??"",o=s.alias?.aliasname??i,a=t.jointype==="JOIN_LEFT"?"left":"inner",l={from:i,type:a};t.quals&&(l.on=this.deparse(t.quals));let c=o;if(c in r){let p=2;for(;`${c}_${p}`in r;)p++;c=`${c}_${p}`;}r[c]=l;}return n}deparseSortClause(t){if(!t)return [];let r=[];for(let n of t){if(!("SortBy"in n))continue;let s=n.SortBy;if(!s.node)continue;let i=String(this.deparseValue(s.node)),o=s.sortby_dir==="SORTBY_DESC"?"desc":"asc",a={column:i,direction:o};s.sortby_nulls==="SORTBY_NULLS_FIRST"?a.nullsFirst=true:s.sortby_nulls==="SORTBY_NULLS_LAST"&&(a.nullsFirst=false),r.push(a);}return r}deparseLimit(t){if(!t)return;let r=this.deparseValue(t);return typeof r=="number"?r:Number(r)}deparseGroupClause(t){return t?t.map(r=>String(this.deparseValue(r))):[]}isAuthFunc(t){let r=bt(t);if(r.length===2&&r[0]==="auth"){if(r[1]==="uid")return "{{auth.uid}}";if(r[1]==="jwt")return "{{auth.jwt}}";if(r[1]==="role")return "{{auth.role}}";throw new Error(`Unsupported auth function: "${r.slice(1).join(".")}"`)}return null}isJwtAccessor(t){if(t.kind!=="AEXPR_OP")return null;let r=t.name?.[0]?tn(t.name[0]):void 0;if(r!=="->"&&r!=="->>")return null;let n=t.rexpr&&"A_Const"in t.rexpr?t.rexpr.A_Const.sval?.sval:void 0;if(n===void 0)return null;if(t.lexpr&&"FuncCall"in t.lexpr)return this.isAuthFunc(t.lexpr.FuncCall.funcname??[])==="{{auth.jwt}}"?`{{auth.jwt.${n}}}`:null;if(t.lexpr&&"A_Expr"in t.lexpr){let s=this.isJwtAccessor(t.lexpr.A_Expr);if(s)return `${s.slice(0,-2)}.${n}}}`}return null}mapOperator(t){switch(t){case "=":return "$eq";case "<>":case "!=":return "$neq";case ">":return "$gt";case ">=":return "$gte";case "<":return "$lt";case "<=":return "$lte";case "~~":return "$like";case "!~~":return "$notLike";default:return}}};});var Bt,Ea=g(()=>{Bt=class e{constructor(t){this.data=t;}appliesTo(t){return this.data.command==="ALL"||this.data.command===t}appliesToRole(t){return this.data.roles.length===0||this.data.roles.includes(t)}toJSON(){return this.data}static fromJSON(t){return new e(t)}};});var nn,xa=g(()=>{nn=class extends Error{constructor(r,n,s,i){super(`check constraint "${s}" violated for ${r}.${n}`);this.table=r;this.column=n;this.constraint=s;this.value=i;this.name="CheckConstraintError";}};});var we,st=g(()=>{xa();we=class{context;constructor(t){this.context=t;}get isShimBacked(){return false}checkConstraint(){return null}serialize(t){return t}deserialize(t){return t}validateStorage(t){return {status:"pass",message:null}}validationFail(t,r){return {status:"fail",message:t,action:r}}validationPass(){return {status:"pass",message:null}}isNullish(t){return t==null}toColumnDDL(t){let{includeNullable:r=true}=t??{},n=[],s=this.context.column;n.push(this.quoteIfNeeded(s)),n.push(this.sqliteType),this.context.isPrimaryKey&&n.push("PRIMARY KEY"),this.context.isSerial&&this.context.isPrimaryKey&&n.push("AUTOINCREMENT"),r&&!this.context.nullable&&!this.context.isPrimaryKey&&n.push("NOT NULL"),this.context.isUnique&&!this.context.isPrimaryKey&&n.push("UNIQUE"),this.context.defaultValue!==null&&n.push(`DEFAULT ${this.context.defaultValue}`);let i=this.checkConstraint();return i&&n.push(`CHECK (${i})`),n.join(" ")}checkError(t,r){return new nn(this.context.table,this.context.column,t,r)}quoteIfNeeded(t){return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)?t:`"${t}"`}};});var qt,Ms=g(()=>{st();qt=class extends we{get sqliteType(){return "INTEGER"}};});var sn,_a=g(()=>{Ms();sn=class extends qt{constructor(t){super({...t,isSerial:true});}};});function vE(e,t){let{precision:r,scale:n}=t,s=10**n,i=10**(r-n);return Math.abs(Math.round(e*s)-e*s)<1e-4&&Math.abs(e)<i}var Ht,Us=g(()=>{st();Ht=class extends we{numericPrecision;constructor(t,r){super(t),this.numericPrecision=r;}get isShimBacked(){return this.numericPrecision!==void 0}get sqliteType(){return "REAL"}checkConstraint(){if(this.numericPrecision){let{precision:t,scale:r}=this.numericPrecision,n=this.context.column,s=10**r,i=10**(t-r);return `ABS(ROUND(${n} * ${s}) - ${n} * ${s}) < 0.0001 AND ABS(${n}) < ${i}`}return null}validateStorage(t){if(this.isNullish(t))return this.validationPass();if(typeof t!="number"||!Number.isFinite(t))return this.validationFail("Expected finite number.","Patch rows with finite numbers.");if(this.numericPrecision){let{precision:r,scale:n}=this.numericPrecision;if(!vE(t,this.numericPrecision))return this.validationFail(`Does not fit numeric(${r}, ${n}).`,"Patch rows within numeric precision.")}return this.validationPass()}};});var le,qe=g(()=>{st();le=class extends we{lengthConstraint;constructor(t,r){super(t),this.lengthConstraint=r;}get isShimBacked(){return this.lengthConstraint!==void 0}get sqliteType(){return "TEXT"}checkConstraint(){return this.lengthConstraint!==void 0?`length(${this.context.column}) <= ${this.lengthConstraint}`:null}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"?this.validationFail("Expected text.","Patch rows with text values."):this.lengthConstraint!==void 0&&Array.from(t).length>this.lengthConstraint?this.validationFail(`Exceeds length ${this.lengthConstraint}.`,"Patch rows with shorter text."):this.validationPass()}};});var on,$a=g(()=>{st();on=class extends we{get sqliteType(){return "BLOB"}};});var an,va=g(()=>{st();an=class extends we{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}checkConstraint(){return `${this.context.column} IN (0, 1)`}serialize(t){if(this.isNullish(t))return t;if(t===true||t===1)return 1;if(t===false||t===0)return 0;throw this.checkError("boolean_range",t)}deserialize(t){if(this.isNullish(t)||t===true||t===false)return t;if(typeof t=="number"&&Number.isFinite(t)){if(t===1)return true;if(t===0)return false}return t===1n?true:t===0n?false:t==="1"||t==="true"?true:t==="0"||t==="false"?false:t}validateStorage(t){return this.isNullish(t)?this.validationPass():t===1||t===0?this.validationPass():this.validationFail("Expected 0 or 1.","Patch rows with boolean values.")}};});function qf(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var ln,Ta=g(()=>{st();ln=class extends we{get isShimBacked(){return true}get sqliteType(){return "TEXT"}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR json_valid(${t})`}serialize(t){if(this.isNullish(t))return t;try{return JSON.stringify(t)}catch{throw this.checkError("json_valid",t)}}deserialize(t){if(this.isNullish(t))return t;if(typeof t=="string"){let r=qf(t);return r.ok?r.value:t}return t}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"?this.validationFail("Expected JSON text.","Patch rows with JSON values."):qf(t).ok?this.validationPass():this.validationFail("Invalid JSON text.","Patch rows with valid JSON.")}};});function TE(e){if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return false;let t=new Date(`${e}T00:00:00.000Z`);return !Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e}var cn,Aa=g(()=>{qe();cn=class extends le{get isShimBacked(){return true}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR date(${t}) IS NOT NULL`}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!TE(t)?this.validationFail("Invalid date.","Patch rows with YYYY-MM-DD dates."):this.validationPass()}};});function AE(e){let t=e.match(/^(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?([+-](\d{2}):?(\d{2}))?$/);if(!t)return false;let r=Number(t[1]),n=Number(t[2]),s=t[3]===void 0?0:Number(t[3]),i=t[5]===void 0?null:Number(t[5]),o=t[6]===void 0?null:Number(t[6]),a=i===null||o!==null&&i<=15&&o<=59;return r<=24&&n<=59&&s<=59&&(r!==24||n===0&&s===0)&&a}var un,Ca=g(()=>{qe();un=class extends le{get isShimBacked(){return true}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR time(${t}) IS NOT NULL`}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!AE(t)?this.validationFail("Invalid time.","Patch rows with HH:MM[:SS] times."):this.validationPass()}};});function CE(e){let t=e.match(/^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?(?:Z|([+-](\d{2}):?(\d{2})))?$/);if(!t)return false;let r=Number(t[1]),n=Number(t[2]),s=Number(t[3]),i=Number(t[4]),o=Number(t[5]),a=t[6]===void 0?0:Number(t[6]),l=t[8]===void 0?null:Number(t[8]),c=t[9]===void 0?null:Number(t[9]),p=new Date(Date.UTC(r,n-1,s)),u=p.getUTCFullYear()===r&&p.getUTCMonth()===n-1&&p.getUTCDate()===s,f=i<=24&&o<=59&&a<=59&&(i!==24||o===0&&a===0),h=l===null||c!==null&&l<=15&&c<=59;return u&&f&&h}var pn,Ra=g(()=>{qe();pn=class extends le{get isShimBacked(){return true}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR datetime(${t}) IS NOT NULL`}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!CE(t)?this.validationFail("Invalid timestamp.","Patch rows with ISO timestamps."):this.validationPass()}};});var fn,ka=g(()=>{qe();fn=class extends le{get isShimBacked(){return true}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||t.trim().length===0?this.validationFail("Expected interval text.","Patch rows with interval strings."):/^-?\d+(?:\.\d+)?$/.test(t.trim())?this.validationFail("Ambiguous numeric interval.","Patch rows with explicit interval strings."):this.validationPass()}};});var mn,Pa=g(()=>{qe();mn=class extends le{enumValues;constructor(t,r){super(t),this.enumValues=r;}get isShimBacked(){return true}checkConstraint(){let t=this.context.column,r=this.enumValues.map(n=>`'${n.replace(/'/g,"''")}'`).join(", ");return `${t} IN (${r})`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string"||!this.enumValues.includes(t))throw this.checkError("enum_membership",t);return t}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!this.enumValues.includes(t)?this.validationFail("Invalid enum value.","Patch rows with declared enum values."):this.validationPass()}};});function Hf(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var St,Bs=g(()=>{st();St=class extends we{elementField;constructor(t,r){super(t),this.elementField=r;}get sqliteType(){return "TEXT"}get isShimBacked(){return true}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR (json_valid(${t}) AND json_type(${t}) = 'array')`}serialize(t){if(this.isNullish(t))return t;if(!Array.isArray(t))throw this.checkError("array_type",t);return this.elementField?JSON.stringify(t.map(r=>this.elementField.serialize(r))):JSON.stringify(t)}deserialize(t){if(this.isNullish(t))return t;if(typeof t=="string"){let r=Hf(t);if(r.ok&&Array.isArray(r.value))return this.elementField?r.value.map(n=>this.elementField.deserialize(n)):r.value}return t}validateStorage(t){if(this.isNullish(t))return this.validationPass();if(typeof t!="string")return this.validationFail("Expected JSON array text.","Patch rows with array values.");let r=Hf(t);if(!r.ok)return this.validationFail("Invalid JSON array text.","Patch rows with array values.");if(!Array.isArray(r.value))return this.validationFail("Expected JSON array.","Patch rows with array values.");if(this.elementField)for(let n of r.value){let s=this.elementField.validateStorage(n);if(s.status==="fail")return this.validationFail(`Invalid ${this.elementField.context.pgTypeName} array element.`,s.action??"Patch rows with valid array elements.")}return this.validationPass()}};});function Wf(e){return kE.test(e.toLowerCase())}var RE,kE,dn,Oa=g(()=>{qe();RE="????????-????-????-????-????????????",kE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;dn=class extends le{get isShimBacked(){return true}checkConstraint(){let t=this.quoteIfNeeded(this.context.column);return `${t} IS NULL OR ${t} GLOB '${RE}'`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string")throw this.checkError("uuid_format",t);let r=t.toLowerCase();if(!Wf(r))throw this.checkError("uuid_format",t);return r}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!Wf(t)?this.validationFail("Invalid UUID.","Patch rows with valid UUIDs."):this.validationPass()}};});function PE(e){let t=e.split("/");if(t.length>2)return null;let r=t[0];if(!r)return null;if(t.length===1)return {address:r,prefix:null};let n=t[1];return !n||!/^\d+$/.test(n)?null:{address:r,prefix:Number(n)}}function OE(e){let t=e.split(".");return t.length!==4?false:t.every(r=>{if(!/^\d+$/.test(r))return false;let n=Number(r);return n>=0&&n<=255})}function NE(e){if(!e.includes(":"))return false;try{return new URL(`http://[${e}]/`),!0}catch{return false}}function Gf(e){let t=PE(e);return t?OE(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=32:NE(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=128:false:false}var hn,Na=g(()=>{qe();hn=class extends le{get isShimBacked(){return true}checkConstraint(){let t=this.quoteIfNeeded(this.context.column);return `${t} IS NULL OR (length(${t}) BETWEEN 3 AND 49 AND (instr(${t}, '.') > 0 OR instr(${t}, ':') > 0))`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string")throw this.checkError("inet_format",t);let r=t.trim();if(!Gf(r))throw this.checkError("inet_format",t);return r}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!Gf(t.trim())?this.validationFail("Invalid inet address.","Patch rows with valid inet strings."):this.validationPass()}};});var gn,Ia=g(()=>{qe();gn=class extends le{serialize(t){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}deserialize(t){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}toColumnDDL(){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}};});function Wt(e,t){if(t?.isArray){let n=Wt(e,{...t,isArray:false});return new St(e,n)}if(t?.enumValues)return new mn(e,t.enumValues);let r=e.pgTypeName.toLowerCase().trim();if(r.startsWith("_")||r.endsWith("[]")){let n=r.startsWith("_")?r.slice(1):r.slice(0,-2),s={...e,pgTypeName:n},i=Wt(s);return new St(e,i)}return LE.has(r)?new sn(e):IE.has(r)?new qt(e):ME.has(r)?new an(e):UE.has(r)?new ln(e):WE.has(r)?new cn(e):GE.has(r)?new un(e):zE.has(r)?new pn(e):VE.has(r)?new fn(e):FE.has(r)?new on(e):DE.has(r)?new Ht(e,t?.numericPrecision):BE.has(r)?new dn(e):qE.has(r)?new le(e,63):HE.has(r)?new hn(e):jE.has(r)?new le(e,t?.lengthConstraint):new gn(e)}var IE,LE,DE,jE,FE,ME,UE,BE,qE,HE,WE,GE,zE,VE,La=g(()=>{Ms();_a();Us();qe();$a();va();Ta();Aa();Ca();Ra();ka();Pa();Bs();Oa();Na();Ia();IE=new Set(["int2","smallint","int4","integer","int","int8","bigint"]),LE=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]),DE=new Set(["float4","real","float8","double precision","numeric","decimal"]),jE=new Set(["text","varchar","character varying","char","character","bpchar"]),FE=new Set(["bytea"]),ME=new Set(["bool","boolean"]),UE=new Set(["json","jsonb"]),BE=new Set(["uuid"]),qE=new Set(["name"]),HE=new Set(["inet"]),WE=new Set(["date"]),GE=new Set(["time","timetz","time without time zone","time with time zone"]),zE=new Set(["timestamp","timestamptz","timestamp without time zone","timestamp with time zone"]),VE=new Set(["interval"]);});function Da(e,t="auto"){let r=e.toLowerCase(),n=qs[r];if(!n)return null;switch(t){case "translate":{if(!n.sqlite)throw new Error(`No SQLite translation for function "${e}"`);return {sqliteExpr:n.sqlite(),jsFn:null}}case "synthetic":{if(!n.js)throw new Error(`No JS implementation for function "${e}"`);return {sqliteExpr:null,jsFn:n.js}}case "auto":return n.js?{sqliteExpr:null,jsFn:n.js}:n.sqlite?{sqliteExpr:n.sqlite(),jsFn:null}:null}}var zf,qs,ja=g(()=>{zf="lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))",qs={gen_random_uuid:{sqlite:()=>zf,js:()=>crypto.randomUUID()},uuid_generate_v4:{sqlite:()=>zf,js:()=>crypto.randomUUID()},now:{sqlite:()=>"datetime('now')",js:()=>new Date().toISOString()},current_timestamp:{sqlite:()=>"datetime('now')",js:()=>new Date().toISOString()},current_date:{sqlite:()=>"date('now')",js:()=>new Date().toISOString().split("T")[0]},current_time:{sqlite:()=>"time('now')",js:()=>new Date().toISOString().split("T")[1].replace("Z","")},random:{sqlite:()=>"random()",js:()=>Math.random()},length:{sqlite:()=>"length",js:null},lower:{sqlite:()=>"lower",js:null},upper:{sqlite:()=>"upper",js:null},substr:{sqlite:()=>"substr",js:null},substring:{sqlite:()=>"substr",js:null},trim:{sqlite:()=>"trim",js:null},ltrim:{sqlite:()=>"ltrim",js:null},rtrim:{sqlite:()=>"rtrim",js:null},replace:{sqlite:()=>"replace",js:null},coalesce:{sqlite:()=>"coalesce",js:null},nullif:{sqlite:()=>"nullif",js:null},count:{sqlite:()=>"count",js:null},sum:{sqlite:()=>"sum",js:null},avg:{sqlite:()=>"avg",js:null},min:{sqlite:()=>"min",js:null},max:{sqlite:()=>"max",js:null},localtime:{sqlite:()=>"time('now', 'localtime')",js:null},localtimestamp:{sqlite:()=>"datetime('now', 'localtime')",js:null}};});var yn,Vf=g(()=>{yn=class{table;schema;fields;constructor(t,r="public",n=new Map){this.table=t,this.schema=r,this.fields=n;}get(t){return this.fields.get(t)}has(t){return this.fields.has(t)}set(t,r){this.fields.set(t,r);}columns(){return Array.from(this.fields.keys())}all(){return Array.from(this.fields.values())}serializeRow(t){let r={};for(let[n,s]of Object.entries(t)){let i=this.fields.get(n);r[n]=i?i.serialize(s):s;}return r}deserializeRow(t){let r={};for(let[n,s]of Object.entries(t)){let i=this.fields.get(n);r[n]=i?i.deserialize(s):s;}return r}applyDefaults(t){let r={...t};for(let[n,s]of this.fields)!(n in r)&&s.context.defaultFn&&(r[n]=s.context.defaultFn());return r}};});var Kf=g(()=>{st();xa();Ms();_a();Us();qe();$a();va();Ta();Aa();Ca();Ra();ka();Pa();Bs();Oa();Na();Ia();La();ja();Vf();});var Va={};de(Va,{_resetWarnedMissingToClauseForTests:()=>KE,collectComments:()=>za,collectEnums:()=>Ba,collectPolicies:()=>Ha,collectSchema:()=>Wa,collectTableConstraints:()=>Ga,collectVariables:()=>qa});function KE(){Ua.clear();}function Ba(e){let t=new Map;for(let r of e.stmts??[]){if(!r.stmt||!("CreateEnumStmt"in r.stmt))continue;let n=r.stmt.CreateEnumStmt,s=bt(n.typeName??[]).join(".");if(!s||!n.vals)continue;let i=bt(n.vals);t.set(s.toLowerCase(),i);}return t}function qa(e){let t=new Map;for(let r of e.stmts??[]){if(!r.stmt||!("VariableSetStmt"in r.stmt))continue;let n=r.stmt.VariableSetStmt,s=n.name,i=Mf(n.args?.[0]??{});t.set(s,{value:i,local:n.is_local});}return t}function Xf(e){let t=[],r=false;for(let n of e??[])if("RoleSpec"in n){let s=n.RoleSpec;s.roletype==="ROLESPEC_PUBLIC"?s.location===-1&&(r=true):s.roletype==="ROLESPEC_CSTRING"&&s.rolename&&t.push(s.rolename);}return {roles:t,implicitPublic:r}}function Jf(e,t){return e&&e.length>0?e:t}function Fa(e,t,r){return e.findIndex(n=>n.data.name===t.name&&n.data.table===t.table&&Jf(n.data.schema,r)===Jf(t.schema,r))}function Ma(e,t){return new Error(`policy "${e}" for table "${t}" does not exist`)}function Ha(e,t={}){let r=t.defaultSchema||"public",n=t.validateMutations===true,s=new rn,i=new Set,o=[];for(let a of e.stmts??[])if(a.stmt){if("CreatePolicyStmt"in a.stmt){let l=a.stmt.CreatePolicyStmt,c=l.table?.relname??"",p=l.table?.schemaname,u={select:"SELECT",insert:"INSERT",update:"UPDATE",delete:"DELETE"},f=l.cmd_name?u[l.cmd_name]??"ALL":"ALL",h=l.permissive===true,{roles:d,implicitPublic:m}=Xf(l.roles),w=l.qual?s.deparse(l.qual):void 0,y=l.with_check?s.deparse(l.with_check):void 0;if(m){let T=p?`${p}.${c}`:c,v=l.policy_name??"",C=`${T}::${v}`;if(!Ua.has(C)){Ua.add(C);let A=JSON.stringify(w)+JSON.stringify(y);/\{\{auth\.(uid|jwt|role)/i.test(A)||console.warn(`[supalite] policy "${v}" on "${T}" has no TO clause \u2014 applies to all roles (PUBLIC). For clarity, prefer an explicit \`TO <role>\` clause (e.g. \`TO authenticated\`).`);}}let E=new Bt({name:l.policy_name??"",table:c,schema:p,command:f,permissive:h,roles:d,using:w,withCheck:y});o.push(E);}if("DropStmt"in a.stmt&&a.stmt.DropStmt.removeType==="OBJECT_POLICY"){let l=a.stmt.DropStmt,c=l.objects?.[0];if(c&&"List"in c){let p=bt(c.List.items??[]),u=p[p.length-1],f=p[p.length-2],h=p.length>=3?p[p.length-3]:void 0;if(u&&f){let d=Fa(o,{name:u,table:f,schema:h},r);if(d!==-1)o.splice(d,1);else if(n&&!l.missing_ok)throw Ma(u,f)}}}if("AlterPolicyStmt"in a.stmt){let l=a.stmt.AlterPolicyStmt,c=l.policy_name??"",p=l.table?.relname??"",u=l.table?.schemaname,f=Fa(o,{name:c,table:p,schema:u},r);if(f===-1){if(n)throw Ma(c,p);continue}let h=o[f].data,d=l.roles?Xf(l.roles).roles:h.roles,m=l.qual?s.deparse(l.qual):h.using,w=l.with_check?s.deparse(l.with_check):h.withCheck;o[f]=new Bt({...h,roles:d,using:m,withCheck:w});}if("RenameStmt"in a.stmt&&a.stmt.RenameStmt.renameType==="OBJECT_POLICY"){let l=a.stmt.RenameStmt,c=l.subname??"",p=l.relation?.relname??"",u=l.relation?.schemaname,f=Fa(o,{name:c,table:p,schema:u},r);if(f===-1){if(n)throw Ma(c,p);continue}l.newname&&(o[f]=new Bt({...o[f].data,name:l.newname}));}if("AlterTableStmt"in a.stmt){let l=a.stmt.AlterTableStmt;if((l.cmds??[]).some(u=>"AlterTableCmd"in u&&(u.AlterTableCmd.subtype==="AT_EnableRowSecurity"||u.AlterTableCmd.subtype==="AT_ForceRowSecurity"))){let u=l.relation?.relname??"";i.add(u);}}}return {policies:o,tables:i}}function Wa(e,t){let r=new Map;for(let n of e.stmts??[]){if(!n.stmt||!("CreateStmt"in n.stmt))continue;let s=n.stmt.CreateStmt,i=s.relation?.relname??"",o=s.relation?.schemaname??"public";if(!i)continue;let a=new yn(i,o);for(let l of s.tableElts??[]){if(!("ColumnDef"in l))continue;let c=l.ColumnDef,p=c.colname;if(!p)continue;let u=c.typeName?.names?.map(O=>O.String?.sval||O.String?.str).filter(Boolean),f=u&&(u.length===2&&u[0]==="pg_catalog"?u[1]:u[0]);if(!f)continue;let h=!!c.typeName?.arrayBounds?.length,d=Array.isArray(c.typeName?.typmods)?c.typeName.typmods:[],m=O=>d[O]?.A_Const?.ival?.ival??d[O]?.A_Const?.val?.ival?.ival,w={isArray:h};if(Ds(f)&&d.length>0){let O=m(0);typeof O=="number"&&O>0&&(w.lengthConstraint=O);}if(js(f)&&d.length>=2){let O=m(0),F=m(1);typeof O=="number"&&typeof F=="number"&&O>0&&F>=0&&(w.numericPrecision={precision:O,scale:F});}let y=t.get(f.toLowerCase());y&&(w.enumValues=y);let E=Array.isArray(c.constraints)?c.constraints:[],T=E.some(O=>O.Constraint?.contype==="CONSTR_PRIMARY"),v=Ls(f)||E.some(O=>O.Constraint?.contype==="CONSTR_IDENTITY"),C=E.some(O=>O.Constraint?.contype==="CONSTR_NOTNULL"),A=E.find(O=>O.Constraint?.contype==="CONSTR_UNIQUE"),$=E.find(O=>O.Constraint?.contype==="CONSTR_GENERATED"),_=E.find(O=>O.Constraint?.contype==="CONSTR_FOREIGN"),I=E.find(O=>O.Constraint?.contype==="CONSTR_CHECK"),b;if(_){let O=_.Constraint,F=O.pktable?.relname,S=O.pktable?.schemaname,x=O.pk_attrs?.[0]?.String?.sval;F&&x&&(b={refSchema:S,refTable:F,refColumn:x,constraintName:O.conname||void 0});}let D={schema:o,table:i,column:p,pgTypeName:f,nullable:!C&&!T,defaultValue:null,defaultFn:null,isPrimaryKey:T,isUnique:!!A,isSerial:v,isGenerated:!!$,fkRef:b,hasCheck:!!I,checkConstraintName:I?.Constraint?.conname||void 0,uniqueConstraintName:A?.Constraint?.conname||void 0};a.set(p,Wt(D,w));}r.set(`${o}.${i}`,a);}return r}function Ga(e){let t=[];for(let r of e.stmts??[]){if(!r.stmt||!("CreateStmt"in r.stmt))continue;let n=r.stmt.CreateStmt,s=n.relation?.relname??"",i=n.relation?.schemaname??"public";if(s)for(let o of n.tableElts??[]){if("ColumnDef"in o)continue;let a=o;if(!a.Constraint)continue;let l=a.Constraint,c=l.contype;if(c==="CONSTR_UNIQUE"){let p=(l.keys??[]).map(u=>u.String?.sval??u.String?.str).filter(Boolean);if(p.length===0)continue;t.push({schema:i,table:s,kind:"unique",name:l.conname||void 0,columns:p});}else if(c==="CONSTR_CHECK")t.push({schema:i,table:s,kind:"check",name:l.conname||void 0,columns:[]});else if(c==="CONSTR_FOREIGN"){let p=(l.fk_attrs??[]).map(h=>h.String?.sval??h.String?.str).filter(Boolean),u=(l.pk_attrs??[]).map(h=>h.String?.sval??h.String?.str).filter(Boolean),f=l.pktable?.relname;if(!f)continue;t.push({schema:i,table:s,kind:"foreign_key",name:l.conname||void 0,columns:p,refSchema:l.pktable?.schemaname,refTable:f,refColumns:u});}}}return t}function za(e){let t=[];for(let r of e.stmts??[]){if(!r.stmt||!("CommentStmt"in r.stmt))continue;let n=r.stmt.CommentStmt,s=n.comment??"";if(!s)continue;let i=n.objtype,o=(n.object?.List?.items??n.object?.items??[]).map(a=>a.String?.sval??a.String?.str).filter(Boolean);if(o.length!==0){if(i==="OBJECT_TABLE"||i==="OBJECT_VIEW"){let[a,l]=o.length>=2?o:["public",o[0]];t.push({schema:a,table:l,text:s});}else if(i==="OBJECT_COLUMN"){let a="public",l,c;o.length>=3?[a,l,c]=o:[l,c]=o,t.push({schema:a,table:l,column:c,text:s});}}}return t}var Ua,Ka=g(()=>{Sa();Mt();Ea();Kf();fr();Ua=new Set;});async function wn(e,t){let r=await e.connection.introspect(),n=Xa(r);await em(e,{...t,dbHasTables:r.tables.length>0,dbFingerprint:n}),await ZE(e);let s=await e.connection.introspect();nm(s,e);}async function YE(e){return Yr(e.config.db?.seed?.sql_paths??["./seed.sql"],{cwd:Me__default.join(process.cwd(),"supabase"),absolute:true})}async function QE(e){let t=await YE(e);return Promise.all(t.map(async r=>{let n=await pe__default.readFile(r,"utf-8"),s=createHash("sha256").update(n).digest("hex");return {path:Me__default.relative(process.cwd(),r),hash:s,statements:splitSqlStatements(n)}}))}async function bn(e,t){if(e.config.db?.seed?.enabled===false)return 0;let n=(await QE(e)).filter(l=>l.statements.length>0);if(n.length===0)return 0;await Lt(e.connection);let s=Le(e.connection),i=new Map((await Lf(e.connection)).map(l=>[l.path,l.hash])),o=n.filter(l=>i.get(l.path)!==l.hash);if(o.length===0)return 0;console.log(M.default.dim("Seeding database..."));let a=[];for(let l of o){a.push(...l.statements);let c=If(s,{path:l.path,hash:l.hash});c&&a.push(c);}try{await e.connection.transaction(a);}catch(l){let c=t?.recoveryHint??"Fix `supabase/seed.sql`, then re-run `lite dev` to reapply the schema and reseed.";throw new Error(`Seed failed and was rolled back: ${String(l.message??l)}
79
- ${c}`)}return o.reduce((l,c)=>l+c.statements.length,0)}async function ZE(e){await bn(e);}async function ge(e){let t=await Yr(e.config?.db?.migrations?.schema_paths??["./schemas/*.sql"],{cwd:Me__default.join(process.cwd(),"supabase"),absolute:true}),r=await Promise.all(t.map(async n=>await pe__default.readFile(n,"utf-8"))).then(n=>n.map(s=>s.split(`
78
+ )`]}function Lf(e,t){let{schema_migrations:r}=Ns(e),n=t.name===null?"NULL":Zr(t.name),s=e==="pg"?yE(t.statements):Zr(JSON.stringify(t.statements));return `INSERT INTO ${r} (version, statements, name) VALUES (${Zr(t.version)}, ${s}, ${n})`}function bE(e){let{schema_migrations:t}=Ns(e);return `SELECT version FROM ${t} ORDER BY version ASC`}function SE(e){let{seed_files:t}=Ns(e);return t?`SELECT path, hash FROM ${t}`:null}function Df(e,t){let{seed_files:r}=Ns(e);return r?`INSERT INTO ${r} (path, hash) VALUES (${Zr(t.path)}, ${Zr(t.hash)}) ON CONFLICT (path) DO UPDATE SET hash = EXCLUDED.hash`:null}async function EE(e,t){if(e.dialect==="postgres"||e.config.ddlDialect==="sqlite")return t;let n=await e.translateDdl(t);return typeof n=="string"?n:n.ddl??t}function xE(e){return e.split(/;\s*(?:\n|$)/).map(t=>t.trim()).filter(t=>t.length>0)}async function Lt(e){let t=Le(e),n=wE(t).map(i=>i.trim()).join(`;
79
+ `)+";",s=await EE(e,n);for(let i of xE(s))await e.exec(i);}async function en(e){let t=Le(e);return ((await e.exec(bE(t)))?.rows??[]).map(n=>n.version)}async function jf(e){let t=Le(e),r=SE(t);return r?((await e.exec(r))?.rows??[]).map(s=>({path:s.path,hash:s.hash})):[]}var Dt=g(()=>{});function Mf(e){return Le(e.connection)==="sqlite"?"./sqlite-migrations/*.sql":"./migrations/*.sql"}function jt(e){return Me__default.posix.dirname(Mf(e))}async function Ue(e){let t=Me__default.join(process.cwd(),"supabase"),r=await Qr([Mf(e)],{cwd:t,absolute:true}),n=[];for(let s of r){let i=Me__default.basename(s),o=_E.exec(i);if(!o)continue;let a=await pe__default.readFile(s,"utf-8");n.push({version:o[1],name:o[2]??null,filename:i,path:s,sql:a});}return n.sort((s,i)=>s.version.localeCompare(i.version))}async function Is(e){return (await Ue(e)).map(r=>r.sql).join(`
80
+ `)}function Sa(e=new Date){return e.getUTCFullYear().toString().padStart(4,"0")+(e.getUTCMonth()+1).toString().padStart(2,"0")+e.getUTCDate().toString().padStart(2,"0")+e.getUTCHours().toString().padStart(2,"0")+e.getUTCMinutes().toString().padStart(2,"0")+e.getUTCSeconds().toString().padStart(2,"0")}function Ea(e,t=Sa()){let r=e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"");return r.length>0?`${t}_${r}.sql`:`${t}.sql`}async function Uf(e,t,r){let n=Me__default.join(process.cwd(),"supabase",jt(e));ke(n);let s=Ea(t,r?.ts),i=Me__default.join(n,s);return await pe__default.writeFile(i,"",{flag:"wx"}),i}var _E,wt=g(()=>{ba();Dt();Tt();_E=/^(\d{14})(?:_([^.]+))?\.sql$/;});function rn(e){if("String"in e)return e.String.sval}function bt(e){return e.map(rn).filter(t=>t!=null)}function Ft(e){return e==null?[]:e.List!==void 0?e.List.items||[]:Array.isArray(e)?e:[e]}function Ls(e){return QuoteUtils.quoteIdentifier(e)}function pr(e){return Object.keys(e)[0]}function Bf(e){if("A_Const"in e){if(e.A_Const.ival)return e.A_Const.ival.ival;if(e.A_Const.fval)return e.A_Const.fval.fval;if(e.A_Const.sval)return e.A_Const.sval.sval;if(e.A_Const.boolval)return e.A_Const.boolval.boolval;if(e.A_Const.isnull)return null}}var Mt=g(()=>{});function Hf(e){let t=e.toLowerCase().trim();if(t.startsWith("_")||t.endsWith("[]"))return "TEXT";let r=TE[t];if(!r)throw new Ut(`Unsupported PostgreSQL type: "${e}"`);return r}function Ds(e){let t=e.toLowerCase();return ["serial","serial4","bigserial","serial8","smallserial","serial2"].includes(t)}function js(e){let t=e.toLowerCase();return ["varchar","character varying","char","character","bpchar"].includes(t)}function Fs(e){let t=e.toLowerCase();return ["numeric","decimal"].includes(t)}var Ut,B,TE,qf,AE,Ms,fr=g(()=>{Mt();Ut=class extends Error{},B=class extends Ut{constructor(r,n){super(n??`Unsupported node type: ${pr(r)}`);this.node=r;}},TE={int2:"INTEGER",smallint:"INTEGER",int4:"INTEGER",integer:"INTEGER",int:"INTEGER",int8:"INTEGER",bigint:"INTEGER",serial:"INTEGER",serial4:"INTEGER",bigserial:"INTEGER",serial8:"INTEGER",smallserial:"INTEGER",serial2:"INTEGER",float4:"REAL",real:"REAL",float8:"REAL","double precision":"REAL",numeric:"REAL",decimal:"REAL",text:"TEXT",varchar:"TEXT","character varying":"TEXT",char:"TEXT",character:"TEXT",bpchar:"TEXT",name:"TEXT",bytea:"BLOB",bool:"INTEGER",boolean:"INTEGER",date:"TEXT",time:"TEXT","time without time zone":"TEXT",timetz:"TEXT","time with time zone":"TEXT",timestamp:"TEXT","timestamp without time zone":"TEXT",timestamptz:"TEXT","timestamp with time zone":"TEXT",interval:"TEXT",json:"TEXT",jsonb:"TEXT",uuid:"TEXT",inet:"TEXT"},qf=["<",">","<=",">=","=","<>","!=","+","-","*","/","%","&","|","<<",">>","||","BETWEEN","NOT BETWEEN","IN","NOT IN","LIKE","NOT LIKE","IS NULL","IS NOT NULL","IS TRUE","IS NOT TRUE","IS FALSE","IS NOT FALSE","IS UNKNOWN","IS NOT UNKNOWN","AND","OR","NOT","->>"];AE={CreateEnumStmt:{react:"ignore"},CreateDomainStmt:{react:"warn"},CreateSeqStmt:{react:"ignore"},AlterSeqStmt:{react:"ignore"},CreateSchemaStmt:{react:"warn"},CreatePolicyStmt:{react:"ignore"},AlterPolicyStmt:{react:"ignore"},PartitionElem:{react:"error"},PartitionCmd:{react:"error"},VariableSetStmt:{react:"ignore"},CompositeTypeStmt:{react:"error"},AlterEnumStmt:{react:"error"},AlterObjectSchemaStmt:{react:"error"},AlterOwnerStmt:{react:"error"},AlterTypeStmt:{react:"error"},AlterFunctionStmt:{react:"error"},AlterDefaultPrivilegesStmt:{react:"error"},GrantStmt:{react:"error"},GrantRoleStmt:{react:"error"},CopyStmt:{react:"error"},CreateCastStmt:{react:"error"},AlterOpFamilyStmt:{react:"error"},AlterOperatorStmt:{react:"error"},TruncateStmt:{react:"error"},A_Indirection:{react:"error"},XmlExpr:{react:"error"},XmlSerialize:{react:"error"},RangeTableSample:{react:"error"},GroupingSet:{react:"error"}},Ms=new Map(Object.entries(AE));});var Be,nn,xa=g(()=>{Mt();fr();Be=class extends B{constructor(t,r){super(t,`Unsupported expression: ${r}`);}},nn=class{deparse(t){if("A_Const"in t){let s=t.A_Const;if(s.boolval!==void 0)return s.boolval.boolval?{}:{$always:false}}let r=Object.keys(t)[0],n=this[r];if(!n)throw new Be({[r]:t},`Unsupported expression: ${r}`);return n.call(this,t[r])}deparseValue(t){if("A_Const"in t)return this.A_Const(t.A_Const);if("ColumnRef"in t)return this.ColumnRef(t.ColumnRef);if("FuncCall"in t)return this.FuncCall(t.FuncCall);if("SubLink"in t)return this.SubLink(t.SubLink);if("TypeCast"in t)return this.TypeCast(t.TypeCast);if("A_Expr"in t){let n=this.isJwtAccessor(t.A_Expr);return n||this.A_Expr(t.A_Expr)}if("BoolExpr"in t)return this.BoolExpr(t.BoolExpr);let r=Object.keys(t)[0];throw new Be({[r]:t},`deparseValue: ${r}`)}A_Expr(t){if(t.kind==="AEXPR_OP"){let r=t.name?.[0],n=r?rn(r):void 0;if(!n)throw new Be({A_Expr:t},"A_Expr missing operator");let s=this.isJwtAccessor(t);if(s)return {[s]:{}};let i=t.lexpr?this.deparseValue(t.lexpr):void 0,o=t.rexpr?this.deparseValue(t.rexpr):void 0,a=this.mapOperator(n);if(!a)throw new Be({A_Expr:t},`Unsupported operator: ${n}`);let l=t.rexpr!=null&&"ColumnRef"in t.rexpr;if(typeof i=="string"&&i.startsWith("{{")&&l)return {[o]:{[a]:i}};let c=l&&typeof o=="string"?{$ref:o}:o;return {[i]:{[a]:c}}}if(t.kind==="AEXPR_LIKE"||t.kind==="AEXPR_ILIKE"){let r=t.lexpr?this.deparseValue(t.lexpr):void 0,n=t.rexpr?this.deparseValue(t.rexpr):void 0,i=(t.name?.[0]?rn(t.name[0]):"~~")==="!~~"?"$notLike":"$like";return {[r]:{[i]:n}}}if(t.kind==="AEXPR_IN"){let r=t.lexpr?this.deparseValue(t.lexpr):void 0,n=t.rexpr&&"List"in t.rexpr&&t.rexpr.List.items?t.rexpr.List.items.map(s=>this.deparseValue(s)):[];return {[r]:{$in:n}}}throw new Be({A_Expr:t},`A_Expr kind: ${t.kind}`)}BoolExpr(t){let r=t.args??[];switch(t.boolop){case "AND_EXPR":return {$and:r.map(n=>this.deparse(n))};case "OR_EXPR":return {$or:r.map(n=>this.deparse(n))};case "NOT_EXPR":return {$not:this.deparse(r[0])};default:throw new Be({BoolExpr:t},`BoolExpr op: ${t.boolop}`)}}NullTest(t){let r=t.arg?this.deparseValue(t.arg):void 0;return t.nulltesttype==="IS_NULL"?{[r]:{$is:null}}:{[r]:{$isNot:null}}}SubLink(t){if(t.subLinkType==="ANY_SUBLINK"){let r=t.testexpr?this.deparseValue(t.testexpr):void 0,n=t.subselect?this.SelectStmt(t.subselect.SelectStmt):void 0;return {[r]:{$in:n}}}if(t.subLinkType==="EXISTS_SUBLINK")return {$exists:t.subselect?this.SelectStmt(t.subselect.SelectStmt):void 0};if(t.subLinkType==="EXPR_SUBLINK"){let r=t.subselect?t.subselect.SelectStmt:void 0;if(r?.fromClause?.length)return this.SelectStmt(r);if(r?.targetList?.[0]){let n=r.targetList[0],s="ResTarget"in n?n.ResTarget:void 0;if(s?.val){let i=this.deparseValue(s.val);return i}}}throw new Be({SubLink:t},`SubLink type: ${t.subLinkType}`)}SelectStmt(t){let{from:r,schema:n,join:s}=this.deparseFromClause(t.fromClause??[]),i=[];for(let f of t.targetList??[]){let h="ResTarget"in f?f.ResTarget:void 0;if(h?.val){let d=this.deparseValue(h.val);Array.isArray(d)?i.push(...d.map(String)):d!=null&&d!==""&&i.push(String(d));}}let o=t.whereClause?this.deparse(t.whereClause):void 0,a=this.deparseSortClause(t.sortClause),l=this.deparseLimit(t.limitCount),c=this.deparseLimit(t.limitOffset),p=this.deparseGroupClause(t.groupClause),u={type:"query",from:r,select:i};return n&&(u.schema=n),Object.keys(s).length>0&&(u.join=s),o&&(u.where=o),a.length>0&&(u.order=a),l!==void 0&&(u.limit=l),c!==void 0&&(u.offset=c),p.length>0&&(u.group=p),u}FuncCall(t){let r=this.isAuthFunc(t.funcname??[]);if(r)return r;throw new Be({FuncCall:t},`FuncCall: ${bt(t.funcname??[]).join(".")}`)}ColumnRef(t){let r=bt(t.fields??[]);return r.length===1?r[0]:r.join(".")}A_Const(t){if(t.boolval!==void 0)return t.boolval.boolval;if(t.ival!==void 0)return t.ival.ival??0;if(t.fval!==void 0)return parseFloat(t.fval.fval??"0");if(t.sval!==void 0)return t.sval.sval??"";if(t.isnull)return null;throw new Be({A_Const:t},"A_Const: unknown variant")}TypeCast(t){if(!t.arg)throw new Be({TypeCast:t},"TypeCast: missing arg");return this.deparseValue(t.arg)}BooleanTest(t){let r=t.arg?this.deparseValue(t.arg):void 0;return t.booltesttype==="IS_TRUE"?{[r]:{$eq:true}}:{[r]:{$eq:false}}}deparseFromClause(t){let r={};if(t.length===0)return {from:"",join:r};let n=t[0];if("RangeVar"in n){let s=n.RangeVar;return {from:s.relname??"",schema:s.schemaname,join:r}}if("JoinExpr"in n){let{from:s,schema:i}=this.walkJoinExpr(n.JoinExpr,r);return {from:s,schema:i,join:r}}return {from:"",join:r}}walkJoinExpr(t,r){let n={from:""};if(t.larg)if("RangeVar"in t.larg){let s=t.larg.RangeVar;n={from:s.relname??"",schema:s.schemaname};}else "JoinExpr"in t.larg&&(n=this.walkJoinExpr(t.larg.JoinExpr,r));if(t.rarg&&"RangeVar"in t.rarg){let s=t.rarg.RangeVar,i=s.relname??"",o=s.alias?.aliasname??i,a=t.jointype==="JOIN_LEFT"?"left":"inner",l={from:i,type:a};t.quals&&(l.on=this.deparse(t.quals));let c=o;if(c in r){let p=2;for(;`${c}_${p}`in r;)p++;c=`${c}_${p}`;}r[c]=l;}return n}deparseSortClause(t){if(!t)return [];let r=[];for(let n of t){if(!("SortBy"in n))continue;let s=n.SortBy;if(!s.node)continue;let i=String(this.deparseValue(s.node)),o=s.sortby_dir==="SORTBY_DESC"?"desc":"asc",a={column:i,direction:o};s.sortby_nulls==="SORTBY_NULLS_FIRST"?a.nullsFirst=true:s.sortby_nulls==="SORTBY_NULLS_LAST"&&(a.nullsFirst=false),r.push(a);}return r}deparseLimit(t){if(!t)return;let r=this.deparseValue(t);return typeof r=="number"?r:Number(r)}deparseGroupClause(t){return t?t.map(r=>String(this.deparseValue(r))):[]}isAuthFunc(t){let r=bt(t);if(r.length===2&&r[0]==="auth"){if(r[1]==="uid")return "{{auth.uid}}";if(r[1]==="jwt")return "{{auth.jwt}}";if(r[1]==="role")return "{{auth.role}}";throw new Error(`Unsupported auth function: "${r.slice(1).join(".")}"`)}return null}isJwtAccessor(t){if(t.kind!=="AEXPR_OP")return null;let r=t.name?.[0]?rn(t.name[0]):void 0;if(r!=="->"&&r!=="->>")return null;let n=t.rexpr&&"A_Const"in t.rexpr?t.rexpr.A_Const.sval?.sval:void 0;if(n===void 0)return null;if(t.lexpr&&"FuncCall"in t.lexpr)return this.isAuthFunc(t.lexpr.FuncCall.funcname??[])==="{{auth.jwt}}"?`{{auth.jwt.${n}}}`:null;if(t.lexpr&&"A_Expr"in t.lexpr){let s=this.isJwtAccessor(t.lexpr.A_Expr);if(s)return `${s.slice(0,-2)}.${n}}}`}return null}mapOperator(t){switch(t){case "=":return "$eq";case "<>":case "!=":return "$neq";case ">":return "$gt";case ">=":return "$gte";case "<":return "$lt";case "<=":return "$lte";case "~~":return "$like";case "!~~":return "$notLike";default:return}}};});var Bt,_a=g(()=>{Bt=class e{constructor(t){this.data=t;}appliesTo(t){return this.data.command==="ALL"||this.data.command===t}appliesToRole(t){return this.data.roles.length===0||this.data.roles.includes(t)}toJSON(){return this.data}static fromJSON(t){return new e(t)}};});var sn,$a=g(()=>{sn=class extends Error{constructor(r,n,s,i){super(`check constraint "${s}" violated for ${r}.${n}`);this.table=r;this.column=n;this.constraint=s;this.value=i;this.name="CheckConstraintError";}};});var we,st=g(()=>{$a();we=class{context;constructor(t){this.context=t;}get isShimBacked(){return false}checkConstraint(){return null}serialize(t){return t}deserialize(t){return t}validateStorage(t){return {status:"pass",message:null}}validationFail(t,r){return {status:"fail",message:t,action:r}}validationPass(){return {status:"pass",message:null}}isNullish(t){return t==null}toColumnDDL(t){let{includeNullable:r=true}=t??{},n=[],s=this.context.column;n.push(this.quoteIfNeeded(s)),n.push(this.sqliteType),this.context.isPrimaryKey&&n.push("PRIMARY KEY"),this.context.isSerial&&this.context.isPrimaryKey&&n.push("AUTOINCREMENT"),r&&!this.context.nullable&&!this.context.isPrimaryKey&&n.push("NOT NULL"),this.context.isUnique&&!this.context.isPrimaryKey&&n.push("UNIQUE"),this.context.defaultValue!==null&&n.push(`DEFAULT ${this.context.defaultValue}`);let i=this.checkConstraint();return i&&n.push(`CHECK (${i})`),n.join(" ")}checkError(t,r){return new sn(this.context.table,this.context.column,t,r)}quoteIfNeeded(t){return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)?t:`"${t}"`}};});var qt,Us=g(()=>{st();qt=class extends we{get sqliteType(){return "INTEGER"}};});var on,va=g(()=>{Us();on=class extends qt{constructor(t){super({...t,isSerial:true});}};});function CE(e,t){let{precision:r,scale:n}=t,s=10**n,i=10**(r-n);return Math.abs(Math.round(e*s)-e*s)<1e-4&&Math.abs(e)<i}var Ht,Bs=g(()=>{st();Ht=class extends we{numericPrecision;constructor(t,r){super(t),this.numericPrecision=r;}get isShimBacked(){return this.numericPrecision!==void 0}get sqliteType(){return "REAL"}checkConstraint(){if(this.numericPrecision){let{precision:t,scale:r}=this.numericPrecision,n=this.context.column,s=10**r,i=10**(t-r);return `ABS(ROUND(${n} * ${s}) - ${n} * ${s}) < 0.0001 AND ABS(${n}) < ${i}`}return null}validateStorage(t){if(this.isNullish(t))return this.validationPass();if(typeof t!="number"||!Number.isFinite(t))return this.validationFail("Expected finite number.","Patch rows with finite numbers.");if(this.numericPrecision){let{precision:r,scale:n}=this.numericPrecision;if(!CE(t,this.numericPrecision))return this.validationFail(`Does not fit numeric(${r}, ${n}).`,"Patch rows within numeric precision.")}return this.validationPass()}};});var le,qe=g(()=>{st();le=class extends we{lengthConstraint;constructor(t,r){super(t),this.lengthConstraint=r;}get isShimBacked(){return this.lengthConstraint!==void 0}get sqliteType(){return "TEXT"}checkConstraint(){return this.lengthConstraint!==void 0?`length(${this.context.column}) <= ${this.lengthConstraint}`:null}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"?this.validationFail("Expected text.","Patch rows with text values."):this.lengthConstraint!==void 0&&Array.from(t).length>this.lengthConstraint?this.validationFail(`Exceeds length ${this.lengthConstraint}.`,"Patch rows with shorter text."):this.validationPass()}};});var an,Ta=g(()=>{st();an=class extends we{get sqliteType(){return "BLOB"}};});var ln,Aa=g(()=>{st();ln=class extends we{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}checkConstraint(){return `${this.context.column} IN (0, 1)`}serialize(t){if(this.isNullish(t))return t;if(t===true||t===1)return 1;if(t===false||t===0)return 0;throw this.checkError("boolean_range",t)}deserialize(t){if(this.isNullish(t)||t===true||t===false)return t;if(typeof t=="number"&&Number.isFinite(t)){if(t===1)return true;if(t===0)return false}return t===1n?true:t===0n?false:t==="1"||t==="true"?true:t==="0"||t==="false"?false:t}validateStorage(t){return this.isNullish(t)?this.validationPass():t===1||t===0?this.validationPass():this.validationFail("Expected 0 or 1.","Patch rows with boolean values.")}};});function Wf(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var cn,Ca=g(()=>{st();cn=class extends we{get isShimBacked(){return true}get sqliteType(){return "TEXT"}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR json_valid(${t})`}serialize(t){if(this.isNullish(t))return t;try{return JSON.stringify(t)}catch{throw this.checkError("json_valid",t)}}deserialize(t){if(this.isNullish(t))return t;if(typeof t=="string"){let r=Wf(t);return r.ok?r.value:t}return t}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"?this.validationFail("Expected JSON text.","Patch rows with JSON values."):Wf(t).ok?this.validationPass():this.validationFail("Invalid JSON text.","Patch rows with valid JSON.")}};});function RE(e){if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return false;let t=new Date(`${e}T00:00:00.000Z`);return !Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e}var un,Ra=g(()=>{qe();un=class extends le{get isShimBacked(){return true}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR date(${t}) IS NOT NULL`}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!RE(t)?this.validationFail("Invalid date.","Patch rows with YYYY-MM-DD dates."):this.validationPass()}};});function kE(e){let t=e.match(/^(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?([+-](\d{2}):?(\d{2}))?$/);if(!t)return false;let r=Number(t[1]),n=Number(t[2]),s=t[3]===void 0?0:Number(t[3]),i=t[5]===void 0?null:Number(t[5]),o=t[6]===void 0?null:Number(t[6]),a=i===null||o!==null&&i<=15&&o<=59;return r<=24&&n<=59&&s<=59&&(r!==24||n===0&&s===0)&&a}var pn,ka=g(()=>{qe();pn=class extends le{get isShimBacked(){return true}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR time(${t}) IS NOT NULL`}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!kE(t)?this.validationFail("Invalid time.","Patch rows with HH:MM[:SS] times."):this.validationPass()}};});function PE(e){let t=e.match(/^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?(?:Z|([+-](\d{2}):?(\d{2})))?$/);if(!t)return false;let r=Number(t[1]),n=Number(t[2]),s=Number(t[3]),i=Number(t[4]),o=Number(t[5]),a=t[6]===void 0?0:Number(t[6]),l=t[8]===void 0?null:Number(t[8]),c=t[9]===void 0?null:Number(t[9]),p=new Date(Date.UTC(r,n-1,s)),u=p.getUTCFullYear()===r&&p.getUTCMonth()===n-1&&p.getUTCDate()===s,f=i<=24&&o<=59&&a<=59&&(i!==24||o===0&&a===0),h=l===null||c!==null&&l<=15&&c<=59;return u&&f&&h}var fn,Pa=g(()=>{qe();fn=class extends le{get isShimBacked(){return true}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR datetime(${t}) IS NOT NULL`}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!PE(t)?this.validationFail("Invalid timestamp.","Patch rows with ISO timestamps."):this.validationPass()}};});var mn,Oa=g(()=>{qe();mn=class extends le{get isShimBacked(){return true}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||t.trim().length===0?this.validationFail("Expected interval text.","Patch rows with interval strings."):/^-?\d+(?:\.\d+)?$/.test(t.trim())?this.validationFail("Ambiguous numeric interval.","Patch rows with explicit interval strings."):this.validationPass()}};});var dn,Na=g(()=>{qe();dn=class extends le{enumValues;constructor(t,r){super(t),this.enumValues=r;}get isShimBacked(){return true}checkConstraint(){let t=this.context.column,r=this.enumValues.map(n=>`'${n.replace(/'/g,"''")}'`).join(", ");return `${t} IN (${r})`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string"||!this.enumValues.includes(t))throw this.checkError("enum_membership",t);return t}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!this.enumValues.includes(t)?this.validationFail("Invalid enum value.","Patch rows with declared enum values."):this.validationPass()}};});function Gf(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var St,qs=g(()=>{st();St=class extends we{elementField;constructor(t,r){super(t),this.elementField=r;}get sqliteType(){return "TEXT"}get isShimBacked(){return true}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR (json_valid(${t}) AND json_type(${t}) = 'array')`}serialize(t){if(this.isNullish(t))return t;if(!Array.isArray(t))throw this.checkError("array_type",t);return this.elementField?JSON.stringify(t.map(r=>this.elementField.serialize(r))):JSON.stringify(t)}deserialize(t){if(this.isNullish(t))return t;if(typeof t=="string"){let r=Gf(t);if(r.ok&&Array.isArray(r.value))return this.elementField?r.value.map(n=>this.elementField.deserialize(n)):r.value}return t}validateStorage(t){if(this.isNullish(t))return this.validationPass();if(typeof t!="string")return this.validationFail("Expected JSON array text.","Patch rows with array values.");let r=Gf(t);if(!r.ok)return this.validationFail("Invalid JSON array text.","Patch rows with array values.");if(!Array.isArray(r.value))return this.validationFail("Expected JSON array.","Patch rows with array values.");if(this.elementField)for(let n of r.value){let s=this.elementField.validateStorage(n);if(s.status==="fail")return this.validationFail(`Invalid ${this.elementField.context.pgTypeName} array element.`,s.action??"Patch rows with valid array elements.")}return this.validationPass()}};});function zf(e){return NE.test(e.toLowerCase())}var OE,NE,hn,Ia=g(()=>{qe();OE="????????-????-????-????-????????????",NE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;hn=class extends le{get isShimBacked(){return true}checkConstraint(){let t=this.quoteIfNeeded(this.context.column);return `${t} IS NULL OR ${t} GLOB '${OE}'`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string")throw this.checkError("uuid_format",t);let r=t.toLowerCase();if(!zf(r))throw this.checkError("uuid_format",t);return r}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!zf(t)?this.validationFail("Invalid UUID.","Patch rows with valid UUIDs."):this.validationPass()}};});function IE(e){let t=e.split("/");if(t.length>2)return null;let r=t[0];if(!r)return null;if(t.length===1)return {address:r,prefix:null};let n=t[1];return !n||!/^\d+$/.test(n)?null:{address:r,prefix:Number(n)}}function LE(e){let t=e.split(".");return t.length!==4?false:t.every(r=>{if(!/^\d+$/.test(r))return false;let n=Number(r);return n>=0&&n<=255})}function DE(e){if(!e.includes(":"))return false;try{return new URL(`http://[${e}]/`),!0}catch{return false}}function Vf(e){let t=IE(e);return t?LE(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=32:DE(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=128:false:false}var gn,La=g(()=>{qe();gn=class extends le{get isShimBacked(){return true}checkConstraint(){let t=this.quoteIfNeeded(this.context.column);return `${t} IS NULL OR (length(${t}) BETWEEN 3 AND 49 AND (instr(${t}, '.') > 0 OR instr(${t}, ':') > 0))`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string")throw this.checkError("inet_format",t);let r=t.trim();if(!Vf(r))throw this.checkError("inet_format",t);return r}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!Vf(t.trim())?this.validationFail("Invalid inet address.","Patch rows with valid inet strings."):this.validationPass()}};});var yn,Da=g(()=>{qe();yn=class extends le{serialize(t){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}deserialize(t){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}toColumnDDL(){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}};});function Wt(e,t){if(t?.isArray){let n=Wt(e,{...t,isArray:false});return new St(e,n)}if(t?.enumValues)return new dn(e,t.enumValues);let r=e.pgTypeName.toLowerCase().trim();if(r.startsWith("_")||r.endsWith("[]")){let n=r.startsWith("_")?r.slice(1):r.slice(0,-2),s={...e,pgTypeName:n},i=Wt(s);return new St(e,i)}return FE.has(r)?new on(e):jE.has(r)?new qt(e):qE.has(r)?new ln(e):HE.has(r)?new cn(e):VE.has(r)?new un(e):KE.has(r)?new pn(e):XE.has(r)?new fn(e):JE.has(r)?new mn(e):BE.has(r)?new an(e):ME.has(r)?new Ht(e,t?.numericPrecision):WE.has(r)?new hn(e):GE.has(r)?new le(e,63):zE.has(r)?new gn(e):UE.has(r)?new le(e,t?.lengthConstraint):new yn(e)}var jE,FE,ME,UE,BE,qE,HE,WE,GE,zE,VE,KE,XE,JE,ja=g(()=>{Us();va();Bs();qe();Ta();Aa();Ca();Ra();ka();Pa();Oa();Na();qs();Ia();La();Da();jE=new Set(["int2","smallint","int4","integer","int","int8","bigint"]),FE=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]),ME=new Set(["float4","real","float8","double precision","numeric","decimal"]),UE=new Set(["text","varchar","character varying","char","character","bpchar"]),BE=new Set(["bytea"]),qE=new Set(["bool","boolean"]),HE=new Set(["json","jsonb"]),WE=new Set(["uuid"]),GE=new Set(["name"]),zE=new Set(["inet"]),VE=new Set(["date"]),KE=new Set(["time","timetz","time without time zone","time with time zone"]),XE=new Set(["timestamp","timestamptz","timestamp without time zone","timestamp with time zone"]),JE=new Set(["interval"]);});function Fa(e,t="auto"){let r=e.toLowerCase(),n=Hs[r];if(!n)return null;switch(t){case "translate":{if(!n.sqlite)throw new Error(`No SQLite translation for function "${e}"`);return {sqliteExpr:n.sqlite(),jsFn:null}}case "synthetic":{if(!n.js)throw new Error(`No JS implementation for function "${e}"`);return {sqliteExpr:null,jsFn:n.js}}case "auto":return n.js?{sqliteExpr:null,jsFn:n.js}:n.sqlite?{sqliteExpr:n.sqlite(),jsFn:null}:null}}var Kf,Hs,Ma=g(()=>{Kf="lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))",Hs={gen_random_uuid:{sqlite:()=>Kf,js:()=>crypto.randomUUID()},uuid_generate_v4:{sqlite:()=>Kf,js:()=>crypto.randomUUID()},now:{sqlite:()=>"datetime('now')",js:()=>new Date().toISOString()},current_timestamp:{sqlite:()=>"datetime('now')",js:()=>new Date().toISOString()},current_date:{sqlite:()=>"date('now')",js:()=>new Date().toISOString().split("T")[0]},current_time:{sqlite:()=>"time('now')",js:()=>new Date().toISOString().split("T")[1].replace("Z","")},random:{sqlite:()=>"random()",js:()=>Math.random()},length:{sqlite:()=>"length",js:null},lower:{sqlite:()=>"lower",js:null},upper:{sqlite:()=>"upper",js:null},substr:{sqlite:()=>"substr",js:null},substring:{sqlite:()=>"substr",js:null},trim:{sqlite:()=>"trim",js:null},ltrim:{sqlite:()=>"ltrim",js:null},rtrim:{sqlite:()=>"rtrim",js:null},replace:{sqlite:()=>"replace",js:null},coalesce:{sqlite:()=>"coalesce",js:null},nullif:{sqlite:()=>"nullif",js:null},count:{sqlite:()=>"count",js:null},sum:{sqlite:()=>"sum",js:null},avg:{sqlite:()=>"avg",js:null},min:{sqlite:()=>"min",js:null},max:{sqlite:()=>"max",js:null},localtime:{sqlite:()=>"time('now', 'localtime')",js:null},localtimestamp:{sqlite:()=>"datetime('now', 'localtime')",js:null}};});var wn,Xf=g(()=>{wn=class{table;schema;fields;constructor(t,r="public",n=new Map){this.table=t,this.schema=r,this.fields=n;}get(t){return this.fields.get(t)}has(t){return this.fields.has(t)}set(t,r){this.fields.set(t,r);}columns(){return Array.from(this.fields.keys())}all(){return Array.from(this.fields.values())}serializeRow(t){let r={};for(let[n,s]of Object.entries(t)){let i=this.fields.get(n);r[n]=i?i.serialize(s):s;}return r}deserializeRow(t){let r={};for(let[n,s]of Object.entries(t)){let i=this.fields.get(n);r[n]=i?i.deserialize(s):s;}return r}applyDefaults(t){let r={...t};for(let[n,s]of this.fields)!(n in r)&&s.context.defaultFn&&(r[n]=s.context.defaultFn());return r}};});var Jf=g(()=>{st();$a();Us();va();Bs();qe();Ta();Aa();Ca();Ra();ka();Pa();Oa();Na();qs();Ia();La();Da();ja();Ma();Xf();});var Xa={};de(Xa,{_resetWarnedMissingToClauseForTests:()=>YE,collectComments:()=>Ka,collectEnums:()=>Ha,collectPolicies:()=>Ga,collectSchema:()=>za,collectTableConstraints:()=>Va,collectVariables:()=>Wa});function YE(){qa.clear();}function Ha(e){let t=new Map;for(let r of e.stmts??[]){if(!r.stmt||!("CreateEnumStmt"in r.stmt))continue;let n=r.stmt.CreateEnumStmt,s=bt(n.typeName??[]).join(".");if(!s||!n.vals)continue;let i=bt(n.vals);t.set(s.toLowerCase(),i);}return t}function Wa(e){let t=new Map;for(let r of e.stmts??[]){if(!r.stmt||!("VariableSetStmt"in r.stmt))continue;let n=r.stmt.VariableSetStmt,s=n.name,i=Bf(n.args?.[0]??{});t.set(s,{value:i,local:n.is_local});}return t}function Yf(e){let t=[],r=false;for(let n of e??[])if("RoleSpec"in n){let s=n.RoleSpec;s.roletype==="ROLESPEC_PUBLIC"?s.location===-1&&(r=true):s.roletype==="ROLESPEC_CSTRING"&&s.rolename&&t.push(s.rolename);}return {roles:t,implicitPublic:r}}function Qf(e,t){return e&&e.length>0?e:t}function Ua(e,t,r){return e.findIndex(n=>n.data.name===t.name&&n.data.table===t.table&&Qf(n.data.schema,r)===Qf(t.schema,r))}function Ba(e,t){return new Error(`policy "${e}" for table "${t}" does not exist`)}function Ga(e,t={}){let r=t.defaultSchema||"public",n=t.validateMutations===true,s=new nn,i=new Set,o=[];for(let a of e.stmts??[])if(a.stmt){if("CreatePolicyStmt"in a.stmt){let l=a.stmt.CreatePolicyStmt,c=l.table?.relname??"",p=l.table?.schemaname,u={select:"SELECT",insert:"INSERT",update:"UPDATE",delete:"DELETE"},f=l.cmd_name?u[l.cmd_name]??"ALL":"ALL",h=l.permissive===true,{roles:d,implicitPublic:m}=Yf(l.roles),w=l.qual?s.deparse(l.qual):void 0,y=l.with_check?s.deparse(l.with_check):void 0;if(m){let T=p?`${p}.${c}`:c,v=l.policy_name??"",C=`${T}::${v}`;if(!qa.has(C)){qa.add(C);let A=JSON.stringify(w)+JSON.stringify(y);/\{\{auth\.(uid|jwt|role)/i.test(A)||console.warn(`[supalite] policy "${v}" on "${T}" has no TO clause \u2014 applies to all roles (PUBLIC). For clarity, prefer an explicit \`TO <role>\` clause (e.g. \`TO authenticated\`).`);}}let E=new Bt({name:l.policy_name??"",table:c,schema:p,command:f,permissive:h,roles:d,using:w,withCheck:y});o.push(E);}if("DropStmt"in a.stmt&&a.stmt.DropStmt.removeType==="OBJECT_POLICY"){let l=a.stmt.DropStmt,c=l.objects?.[0];if(c&&"List"in c){let p=bt(c.List.items??[]),u=p[p.length-1],f=p[p.length-2],h=p.length>=3?p[p.length-3]:void 0;if(u&&f){let d=Ua(o,{name:u,table:f,schema:h},r);if(d!==-1)o.splice(d,1);else if(n&&!l.missing_ok)throw Ba(u,f)}}}if("AlterPolicyStmt"in a.stmt){let l=a.stmt.AlterPolicyStmt,c=l.policy_name??"",p=l.table?.relname??"",u=l.table?.schemaname,f=Ua(o,{name:c,table:p,schema:u},r);if(f===-1){if(n)throw Ba(c,p);continue}let h=o[f].data,d=l.roles?Yf(l.roles).roles:h.roles,m=l.qual?s.deparse(l.qual):h.using,w=l.with_check?s.deparse(l.with_check):h.withCheck;o[f]=new Bt({...h,roles:d,using:m,withCheck:w});}if("RenameStmt"in a.stmt&&a.stmt.RenameStmt.renameType==="OBJECT_POLICY"){let l=a.stmt.RenameStmt,c=l.subname??"",p=l.relation?.relname??"",u=l.relation?.schemaname,f=Ua(o,{name:c,table:p,schema:u},r);if(f===-1){if(n)throw Ba(c,p);continue}l.newname&&(o[f]=new Bt({...o[f].data,name:l.newname}));}if("AlterTableStmt"in a.stmt){let l=a.stmt.AlterTableStmt;if((l.cmds??[]).some(u=>"AlterTableCmd"in u&&(u.AlterTableCmd.subtype==="AT_EnableRowSecurity"||u.AlterTableCmd.subtype==="AT_ForceRowSecurity"))){let u=l.relation?.relname??"";i.add(u);}}}return {policies:o,tables:i}}function za(e,t){let r=new Map;for(let n of e.stmts??[]){if(!n.stmt||!("CreateStmt"in n.stmt))continue;let s=n.stmt.CreateStmt,i=s.relation?.relname??"",o=s.relation?.schemaname??"public";if(!i)continue;let a=new wn(i,o);for(let l of s.tableElts??[]){if(!("ColumnDef"in l))continue;let c=l.ColumnDef,p=c.colname;if(!p)continue;let u=c.typeName?.names?.map(O=>O.String?.sval||O.String?.str).filter(Boolean),f=u&&(u.length===2&&u[0]==="pg_catalog"?u[1]:u[0]);if(!f)continue;let h=!!c.typeName?.arrayBounds?.length,d=Array.isArray(c.typeName?.typmods)?c.typeName.typmods:[],m=O=>d[O]?.A_Const?.ival?.ival??d[O]?.A_Const?.val?.ival?.ival,w={isArray:h};if(js(f)&&d.length>0){let O=m(0);typeof O=="number"&&O>0&&(w.lengthConstraint=O);}if(Fs(f)&&d.length>=2){let O=m(0),F=m(1);typeof O=="number"&&typeof F=="number"&&O>0&&F>=0&&(w.numericPrecision={precision:O,scale:F});}let y=t.get(f.toLowerCase());y&&(w.enumValues=y);let E=Array.isArray(c.constraints)?c.constraints:[],T=E.some(O=>O.Constraint?.contype==="CONSTR_PRIMARY"),v=Ds(f)||E.some(O=>O.Constraint?.contype==="CONSTR_IDENTITY"),C=E.some(O=>O.Constraint?.contype==="CONSTR_NOTNULL"),A=E.find(O=>O.Constraint?.contype==="CONSTR_UNIQUE"),$=E.find(O=>O.Constraint?.contype==="CONSTR_GENERATED"),_=E.find(O=>O.Constraint?.contype==="CONSTR_FOREIGN"),I=E.find(O=>O.Constraint?.contype==="CONSTR_CHECK"),b;if(_){let O=_.Constraint,F=O.pktable?.relname,S=O.pktable?.schemaname,x=O.pk_attrs?.[0]?.String?.sval;F&&x&&(b={refSchema:S,refTable:F,refColumn:x,constraintName:O.conname||void 0});}let D={schema:o,table:i,column:p,pgTypeName:f,nullable:!C&&!T,defaultValue:null,defaultFn:null,isPrimaryKey:T,isUnique:!!A,isSerial:v,isGenerated:!!$,fkRef:b,hasCheck:!!I,checkConstraintName:I?.Constraint?.conname||void 0,uniqueConstraintName:A?.Constraint?.conname||void 0};a.set(p,Wt(D,w));}r.set(`${o}.${i}`,a);}return r}function Va(e){let t=[];for(let r of e.stmts??[]){if(!r.stmt||!("CreateStmt"in r.stmt))continue;let n=r.stmt.CreateStmt,s=n.relation?.relname??"",i=n.relation?.schemaname??"public";if(s)for(let o of n.tableElts??[]){if("ColumnDef"in o)continue;let a=o;if(!a.Constraint)continue;let l=a.Constraint,c=l.contype;if(c==="CONSTR_UNIQUE"){let p=(l.keys??[]).map(u=>u.String?.sval??u.String?.str).filter(Boolean);if(p.length===0)continue;t.push({schema:i,table:s,kind:"unique",name:l.conname||void 0,columns:p});}else if(c==="CONSTR_CHECK")t.push({schema:i,table:s,kind:"check",name:l.conname||void 0,columns:[]});else if(c==="CONSTR_FOREIGN"){let p=(l.fk_attrs??[]).map(h=>h.String?.sval??h.String?.str).filter(Boolean),u=(l.pk_attrs??[]).map(h=>h.String?.sval??h.String?.str).filter(Boolean),f=l.pktable?.relname;if(!f)continue;t.push({schema:i,table:s,kind:"foreign_key",name:l.conname||void 0,columns:p,refSchema:l.pktable?.schemaname,refTable:f,refColumns:u});}}}return t}function Ka(e){let t=[];for(let r of e.stmts??[]){if(!r.stmt||!("CommentStmt"in r.stmt))continue;let n=r.stmt.CommentStmt,s=n.comment??"";if(!s)continue;let i=n.objtype,o=(n.object?.List?.items??n.object?.items??[]).map(a=>a.String?.sval??a.String?.str).filter(Boolean);if(o.length!==0){if(i==="OBJECT_TABLE"||i==="OBJECT_VIEW"){let[a,l]=o.length>=2?o:["public",o[0]];t.push({schema:a,table:l,text:s});}else if(i==="OBJECT_COLUMN"){let a="public",l,c;o.length>=3?[a,l,c]=o:[l,c]=o,t.push({schema:a,table:l,column:c,text:s});}}}return t}var qa,Ja=g(()=>{xa();Mt();_a();Jf();fr();qa=new Set;});async function bn(e,t){let r=await e.connection.introspect(),n=Ya(r);await rm(e,{...t,dbHasTables:r.tables.length>0,dbFingerprint:n}),await rx(e);let s=await e.connection.introspect();im(s,e);}async function ex(e){return Qr(e.config.db?.seed?.sql_paths??["./seed.sql"],{cwd:Me__default.join(process.cwd(),"supabase"),absolute:true})}async function tx(e){let t=await ex(e);return Promise.all(t.map(async r=>{let n=await pe__default.readFile(r,"utf-8"),s=createHash("sha256").update(n).digest("hex");return {path:Me__default.relative(process.cwd(),r),hash:s,statements:splitSqlStatements(n)}}))}async function Sn(e,t){if(e.config.db?.seed?.enabled===false)return 0;let n=(await tx(e)).filter(l=>l.statements.length>0);if(n.length===0)return 0;await Lt(e.connection);let s=Le(e.connection),i=new Map((await jf(e.connection)).map(l=>[l.path,l.hash])),o=n.filter(l=>i.get(l.path)!==l.hash);if(o.length===0)return 0;console.log(M.default.dim("Seeding database..."));let a=[];for(let l of o){a.push(...l.statements);let c=Df(s,{path:l.path,hash:l.hash});c&&a.push(c);}try{await e.connection.transaction(a);}catch(l){let c=t?.recoveryHint??"Fix `supabase/seed.sql`, then re-run `lite dev` to reapply the schema and reseed.";throw new Error(`Seed failed and was rolled back: ${String(l.message??l)}
81
+ ${c}`)}return o.reduce((l,c)=>l+c.statements.length,0)}async function rx(e){await Sn(e);}async function ge(e){let t=await Qr(e.config?.db?.migrations?.schema_paths??["./schemas/*.sql"],{cwd:Me__default.join(process.cwd(),"supabase"),absolute:true}),r=await Promise.all(t.map(async n=>await pe__default.readFile(n,"utf-8"))).then(n=>n.map(s=>s.split(`
80
82
  `).filter(i=>i.trim().length>0&&!i.trim().startsWith("--")).join(`
81
83
  `)).join(`
82
- `));return r||""}async function em(e,t){let r=await ge(e);if(!(!r&&(await Ue(e)).length>0)&&!(!r&&!e.connection.config.baseSchema)){if(t?.dbHasTables&&await tx(e,r,t.dbFingerprint)){console.log(M.default.dim("Schema unchanged \u2014 skipping translation."));return}try{let n=e.connection.createMigrator(r),s=await n.diff(),i=n.translationResult?.ast,o=await e.connection.introspect(),a=Xa(o);if(s.plan.steps.length===0){await Qf(e,r,i,a);return}await n.migratePlan(s.plan,{force:t?.force??!1}),nx(s);let l=await e.connection.introspect();return await Qf(e,r,i,Xa(l)),console.log(""),dr(s),s}catch(n){if(String(n).includes("likely empty"))console.log(M.default.dim("Nothing to migrate."));else {console.error("Migration error: "+String(n));try{await e.connection.exec("rollback");}catch{}}}}}function ex(e){return e.connection.config?.baseSchema??""}function tm(e,t){let r=createHash("sha256");return r.update(JSON.stringify([ex(e),t??""])),r.digest("hex")}function Xa(e){let t=(n,s)=>[...n].sort((i,o)=>s(i).localeCompare(s(o))),r={tables:t(e.tables??[],n=>`${n.schema??""}.${n.name}`).map(n=>({schema:n.schema,name:n.name,type:n.type,sql:n.sql})),columns:t(e.columns??[],n=>`${n.schema??""}.${n.table}.${n.name}`).map(n=>({schema:n.schema,table:n.table,name:n.name,type:n.type,nullable:n.nullable,default_value:n.default_value,is_primary_key:n.is_primary_key})),indexes:t(e.indexes??[],n=>`${n.schema??""}.${n.table}.${n.name}`).map(n=>({schema:n.schema,table:n.table,name:n.name,unique:n.unique,columns:n.columns})),foreign_keys:t(e.foreign_keys??[],n=>`${n.schema??""}.${n.table}.${n.column}->${n.ref_table}.${n.ref_column}`).map(n=>({schema:n.schema,table:n.table,column:n.column,ref_schema:n.ref_schema,ref_table:n.ref_table,ref_column:n.ref_column})),primary_keys:t(e.primary_keys??[],n=>`${n.schema??""}.${n.table}`).map(n=>({schema:n.schema,table:n.table,columns:n.columns})),check_constraints:t(e.check_constraints??[],n=>`${n.schema??""}.${n.table}.${n.name??""}.${n.column??""}`).map(n=>({schema:n.schema,table:n.table,name:n.name,column:n.column,expression:n.expression})),unique_constraints:t(e.unique_constraints??[],n=>`${n.schema??""}.${n.table}.${n.name}`).map(n=>({schema:n.schema,table:n.table,name:n.name,columns:n.columns})),views:t(e.views??[],n=>`${n.schema??""}.${n.name}`).map(n=>({schema:n.schema,name:n.name,sql:n.sql})),triggers:t(e.triggers??[],n=>`${n.schema??""}.${n.table}.${n.name}`).map(n=>({schema:n.schema,table:n.table,name:n.name,sql:n.sql})),custom_types:t(e.custom_types??[],n=>`${n.schema??""}.${n.type}`).map(n=>({schema:n.schema,type:n.type,kind:n.kind,values:n.values,fields:n.fields}))};return createHash("sha256").update(JSON.stringify(r)).digest("hex")}async function tx(e,t,r){let n=e.connection;if(typeof n.updateDeparseInfo!="function")return false;let s=Me__default.join(process.cwd(),Ya),i;try{i=await pe__default.readFile(s,"utf-8");}catch{return false}let o;try{o=JSON.parse(i);}catch{return false}if(o.v!==Zf||o.hash!==tm(e,t)||!r||o.dbFingerprint!==r||!o.ast||typeof o.ast!="object")return false;try{let a=await Promise.resolve().then(()=>(Ka(),Va)),l=o.ast,c=a.collectEnums(l),p=a.collectSchema(l,c),u=a.collectVariables(l),f=a.collectTableConstraints(l),h=a.collectComments(l),d=n.config?.translation?.schemas?.defaultSchema,{policies:m,tables:w}=a.collectPolicies(l,{defaultSchema:d});return n.updateDeparseInfo({enums:c,rls:{tables:w,policies:m},schema:p,vars:u,tableConstraints:f,comments:h}),!0}catch{return false}}async function Qf(e,t,r,n){if(!r||typeof r!="object")return;let s={v:Zf,hash:tm(e,t),dbFingerprint:n,ast:r},i=Me__default.join(process.cwd(),Ya);try{await pe__default.mkdir(Me__default.dirname(i),{recursive:!0}),await pe__default.writeFile(i,JSON.stringify(s),"utf-8");}catch{}}async function rm(){let e=Me__default.join(process.cwd(),Ya);try{await pe__default.unlink(e);}catch{}}function nm(e,t){console.log();let r=(s,i)=>{let o=l=>{let c=M.default.dim;return typeof l=="number"&&(l>=0&&(c=l>0?M.default.green:M.default.dim),l<0&&(c=M.default.red)),typeof l=="boolean"?l?M.default.green("\u2713"):M.default.red("\u2717"):c(String(l))},a=Object.entries(i).map(([l,c])=>`${l}: ${o(c)}`).join(M.default.dim(" / "));console.log(`${M.default.dim("[")} ${s} ${M.default.dim("]")} ${a}`);};r(M.default.green("DATA"),{tables:e.tables.length,columns:e.columns.length,indexes:e.indexes.length});let n=t.config.rls??t.connection.config.translation?.deparse?.rls??{tables:new Set([]),policies:[]};r(M.default.green("AUTH"),{enabled:!!t.config.auth?.enabled,tables:ensureVar.Set(n.tables).size,policies:ensureVar.Array(n.policies).length});}function sm(e,t){setTimeout(()=>{console.log(M.default.dim("Watching for changes...")),JE.watch("./supabase/schemas").on("change",async n=>{console.log(),console.log(M.default.dim(`Schema changed: ${n}`)),await em(e,t);let s=await e.connection.introspect();nm(s,e);});},200);}function Qa(e,t){let r=t?.colorize?M.default.dim:n=>n;return e.plan.steps.flatMap(n=>[n.description?r(`-- ${n.description}`):"",n.sql+`
84
+ `));return r||""}async function rm(e,t){let r=await ge(e);if(!(!r&&(await Ue(e)).length>0)&&!(!r&&!e.connection.config.baseSchema)){if(t?.dbHasTables&&await sx(e,r,t.dbFingerprint)){console.log(M.default.dim("Schema unchanged \u2014 skipping translation."));return}try{let n=e.connection.createMigrator(r),s=await n.diff(),i=n.translationResult?.ast,o=await e.connection.introspect(),a=Ya(o);if(s.plan.steps.length===0){await em(e,r,i,a);return}await n.migratePlan(s.plan,{force:t?.force??!1}),ox(s);let l=await e.connection.introspect();return await em(e,r,i,Ya(l)),console.log(""),dr(s),s}catch(n){if(String(n).includes("likely empty"))console.log(M.default.dim("Nothing to migrate."));else {console.error("Migration error: "+String(n));try{await e.connection.exec("rollback");}catch{}}}}}function nx(e){return e.connection.config?.baseSchema??""}function nm(e,t){let r=createHash("sha256");return r.update(JSON.stringify([nx(e),t??""])),r.digest("hex")}function Ya(e){let t=(n,s)=>[...n].sort((i,o)=>s(i).localeCompare(s(o))),r={tables:t(e.tables??[],n=>`${n.schema??""}.${n.name}`).map(n=>({schema:n.schema,name:n.name,type:n.type,sql:n.sql})),columns:t(e.columns??[],n=>`${n.schema??""}.${n.table}.${n.name}`).map(n=>({schema:n.schema,table:n.table,name:n.name,type:n.type,nullable:n.nullable,default_value:n.default_value,is_primary_key:n.is_primary_key})),indexes:t(e.indexes??[],n=>`${n.schema??""}.${n.table}.${n.name}`).map(n=>({schema:n.schema,table:n.table,name:n.name,unique:n.unique,columns:n.columns})),foreign_keys:t(e.foreign_keys??[],n=>`${n.schema??""}.${n.table}.${n.column}->${n.ref_table}.${n.ref_column}`).map(n=>({schema:n.schema,table:n.table,column:n.column,ref_schema:n.ref_schema,ref_table:n.ref_table,ref_column:n.ref_column})),primary_keys:t(e.primary_keys??[],n=>`${n.schema??""}.${n.table}`).map(n=>({schema:n.schema,table:n.table,columns:n.columns})),check_constraints:t(e.check_constraints??[],n=>`${n.schema??""}.${n.table}.${n.name??""}.${n.column??""}`).map(n=>({schema:n.schema,table:n.table,name:n.name,column:n.column,expression:n.expression})),unique_constraints:t(e.unique_constraints??[],n=>`${n.schema??""}.${n.table}.${n.name}`).map(n=>({schema:n.schema,table:n.table,name:n.name,columns:n.columns})),views:t(e.views??[],n=>`${n.schema??""}.${n.name}`).map(n=>({schema:n.schema,name:n.name,sql:n.sql})),triggers:t(e.triggers??[],n=>`${n.schema??""}.${n.table}.${n.name}`).map(n=>({schema:n.schema,table:n.table,name:n.name,sql:n.sql})),custom_types:t(e.custom_types??[],n=>`${n.schema??""}.${n.type}`).map(n=>({schema:n.schema,type:n.type,kind:n.kind,values:n.values,fields:n.fields}))};return createHash("sha256").update(JSON.stringify(r)).digest("hex")}async function sx(e,t,r){let n=e.connection;if(typeof n.updateDeparseInfo!="function")return false;let s=Me__default.join(process.cwd(),Za),i;try{i=await pe__default.readFile(s,"utf-8");}catch{return false}let o;try{o=JSON.parse(i);}catch{return false}if(o.v!==tm||o.hash!==nm(e,t)||!r||o.dbFingerprint!==r||!o.ast||typeof o.ast!="object")return false;try{let a=await Promise.resolve().then(()=>(Ja(),Xa)),l=o.ast,c=a.collectEnums(l),p=a.collectSchema(l,c),u=a.collectVariables(l),f=a.collectTableConstraints(l),h=a.collectComments(l),d=n.config?.translation?.schemas?.defaultSchema,{policies:m,tables:w}=a.collectPolicies(l,{defaultSchema:d});return n.updateDeparseInfo({enums:c,rls:{tables:w,policies:m},schema:p,vars:u,tableConstraints:f,comments:h}),!0}catch{return false}}async function em(e,t,r,n){if(!r||typeof r!="object")return;let s={v:tm,hash:nm(e,t),dbFingerprint:n,ast:r},i=Me__default.join(process.cwd(),Za);try{await pe__default.mkdir(Me__default.dirname(i),{recursive:!0}),await pe__default.writeFile(i,JSON.stringify(s),"utf-8");}catch{}}async function sm(){let e=Me__default.join(process.cwd(),Za);try{await pe__default.unlink(e);}catch{}}function im(e,t){console.log();let r=(s,i)=>{let o=l=>{let c=M.default.dim;return typeof l=="number"&&(l>=0&&(c=l>0?M.default.green:M.default.dim),l<0&&(c=M.default.red)),typeof l=="boolean"?l?M.default.green("\u2713"):M.default.red("\u2717"):c(String(l))},a=Object.entries(i).map(([l,c])=>`${l}: ${o(c)}`).join(M.default.dim(" / "));console.log(`${M.default.dim("[")} ${s} ${M.default.dim("]")} ${a}`);};r(M.default.green("DATA"),{tables:e.tables.length,columns:e.columns.length,indexes:e.indexes.length});let n=t.config.rls??t.connection.config.translation?.deparse?.rls??{tables:new Set([]),policies:[]};r(M.default.green("AUTH"),{enabled:!!t.config.auth?.enabled,tables:ensureVar.Set(n.tables).size,policies:ensureVar.Array(n.policies).length});}function om(e,t){setTimeout(()=>{console.log(M.default.dim("Watching for changes...")),ZE.watch("./supabase/schemas").on("change",async n=>{console.log(),console.log(M.default.dim(`Schema changed: ${n}`)),await rm(e,t);let s=await e.connection.introspect();im(s,e);});},200);}function el(e,t){let r=t?.colorize?M.default.dim:n=>n;return e.plan.steps.flatMap(n=>[n.description?r(`-- ${n.description}`):"",n.sql+`
83
85
  `]).filter(n=>n.trim().length>0).join(`
84
- `)}function rx(e){let t=new Date;return `${t.getFullYear().toString()+(t.getMonth()+1).toString().padStart(2,"0")+t.getDate().toString().padStart(2,"0")+t.getHours().toString().padStart(2,"0")+t.getMinutes().toString().padStart(2,"0")+t.getSeconds().toString().padStart(2,"0")}.sql`}function nx(e,t){let r="./supabase/.temp/migrations";ke(r);let n=rx(),s=Qa(e);vt(Me__default.join(r,n),s),console.log(M.default.dim(`Migration written to ${M.default.cyan(Me__default.join(r,n))}`));}function im(e){let t=e.schema_separator??".",r=e.ddl_dialect==="postgres",n=(a,l)=>r&&a?`${a}${t}${l}`:l;console.log(M.default.bgWhite(M.default.black(" Schema "))),console.log();let s=e.tables.filter(a=>a.type==="table"),i=r?"sqlite-postgres":"sqlite";if(console.log(M.default.dim(`${i}${e.version?` (sqlite ${e.version})`:""} \xB7 ${e.database_name}`)),console.log(),s.length===0){console.log(M.default.dim("No tables."));return}console.log(M.default.dim("Tables:"));for(let a of s){let l=n(a.schema,a.name),c=e.columns.filter(u=>u.table===a.name&&(!r||u.schema===a.schema)).sort((u,f)=>u.ordinal_position-f.ordinal_position),p=a.rows>=0?` ${M.default.dim(`(${a.rows} rows)`)}`:"";console.log(`${M.default.bold(l)}${p}`);for(let u of c){let f=[];u.is_primary_key&&f.push(M.default.green("PK")),u.nullable||f.push(M.default.dim("NOT NULL")),u.default_value!==null&&f.push(M.default.dim(`DEFAULT ${u.default_value}`));let h=f.length?" "+f.join(" "):"";console.log(` ${u.name} ${M.default.cyan(u.type)}${h}`);}console.log();}let o=e.indexes.filter(a=>!a.name.startsWith("sqlite_autoindex_"));if(o.length>0){console.log(M.default.dim("Indexes:"));for(let a of o){let l=a.unique?M.default.yellow("UNIQUE "):"";console.log(` ${a.name} on ${n(a.schema,a.table)} ${l}(${a.columns.join(", ")})`);}console.log();}if(e.foreign_keys.length>0){console.log(M.default.dim("Foreign Keys:"));for(let a of e.foreign_keys){let l=`${n(a.schema,a.table)}.${a.column}`,c=`${n(a.ref_schema,a.ref_table)}.${a.ref_column}`;console.log(` ${l} \u2192 ${c} ${M.default.dim(`ON DELETE ${a.on_delete} ON UPDATE ${a.on_update}`)}`);}console.log();}if(e.views.length>0){console.log(M.default.dim("Views:"));for(let a of e.views)console.log(` ${n(a.schema,a.name)}`);console.log();}if(e.triggers.length>0){console.log(M.default.dim("Triggers:"));for(let a of e.triggers)console.log(` ${a.name} on ${n(a.schema,a.table)}`);console.log();}}function dr({diff:e}){if(typeof e=="string"){console.log(M.default.cyan(e));return}if(!e.has_changes)return;console.log(M.default.bgWhite(M.default.black(" Schema Diff "))),console.log();let t={added:{color:M.default.green,symbol:"+"},removed:{color:M.default.red,symbol:"-"},modified:{color:M.default.yellow,symbol:"~"}};if(e.tables.length>0){console.log(M.default.dim("Tables:"));for(let r of e.tables){let{color:n,symbol:s}=t[r.type];console.log(n(`${s} ${r.name}`));}console.log();}if(e.columns.length>0){console.log(M.default.dim("Columns:"));for(let r of e.columns){let{color:n,symbol:s}=t[r.type],i="";r.changes&&(i=Object.entries(r.changes).map(([o,a])=>`${o}: ${a.from} \u2192 ${a.to}`).join(", ")),console.log(n(`${s} ${r.table}.${r.name}${i?` (${i})`:""}`));}console.log();}if(e.indexes.length>0){console.log(M.default.dim("Indexes:"));for(let r of e.indexes){let{color:n,symbol:s}=t[r.type];console.log(n(`${s} ${r.name} on ${r.table}`));}console.log();}if(e.foreign_keys.length>0){console.log(M.default.dim("Foreign Keys:"));for(let r of e.foreign_keys){let{color:n,symbol:s}=t[r.type];console.log(n(`${s} ${r.table}.${r.column} \u2192 ${r.ref_table}.${r.ref_column}`));}console.log();}}var M,Ya,Zf,Ye=g(()=>{ya();M=te(ae());Tt();wt();Dt();Ya="supabase/.temp/.translation-cache.json",Zf=2;});function sx(e){return e==="service_role"?"NOLOGIN BYPASSRLS":"NOLOGIN"}function Et(e){return e.size===0?"":`DO $$ BEGIN${[...e].map(r=>`
86
+ `)}function ix(e){let t=new Date;return `${t.getFullYear().toString()+(t.getMonth()+1).toString().padStart(2,"0")+t.getDate().toString().padStart(2,"0")+t.getHours().toString().padStart(2,"0")+t.getMinutes().toString().padStart(2,"0")+t.getSeconds().toString().padStart(2,"0")}.sql`}function ox(e,t){let r="./supabase/.temp/migrations";ke(r);let n=ix(),s=el(e);vt(Me__default.join(r,n),s),console.log(M.default.dim(`Migration written to ${M.default.cyan(Me__default.join(r,n))}`));}function am(e){let t=e.schema_separator??".",r=e.ddl_dialect==="postgres",n=(a,l)=>r&&a?`${a}${t}${l}`:l;console.log(M.default.bgWhite(M.default.black(" Schema "))),console.log();let s=e.tables.filter(a=>a.type==="table"),i=r?"sqlite-postgres":"sqlite";if(console.log(M.default.dim(`${i}${e.version?` (sqlite ${e.version})`:""} \xB7 ${e.database_name}`)),console.log(),s.length===0){console.log(M.default.dim("No tables."));return}console.log(M.default.dim("Tables:"));for(let a of s){let l=n(a.schema,a.name),c=e.columns.filter(u=>u.table===a.name&&(!r||u.schema===a.schema)).sort((u,f)=>u.ordinal_position-f.ordinal_position),p=a.rows>=0?` ${M.default.dim(`(${a.rows} rows)`)}`:"";console.log(`${M.default.bold(l)}${p}`);for(let u of c){let f=[];u.is_primary_key&&f.push(M.default.green("PK")),u.nullable||f.push(M.default.dim("NOT NULL")),u.default_value!==null&&f.push(M.default.dim(`DEFAULT ${u.default_value}`));let h=f.length?" "+f.join(" "):"";console.log(` ${u.name} ${M.default.cyan(u.type)}${h}`);}console.log();}let o=e.indexes.filter(a=>!a.name.startsWith("sqlite_autoindex_"));if(o.length>0){console.log(M.default.dim("Indexes:"));for(let a of o){let l=a.unique?M.default.yellow("UNIQUE "):"";console.log(` ${a.name} on ${n(a.schema,a.table)} ${l}(${a.columns.join(", ")})`);}console.log();}if(e.foreign_keys.length>0){console.log(M.default.dim("Foreign Keys:"));for(let a of e.foreign_keys){let l=`${n(a.schema,a.table)}.${a.column}`,c=`${n(a.ref_schema,a.ref_table)}.${a.ref_column}`;console.log(` ${l} \u2192 ${c} ${M.default.dim(`ON DELETE ${a.on_delete} ON UPDATE ${a.on_update}`)}`);}console.log();}if(e.views.length>0){console.log(M.default.dim("Views:"));for(let a of e.views)console.log(` ${n(a.schema,a.name)}`);console.log();}if(e.triggers.length>0){console.log(M.default.dim("Triggers:"));for(let a of e.triggers)console.log(` ${a.name} on ${n(a.schema,a.table)}`);console.log();}}function dr({diff:e}){if(typeof e=="string"){console.log(M.default.cyan(e));return}if(!e.has_changes)return;console.log(M.default.bgWhite(M.default.black(" Schema Diff "))),console.log();let t={added:{color:M.default.green,symbol:"+"},removed:{color:M.default.red,symbol:"-"},modified:{color:M.default.yellow,symbol:"~"}};if(e.tables.length>0){console.log(M.default.dim("Tables:"));for(let r of e.tables){let{color:n,symbol:s}=t[r.type];console.log(n(`${s} ${r.name}`));}console.log();}if(e.columns.length>0){console.log(M.default.dim("Columns:"));for(let r of e.columns){let{color:n,symbol:s}=t[r.type],i="";r.changes&&(i=Object.entries(r.changes).map(([o,a])=>`${o}: ${a.from} \u2192 ${a.to}`).join(", ")),console.log(n(`${s} ${r.table}.${r.name}${i?` (${i})`:""}`));}console.log();}if(e.indexes.length>0){console.log(M.default.dim("Indexes:"));for(let r of e.indexes){let{color:n,symbol:s}=t[r.type];console.log(n(`${s} ${r.name} on ${r.table}`));}console.log();}if(e.foreign_keys.length>0){console.log(M.default.dim("Foreign Keys:"));for(let r of e.foreign_keys){let{color:n,symbol:s}=t[r.type];console.log(n(`${s} ${r.table}.${r.column} \u2192 ${r.ref_table}.${r.ref_column}`));}console.log();}}var M,Za,tm,Ye=g(()=>{ba();M=te(ae());Tt();wt();Dt();Za="supabase/.temp/.translation-cache.json",tm=2;});function ax(e){return e==="service_role"?"NOLOGIN BYPASSRLS":"NOLOGIN"}function Et(e){return e.size===0?"":`DO $$ BEGIN${[...e].map(r=>`
85
87
  IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '${r}') THEN
86
- CREATE ROLE ${r} ${sx(r)};
88
+ CREATE ROLE ${r} ${ax(r)};
87
89
  END IF;`).join("")}
88
90
  END $$;
89
- `}function Sn(e,t){return e?e.quoted?e.value===t:e.value.toLowerCase()===t:false}function Re(e){return e?.quoted?e.value:e?.value.toLowerCase()}function ix(e,t){let r="",n=t+1;for(;n<e.length;){if(e[n]==='"'&&e[n+1]==='"'){r+='"',n+=2;continue}if(e[n]==='"')return {token:{value:r,quoted:true},end:n+1};r+=e[n],n++;}return {token:{value:r,quoted:true},end:n}}function ox(e,t){let r=t+1;for(;r<e.length;){if(e[r]==="'"&&e[r+1]==="'"){r+=2;continue}if(e[r]==="'")return r+1;r++;}return r}function ax(e,t){let r=/^\$[A-Za-z_][A-Za-z0-9_]*\$|^\$\$/.exec(e.slice(t))?.[0];if(!r)return;let n=t+r.length,s=e.indexOf(r,n);return s===-1?e.length:s+r.length}function el(e){let t=[],r=0;for(;r<e.length;){let n=e[r],s=e[r+1];if(/\s/.test(n)){r++;continue}if(n==="-"&&s==="-"){for(r+=2;r<e.length&&e[r]!==`
90
- `;)r++;continue}if(n==="/"&&s==="*"){for(r+=2;r<e.length&&!(e[r]==="*"&&e[r+1]==="/");)r++;r=r<e.length?r+2:r;continue}if(n==="'"){r=ox(e,r);continue}if(n==="$"){let i=ax(e,r);if(i!==void 0){r=i;continue}}if(n==='"'){let{token:i,end:o}=ix(e,r);t.push(i),r=o;continue}if(n===","||n===";"){t.push({value:n,quoted:false}),r++;continue}if(/[A-Za-z_]/.test(n)){let i=r;for(r++;r<e.length&&/[A-Za-z0-9_$]/.test(e[r]);)r++;t.push({value:e.slice(i,r).toLowerCase(),quoted:false});continue}r++;}return t}function am(e,t){let r=Re(e[t]),n=Re(e[t+1]);if((r==="create"||r==="alter")&&(n==="role"||n==="user"||n==="group"))return e[t+2]}function Ws(e){let t=new Set,r=el(e);for(let n=0;n<r.length;n++){if(Re(r[n])!=="create")continue;let s=am(r,n);for(let i of hr)Sn(s,i)&&t.add(i);}return t}function Za(e,t,r){let n=new Set([";","as","by","check","for","granted","in","on","option","using","where","with"]);for(let s=t;s<e.length;s++){let i=Re(e[s]);if(!i||n.has(i))return;for(let o of hr)Sn(e[s],o)&&r.add(o);}}function lx(e){let t=[],r=[];for(let n of e){if(Re(n)===";"){r.length>0&&t.push(r),r=[];continue}r.push(n);}return r.length>0&&t.push(r),t}function om(e,t){return e.some(r=>Re(r)===t)}function cx(e){let t=new Set,r=lx(el(e));for(let n of r){let s=Re(n[0]);for(let a=0;a<n.length;a++){let l=Re(n[a]);l==="to"&&(om(n,"grant")||om(n,"policy")||Re(n[a-1])==="owner")&&Za(n,a+1,t),l==="from"&&s==="revoke"&&Za(n,a+1,t);}let i=n.findIndex(a=>Re(a)==="to"),o=n.findIndex(a=>Re(a)==="on");s==="grant"&&i>1&&(o===-1||i<o)&&Za(n,1,t);}return t}function xt(e){let t=Ws(e);return new Set([...cx(e)].filter(r=>!t.has(r)))}function lm(e){let t=Ws(e);return new Set(hr.filter(r=>!t.has(r)))}function cm(e,t){let r=el(e);if(r.length===0)return false;let n=am(r,0);if(n){for(let o of t)if(Sn(n,o))return true;return false}let s=Re(r[0]),i=Re(r[1]);if(s==="drop"&&(i==="role"||i==="user"||i==="group")){for(let o of r.slice(2))for(let a of t)if(Sn(o,a))return true}if(s==="comment"&&Re(r[1])==="on"&&Re(r[2])==="role"){for(let o of t)if(Sn(r[3],o))return true}return false}var hr,Hs,En=g(()=>{hr=["anon","authenticated","service_role"];Et(new Set(hr)),Hs=`
91
+ `}function En(e,t){return e?e.quoted?e.value===t:e.value.toLowerCase()===t:false}function Re(e){return e?.quoted?e.value:e?.value.toLowerCase()}function lx(e,t){let r="",n=t+1;for(;n<e.length;){if(e[n]==='"'&&e[n+1]==='"'){r+='"',n+=2;continue}if(e[n]==='"')return {token:{value:r,quoted:true},end:n+1};r+=e[n],n++;}return {token:{value:r,quoted:true},end:n}}function cx(e,t){let r=t+1;for(;r<e.length;){if(e[r]==="'"&&e[r+1]==="'"){r+=2;continue}if(e[r]==="'")return r+1;r++;}return r}function ux(e,t){let r=/^\$[A-Za-z_][A-Za-z0-9_]*\$|^\$\$/.exec(e.slice(t))?.[0];if(!r)return;let n=t+r.length,s=e.indexOf(r,n);return s===-1?e.length:s+r.length}function rl(e){let t=[],r=0;for(;r<e.length;){let n=e[r],s=e[r+1];if(/\s/.test(n)){r++;continue}if(n==="-"&&s==="-"){for(r+=2;r<e.length&&e[r]!==`
92
+ `;)r++;continue}if(n==="/"&&s==="*"){for(r+=2;r<e.length&&!(e[r]==="*"&&e[r+1]==="/");)r++;r=r<e.length?r+2:r;continue}if(n==="'"){r=cx(e,r);continue}if(n==="$"){let i=ux(e,r);if(i!==void 0){r=i;continue}}if(n==='"'){let{token:i,end:o}=lx(e,r);t.push(i),r=o;continue}if(n===","||n===";"){t.push({value:n,quoted:false}),r++;continue}if(/[A-Za-z_]/.test(n)){let i=r;for(r++;r<e.length&&/[A-Za-z0-9_$]/.test(e[r]);)r++;t.push({value:e.slice(i,r).toLowerCase(),quoted:false});continue}r++;}return t}function cm(e,t){let r=Re(e[t]),n=Re(e[t+1]);if((r==="create"||r==="alter")&&(n==="role"||n==="user"||n==="group"))return e[t+2]}function Gs(e){let t=new Set,r=rl(e);for(let n=0;n<r.length;n++){if(Re(r[n])!=="create")continue;let s=cm(r,n);for(let i of hr)En(s,i)&&t.add(i);}return t}function tl(e,t,r){let n=new Set([";","as","by","check","for","granted","in","on","option","using","where","with"]);for(let s=t;s<e.length;s++){let i=Re(e[s]);if(!i||n.has(i))return;for(let o of hr)En(e[s],o)&&r.add(o);}}function px(e){let t=[],r=[];for(let n of e){if(Re(n)===";"){r.length>0&&t.push(r),r=[];continue}r.push(n);}return r.length>0&&t.push(r),t}function lm(e,t){return e.some(r=>Re(r)===t)}function fx(e){let t=new Set,r=px(rl(e));for(let n of r){let s=Re(n[0]);for(let a=0;a<n.length;a++){let l=Re(n[a]);l==="to"&&(lm(n,"grant")||lm(n,"policy")||Re(n[a-1])==="owner")&&tl(n,a+1,t),l==="from"&&s==="revoke"&&tl(n,a+1,t);}let i=n.findIndex(a=>Re(a)==="to"),o=n.findIndex(a=>Re(a)==="on");s==="grant"&&i>1&&(o===-1||i<o)&&tl(n,1,t);}return t}function xt(e){let t=Gs(e);return new Set([...fx(e)].filter(r=>!t.has(r)))}function um(e){let t=Gs(e);return new Set(hr.filter(r=>!t.has(r)))}function pm(e,t){let r=rl(e);if(r.length===0)return false;let n=cm(r,0);if(n){for(let o of t)if(En(n,o))return true;return false}let s=Re(r[0]),i=Re(r[1]);if(s==="drop"&&(i==="role"||i==="user"||i==="group")){for(let o of r.slice(2))for(let a of t)if(En(o,a))return true}if(s==="comment"&&Re(r[1])==="on"&&Re(r[2])==="role"){for(let o of t)if(En(r[3],o))return true}return false}var hr,Ws,xn=g(()=>{hr=["anon","authenticated","service_role"];Et(new Set(hr)),Ws=`
91
93
  CREATE SCHEMA IF NOT EXISTS auth;
92
94
 
93
95
  CREATE OR REPLACE FUNCTION auth.uid() RETURNS UUID AS $$
@@ -108,96 +110,96 @@ CREATE OR REPLACE FUNCTION auth.jwt() RETURNS JSONB AS $$
108
110
  '{}'
109
111
  )::jsonb;
110
112
  $$ LANGUAGE SQL STABLE;
111
- `;});async function Gt(e){await px(e),await Lt(e.connection);let t=new Set(await Zr(e.connection)),r=await Ue(e),n=Le(e.connection),s=[],i=[];for(let o of r){if(t.has(o.version)){i.push(o);continue}let a=mt(o.sql),l;if(n==="pg-flat"){let p=await e.connection.translateDdl(o.sql),u=typeof p=="string"?p:p.ddl??"";l=mt(u);}else l=a;let c=Nf(n,{version:o.version,name:o.name,statements:a});if(n==="pg"){let p=Et(xt(o.sql));p&&await e.connection.exec(p);}await e.connection.transaction([...l,c],{intent:"migration"}),s.push(o);}return r.length>0&&n!=="sqlite"&&await ux(e,r),{applied:s,skipped:i}}async function ux(e,t){let r=t.map(o=>o.sql).join(`
112
- `);if(!r.trim())return;let n=e.connection;if(typeof n.translateDdl!="function"||typeof n.updateDeparseInfo!="function")return;let s=await n.translateDdl(r),i=n.config?.translation?.deparse??{};n.updateDeparseInfo({...i,...s});}async function px(e){let t=e.connection.config?.baseSchema;if(!t||!t.trim())return;let r=e.connection,n=t;if(r.dialect==="sqlite"&&r.config.ddlDialect!=="sqlite"&&r.translateDdl){let s=await r.translateDdl(t);n=typeof s=="string"?s:s.ddl??t;}for(let s of mt(n))try{await r.exec(s);}catch{}}var Gs=g(()=>{Rt();Dt();wt();En();});function be(e){return `${fx} ${e}`}var fx,ot=g(()=>{fx="[lite]";});var um={};de(um,{dev:()=>hx});var He,hx,pm=g(()=>{no();Yo();ht();He=te(ae());Zt();Ye();Gs();wt();Ce();$e();Yt();ot();hx=e=>{e.command("dev").option("--template","Create a template for the database",false).option("--config <config>","Path to the config file").description(be("Start the development server with schema watching")).helpGroup("Local Development:").action(async t=>{await Q(t.config),console.log(He.default.yellow(" \u26A0 [lite] dev is experimental and works with declarative schema only.")),await ns(async()=>{await ts({template:t.template}),console.log();let n=await(await z({withSupabaseClient:false})).project.local.createApp(t.config),s=n.config.api?.port??ye.default_api_port;if((await Ue(n)).length>0){let c=await Gt(n);for(let p of c.applied)console.log(He.default.green(" \u2713"),"Applied migration",He.default.cyan(p.filename));}await wn(n,{force:true}),console.log();await Es(n,{port:s});console.log(He.default.green(" \u279C"),"Server running on ",He.default.cyan(`http://localhost:${s}`));let a=Bn();a&&console.log(He.default.yellow(` \u26A0 ${a}`)),await n.connection.ping(),sm(n,{translate:true,force:true});let l=Me__default.join(process.cwd(),"supabase",jt(n));setTimeout(()=>{JE.watch(l,{ignoreInitial:true}).on("add",async p=>{console.log(),console.log(He.default.dim(`Migration added: ${p}`));try{let u=await Gt(n);for(let f of u.applied)console.log(He.default.green(" \u2713"),"Applied",He.default.cyan(f.filename));}catch(u){console.error(He.default.red("Migration failed: "+String(u.message??u)));}});},200),process.on("SIGINT",async()=>{await n.connection.close(),process.exit(1);});},r=>{console.log(),console.log(He.default.green(`Ready in ${r.toFixed(2)}ms`));});});};});async function at(e){let t=await z({withSupabaseClient:false}),r=t.project.local.ref();if(typeof e=="boolean"&&e){if(!r)throw new Error("No project linked");if(!await t.project.remote.ping())throw new Error("Remote project is not reachable");return Ze("creating app for remote project",r),t.project.remote.createApp(r)}return t.project.local.createApp(e)}var tl=g(()=>{Ce();er();});var fm={};de(fm,{repl:()=>gx});var Se,gx,mm=g(()=>{ht();Se=te(ae());tl();$e();ot();gx=e=>{e.command("repl").option("--config <config>","Path to the config file").option("--remote","Connect REPL to a remote project").description(be("Start a REPL session")).helpGroup("Local Development:").action(async t=>{t.remote||await Q(t.config);let r=await at(t.remote?true:t.config);rs()||(console.error(Se.default.red("REPL is only supported on Node.js")),process.exit(1));let n={app:r,client:r.getClient(),conn:r.connection,db:r.connection.driver};console.log(Se.default.green("Starting a REPL session")),console.log(Se.default.bold("Available variables:"),Object.keys(n).map(o=>Se.default.cyan(o)).join(", "));let i=(await import('node:repl')).start("> ");i.on("exit",async()=>{await r.connection.close(),process.exit();});for(let o of Object.keys(n))Object.defineProperty(i.context,o,{configurable:false,enumerable:true,value:n[o]});i.defineCommand("tables",{help:"List all tables",action:async function(){let a=await r.connection.introspect(),l=c=>a.columns.filter(p=>p.table===c);console.log(a.tables.map(c=>`${Se.default.cyan(c.name)} (${l(c.name).length} columns)`).join(`
113
+ `;});async function Gt(e){await dx(e),await Lt(e.connection);let t=new Set(await en(e.connection)),r=await Ue(e),n=Le(e.connection),s=[],i=[];for(let o of r){if(t.has(o.version)){i.push(o);continue}let a=mt(o.sql),l;if(n==="pg-flat"){let p=await e.connection.translateDdl(o.sql),u=typeof p=="string"?p:p.ddl??"";l=mt(u);}else l=a;let c=Lf(n,{version:o.version,name:o.name,statements:a});if(n==="pg"){let p=Et(xt(o.sql));p&&await e.connection.exec(p);}await e.connection.transaction([...l,c],{intent:"migration"}),s.push(o);}return r.length>0&&n!=="sqlite"&&await mx(e,r),{applied:s,skipped:i}}async function mx(e,t){let r=t.map(o=>o.sql).join(`
114
+ `);if(!r.trim())return;let n=e.connection;if(typeof n.translateDdl!="function"||typeof n.updateDeparseInfo!="function")return;let s=await n.translateDdl(r),i=n.config?.translation?.deparse??{};n.updateDeparseInfo({...i,...s});}async function dx(e){let t=e.connection.config?.baseSchema;if(!t||!t.trim())return;let r=e.connection,n=t;if(r.dialect==="sqlite"&&r.config.ddlDialect!=="sqlite"&&r.translateDdl){let s=await r.translateDdl(t);n=typeof s=="string"?s:s.ddl??t;}for(let s of mt(n))try{await r.exec(s);}catch{}}var zs=g(()=>{Rt();Dt();wt();xn();});function be(e){return `${hx} ${e}`}var hx,ot=g(()=>{hx="[lite]";});var fm={};de(fm,{dev:()=>wx});var He,wx,mm=g(()=>{so();Zo();ht();He=te(ae());Zt();Ye();zs();wt();Ce();$e();Yt();ot();wx=e=>{e.command("dev").option("--template","Create a template for the database",false).option("--config <config>","Path to the config file").description(be("Start the development server with schema watching")).helpGroup("Local Development:").action(async t=>{await Q(t.config),console.log(He.default.yellow(" \u26A0 [lite] dev is experimental and works with declarative schema only.")),await ss(async()=>{await rs({template:t.template}),console.log();let n=await(await z({withSupabaseClient:false})).project.local.createApp(t.config),s=n.config.api?.port??ye.default_api_port;if((await Ue(n)).length>0){let c=await Gt(n);for(let p of c.applied)console.log(He.default.green(" \u2713"),"Applied migration",He.default.cyan(p.filename));}await bn(n,{force:true}),console.log();await xs(n,{port:s});console.log(He.default.green(" \u279C"),"Server running on ",He.default.cyan(`http://localhost:${s}`));let a=qn();a&&console.log(He.default.yellow(` \u26A0 ${a}`)),await n.connection.ping(),om(n,{translate:true,force:true});let l=Me__default.join(process.cwd(),"supabase",jt(n));setTimeout(()=>{ZE.watch(l,{ignoreInitial:true}).on("add",async p=>{console.log(),console.log(He.default.dim(`Migration added: ${p}`));try{let u=await Gt(n);for(let f of u.applied)console.log(He.default.green(" \u2713"),"Applied",He.default.cyan(f.filename));}catch(u){console.error(He.default.red("Migration failed: "+String(u.message??u)));}});},200),process.on("SIGINT",async()=>{await n.connection.close(),process.exit(1);});},r=>{console.log(),console.log(He.default.green(`Ready in ${r.toFixed(2)}ms`));});});};});async function at(e){let t=await z({withSupabaseClient:false}),r=t.project.local.ref();if(typeof e=="boolean"&&e){if(!r)throw new Error("No project linked");if(!await t.project.remote.ping())throw new Error("Remote project is not reachable");return Ze("creating app for remote project",r),t.project.remote.createApp(r)}return t.project.local.createApp(e)}var nl=g(()=>{Ce();er();});var dm={};de(dm,{repl:()=>bx});var Se,bx,hm=g(()=>{ht();Se=te(ae());nl();$e();ot();bx=e=>{e.command("repl").option("--config <config>","Path to the config file").option("--remote","Connect REPL to a remote project").description(be("Start a REPL session")).helpGroup("Local Development:").action(async t=>{t.remote||await Q(t.config);let r=await at(t.remote?true:t.config);ns()||(console.error(Se.default.red("REPL is only supported on Node.js")),process.exit(1));let n={app:r,client:r.getClient(),conn:r.connection,db:r.connection.driver};console.log(Se.default.green("Starting a REPL session")),console.log(Se.default.bold("Available variables:"),Object.keys(n).map(o=>Se.default.cyan(o)).join(", "));let i=(await import('node:repl')).start("> ");i.on("exit",async()=>{await r.connection.close(),process.exit();});for(let o of Object.keys(n))Object.defineProperty(i.context,o,{configurable:false,enumerable:true,value:n[o]});i.defineCommand("tables",{help:"List all tables",action:async function(){let a=await r.connection.introspect(),l=c=>a.columns.filter(p=>p.table===c);console.log(a.tables.map(c=>`${Se.default.cyan(c.name)} (${l(c.name).length} columns)`).join(`
113
115
  `)),this.displayPrompt();}}),i.defineCommand("table",{help:"Show a table",action:async function(a){let l=await r.connection.introspect(),c=u=>l.columns.filter(f=>f.table===u),p=l.tables.find(u=>u.name===a);p?(console.log(`${Se.default.cyan(p?.name)} (${c(a).length} columns)`),console.log(c(a).map(u=>` - ${Se.default.cyan(u.name)} ${Se.default.yellow(u.type)}`).join(`
114
116
  `)),console.log(),console.log(Se.default.dim(p.sql))):(console.log(Se.default.red(`Table ${a} not found`)),console.log(`Available tables:
115
117
  `+l.tables.map(u=>`- ${Se.default.cyan(u.name)}`).join(`
116
118
  `))),this.displayPrompt();}}),i.defineCommand("indexes",{help:"List all indexes",action:async function(){let a=await r.connection.introspect().then(l=>l.indexes);console.log(a.map(l=>`${Se.default.bold(Se.default.cyan(l.name))} ${l.unique?Se.default.yellow("unique "):""}on ${Se.default.blue(l.table)}(${l.columns.map(c=>Se.default.magenta(c)).join(", ")})`).join(`
117
- `)),this.displayPrompt();}}),i.defineCommand("config",{help:"Show the current config",action:async function(a){console.log(a?io(r.config,a):r.config),this.displayPrompt();}});});};});var dm={};de(dm,{debug:()=>yx});var yx,hm=g(()=>{ht();$e();ot();yx=e=>{e.command("debug").description(be("Print runtime info (bun/node detection, paths)")).helpGroup("Local Development:").action(async()=>{console.log("Debugging the application"),console.log({bun:Or(),node:rs(),cwd:process.cwd(),paths:{root:Qn(),dist:eo(),relativeDist:Zn()}});});};});var nl=ft((wO,gm)=>{var rl={to(e,t){return t?`\x1B[${t+1};${e+1}H`:`\x1B[${e+1}G`},move(e,t){let r="";return e<0?r+=`\x1B[${-e}D`:e>0&&(r+=`\x1B[${e}C`),t<0?r+=`\x1B[${-t}A`:t>0&&(r+=`\x1B[${t}B`),r},up:(e=1)=>`\x1B[${e}A`,down:(e=1)=>`\x1B[${e}B`,forward:(e=1)=>`\x1B[${e}C`,backward:(e=1)=>`\x1B[${e}D`,nextLine:(e=1)=>"\x1B[E".repeat(e),prevLine:(e=1)=>"\x1B[F".repeat(e),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},wx={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},bx={screen:"\x1B[2J",up:(e=1)=>"\x1B[1J".repeat(e),down:(e=1)=>"\x1B[J".repeat(e),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(e){let t="";for(let r=0;r<e;r++)t+=this.line+(r<e-1?rl.up():"");return e&&(t+=rl.left),t}};gm.exports={cursor:rl,scroll:wx,erase:bx,beep:"\x07"};});function Js(e,t,r){if(!r.some(o=>!o.disabled))return e;let n=e+t,s=Math.max(r.length-1,0),i=n<0?s:n>s?0:n;return r[i].disabled?Js(i,t<0?-1:1,r):i}function ll(e,t,r){return String(e).normalize().replaceAll(`\r
119
+ `)),this.displayPrompt();}}),i.defineCommand("config",{help:"Show the current config",action:async function(a){console.log(a?oo(r.config,a):r.config),this.displayPrompt();}});});};});var gm={};de(gm,{debug:()=>Sx});var Sx,ym=g(()=>{ht();$e();ot();Sx=e=>{e.command("debug").description(be("Print runtime info (bun/node detection, paths)")).helpGroup("Local Development:").action(async()=>{console.log("Debugging the application"),console.log({bun:Or(),node:ns(),cwd:process.cwd(),paths:{root:Zn(),dist:to(),relativeDist:es()}});});};});var il=ft((EO,wm)=>{var sl={to(e,t){return t?`\x1B[${t+1};${e+1}H`:`\x1B[${e+1}G`},move(e,t){let r="";return e<0?r+=`\x1B[${-e}D`:e>0&&(r+=`\x1B[${e}C`),t<0?r+=`\x1B[${-t}A`:t>0&&(r+=`\x1B[${t}B`),r},up:(e=1)=>`\x1B[${e}A`,down:(e=1)=>`\x1B[${e}B`,forward:(e=1)=>`\x1B[${e}C`,backward:(e=1)=>`\x1B[${e}D`,nextLine:(e=1)=>"\x1B[E".repeat(e),prevLine:(e=1)=>"\x1B[F".repeat(e),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},Ex={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},xx={screen:"\x1B[2J",up:(e=1)=>"\x1B[1J".repeat(e),down:(e=1)=>"\x1B[J".repeat(e),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(e){let t="";for(let r=0;r<e;r++)t+=this.line+(r<e-1?sl.up():"");return e&&(t+=sl.left),t}};wm.exports={cursor:sl,scroll:Ex,erase:xx,beep:"\x07"};});function Ys(e,t,r){if(!r.some(o=>!o.disabled))return e;let n=e+t,s=Math.max(r.length-1,0),i=n<0?s:n>s?0:n;return r[i].disabled?Ys(i,t<0?-1:1,r):i}function ul(e,t,r){return String(e).normalize().replaceAll(`\r
118
120
  `,`
119
121
  `).split(`
120
- `).map(n=>Ox(n,t,r)).join(`
121
- `)}function ml(e,t){if(typeof e=="string")return Ne.aliases.get(e)===t;for(let r of e)if(r!==void 0&&ml(r,t))return true;return false}function Ix(e,t){if(e===t)return;let r=e.split(`
122
+ `).map(n=>Lx(n,t,r)).join(`
123
+ `)}function hl(e,t){if(typeof e=="string")return Ne.aliases.get(e)===t;for(let r of e)if(r!==void 0&&hl(r,t))return true;return false}function jx(e,t){if(e===t)return;let r=e.split(`
122
124
  `),n=t.split(`
123
- `),s=Math.max(r.length,n.length),i=[];for(let o=0;o<s;o++)r[o]!==n[o]&&i.push(o);return {lines:i,numLinesBefore:r.length,numLinesAfter:n.length,numLines:s}}function Ee(e){return e===cl}function Xs(e,t){let r=e;r.isTTY&&r.setRawMode(t);}function Tm({input:e=stdin,output:t=stdout,overwrite:r=true,hideCursor:n=true}={}){let s=_t.createInterface({input:e,output:t,prompt:"",tabSize:1});_t.emitKeypressEvents(e,s),e instanceof ReadStream&&e.isTTY&&e.setRawMode(true);let i=(o,{name:a,sequence:l})=>{let c=String(o);if(ml([c,a,l],"cancel")){n&&t.write(ve.cursor.show),process.exit(0);return}if(!r)return;_t.moveCursor(t,a==="return"?0:-1,a==="return"?-1:0,()=>{_t.clearLine(t,1,()=>{e.once("keypress",i);});});};return n&&t.write(ve.cursor.hide),e.once("keypress",i),()=>{e.off("keypress",i),n&&t.write(ve.cursor.show),e instanceof ReadStream&&e.isTTY&&!Lx&&e.setRawMode(false),s.terminal=false,s.close();}}function ni(e,t,r,n=r){let s=ri(e??stdout);return ll(t,s-r.length,{hard:true,trim:false}).split(`
125
+ `),s=Math.max(r.length,n.length),i=[];for(let o=0;o<s;o++)r[o]!==n[o]&&i.push(o);return {lines:i,numLinesBefore:r.length,numLinesAfter:n.length,numLines:s}}function Ee(e){return e===pl}function Js(e,t){let r=e;r.isTTY&&r.setRawMode(t);}function Cm({input:e=stdin,output:t=stdout,overwrite:r=true,hideCursor:n=true}={}){let s=_t.createInterface({input:e,output:t,prompt:"",tabSize:1});_t.emitKeypressEvents(e,s),e instanceof ReadStream&&e.isTTY&&e.setRawMode(true);let i=(o,{name:a,sequence:l})=>{let c=String(o);if(hl([c,a,l],"cancel")){n&&t.write(ve.cursor.show),process.exit(0);return}if(!r)return;_t.moveCursor(t,a==="return"?0:-1,a==="return"?-1:0,()=>{_t.clearLine(t,1,()=>{e.once("keypress",i);});});};return n&&t.write(ve.cursor.hide),e.once("keypress",i),()=>{e.off("keypress",i),n&&t.write(ve.cursor.show),e instanceof ReadStream&&e.isTTY&&!Fx&&e.setRawMode(false),s.terminal=false,s.close();}}function si(e,t,r,n=r){let s=ni(e??stdout);return ul(t,s-r.length,{hard:true,trim:false}).split(`
124
126
  `).map((i,o)=>`${o===0?n:r}${i}`).join(`
125
- `)}var ve,Ex,xx,_x,sl,zs,Vs,il,Ks,$x,vx,xm,Tx,xn,ti,_m,Ax,pl,$m,Cx,vm,fl,wm,Rx,bm,Sm,kx,ol,Px,Ox,Nx,Ne,Lx,cl,ri,dl,gr,Ys,Qs,Zs,ei,hl=g(()=>{ve=te(nl());Ex=e=>e===161||e===164||e===167||e===168||e===170||e===173||e===174||e>=176&&e<=180||e>=182&&e<=186||e>=188&&e<=191||e===198||e===208||e===215||e===216||e>=222&&e<=225||e===230||e>=232&&e<=234||e===236||e===237||e===240||e===242||e===243||e>=247&&e<=250||e===252||e===254||e===257||e===273||e===275||e===283||e===294||e===295||e===299||e>=305&&e<=307||e===312||e>=319&&e<=322||e===324||e>=328&&e<=331||e===333||e===338||e===339||e===358||e===359||e===363||e===462||e===464||e===466||e===468||e===470||e===472||e===474||e===476||e===593||e===609||e===708||e===711||e>=713&&e<=715||e===717||e===720||e>=728&&e<=731||e===733||e===735||e>=768&&e<=879||e>=913&&e<=929||e>=931&&e<=937||e>=945&&e<=961||e>=963&&e<=969||e===1025||e>=1040&&e<=1103||e===1105||e===8208||e>=8211&&e<=8214||e===8216||e===8217||e===8220||e===8221||e>=8224&&e<=8226||e>=8228&&e<=8231||e===8240||e===8242||e===8243||e===8245||e===8251||e===8254||e===8308||e===8319||e>=8321&&e<=8324||e===8364||e===8451||e===8453||e===8457||e===8467||e===8470||e===8481||e===8482||e===8486||e===8491||e===8531||e===8532||e>=8539&&e<=8542||e>=8544&&e<=8555||e>=8560&&e<=8569||e===8585||e>=8592&&e<=8601||e===8632||e===8633||e===8658||e===8660||e===8679||e===8704||e===8706||e===8707||e===8711||e===8712||e===8715||e===8719||e===8721||e===8725||e===8730||e>=8733&&e<=8736||e===8739||e===8741||e>=8743&&e<=8748||e===8750||e>=8756&&e<=8759||e===8764||e===8765||e===8776||e===8780||e===8786||e===8800||e===8801||e>=8804&&e<=8807||e===8810||e===8811||e===8814||e===8815||e===8834||e===8835||e===8838||e===8839||e===8853||e===8857||e===8869||e===8895||e===8978||e>=9312&&e<=9449||e>=9451&&e<=9547||e>=9552&&e<=9587||e>=9600&&e<=9615||e>=9618&&e<=9621||e===9632||e===9633||e>=9635&&e<=9641||e===9650||e===9651||e===9654||e===9655||e===9660||e===9661||e===9664||e===9665||e>=9670&&e<=9672||e===9675||e>=9678&&e<=9681||e>=9698&&e<=9701||e===9711||e===9733||e===9734||e===9737||e===9742||e===9743||e===9756||e===9758||e===9792||e===9794||e===9824||e===9825||e>=9827&&e<=9829||e>=9831&&e<=9834||e===9836||e===9837||e===9839||e===9886||e===9887||e===9919||e>=9926&&e<=9933||e>=9935&&e<=9939||e>=9941&&e<=9953||e===9955||e===9960||e===9961||e>=9963&&e<=9969||e===9972||e>=9974&&e<=9977||e===9979||e===9980||e===9982||e===9983||e===10045||e>=10102&&e<=10111||e>=11094&&e<=11097||e>=12872&&e<=12879||e>=57344&&e<=63743||e>=65024&&e<=65039||e===65533||e>=127232&&e<=127242||e>=127248&&e<=127277||e>=127280&&e<=127337||e>=127344&&e<=127373||e===127375||e===127376||e>=127387&&e<=127404||e>=917760&&e<=917999||e>=983040&&e<=1048573||e>=1048576&&e<=1114109,xx=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,_x=e=>e>=4352&&e<=4447||e===8986||e===8987||e===9001||e===9002||e>=9193&&e<=9196||e===9200||e===9203||e===9725||e===9726||e===9748||e===9749||e>=9800&&e<=9811||e===9855||e===9875||e===9889||e===9898||e===9899||e===9917||e===9918||e===9924||e===9925||e===9934||e===9940||e===9962||e===9970||e===9971||e===9973||e===9978||e===9981||e===9989||e===9994||e===9995||e===10024||e===10060||e===10062||e>=10067&&e<=10069||e===10071||e>=10133&&e<=10135||e===10160||e===10175||e===11035||e===11036||e===11088||e===11093||e>=11904&&e<=11929||e>=11931&&e<=12019||e>=12032&&e<=12245||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12353&&e<=12438||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=19968&&e<=42124||e>=42128&&e<=42182||e>=43360&&e<=43388||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=94176&&e<=94180||e===94192||e===94193||e>=94208&&e<=100343||e>=100352&&e<=101589||e>=101632&&e<=101640||e>=110576&&e<=110579||e>=110581&&e<=110587||e===110589||e===110590||e>=110592&&e<=110882||e===110898||e>=110928&&e<=110930||e===110933||e>=110948&&e<=110951||e>=110960&&e<=111355||e===126980||e===127183||e===127374||e>=127377&&e<=127386||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e===127568||e===127569||e>=127584&&e<=127589||e>=127744&&e<=127776||e>=127789&&e<=127797||e>=127799&&e<=127868||e>=127870&&e<=127891||e>=127904&&e<=127946||e>=127951&&e<=127955||e>=127968&&e<=127984||e===127988||e>=127992&&e<=128062||e===128064||e>=128066&&e<=128252||e>=128255&&e<=128317||e>=128331&&e<=128334||e>=128336&&e<=128359||e===128378||e===128405||e===128406||e===128420||e>=128507&&e<=128591||e>=128640&&e<=128709||e===128716||e>=128720&&e<=128722||e>=128725&&e<=128727||e>=128732&&e<=128735||e===128747||e===128748||e>=128756&&e<=128764||e>=128992&&e<=129003||e===129008||e>=129292&&e<=129338||e>=129340&&e<=129349||e>=129351&&e<=129535||e>=129648&&e<=129660||e>=129664&&e<=129672||e>=129680&&e<=129725||e>=129727&&e<=129733||e>=129742&&e<=129755||e>=129760&&e<=129768||e>=129776&&e<=129784||e>=131072&&e<=196605||e>=196608&&e<=262141,sl=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,zs=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Vs=/\t{1,1000}/y,il=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,Ks=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,$x=/\p{M}+/gu,vx={limit:1/0,ellipsis:""},xm=(e,t={},r={})=>{let n=t.limit??1/0,s=t.ellipsis??"",i=t?.ellipsisWidth??(s?xm(s,vx,r).width:0),o=r.ansiWidth??0,a=r.controlWidth??0,l=r.tabWidth??8,c=r.ambiguousWidth??1,p=r.emojiWidth??2,u=r.fullWidthWidth??2,f=r.regularWidth??1,h=r.wideWidth??2,d=0,m=0,w=e.length,y=0,E=false,T=w,v=Math.max(0,n-i),C=0,A=0,$=0,_=0;e:for(;;){if(A>C||m>=w&&m>d){let I=e.slice(C,A)||e.slice(d,m);y=0;for(let b of I.replaceAll($x,"")){let D=b.codePointAt(0)||0;if(xx(D)?_=u:_x(D)?_=h:c!==f&&Ex(D)?_=c:_=f,$+_>v&&(T=Math.min(T,Math.max(C,d)+y)),$+_>n){E=true;break e}y+=b.length,$+=_;}C=A=0;}if(m>=w)break;if(Ks.lastIndex=m,Ks.test(e)){if(y=Ks.lastIndex-m,_=y*f,$+_>v&&(T=Math.min(T,m+Math.floor((v-$)/f))),$+_>n){E=true;break}$+=_,C=d,A=m,m=d=Ks.lastIndex;continue}if(sl.lastIndex=m,sl.test(e)){if($+o>v&&(T=Math.min(T,m)),$+o>n){E=true;break}$+=o,C=d,A=m,m=d=sl.lastIndex;continue}if(zs.lastIndex=m,zs.test(e)){if(y=zs.lastIndex-m,_=y*a,$+_>v&&(T=Math.min(T,m+Math.floor((v-$)/a))),$+_>n){E=true;break}$+=_,C=d,A=m,m=d=zs.lastIndex;continue}if(Vs.lastIndex=m,Vs.test(e)){if(y=Vs.lastIndex-m,_=y*l,$+_>v&&(T=Math.min(T,m+Math.floor((v-$)/l))),$+_>n){E=true;break}$+=_,C=d,A=m,m=d=Vs.lastIndex;continue}if(il.lastIndex=m,il.test(e)){if($+p>v&&(T=Math.min(T,m)),$+p>n){E=true;break}$+=p,C=d,A=m,m=d=il.lastIndex;continue}m+=1;}return {width:E?v:$,index:E?T:w,truncated:E,ellipsed:E&&n>=i}},Tx={limit:1/0,ellipsis:"",ellipsisWidth:0},xn=(e,t={})=>xm(e,Tx,t).width,ti="\x1B",_m="\x9B",Ax=39,pl="\x07",$m="[",Cx="]",vm="m",fl=`${Cx}8;;`,wm=new RegExp(`(?:\\${$m}(?<code>\\d+)m|\\${fl}(?<uri>.*)${pl})`,"y"),Rx=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},bm=e=>`${ti}${$m}${e}${vm}`,Sm=e=>`${ti}${fl}${e}${pl}`,kx=e=>e.map(t=>xn(t)),ol=(e,t,r)=>{let n=t[Symbol.iterator](),s=false,i=false,o=e.at(-1),a=o===void 0?0:xn(o),l=n.next(),c=n.next(),p=0;for(;!l.done;){let u=l.value,f=xn(u);a+f<=r?e[e.length-1]+=u:(e.push(u),a=0),(u===ti||u===_m)&&(s=true,i=t.startsWith(fl,p+1)),s?i?u===pl&&(s=false,i=false):u===vm&&(s=false):(a+=f,a===r&&!c.done&&(e.push(""),a=0)),l=c,c=n.next(),p+=u.length;}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop());},Px=e=>{let t=e.split(" "),r=t.length;for(;r>0&&!(xn(t[r-1])>0);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")},Ox=(e,t,r={})=>{if(r.trim!==false&&e.trim()==="")return "";let n="",s,i,o=e.split(" "),a=kx(o),l=[""];for(let[d,m]of o.entries()){r.trim!==false&&(l[l.length-1]=(l.at(-1)??"").trimStart());let w=xn(l.at(-1)??"");if(d!==0&&(w>=t&&(r.wordWrap===false||r.trim===false)&&(l.push(""),w=0),(w>0||r.trim===false)&&(l[l.length-1]+=" ",w++)),r.hard&&a[d]>t){let y=t-w,E=1+Math.floor((a[d]-y-1)/t);Math.floor((a[d]-1)/t)<E&&l.push(""),ol(l,m,t);continue}if(w+a[d]>t&&w>0&&a[d]>0){if(r.wordWrap===false&&w<t){ol(l,m,t);continue}l.push("");}if(w+a[d]>t&&r.wordWrap===false){ol(l,m,t);continue}l[l.length-1]+=m;}r.trim!==false&&(l=l.map(d=>Px(d)));let c=l.join(`
126
- `),p=c[Symbol.iterator](),u=p.next(),f=p.next(),h=0;for(;!u.done;){let d=u.value,m=f.value;if(n+=d,d===ti||d===_m){wm.lastIndex=h+1;let y=wm.exec(c)?.groups;if(y?.code!==void 0){let E=Number.parseFloat(y.code);s=E===Ax?void 0:E;}else y?.uri!==void 0&&(i=y.uri.length===0?void 0:y.uri);}let w=s?Rx(s):void 0;m===`
127
- `?(i&&(n+=Sm("")),s&&w&&(n+=bm(w))):d===`
128
- `&&(s&&w&&(n+=bm(s)),i&&(n+=Sm(i))),h+=d.length,u=f,f=p.next();}return n};Nx=["up","down","left","right","space","enter","cancel"],Ne={actions:new Set(Nx),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:true};Lx=globalThis.process.platform.startsWith("win"),cl=Symbol("clack:cancel");ri=e=>"columns"in e&&typeof e.columns=="number"?e.columns:80,dl=e=>"rows"in e&&typeof e.rows=="number"?e.rows:20;gr=class{input;output;_abortSignal;rl;opts;_render;_track=false;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(t,r=true){let{input:n=stdin,output:s=stdout,render:i,signal:o,...a}=t;this.opts=a,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=r,this._abortSignal=o,this.input=n,this.output=s;}unsubscribe(){this._subscribers.clear();}setSubscriber(t,r){let n=this._subscribers.get(t)??[];n.push(r),this._subscribers.set(t,n);}on(t,r){this.setSubscriber(t,{cb:r});}once(t,r){this.setSubscriber(t,{cb:r,once:true});}emit(t,...r){let n=this._subscribers.get(t)??[],s=[];for(let i of n)i.cb(...r),i.once&&s.push(()=>n.splice(n.indexOf(i),1));for(let i of s)i();}prompt(){return new Promise(t=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),t(cl);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close();},{once:true});}this.rl=_t__default.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:true}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,true),this.input.on("keypress",this.onKeypress),Xs(this.input,true),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(ve.cursor.show),this.output.off("resize",this.render),Xs(this.input,false),t(this.value);}),this.once("cancel",()=>{this.output.write(ve.cursor.show),this.output.off("resize",this.render),Xs(this.input,false),t(cl);});})}_isActionKey(t,r){return t===" "}_setValue(t){this.value=t,this.emit("value",this.value);}_setUserInput(t,r){this.userInput=t??"",this.emit("userInput",this.userInput),r&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor);}_clearUserInput(){this.rl?.write(null,{ctrl:true,name:"u"}),this._setUserInput("");}onKeypress(t,r){if(this._track&&r.name!=="return"&&(r.name&&this._isActionKey(t,r)&&this.rl?.write(null,{ctrl:true,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),r?.name&&(!this._track&&Ne.aliases.has(r.name)&&this.emit("cursor",Ne.aliases.get(r.name)),Ne.actions.has(r.name)&&this.emit("cursor",r.name)),t&&(t.toLowerCase()==="y"||t.toLowerCase()==="n")&&this.emit("confirm",t.toLowerCase()==="y"),this.emit("key",t?.toLowerCase(),r),r?.name==="return"){if(this.opts.validate){let n=this.opts.validate(this.value);n&&(this.error=n instanceof Error?n.message:n,this.state="error",this.rl?.write(this.userInput));}this.state!=="error"&&(this.state="submit");}ml([t,r?.name,r?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close();}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
129
- `),Xs(this.input,false),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe();}restoreCursor(){let t=ll(this._prevFrame,process.stdout.columns,{hard:true,trim:false}).split(`
130
- `).length-1;this.output.write(ve.cursor.move(-999,t*-1));}render(){let t=ll(this._render(this)??"",process.stdout.columns,{hard:true,trim:false});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(ve.cursor.hide);else {let r=Ix(this._prevFrame,t),n=dl(this.output);if(this.restoreCursor(),r){let s=Math.max(0,r.numLinesAfter-n),i=Math.max(0,r.numLinesBefore-n),o=r.lines.find(a=>a>=s);if(o===void 0){this._prevFrame=t;return}if(r.lines.length===1){this.output.write(ve.cursor.move(0,o-i)),this.output.write(ve.erase.lines(1));let a=t.split(`
127
+ `)}var ve,$x,vx,Tx,ol,Vs,Ks,al,Xs,Ax,Cx,$m,Rx,_n,ri,vm,kx,ml,Tm,Px,Am,dl,Sm,Ox,Em,xm,Nx,ll,Ix,Lx,Dx,Ne,Fx,pl,ni,gl,gr,Qs,Zs,ei,ti,yl=g(()=>{ve=te(il());$x=e=>e===161||e===164||e===167||e===168||e===170||e===173||e===174||e>=176&&e<=180||e>=182&&e<=186||e>=188&&e<=191||e===198||e===208||e===215||e===216||e>=222&&e<=225||e===230||e>=232&&e<=234||e===236||e===237||e===240||e===242||e===243||e>=247&&e<=250||e===252||e===254||e===257||e===273||e===275||e===283||e===294||e===295||e===299||e>=305&&e<=307||e===312||e>=319&&e<=322||e===324||e>=328&&e<=331||e===333||e===338||e===339||e===358||e===359||e===363||e===462||e===464||e===466||e===468||e===470||e===472||e===474||e===476||e===593||e===609||e===708||e===711||e>=713&&e<=715||e===717||e===720||e>=728&&e<=731||e===733||e===735||e>=768&&e<=879||e>=913&&e<=929||e>=931&&e<=937||e>=945&&e<=961||e>=963&&e<=969||e===1025||e>=1040&&e<=1103||e===1105||e===8208||e>=8211&&e<=8214||e===8216||e===8217||e===8220||e===8221||e>=8224&&e<=8226||e>=8228&&e<=8231||e===8240||e===8242||e===8243||e===8245||e===8251||e===8254||e===8308||e===8319||e>=8321&&e<=8324||e===8364||e===8451||e===8453||e===8457||e===8467||e===8470||e===8481||e===8482||e===8486||e===8491||e===8531||e===8532||e>=8539&&e<=8542||e>=8544&&e<=8555||e>=8560&&e<=8569||e===8585||e>=8592&&e<=8601||e===8632||e===8633||e===8658||e===8660||e===8679||e===8704||e===8706||e===8707||e===8711||e===8712||e===8715||e===8719||e===8721||e===8725||e===8730||e>=8733&&e<=8736||e===8739||e===8741||e>=8743&&e<=8748||e===8750||e>=8756&&e<=8759||e===8764||e===8765||e===8776||e===8780||e===8786||e===8800||e===8801||e>=8804&&e<=8807||e===8810||e===8811||e===8814||e===8815||e===8834||e===8835||e===8838||e===8839||e===8853||e===8857||e===8869||e===8895||e===8978||e>=9312&&e<=9449||e>=9451&&e<=9547||e>=9552&&e<=9587||e>=9600&&e<=9615||e>=9618&&e<=9621||e===9632||e===9633||e>=9635&&e<=9641||e===9650||e===9651||e===9654||e===9655||e===9660||e===9661||e===9664||e===9665||e>=9670&&e<=9672||e===9675||e>=9678&&e<=9681||e>=9698&&e<=9701||e===9711||e===9733||e===9734||e===9737||e===9742||e===9743||e===9756||e===9758||e===9792||e===9794||e===9824||e===9825||e>=9827&&e<=9829||e>=9831&&e<=9834||e===9836||e===9837||e===9839||e===9886||e===9887||e===9919||e>=9926&&e<=9933||e>=9935&&e<=9939||e>=9941&&e<=9953||e===9955||e===9960||e===9961||e>=9963&&e<=9969||e===9972||e>=9974&&e<=9977||e===9979||e===9980||e===9982||e===9983||e===10045||e>=10102&&e<=10111||e>=11094&&e<=11097||e>=12872&&e<=12879||e>=57344&&e<=63743||e>=65024&&e<=65039||e===65533||e>=127232&&e<=127242||e>=127248&&e<=127277||e>=127280&&e<=127337||e>=127344&&e<=127373||e===127375||e===127376||e>=127387&&e<=127404||e>=917760&&e<=917999||e>=983040&&e<=1048573||e>=1048576&&e<=1114109,vx=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Tx=e=>e>=4352&&e<=4447||e===8986||e===8987||e===9001||e===9002||e>=9193&&e<=9196||e===9200||e===9203||e===9725||e===9726||e===9748||e===9749||e>=9800&&e<=9811||e===9855||e===9875||e===9889||e===9898||e===9899||e===9917||e===9918||e===9924||e===9925||e===9934||e===9940||e===9962||e===9970||e===9971||e===9973||e===9978||e===9981||e===9989||e===9994||e===9995||e===10024||e===10060||e===10062||e>=10067&&e<=10069||e===10071||e>=10133&&e<=10135||e===10160||e===10175||e===11035||e===11036||e===11088||e===11093||e>=11904&&e<=11929||e>=11931&&e<=12019||e>=12032&&e<=12245||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12353&&e<=12438||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=19968&&e<=42124||e>=42128&&e<=42182||e>=43360&&e<=43388||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=94176&&e<=94180||e===94192||e===94193||e>=94208&&e<=100343||e>=100352&&e<=101589||e>=101632&&e<=101640||e>=110576&&e<=110579||e>=110581&&e<=110587||e===110589||e===110590||e>=110592&&e<=110882||e===110898||e>=110928&&e<=110930||e===110933||e>=110948&&e<=110951||e>=110960&&e<=111355||e===126980||e===127183||e===127374||e>=127377&&e<=127386||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e===127568||e===127569||e>=127584&&e<=127589||e>=127744&&e<=127776||e>=127789&&e<=127797||e>=127799&&e<=127868||e>=127870&&e<=127891||e>=127904&&e<=127946||e>=127951&&e<=127955||e>=127968&&e<=127984||e===127988||e>=127992&&e<=128062||e===128064||e>=128066&&e<=128252||e>=128255&&e<=128317||e>=128331&&e<=128334||e>=128336&&e<=128359||e===128378||e===128405||e===128406||e===128420||e>=128507&&e<=128591||e>=128640&&e<=128709||e===128716||e>=128720&&e<=128722||e>=128725&&e<=128727||e>=128732&&e<=128735||e===128747||e===128748||e>=128756&&e<=128764||e>=128992&&e<=129003||e===129008||e>=129292&&e<=129338||e>=129340&&e<=129349||e>=129351&&e<=129535||e>=129648&&e<=129660||e>=129664&&e<=129672||e>=129680&&e<=129725||e>=129727&&e<=129733||e>=129742&&e<=129755||e>=129760&&e<=129768||e>=129776&&e<=129784||e>=131072&&e<=196605||e>=196608&&e<=262141,ol=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,Vs=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Ks=/\t{1,1000}/y,al=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,Xs=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Ax=/\p{M}+/gu,Cx={limit:1/0,ellipsis:""},$m=(e,t={},r={})=>{let n=t.limit??1/0,s=t.ellipsis??"",i=t?.ellipsisWidth??(s?$m(s,Cx,r).width:0),o=r.ansiWidth??0,a=r.controlWidth??0,l=r.tabWidth??8,c=r.ambiguousWidth??1,p=r.emojiWidth??2,u=r.fullWidthWidth??2,f=r.regularWidth??1,h=r.wideWidth??2,d=0,m=0,w=e.length,y=0,E=false,T=w,v=Math.max(0,n-i),C=0,A=0,$=0,_=0;e:for(;;){if(A>C||m>=w&&m>d){let I=e.slice(C,A)||e.slice(d,m);y=0;for(let b of I.replaceAll(Ax,"")){let D=b.codePointAt(0)||0;if(vx(D)?_=u:Tx(D)?_=h:c!==f&&$x(D)?_=c:_=f,$+_>v&&(T=Math.min(T,Math.max(C,d)+y)),$+_>n){E=true;break e}y+=b.length,$+=_;}C=A=0;}if(m>=w)break;if(Xs.lastIndex=m,Xs.test(e)){if(y=Xs.lastIndex-m,_=y*f,$+_>v&&(T=Math.min(T,m+Math.floor((v-$)/f))),$+_>n){E=true;break}$+=_,C=d,A=m,m=d=Xs.lastIndex;continue}if(ol.lastIndex=m,ol.test(e)){if($+o>v&&(T=Math.min(T,m)),$+o>n){E=true;break}$+=o,C=d,A=m,m=d=ol.lastIndex;continue}if(Vs.lastIndex=m,Vs.test(e)){if(y=Vs.lastIndex-m,_=y*a,$+_>v&&(T=Math.min(T,m+Math.floor((v-$)/a))),$+_>n){E=true;break}$+=_,C=d,A=m,m=d=Vs.lastIndex;continue}if(Ks.lastIndex=m,Ks.test(e)){if(y=Ks.lastIndex-m,_=y*l,$+_>v&&(T=Math.min(T,m+Math.floor((v-$)/l))),$+_>n){E=true;break}$+=_,C=d,A=m,m=d=Ks.lastIndex;continue}if(al.lastIndex=m,al.test(e)){if($+p>v&&(T=Math.min(T,m)),$+p>n){E=true;break}$+=p,C=d,A=m,m=d=al.lastIndex;continue}m+=1;}return {width:E?v:$,index:E?T:w,truncated:E,ellipsed:E&&n>=i}},Rx={limit:1/0,ellipsis:"",ellipsisWidth:0},_n=(e,t={})=>$m(e,Rx,t).width,ri="\x1B",vm="\x9B",kx=39,ml="\x07",Tm="[",Px="]",Am="m",dl=`${Px}8;;`,Sm=new RegExp(`(?:\\${Tm}(?<code>\\d+)m|\\${dl}(?<uri>.*)${ml})`,"y"),Ox=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},Em=e=>`${ri}${Tm}${e}${Am}`,xm=e=>`${ri}${dl}${e}${ml}`,Nx=e=>e.map(t=>_n(t)),ll=(e,t,r)=>{let n=t[Symbol.iterator](),s=false,i=false,o=e.at(-1),a=o===void 0?0:_n(o),l=n.next(),c=n.next(),p=0;for(;!l.done;){let u=l.value,f=_n(u);a+f<=r?e[e.length-1]+=u:(e.push(u),a=0),(u===ri||u===vm)&&(s=true,i=t.startsWith(dl,p+1)),s?i?u===ml&&(s=false,i=false):u===Am&&(s=false):(a+=f,a===r&&!c.done&&(e.push(""),a=0)),l=c,c=n.next(),p+=u.length;}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop());},Ix=e=>{let t=e.split(" "),r=t.length;for(;r>0&&!(_n(t[r-1])>0);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")},Lx=(e,t,r={})=>{if(r.trim!==false&&e.trim()==="")return "";let n="",s,i,o=e.split(" "),a=Nx(o),l=[""];for(let[d,m]of o.entries()){r.trim!==false&&(l[l.length-1]=(l.at(-1)??"").trimStart());let w=_n(l.at(-1)??"");if(d!==0&&(w>=t&&(r.wordWrap===false||r.trim===false)&&(l.push(""),w=0),(w>0||r.trim===false)&&(l[l.length-1]+=" ",w++)),r.hard&&a[d]>t){let y=t-w,E=1+Math.floor((a[d]-y-1)/t);Math.floor((a[d]-1)/t)<E&&l.push(""),ll(l,m,t);continue}if(w+a[d]>t&&w>0&&a[d]>0){if(r.wordWrap===false&&w<t){ll(l,m,t);continue}l.push("");}if(w+a[d]>t&&r.wordWrap===false){ll(l,m,t);continue}l[l.length-1]+=m;}r.trim!==false&&(l=l.map(d=>Ix(d)));let c=l.join(`
128
+ `),p=c[Symbol.iterator](),u=p.next(),f=p.next(),h=0;for(;!u.done;){let d=u.value,m=f.value;if(n+=d,d===ri||d===vm){Sm.lastIndex=h+1;let y=Sm.exec(c)?.groups;if(y?.code!==void 0){let E=Number.parseFloat(y.code);s=E===kx?void 0:E;}else y?.uri!==void 0&&(i=y.uri.length===0?void 0:y.uri);}let w=s?Ox(s):void 0;m===`
129
+ `?(i&&(n+=xm("")),s&&w&&(n+=Em(w))):d===`
130
+ `&&(s&&w&&(n+=Em(s)),i&&(n+=xm(i))),h+=d.length,u=f,f=p.next();}return n};Dx=["up","down","left","right","space","enter","cancel"],Ne={actions:new Set(Dx),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:true};Fx=globalThis.process.platform.startsWith("win"),pl=Symbol("clack:cancel");ni=e=>"columns"in e&&typeof e.columns=="number"?e.columns:80,gl=e=>"rows"in e&&typeof e.rows=="number"?e.rows:20;gr=class{input;output;_abortSignal;rl;opts;_render;_track=false;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(t,r=true){let{input:n=stdin,output:s=stdout,render:i,signal:o,...a}=t;this.opts=a,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=r,this._abortSignal=o,this.input=n,this.output=s;}unsubscribe(){this._subscribers.clear();}setSubscriber(t,r){let n=this._subscribers.get(t)??[];n.push(r),this._subscribers.set(t,n);}on(t,r){this.setSubscriber(t,{cb:r});}once(t,r){this.setSubscriber(t,{cb:r,once:true});}emit(t,...r){let n=this._subscribers.get(t)??[],s=[];for(let i of n)i.cb(...r),i.once&&s.push(()=>n.splice(n.indexOf(i),1));for(let i of s)i();}prompt(){return new Promise(t=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),t(pl);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close();},{once:true});}this.rl=_t__default.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:true}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,true),this.input.on("keypress",this.onKeypress),Js(this.input,true),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(ve.cursor.show),this.output.off("resize",this.render),Js(this.input,false),t(this.value);}),this.once("cancel",()=>{this.output.write(ve.cursor.show),this.output.off("resize",this.render),Js(this.input,false),t(pl);});})}_isActionKey(t,r){return t===" "}_setValue(t){this.value=t,this.emit("value",this.value);}_setUserInput(t,r){this.userInput=t??"",this.emit("userInput",this.userInput),r&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor);}_clearUserInput(){this.rl?.write(null,{ctrl:true,name:"u"}),this._setUserInput("");}onKeypress(t,r){if(this._track&&r.name!=="return"&&(r.name&&this._isActionKey(t,r)&&this.rl?.write(null,{ctrl:true,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),r?.name&&(!this._track&&Ne.aliases.has(r.name)&&this.emit("cursor",Ne.aliases.get(r.name)),Ne.actions.has(r.name)&&this.emit("cursor",r.name)),t&&(t.toLowerCase()==="y"||t.toLowerCase()==="n")&&this.emit("confirm",t.toLowerCase()==="y"),this.emit("key",t?.toLowerCase(),r),r?.name==="return"){if(this.opts.validate){let n=this.opts.validate(this.value);n&&(this.error=n instanceof Error?n.message:n,this.state="error",this.rl?.write(this.userInput));}this.state!=="error"&&(this.state="submit");}hl([t,r?.name,r?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close();}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
131
+ `),Js(this.input,false),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe();}restoreCursor(){let t=ul(this._prevFrame,process.stdout.columns,{hard:true,trim:false}).split(`
132
+ `).length-1;this.output.write(ve.cursor.move(-999,t*-1));}render(){let t=ul(this._render(this)??"",process.stdout.columns,{hard:true,trim:false});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(ve.cursor.hide);else {let r=jx(this._prevFrame,t),n=gl(this.output);if(this.restoreCursor(),r){let s=Math.max(0,r.numLinesAfter-n),i=Math.max(0,r.numLinesBefore-n),o=r.lines.find(a=>a>=s);if(o===void 0){this._prevFrame=t;return}if(r.lines.length===1){this.output.write(ve.cursor.move(0,o-i)),this.output.write(ve.erase.lines(1));let a=t.split(`
131
133
  `);this.output.write(a[o]),this._prevFrame=t,this.output.write(ve.cursor.move(0,a.length-o-1));return}else if(r.lines.length>1){if(s<i)o=s;else {let l=o-i;l>0&&this.output.write(ve.cursor.move(0,l));}this.output.write(ve.erase.down());let a=t.split(`
132
134
  `).slice(o);this.output.write(a.join(`
133
- `)),this._prevFrame=t;return}}this.output.write(ve.erase.down());}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t;}}},Ys=class extends gr{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t){super(t,false),this.value=!!t.initialValue,this.on("userInput",()=>{this.value=this._value;}),this.on("confirm",r=>{this.output.write(ve.cursor.move(0,-1)),this.value=r,this.state="submit",this.close();}),this.on("cursor",()=>{this.value=!this.value;});}},Qs=class extends gr{_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let t=this.userInput;if(this.cursor>=t.length)return `${this.masked}${styleText(["inverse","hidden"],"_")}`;let r=this.masked,n=r.slice(0,this.cursor),s=r.slice(this.cursor);return `${n}${styleText("inverse",s[0])}${s.slice(1)}`}clear(){this._clearUserInput();}constructor({mask:t,...r}){super(r),this._mask=t??"\u2022",this.on("userInput",n=>{this._setValue(n);});}},Zs=class extends gr{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value;}constructor(t){super(t,false),this.options=t.options;let r=this.options.findIndex(({value:s})=>s===t.initialValue),n=r===-1?0:r;this.cursor=this.options[n].disabled?Js(n,1,this.options):n,this.changeValue(),this.on("cursor",s=>{switch(s){case "left":case "up":this.cursor=Js(this.cursor,-1,this.options);break;case "down":case "right":this.cursor=Js(this.cursor,1,this.options);break}this.changeValue();});}},ei=class extends gr{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return `${this.userInput}\u2588`;let r=t.slice(0,this.cursor),[n,...s]=t.slice(this.cursor);return `${r}${styleText("inverse",n)}${s.join("")}`}get cursor(){return this._cursor}constructor(t){super({...t,initialUserInput:t.initialUserInput??t.initialValue}),this.on("userInput",r=>{this._setValue(r);}),this.on("finalize",()=>{this.value||(this.value=t.defaultValue),this.value===void 0&&(this.value="");});}};});function Dx(){return Ge.platform!=="win32"?Ge.env.TERM!=="linux":!!Ge.env.CI||!!Ge.env.WT_SESSION||!!Ge.env.TERMINUS_SUBLIME||Ge.env.ConEmuTask==="{cmd::Cmder}"||Ge.env.TERM_PROGRAM==="Terminus-Sublime"||Ge.env.TERM_PROGRAM==="vscode"||Ge.env.TERM==="xterm-256color"||Ge.env.TERM==="alacritty"||Ge.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}function El(e,t,r){return String(e).normalize().replaceAll(`\r
135
+ `)),this._prevFrame=t;return}}this.output.write(ve.erase.down());}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t;}}},Qs=class extends gr{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t){super(t,false),this.value=!!t.initialValue,this.on("userInput",()=>{this.value=this._value;}),this.on("confirm",r=>{this.output.write(ve.cursor.move(0,-1)),this.value=r,this.state="submit",this.close();}),this.on("cursor",()=>{this.value=!this.value;});}},Zs=class extends gr{_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let t=this.userInput;if(this.cursor>=t.length)return `${this.masked}${styleText(["inverse","hidden"],"_")}`;let r=this.masked,n=r.slice(0,this.cursor),s=r.slice(this.cursor);return `${n}${styleText("inverse",s[0])}${s.slice(1)}`}clear(){this._clearUserInput();}constructor({mask:t,...r}){super(r),this._mask=t??"\u2022",this.on("userInput",n=>{this._setValue(n);});}},ei=class extends gr{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value;}constructor(t){super(t,false),this.options=t.options;let r=this.options.findIndex(({value:s})=>s===t.initialValue),n=r===-1?0:r;this.cursor=this.options[n].disabled?Ys(n,1,this.options):n,this.changeValue(),this.on("cursor",s=>{switch(s){case "left":case "up":this.cursor=Ys(this.cursor,-1,this.options);break;case "down":case "right":this.cursor=Ys(this.cursor,1,this.options);break}this.changeValue();});}},ti=class extends gr{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return `${this.userInput}\u2588`;let r=t.slice(0,this.cursor),[n,...s]=t.slice(this.cursor);return `${r}${styleText("inverse",n)}${s.join("")}`}get cursor(){return this._cursor}constructor(t){super({...t,initialUserInput:t.initialUserInput??t.initialValue}),this.on("userInput",r=>{this._setValue(r);}),this.on("finalize",()=>{this.value||(this.value=t.defaultValue),this.value===void 0&&(this.value="");});}};});function Mx(){return Ge.platform!=="win32"?Ge.env.TERM!=="linux":!!Ge.env.CI||!!Ge.env.WT_SESSION||!!Ge.env.TERMINUS_SUBLIME||Ge.env.ConEmuTask==="{cmd::Cmder}"||Ge.env.TERM_PROGRAM==="Terminus-Sublime"||Ge.env.TERM_PROGRAM==="vscode"||Ge.env.TERM==="xterm-256color"||Ge.env.TERM==="alacritty"||Ge.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}function _l(e,t,r){return String(e).normalize().replaceAll(`\r
134
136
  `,`
135
137
  `).split(`
136
- `).map(n=>r0(n,t,r)).join(`
137
- `)}var _n,bl,jx,X,Fx,km,Pm,xl,V,yr,Sl,li,Mx,Ux,Bx,qx,Hx,ci,Wx,Gx,zx,Vx,gl,si,ii,yl,oi,Kx,Xx,Om,Jx,$n,ui,Nm,Yx,_l,Im,Qx,Lm,$l,Am,Zx,Cm,Rm,e0,wl,t0,r0,n0,s0,vn,K,Tn,i0,vl,ai,An,Cn,Qe=g(()=>{hl();hl();_n=te(nl());bl=Dx(),jx=()=>process.env.CI==="true",X=(e,t)=>bl?e:t,Fx=X("\u25C6","*"),km=X("\u25A0","x"),Pm=X("\u25B2","x"),xl=X("\u25C7","o"),X("\u250C","T"),V=X("\u2502","|"),yr=X("\u2514","\u2014"),X("\u2510","T"),X("\u2518","\u2014"),Sl=X("\u25CF",">"),li=X("\u25CB"," "),X("\u25FB","[\u2022]"),X("\u25FC","[+]"),X("\u25FB","[ ]"),Mx=X("\u25AA","\u2022"),X("\u2500","-"),X("\u256E","+"),X("\u251C","+"),X("\u256F","+"),X("\u2570","+"),X("\u256D","+"),Ux=X("\u25CF","\u2022"),Bx=X("\u25C6","*"),qx=X("\u25B2","!"),Hx=X("\u25A0","x"),ci=e=>{switch(e){case "initial":case "active":return styleText("cyan",Fx);case "cancel":return styleText("red",km);case "error":return styleText("yellow",Pm);case "submit":return styleText("green",xl)}},Wx=e=>{switch(e){case "initial":case "active":return styleText("cyan",V);case "cancel":return styleText("red",V);case "error":return styleText("yellow",V);case "submit":return styleText("green",V)}},Gx=e=>e===161||e===164||e===167||e===168||e===170||e===173||e===174||e>=176&&e<=180||e>=182&&e<=186||e>=188&&e<=191||e===198||e===208||e===215||e===216||e>=222&&e<=225||e===230||e>=232&&e<=234||e===236||e===237||e===240||e===242||e===243||e>=247&&e<=250||e===252||e===254||e===257||e===273||e===275||e===283||e===294||e===295||e===299||e>=305&&e<=307||e===312||e>=319&&e<=322||e===324||e>=328&&e<=331||e===333||e===338||e===339||e===358||e===359||e===363||e===462||e===464||e===466||e===468||e===470||e===472||e===474||e===476||e===593||e===609||e===708||e===711||e>=713&&e<=715||e===717||e===720||e>=728&&e<=731||e===733||e===735||e>=768&&e<=879||e>=913&&e<=929||e>=931&&e<=937||e>=945&&e<=961||e>=963&&e<=969||e===1025||e>=1040&&e<=1103||e===1105||e===8208||e>=8211&&e<=8214||e===8216||e===8217||e===8220||e===8221||e>=8224&&e<=8226||e>=8228&&e<=8231||e===8240||e===8242||e===8243||e===8245||e===8251||e===8254||e===8308||e===8319||e>=8321&&e<=8324||e===8364||e===8451||e===8453||e===8457||e===8467||e===8470||e===8481||e===8482||e===8486||e===8491||e===8531||e===8532||e>=8539&&e<=8542||e>=8544&&e<=8555||e>=8560&&e<=8569||e===8585||e>=8592&&e<=8601||e===8632||e===8633||e===8658||e===8660||e===8679||e===8704||e===8706||e===8707||e===8711||e===8712||e===8715||e===8719||e===8721||e===8725||e===8730||e>=8733&&e<=8736||e===8739||e===8741||e>=8743&&e<=8748||e===8750||e>=8756&&e<=8759||e===8764||e===8765||e===8776||e===8780||e===8786||e===8800||e===8801||e>=8804&&e<=8807||e===8810||e===8811||e===8814||e===8815||e===8834||e===8835||e===8838||e===8839||e===8853||e===8857||e===8869||e===8895||e===8978||e>=9312&&e<=9449||e>=9451&&e<=9547||e>=9552&&e<=9587||e>=9600&&e<=9615||e>=9618&&e<=9621||e===9632||e===9633||e>=9635&&e<=9641||e===9650||e===9651||e===9654||e===9655||e===9660||e===9661||e===9664||e===9665||e>=9670&&e<=9672||e===9675||e>=9678&&e<=9681||e>=9698&&e<=9701||e===9711||e===9733||e===9734||e===9737||e===9742||e===9743||e===9756||e===9758||e===9792||e===9794||e===9824||e===9825||e>=9827&&e<=9829||e>=9831&&e<=9834||e===9836||e===9837||e===9839||e===9886||e===9887||e===9919||e>=9926&&e<=9933||e>=9935&&e<=9939||e>=9941&&e<=9953||e===9955||e===9960||e===9961||e>=9963&&e<=9969||e===9972||e>=9974&&e<=9977||e===9979||e===9980||e===9982||e===9983||e===10045||e>=10102&&e<=10111||e>=11094&&e<=11097||e>=12872&&e<=12879||e>=57344&&e<=63743||e>=65024&&e<=65039||e===65533||e>=127232&&e<=127242||e>=127248&&e<=127277||e>=127280&&e<=127337||e>=127344&&e<=127373||e===127375||e===127376||e>=127387&&e<=127404||e>=917760&&e<=917999||e>=983040&&e<=1048573||e>=1048576&&e<=1114109,zx=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Vx=e=>e>=4352&&e<=4447||e===8986||e===8987||e===9001||e===9002||e>=9193&&e<=9196||e===9200||e===9203||e===9725||e===9726||e===9748||e===9749||e>=9800&&e<=9811||e===9855||e===9875||e===9889||e===9898||e===9899||e===9917||e===9918||e===9924||e===9925||e===9934||e===9940||e===9962||e===9970||e===9971||e===9973||e===9978||e===9981||e===9989||e===9994||e===9995||e===10024||e===10060||e===10062||e>=10067&&e<=10069||e===10071||e>=10133&&e<=10135||e===10160||e===10175||e===11035||e===11036||e===11088||e===11093||e>=11904&&e<=11929||e>=11931&&e<=12019||e>=12032&&e<=12245||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12353&&e<=12438||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=19968&&e<=42124||e>=42128&&e<=42182||e>=43360&&e<=43388||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=94176&&e<=94180||e===94192||e===94193||e>=94208&&e<=100343||e>=100352&&e<=101589||e>=101632&&e<=101640||e>=110576&&e<=110579||e>=110581&&e<=110587||e===110589||e===110590||e>=110592&&e<=110882||e===110898||e>=110928&&e<=110930||e===110933||e>=110948&&e<=110951||e>=110960&&e<=111355||e===126980||e===127183||e===127374||e>=127377&&e<=127386||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e===127568||e===127569||e>=127584&&e<=127589||e>=127744&&e<=127776||e>=127789&&e<=127797||e>=127799&&e<=127868||e>=127870&&e<=127891||e>=127904&&e<=127946||e>=127951&&e<=127955||e>=127968&&e<=127984||e===127988||e>=127992&&e<=128062||e===128064||e>=128066&&e<=128252||e>=128255&&e<=128317||e>=128331&&e<=128334||e>=128336&&e<=128359||e===128378||e===128405||e===128406||e===128420||e>=128507&&e<=128591||e>=128640&&e<=128709||e===128716||e>=128720&&e<=128722||e>=128725&&e<=128727||e>=128732&&e<=128735||e===128747||e===128748||e>=128756&&e<=128764||e>=128992&&e<=129003||e===129008||e>=129292&&e<=129338||e>=129340&&e<=129349||e>=129351&&e<=129535||e>=129648&&e<=129660||e>=129664&&e<=129672||e>=129680&&e<=129725||e>=129727&&e<=129733||e>=129742&&e<=129755||e>=129760&&e<=129768||e>=129776&&e<=129784||e>=131072&&e<=196605||e>=196608&&e<=262141,gl=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,si=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,ii=/\t{1,1000}/y,yl=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,oi=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Kx=/\p{M}+/gu,Xx={limit:1/0,ellipsis:""},Om=(e,t={},r={})=>{let n=t.limit??1/0,s=t.ellipsis??"",i=t?.ellipsisWidth??(s?Om(s,Xx,r).width:0),o=r.ansiWidth??0,a=r.controlWidth??0,l=r.tabWidth??8,c=r.ambiguousWidth??1,p=r.emojiWidth??2,u=r.fullWidthWidth??2,f=r.regularWidth??1,h=r.wideWidth??2,d=0,m=0,w=e.length,y=0,E=false,T=w,v=Math.max(0,n-i),C=0,A=0,$=0,_=0;e:for(;;){if(A>C||m>=w&&m>d){let I=e.slice(C,A)||e.slice(d,m);y=0;for(let b of I.replaceAll(Kx,"")){let D=b.codePointAt(0)||0;if(zx(D)?_=u:Vx(D)?_=h:c!==f&&Gx(D)?_=c:_=f,$+_>v&&(T=Math.min(T,Math.max(C,d)+y)),$+_>n){E=true;break e}y+=b.length,$+=_;}C=A=0;}if(m>=w)break;if(oi.lastIndex=m,oi.test(e)){if(y=oi.lastIndex-m,_=y*f,$+_>v&&(T=Math.min(T,m+Math.floor((v-$)/f))),$+_>n){E=true;break}$+=_,C=d,A=m,m=d=oi.lastIndex;continue}if(gl.lastIndex=m,gl.test(e)){if($+o>v&&(T=Math.min(T,m)),$+o>n){E=true;break}$+=o,C=d,A=m,m=d=gl.lastIndex;continue}if(si.lastIndex=m,si.test(e)){if(y=si.lastIndex-m,_=y*a,$+_>v&&(T=Math.min(T,m+Math.floor((v-$)/a))),$+_>n){E=true;break}$+=_,C=d,A=m,m=d=si.lastIndex;continue}if(ii.lastIndex=m,ii.test(e)){if(y=ii.lastIndex-m,_=y*l,$+_>v&&(T=Math.min(T,m+Math.floor((v-$)/l))),$+_>n){E=true;break}$+=_,C=d,A=m,m=d=ii.lastIndex;continue}if(yl.lastIndex=m,yl.test(e)){if($+p>v&&(T=Math.min(T,m)),$+p>n){E=true;break}$+=p,C=d,A=m,m=d=yl.lastIndex;continue}m+=1;}return {width:E?v:$,index:E?T:w,truncated:E,ellipsed:E&&n>=i}},Jx={limit:1/0,ellipsis:"",ellipsisWidth:0},$n=(e,t={})=>Om(e,Jx,t).width,ui="\x1B",Nm="\x9B",Yx=39,_l="\x07",Im="[",Qx="]",Lm="m",$l=`${Qx}8;;`,Am=new RegExp(`(?:\\${Im}(?<code>\\d+)m|\\${$l}(?<uri>.*)${_l})`,"y"),Zx=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},Cm=e=>`${ui}${Im}${e}${Lm}`,Rm=e=>`${ui}${$l}${e}${_l}`,e0=e=>e.map(t=>$n(t)),wl=(e,t,r)=>{let n=t[Symbol.iterator](),s=false,i=false,o=e.at(-1),a=o===void 0?0:$n(o),l=n.next(),c=n.next(),p=0;for(;!l.done;){let u=l.value,f=$n(u);a+f<=r?e[e.length-1]+=u:(e.push(u),a=0),(u===ui||u===Nm)&&(s=true,i=t.startsWith($l,p+1)),s?i?u===_l&&(s=false,i=false):u===Lm&&(s=false):(a+=f,a===r&&!c.done&&(e.push(""),a=0)),l=c,c=n.next(),p+=u.length;}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop());},t0=e=>{let t=e.split(" "),r=t.length;for(;r>0&&!($n(t[r-1])>0);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")},r0=(e,t,r={})=>{if(r.trim!==false&&e.trim()==="")return "";let n="",s,i,o=e.split(" "),a=e0(o),l=[""];for(let[d,m]of o.entries()){r.trim!==false&&(l[l.length-1]=(l.at(-1)??"").trimStart());let w=$n(l.at(-1)??"");if(d!==0&&(w>=t&&(r.wordWrap===false||r.trim===false)&&(l.push(""),w=0),(w>0||r.trim===false)&&(l[l.length-1]+=" ",w++)),r.hard&&a[d]>t){let y=t-w,E=1+Math.floor((a[d]-y-1)/t);Math.floor((a[d]-1)/t)<E&&l.push(""),wl(l,m,t);continue}if(w+a[d]>t&&w>0&&a[d]>0){if(r.wordWrap===false&&w<t){wl(l,m,t);continue}l.push("");}if(w+a[d]>t&&r.wordWrap===false){wl(l,m,t);continue}l[l.length-1]+=m;}r.trim!==false&&(l=l.map(d=>t0(d)));let c=l.join(`
138
- `),p=c[Symbol.iterator](),u=p.next(),f=p.next(),h=0;for(;!u.done;){let d=u.value,m=f.value;if(n+=d,d===ui||d===Nm){Am.lastIndex=h+1;let y=Am.exec(c)?.groups;if(y?.code!==void 0){let E=Number.parseFloat(y.code);s=E===Yx?void 0:E;}else y?.uri!==void 0&&(i=y.uri.length===0?void 0:y.uri);}let w=s?Zx(s):void 0;m===`
139
- `?(i&&(n+=Rm("")),s&&w&&(n+=Cm(w))):d===`
140
- `&&(s&&w&&(n+=Cm(s)),i&&(n+=Rm(i))),h+=d.length,u=f,f=p.next();}return n};n0=(e,t,r,n,s)=>{let i=t,o=0;for(let a=r;a<n;a++){let l=e[a];if(i=i-l.length,o++,i<=s)break}return {lineCount:i,removals:o}},s0=({cursor:e,options:t,style:r,output:n=process.stdout,maxItems:s=Number.POSITIVE_INFINITY,columnPadding:i=0,rowPadding:o=4})=>{let a=ri(n)-i,l=dl(n),c=styleText("dim","..."),p=Math.max(l-o,0),u=Math.max(Math.min(s,p),5),f=0;e>=u-3&&(f=Math.max(Math.min(e-u+3,t.length-u),0));let h=u<t.length&&f>0,d=u<t.length&&f+u<t.length,m=Math.min(f+u,t.length),w=[],y=0;h&&y++,d&&y++;let E=f+(h?1:0),T=m-(d?1:0);for(let C=E;C<T;C++){let A=El(r(t[C],C===e),a,{hard:true,trim:false}).split(`
141
- `);w.push(A),y+=A.length;}if(y>p){let C=0,A=0,$=y,_=e-E,I=(b,D)=>n0(w,$,b,D,p);h?({lineCount:$,removals:C}=I(0,_),$>p&&({lineCount:$,removals:A}=I(_+1,w.length))):({lineCount:$,removals:A}=I(_+1,w.length),$>p&&({lineCount:$,removals:C}=I(0,_))),C>0&&(h=true,w.splice(0,C)),A>0&&(d=true,w.splice(w.length-A,A));}let v=[];h&&v.push(c);for(let C of w)for(let A of C)v.push(A);return d&&v.push(c),v},vn=e=>{let t=e.active??"Yes",r=e.inactive??"No";return new Ys({active:t,inactive:r,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??true,render(){let n=e.withGuide??Ne.withGuide,s=`${n?`${styleText("gray",V)}
142
- `:""}${ci(this.state)} ${e.message}
138
+ `).map(n=>i0(n,t,r)).join(`
139
+ `)}var $n,El,Ux,X,Bx,Om,Nm,$l,V,yr,xl,ci,qx,Hx,Wx,Gx,zx,ui,Vx,Kx,Xx,Jx,wl,ii,oi,bl,ai,Yx,Qx,Im,Zx,vn,pi,Lm,e0,vl,Dm,t0,jm,Tl,Rm,r0,km,Pm,n0,Sl,s0,i0,o0,a0,Tn,K,An,l0,Al,li,Cn,Rn,Qe=g(()=>{yl();yl();$n=te(il());El=Mx(),Ux=()=>process.env.CI==="true",X=(e,t)=>El?e:t,Bx=X("\u25C6","*"),Om=X("\u25A0","x"),Nm=X("\u25B2","x"),$l=X("\u25C7","o"),X("\u250C","T"),V=X("\u2502","|"),yr=X("\u2514","\u2014"),X("\u2510","T"),X("\u2518","\u2014"),xl=X("\u25CF",">"),ci=X("\u25CB"," "),X("\u25FB","[\u2022]"),X("\u25FC","[+]"),X("\u25FB","[ ]"),qx=X("\u25AA","\u2022"),X("\u2500","-"),X("\u256E","+"),X("\u251C","+"),X("\u256F","+"),X("\u2570","+"),X("\u256D","+"),Hx=X("\u25CF","\u2022"),Wx=X("\u25C6","*"),Gx=X("\u25B2","!"),zx=X("\u25A0","x"),ui=e=>{switch(e){case "initial":case "active":return styleText("cyan",Bx);case "cancel":return styleText("red",Om);case "error":return styleText("yellow",Nm);case "submit":return styleText("green",$l)}},Vx=e=>{switch(e){case "initial":case "active":return styleText("cyan",V);case "cancel":return styleText("red",V);case "error":return styleText("yellow",V);case "submit":return styleText("green",V)}},Kx=e=>e===161||e===164||e===167||e===168||e===170||e===173||e===174||e>=176&&e<=180||e>=182&&e<=186||e>=188&&e<=191||e===198||e===208||e===215||e===216||e>=222&&e<=225||e===230||e>=232&&e<=234||e===236||e===237||e===240||e===242||e===243||e>=247&&e<=250||e===252||e===254||e===257||e===273||e===275||e===283||e===294||e===295||e===299||e>=305&&e<=307||e===312||e>=319&&e<=322||e===324||e>=328&&e<=331||e===333||e===338||e===339||e===358||e===359||e===363||e===462||e===464||e===466||e===468||e===470||e===472||e===474||e===476||e===593||e===609||e===708||e===711||e>=713&&e<=715||e===717||e===720||e>=728&&e<=731||e===733||e===735||e>=768&&e<=879||e>=913&&e<=929||e>=931&&e<=937||e>=945&&e<=961||e>=963&&e<=969||e===1025||e>=1040&&e<=1103||e===1105||e===8208||e>=8211&&e<=8214||e===8216||e===8217||e===8220||e===8221||e>=8224&&e<=8226||e>=8228&&e<=8231||e===8240||e===8242||e===8243||e===8245||e===8251||e===8254||e===8308||e===8319||e>=8321&&e<=8324||e===8364||e===8451||e===8453||e===8457||e===8467||e===8470||e===8481||e===8482||e===8486||e===8491||e===8531||e===8532||e>=8539&&e<=8542||e>=8544&&e<=8555||e>=8560&&e<=8569||e===8585||e>=8592&&e<=8601||e===8632||e===8633||e===8658||e===8660||e===8679||e===8704||e===8706||e===8707||e===8711||e===8712||e===8715||e===8719||e===8721||e===8725||e===8730||e>=8733&&e<=8736||e===8739||e===8741||e>=8743&&e<=8748||e===8750||e>=8756&&e<=8759||e===8764||e===8765||e===8776||e===8780||e===8786||e===8800||e===8801||e>=8804&&e<=8807||e===8810||e===8811||e===8814||e===8815||e===8834||e===8835||e===8838||e===8839||e===8853||e===8857||e===8869||e===8895||e===8978||e>=9312&&e<=9449||e>=9451&&e<=9547||e>=9552&&e<=9587||e>=9600&&e<=9615||e>=9618&&e<=9621||e===9632||e===9633||e>=9635&&e<=9641||e===9650||e===9651||e===9654||e===9655||e===9660||e===9661||e===9664||e===9665||e>=9670&&e<=9672||e===9675||e>=9678&&e<=9681||e>=9698&&e<=9701||e===9711||e===9733||e===9734||e===9737||e===9742||e===9743||e===9756||e===9758||e===9792||e===9794||e===9824||e===9825||e>=9827&&e<=9829||e>=9831&&e<=9834||e===9836||e===9837||e===9839||e===9886||e===9887||e===9919||e>=9926&&e<=9933||e>=9935&&e<=9939||e>=9941&&e<=9953||e===9955||e===9960||e===9961||e>=9963&&e<=9969||e===9972||e>=9974&&e<=9977||e===9979||e===9980||e===9982||e===9983||e===10045||e>=10102&&e<=10111||e>=11094&&e<=11097||e>=12872&&e<=12879||e>=57344&&e<=63743||e>=65024&&e<=65039||e===65533||e>=127232&&e<=127242||e>=127248&&e<=127277||e>=127280&&e<=127337||e>=127344&&e<=127373||e===127375||e===127376||e>=127387&&e<=127404||e>=917760&&e<=917999||e>=983040&&e<=1048573||e>=1048576&&e<=1114109,Xx=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Jx=e=>e>=4352&&e<=4447||e===8986||e===8987||e===9001||e===9002||e>=9193&&e<=9196||e===9200||e===9203||e===9725||e===9726||e===9748||e===9749||e>=9800&&e<=9811||e===9855||e===9875||e===9889||e===9898||e===9899||e===9917||e===9918||e===9924||e===9925||e===9934||e===9940||e===9962||e===9970||e===9971||e===9973||e===9978||e===9981||e===9989||e===9994||e===9995||e===10024||e===10060||e===10062||e>=10067&&e<=10069||e===10071||e>=10133&&e<=10135||e===10160||e===10175||e===11035||e===11036||e===11088||e===11093||e>=11904&&e<=11929||e>=11931&&e<=12019||e>=12032&&e<=12245||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12353&&e<=12438||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=19968&&e<=42124||e>=42128&&e<=42182||e>=43360&&e<=43388||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=94176&&e<=94180||e===94192||e===94193||e>=94208&&e<=100343||e>=100352&&e<=101589||e>=101632&&e<=101640||e>=110576&&e<=110579||e>=110581&&e<=110587||e===110589||e===110590||e>=110592&&e<=110882||e===110898||e>=110928&&e<=110930||e===110933||e>=110948&&e<=110951||e>=110960&&e<=111355||e===126980||e===127183||e===127374||e>=127377&&e<=127386||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e===127568||e===127569||e>=127584&&e<=127589||e>=127744&&e<=127776||e>=127789&&e<=127797||e>=127799&&e<=127868||e>=127870&&e<=127891||e>=127904&&e<=127946||e>=127951&&e<=127955||e>=127968&&e<=127984||e===127988||e>=127992&&e<=128062||e===128064||e>=128066&&e<=128252||e>=128255&&e<=128317||e>=128331&&e<=128334||e>=128336&&e<=128359||e===128378||e===128405||e===128406||e===128420||e>=128507&&e<=128591||e>=128640&&e<=128709||e===128716||e>=128720&&e<=128722||e>=128725&&e<=128727||e>=128732&&e<=128735||e===128747||e===128748||e>=128756&&e<=128764||e>=128992&&e<=129003||e===129008||e>=129292&&e<=129338||e>=129340&&e<=129349||e>=129351&&e<=129535||e>=129648&&e<=129660||e>=129664&&e<=129672||e>=129680&&e<=129725||e>=129727&&e<=129733||e>=129742&&e<=129755||e>=129760&&e<=129768||e>=129776&&e<=129784||e>=131072&&e<=196605||e>=196608&&e<=262141,wl=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,ii=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,oi=/\t{1,1000}/y,bl=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,ai=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Yx=/\p{M}+/gu,Qx={limit:1/0,ellipsis:""},Im=(e,t={},r={})=>{let n=t.limit??1/0,s=t.ellipsis??"",i=t?.ellipsisWidth??(s?Im(s,Qx,r).width:0),o=r.ansiWidth??0,a=r.controlWidth??0,l=r.tabWidth??8,c=r.ambiguousWidth??1,p=r.emojiWidth??2,u=r.fullWidthWidth??2,f=r.regularWidth??1,h=r.wideWidth??2,d=0,m=0,w=e.length,y=0,E=false,T=w,v=Math.max(0,n-i),C=0,A=0,$=0,_=0;e:for(;;){if(A>C||m>=w&&m>d){let I=e.slice(C,A)||e.slice(d,m);y=0;for(let b of I.replaceAll(Yx,"")){let D=b.codePointAt(0)||0;if(Xx(D)?_=u:Jx(D)?_=h:c!==f&&Kx(D)?_=c:_=f,$+_>v&&(T=Math.min(T,Math.max(C,d)+y)),$+_>n){E=true;break e}y+=b.length,$+=_;}C=A=0;}if(m>=w)break;if(ai.lastIndex=m,ai.test(e)){if(y=ai.lastIndex-m,_=y*f,$+_>v&&(T=Math.min(T,m+Math.floor((v-$)/f))),$+_>n){E=true;break}$+=_,C=d,A=m,m=d=ai.lastIndex;continue}if(wl.lastIndex=m,wl.test(e)){if($+o>v&&(T=Math.min(T,m)),$+o>n){E=true;break}$+=o,C=d,A=m,m=d=wl.lastIndex;continue}if(ii.lastIndex=m,ii.test(e)){if(y=ii.lastIndex-m,_=y*a,$+_>v&&(T=Math.min(T,m+Math.floor((v-$)/a))),$+_>n){E=true;break}$+=_,C=d,A=m,m=d=ii.lastIndex;continue}if(oi.lastIndex=m,oi.test(e)){if(y=oi.lastIndex-m,_=y*l,$+_>v&&(T=Math.min(T,m+Math.floor((v-$)/l))),$+_>n){E=true;break}$+=_,C=d,A=m,m=d=oi.lastIndex;continue}if(bl.lastIndex=m,bl.test(e)){if($+p>v&&(T=Math.min(T,m)),$+p>n){E=true;break}$+=p,C=d,A=m,m=d=bl.lastIndex;continue}m+=1;}return {width:E?v:$,index:E?T:w,truncated:E,ellipsed:E&&n>=i}},Zx={limit:1/0,ellipsis:"",ellipsisWidth:0},vn=(e,t={})=>Im(e,Zx,t).width,pi="\x1B",Lm="\x9B",e0=39,vl="\x07",Dm="[",t0="]",jm="m",Tl=`${t0}8;;`,Rm=new RegExp(`(?:\\${Dm}(?<code>\\d+)m|\\${Tl}(?<uri>.*)${vl})`,"y"),r0=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},km=e=>`${pi}${Dm}${e}${jm}`,Pm=e=>`${pi}${Tl}${e}${vl}`,n0=e=>e.map(t=>vn(t)),Sl=(e,t,r)=>{let n=t[Symbol.iterator](),s=false,i=false,o=e.at(-1),a=o===void 0?0:vn(o),l=n.next(),c=n.next(),p=0;for(;!l.done;){let u=l.value,f=vn(u);a+f<=r?e[e.length-1]+=u:(e.push(u),a=0),(u===pi||u===Lm)&&(s=true,i=t.startsWith(Tl,p+1)),s?i?u===vl&&(s=false,i=false):u===jm&&(s=false):(a+=f,a===r&&!c.done&&(e.push(""),a=0)),l=c,c=n.next(),p+=u.length;}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop());},s0=e=>{let t=e.split(" "),r=t.length;for(;r>0&&!(vn(t[r-1])>0);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")},i0=(e,t,r={})=>{if(r.trim!==false&&e.trim()==="")return "";let n="",s,i,o=e.split(" "),a=n0(o),l=[""];for(let[d,m]of o.entries()){r.trim!==false&&(l[l.length-1]=(l.at(-1)??"").trimStart());let w=vn(l.at(-1)??"");if(d!==0&&(w>=t&&(r.wordWrap===false||r.trim===false)&&(l.push(""),w=0),(w>0||r.trim===false)&&(l[l.length-1]+=" ",w++)),r.hard&&a[d]>t){let y=t-w,E=1+Math.floor((a[d]-y-1)/t);Math.floor((a[d]-1)/t)<E&&l.push(""),Sl(l,m,t);continue}if(w+a[d]>t&&w>0&&a[d]>0){if(r.wordWrap===false&&w<t){Sl(l,m,t);continue}l.push("");}if(w+a[d]>t&&r.wordWrap===false){Sl(l,m,t);continue}l[l.length-1]+=m;}r.trim!==false&&(l=l.map(d=>s0(d)));let c=l.join(`
140
+ `),p=c[Symbol.iterator](),u=p.next(),f=p.next(),h=0;for(;!u.done;){let d=u.value,m=f.value;if(n+=d,d===pi||d===Lm){Rm.lastIndex=h+1;let y=Rm.exec(c)?.groups;if(y?.code!==void 0){let E=Number.parseFloat(y.code);s=E===e0?void 0:E;}else y?.uri!==void 0&&(i=y.uri.length===0?void 0:y.uri);}let w=s?r0(s):void 0;m===`
141
+ `?(i&&(n+=Pm("")),s&&w&&(n+=km(w))):d===`
142
+ `&&(s&&w&&(n+=km(s)),i&&(n+=Pm(i))),h+=d.length,u=f,f=p.next();}return n};o0=(e,t,r,n,s)=>{let i=t,o=0;for(let a=r;a<n;a++){let l=e[a];if(i=i-l.length,o++,i<=s)break}return {lineCount:i,removals:o}},a0=({cursor:e,options:t,style:r,output:n=process.stdout,maxItems:s=Number.POSITIVE_INFINITY,columnPadding:i=0,rowPadding:o=4})=>{let a=ni(n)-i,l=gl(n),c=styleText("dim","..."),p=Math.max(l-o,0),u=Math.max(Math.min(s,p),5),f=0;e>=u-3&&(f=Math.max(Math.min(e-u+3,t.length-u),0));let h=u<t.length&&f>0,d=u<t.length&&f+u<t.length,m=Math.min(f+u,t.length),w=[],y=0;h&&y++,d&&y++;let E=f+(h?1:0),T=m-(d?1:0);for(let C=E;C<T;C++){let A=_l(r(t[C],C===e),a,{hard:true,trim:false}).split(`
143
+ `);w.push(A),y+=A.length;}if(y>p){let C=0,A=0,$=y,_=e-E,I=(b,D)=>o0(w,$,b,D,p);h?({lineCount:$,removals:C}=I(0,_),$>p&&({lineCount:$,removals:A}=I(_+1,w.length))):({lineCount:$,removals:A}=I(_+1,w.length),$>p&&({lineCount:$,removals:C}=I(0,_))),C>0&&(h=true,w.splice(0,C)),A>0&&(d=true,w.splice(w.length-A,A));}let v=[];h&&v.push(c);for(let C of w)for(let A of C)v.push(A);return d&&v.push(c),v},Tn=e=>{let t=e.active??"Yes",r=e.inactive??"No";return new Qs({active:t,inactive:r,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??true,render(){let n=e.withGuide??Ne.withGuide,s=`${n?`${styleText("gray",V)}
144
+ `:""}${ui(this.state)} ${e.message}
143
145
  `,i=this.value?t:r;switch(this.state){case "submit":{let o=n?`${styleText("gray",V)} `:"";return `${s}${o}${styleText("dim",i)}`}case "cancel":{let o=n?`${styleText("gray",V)} `:"";return `${s}${o}${styleText(["strikethrough","dim"],i)}${n?`
144
- ${styleText("gray",V)}`:""}`}default:{let o=n?`${styleText("cyan",V)} `:"",a=n?styleText("cyan",yr):"";return `${s}${o}${this.value?`${styleText("green",Sl)} ${t}`:`${styleText("dim",li)} ${styleText("dim",t)}`}${e.vertical?n?`
146
+ ${styleText("gray",V)}`:""}`}default:{let o=n?`${styleText("cyan",V)} `:"",a=n?styleText("cyan",yr):"";return `${s}${o}${this.value?`${styleText("green",xl)} ${t}`:`${styleText("dim",ci)} ${styleText("dim",t)}`}${e.vertical?n?`
145
147
  ${styleText("cyan",V)} `:`
146
- `:` ${styleText("dim","/")} `}${this.value?`${styleText("dim",li)} ${styleText("dim",r)}`:`${styleText("green",Sl)} ${r}`}
148
+ `:` ${styleText("dim","/")} `}${this.value?`${styleText("dim",ci)} ${styleText("dim",r)}`:`${styleText("green",xl)} ${r}`}
147
149
  ${a}
148
150
  `}}}}).prompt()},K={message:(e=[],{symbol:t=styleText("gray",V),secondarySymbol:r=styleText("gray",V),output:n=process.stdout,spacing:s=1,withGuide:i}={})=>{let o=[],a=i??Ne.withGuide,l=a?r:"",c=a?`${t} `:"",p=a?`${r} `:"";for(let f=0;f<s;f++)o.push(l);let u=Array.isArray(e)?e:e.split(`
149
151
  `);if(u.length>0){let[f,...h]=u;f.length>0?o.push(`${c}${f}`):o.push(a?t:"");for(let d of h)d.length>0?o.push(`${p}${d}`):o.push(a?r:"");}n.write(`${o.join(`
150
152
  `)}
151
- `);},info:(e,t)=>{K.message(e,{...t,symbol:styleText("blue",Ux)});},success:(e,t)=>{K.message(e,{...t,symbol:styleText("green",Bx)});},step:(e,t)=>{K.message(e,{...t,symbol:styleText("green",xl)});},warn:(e,t)=>{K.message(e,{...t,symbol:styleText("yellow",qx)});},warning:(e,t)=>{K.warn(e,t);},error:(e,t)=>{K.message(e,{...t,symbol:styleText("red",Hx)});}},Tn=e=>new Qs({validate:e.validate,mask:e.mask??Mx,signal:e.signal,input:e.input,output:e.output,render(){let t=e.withGuide??Ne.withGuide,r=`${t?`${styleText("gray",V)}
152
- `:""}${ci(this.state)} ${e.message}
153
+ `);},info:(e,t)=>{K.message(e,{...t,symbol:styleText("blue",Hx)});},success:(e,t)=>{K.message(e,{...t,symbol:styleText("green",Wx)});},step:(e,t)=>{K.message(e,{...t,symbol:styleText("green",$l)});},warn:(e,t)=>{K.message(e,{...t,symbol:styleText("yellow",Gx)});},warning:(e,t)=>{K.warn(e,t);},error:(e,t)=>{K.message(e,{...t,symbol:styleText("red",zx)});}},An=e=>new Zs({validate:e.validate,mask:e.mask??qx,signal:e.signal,input:e.input,output:e.output,render(){let t=e.withGuide??Ne.withGuide,r=`${t?`${styleText("gray",V)}
154
+ `:""}${ui(this.state)} ${e.message}
153
155
  `,n=this.userInputWithCursor,s=this.masked;switch(this.state){case "error":{let i=t?`${styleText("yellow",V)} `:"",o=t?`${styleText("yellow",yr)} `:"",a=s??"";return e.clearOnError&&this.clear(),`${r.trim()}
154
156
  ${i}${a}
155
157
  ${o}${styleText("yellow",this.error)}
156
158
  `}case "submit":{let i=t?`${styleText("gray",V)} `:"",o=s?styleText("dim",s):"";return `${r}${i}${o}`}case "cancel":{let i=t?`${styleText("gray",V)} `:"",o=s?styleText(["strikethrough","dim"],s):"";return `${r}${i}${o}${s&&t?`
157
159
  ${styleText("gray",V)}`:""}`}default:{let i=t?`${styleText("cyan",V)} `:"",o=t?styleText("cyan",yr):"";return `${r}${i}${n}
158
160
  ${o}
159
- `}}}}).prompt(),i0=e=>styleText("magenta",e),vl=({indicator:e="dots",onCancel:t,output:r=process.stdout,cancelMessage:n,errorMessage:s,frames:i=bl?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:o=bl?80:120,signal:a,...l}={})=>{let c=jx(),p,u,f=false,h=false,d="",m,w=performance.now(),y=ri(r),E=l?.styleFrame??i0,T=S=>{let x=S>1?s??Ne.messages.error:n??Ne.messages.cancel;h=S===1,f&&(F(x,S),h&&typeof t=="function"&&t());},v=()=>T(2),C=()=>T(1),A=()=>{process.on("uncaughtExceptionMonitor",v),process.on("unhandledRejection",v),process.on("SIGINT",C),process.on("SIGTERM",C),process.on("exit",T),a&&a.addEventListener("abort",C);},$=()=>{process.removeListener("uncaughtExceptionMonitor",v),process.removeListener("unhandledRejection",v),process.removeListener("SIGINT",C),process.removeListener("SIGTERM",C),process.removeListener("exit",T),a&&a.removeEventListener("abort",C);},_=()=>{if(m===void 0)return;c&&r.write(`
160
- `);let S=El(m,y,{hard:true,trim:false}).split(`
161
- `);S.length>1&&r.write(_n.cursor.up(S.length-1)),r.write(_n.cursor.to(0)),r.write(_n.erase.down());},I=S=>S.replace(/\.+$/,""),b=S=>{let x=(performance.now()-S)/1e3,Y=Math.floor(x/60),q=Math.floor(x%60);return Y>0?`[${Y}m ${q}s]`:`[${q}s]`},D=l.withGuide??Ne.withGuide,O=(S="")=>{f=true,p=Tm({output:r}),d=I(S),w=performance.now(),D&&r.write(`${styleText("gray",V)}
162
- `);let x=0,Y=0;A(),u=setInterval(()=>{if(c&&d===m)return;_(),m=d;let q=E(i[x]),j;if(c)j=`${q} ${d}...`;else if(e==="timer")j=`${q} ${d} ${b(w)}`;else {let ce=".".repeat(Math.floor(Y)).slice(0,3);j=`${q} ${d}${ce}`;}let ie=El(j,y,{hard:true,trim:false});r.write(ie),x=x+1<i.length?x+1:0,Y=Y<4?Y+.125:0;},o);},F=(S="",x=0,Y=false)=>{if(!f)return;f=false,clearInterval(u),_();let q=x===0?styleText("green",xl):x===1?styleText("red",km):styleText("red",Pm);d=S??d,Y||(e==="timer"?r.write(`${q} ${d} ${b(w)}
161
+ `}}}}).prompt(),l0=e=>styleText("magenta",e),Al=({indicator:e="dots",onCancel:t,output:r=process.stdout,cancelMessage:n,errorMessage:s,frames:i=El?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:o=El?80:120,signal:a,...l}={})=>{let c=Ux(),p,u,f=false,h=false,d="",m,w=performance.now(),y=ni(r),E=l?.styleFrame??l0,T=S=>{let x=S>1?s??Ne.messages.error:n??Ne.messages.cancel;h=S===1,f&&(F(x,S),h&&typeof t=="function"&&t());},v=()=>T(2),C=()=>T(1),A=()=>{process.on("uncaughtExceptionMonitor",v),process.on("unhandledRejection",v),process.on("SIGINT",C),process.on("SIGTERM",C),process.on("exit",T),a&&a.addEventListener("abort",C);},$=()=>{process.removeListener("uncaughtExceptionMonitor",v),process.removeListener("unhandledRejection",v),process.removeListener("SIGINT",C),process.removeListener("SIGTERM",C),process.removeListener("exit",T),a&&a.removeEventListener("abort",C);},_=()=>{if(m===void 0)return;c&&r.write(`
162
+ `);let S=_l(m,y,{hard:true,trim:false}).split(`
163
+ `);S.length>1&&r.write($n.cursor.up(S.length-1)),r.write($n.cursor.to(0)),r.write($n.erase.down());},I=S=>S.replace(/\.+$/,""),b=S=>{let x=(performance.now()-S)/1e3,Y=Math.floor(x/60),q=Math.floor(x%60);return Y>0?`[${Y}m ${q}s]`:`[${q}s]`},D=l.withGuide??Ne.withGuide,O=(S="")=>{f=true,p=Cm({output:r}),d=I(S),w=performance.now(),D&&r.write(`${styleText("gray",V)}
164
+ `);let x=0,Y=0;A(),u=setInterval(()=>{if(c&&d===m)return;_(),m=d;let q=E(i[x]),j;if(c)j=`${q} ${d}...`;else if(e==="timer")j=`${q} ${d} ${b(w)}`;else {let ce=".".repeat(Math.floor(Y)).slice(0,3);j=`${q} ${d}${ce}`;}let ie=_l(j,y,{hard:true,trim:false});r.write(ie),x=x+1<i.length?x+1:0,Y=Y<4?Y+.125:0;},o);},F=(S="",x=0,Y=false)=>{if(!f)return;f=false,clearInterval(u),_();let q=x===0?styleText("green",$l):x===1?styleText("red",Om):styleText("red",Nm);d=S??d,Y||(e==="timer"?r.write(`${q} ${d} ${b(w)}
163
165
  `):r.write(`${q} ${d}
164
- `)),$(),p();};return {start:O,stop:(S="")=>F(S,0),message:(S="")=>{d=I(S??d);},cancel:(S="")=>F(S,1),error:(S="")=>F(S,2),clear:()=>F("",0,true),get isCancelled(){return h}}},{light:X("\u2500","-"),heavy:X("\u2501","="),block:X("\u2588","#")},ai=(e,t)=>e.includes(`
166
+ `)),$(),p();};return {start:O,stop:(S="")=>F(S,0),message:(S="")=>{d=I(S??d);},cancel:(S="")=>F(S,1),error:(S="")=>F(S,2),clear:()=>F("",0,true),get isCancelled(){return h}}},{light:X("\u2500","-"),heavy:X("\u2501","="),block:X("\u2588","#")},li=(e,t)=>e.includes(`
165
167
  `)?e.split(`
166
168
  `).map(r=>t(r)).join(`
167
- `):t(e),An=e=>{let t=(r,n)=>{let s=r.label??String(r.value);switch(n){case "disabled":return `${styleText("gray",li)} ${ai(s,i=>styleText("gray",i))}${r.hint?` ${styleText("dim",`(${r.hint??"disabled"})`)}`:""}`;case "selected":return `${ai(s,i=>styleText("dim",i))}`;case "active":return `${styleText("green",Sl)} ${s}${r.hint?` ${styleText("dim",`(${r.hint})`)}`:""}`;case "cancelled":return `${ai(s,i=>styleText(["strikethrough","dim"],i))}`;default:return `${styleText("dim",li)} ${ai(s,i=>styleText("dim",i))}`}};return new Zs({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let r=e.withGuide??Ne.withGuide,n=`${ci(this.state)} `,s=`${Wx(this.state)} `,i=ni(e.output,e.message,s,n),o=`${r?`${styleText("gray",V)}
169
+ `):t(e),Cn=e=>{let t=(r,n)=>{let s=r.label??String(r.value);switch(n){case "disabled":return `${styleText("gray",ci)} ${li(s,i=>styleText("gray",i))}${r.hint?` ${styleText("dim",`(${r.hint??"disabled"})`)}`:""}`;case "selected":return `${li(s,i=>styleText("dim",i))}`;case "active":return `${styleText("green",xl)} ${s}${r.hint?` ${styleText("dim",`(${r.hint})`)}`:""}`;case "cancelled":return `${li(s,i=>styleText(["strikethrough","dim"],i))}`;default:return `${styleText("dim",ci)} ${li(s,i=>styleText("dim",i))}`}};return new ei({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let r=e.withGuide??Ne.withGuide,n=`${ui(this.state)} `,s=`${Vx(this.state)} `,i=si(e.output,e.message,s,n),o=`${r?`${styleText("gray",V)}
168
170
  `:""}${i}
169
- `;switch(this.state){case "submit":{let a=r?`${styleText("gray",V)} `:"",l=ni(e.output,t(this.options[this.cursor],"selected"),a);return `${o}${l}`}case "cancel":{let a=r?`${styleText("gray",V)} `:"",l=ni(e.output,t(this.options[this.cursor],"cancelled"),a);return `${o}${l}${r?`
171
+ `;switch(this.state){case "submit":{let a=r?`${styleText("gray",V)} `:"",l=si(e.output,t(this.options[this.cursor],"selected"),a);return `${o}${l}`}case "cancel":{let a=r?`${styleText("gray",V)} `:"",l=si(e.output,t(this.options[this.cursor],"cancelled"),a);return `${o}${l}${r?`
170
172
  ${styleText("gray",V)}`:""}`}default:{let a=r?`${styleText("cyan",V)} `:"",l=r?styleText("cyan",yr):"",c=o.split(`
171
- `).length,p=r?2:1;return `${o}${a}${s0({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:a.length,rowPadding:c+p,style:(u,f)=>t(u,u.disabled?"disabled":f?"active":"inactive")}).join(`
173
+ `).length,p=r?2:1;return `${o}${a}${a0({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:a.length,rowPadding:c+p,style:(u,f)=>t(u,u.disabled?"disabled":f?"active":"inactive")}).join(`
172
174
  ${a}`)}
173
175
  ${l}
174
- `}}}}).prompt()},`${styleText("gray",V)} `,Cn=e=>new ei({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,output:e.output,signal:e.signal,input:e.input,render(){let t=e?.withGuide??Ne.withGuide,r=`${`${t?`${styleText("gray",V)}
175
- `:""}${ci(this.state)} `}${e.message}
176
+ `}}}}).prompt()},`${styleText("gray",V)} `,Rn=e=>new ti({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,output:e.output,signal:e.signal,input:e.input,render(){let t=e?.withGuide??Ne.withGuide,r=`${`${t?`${styleText("gray",V)}
177
+ `:""}${ui(this.state)} `}${e.message}
176
178
  `,n=e.placeholder?styleText("inverse",e.placeholder[0])+styleText("dim",e.placeholder.slice(1)):styleText(["inverse","hidden"],"_"),s=this.userInput?this.userInputWithCursor:n,i=this.value??"";switch(this.state){case "error":{let o=this.error?` ${styleText("yellow",this.error)}`:"",a=t?`${styleText("yellow",V)} `:"",l=t?styleText("yellow",yr):"";return `${r.trim()}
177
179
  ${a}${s}
178
180
  ${l}${o}
179
181
  `}case "submit":{let o=i?` ${styleText("dim",i)}`:"",a=t?styleText("gray",V):"";return `${r}${a}${o}`}case "cancel":{let o=i?` ${styleText(["strikethrough","dim"],i)}`:"",a=t?styleText("gray",V):"";return `${r}${a}${o}${i.trim()?`
180
182
  ${a}`:""}`}default:{let o=t?`${styleText("cyan",V)} `:"",a=t?styleText("cyan",yr):"";return `${r}${o}${s}
181
183
  ${a}
182
- `}}}}).prompt();});function jm(e,t){let r=t?.renderHeader??(a=>String(a)),n=Object.keys(e[0]).filter(a=>!t?.omitKeys?.includes(a)).map(a=>{let l=r(a),c=Math.max(l.length,...e.map(p=>String(p[a]).length));return {key:a,header:l,length:c}}),s=" ".repeat(t?.paddingHorizontal??1),i=`
183
- `.repeat(t?.paddingVertical??1),o=t?.renderCell??((a,l)=>l===null?Dm.default.dim("null"):String(l));return `${i}${s}| ${n.map(a=>a.header.padEnd(a.length)).join(" | ")} |
184
+ `}}}}).prompt();});function Mm(e,t){let r=t?.renderHeader??(a=>String(a)),n=Object.keys(e[0]).filter(a=>!t?.omitKeys?.includes(a)).map(a=>{let l=r(a),c=Math.max(l.length,...e.map(p=>String(p[a]).length));return {key:a,header:l,length:c}}),s=" ".repeat(t?.paddingHorizontal??1),i=`
185
+ `.repeat(t?.paddingVertical??1),o=t?.renderCell??((a,l)=>l===null?Fm.default.dim("null"):String(l));return `${i}${s}| ${n.map(a=>a.header.padEnd(a.length)).join(" | ")} |
184
186
  ${s}| ${n.map(a=>"\u2500".repeat(a.length)).join(" | ")} |
185
187
  ${e.map(a=>`${s}| ${Object.entries(a).filter(([l])=>!t?.omitKeys?.includes(l)).map(([l,c])=>o(l,c).padEnd(n.find(p=>p.key===l)?.length??0)).join(" | ")} |`).join(`
186
- `)}${i}`}async function J(e){try{await e(),process.exit(0);}catch(t){(process.env.LOCAL||process.env.DEBUG)&&console.error(t),K.error(String(t)),process.exit(1);}}var Dm,De=g(()=>{Dm=te(ae());Qe();});function Mm(e){return typeof e=="object"&&e!==null&&"text"in e&&"values"in e}function l0(e,t){if(e==null)return e;switch(t){case 20:return typeof e=="bigint"?e:BigInt(e);case 22:return Array.isArray(e)?e:typeof e=="string"?e.split(" ").map(Number).filter(r=>!Number.isNaN(r)):e;case 1002:case 1009:case 1015:return typeof e=="string"?Fm(e,o0):e;case 1005:case 1007:case 1016:return typeof e=="string"?Fm(e,a0):e;default:return e}}function Tl(e){return {async query(t,r){let n=Mm(t)?t.text:t,s=Mm(t)?t.values:r??[],i=await e.driver.query(n,[...s]);return {rows:i.rows.map(a=>Object.fromEntries(i.fields.map(l=>[l.name,l0(a[l.name],l.dataTypeID)])))}}}}var Fm,o0,a0,Um=g(()=>{Fm=(e,t=r=>r)=>{if(!e||e==="{}")return [];let r=e.slice(1,-1);if(r==="")return [];let n=[],s="",i=false,o=0;for(let a=0;a<r.length;a++){let l=r[a];l==='"'&&r[a-1]!=="\\"?(i=!i,s+=l):l==="{"&&!i?(o++,s+=l):l==="}"&&!i?(o--,s+=l):l===","&&!i&&o===0?(n.push(t(s)),s=""):s+=l;}return s!==""&&n.push(t(s)),n},o0=e=>e==="NULL"?null:e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/\\(.)/g,"$1"):e,a0=e=>e==="NULL"?null:Number.parseInt(e,10);});function p0(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`(?<![\\w$"])${r}\\.`);return e.some(s=>n.test(s))}function Bm(e,t){let r=new Set;for(let n of t)for(let s of n.matchAll(u0))r.add(s[1]);return Object.values(e.schemas).map(n=>n.name).filter(n=>!c0.has(n)&&!r.has(n)&&p0(t,n)).map(n=>`CREATE SCHEMA IF NOT EXISTS ${n};`)}var c0,u0,qm=g(()=>{c0=new Set(["public","supabase_migrations"]),u0=/\bCREATE\s+SCHEMA\b(?:\s+IF\s+NOT\s+EXISTS)?\s+("?[\w$]+"?)/gi;});async function m0(){try{return await import('@supabase/pg-delta')}catch(e){throw new Error("Postgres schema diffing requires pg-delta to be available.",{cause:e})}}function d0(e){let t=/^drop table (.+)$/.exec(e);if(t)return {table:t[1],reason:"drop table"};let r=/^drop column (.+) on (.+)$/.exec(e);if(r)return {table:r[2],reason:`drop column ${r[1]}`};let n=/^drop sequence (.+)$/.exec(e);return n?{table:n[1],reason:"drop sequence"}:{table:"unknown",reason:e}}function h0(e,t){let r=Ws(e),n=new Set([...xt(e),...xt(t)]);return new Set(hr.filter(s=>n.has(s)&&!r.has(s)))}function g0(e){let t=e.trimEnd();return t.endsWith(";")?t:`${t};`}async function Hm(e,t,r=""){let{createPlan:n,extractCatalog:s}=await m0(),{PgliteConnection:i}=await We("@supabase/lite/pglite","pglite","@electric-sql/pglite"),o=new i,a=new i;try{let l=lm(t),c=h0(e,t),p=xt(t);await o.exec(Et(c)),await a.exec(Et(p)),o.config.baseSchema&&await o.exec(o.config.baseSchema),a.config.baseSchema&&await a.exec(a.config.baseSchema),r.trim()&&(await o.exec(r),await a.exec(r)),e.trim()&&await o.exec(e),t.trim()&&await a.exec(t);let u=await s(Tl(o)),f=await s(Tl(a)),h=await n(u,f);if(!h)return "";if(h.plan.risk?.level==="data_loss")throw new DataLossError(h.plan.risk.statements.map(d0));let d=h.plan.statements.filter(w=>!cm(w,l));return [...Bm(f,d),...d.map(g0)].join(`
188
+ `)}${i}`}async function J(e){try{await e(),process.exit(0);}catch(t){(process.env.LOCAL||process.env.DEBUG)&&console.error(t),K.error(String(t)),process.exit(1);}}var Fm,De=g(()=>{Fm=te(ae());Qe();});function Bm(e){return typeof e=="object"&&e!==null&&"text"in e&&"values"in e}function p0(e,t){if(e==null)return e;switch(t){case 20:return typeof e=="bigint"?e:BigInt(e);case 22:return Array.isArray(e)?e:typeof e=="string"?e.split(" ").map(Number).filter(r=>!Number.isNaN(r)):e;case 1002:case 1009:case 1015:return typeof e=="string"?Um(e,c0):e;case 1005:case 1007:case 1016:return typeof e=="string"?Um(e,u0):e;default:return e}}function Cl(e){return {async query(t,r){let n=Bm(t)?t.text:t,s=Bm(t)?t.values:r??[],i=await e.driver.query(n,[...s]);return {rows:i.rows.map(a=>Object.fromEntries(i.fields.map(l=>[l.name,p0(a[l.name],l.dataTypeID)])))}}}}var Um,c0,u0,qm=g(()=>{Um=(e,t=r=>r)=>{if(!e||e==="{}")return [];let r=e.slice(1,-1);if(r==="")return [];let n=[],s="",i=false,o=0;for(let a=0;a<r.length;a++){let l=r[a];l==='"'&&r[a-1]!=="\\"?(i=!i,s+=l):l==="{"&&!i?(o++,s+=l):l==="}"&&!i?(o--,s+=l):l===","&&!i&&o===0?(n.push(t(s)),s=""):s+=l;}return s!==""&&n.push(t(s)),n},c0=e=>e==="NULL"?null:e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/\\(.)/g,"$1"):e,u0=e=>e==="NULL"?null:Number.parseInt(e,10);});function d0(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`(?<![\\w$"])${r}\\.`);return e.some(s=>n.test(s))}function Hm(e,t){let r=new Set;for(let n of t)for(let s of n.matchAll(m0))r.add(s[1]);return Object.values(e.schemas).map(n=>n.name).filter(n=>!f0.has(n)&&!r.has(n)&&d0(t,n)).map(n=>`CREATE SCHEMA IF NOT EXISTS ${n};`)}var f0,m0,Wm=g(()=>{f0=new Set(["public","supabase_migrations"]),m0=/\bCREATE\s+SCHEMA\b(?:\s+IF\s+NOT\s+EXISTS)?\s+("?[\w$]+"?)/gi;});async function g0(){try{return await import('@supabase/pg-delta')}catch(e){throw new Error("Postgres schema diffing requires pg-delta to be available.",{cause:e})}}function y0(e){let t=/^drop table (.+)$/.exec(e);if(t)return {table:t[1],reason:"drop table"};let r=/^drop column (.+) on (.+)$/.exec(e);if(r)return {table:r[2],reason:`drop column ${r[1]}`};let n=/^drop sequence (.+)$/.exec(e);return n?{table:n[1],reason:"drop sequence"}:{table:"unknown",reason:e}}function w0(e,t){let r=Gs(e),n=new Set([...xt(e),...xt(t)]);return new Set(hr.filter(s=>n.has(s)&&!r.has(s)))}function b0(e){let t=e.trimEnd();return t.endsWith(";")?t:`${t};`}async function Gm(e,t,r=""){let{createPlan:n,extractCatalog:s}=await g0(),{PgliteConnection:i}=await We("@supabase/lite/pglite","pglite","@electric-sql/pglite"),o=new i,a=new i;try{let l=um(t),c=w0(e,t),p=xt(t);await o.exec(Et(c)),await a.exec(Et(p)),o.config.baseSchema&&await o.exec(o.config.baseSchema),a.config.baseSchema&&await a.exec(a.config.baseSchema),r.trim()&&(await o.exec(r),await a.exec(r)),e.trim()&&await o.exec(e),t.trim()&&await a.exec(t);let u=await s(Cl(o)),f=await s(Cl(a)),h=await n(u,f);if(!h)return "";if(h.plan.risk?.level==="data_loss")throw new DataLossError(h.plan.risk.statements.map(y0));let d=h.plan.statements.filter(w=>!pm(w,l));return [...Hm(f,d),...d.map(b0)].join(`
187
189
 
188
- `)}finally{await o.close().catch(()=>{}),await a.close().catch(()=>{});}}var Wm=g(()=>{lr();Um();qm();En();});async function pi(e){let{parse:t}=await import('pgsql-parser');return t(e)}var Gm=g(()=>{});var fi,zm=g(()=>{fr();Mt();fi=class{constructor(t){this.ast=t;this.result=[...this.walk(this.ast,[],{trackPaths:["returningList"]})];}result=[];*walk(t=this.ast,r=[],n={}){if(!t||typeof t!="object")return;let{trackPaths:s=[]}=n;if(Array.isArray(t)){for(let o=0;o<t.length;o++)yield*this.walk(t[o],r,n);return}let i=Object.keys(t);if(i.length===1&&i[0][0]>="A"&&i[0][0]<="Z"){let o=i[0];yield {node:t,path:r},yield*this.walk(t[o],[...r,o],n);}else for(let[o,a]of Object.entries(t))if(a&&typeof a=="object"){let l=s.includes(o)?[...r,o]:r;yield*this.walk(a,l,n);}}containsUnsupportedNode(){for(let{node:t}of this.result){let r=pr(t),n=Fs.get(r);if(n&&n.react==="error")return true}}hasFuncCall(){for(let{node:t}of this.result)if("FuncCall"in t)return true;return false}getFuncCalls(){return Array.from(this.result).map(({node:t})=>t).filter(t=>"FuncCall"in t).map(t=>t.FuncCall)}getFuncCallNames(){return this.getFuncCalls().flatMap(t=>t.funcname?.map(r=>r.String?.sval||r.String?.str))}hasSqlValueFunction(){for(let{node:t}of this.result)if("SQLValueFunction"in t)return true;return false}getSqlValueFunctions(){return Array.from(this.result).map(({node:t})=>t).filter(t=>"SQLValueFunction"in t).map(t=>t.SQLValueFunction)}getSqlValueFunctionNames(){return this.getSqlValueFunctions().map(t=>t.op)}hasUnsafeStar(){let t=this.result.filter(({node:r})=>"A_Star"in r);if(t.length===0)return false;for(let{path:r}of t)if(!r.includes("SelectStmt")&&!r.includes("returningList"))return true;return false}getRelationDefinitions(){return this.result.filter(({node:r})=>"CreateStmt"in r).map(({node:r})=>r.CreateStmt).map(r=>({relation:{relname:r.relation?.relname??"",inh:r.relation?.inh,relpersistence:r.relation?.relpersistence},columns:r.tableElts?.map(n=>{let s=n.ColumnDef?.typeName?.names?.map(o=>"String"in o?o.String.sval:""),i=s?.some(o=>o.toLowerCase().includes("pg_catalog"));return {name:n.ColumnDef?.colname??"",is_local:n.ColumnDef?.is_local,pg_catalog:i,type:s?.filter(o=>!o.toLowerCase().includes("pg_catalog"))[0]??"",types:s,constraints:n.ColumnDef?.constraints}})}))}getRelationColumnTypes(){return {has_non_pg_catalog_types:this.getRelationDefinitions().some(t=>t.columns?.some(r=>!r.pg_catalog)),types:Array.from(new Set(this.getRelationDefinitions().flatMap(t=>t.columns?.map(r=>r.type))))}}};});var y0,w0,b0,S0,wr,mi,Vm=g(()=>{fr();y0=["DECLARE","IF","ELSIF","ELSE","LOOP","WHILE","FOR","FOREACH","EXCEPTION","RAISE","PERFORM","EXECUTE","SELECT"],w0=/^NEW\.(\w+)\s*(?::=|=)\s*(.+)$/is,b0=/^RETURN\s+(NEW|OLD)$/i,S0=/^(INSERT|UPDATE|DELETE)\b/i,wr=class extends Ut{constructor(r,n,s){super(s??`Unsupported PL/pgSQL: ${r}`);this.hint=r;this.body=n;}},mi=class{parse(t){let r=this.extractBlock(t),n=this.splitStatements(r),s=[],i=null;for(let o of n){let a=o.trim();if(!a)continue;this.rejectUnsupported(a);let l=a.match(b0);if(l){i=l[1].toUpperCase(),s.push({type:"return",value:i});continue}let c=a.match(w0);if(c){s.push({type:"assignment",column:c[1],expression:c[2].trim()});continue}if(S0.test(a)){s.push({type:"dml",sql:a});continue}throw new wr(`"${a.substring(0,80)}" is not translatable to SQLite`,r)}if(!i)throw new Ut("Trigger function body must end with RETURN NEW or RETURN OLD");return {statements:s,returnValue:i}}extractBlock(t){let r=t.trim(),n=r.toUpperCase();if(/^\s*DECLARE\b/i.test(r))throw new wr('"DECLARE" is not translatable to SQLite',t);let s=n.indexOf("BEGIN"),i=n.lastIndexOf("END");if(s===-1||i===-1||i<=s)throw new wr("Expected BEGIN ... END block in trigger function body",t);return r.slice(s+5,i).trim()}splitStatements(t){let r=[],n="",s=0,i=false,o="";for(let l=0;l<t.length;l++){let c=t[l];if(i){n+=c,c===o&&(l+1<t.length&&t[l+1]===o?n+=t[++l]:i=false);continue}if(c==="'"||c==='"'){i=true,o=c,n+=c;continue}if(c==="("){s++,n+=c;continue}if(c===")"){s--,n+=c;continue}if(c===";"&&s===0){r.push(n.trim()),n="";continue}n+=c;}let a=n.trim();return a&&r.push(a),r}rejectUnsupported(t){let r=t.match(/^(\w+)/)?.[1]?.toUpperCase();if(r&&y0.includes(r))throw new wr(`"${r}" is not translatable to SQLite`,t)}};});var di,hi=g(()=>{di=class extends Error{constructor(r){super(`Migration would cause data loss:
190
+ `)}finally{await o.close().catch(()=>{}),await a.close().catch(()=>{});}}var zm=g(()=>{lr();qm();Wm();xn();});async function fi(e){let{parse:t}=await import('pgsql-parser');return t(e)}var Vm=g(()=>{});var mi,Km=g(()=>{fr();Mt();mi=class{constructor(t){this.ast=t;this.result=[...this.walk(this.ast,[],{trackPaths:["returningList"]})];}result=[];*walk(t=this.ast,r=[],n={}){if(!t||typeof t!="object")return;let{trackPaths:s=[]}=n;if(Array.isArray(t)){for(let o=0;o<t.length;o++)yield*this.walk(t[o],r,n);return}let i=Object.keys(t);if(i.length===1&&i[0][0]>="A"&&i[0][0]<="Z"){let o=i[0];yield {node:t,path:r},yield*this.walk(t[o],[...r,o],n);}else for(let[o,a]of Object.entries(t))if(a&&typeof a=="object"){let l=s.includes(o)?[...r,o]:r;yield*this.walk(a,l,n);}}containsUnsupportedNode(){for(let{node:t}of this.result){let r=pr(t),n=Ms.get(r);if(n&&n.react==="error")return true}}hasFuncCall(){for(let{node:t}of this.result)if("FuncCall"in t)return true;return false}getFuncCalls(){return Array.from(this.result).map(({node:t})=>t).filter(t=>"FuncCall"in t).map(t=>t.FuncCall)}getFuncCallNames(){return this.getFuncCalls().flatMap(t=>t.funcname?.map(r=>r.String?.sval||r.String?.str))}hasSqlValueFunction(){for(let{node:t}of this.result)if("SQLValueFunction"in t)return true;return false}getSqlValueFunctions(){return Array.from(this.result).map(({node:t})=>t).filter(t=>"SQLValueFunction"in t).map(t=>t.SQLValueFunction)}getSqlValueFunctionNames(){return this.getSqlValueFunctions().map(t=>t.op)}hasUnsafeStar(){let t=this.result.filter(({node:r})=>"A_Star"in r);if(t.length===0)return false;for(let{path:r}of t)if(!r.includes("SelectStmt")&&!r.includes("returningList"))return true;return false}getRelationDefinitions(){return this.result.filter(({node:r})=>"CreateStmt"in r).map(({node:r})=>r.CreateStmt).map(r=>({relation:{relname:r.relation?.relname??"",inh:r.relation?.inh,relpersistence:r.relation?.relpersistence},columns:r.tableElts?.map(n=>{let s=n.ColumnDef?.typeName?.names?.map(o=>"String"in o?o.String.sval:""),i=s?.some(o=>o.toLowerCase().includes("pg_catalog"));return {name:n.ColumnDef?.colname??"",is_local:n.ColumnDef?.is_local,pg_catalog:i,type:s?.filter(o=>!o.toLowerCase().includes("pg_catalog"))[0]??"",types:s,constraints:n.ColumnDef?.constraints}})}))}getRelationColumnTypes(){return {has_non_pg_catalog_types:this.getRelationDefinitions().some(t=>t.columns?.some(r=>!r.pg_catalog)),types:Array.from(new Set(this.getRelationDefinitions().flatMap(t=>t.columns?.map(r=>r.type))))}}};});var S0,E0,x0,_0,wr,di,Xm=g(()=>{fr();S0=["DECLARE","IF","ELSIF","ELSE","LOOP","WHILE","FOR","FOREACH","EXCEPTION","RAISE","PERFORM","EXECUTE","SELECT"],E0=/^NEW\.(\w+)\s*(?::=|=)\s*(.+)$/is,x0=/^RETURN\s+(NEW|OLD)$/i,_0=/^(INSERT|UPDATE|DELETE)\b/i,wr=class extends Ut{constructor(r,n,s){super(s??`Unsupported PL/pgSQL: ${r}`);this.hint=r;this.body=n;}},di=class{parse(t){let r=this.extractBlock(t),n=this.splitStatements(r),s=[],i=null;for(let o of n){let a=o.trim();if(!a)continue;this.rejectUnsupported(a);let l=a.match(x0);if(l){i=l[1].toUpperCase(),s.push({type:"return",value:i});continue}let c=a.match(E0);if(c){s.push({type:"assignment",column:c[1],expression:c[2].trim()});continue}if(_0.test(a)){s.push({type:"dml",sql:a});continue}throw new wr(`"${a.substring(0,80)}" is not translatable to SQLite`,r)}if(!i)throw new Ut("Trigger function body must end with RETURN NEW or RETURN OLD");return {statements:s,returnValue:i}}extractBlock(t){let r=t.trim(),n=r.toUpperCase();if(/^\s*DECLARE\b/i.test(r))throw new wr('"DECLARE" is not translatable to SQLite',t);let s=n.indexOf("BEGIN"),i=n.lastIndexOf("END");if(s===-1||i===-1||i<=s)throw new wr("Expected BEGIN ... END block in trigger function body",t);return r.slice(s+5,i).trim()}splitStatements(t){let r=[],n="",s=0,i=false,o="";for(let l=0;l<t.length;l++){let c=t[l];if(i){n+=c,c===o&&(l+1<t.length&&t[l+1]===o?n+=t[++l]:i=false);continue}if(c==="'"||c==='"'){i=true,o=c,n+=c;continue}if(c==="("){s++,n+=c;continue}if(c===")"){s--,n+=c;continue}if(c===";"&&s===0){r.push(n.trim()),n="";continue}n+=c;}let a=n.trim();return a&&r.push(a),r}rejectUnsupported(t){let r=t.match(/^(\w+)/)?.[1]?.toUpperCase();if(r&&S0.includes(r))throw new wr(`"${r}" is not translatable to SQLite`,t)}};});var hi,gi=g(()=>{hi=class extends Error{constructor(r){super(`Migration would cause data loss:
189
191
  ${r.map(n=>` - ${n.table}: ${n.reason}`).join(`
190
- `)}`);this.warnings=r;this.name="DataLossError";}};});var gi,Km=g(()=>{Rt();gi=class{makeIndexKey(t){return `${t.table}:${t.name}:${t.unique}:${t.columns.join(",")}`}makeForeignKeyKey(t){return `${t.table}:${t.column}:${t.ref_table}:${t.ref_column}`}diff(t,r){let n=[],s=[],i=[],o=[],a=new Set(t.tables.map(m=>m.name)),l=new Set(r.tables.map(m=>m.name));for(let m of r.tables)a.has(m.name)||n.push({type:"added",name:m.name,sql:m.sql});for(let m of t.tables)l.has(m.name)||n.push({type:"removed",name:m.name});for(let m of t.tables){let w=r.tables.find(T=>T.name===m.name);if(!w)continue;let y=ao(m.sql),E=ao(w.sql);y!==E&&n.push({type:"modified",name:m.name,sql:w.sql});}let c=t.tables.filter(m=>l.has(m.name));for(let m of c){let w=t.columns.filter(v=>v.table===m.name),y=r.columns.filter(v=>v.table===m.name),E=new Map(w.map(v=>[v.name,v])),T=new Map(y.map(v=>[v.name,v]));for(let[v,C]of T)E.has(v)||s.push({type:"added",table:m.name,name:v,column:C});for(let[v]of E)T.has(v)||s.push({type:"removed",table:m.name,name:v});for(let[v,C]of E){let A=T.get(v);if(!A)continue;let $={};oo(C.type)!==oo(A.type)&&($.type={from:C.type,to:A.type}),C.nullable!==A.nullable&&($.nullable={from:C.nullable,to:A.nullable}),lo(C.default_value)!==lo(A.default_value)&&($.default_value={from:C.default_value,to:A.default_value}),Object.keys($).length>0&&s.push({type:"modified",table:m.name,name:v,changes:$});}}let p=new Map(t.indexes.map(m=>[this.makeIndexKey(m),m])),u=new Map(r.indexes.map(m=>[this.makeIndexKey(m),m]));for(let[m,w]of u)p.has(m)||i.push({type:"added",...w});for(let[m,w]of p)u.has(m)||i.push({type:"removed",...w});let f=new Map(t.foreign_keys.map(m=>[this.makeForeignKeyKey(m),m])),h=new Map(r.foreign_keys.map(m=>[this.makeForeignKeyKey(m),m]));for(let[m,w]of h)f.has(m)||o.push({type:"added",...w});for(let[m,w]of f)h.has(m)||o.push({type:"removed",...w});let d=n.length>0||s.length>0||i.length>0||o.length>0;return {tables:n,columns:s,indexes:i,foreign_keys:o,has_changes:d}}};});var x0,yi,Xm=g(()=>{hi();Lr();x0=["CURRENT_TIMESTAMP","CURRENT_TIME","CURRENT_DATE"],yi=class{plan(t,r,n,s){if(!t.has_changes)return {steps:[],warnings:[],unsafe:false};let i=[],o=[];i.push({sql:"PRAGMA foreign_keys=OFF;",description:"Disable foreign key checks",type:"disable_foreign_keys"}),i.push({sql:"BEGIN;",description:"Begin transaction",type:"begin_transaction"});for(let u of t.tables.filter(f=>f.type==="added")){i.push({sql:`${u.sql};`,description:`CREATE TABLE ${U(u.name)}`,type:"create_table"});let f=n.indexes.filter(h=>h.table===u.name);for(let h of f){let d=h.unique?"UNIQUE ":"",m=h.columns.map(w=>U(w)).join(", ");i.push({sql:`CREATE ${d}INDEX ${U(h.name)} ON ${U(u.name)} (${m});`,description:`Create index ${U(h.name)} on ${U(u.name)}`,type:"add_index"});}}let a=new Set(r.tables.map(u=>u.name)),l=new Set(n.tables.map(u=>u.name)),c=new Set(t.tables.filter(u=>u.type==="modified").map(u=>u.name)),p=[...a].filter(u=>l.has(u));for(let u of p){if(!(c.has(u)||t.columns.some(m=>m.table===u)||t.indexes.some(m=>m.table===u)||t.foreign_keys.some(m=>m.table===u)))continue;let{canAlter:h,addedCols:d}=this.canSimpleAlter(u,t,n);if(h){for(let y of d)i.push({sql:`ALTER TABLE ${U(u)} ADD COLUMN ${this.columnDef(y)};`,description:`Add column ${U(y.name)} to ${U(u)}`,type:"add_column"});let m=t.indexes.filter(y=>y.table===u&&y.type==="added"),w=t.indexes.filter(y=>y.table===u&&y.type==="removed");for(let y of w)i.push({sql:`DROP INDEX IF EXISTS ${U(y.name)};`,description:`Drop index ${U(y.name)}`,type:"drop_index"});for(let y of m){let E=y.unique?"UNIQUE ":"",T=y.columns.map(v=>U(v)).join(", ");i.push({sql:`CREATE ${E}INDEX ${U(y.name)} ON ${U(u)} (${T});`,description:`Create index ${U(y.name)} on ${U(u)}`,type:"add_index"});}}else {let m=this.rebuildTable(u,r,n,t);i.push(...m.steps),o.push(...m.warnings);}}for(let u of t.tables.filter(f=>f.type==="removed"))i.push({sql:`DROP TABLE ${U(u.name)};`,description:`Drop table ${U(u.name)}`,type:"drop_table"}),o.push({table:u.name,reason:"table will be dropped"});return i.push({sql:"COMMIT;",description:"Commit transaction",type:"commit_transaction"}),i.push({sql:"PRAGMA foreign_keys=ON;",description:"Re-enable foreign key checks",type:"enable_foreign_keys"}),{steps:i,warnings:o,unsafe:o.length>0}}rebuildTable(t,r,n,s){let i=[],o=[],a=n.tables.find(y=>y.name===t);if(!a)return {steps:i,warnings:o};let l=`_${t}_migrate_new`,c=a.sql.replace(new RegExp(`(CREATE\\s+TABLE\\s+)(?:"${t}"|${t})`,"i"),`$1${U(l)}`);i.push({sql:`${c};`,description:`Create temporary table ${U(l)}`,type:"create_table"});let p=r.columns.filter(y=>y.table===t).map(y=>y.name),u=n.columns.filter(y=>y.table===t).map(y=>y.name),f=p.filter(y=>u.includes(y));if(f.length>0){let y=f.map(E=>U(E)).join(", ");i.push({sql:`INSERT INTO ${U(l)} (${y})
192
+ `)}`);this.warnings=r;this.name="DataLossError";}};});var yi,Jm=g(()=>{Rt();yi=class{makeIndexKey(t){return `${t.table}:${t.name}:${t.unique}:${t.columns.join(",")}`}makeForeignKeyKey(t){return `${t.table}:${t.column}:${t.ref_table}:${t.ref_column}`}diff(t,r){let n=[],s=[],i=[],o=[],a=new Set(t.tables.map(m=>m.name)),l=new Set(r.tables.map(m=>m.name));for(let m of r.tables)a.has(m.name)||n.push({type:"added",name:m.name,sql:m.sql});for(let m of t.tables)l.has(m.name)||n.push({type:"removed",name:m.name});for(let m of t.tables){let w=r.tables.find(T=>T.name===m.name);if(!w)continue;let y=lo(m.sql),E=lo(w.sql);y!==E&&n.push({type:"modified",name:m.name,sql:w.sql});}let c=t.tables.filter(m=>l.has(m.name));for(let m of c){let w=t.columns.filter(v=>v.table===m.name),y=r.columns.filter(v=>v.table===m.name),E=new Map(w.map(v=>[v.name,v])),T=new Map(y.map(v=>[v.name,v]));for(let[v,C]of T)E.has(v)||s.push({type:"added",table:m.name,name:v,column:C});for(let[v]of E)T.has(v)||s.push({type:"removed",table:m.name,name:v});for(let[v,C]of E){let A=T.get(v);if(!A)continue;let $={};ao(C.type)!==ao(A.type)&&($.type={from:C.type,to:A.type}),C.nullable!==A.nullable&&($.nullable={from:C.nullable,to:A.nullable}),co(C.default_value)!==co(A.default_value)&&($.default_value={from:C.default_value,to:A.default_value}),Object.keys($).length>0&&s.push({type:"modified",table:m.name,name:v,changes:$});}}let p=new Map(t.indexes.map(m=>[this.makeIndexKey(m),m])),u=new Map(r.indexes.map(m=>[this.makeIndexKey(m),m]));for(let[m,w]of u)p.has(m)||i.push({type:"added",...w});for(let[m,w]of p)u.has(m)||i.push({type:"removed",...w});let f=new Map(t.foreign_keys.map(m=>[this.makeForeignKeyKey(m),m])),h=new Map(r.foreign_keys.map(m=>[this.makeForeignKeyKey(m),m]));for(let[m,w]of h)f.has(m)||o.push({type:"added",...w});for(let[m,w]of f)h.has(m)||o.push({type:"removed",...w});let d=n.length>0||s.length>0||i.length>0||o.length>0;return {tables:n,columns:s,indexes:i,foreign_keys:o,has_changes:d}}};});var v0,wi,Ym=g(()=>{gi();Lr();v0=["CURRENT_TIMESTAMP","CURRENT_TIME","CURRENT_DATE"],wi=class{plan(t,r,n,s){if(!t.has_changes)return {steps:[],warnings:[],unsafe:false};let i=[],o=[];i.push({sql:"PRAGMA foreign_keys=OFF;",description:"Disable foreign key checks",type:"disable_foreign_keys"}),i.push({sql:"BEGIN;",description:"Begin transaction",type:"begin_transaction"});for(let u of t.tables.filter(f=>f.type==="added")){i.push({sql:`${u.sql};`,description:`CREATE TABLE ${U(u.name)}`,type:"create_table"});let f=n.indexes.filter(h=>h.table===u.name);for(let h of f){let d=h.unique?"UNIQUE ":"",m=h.columns.map(w=>U(w)).join(", ");i.push({sql:`CREATE ${d}INDEX ${U(h.name)} ON ${U(u.name)} (${m});`,description:`Create index ${U(h.name)} on ${U(u.name)}`,type:"add_index"});}}let a=new Set(r.tables.map(u=>u.name)),l=new Set(n.tables.map(u=>u.name)),c=new Set(t.tables.filter(u=>u.type==="modified").map(u=>u.name)),p=[...a].filter(u=>l.has(u));for(let u of p){if(!(c.has(u)||t.columns.some(m=>m.table===u)||t.indexes.some(m=>m.table===u)||t.foreign_keys.some(m=>m.table===u)))continue;let{canAlter:h,addedCols:d}=this.canSimpleAlter(u,t,n);if(h){for(let y of d)i.push({sql:`ALTER TABLE ${U(u)} ADD COLUMN ${this.columnDef(y)};`,description:`Add column ${U(y.name)} to ${U(u)}`,type:"add_column"});let m=t.indexes.filter(y=>y.table===u&&y.type==="added"),w=t.indexes.filter(y=>y.table===u&&y.type==="removed");for(let y of w)i.push({sql:`DROP INDEX IF EXISTS ${U(y.name)};`,description:`Drop index ${U(y.name)}`,type:"drop_index"});for(let y of m){let E=y.unique?"UNIQUE ":"",T=y.columns.map(v=>U(v)).join(", ");i.push({sql:`CREATE ${E}INDEX ${U(y.name)} ON ${U(u)} (${T});`,description:`Create index ${U(y.name)} on ${U(u)}`,type:"add_index"});}}else {let m=this.rebuildTable(u,r,n,t);i.push(...m.steps),o.push(...m.warnings);}}for(let u of t.tables.filter(f=>f.type==="removed"))i.push({sql:`DROP TABLE ${U(u.name)};`,description:`Drop table ${U(u.name)}`,type:"drop_table"}),o.push({table:u.name,reason:"table will be dropped"});return i.push({sql:"COMMIT;",description:"Commit transaction",type:"commit_transaction"}),i.push({sql:"PRAGMA foreign_keys=ON;",description:"Re-enable foreign key checks",type:"enable_foreign_keys"}),{steps:i,warnings:o,unsafe:o.length>0}}rebuildTable(t,r,n,s){let i=[],o=[],a=n.tables.find(y=>y.name===t);if(!a)return {steps:i,warnings:o};let l=`_${t}_migrate_new`,c=a.sql.replace(new RegExp(`(CREATE\\s+TABLE\\s+)(?:"${t}"|${t})`,"i"),`$1${U(l)}`);i.push({sql:`${c};`,description:`Create temporary table ${U(l)}`,type:"create_table"});let p=r.columns.filter(y=>y.table===t).map(y=>y.name),u=n.columns.filter(y=>y.table===t).map(y=>y.name),f=p.filter(y=>u.includes(y));if(f.length>0){let y=f.map(E=>U(E)).join(", ");i.push({sql:`INSERT INTO ${U(l)} (${y})
191
193
  SELECT ${y}
192
- FROM ${U(t)};`,description:`Copy data from ${U(t)} to ${U(l)}`,type:"copy_data"});}i.push({sql:`DROP TABLE ${U(t)};`,description:`Drop old table ${U(t)}`,type:"drop_table"}),i.push({sql:`ALTER TABLE ${U(l)} RENAME TO ${U(t)};`,description:`Rename ${U(l)} to ${U(t)}`,type:"rename_table"});let h=n.indexes.filter(y=>y.table===t);for(let y of h){let E=y.unique?"UNIQUE ":"",T=y.columns.map(v=>U(v)).join(", ");i.push({sql:`CREATE ${E}INDEX ${U(y.name)} ON ${U(t)} (${T});`,description:`Recreate index ${U(y.name)} on ${U(t)}`,type:"add_index"});}let d=n.triggers?.filter(y=>y.table===t)??[];for(let y of d)i.push({sql:`${y.sql};`,description:`Recreate trigger ${U(y.name)} on ${U(t)}`,type:"create_trigger"});let m=s.columns.filter(y=>y.table===t&&y.type==="removed");for(let y of m)o.push({table:t,reason:`column "${y.name}" will be dropped`});let w=s.columns.filter(y=>y.table===t&&y.type==="modified");for(let y of w)y.changes?.type&&o.push({table:t,reason:`column "${y.name}" type changes from ${y.changes.type.from} to ${y.changes.type.to}`}),y.changes?.nullable&&!y.changes.nullable.to&&o.push({table:t,reason:`column "${y.name}" becomes NOT NULL`});return {steps:i,warnings:o}}canSimpleAlter(t,r,n){let s=r.columns.filter(u=>u.table===t),i=s.filter(u=>u.type==="added"),o=s.filter(u=>u.type==="removed"),a=s.filter(u=>u.type==="modified"),l=r.foreign_keys.some(u=>u.table===t);if(o.length>0||a.length>0||l)return {canAlter:false,addedCols:i};let c=n.tables.find(u=>u.name===t);return c&&/\bCHECK\s*\(/i.test(c.sql)?{canAlter:false,addedCols:i}:{canAlter:i.every(u=>{let f=u.column;return this.hasNonConstantDefault(f.default_value)?false:f.nullable||f.default_value!=null})&&i.length>0,addedCols:i}}hasNonConstantDefault(t){if(t==null)return false;let r=t.trim().toUpperCase();return x0.includes(r)}columnDef(t){let r=t.column,n=`${U(r.name)} ${r.type||"TEXT"}`;return r.nullable||(n+=" NOT NULL"),r.default_value!=null&&(n+=` DEFAULT ${r.default_value}`),n}};});function A0(e){let t=e?.GrantStmt??e;return t?.is_grant!==true?false:t.targtype==="ACL_TARGET_ALL_IN_SCHEMA"?t.objtype==="OBJECT_TABLE"||t.objtype==="OBJECT_SEQUENCE":t.targtype==="ACL_TARGET_OBJECT"&&T0.has(t.objtype)}var T0,wi,Jm=g(()=>{fr();Mt();Mt();zm();ht();Vm();hi();Km();Xm();Lr();La();ja();T0=new Set(["OBJECT_TABLE","OBJECT_VIEW","OBJECT_SEQUENCE","OBJECT_SCHEMA"]);wi=class extends Deparser{enums;schemaHandling;warnings=[];helper;config;triggerFunctions=new Map;plpgsqlParser=new mi;introspection;functionResolution;serialColumns;constructor(t,{enums:r,schemaHandling:n,introspection:s,serialColumns:i,...o}={}){super(t,o),this.schemaHandling=n??"default",this.enums=r??new Map,this.helper=new fi(t),this.config=o,this.introspection=s,this.functionResolution=o?.functionResolution??"translate",this.serialColumns=i??new WeakSet;}visit(t,r){let n=pr(t);if(n==="GrantStmt"&&A0(t))return "";let s=Fs.get(n);if(s){if(s.react==="error")throw new B({[n]:t},`Unsupported node type: ${n}`);return s.react==="warn"&&this.warnings.push({type:n,node:t}),""}return super.visit(t,r)}deparse(t,r){if(t==null)return null;if(!r){let n=new SqlFormatter;r=new DeparserContext({formatter:n});}return typeof t=="number"||t instanceof Number?t.toString():this.visit(t,r)}RawStmt(t,r){if(!t.stmt||t.stmt.CommentStmt)return "";let n=this.deparse(t.stmt,r);return !n||n.length===0?"":t.stmt_len?n+";":n}RangeVar(t,r){this.ensureRelation(t);let n=this.effectiveSchema(t.schemaname),s=t.relname,i=this.quoteBareIfNeeded(s);n&&(this.schemaHandling==="prefix"?i=`${n}__${s}`:i=`"${n}.${s}"`);let o=t.alias?" "+this.Alias(t.alias,r):"";return i+o}getRelationName(t){this.ensureRelation(t);let r=this.effectiveSchema(t.schemaname),n=t.relname;return r?this.schemaHandling==="prefix"?`${r}__${n}`:`${r}.${n}`:n}quoteBareIfNeeded(t){return /^[A-Za-z_][A-Za-z0-9_]*$/.test(t)?t:`"${t.replace(/"/g,'""')}"`}effectiveSchema(t){if(t){if(this.config.forceDefaultSchema||this.schemaHandling!=="default")return t;if(t!=="public")return t}}ensureRelation(t){let r=this.config.forceDefaultSchema;r&&(!t||typeof t!="object"||r.length===0||t.schemaname||(t.schemaname=r));}CreateStmt(t,r){if(t.inhRelations&&t.inhRelations.length>0)throw new B({CreateStmt:t},"Inheritance is not supported in SQLite");if(t.ofTypename!==void 0)throw new B({CreateStmt:t},"Typed tables (CREATE TABLE ... OF type_name) are not supported. Define columns directly in the CREATE TABLE statement instead.");if(t.options&&t.options.length>0&&(t.options=void 0),!t.tableElts||t.tableElts.length===0)throw new B({CreateStmt:t},"Empty tables are not supported in SQLite. Define at least one column.");return t.accessMethod&&(t.accessMethod=void 0),super.CreateStmt(t,r)+" STRICT"}TableLikeClause(t,r){throw new B({TableLikeClause:t},"CREATE TABLE ... (LIKE ...) is not supported in SQLite. Define the table columns explicitly instead.")}DefElem(t,r){if(["oids","fillfactor",/^autovacuum_/i,"toast_tuple_target","parallel_workers","user_catalog_table"].some(i=>iu(t.defname??"",i)))return "";let s=super.DefElem(t,r);throw new B({DefElem:t},`DefElem "${t.defname}" (${s}) not supported`)}TypeName(t,r){if(!t.names)return "";let n=t.names.map(i=>i.String?i.String.sval||i.String.str:"").filter(Boolean);if(n.length===0)return "";let s=n.length===2&&n[0]==="pg_catalog"?n[1]:n.join(".");return t.arrayBounds&&t.arrayBounds.length>0||this.enums.has(s.toLowerCase())?"TEXT":Bf(s)}ColumnDef(t,r){let n=[],s=t.colname;s&&n.push(this.quoteIfNeeded(s));let i=false,o=false,a=null,l=null,c=null,p=false;if(t.typeName){let u=t.typeName.names?.map(d=>d.String?.sval||d.String?.str).filter(Boolean);c=u&&(u.length===2&&u[0]==="pg_catalog"?u[1]:u[0]),i=!!(c&&Ls(c))||this.serialColumns.has(t),p=!!(t.typeName.arrayBounds&&t.typeName.arrayBounds.length>0);let f=Array.isArray(t.typeName.typmods)?t.typeName.typmods:[],h=d=>f[d]?.A_Const?.ival?.ival??f[d]?.A_Const?.val?.ival?.ival;if(c&&Ds(c)&&f.length>0){let d=h(0);typeof d=="number"&&d>0&&(a={maxLen:d});}if(c&&js(c)&&f.length>=2){let d=h(0),m=h(1);typeof d=="number"&&typeof m=="number"&&d>0&&m>=0&&(l={precision:d,scale:m});}if(t.constraints){let d=Array.isArray(t.constraints)?t.constraints:[];o=d.some(m=>m.Constraint?.contype==="CONSTR_PRIMARY"),d.some(m=>m.Constraint?.contype==="CONSTR_IDENTITY")&&(i=true);}n.push(this.TypeName(t.typeName,r));}if(t.constraints){let u=Array.isArray(t.constraints)?t.constraints:[],f=u.map(d=>this.visit(d,r));n.push(...f.filter(Boolean));let h=u.some(d=>d.Constraint?.contype==="CONSTR_CHECK");i&&o&&!h?n.push("AUTOINCREMENT"):i&&!o&&this.warnings.push({type:"ColumnDef",node:{ColumnDef:t},message:`Column "${s}" is serial/auto-increment but not the primary key; SQLite can't auto-increment a non-primary-key column, so it becomes a plain INTEGER (no auto-increment).`});}if(s&&c){let u={isArray:p};a&&(u.lengthConstraint=a.maxLen),l&&(u.numericPrecision=l);let f=this.enums.get(c.toLowerCase());f&&(u.enumValues=f);let m=Wt({schema:"public",table:"",column:s,pgTypeName:c,nullable:true,defaultValue:null,defaultFn:null,isPrimaryKey:o,isUnique:false,isSerial:i},u).checkConstraint();m&&n.push(`CHECK (${m})`);}return n.join(" ")}Constraint(t,r){let n=t.contype;if(n==="CONSTR_IDENTITY"||n==="CONSTR_ATTR_DEFERRABLE"||n==="CONSTR_ATTR_NOT_DEFERRABLE"||n==="CONSTR_ATTR_DEFERRED"||n==="CONSTR_ATTR_IMMEDIATE")return "";if(n==="CONSTR_NULL")return "NULL";if(n==="CONSTR_NOTNULL")return "NOT NULL";if(n==="CONSTR_DEFAULT"&&t.raw_expr){let s=this.visit(t.raw_expr,r);return s.includes("(")&&!s.startsWith("(")?`DEFAULT (${s})`:`DEFAULT ${s}`}if(n==="CONSTR_CHECK"&&t.raw_expr){let s=[];t.conname&&s.push("CONSTRAINT",Is(t.conname)),s.push("CHECK");let i=this.visit(t.raw_expr,r);return s.push(`(${i})`),s.join(" ")}if(n==="CONSTR_PRIMARY")return t.keys&&t.keys.length>0?`PRIMARY KEY (${Ft(t.keys).map(i=>this.visit(i,r)).join(", ")})`:"PRIMARY KEY";if(n==="CONSTR_UNIQUE")return t.keys&&t.keys.length>0?`UNIQUE (${Ft(t.keys).map(i=>this.visit(i,r)).join(", ")})`:"UNIQUE";if(n==="CONSTR_FOREIGN")return super.Constraint(t,r).replace(/FOREIGN\s+KEY\s+REFERENCES/gi,"REFERENCES");if(n==="CONSTR_GENERATED"&&t.raw_expr)return `GENERATED ALWAYS AS (${this.visit(t.raw_expr,r)}) STORED`;if(n==="CONSTR_EXCLUSION")throw new B({Constraint:t},"EXCLUSION constraints are not supported in SQLite");return ""}FuncCall(t,r){let s=(t.funcname||[]).map(c=>c.String?.sval||c.String?.str).filter(Boolean);if(s.length===0)throw new Error("Function call has no name");let i=s[s.length-1].toLowerCase();if(i==="extract"&&t.args&&t.args.length>=2){let c=t.args[0];if((c?.A_Const?.sval?.sval||c?.String?.sval)==="epoch")return `strftime('%s', ${this.visit(t.args[1],r)})`}let a=(t.args??[]).map(c=>this.visit(c,r));if(t.agg_star)return `${i}(*)`;if(t.agg_distinct)return `${i}(DISTINCT ${a.join(", ")})`;let l=Da(i,this.functionResolution);if(l){if(l.sqliteExpr!==null){let c=l.sqliteExpr;return c.includes("(")?c:`${c}(${a.join(", ")})`}if(l.jsFn!==null){let c=qs[i];if(c?.sqlite){let p=c.sqlite();return p.includes("(")?p:`${p}(${a.join(", ")})`}}}throw new B({FuncCall:t},`Function call "${i}" not supported`)}SQLValueFunction(t,r){switch(t.op){case "SVFOP_CURRENT_TIMESTAMP":return "datetime('now')";case "SVFOP_CURRENT_DATE":return "date('now')";case "SVFOP_CURRENT_TIME":return "time('now')";default:throw new B({SQLValueFunction:t},`SQLValueFunction "${t.op}" not supported`)}}ResTarget(t,r){if(t.indirection&&t.indirection.length>0)throw new B({ResTarget:t},"Indirections are not supported in SQLite");let n=[];return r.update&&t.name?(n.push(this.quoteIfNeeded(t.name)),n.push("="),t.val&&n.push(this.deparse(t.val,r))):r.insertColumns&&t.name?n.push(this.quoteIfNeeded(t.name)):(t.val&&n.push(this.deparse(t.val,r)),t.name&&n.push(this.Alias({aliasname:t.name},r))),n.join(" ")}A_Expr(t,r){if(["AEXPR_OP_ALL","AEXPR_OP_ANY"].includes(t.kind))throw new B({A_Expr:t},"ALL/ANY/SOME comparison operators are not supported. Use NOT EXISTS or IN instead");if(t.name&&t.name.length>0){if(t.name.length>1)throw new B({A_Expr:t},"Schema-qualified OPERATOR() syntax is not supported in SQLite");let n=t.name[0]?.String?.sval||t.name[0]?.String?.str;if(n){if(!t.lexpr||!t.rexpr)throw new B({A_Expr:t},"A_Expr missing left or right expression");if(!Uf.includes(n.toUpperCase()))throw new B({A_Expr:t},`Operator "${n}" is not supported in SQLite`);if(n==="~~"||n==="~~*"){let s=this.visit(t.lexpr,r),i=this.visit(t.rexpr,r);return `${s} LIKE ${i}`}if(n==="!~~"||n==="!~~*"){let s=this.visit(t.lexpr,r),i=this.visit(t.rexpr,r);return `${s} NOT LIKE ${i}`}if(n==="~"||n==="~*"){let s=this.visit(t.lexpr,r),i=this.visit(t.rexpr,r);return `${s} GLOB ${i}`}}}return super.A_Expr(t,r)}IndexStmt(t,r){let n=["CREATE"];t.unique&&n.push("UNIQUE"),n.push("INDEX"),t.if_not_exists&&n.push("IF NOT EXISTS"),t.idxname&&n.push(Is(t.idxname)),n.push("ON"),t.relation&&n.push(this.RangeVar(t.relation,r));let s=(t.indexParams??[]).map(i=>"IndexElem"in i?this.IndexElem(i.IndexElem,r):this.visit(i,r)).filter(Boolean);return n.push(`(${s.join(", ")})`),n.join(" ")}IndexElem(t,r){let n=[];return t.name?n.push(Is(t.name)):t.expr&&n.push(`(${this.visit(t.expr,r)})`),t.ordering==="SORTBY_ASC"&&n.push("ASC"),t.ordering==="SORTBY_DESC"&&n.push("DESC"),t.nulls_ordering==="SORTBY_NULLS_FIRST"&&n.push("NULLS FIRST"),t.nulls_ordering==="SORTBY_NULLS_LAST"&&n.push("NULLS LAST"),n.join(" ")}TypeCast(t,r){if(!t.arg||!t.typeName)return super.TypeCast(t,r);if([...this.helper.walk(t)].filter(({node:o})=>"A_Star"in o).length>0)throw new B({TypeCast:t},"A.* in type casts are not supported in SQLite");if(t.typeName.arrayBounds&&t.typeName.arrayBounds.length>0){if("A_Const"in t.arg&&t.arg.A_Const.sval){let o=t.arg.A_Const.sval.sval;if(o.startsWith("{")&&o.endsWith("}")){let a=t.typeName.names?.map(u=>u.String?.sval).filter(Boolean)??[],l=a.length===2&&a[0]==="pg_catalog"?a[1]:a[0],p=["text","varchar","character varying","char","bpchar","name","uuid"].includes(l?.toLowerCase());try{let u=this.parsePgArrayLiteral(o,p);return `'${JSON.stringify(u).replace(/'/g,"''")}'`}catch{}}}return this.visit(t.arg,r)}let s=this.visit(t.arg,r),i=this.TypeName(t.typeName,r);return `CAST(${s} AS ${i})`}A_ArrayExpr(t,r){let n=Ft(t.elements),s=this.tryExtractStaticArray(n);return s!==void 0?`'${JSON.stringify(s).replace(/'/g,"''")}'`:`json_array(${n.map(o=>this.visit(o,r)).join(", ")})`}tryExtractStaticArray(t){let r=[];for(let n of t)if("A_ArrayExpr"in n){let s=Ft(n.A_ArrayExpr.elements),i=this.tryExtractStaticArray(s);if(i===void 0)return;r.push(i);}else if("A_Const"in n){let s=n.A_Const;if(s.isnull)r.push(null);else if(s.ival)r.push(s.ival.ival);else if(s.fval)r.push(parseFloat(s.fval.fval));else if(s.sval)r.push(s.sval.sval);else if("boolval"in s)r.push(s.boolval.boolval===true);else return}else return;return r}parsePgArrayLiteral(t,r){if(!t.startsWith("{")||!t.endsWith("}"))throw new Error("Not a PG array literal");let n=t.slice(1,-1);if(n.length===0)return [];let s=[],i=0;for(;i<n.length;)if(n[i]==="{"){let o=0,a=i;for(;a<n.length;){if(n[a]==="{")o++;else if(n[a]==="}"&&(o--,o===0))break;a++;}s.push(this.parsePgArrayLiteral(n.slice(i,a+1),r)),i=a+1,n[i]===","&&i++;}else if(n[i]==='"'){let o=i+1,a="";for(;o<n.length&&n[o]!=='"';)n[o]==="\\"&&o++,a+=n[o],o++;s.push(a),i=o+1,n[i]===","&&i++;}else {let o=i;for(;o<n.length&&n[o]!==","&&n[o]!=="}";)o++;if(o===i)throw new Error("Malformed PG array literal");let a=n.slice(i,o);if(a==="NULL")s.push(null);else if(r)s.push(a);else {let l=Number(a);s.push(isNaN(l)?a:l);}i=o,n[i]===","&&i++;}return s}BetweenExpr(t,r){return super.A_Expr(t,r)}AlterTableStmt(t,r){let n=t.cmds??[],s=["AT_EnableRowSecurity","AT_ForceRowSecurity"],i=n.filter(p=>"AlterTableCmd"in p&&!s.includes(p.AlterTableCmd.subtype));if(i.length===0)return "";if(!["OBJECT_TABLE","OBJECT_INDEX","OBJECT_VIEW"].includes(t.objtype))throw new B({AlterTableStmt:t},`AlterTableStmt with objtype ${t.objtype} is not supported`);let o=["AT_AddColumn","AT_DropColumn"],a=["AT_AlterColumnType","AT_SetNotNull","AT_DropNotNull","AT_ColumnDefault","AT_AddConstraint","AT_DropConstraint"],l=[],c=[];for(let p of i){let u=p.AlterTableCmd.subtype;if(o.includes(u)){let f={...t,cmds:[p]};l.push(super.AlterTableStmt(f,r));}else if(a.includes(u))c.push(p.AlterTableCmd);else throw new B({AlterTableStmt:t},`AlterTableCmd with subtype ${u} is not supported in SQLite`)}if(c.length>0){let p=this.getRelationName(t.relation);l.push(this.generateRebuildSql(p,c));}return l.join(`;
194
+ FROM ${U(t)};`,description:`Copy data from ${U(t)} to ${U(l)}`,type:"copy_data"});}i.push({sql:`DROP TABLE ${U(t)};`,description:`Drop old table ${U(t)}`,type:"drop_table"}),i.push({sql:`ALTER TABLE ${U(l)} RENAME TO ${U(t)};`,description:`Rename ${U(l)} to ${U(t)}`,type:"rename_table"});let h=n.indexes.filter(y=>y.table===t);for(let y of h){let E=y.unique?"UNIQUE ":"",T=y.columns.map(v=>U(v)).join(", ");i.push({sql:`CREATE ${E}INDEX ${U(y.name)} ON ${U(t)} (${T});`,description:`Recreate index ${U(y.name)} on ${U(t)}`,type:"add_index"});}let d=n.triggers?.filter(y=>y.table===t)??[];for(let y of d)i.push({sql:`${y.sql};`,description:`Recreate trigger ${U(y.name)} on ${U(t)}`,type:"create_trigger"});let m=s.columns.filter(y=>y.table===t&&y.type==="removed");for(let y of m)o.push({table:t,reason:`column "${y.name}" will be dropped`});let w=s.columns.filter(y=>y.table===t&&y.type==="modified");for(let y of w)y.changes?.type&&o.push({table:t,reason:`column "${y.name}" type changes from ${y.changes.type.from} to ${y.changes.type.to}`}),y.changes?.nullable&&!y.changes.nullable.to&&o.push({table:t,reason:`column "${y.name}" becomes NOT NULL`});return {steps:i,warnings:o}}canSimpleAlter(t,r,n){let s=r.columns.filter(u=>u.table===t),i=s.filter(u=>u.type==="added"),o=s.filter(u=>u.type==="removed"),a=s.filter(u=>u.type==="modified"),l=r.foreign_keys.some(u=>u.table===t);if(o.length>0||a.length>0||l)return {canAlter:false,addedCols:i};let c=n.tables.find(u=>u.name===t);return c&&/\bCHECK\s*\(/i.test(c.sql)?{canAlter:false,addedCols:i}:{canAlter:i.every(u=>{let f=u.column;return this.hasNonConstantDefault(f.default_value)?false:f.nullable||f.default_value!=null})&&i.length>0,addedCols:i}}hasNonConstantDefault(t){if(t==null)return false;let r=t.trim().toUpperCase();return v0.includes(r)}columnDef(t){let r=t.column,n=`${U(r.name)} ${r.type||"TEXT"}`;return r.nullable||(n+=" NOT NULL"),r.default_value!=null&&(n+=` DEFAULT ${r.default_value}`),n}};});function k0(e){let t=e?.GrantStmt??e;return t?.is_grant!==true?false:t.targtype==="ACL_TARGET_ALL_IN_SCHEMA"?t.objtype==="OBJECT_TABLE"||t.objtype==="OBJECT_SEQUENCE":t.targtype==="ACL_TARGET_OBJECT"&&R0.has(t.objtype)}var R0,bi,Qm=g(()=>{fr();Mt();Mt();Km();ht();Xm();gi();Jm();Ym();Lr();ja();Ma();R0=new Set(["OBJECT_TABLE","OBJECT_VIEW","OBJECT_SEQUENCE","OBJECT_SCHEMA"]);bi=class extends Deparser{enums;schemaHandling;warnings=[];helper;config;triggerFunctions=new Map;plpgsqlParser=new di;introspection;functionResolution;serialColumns;constructor(t,{enums:r,schemaHandling:n,introspection:s,serialColumns:i,...o}={}){super(t,o),this.schemaHandling=n??"default",this.enums=r??new Map,this.helper=new mi(t),this.config=o,this.introspection=s,this.functionResolution=o?.functionResolution??"translate",this.serialColumns=i??new WeakSet;}visit(t,r){let n=pr(t);if(n==="GrantStmt"&&k0(t))return "";let s=Ms.get(n);if(s){if(s.react==="error")throw new B({[n]:t},`Unsupported node type: ${n}`);return s.react==="warn"&&this.warnings.push({type:n,node:t}),""}return super.visit(t,r)}deparse(t,r){if(t==null)return null;if(!r){let n=new SqlFormatter;r=new DeparserContext({formatter:n});}return typeof t=="number"||t instanceof Number?t.toString():this.visit(t,r)}RawStmt(t,r){if(!t.stmt||t.stmt.CommentStmt)return "";let n=this.deparse(t.stmt,r);return !n||n.length===0?"":t.stmt_len?n+";":n}RangeVar(t,r){this.ensureRelation(t);let n=this.effectiveSchema(t.schemaname),s=t.relname,i=this.quoteBareIfNeeded(s);n&&(this.schemaHandling==="prefix"?i=`${n}__${s}`:i=`"${n}.${s}"`);let o=t.alias?" "+this.Alias(t.alias,r):"";return i+o}getRelationName(t){this.ensureRelation(t);let r=this.effectiveSchema(t.schemaname),n=t.relname;return r?this.schemaHandling==="prefix"?`${r}__${n}`:`${r}.${n}`:n}quoteBareIfNeeded(t){return /^[A-Za-z_][A-Za-z0-9_]*$/.test(t)?t:`"${t.replace(/"/g,'""')}"`}effectiveSchema(t){if(t){if(this.config.forceDefaultSchema||this.schemaHandling!=="default")return t;if(t!=="public")return t}}ensureRelation(t){let r=this.config.forceDefaultSchema;r&&(!t||typeof t!="object"||r.length===0||t.schemaname||(t.schemaname=r));}CreateStmt(t,r){if(t.inhRelations&&t.inhRelations.length>0)throw new B({CreateStmt:t},"Inheritance is not supported in SQLite");if(t.ofTypename!==void 0)throw new B({CreateStmt:t},"Typed tables (CREATE TABLE ... OF type_name) are not supported. Define columns directly in the CREATE TABLE statement instead.");if(t.options&&t.options.length>0&&(t.options=void 0),!t.tableElts||t.tableElts.length===0)throw new B({CreateStmt:t},"Empty tables are not supported in SQLite. Define at least one column.");return t.accessMethod&&(t.accessMethod=void 0),super.CreateStmt(t,r)+" STRICT"}TableLikeClause(t,r){throw new B({TableLikeClause:t},"CREATE TABLE ... (LIKE ...) is not supported in SQLite. Define the table columns explicitly instead.")}DefElem(t,r){if(["oids","fillfactor",/^autovacuum_/i,"toast_tuple_target","parallel_workers","user_catalog_table"].some(i=>au(t.defname??"",i)))return "";let s=super.DefElem(t,r);throw new B({DefElem:t},`DefElem "${t.defname}" (${s}) not supported`)}TypeName(t,r){if(!t.names)return "";let n=t.names.map(i=>i.String?i.String.sval||i.String.str:"").filter(Boolean);if(n.length===0)return "";let s=n.length===2&&n[0]==="pg_catalog"?n[1]:n.join(".");return t.arrayBounds&&t.arrayBounds.length>0||this.enums.has(s.toLowerCase())?"TEXT":Hf(s)}ColumnDef(t,r){let n=[],s=t.colname;s&&n.push(this.quoteIfNeeded(s));let i=false,o=false,a=null,l=null,c=null,p=false;if(t.typeName){let u=t.typeName.names?.map(d=>d.String?.sval||d.String?.str).filter(Boolean);c=u&&(u.length===2&&u[0]==="pg_catalog"?u[1]:u[0]),i=!!(c&&Ds(c))||this.serialColumns.has(t),p=!!(t.typeName.arrayBounds&&t.typeName.arrayBounds.length>0);let f=Array.isArray(t.typeName.typmods)?t.typeName.typmods:[],h=d=>f[d]?.A_Const?.ival?.ival??f[d]?.A_Const?.val?.ival?.ival;if(c&&js(c)&&f.length>0){let d=h(0);typeof d=="number"&&d>0&&(a={maxLen:d});}if(c&&Fs(c)&&f.length>=2){let d=h(0),m=h(1);typeof d=="number"&&typeof m=="number"&&d>0&&m>=0&&(l={precision:d,scale:m});}if(t.constraints){let d=Array.isArray(t.constraints)?t.constraints:[];o=d.some(m=>m.Constraint?.contype==="CONSTR_PRIMARY"),d.some(m=>m.Constraint?.contype==="CONSTR_IDENTITY")&&(i=true);}n.push(this.TypeName(t.typeName,r));}if(t.constraints){let u=Array.isArray(t.constraints)?t.constraints:[],f=u.map(d=>this.visit(d,r));n.push(...f.filter(Boolean));let h=u.some(d=>d.Constraint?.contype==="CONSTR_CHECK");i&&o&&!h?n.push("AUTOINCREMENT"):i&&!o&&this.warnings.push({type:"ColumnDef",node:{ColumnDef:t},message:`Column "${s}" is serial/auto-increment but not the primary key; SQLite can't auto-increment a non-primary-key column, so it becomes a plain INTEGER (no auto-increment).`});}if(s&&c){let u={isArray:p};a&&(u.lengthConstraint=a.maxLen),l&&(u.numericPrecision=l);let f=this.enums.get(c.toLowerCase());f&&(u.enumValues=f);let m=Wt({schema:"public",table:"",column:s,pgTypeName:c,nullable:true,defaultValue:null,defaultFn:null,isPrimaryKey:o,isUnique:false,isSerial:i},u).checkConstraint();m&&n.push(`CHECK (${m})`);}return n.join(" ")}Constraint(t,r){let n=t.contype;if(n==="CONSTR_IDENTITY"||n==="CONSTR_ATTR_DEFERRABLE"||n==="CONSTR_ATTR_NOT_DEFERRABLE"||n==="CONSTR_ATTR_DEFERRED"||n==="CONSTR_ATTR_IMMEDIATE")return "";if(n==="CONSTR_NULL")return "NULL";if(n==="CONSTR_NOTNULL")return "NOT NULL";if(n==="CONSTR_DEFAULT"&&t.raw_expr){let s=this.visit(t.raw_expr,r);return s.includes("(")&&!s.startsWith("(")?`DEFAULT (${s})`:`DEFAULT ${s}`}if(n==="CONSTR_CHECK"&&t.raw_expr){let s=[];t.conname&&s.push("CONSTRAINT",Ls(t.conname)),s.push("CHECK");let i=this.visit(t.raw_expr,r);return s.push(`(${i})`),s.join(" ")}if(n==="CONSTR_PRIMARY")return t.keys&&t.keys.length>0?`PRIMARY KEY (${Ft(t.keys).map(i=>this.visit(i,r)).join(", ")})`:"PRIMARY KEY";if(n==="CONSTR_UNIQUE")return t.keys&&t.keys.length>0?`UNIQUE (${Ft(t.keys).map(i=>this.visit(i,r)).join(", ")})`:"UNIQUE";if(n==="CONSTR_FOREIGN")return super.Constraint(t,r).replace(/FOREIGN\s+KEY\s+REFERENCES/gi,"REFERENCES");if(n==="CONSTR_GENERATED"&&t.raw_expr)return `GENERATED ALWAYS AS (${this.visit(t.raw_expr,r)}) STORED`;if(n==="CONSTR_EXCLUSION")throw new B({Constraint:t},"EXCLUSION constraints are not supported in SQLite");return ""}FuncCall(t,r){let s=(t.funcname||[]).map(c=>c.String?.sval||c.String?.str).filter(Boolean);if(s.length===0)throw new Error("Function call has no name");let i=s[s.length-1].toLowerCase();if(i==="extract"&&t.args&&t.args.length>=2){let c=t.args[0];if((c?.A_Const?.sval?.sval||c?.String?.sval)==="epoch")return `strftime('%s', ${this.visit(t.args[1],r)})`}let a=(t.args??[]).map(c=>this.visit(c,r));if(t.agg_star)return `${i}(*)`;if(t.agg_distinct)return `${i}(DISTINCT ${a.join(", ")})`;let l=Fa(i,this.functionResolution);if(l){if(l.sqliteExpr!==null){let c=l.sqliteExpr;return c.includes("(")?c:`${c}(${a.join(", ")})`}if(l.jsFn!==null){let c=Hs[i];if(c?.sqlite){let p=c.sqlite();return p.includes("(")?p:`${p}(${a.join(", ")})`}}}throw new B({FuncCall:t},`Function call "${i}" not supported`)}SQLValueFunction(t,r){switch(t.op){case "SVFOP_CURRENT_TIMESTAMP":return "datetime('now')";case "SVFOP_CURRENT_DATE":return "date('now')";case "SVFOP_CURRENT_TIME":return "time('now')";default:throw new B({SQLValueFunction:t},`SQLValueFunction "${t.op}" not supported`)}}ResTarget(t,r){if(t.indirection&&t.indirection.length>0)throw new B({ResTarget:t},"Indirections are not supported in SQLite");let n=[];return r.update&&t.name?(n.push(this.quoteIfNeeded(t.name)),n.push("="),t.val&&n.push(this.deparse(t.val,r))):r.insertColumns&&t.name?n.push(this.quoteIfNeeded(t.name)):(t.val&&n.push(this.deparse(t.val,r)),t.name&&n.push(this.Alias({aliasname:t.name},r))),n.join(" ")}A_Expr(t,r){if(["AEXPR_OP_ALL","AEXPR_OP_ANY"].includes(t.kind))throw new B({A_Expr:t},"ALL/ANY/SOME comparison operators are not supported. Use NOT EXISTS or IN instead");if(t.name&&t.name.length>0){if(t.name.length>1)throw new B({A_Expr:t},"Schema-qualified OPERATOR() syntax is not supported in SQLite");let n=t.name[0]?.String?.sval||t.name[0]?.String?.str;if(n){if(!t.lexpr||!t.rexpr)throw new B({A_Expr:t},"A_Expr missing left or right expression");if(!qf.includes(n.toUpperCase()))throw new B({A_Expr:t},`Operator "${n}" is not supported in SQLite`);if(n==="~~"||n==="~~*"){let s=this.visit(t.lexpr,r),i=this.visit(t.rexpr,r);return `${s} LIKE ${i}`}if(n==="!~~"||n==="!~~*"){let s=this.visit(t.lexpr,r),i=this.visit(t.rexpr,r);return `${s} NOT LIKE ${i}`}if(n==="~"||n==="~*"){let s=this.visit(t.lexpr,r),i=this.visit(t.rexpr,r);return `${s} GLOB ${i}`}}}return super.A_Expr(t,r)}IndexStmt(t,r){let n=["CREATE"];t.unique&&n.push("UNIQUE"),n.push("INDEX"),t.if_not_exists&&n.push("IF NOT EXISTS"),t.idxname&&n.push(Ls(t.idxname)),n.push("ON"),t.relation&&n.push(this.RangeVar(t.relation,r));let s=(t.indexParams??[]).map(i=>"IndexElem"in i?this.IndexElem(i.IndexElem,r):this.visit(i,r)).filter(Boolean);return n.push(`(${s.join(", ")})`),n.join(" ")}IndexElem(t,r){let n=[];return t.name?n.push(Ls(t.name)):t.expr&&n.push(`(${this.visit(t.expr,r)})`),t.ordering==="SORTBY_ASC"&&n.push("ASC"),t.ordering==="SORTBY_DESC"&&n.push("DESC"),t.nulls_ordering==="SORTBY_NULLS_FIRST"&&n.push("NULLS FIRST"),t.nulls_ordering==="SORTBY_NULLS_LAST"&&n.push("NULLS LAST"),n.join(" ")}TypeCast(t,r){if(!t.arg||!t.typeName)return super.TypeCast(t,r);if([...this.helper.walk(t)].filter(({node:o})=>"A_Star"in o).length>0)throw new B({TypeCast:t},"A.* in type casts are not supported in SQLite");if(t.typeName.arrayBounds&&t.typeName.arrayBounds.length>0){if("A_Const"in t.arg&&t.arg.A_Const.sval){let o=t.arg.A_Const.sval.sval;if(o.startsWith("{")&&o.endsWith("}")){let a=t.typeName.names?.map(u=>u.String?.sval).filter(Boolean)??[],l=a.length===2&&a[0]==="pg_catalog"?a[1]:a[0],p=["text","varchar","character varying","char","bpchar","name","uuid"].includes(l?.toLowerCase());try{let u=this.parsePgArrayLiteral(o,p);return `'${JSON.stringify(u).replace(/'/g,"''")}'`}catch{}}}return this.visit(t.arg,r)}let s=this.visit(t.arg,r),i=this.TypeName(t.typeName,r);return `CAST(${s} AS ${i})`}A_ArrayExpr(t,r){let n=Ft(t.elements),s=this.tryExtractStaticArray(n);return s!==void 0?`'${JSON.stringify(s).replace(/'/g,"''")}'`:`json_array(${n.map(o=>this.visit(o,r)).join(", ")})`}tryExtractStaticArray(t){let r=[];for(let n of t)if("A_ArrayExpr"in n){let s=Ft(n.A_ArrayExpr.elements),i=this.tryExtractStaticArray(s);if(i===void 0)return;r.push(i);}else if("A_Const"in n){let s=n.A_Const;if(s.isnull)r.push(null);else if(s.ival)r.push(s.ival.ival);else if(s.fval)r.push(parseFloat(s.fval.fval));else if(s.sval)r.push(s.sval.sval);else if("boolval"in s)r.push(s.boolval.boolval===true);else return}else return;return r}parsePgArrayLiteral(t,r){if(!t.startsWith("{")||!t.endsWith("}"))throw new Error("Not a PG array literal");let n=t.slice(1,-1);if(n.length===0)return [];let s=[],i=0;for(;i<n.length;)if(n[i]==="{"){let o=0,a=i;for(;a<n.length;){if(n[a]==="{")o++;else if(n[a]==="}"&&(o--,o===0))break;a++;}s.push(this.parsePgArrayLiteral(n.slice(i,a+1),r)),i=a+1,n[i]===","&&i++;}else if(n[i]==='"'){let o=i+1,a="";for(;o<n.length&&n[o]!=='"';)n[o]==="\\"&&o++,a+=n[o],o++;s.push(a),i=o+1,n[i]===","&&i++;}else {let o=i;for(;o<n.length&&n[o]!==","&&n[o]!=="}";)o++;if(o===i)throw new Error("Malformed PG array literal");let a=n.slice(i,o);if(a==="NULL")s.push(null);else if(r)s.push(a);else {let l=Number(a);s.push(isNaN(l)?a:l);}i=o,n[i]===","&&i++;}return s}BetweenExpr(t,r){return super.A_Expr(t,r)}AlterTableStmt(t,r){let n=t.cmds??[],s=["AT_EnableRowSecurity","AT_ForceRowSecurity"],i=n.filter(p=>"AlterTableCmd"in p&&!s.includes(p.AlterTableCmd.subtype));if(i.length===0)return "";if(!["OBJECT_TABLE","OBJECT_INDEX","OBJECT_VIEW"].includes(t.objtype))throw new B({AlterTableStmt:t},`AlterTableStmt with objtype ${t.objtype} is not supported`);let o=["AT_AddColumn","AT_DropColumn"],a=["AT_AlterColumnType","AT_SetNotNull","AT_DropNotNull","AT_ColumnDefault","AT_AddConstraint","AT_DropConstraint"],l=[],c=[];for(let p of i){let u=p.AlterTableCmd.subtype;if(o.includes(u)){let f={...t,cmds:[p]};l.push(super.AlterTableStmt(f,r));}else if(a.includes(u))c.push(p.AlterTableCmd);else throw new B({AlterTableStmt:t},`AlterTableCmd with subtype ${u} is not supported in SQLite`)}if(c.length>0){let p=this.getRelationName(t.relation);l.push(this.generateRebuildSql(p,c));}return l.join(`;
193
195
  `)}AlterTableCmd(t,r){if(!["AT_AddColumn","AT_DropColumn"].includes(t.subtype))throw new B({AlterTableCmd:t},`AlterTableCmd with subtype ${t.subtype} is not supported`);return t.subtype==="AT_DropColumn"&&t.behavior?super.AlterTableCmd({...t,behavior:void 0},r):super.AlterTableCmd(t,r)}DefineStmt(t,r){if(t.kind==="OBJECT_AGGREGATE")throw new Error("AGGREGATE definitions are not supported in SQLite");return super.DefineStmt(t,r)}InsertStmt(t,r){if("selectStmt"in t){let s=(t.selectStmt?.SelectStmt?.valuesLists??[]).map(i=>i.List?.items?.map(o=>"SetToDefault"in o));if(s.length===1&&s[0]?.every(i=>i===true))return super.InsertStmt({...t,selectStmt:void 0,cols:void 0},r);if(s.some(i=>i.some(o=>o===true)))throw new B({InsertStmt:t},"Insert with partial DEFAULT values is not supported")}return super.InsertStmt(t,r)}SelectStmt(t,r){if(this.helper.hasUnsafeStar())throw new B({SelectStmt:t},"Row-wise comparison using .* is not supported in SQLite. Expand to explicit per-column comparisons instead.");if(t.intoClause)throw new B({SelectStmt:t},"SELECT ... INTO clause is not supported in SQLite");if(t.distinctClause){let s=Ft(t.distinctClause);if(s.length>0&&Object.keys(s[0]).length>0)throw new B({SelectStmt:t},"DISTINCT ON clause is not supported in SQLite. Use window functions instead.")}if(t.limitOffset&&!t.limitCount)throw new B({SelectStmt:t},"OFFSET without LIMIT is not supported in SQLite");let n=super.SelectStmt(t,r);if(/^SELECT\s+FROM/.test(n))throw new B({SelectStmt:t},"SELECT without a target list is not supported in SQLite");return n}JoinExpr(t,r){return t.alias&&this.Alias(t.alias,r),super.JoinExpr(t,r)}A_Const(t,r){if(t.bsval!==void 0)throw new B({A_Const:t},"Bit string literals are not supported in SQLite");let n=super.A_Const(t,r);return typeof n=="string"&&n.startsWith("E'")?n.substring(2,n.length-1):n}SortBy(t,r){if(t.sortby_dir==="SORTBY_USING"){let n=Ft(t.useOp),s=n[0]?.String?.sval;if(n.length>1||!["<",">"].includes(s??""))throw new B({SortBy:t},"Only `USING <` or `USING >` are supported.");t.sortby_dir=s==="<"?"SORTBY_DESC":"SORTBY_ASC",t.useOp=void 0;}return super.SortBy(t,r)}RangeSubselect(t,r){if(t.lateral)throw new B({RangeSubselect:t},"LATERAL subqueries are not supported in SQLite");return super.RangeSubselect(t,r)}SubLink(t,r){if(["ANY_SUBLINK","ALL_SUBLINK"].includes(t.subLinkType))throw new B({SubLink:t},"ANY/ALL/SOME subqueries are not supported. Use NOT EXISTS or IN instead");if(t.subLinkType==="ARRAY_SUBLINK")throw new B({SubLink:t},"ARRAY subqueries are not supported in SQLite");return super.SubLink(t,r)}LockingClause(t,r){return ""}UpdateStmt(t,r){if(r.parentNodeTypes.includes("SelectStmt"))throw new B({UpdateStmt:t},"UPDATE ... FROM (SELECT ...) is not supported in SQLite");return super.UpdateStmt(t,r)}Alias(t,r){if(t.colnames&&t.colnames.length>0)throw new B({Alias:t},"Aliasing with column names is not supported in SQLite");return `AS "${t.aliasname}"`}CreateFunctionStmt(t,r){let n=t.options??[],s=t.returnType?.names?.map(c=>c.String?.sval).filter(Boolean).join("."),i=n.find(c=>c.DefElem?.defname==="language")?.DefElem?.arg?.String?.sval;if(s!=="trigger"||i!=="plpgsql")throw new B({CreateFunctionStmt:t},"Only trigger functions with LANGUAGE plpgsql are supported");let o=t.funcname?.map(c=>c.String?.sval).filter(Boolean).pop();if(!o)throw new Error("Function has no name");let a=n.find(c=>c.DefElem?.defname==="as")?.DefElem?.arg?.List?.items?.[0]?.String?.sval;if(!a)throw new Error("Function has no body");let l=this.plpgsqlParser.parse(a);return this.triggerFunctions.set(o,l),""}CreateTrigStmt(t,r){let n=t.trigname,s=this.RangeVar(t.relation,r),i=t.funcname?.map(u=>u.String?.sval).filter(Boolean).pop();if(!i)throw new Error(`Trigger "${n}" has no function reference`);let o=this.triggerFunctions.get(i);if(!o)throw new B({CreateTrigStmt:t},`Trigger "${n}" references unknown function "${i}"`);let a=t.timing===2?"BEFORE":t.timing===64?"INSTEAD OF":"AFTER",l=[];if(t.events&4&&l.push("INSERT"),t.events&8&&l.push("DELETE"),t.events&16)if(t.columns?.length){let u=t.columns.map(f=>f.String?.sval).filter(Boolean);l.push(`UPDATE OF ${u.join(", ")}`);}else l.push("UPDATE");let c=l.join(" OR "),p=this.buildTriggerBody(o,s,r);return [`CREATE TRIGGER ${n}`,`${a} ${c} ON ${s}`,"FOR EACH ROW","BEGIN",...p.map(u=>` ${u};`),"END"].join(`
194
- `)}buildTriggerBody(t,r,n){let s=[],i=[];for(let o of t.statements)if(o.type!=="return"){if(o.type==="assignment"){i.push(o);continue}i.length>0&&(s.push(this.buildAssignmentUpdate(i,r,n)),i.length=0),o.type==="dml"&&s.push(this.translateDml(o.sql,n));}return i.length>0&&s.push(this.buildAssignmentUpdate(i,r,n)),s}buildAssignmentUpdate(t,r,n){let s=t.map(i=>{let o=this.translateExpression(i.expression,n);return `${i.column} = ${o}`});return `UPDATE ${r} SET ${s.join(", ")} WHERE rowid = NEW.rowid`}translateExpression(t,r){try{let n=`SELECT ${t}`,s=t.trim().toLowerCase();return s==="now()"||s==="current_timestamp"?"datetime('now')":t}catch{return t}}flattenTriggerTableRef(t,r){let n=this.effectiveSchema(t);return n?this.schemaHandling==="prefix"?`${n}__${r}`:`"${n}.${r}"`:this.quoteBareIfNeeded(r)}translateDml(t,r){let n=/^(\s*)(insert\s+into|update|delete\s+from)\s+(?:"([^"]+)"|(\w+))\s*\.\s*(?:"([^"]+)"|(\w+))/i;return t=t.replace(n,(s,i,o,a,l,c,p)=>`${i}${o} ${this.flattenTriggerTableRef(a??l,c??p)}`),t.replace(/\bnow\(\)/gi,"datetime('now')").replace(/\bcurrent_timestamp\b/gi,"datetime('now')").replace(/\bgen_random_uuid\(\)/gi,this.uuidExpression()).replace(/\buuid_generate_v4\(\)/gi,this.uuidExpression())}uuidExpression(){return "lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))"}NullTest(t,r){if(t.arg?.ColumnRef?.fields?.length>1)throw new B({NullTest:t},"row-level NULL tests are not supported in SQLite");return super.NullTest(t,r)}RenameStmt(t,r){if(!t.renameType)throw new Error("RenameStmt requires renameType");if(t.renameType==="OBJECT_POLICY")return "";let n=["OBJECT_TABLE","OBJECT_VIEW","OBJECT_COLUMN"];if(t.renameType==="OBJECT_COLUMN"&&(t.relationType==="OBJECT_FOREIGN_TABLE"||t.relationType==="OBJECT_VIEW"))throw new B({RenameStmt:t},`RenameStmt with relationType ${t.relationType} is not supported`);if(!n.includes(t.renameType))throw new B({RenameStmt:t},`RenameStmt with renameType ${t.renameType} is not supported in SQLite`);return super.RenameStmt(t,r)}DropStmt(t,r){let n=t.removeType;if(["OBJECT_TABLE","OBJECT_VIEW","OBJECT_INDEX","OBJECT_TRIGGER"].includes(n))return super.DropStmt(t,r);if(["OBJECT_POLICY"].includes(n))return "";throw new B({DropStmt:t},`DROP with removeType ${n} is not supported in SQLite`)}generateRebuildSql(t,r){if(!this.introspection)throw new Error(`ALTER TABLE on "${t}" requires 12-step rebuild but no introspection was provided. Pass introspection in DeparseOptions to enable column type changes, NOT NULL, defaults, and constraint modifications.`);let n=this.buildDesiredSchema(this.introspection,t,r),s=new gi,i=new yi,o=s.diff(this.introspection,n);return o.has_changes?i.plan(o,this.introspection,n).steps.filter(l=>!["disable_foreign_keys","begin_transaction","commit_transaction","enable_foreign_keys"].includes(l.type)).map(l=>l.sql).join(`
195
- `):""}buildDesiredSchema(t,r,n){let s={...t,tables:t.tables.map(i=>({...i})),columns:t.columns.map(i=>({...i})),indexes:t.indexes.map(i=>({...i})),foreign_keys:t.foreign_keys.map(i=>({...i})),primary_keys:t.primary_keys.map(i=>({...i})),views:t.views.map(i=>({...i})),triggers:(t.triggers??[]).map(i=>({...i})),check_constraints:t.check_constraints.map(i=>({...i})),unique_constraints:(t.unique_constraints??[]).map(i=>({...i})),comments:(t.comments??[]).map(i=>({...i})),custom_types:t.custom_types.map(i=>({...i}))};for(let i of n){let o=s.columns.findIndex(a=>a.table===r&&a.name===i.name);switch(i.subtype){case "AT_AlterColumnType":{if(o===-1)break;let a=this.extractTypeName(i);a&&(s.columns[o]={...s.columns[o],type:a.toLowerCase()});break}case "AT_SetNotNull":{if(o===-1)break;s.columns[o]={...s.columns[o],nullable:false};break}case "AT_DropNotNull":{if(o===-1)break;s.columns[o]={...s.columns[o],nullable:true};break}case "AT_ColumnDefault":{if(o===-1)break;if(i.def){let a=this.extractDefaultValue(i);s.columns[o]={...s.columns[o],default_value:a};}else s.columns[o]={...s.columns[o],default_value:null};break}case "AT_AddConstraint":case "AT_DropConstraint":{let a=s.tables.findIndex(l=>l.name===r);a!==-1&&(s.tables[a]={...s.tables[a],sql:s.tables[a].sql+" /* modified */"});break}}}return this.rebuildTableSql(s,r),s}rebuildTableSql(t,r){let n=t.tables.findIndex(u=>u.name===r);if(n===-1)return;let s=t.columns.filter(u=>u.table===r),i=t.foreign_keys.filter(u=>u.table===r),o=t.check_constraints.filter(u=>u.table===r),a=s.map(u=>{let f=`${U(u.name)} ${u.type||"TEXT"}`;return u.is_primary_key&&(f+=" PRIMARY KEY"),u.nullable||(f+=" NOT NULL"),u.default_value!=null&&(f+=` DEFAULT ${u.default_value}`),f}),l=i.map(u=>`FOREIGN KEY (${U(u.column)}) REFERENCES ${U(u.ref_table)}(${U(u.ref_column)}) ON UPDATE ${u.on_update} ON DELETE ${u.on_delete}`),c=o.map(u=>`CHECK (${u.expression})`),p=[...a,...l,...c];t.tables[n]={...t.tables[n],sql:`CREATE TABLE ${U(r)} (${p.join(", ")}) STRICT`};}extractTypeName(t){let r=t.def?.ColumnDef;return r?.typeName?.TypeName?(r.typeName.TypeName.names??[]).map(s=>s.String?.sval).filter(Boolean).pop()??null:null}extractDefaultValue(t){return t.def?"Integer"in t.def?String(t.def.Integer.ival):"Float"in t.def?t.def.Float.fval:"String"in t.def?`'${t.def.String.sval}'`:null:null}};});function Ym(e){return `${e?.schemaname??"public"}.${e?.relname??""}`}function C0(e){let t=e?.Constraint;if(!t||t.contype!=="CONSTR_DEFAULT")return false;let r=t.raw_expr?.FuncCall?.funcname;if(!Array.isArray(r))return false;let n=r.map(s=>s.String?.sval??s.String?.str).filter(Boolean);return n[n.length-1]?.toLowerCase()==="nextval"}function R0(e){return (Array.isArray(e.constraints)?e.constraints:[]).some(r=>r.Constraint?.contype==="CONSTR_IDENTITY")}function Qm(e,t){let r=Array.isArray(e.constraints)?e.constraints:[],n=r.filter(s=>!C0(s));n.length!==r.length?(e.constraints=n,t.add(e)):R0(e)&&t.add(e);}function k0(e,t,r){let n=t?.Constraint;if(!n)return false;let s=n.contype;if(s!=="CONSTR_PRIMARY"&&s!=="CONSTR_UNIQUE"&&s!=="CONSTR_FOREIGN")return false;let i=e.tableElts??[];if(s==="CONSTR_PRIMARY"){let o=(n.keys??[]).map(a=>a.String?.sval??a.String?.str).filter(Boolean);if(o.length===1){let a=i.find(l=>"ColumnDef"in l&&l.ColumnDef.colname===o[0]);if(a&&r.has(a.ColumnDef)){let l=Array.isArray(a.ColumnDef.constraints)?a.ColumnDef.constraints:[];return l.push({Constraint:{contype:"CONSTR_PRIMARY"}}),a.ColumnDef.constraints=l,true}}}return i.push(t),e.tableElts=i,true}function Zm(e){let t=new WeakSet,r=new Map;for(let n of e.stmts??[]){let s=n.stmt;if(!s||!("CreateStmt"in s))continue;let i=s.CreateStmt;r.set(Ym(i.relation),i);for(let o of i.tableElts??[])"ColumnDef"in o&&Qm(o.ColumnDef,t);}for(let n of e.stmts??[]){let s=n.stmt;if(!s||!("AlterTableStmt"in s))continue;let i=s.AlterTableStmt,o=r.get(Ym(i.relation)),a=i.cmds??[],l=[];for(let c of a){let p=c.AlterTableCmd;p?.subtype==="AT_AddColumn"&&p.def&&"ColumnDef"in p.def&&Qm(p.def.ColumnDef,t),!(o&&p?.subtype==="AT_AddConstraint"&&p.def&&k0(o,p.def,t))&&l.push(c);}i.cmds=l;}return t}var ed=g(()=>{});async function Rn(e,t={}){let r=await pi(e);return {ast:r,...P0(r,t)}}function P0(e,t={}){let r=Zm(e),n=Ba(e),s=Wa(e,n),i=qa(e),o=Ga(e),a=za(e),l=new wi(e,{...t,enums:n,serialColumns:r}),{policies:c,tables:p}=Ha(e,{defaultSchema:t.defaultSchema,validateMutations:t.strict});if(t.strict)for(let u of c){if(!s.get(`${u.data.schema??"public"}.${u.data.table}`))throw new Error(`Policy "${u.data.name}" references unknown table "${u.data.table}"`);if(!p.has(u.data.table))throw new Error(`RLS is not enabled on table "${u.data.table}"`)}return {ddl:l.deparseQuery(),enums:n,rls:{tables:p,policies:c},schema:s,vars:i,tableConstraints:o,comments:a}}var bi=g(()=>{Gm();Jm();ed();Sa();Ka();Ea();});async function td(e){if(e.trim())try{await pi(e);}catch(t){let r=t instanceof Error?t.message:String(t);throw new Cl(`Declarative schema (schemas/*.sql) is not valid SQL: ${r}`,{cause:t})}}async function Al(e,t,r,n){if(t.trim())try{let s=t;if(r==="postgres"){let i=await e.translateDdl(t);s=typeof i=="string"?i:i.ddl??"";}for(let i of mt(s))if(i.trim())try{await e.exec(i);}catch(o){if(!n)throw o}}catch(s){if(!n)throw s}}async function rd(e,t){if(!t.trim())return;let r=Le(e.connection);if(r==="pg")return;let n=r==="sqlite"?"sqlite":"postgres",s=await createConnection({url:":memory:",ddlDialect:n,translation:e.connection.config.translation});try{let i=e.connection.config.baseSchema;i&&await Al(s,i,n,!0);for(let o of await Ue(e))await Al(s,o.sql,n,!0);await Al(s,t,n,!1);}finally{await s.close().catch(()=>{});}}var Cl,nd=g(()=>{bi();Rt();wt();Dt();Cl=class extends Error{constructor(t,r){super(t,r),this.name="SchemaParseError";}};});async function L0(){return Vt||(Vt=await import('@sentry/node')),Vt}function D0(){if(id)return;id=true;let e=process.exit.bind(process),t=false;process.exit=(r=>{if(t)return;t=true,Si((r??0)!==0).finally(()=>e(r));});}function ld(e){if(e)return false;let t=process.env.LITE_TELEMETRY;if(t==="0"||t==="false")return false;let r=process.env.DO_NOT_TRACK;return !(r==="1"||r==="true"||process.env.CI||process.env.LOCAL)}function j0(){let e=process.versions;return e.bun?"bun":e.deno?"deno":"node"}function F0(){if(process.env.CODESPACES)return "codespaces";if(process.env.REMOTE_CONTAINERS)return "devcontainer";try{return statSync("/.dockerenv"),"docker"}catch{return}}function M0(e){let t=e/1e6;return t<1?"<1MB":t<10?"1-10MB":t<100?"10-100MB":t<1e3?"100MB-1GB":">1GB"}function U0(e,t){if(e==="sqlite"||e==="sqlite-postgres"||e==="pglite")return !t||t===":memory:"||t.startsWith("file::memory:")?e==="pglite"&&!t?void 0:"memory":t.startsWith("file:")?"file":void 0;if(e==="postgres"){if(!t)return;try{let r=new URL(t).hostname;return r==="localhost"||r==="127.0.0.1"||r==="::1"?"local":"remote"}catch{return "remote"}}}function B0(){try{let e=Me__default.resolve(process.cwd(),ye.config_dir,"config.toml"),t;try{t=readFileSync(e,"utf-8");}catch{return {}}let r;try{r=Ct(t);}catch{return {}}let n=r.db?.driver,s=n==="sqlite"||n==="sqlite-postgres"||n==="pglite"||n==="postgres"?n:"sqlite-postgres",i=r.db?.url??ye.default_db_url,o=U0(s,i),a;if(o==="file"&&i.startsWith("file:"))try{let l=i.startsWith("file://")?i.slice(7):i.slice(5),c=Me__default.resolve(process.cwd(),l);a=statSync(c).size;}catch{}return {driver:s,location:o,sizeBytes:a}}catch{return {}}}async function cd(e){if(br)return;br=true;let t=await L0(),{version:r}=await Yn();t.init({dsn:I0,release:`@supabase/lite@${r}`,sendDefaultPii:false,defaultIntegrations:false,integrations:[t.httpIntegration()],tracesSampleRate:1,tracePropagationTargets:["sentry.io"],beforeSend(i){return delete i.server_name,i.user&&delete i.user.ip_address,i},beforeSendTransaction(i){return delete i.server_name,i.user&&delete i.user.ip_address,i}}),t.setTag("command",e.command),t.setTag("runtime",j0()),t.setTag("node",process.version),t.setTag("platform",process.platform),t.setTag("arch",process.arch),t.setTag("ci",!!process.env.CI);let n=F0();n&&t.setTag("container",n);try{let{determineAgent:i}=await import('@vercel/detect-agent'),o=await i();o.isAgent&&t.setTag("agent",o.agent.name);}catch{}let s=B0();s.driver&&t.setTag("db.driver",s.driver),s.location&&t.setTag("db.location",s.location),typeof s.sizeBytes=="number"&&t.setTag("db.size",M0(s.sizeBytes));for(let[i,o]of Object.entries(e.args))t.setTag(`arg.${i}`,!!o);t.startSession(),ad=true,zt=t.startInactiveSpan({name:`cli:${e.command}`,op:"cli.command",forceTransaction:true}),D0();}async function Si(e,t){if(!br)return;let r=Vt;try{if(e&&(r.setTag("status","failed"),t instanceof Error&&r.setTag("error_class",t.constructor.name)),zt&&(zt.setStatus({code:e?2:1,message:e?"internal_error":"ok"}),zt.end(),zt=void 0),ad){let n=r.getCurrentScope().getSession();n&&e&&(n.status="crashed"),r.endSession();}}finally{await r.flush(2e3).catch(()=>{});}}function kn(e,t){if(!br)return Promise.resolve(t());let r=Vt,n=()=>r.startSpan({name:e,op:"cli.step"},t);return zt?r.withActiveSpan(zt,n):n()}function Rl(e,t){br&&Vt.setTag(e,t);}function ud(e,t){if(!br)return;let r=Vt;try{r.captureException(e,{tags:{translation_gap:!0,"db.variant":t.variant,error_class:e instanceof Error?e.constructor.name:"unknown"},contexts:{translation_gap:{variant:t.variant,failing_sql:t.failingSql?t.failingSql.slice(0,4e3):void 0}}});}catch{}}var I0,Vt,br,ad,zt,id,Ei=g(()=>{Rr();Zt();$e();I0="https://9562525a4ea320539ea7e94859533a17@o398706.ingest.us.sentry.io/4511381939290112";br=false,ad=false,id=false;});var md={};de(md,{checkPendingDeclarativeSchema:()=>fd,db:()=>G0});function W0(){console.log(fe.default.yellow("Declarative diff includes potentially destructive changes.")),console.log(fe.default.dim("Review the schema manually and author an explicit migration for drops or other data-loss changes."));}async function fd(e,t){let r=await ge(e);if(!r)return {hint:false,reason:"no-schemas"};try{let s=await e.connection.createMigrator(r).diff();return (typeof s.diff=="string"?s.diff.trim().length>0:s.diff.has_changes)?{hint:!0,reason:"pending"}:{hint:!1,reason:"in-sync"}}catch{return {hint:false,reason:"diff-failed"}}}async function pd(e){let t=await at(e),r=await ge(t);if(!r&&!t.connection.config.baseSchema){console.log(fe.default.dim("No schema files found."));return}let s=await t.connection.createMigrator(r).diff();if(typeof s.diff!="string"&&!s.diff.has_changes){console.log(fe.default.dim("Schema in sync."));return}dr(s);}var fe,H0,G0,dd=g(()=>{fe=te(ae());De();tl();Ye();wt();Wm();$e();ot();Tt();er();Rt();Gs();Ye();Dt();nd();Ei();H0="Local Development:";G0=e=>{let t=e.command("db").description("Database operations").helpGroup(H0);t.command("diff").description("Diff current DB against schemas/*.sql; with -f, emit a pg migration file").option("--config <config>","Path to the config file").option("-f, --file <name>","Write the diff as a new migration file with this name").action(async r=>{console.log(),await J(async()=>{if(await Q(r.config),!r.file){await pd(r.config);return}let n=await at(r.config),s=await ge(n);if(!s.trim()){console.log(fe.default.dim("No declarative schemas found \u2014 nothing to diff."));return}await td(s);let i=Le(n.connection);if(i==="sqlite"){console.log(fe.default.yellow('`lite db diff -f` is not supported on the bare "sqlite" driver yet.')),console.log(fe.default.dim('Declarative schema diffs require the "sqlite-postgres" driver. Set db.driver = "sqlite-postgres" in supabase/config.toml.'));return}let o;{let p=await Ns(n);try{o=await Hm(p,s,n.connection.config.baseSchema??"");}catch(u){throw u instanceof DataLossError?(W0(),new Error("Declarative diff includes potentially destructive changes.")):u}if(!o.trim()){console.log(fe.default.green("Schema in sync \u2014 no migration written."));return}}try{await rd(n,o);}catch(p){ud(p,{variant:i,failingSql:o});let u=p instanceof Error?p.message:String(p);throw new Error(`Generated migration does not run on the "${i}" backend and was not written: ${u}. This likely indicates a gap in supalite's Postgres\u2192SQLite translation; it has been reported.`)}let a=Me__default.join(process.cwd(),"supabase",jt(n));ke(a);let l=ba(r.file,wa()),c=Me__default.join(a,l);await pe__default.writeFile(c,o+`
196
- `,{flag:"wx"}),console.log(fe.default.green(" \u279C"),"Wrote migration",fe.default.cyan(Me__default.relative(process.cwd(),c)));});}),t.command("reset").description(be("Drop user objects, clear history, replay migrations + seed")).option("--config <config>","Path to the config file").option("--no-seed","Skip running seed.sql after replay").option("--hard","Delete and recreate the local DB file/dir instead of dropping objects via SQL",false).action(async r=>{console.log(),await J(async()=>{if(await Q(r.config),r.hard){let l=await es(r.config);if(l){await pe__default.rm(l,{recursive:!0,force:!0});for(let c of ["-wal","-shm","-journal"])await pe__default.rm(`${l}${c}`,{force:!0});console.log(fe.default.dim(` \u279C removed ${Me__default.relative(process.cwd(),l)}`));}else console.log(fe.default.dim("--hard: no local database file to delete; resetting via SQL."));}let n=await at(r.config),s=n.connection.dialect==="postgres",i=[];if(s){let{rows:l}=await n.connection.exec(`SELECT nspname AS name FROM pg_namespace
197
- WHERE nspname NOT LIKE 'pg\\_%' AND nspname <> 'information_schema'`);for(let c of l)i.push(`DROP SCHEMA IF EXISTS "${c.name.replace(/"/g,'""')}" CASCADE`);i.push("CREATE SCHEMA IF NOT EXISTS public AUTHORIZATION pg_database_owner");}else {let c=(await n.connection.introspect()).tables.filter(u=>u.type==="table"),p=(u,f)=>`"${u?`${u}.${f}`:f}"`;for(let u of c)i.push(`DROP TABLE IF EXISTS ${p(u.schema,u.name)}`);i.push("DROP TABLE IF EXISTS migrations"),i.push("DROP TABLE IF EXISTS seed_files"),i.push('DROP TABLE IF EXISTS "supabase_migrations.schema_migrations"'),i.push('DROP TABLE IF EXISTS "supabase_migrations.seed_files"');}for(let l of i)try{await n.connection.exec(l);}catch{}await n.connection.clearSchemaCache(),await rm();let o=await Gt(n);for(let l of o.applied)console.log(fe.default.green(" \u2713"),"Applied",fe.default.cyan(l.filename));(await fd(n,o.applied.length)).hint&&(console.log(),console.log(fe.default.yellow("Declarative schemas detected with pending changes.")),console.log(fe.default.dim("Run `lite db diff -f <name>` to generate a migration, then re-run `lite db reset`."))),r.seed!==!1&&await bn(n).catch(l=>console.error(fe.default.yellow("Seed warning: "+String(l)))),console.log(fe.default.green("Database reset."));});}),t.command("translate").description("Translate Postgres SQL to this project's backend dialect").argument("[sql]","SQL to translate; reads stdin if omitted").option("--config <config>","Path to the config file").action(async(r,n)=>{await J(async()=>{await Q(n.config);let s=await at(n.config);try{let i=r??await qi(),o=await s.connection.translateDdl(i),a=typeof o=="string"?o:o.ddl??"";console.log(a);}finally{await s.connection.close();}});}),t.command("query").description("Execute a SQL statement against the local or remote project").argument("[statement]","The statement to execute; reads stdin if omitted").option("--remote","Execute the statement on the remote project",false).option("--config <config>","Path to the config file").action(async(r,n)=>{await J(async()=>{n.remote||await Q(n.config);let s=await at(n.remote?!0:n.config);try{if(r){Ze(`Executing: ${fe.default.cyan(r)}`);let o=await s.connection.exec(r);console.log(o);return}let i=await qi();for(let o of mt(i)){if(!o.trim())continue;let a=await s.connection.exec(o);console.log(a);}}finally{await s.connection.close();}});}),t.command("schema").description(be("Print the current database schema")).option("--diff","Diff current DB against schemas/*.sql",false).option("--sql","Print raw CREATE statements from sqlite_master",false).option("--config <config>","Path to the config file").action(async r=>{console.log(),await J(async()=>{if(await Q(r.config),r.diff){await pd(r.config);return}let s=await(await at(r.config)).connection.introspect();if(r.sql){let i=[...s.tables.map(o=>o.sql),...s.views.map(o=>o.sql),...s.triggers.map(o=>o.sql)].filter(o=>o&&o.trim().length>0);console.log(i.join(`;
196
+ `)}buildTriggerBody(t,r,n){let s=[],i=[];for(let o of t.statements)if(o.type!=="return"){if(o.type==="assignment"){i.push(o);continue}i.length>0&&(s.push(this.buildAssignmentUpdate(i,r,n)),i.length=0),o.type==="dml"&&s.push(this.translateDml(o.sql,n));}return i.length>0&&s.push(this.buildAssignmentUpdate(i,r,n)),s}buildAssignmentUpdate(t,r,n){let s=t.map(i=>{let o=this.translateExpression(i.expression,n);return `${i.column} = ${o}`});return `UPDATE ${r} SET ${s.join(", ")} WHERE rowid = NEW.rowid`}translateExpression(t,r){try{let n=`SELECT ${t}`,s=t.trim().toLowerCase();return s==="now()"||s==="current_timestamp"?"datetime('now')":t}catch{return t}}flattenTriggerTableRef(t,r){let n=this.effectiveSchema(t);return n?this.schemaHandling==="prefix"?`${n}__${r}`:`"${n}.${r}"`:this.quoteBareIfNeeded(r)}translateDml(t,r){let n=/^(\s*)(insert\s+into|update|delete\s+from)\s+(?:"([^"]+)"|(\w+))\s*\.\s*(?:"([^"]+)"|(\w+))/i;return t=t.replace(n,(s,i,o,a,l,c,p)=>`${i}${o} ${this.flattenTriggerTableRef(a??l,c??p)}`),t.replace(/\bnow\(\)/gi,"datetime('now')").replace(/\bcurrent_timestamp\b/gi,"datetime('now')").replace(/\bgen_random_uuid\(\)/gi,this.uuidExpression()).replace(/\buuid_generate_v4\(\)/gi,this.uuidExpression())}uuidExpression(){return "lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))"}NullTest(t,r){if(t.arg?.ColumnRef?.fields?.length>1)throw new B({NullTest:t},"row-level NULL tests are not supported in SQLite");return super.NullTest(t,r)}RenameStmt(t,r){if(!t.renameType)throw new Error("RenameStmt requires renameType");if(t.renameType==="OBJECT_POLICY")return "";let n=["OBJECT_TABLE","OBJECT_VIEW","OBJECT_COLUMN"];if(t.renameType==="OBJECT_COLUMN"&&(t.relationType==="OBJECT_FOREIGN_TABLE"||t.relationType==="OBJECT_VIEW"))throw new B({RenameStmt:t},`RenameStmt with relationType ${t.relationType} is not supported`);if(!n.includes(t.renameType))throw new B({RenameStmt:t},`RenameStmt with renameType ${t.renameType} is not supported in SQLite`);return super.RenameStmt(t,r)}DropStmt(t,r){let n=t.removeType;if(["OBJECT_TABLE","OBJECT_VIEW","OBJECT_INDEX","OBJECT_TRIGGER"].includes(n))return super.DropStmt(t,r);if(["OBJECT_POLICY"].includes(n))return "";throw new B({DropStmt:t},`DROP with removeType ${n} is not supported in SQLite`)}generateRebuildSql(t,r){if(!this.introspection)throw new Error(`ALTER TABLE on "${t}" requires 12-step rebuild but no introspection was provided. Pass introspection in DeparseOptions to enable column type changes, NOT NULL, defaults, and constraint modifications.`);let n=this.buildDesiredSchema(this.introspection,t,r),s=new yi,i=new wi,o=s.diff(this.introspection,n);return o.has_changes?i.plan(o,this.introspection,n).steps.filter(l=>!["disable_foreign_keys","begin_transaction","commit_transaction","enable_foreign_keys"].includes(l.type)).map(l=>l.sql).join(`
197
+ `):""}buildDesiredSchema(t,r,n){let s={...t,tables:t.tables.map(i=>({...i})),columns:t.columns.map(i=>({...i})),indexes:t.indexes.map(i=>({...i})),foreign_keys:t.foreign_keys.map(i=>({...i})),primary_keys:t.primary_keys.map(i=>({...i})),views:t.views.map(i=>({...i})),triggers:(t.triggers??[]).map(i=>({...i})),check_constraints:t.check_constraints.map(i=>({...i})),unique_constraints:(t.unique_constraints??[]).map(i=>({...i})),comments:(t.comments??[]).map(i=>({...i})),custom_types:t.custom_types.map(i=>({...i}))};for(let i of n){let o=s.columns.findIndex(a=>a.table===r&&a.name===i.name);switch(i.subtype){case "AT_AlterColumnType":{if(o===-1)break;let a=this.extractTypeName(i);a&&(s.columns[o]={...s.columns[o],type:a.toLowerCase()});break}case "AT_SetNotNull":{if(o===-1)break;s.columns[o]={...s.columns[o],nullable:false};break}case "AT_DropNotNull":{if(o===-1)break;s.columns[o]={...s.columns[o],nullable:true};break}case "AT_ColumnDefault":{if(o===-1)break;if(i.def){let a=this.extractDefaultValue(i);s.columns[o]={...s.columns[o],default_value:a};}else s.columns[o]={...s.columns[o],default_value:null};break}case "AT_AddConstraint":case "AT_DropConstraint":{let a=s.tables.findIndex(l=>l.name===r);a!==-1&&(s.tables[a]={...s.tables[a],sql:s.tables[a].sql+" /* modified */"});break}}}return this.rebuildTableSql(s,r),s}rebuildTableSql(t,r){let n=t.tables.findIndex(u=>u.name===r);if(n===-1)return;let s=t.columns.filter(u=>u.table===r),i=t.foreign_keys.filter(u=>u.table===r),o=t.check_constraints.filter(u=>u.table===r),a=s.map(u=>{let f=`${U(u.name)} ${u.type||"TEXT"}`;return u.is_primary_key&&(f+=" PRIMARY KEY"),u.nullable||(f+=" NOT NULL"),u.default_value!=null&&(f+=` DEFAULT ${u.default_value}`),f}),l=i.map(u=>`FOREIGN KEY (${U(u.column)}) REFERENCES ${U(u.ref_table)}(${U(u.ref_column)}) ON UPDATE ${u.on_update} ON DELETE ${u.on_delete}`),c=o.map(u=>`CHECK (${u.expression})`),p=[...a,...l,...c];t.tables[n]={...t.tables[n],sql:`CREATE TABLE ${U(r)} (${p.join(", ")}) STRICT`};}extractTypeName(t){let r=t.def?.ColumnDef;return r?.typeName?.TypeName?(r.typeName.TypeName.names??[]).map(s=>s.String?.sval).filter(Boolean).pop()??null:null}extractDefaultValue(t){return t.def?"Integer"in t.def?String(t.def.Integer.ival):"Float"in t.def?t.def.Float.fval:"String"in t.def?`'${t.def.String.sval}'`:null:null}};});function Zm(e){return `${e?.schemaname??"public"}.${e?.relname??""}`}function P0(e){let t=e?.Constraint;if(!t||t.contype!=="CONSTR_DEFAULT")return false;let r=t.raw_expr?.FuncCall?.funcname;if(!Array.isArray(r))return false;let n=r.map(s=>s.String?.sval??s.String?.str).filter(Boolean);return n[n.length-1]?.toLowerCase()==="nextval"}function O0(e){return (Array.isArray(e.constraints)?e.constraints:[]).some(r=>r.Constraint?.contype==="CONSTR_IDENTITY")}function ed(e,t){let r=Array.isArray(e.constraints)?e.constraints:[],n=r.filter(s=>!P0(s));n.length!==r.length?(e.constraints=n,t.add(e)):O0(e)&&t.add(e);}function N0(e,t,r){let n=t?.Constraint;if(!n)return false;let s=n.contype;if(s!=="CONSTR_PRIMARY"&&s!=="CONSTR_UNIQUE"&&s!=="CONSTR_FOREIGN")return false;let i=e.tableElts??[];if(s==="CONSTR_PRIMARY"){let o=(n.keys??[]).map(a=>a.String?.sval??a.String?.str).filter(Boolean);if(o.length===1){let a=i.find(l=>"ColumnDef"in l&&l.ColumnDef.colname===o[0]);if(a&&r.has(a.ColumnDef)){let l=Array.isArray(a.ColumnDef.constraints)?a.ColumnDef.constraints:[];return l.push({Constraint:{contype:"CONSTR_PRIMARY"}}),a.ColumnDef.constraints=l,true}}}return i.push(t),e.tableElts=i,true}function td(e){let t=new WeakSet,r=new Map;for(let n of e.stmts??[]){let s=n.stmt;if(!s||!("CreateStmt"in s))continue;let i=s.CreateStmt;r.set(Zm(i.relation),i);for(let o of i.tableElts??[])"ColumnDef"in o&&ed(o.ColumnDef,t);}for(let n of e.stmts??[]){let s=n.stmt;if(!s||!("AlterTableStmt"in s))continue;let i=s.AlterTableStmt,o=r.get(Zm(i.relation)),a=i.cmds??[],l=[];for(let c of a){let p=c.AlterTableCmd;p?.subtype==="AT_AddColumn"&&p.def&&"ColumnDef"in p.def&&ed(p.def.ColumnDef,t),!(o&&p?.subtype==="AT_AddConstraint"&&p.def&&N0(o,p.def,t))&&l.push(c);}i.cmds=l;}return t}var rd=g(()=>{});async function kn(e,t={}){let r=await fi(e);return {ast:r,...I0(r,t)}}function I0(e,t={}){let r=td(e),n=Ha(e),s=za(e,n),i=Wa(e),o=Va(e),a=Ka(e),l=new bi(e,{...t,enums:n,serialColumns:r}),{policies:c,tables:p}=Ga(e,{defaultSchema:t.defaultSchema,validateMutations:t.strict});if(t.strict)for(let u of c){if(!s.get(`${u.data.schema??"public"}.${u.data.table}`))throw new Error(`Policy "${u.data.name}" references unknown table "${u.data.table}"`);if(!p.has(u.data.table))throw new Error(`RLS is not enabled on table "${u.data.table}"`)}return {ddl:l.deparseQuery(),enums:n,rls:{tables:p,policies:c},schema:s,vars:i,tableConstraints:o,comments:a}}var Si=g(()=>{Vm();Qm();rd();xa();Ja();_a();});async function nd(e){if(e.trim())try{await fi(e);}catch(t){let r=t instanceof Error?t.message:String(t);throw new kl(`Declarative schema (schemas/*.sql) is not valid SQL: ${r}`,{cause:t})}}async function Rl(e,t,r,n){if(t.trim())try{let s=t;if(r==="postgres"){let i=await e.translateDdl(t);s=typeof i=="string"?i:i.ddl??"";}for(let i of mt(s))if(i.trim())try{await e.exec(i);}catch(o){if(!n)throw o}}catch(s){if(!n)throw s}}async function sd(e,t){if(!t.trim())return;let r=Le(e.connection);if(r==="pg")return;let n=r==="sqlite"?"sqlite":"postgres",s=await createConnection({url:":memory:",ddlDialect:n,translation:e.connection.config.translation});try{let i=e.connection.config.baseSchema;i&&await Rl(s,i,n,!0);for(let o of await Ue(e))await Rl(s,o.sql,n,!0);await Rl(s,t,n,!1);}finally{await s.close().catch(()=>{});}}var kl,id=g(()=>{Si();Rt();wt();Dt();kl=class extends Error{constructor(t,r){super(t,r),this.name="SchemaParseError";}};});async function F0(){return Vt||(Vt=await import('@sentry/node')),Vt}function M0(){if(ad)return;ad=true;let e=process.exit.bind(process),t=false;process.exit=(r=>{if(t)return;t=true,Ei((r??0)!==0).finally(()=>e(r));});}function ud(e){if(e)return false;let t=process.env.LITE_TELEMETRY;if(t==="0"||t==="false")return false;let r=process.env.DO_NOT_TRACK;return !(r==="1"||r==="true"||process.env.CI||process.env.LOCAL)}function U0(){let e=process.versions;return e.bun?"bun":e.deno?"deno":"node"}function B0(){if(process.env.CODESPACES)return "codespaces";if(process.env.REMOTE_CONTAINERS)return "devcontainer";try{return statSync("/.dockerenv"),"docker"}catch{return}}function q0(e){let t=e/1e6;return t<1?"<1MB":t<10?"1-10MB":t<100?"10-100MB":t<1e3?"100MB-1GB":">1GB"}function H0(e,t){if(e==="sqlite"||e==="sqlite-postgres"||e==="pglite")return !t||t===":memory:"||t.startsWith("file::memory:")?e==="pglite"&&!t?void 0:"memory":t.startsWith("file:")?"file":void 0;if(e==="postgres"){if(!t)return;try{let r=new URL(t).hostname;return r==="localhost"||r==="127.0.0.1"||r==="::1"?"local":"remote"}catch{return "remote"}}}function W0(){try{let e=Me__default.resolve(process.cwd(),ye.config_dir,"config.toml"),t;try{t=readFileSync(e,"utf-8");}catch{return {}}let r;try{r=Ct(t);}catch{return {}}let n=r.db?.driver,s=n==="sqlite"||n==="sqlite-postgres"||n==="pglite"||n==="postgres"?n:"sqlite-postgres",i=r.db?.url??ye.default_db_url,o=H0(s,i),a;if(o==="file"&&i.startsWith("file:"))try{let l=i.startsWith("file://")?i.slice(7):i.slice(5),c=Me__default.resolve(process.cwd(),l);a=statSync(c).size;}catch{}return {driver:s,location:o,sizeBytes:a}}catch{return {}}}async function pd(e){if(br)return;br=true;let t=await F0(),{version:r}=await Qn();t.init({dsn:j0,release:`@supabase/lite@${r}`,sendDefaultPii:false,defaultIntegrations:false,integrations:[t.httpIntegration()],tracesSampleRate:1,tracePropagationTargets:["sentry.io"],beforeSend(i){return delete i.server_name,i.user&&delete i.user.ip_address,i},beforeSendTransaction(i){return delete i.server_name,i.user&&delete i.user.ip_address,i}}),t.setTag("command",e.command),t.setTag("runtime",U0()),t.setTag("node",process.version),t.setTag("platform",process.platform),t.setTag("arch",process.arch),t.setTag("ci",!!process.env.CI);let n=B0();n&&t.setTag("container",n);try{let{determineAgent:i}=await import('@vercel/detect-agent'),o=await i();o.isAgent&&t.setTag("agent",o.agent.name);}catch{}let s=W0();s.driver&&t.setTag("db.driver",s.driver),s.location&&t.setTag("db.location",s.location),typeof s.sizeBytes=="number"&&t.setTag("db.size",q0(s.sizeBytes));for(let[i,o]of Object.entries(e.args))t.setTag(`arg.${i}`,!!o);t.startSession(),cd=true,zt=t.startInactiveSpan({name:`cli:${e.command}`,op:"cli.command",forceTransaction:true}),M0();}async function Ei(e,t){if(!br)return;let r=Vt;try{if(e&&(r.setTag("status","failed"),t instanceof Error&&r.setTag("error_class",t.constructor.name)),zt&&(zt.setStatus({code:e?2:1,message:e?"internal_error":"ok"}),zt.end(),zt=void 0),cd){let n=r.getCurrentScope().getSession();n&&e&&(n.status="crashed"),r.endSession();}}finally{await r.flush(2e3).catch(()=>{});}}function Pn(e,t){if(!br)return Promise.resolve(t());let r=Vt,n=()=>r.startSpan({name:e,op:"cli.step"},t);return zt?r.withActiveSpan(zt,n):n()}function Pl(e,t){br&&Vt.setTag(e,t);}function fd(e,t){if(!br)return;let r=Vt;try{r.captureException(e,{tags:{translation_gap:!0,"db.variant":t.variant,error_class:e instanceof Error?e.constructor.name:"unknown"},contexts:{translation_gap:{variant:t.variant,failing_sql:t.failingSql?t.failingSql.slice(0,4e3):void 0}}});}catch{}}var j0,Vt,br,cd,zt,ad,xi=g(()=>{Rr();Zt();$e();j0="https://9562525a4ea320539ea7e94859533a17@o398706.ingest.us.sentry.io/4511381939290112";br=false,cd=false,ad=false;});var hd={};de(hd,{checkPendingDeclarativeSchema:()=>dd,db:()=>K0});function V0(){console.log(fe.default.yellow("Declarative diff includes potentially destructive changes.")),console.log(fe.default.dim("Review the schema manually and author an explicit migration for drops or other data-loss changes."));}async function dd(e,t){let r=await ge(e);if(!r)return {hint:false,reason:"no-schemas"};try{let s=await e.connection.createMigrator(r).diff();return (typeof s.diff=="string"?s.diff.trim().length>0:s.diff.has_changes)?{hint:!0,reason:"pending"}:{hint:!1,reason:"in-sync"}}catch{return {hint:false,reason:"diff-failed"}}}async function md(e){let t=await at(e),r=await ge(t);if(!r&&!t.connection.config.baseSchema){console.log(fe.default.dim("No schema files found."));return}let s=await t.connection.createMigrator(r).diff();if(typeof s.diff!="string"&&!s.diff.has_changes){console.log(fe.default.dim("Schema in sync."));return}dr(s);}var fe,z0,K0,gd=g(()=>{fe=te(ae());De();nl();Ye();wt();zm();$e();ot();Tt();er();Rt();zs();Ye();Dt();id();xi();z0="Local Development:";K0=e=>{let t=e.command("db").description("Database operations").helpGroup(z0);t.command("diff").description("Diff current DB against schemas/*.sql; with -f, emit a pg migration file").option("--config <config>","Path to the config file").option("-f, --file <name>","Write the diff as a new migration file with this name").action(async r=>{console.log(),await J(async()=>{if(await Q(r.config),!r.file){await md(r.config);return}let n=await at(r.config),s=await ge(n);if(!s.trim()){console.log(fe.default.dim("No declarative schemas found \u2014 nothing to diff."));return}await nd(s);let i=Le(n.connection);if(i==="sqlite"){console.log(fe.default.yellow('`lite db diff -f` is not supported on the bare "sqlite" driver yet.')),console.log(fe.default.dim('Declarative schema diffs require the "sqlite-postgres" driver. Set db.driver = "sqlite-postgres" in supabase/config.toml.'));return}let o;{let p=await Is(n);try{o=await Gm(p,s,n.connection.config.baseSchema??"");}catch(u){throw u instanceof DataLossError?(V0(),new Error("Declarative diff includes potentially destructive changes.")):u}if(!o.trim()){console.log(fe.default.green("Schema in sync \u2014 no migration written."));return}}try{await sd(n,o);}catch(p){fd(p,{variant:i,failingSql:o});let u=p instanceof Error?p.message:String(p);throw new Error(`Generated migration does not run on the "${i}" backend and was not written: ${u}. This likely indicates a gap in supalite's Postgres\u2192SQLite translation; it has been reported.`)}let a=Me__default.join(process.cwd(),"supabase",jt(n));ke(a);let l=Ea(r.file,Sa()),c=Me__default.join(a,l);await pe__default.writeFile(c,o+`
198
+ `,{flag:"wx"}),console.log(fe.default.green(" \u279C"),"Wrote migration",fe.default.cyan(Me__default.relative(process.cwd(),c)));});}),t.command("reset").description(be("Drop user objects, clear history, replay migrations + seed")).option("--config <config>","Path to the config file").option("--no-seed","Skip running seed.sql after replay").option("--hard","Delete and recreate the local DB file/dir instead of dropping objects via SQL",false).action(async r=>{console.log(),await J(async()=>{if(await Q(r.config),r.hard){let l=await ts(r.config);if(l){await pe__default.rm(l,{recursive:!0,force:!0});for(let c of ["-wal","-shm","-journal"])await pe__default.rm(`${l}${c}`,{force:!0});console.log(fe.default.dim(` \u279C removed ${Me__default.relative(process.cwd(),l)}`));}else console.log(fe.default.dim("--hard: no local database file to delete; resetting via SQL."));}let n=await at(r.config),s=n.connection.dialect==="postgres",i=[];if(s){let{rows:l}=await n.connection.exec(`SELECT nspname AS name FROM pg_namespace
199
+ WHERE nspname NOT LIKE 'pg\\_%' AND nspname <> 'information_schema'`);for(let c of l)i.push(`DROP SCHEMA IF EXISTS "${c.name.replace(/"/g,'""')}" CASCADE`);i.push("CREATE SCHEMA IF NOT EXISTS public AUTHORIZATION pg_database_owner");}else {let c=(await n.connection.introspect()).tables.filter(u=>u.type==="table"),p=(u,f)=>`"${u?`${u}.${f}`:f}"`;for(let u of c)i.push(`DROP TABLE IF EXISTS ${p(u.schema,u.name)}`);i.push("DROP TABLE IF EXISTS migrations"),i.push("DROP TABLE IF EXISTS seed_files"),i.push('DROP TABLE IF EXISTS "supabase_migrations.schema_migrations"'),i.push('DROP TABLE IF EXISTS "supabase_migrations.seed_files"');}for(let l of i)try{await n.connection.exec(l);}catch{}await n.connection.clearSchemaCache(),await sm();let o=await Gt(n);for(let l of o.applied)console.log(fe.default.green(" \u2713"),"Applied",fe.default.cyan(l.filename));(await dd(n,o.applied.length)).hint&&(console.log(),console.log(fe.default.yellow("Declarative schemas detected with pending changes.")),console.log(fe.default.dim("Run `lite db diff -f <name>` to generate a migration, then re-run `lite db reset`."))),r.seed!==!1&&await Sn(n).catch(l=>console.error(fe.default.yellow("Seed warning: "+String(l)))),console.log(fe.default.green("Database reset."));});}),t.command("translate").description("Translate Postgres SQL to this project's backend dialect").argument("[sql]","SQL to translate; reads stdin if omitted").option("--config <config>","Path to the config file").action(async(r,n)=>{await J(async()=>{await Q(n.config);let s=await at(n.config);try{let i=r??await Hi(),o=await s.connection.translateDdl(i),a=typeof o=="string"?o:o.ddl??"";console.log(a);}finally{await s.connection.close();}});}),t.command("query").description("Execute a SQL statement against the local or remote project").argument("[statement]","The statement to execute; reads stdin if omitted").option("--remote","Execute the statement on the remote project",false).option("--config <config>","Path to the config file").action(async(r,n)=>{await J(async()=>{n.remote||await Q(n.config);let s=await at(n.remote?!0:n.config);try{if(r){Ze(`Executing: ${fe.default.cyan(r)}`);let o=await s.connection.exec(r);console.log(o);return}let i=await Hi();for(let o of mt(i)){if(!o.trim())continue;let a=await s.connection.exec(o);console.log(a);}}finally{await s.connection.close();}});}),t.command("schema").description(be("Print the current database schema")).option("--diff","Diff current DB against schemas/*.sql",false).option("--sql","Print raw CREATE statements from sqlite_master",false).option("--config <config>","Path to the config file").action(async r=>{console.log(),await J(async()=>{if(await Q(r.config),r.diff){await md(r.config);return}let s=await(await at(r.config)).connection.introspect();if(r.sql){let i=[...s.tables.map(o=>o.sql),...s.views.map(o=>o.sql),...s.triggers.map(o=>o.sql)].filter(o=>o&&o.trim().length>0);console.log(i.join(`;
198
200
 
199
- `)+(i.length?";":""));return}im(s);});});};});var hd={};de(hd,{migration:()=>K0});var xe,V0,K0,gd=g(()=>{xe=te(ae());wt();Gs();Dt();Ce();$e();V0="Local Development:",K0=e=>{let t=e.command("migration").description("Manage database migrations").helpGroup(V0);t.command("new").description("Create a new empty migration file").argument("<name>","The migration name").option("--config <config>","Path to the config file").action(async(r,n)=>{await Q(n.config);let i=await(await z({withSupabaseClient:false})).project.local.createApp(n.config),o=await Ff(i,r);console.log(xe.default.green(" \u279C"),"Created",xe.default.cyan(Me__default.relative(process.cwd(),o))),process.exit(0);}),t.command("up").description("Apply pending migrations from the migrations directory").option("--config <config>","Path to the config file").option("--dry-run","Print pending migrations without applying",false).action(async r=>{await Q(r.config);let s=await(await z({withSupabaseClient:false})).project.local.createApp(r.config);if(r.dryRun){await Lt(s.connection);let i=new Set(await Zr(s.connection)),a=(await Ue(s)).filter(l=>!i.has(l.version));a.length===0&&(console.log(xe.default.green("No pending migrations.")),process.exit(0)),console.log(xe.default.dim("Pending:"));for(let l of a)console.log(" "+xe.default.cyan(l.filename));process.exit(0);}try{let i=await Gt(s);if(i.applied.length===0)console.log(xe.default.green("Local database is up to date."));else for(let o of i.applied)console.log(xe.default.green(" \u2713"),"Applied",xe.default.cyan(o.filename));process.exit(0);}catch(i){console.error(xe.default.red("Migration failed: "+String(i.message??i))),process.exit(1);}}),t.command("list").description("List applied and pending migrations").option("--config <config>","Path to the config file").action(async r=>{await Q(r.config);let s=await(await z({withSupabaseClient:false})).project.local.createApp(r.config);await Lt(s.connection);let i=new Set(await Zr(s.connection)),o=await Ue(s);console.log(xe.default.dim(`Migrations in ${jt(s)}:`)),o.length===0&&console.log(xe.default.dim(" (none)"));for(let c of o){let p=i.has(c.version)?xe.default.green("[applied]"):xe.default.yellow("[pending]");console.log(` ${p} ${xe.default.cyan(c.filename)}`);}let a=new Set(o.map(c=>c.version)),l=[...i].filter(c=>!a.has(c));if(l.length>0){console.log(),console.log(xe.default.dim("Recorded versions without matching file:"));for(let c of l)console.log(` ${xe.default.red("[orphan]")} ${c}`);}process.exit(0);});};});function J0(e){let t=(e??process.env.SUPABASE_ENDPOINT??X0).replace(/\/+$/,""),r=new URL(t),n=r.host;return {apiUrl:`${r.protocol}//${n.startsWith("api.")?n:`api.${n}`}`,projectDomain:n==="supabase.com"?"supabase.co":n}}function yd(e){if(Array.isArray(e)){let t=e.find(n=>n.name==="anon")?.api_key??"",r=e.find(n=>n.name==="service_role")?.api_key??"";return {anon:t,service_role:r}}return e}var X0,_i,wd=g(()=>{X0="https://supabase.com";_i=class{constructor(t,r){this.token=t;if(!t)throw new Error("Supabase access token required");let n=J0(r?.endpoint);this.apiUrl=n.apiUrl,this.projectDomain=n.projectDomain;}apiUrl;projectDomain;async request(t,r,n){let s=await fetch(`${this.apiUrl}${r}`,{method:t,headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json",Accept:"application/json"},body:n===void 0?void 0:JSON.stringify(n)});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Supabase API ${t} ${r} failed: ${s.status} ${s.statusText}${o?` \u2014 ${o}`:""}`)}return (s.headers.get("content-type")??"").includes("application/json")?await s.json():await s.text()}listOrganizations(){return this.request("GET","/v1/organizations")}async validateToken(){try{return await this.listOrganizations(),!0}catch{return false}}listRegions(t){return this.request("GET",`/v1/projects/available-regions?organization_slug=${encodeURIComponent(t)}`)}createProject(t){return this.request("POST","/v1/projects",t)}getProject(t){return this.request("GET",`/v1/projects/${t}`)}getApiKeys(t){return this.request("GET",`/v1/projects/${t}/api-keys`)}updateAuthConfig(t,r){return this.request("PATCH",`/v1/projects/${t}/config/auth`,r)}createSigningKey(t,r){return this.request("POST",`/v1/projects/${t}/config/auth/signing-keys`,r)}runSql(t,r){return this.request("POST",`/v1/projects/${t}/database/query`,{query:r})}async waitForActive(t,r={}){let n=r.timeoutMs??6e5,s=r.intervalMs??5e3,i=Date.now();for(;;){let o=await this.getProject(t);if(r.onTick?.(o.status),o.status==="ACTIVE_HEALTHY")return o;if(Date.now()-i>n)throw new Error(`Timed out waiting for project ${t} to become ACTIVE_HEALTHY (last status: ${o.status})`);await new Promise(a=>setTimeout(a,s));}}};});function Q0(e){if(e==null||typeof e!="string")return true;try{return JSON.parse(e),!0}catch{return false}}function Z0(e){return e==null?true:typeof e!="string"?false:Y0.test(e)}function e_(e){if(e==null)return true;if(typeof e=="number")return Number.isFinite(e);if(typeof e!="string")return false;let t=Date.parse(e);return !Number.isNaN(t)}function bd(e){if(!e)return;let t=e.match(/varchar\s*\(\s*(\d+)\s*\)/i);return t?Number(t[1]):void 0}function Sd(e){return e?/jsonb?/i.test(e):false}function Ed(e){return e?/\buuid\b/i.test(e):false}function xd(e){return e?/timestamp(tz)?|timestamp with|timestamp without/i.test(e):false}async function _d(e){let t=await e.connection.introspect(),r=[],n=e.connection.dialect;for(let s of t.tables){let i=s.name,o=s.schema,a=n==="sqlite"&&o&&o!=="main"?`"${o}.${i}"`:o?`"${o}"."${i}"`:`"${i}"`,l=t.columns.filter(h=>h.table===i&&(h.schema??o)===o),c=0,p=[];try{let h=await e.connection.exec(`SELECT COUNT(*) as c FROM ${a}`);c=Number(h?.rows?.[0]?.c??0);}catch{r.push({table:i,schema:o,rowCount:0,issues:p});continue}if(c===0){r.push({table:i,schema:o,rowCount:c,issues:p});continue}let u=l.filter(h=>Sd(h.type)||Ed(h.type)||xd(h.type)||bd(h.type)!==void 0);if(u.length===0){r.push({table:i,schema:o,rowCount:c,issues:p});continue}let f=u.map(h=>`"${h.name}"`).join(", ");try{let d=(await e.connection.exec(`SELECT ${f} FROM ${a}`))?.rows??[];for(let m of d)for(let w of u){let y=m[w.name];if(Sd(w.type)&&!Q0(y)){p.push({table:i,column:w.name,kind:"invalid_json",message:`row contains non-parseable JSON in ${i}.${w.name}`});continue}if(Ed(w.type)&&y!=null&&!Z0(y)){p.push({table:i,column:w.name,kind:"invalid_uuid",message:`row contains invalid UUID in ${i}.${w.name}`});continue}if(xd(w.type)&&!e_(y)){p.push({table:i,column:w.name,kind:"invalid_timestamp",message:`row contains unparseable timestamp in ${i}.${w.name}`});continue}let E=bd(w.type);E!==void 0&&typeof y=="string"&&y.length>E&&p.push({table:i,column:w.name,kind:"varchar_overflow",message:`value exceeds varchar(${E}) in ${i}.${w.name}`});}}catch{}r.push({table:i,schema:o,rowCount:c,issues:p});}return r}var Y0,$d=g(()=>{Y0=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;});function $t(e){let t=[],r="",n=0,s=false,i=false,o=false,a=false,l=null;for(;n<e.length;){let p=e[n],u=e[n+1];if(o){r+=p,p===`
200
- `&&(o=false),n++;continue}if(a){if(r+=p,p==="*"&&u==="/"){r+=u,n+=2,a=false;continue}n++;continue}if(l){if(r+=p,p==="$"&&e.startsWith(l,n)){r+=e.slice(n+1,n+l.length),n+=l.length,l=null;continue}n++;continue}if(s){if(r+=p,p==="'"&&u==="'"){r+=u,n+=2;continue}p==="'"&&(s=false),n++;continue}if(i){if(r+=p,p==='"'&&u==='"'){r+=u,n+=2;continue}p==='"'&&(i=false),n++;continue}if(p==="-"&&u==="-"){o=true,r+=p,n++;continue}if(p==="/"&&u==="*"){a=true,r+=p,n++;continue}if(p==="'"){s=true,r+=p,n++;continue}if(p==='"'){i=true,r+=p,n++;continue}if(p==="$"){let f=e.slice(n).match(/^\$[A-Za-z0-9_]*\$/);if(f){l=f[0],r+=f[0],n+=f[0].length;continue}}if(p===";"){let f=r.trim();f&&t.push(f),r="",n++;continue}r+=p,n++;}let c=r.trim();return c&&t.push(c),t}var $i=g(()=>{});async function vi(e,t){let n=e.connection.dialect==="sqlite"?`"auth.${t}"`:`auth."${t}"`;try{let s=await e.connection.exec(`SELECT COUNT(*) as c FROM ${n}`);return Number(s?.rows?.[0]?.c??0)}catch{return 0}}async function vd(e){let t=[],r=[],n=false;try{await e.connection.exec("SELECT 1"),n=!0;}catch(l){t.push(`Database not reachable: ${String(l)}`);}let s=await ge(e),i=$t(s);i.length===0&&t.push("No schema statements found in supabase/schemas/*.sql");let o=[];if(n)try{o=await _d(e);}catch(l){r.push(`Data validation skipped: ${String(l)}`);}for(let l of o)for(let c of l.issues)r.push(`${c.kind}: ${c.message}`);let a={users:0,sessions:0,refresh_tokens:0,identities:0,jwt_secret_set:!!e.config.auth?.jwt_secret};return n&&(a.users=await vi(e,"users"),a.sessions=await vi(e,"sessions"),a.refresh_tokens=await vi(e,"refresh_tokens"),a.identities=await vi(e,"identities")),a.jwt_secret_set||r.push("auth.jwt_secret is not configured \u2014 tokens will not survive upgrade"),e.config.storage?.enabled&&r.push("Storage is enabled but migration is not yet supported"),e.config.realtime?.enabled&&r.push("Realtime config migration is not yet supported"),{ok:t.length===0,errors:t,warnings:r,dbReachable:n,schemaStatementCount:i.length,schemaBytes:s.length,tables:o,auth:a}}var Td=g(()=>{Ye();$d();$i();});var Pl,Ad=g(()=>{Pl=`-- supabase/auth core schema (Postgres)
201
+ `)+(i.length?";":""));return}am(s);});});};});var yd={};de(yd,{migration:()=>Y0});var xe,J0,Y0,wd=g(()=>{xe=te(ae());wt();zs();Dt();Ce();$e();J0="Local Development:",Y0=e=>{let t=e.command("migration").description("Manage database migrations").helpGroup(J0);t.command("new").description("Create a new empty migration file").argument("<name>","The migration name").option("--config <config>","Path to the config file").action(async(r,n)=>{await Q(n.config);let i=await(await z({withSupabaseClient:false})).project.local.createApp(n.config),o=await Uf(i,r);console.log(xe.default.green(" \u279C"),"Created",xe.default.cyan(Me__default.relative(process.cwd(),o))),process.exit(0);}),t.command("up").description("Apply pending migrations from the migrations directory").option("--config <config>","Path to the config file").option("--dry-run","Print pending migrations without applying",false).action(async r=>{await Q(r.config);let s=await(await z({withSupabaseClient:false})).project.local.createApp(r.config);if(r.dryRun){await Lt(s.connection);let i=new Set(await en(s.connection)),a=(await Ue(s)).filter(l=>!i.has(l.version));a.length===0&&(console.log(xe.default.green("No pending migrations.")),process.exit(0)),console.log(xe.default.dim("Pending:"));for(let l of a)console.log(" "+xe.default.cyan(l.filename));process.exit(0);}try{let i=await Gt(s);if(i.applied.length===0)console.log(xe.default.green("Local database is up to date."));else for(let o of i.applied)console.log(xe.default.green(" \u2713"),"Applied",xe.default.cyan(o.filename));process.exit(0);}catch(i){console.error(xe.default.red("Migration failed: "+String(i.message??i))),process.exit(1);}}),t.command("list").description("List applied and pending migrations").option("--config <config>","Path to the config file").action(async r=>{await Q(r.config);let s=await(await z({withSupabaseClient:false})).project.local.createApp(r.config);await Lt(s.connection);let i=new Set(await en(s.connection)),o=await Ue(s);console.log(xe.default.dim(`Migrations in ${jt(s)}:`)),o.length===0&&console.log(xe.default.dim(" (none)"));for(let c of o){let p=i.has(c.version)?xe.default.green("[applied]"):xe.default.yellow("[pending]");console.log(` ${p} ${xe.default.cyan(c.filename)}`);}let a=new Set(o.map(c=>c.version)),l=[...i].filter(c=>!a.has(c));if(l.length>0){console.log(),console.log(xe.default.dim("Recorded versions without matching file:"));for(let c of l)console.log(` ${xe.default.red("[orphan]")} ${c}`);}process.exit(0);});};});function Z0(e){let t=(e??process.env.SUPABASE_ENDPOINT??Q0).replace(/\/+$/,""),r=new URL(t),n=r.host;return {apiUrl:`${r.protocol}//${n.startsWith("api.")?n:`api.${n}`}`,projectDomain:n==="supabase.com"?"supabase.co":n}}function bd(e){if(Array.isArray(e)){let t=e.find(n=>n.name==="anon")?.api_key??"",r=e.find(n=>n.name==="service_role")?.api_key??"";return {anon:t,service_role:r}}return e}var Q0,$i,Sd=g(()=>{Q0="https://supabase.com";$i=class{constructor(t,r){this.token=t;if(!t)throw new Error("Supabase access token required");let n=Z0(r?.endpoint);this.apiUrl=n.apiUrl,this.projectDomain=n.projectDomain;}apiUrl;projectDomain;async request(t,r,n){let s=await fetch(`${this.apiUrl}${r}`,{method:t,headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json",Accept:"application/json"},body:n===void 0?void 0:JSON.stringify(n)});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Supabase API ${t} ${r} failed: ${s.status} ${s.statusText}${o?` \u2014 ${o}`:""}`)}return (s.headers.get("content-type")??"").includes("application/json")?await s.json():await s.text()}listOrganizations(){return this.request("GET","/v1/organizations")}async validateToken(){try{return await this.listOrganizations(),!0}catch{return false}}listRegions(t){return this.request("GET",`/v1/projects/available-regions?organization_slug=${encodeURIComponent(t)}`)}createProject(t){return this.request("POST","/v1/projects",t)}getProject(t){return this.request("GET",`/v1/projects/${t}`)}getApiKeys(t){return this.request("GET",`/v1/projects/${t}/api-keys`)}updateAuthConfig(t,r){return this.request("PATCH",`/v1/projects/${t}/config/auth`,r)}createSigningKey(t,r){return this.request("POST",`/v1/projects/${t}/config/auth/signing-keys`,r)}runSql(t,r){return this.request("POST",`/v1/projects/${t}/database/query`,{query:r})}async waitForActive(t,r={}){let n=r.timeoutMs??6e5,s=r.intervalMs??5e3,i=Date.now();for(;;){let o=await this.getProject(t);if(r.onTick?.(o.status),o.status==="ACTIVE_HEALTHY")return o;if(Date.now()-i>n)throw new Error(`Timed out waiting for project ${t} to become ACTIVE_HEALTHY (last status: ${o.status})`);await new Promise(a=>setTimeout(a,s));}}};});function t_(e){if(e==null||typeof e!="string")return true;try{return JSON.parse(e),!0}catch{return false}}function r_(e){return e==null?true:typeof e!="string"?false:e_.test(e)}function n_(e){if(e==null)return true;if(typeof e=="number")return Number.isFinite(e);if(typeof e!="string")return false;let t=Date.parse(e);return !Number.isNaN(t)}function Ed(e){if(!e)return;let t=e.match(/varchar\s*\(\s*(\d+)\s*\)/i);return t?Number(t[1]):void 0}function xd(e){return e?/jsonb?/i.test(e):false}function _d(e){return e?/\buuid\b/i.test(e):false}function $d(e){return e?/timestamp(tz)?|timestamp with|timestamp without/i.test(e):false}async function vd(e){let t=await e.connection.introspect(),r=[],n=e.connection.dialect;for(let s of t.tables){let i=s.name,o=s.schema,a=n==="sqlite"&&o&&o!=="main"?`"${o}.${i}"`:o?`"${o}"."${i}"`:`"${i}"`,l=t.columns.filter(h=>h.table===i&&(h.schema??o)===o),c=0,p=[];try{let h=await e.connection.exec(`SELECT COUNT(*) as c FROM ${a}`);c=Number(h?.rows?.[0]?.c??0);}catch{r.push({table:i,schema:o,rowCount:0,issues:p});continue}if(c===0){r.push({table:i,schema:o,rowCount:c,issues:p});continue}let u=l.filter(h=>xd(h.type)||_d(h.type)||$d(h.type)||Ed(h.type)!==void 0);if(u.length===0){r.push({table:i,schema:o,rowCount:c,issues:p});continue}let f=u.map(h=>`"${h.name}"`).join(", ");try{let d=(await e.connection.exec(`SELECT ${f} FROM ${a}`))?.rows??[];for(let m of d)for(let w of u){let y=m[w.name];if(xd(w.type)&&!t_(y)){p.push({table:i,column:w.name,kind:"invalid_json",message:`row contains non-parseable JSON in ${i}.${w.name}`});continue}if(_d(w.type)&&y!=null&&!r_(y)){p.push({table:i,column:w.name,kind:"invalid_uuid",message:`row contains invalid UUID in ${i}.${w.name}`});continue}if($d(w.type)&&!n_(y)){p.push({table:i,column:w.name,kind:"invalid_timestamp",message:`row contains unparseable timestamp in ${i}.${w.name}`});continue}let E=Ed(w.type);E!==void 0&&typeof y=="string"&&y.length>E&&p.push({table:i,column:w.name,kind:"varchar_overflow",message:`value exceeds varchar(${E}) in ${i}.${w.name}`});}}catch{}r.push({table:i,schema:o,rowCount:c,issues:p});}return r}var e_,Td=g(()=>{e_=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;});function $t(e){let t=[],r="",n=0,s=false,i=false,o=false,a=false,l=null;for(;n<e.length;){let p=e[n],u=e[n+1];if(o){r+=p,p===`
202
+ `&&(o=false),n++;continue}if(a){if(r+=p,p==="*"&&u==="/"){r+=u,n+=2,a=false;continue}n++;continue}if(l){if(r+=p,p==="$"&&e.startsWith(l,n)){r+=e.slice(n+1,n+l.length),n+=l.length,l=null;continue}n++;continue}if(s){if(r+=p,p==="'"&&u==="'"){r+=u,n+=2;continue}p==="'"&&(s=false),n++;continue}if(i){if(r+=p,p==='"'&&u==='"'){r+=u,n+=2;continue}p==='"'&&(i=false),n++;continue}if(p==="-"&&u==="-"){o=true,r+=p,n++;continue}if(p==="/"&&u==="*"){a=true,r+=p,n++;continue}if(p==="'"){s=true,r+=p,n++;continue}if(p==='"'){i=true,r+=p,n++;continue}if(p==="$"){let f=e.slice(n).match(/^\$[A-Za-z0-9_]*\$/);if(f){l=f[0],r+=f[0],n+=f[0].length;continue}}if(p===";"){let f=r.trim();f&&t.push(f),r="",n++;continue}r+=p,n++;}let c=r.trim();return c&&t.push(c),t}var vi=g(()=>{});async function Ti(e,t){let n=e.connection.dialect==="sqlite"?`"auth.${t}"`:`auth."${t}"`;try{let s=await e.connection.exec(`SELECT COUNT(*) as c FROM ${n}`);return Number(s?.rows?.[0]?.c??0)}catch{return 0}}async function Ad(e){let t=[],r=[],n=false;try{await e.connection.exec("SELECT 1"),n=!0;}catch(l){t.push(`Database not reachable: ${String(l)}`);}let s=await ge(e),i=$t(s);i.length===0&&t.push("No schema statements found in supabase/schemas/*.sql");let o=[];if(n)try{o=await vd(e);}catch(l){r.push(`Data validation skipped: ${String(l)}`);}for(let l of o)for(let c of l.issues)r.push(`${c.kind}: ${c.message}`);let a={users:0,sessions:0,refresh_tokens:0,identities:0,jwt_secret_set:!!e.config.auth?.jwt_secret};return n&&(a.users=await Ti(e,"users"),a.sessions=await Ti(e,"sessions"),a.refresh_tokens=await Ti(e,"refresh_tokens"),a.identities=await Ti(e,"identities")),a.jwt_secret_set||r.push("auth.jwt_secret is not configured \u2014 tokens will not survive upgrade"),e.config.storage?.enabled&&r.push("Storage is enabled but migration is not yet supported"),e.config.realtime?.enabled&&r.push("Realtime config migration is not yet supported"),{ok:t.length===0,errors:t,warnings:r,dbReachable:n,schemaStatementCount:i.length,schemaBytes:s.length,tables:o,auth:a}}var Cd=g(()=>{Ye();Td();vi();});var Nl,Rd=g(()=>{Nl=`-- supabase/auth core schema (Postgres)
201
203
  -- Scope: Core Authentication + User Management
202
204
  -- Source: GoTrue migrations + runtime analysis
203
205
 
@@ -375,7 +377,7 @@ CREATE TABLE IF NOT EXISTS auth.audit_log_entries (
375
377
  created_at timestamptz DEFAULT now(),
376
378
  ip_address varchar(64) DEFAULT ''
377
379
  );
378
- `;});function Cd(e=true){return e?Mc(Pl):Pl}var Rd=g(()=>{Rt();Ad();});function a_(e,t,r,n){if(e==null)return "NULL";if(n.includes(t))return e===true||e===1||e==="1"||e==="true"?"true":"false";if(r.includes(t)){let s=typeof e=="string"?e:JSON.stringify(e);return `${kd(s)}::jsonb`}return typeof e=="number"?Number.isFinite(e)?String(e):"NULL":typeof e=="boolean"?e?"true":"false":kd(String(e))}function kd(e){return `'${e.replace(/'/g,"''")}'`}async function Ti(e,t={}){let r=t.target??"supabase",n={users:[],sessions:[],identities:[],refresh_tokens:[]},s=e.connection.dialect,i=o_[r];for(let o of n_){let a=s==="sqlite"?`"auth.${o}"`:`auth."${o}"`,l=[];try{l=(await e.connection.exec(`SELECT * FROM ${a}`))?.rows??[];}catch{continue}if(l.length===0)continue;let c=new Set(i[o]),p=s_[o],u=i_[o];for(let f of l){let h={...f};if(r==="supabase"&&o==="users"){let y=h.confirmed_at;y!=null&&h.email_confirmed_at==null&&(h.email_confirmed_at=y);}let d=Object.keys(h).filter(y=>!c.has(y)),m=d.map(y=>a_(h[y],y,p,u)),w=`INSERT INTO auth.${o} (${d.map(y=>`"${y}"`).join(", ")}) VALUES (${m.join(", ")}) ON CONFLICT DO NOTHING`;n[o].push(w);}}return n}var r_,n_,s_,i_,o_,Ol=g(()=>{r_=["users","sessions","identities","refresh_tokens"],n_=r_,s_={users:["raw_app_meta_data","raw_user_meta_data"],sessions:[],identities:["identity_data"],refresh_tokens:[]},i_={users:["is_sso_user","is_anonymous"],sessions:[],identities:[],refresh_tokens:["revoked"]},o_={supabase:{users:["confirmed_at"],sessions:[],identities:["email"],refresh_tokens:["id"]},local:{users:["confirmed_at"],sessions:[],identities:["email"],refresh_tokens:[]}};});function Ai(e){return !e||e==="main"||e==="public"?"public":e}function Pn(e,t){return `${Ai(e)}.${t}`}function c_(e,t){let r=new Map(e.map(a=>[Pn(a.schema,a.name),a])),n=new Map,s=new Map;for(let a of r.keys())n.set(a,new Set),s.set(a,new Set);for(let a of t){let l=Pn(a.schema,a.table),c=Pn(a.ref_schema??a.schema,a.ref_table);!n.has(l)||!n.has(c)||(n.get(l).add(c),s.get(c).add(l));}let i=[...n.entries()].filter(([,a])=>a.size===0).map(([a])=>a),o=[];for(let a=0;a<i.length;a++){let l=i[a];o.push(l);for(let c of s.get(l)??[]){let p=n.get(c);p&&(p.delete(l),p.size===0&&i.push(c));}}if(o.length<e.length){console.warn("Warning: cycle detected in user table foreign keys; using best-effort data export order.");let a=new Set(o);for(let l of e){let c=Pn(l.schema,l.name);a.has(c)||o.push(c);}}return o.map(a=>r.get(a)).filter(Boolean)}function Od(e,t){if(e==null)return "NULL";let r=(t??"").toLowerCase();if(Array.isArray(e)&&r.endsWith("[]")){let n=t?.slice(0,-2);return `ARRAY[${e.map(s=>Od(s,n)).join(", ")}]::${t}`}if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return Number.isFinite(e)?String(e):"NULL";if(r.includes("bool")&&(e===0||e===1||e==="0"||e==="1"))return e===1||e==="1"?"true":"false";if(r.includes("json")){let n=typeof e=="string"?e:JSON.stringify(e),s=r.includes("jsonb")?"::jsonb":"::json";return `${Sr(n)}${s}`}return e instanceof Date?Sr(e.toISOString()):typeof e=="object"?`${Sr(JSON.stringify(e))}::jsonb`:Sr(String(e))}function Sr(e){return `'${e.replace(/'/g,"''")}'`}function Nl(e){return `"${e.replace(/"/g,'""')}"`}function u_(e){let t=e.default_value??e.default;if(typeof t=="string"&&t.trim().toLowerCase().startsWith("nextval("))return true;let r=typeof e.type=="string"?e.type.toLowerCase():"",n=typeof e.pg_type=="string"?e.pg_type.toLowerCase():"";return Pd.has(r)||Pd.has(n)}function p_(e,t,r){let n=`${Nl(e)}.${Nl(t)}`;return `SELECT setval(pg_get_serial_sequence(${Sr(n)}, ${Sr(r)}), COALESCE((SELECT MAX(${Nl(r)}) FROM ${n}), 1));`}async function f_(e){let t=e.connection.config?.translation?.deparse?.schema;if(t instanceof Map&&t.size>0)return t;let r=await ge(e);return r.trim()?(await Rn(r)).schema:new Map}async function Ci(e){let t=await e.connection.introspect(),r=e.connection.dialect,n=await f_(e),s=c_(t.tables.filter(o=>!l_.has(Ai(o.schema))),t.foreign_keys),i=[];for(let o of s){let a=Ai(o.schema),l=r==="sqlite"?a==="public"?`"${o.name}"`:`"${a}.${o.name}"`:`"${a}"."${o.name}"`,p=t.columns.filter(E=>E.table===o.name&&Ai(E.schema)===a).filter(E=>!E.generated&&!E.is_generated),u=[];try{u=(await e.connection.exec(`SELECT * FROM ${l}`))?.rows??[];}catch{continue}if(u.length===0)continue;let f=n.get(Pn(a,o.name)),h=typeof e.connection.deserializeRow=="function"?e.connection.deserializeRow.bind(e.connection):E=>E;u=u.map(E=>{let T=f?f.deserializeRow(E):E;return h(T)});let d=p.map(E=>E.name),m=new Map(p.map(E=>[E.name,E.pg_type??E.type])),w=[];for(let E of u){let T=d.map(v=>Od(E[v],m.get(v)));w.push(`INSERT INTO "${a}"."${o.name}" (${d.map(v=>`"${v}"`).join(", ")}) VALUES (${T.join(", ")}) ON CONFLICT DO NOTHING`);}let y=p.filter(u_).map(E=>p_(a,o.name,E.name));i.push({schema:a,table:o.name,inserts:w,sequenceResets:y});}return i}var l_,Pd,Il=g(()=>{bi();Ye();l_=new Set(["auth","storage","realtime","supabase_functions","graphql","graphql_public","extensions","pgsodium","pgsodium_masks","vault","information_schema","pg_catalog","pg_toast"]),Pd=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]);});async function Nd(e){let{PGlite:t}=await We("@supabase/lite/pglite","pglite","@electric-sql/pglite"),r=new t,n=[],s=0,i=0,o=0,a=0;try{for(let d of ["anon","authenticated","service_role","supabase_auth_admin"])await r.exec(`CREATE ROLE ${d}`);let l=$t(Hs);for(let d=0;d<l.length;d++)try{await r.exec(l[d]);}catch(m){return n.push({phase:"schema",label:`auth helpers ${d+1}/${l.length}`,statement:l[d],error:String(m)}),{ok:!1,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:n}}if(e.config.auth?.enabled!==!1){let d=$t(Cd());s=d.length;for(let m=0;m<d.length;m++)try{await r.exec(d[m]);}catch(w){return n.push({phase:"schema",label:`auth base schema ${m+1}/${d.length}`,statement:d[m],error:String(w)}),{ok:!1,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:n}}}let c=await ge(e),p=$t(c);i=p.length;for(let d=0;d<p.length;d++)try{await r.exec(p[d]);}catch(m){return n.push({phase:"schema",label:`schema ${d+1}/${p.length}`,statement:p[d],error:String(m)}),{ok:!1,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:n}}let u=await Ti(e,{target:"local"}),f=["users","sessions","identities","refresh_tokens"];for(let d of f){let m=u[d];for(let w=0;w<m.length;w++){o++;try{await r.exec(m[w]);}catch(y){n.push({phase:"auth",label:`auth.${d} row ${w+1}/${m.length}`,statement:m[w],error:String(y)});}}}let h=await Ci(e);for(let d of h){for(let m=0;m<d.inserts.length;m++){a++;try{await r.exec(d.inserts[m]);}catch(w){n.push({phase:"data",label:`${d.schema}.${d.table} row ${m+1}/${d.inserts.length}`,statement:d.inserts[m],error:String(w)});}}for(let m=0;m<d.sequenceResets.length;m++)try{await r.exec(d.sequenceResets[m]);}catch(w){n.push({phase:"data",label:`${d.schema}.${d.table} sequence reset ${m+1}/${d.sequenceResets.length}`,statement:d.sequenceResets[m],error:String(w)});}}}finally{await r.close().catch(()=>{});}return {ok:n.length===0,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:n}}var Id=g(()=>{lr();Ye();Rd();En();$i();Ol();Il();});function Ld(e){if(console.log(N.default.bold("Readiness Report")),console.log(` db reachable: ${e.dbReachable?N.default.green("yes"):N.default.red("no")} schema statements: ${N.default.cyan(e.schemaStatementCount)} schema bytes: ${N.default.cyan(e.schemaBytes)}`),console.log(` auth \u2014 users: ${N.default.cyan(e.auth.users)} sessions: ${N.default.cyan(e.auth.sessions)} identities: ${N.default.cyan(e.auth.identities)} refresh_tokens: ${N.default.cyan(e.auth.refresh_tokens)} jwt_secret: ${e.auth.jwt_secret_set?N.default.green("set"):N.default.yellow("unset")}`),e.tables.length>0){console.log(N.default.dim(" tables:"));for(let t of e.tables){let r=t.issues.length>0?N.default.yellow(` (${t.issues.length} issues)`):"",n=t.schema?`${t.schema}.`:"";console.log(` ${n}${t.table}: ${N.default.cyan(t.rowCount)} rows${r}`);}}if(e.errors.length>0){console.log(N.default.red("Errors:"));for(let t of e.errors)console.log(` ${N.default.red("\u2717")} ${t}`);}if(e.warnings.length>0){console.log(N.default.yellow("Warnings:"));for(let t of e.warnings)console.log(` ${N.default.yellow("!")} ${t}`);}console.log(),console.log(e.ok?N.default.green("Ready to upgrade."):N.default.red("Not ready."));}function Dd(e){if(console.log(),console.log(N.default.bold("Rehearsal (in-memory pglite)")),console.log(` auth schema: ${N.default.cyan(e.baseSchemaStatements)} stmts user schema: ${N.default.cyan(e.schemaStatements)} stmts auth: ${N.default.cyan(e.authInserts)} inserts data: ${N.default.cyan(e.dataInserts)} inserts`),e.failures.length>0){console.log(N.default.red(` ${e.failures.length} failure(s):`));for(let t of e.failures)console.log(N.default.red(` \u2717 [${t.phase}] ${t.label}`)),console.log(N.default.dim(` ${t.statement}`)),console.log(N.default.dim(` ${t.error}`));}console.log(e.ok?N.default.green(" rehearsal passed"):N.default.red(" rehearsal failed"));}function jd(e){console.log(),console.log(N.default.bold("SQLite Shim Audit")),console.log(` fields: ${N.default.cyan(e.summary.total)} passed: ${N.default.green(String(e.summary.passed))} warned: ${N.default.yellow(String(e.summary.warned))} failed: ${N.default.red(String(e.summary.failed))}`),e.results.length===0&&console.log(N.default.dim(" no shim-backed fields found"));for(let t of e.results.filter(r=>r.status!=="pass")){let r=t.status==="fail"?N.default.red:N.default.yellow;if(console.log(` ${r(t.status)} ${t.field} (${t.pg_type}) rows: ${N.default.cyan(t.rows_checked)} affected: ${N.default.cyan(t.affected_rows??0)}`),t.message&&console.log(` ${t.message}`),t.samples?.length)for(let n of t.samples)console.log(N.default.dim(` sample ${JSON.stringify(n.id)} raw=${JSON.stringify(n.raw_value)}`));t.action&&console.log(N.default.dim(` action: ${t.action}`));}console.log(e.summary.upgrade_safe?N.default.green(" shim audit passed"):N.default.red(" shim audit failed"));}function Ll(e){if(console.log(),console.log(N.default.bold(N.default.green("Upgrade complete."))),console.log(),console.log(` ${N.default.bold("Project URL:")} ${N.default.cyan(e.projectUrl)}`),console.log(` ${N.default.bold("API URL:")} ${N.default.cyan(e.apiUrl)}`),e.studioUrl&&console.log(` ${N.default.bold("Studio URL:")} ${N.default.cyan(e.studioUrl)}`),console.log(` ${N.default.bold("Ref:")} ${N.default.cyan(e.projectRef)}`),console.log(),console.log(` ${N.default.bold("anon key:")} ${e.anonKey}`),console.log(` ${N.default.bold("service_role key:")} ${e.serviceRoleKey}`),console.log(` ${N.default.bold("db password:")} ${e.dbPassword}`),console.log(),console.log(` migrated auth \u2014 users: ${N.default.cyan(e.auth.users)} sessions: ${N.default.cyan(e.auth.sessions)} identities: ${N.default.cyan(e.auth.identities)} refresh_tokens: ${N.default.cyan(e.auth.refresh_tokens)}`),console.log(` jwt secret: ${e.jwtMigrated?N.default.green("migrated"):N.default.yellow("not migrated \u2014 users must re-authenticate")}`),e.warnings.length>0){console.log(),console.log(N.default.yellow("Warnings:"));for(let t of e.warnings)console.log(` ${N.default.yellow("!")} ${t}`);}console.log(),console.log(N.default.bold("Update your supabase-js client:")),console.log(` url: ${N.default.cyan(e.apiUrl)}`),console.log(` anonKey: ${N.default.cyan(e.anonKey)}`),console.log();}var N,Fd=g(()=>{N=te(ae());});function Ud(e){let t=[],r=e??"",n=r.toLowerCase(),s=Buffer$1.byteLength(r,"utf8");if(!r)return t.push("auth.jwt_secret is empty"),{strong:false,reasons:t};m_.has(r)&&t.push(`matches Supalite development default "${r}"`),s<32&&t.push(`is ${s} bytes; use at least 32 bytes for production secrets`),[/[a-z]/.test(r),/[A-Z]/.test(r),/[0-9]/.test(r),/[^A-Za-z0-9]/.test(r)].filter(Boolean).length<3&&t.push("uses too little character variety"),/^(.)\1{7,}$/.test(r)?t.push("is one repeated character"):h_(r)&&t.push("contains an obvious repeated pattern");let o=d_.find(a=>n.includes(a));return o&&t.push(`contains placeholder term "${o}"`),{strong:t.length===0,reasons:t}}function Bd(e){return {kty:"oct",alg:"HS256",k:Buffer$1.from(e,"utf8").toString("base64url")}}function h_(e){if(e.length<8)return false;for(let t=2;t<=Math.floor(e.length/2);t++){if(e.length%t!==0)continue;if(e.slice(0,t).repeat(e.length/t)===e)return true}return false}var m_,d_,qd=g(()=>{m_=new Set(["unsafe-secret-change-me","dev-secret-change-me"]),d_=["change-me","changeme","secret","password","passwd","test","dev"];});async function Hd(e){let t=e.trim();if(!t)return "";let{PGlite:r}=await We("@supabase/lite/pglite","pglite","@electric-sql/pglite"),n=new r;try{return await n.exec(Et(xt(t))),await n.exec(Hs),await g_(n,t)}finally{await n.close().catch(()=>{});}}async function g_(e,t){return t?(await e.exec(t),await y_(e)):""}async function y_(e){let t=await e.query(`
380
+ `;});function kd(e=true){return e?Bc(Nl):Nl}var Pd=g(()=>{Rt();Rd();});function u_(e,t,r,n){if(e==null)return "NULL";if(n.includes(t))return e===true||e===1||e==="1"||e==="true"?"true":"false";if(r.includes(t)){let s=typeof e=="string"?e:JSON.stringify(e);return `${Od(s)}::jsonb`}return typeof e=="number"?Number.isFinite(e)?String(e):"NULL":typeof e=="boolean"?e?"true":"false":Od(String(e))}function Od(e){return `'${e.replace(/'/g,"''")}'`}async function Ai(e,t={}){let r=t.target??"supabase",n={users:[],sessions:[],identities:[],refresh_tokens:[]},s=e.connection.dialect,i=c_[r];for(let o of o_){let a=s==="sqlite"?`"auth.${o}"`:`auth."${o}"`,l=[];try{l=(await e.connection.exec(`SELECT * FROM ${a}`))?.rows??[];}catch{continue}if(l.length===0)continue;let c=new Set(i[o]),p=a_[o],u=l_[o];for(let f of l){let h={...f};if(r==="supabase"&&o==="users"){let y=h.confirmed_at;y!=null&&h.email_confirmed_at==null&&(h.email_confirmed_at=y);}let d=Object.keys(h).filter(y=>!c.has(y)),m=d.map(y=>u_(h[y],y,p,u)),w=`INSERT INTO auth.${o} (${d.map(y=>`"${y}"`).join(", ")}) VALUES (${m.join(", ")}) ON CONFLICT DO NOTHING`;n[o].push(w);}}return n}var i_,o_,a_,l_,c_,Il=g(()=>{i_=["users","sessions","identities","refresh_tokens"],o_=i_,a_={users:["raw_app_meta_data","raw_user_meta_data"],sessions:[],identities:["identity_data"],refresh_tokens:[]},l_={users:["is_sso_user","is_anonymous"],sessions:[],identities:[],refresh_tokens:["revoked"]},c_={supabase:{users:["confirmed_at"],sessions:[],identities:["email"],refresh_tokens:["id"]},local:{users:["confirmed_at"],sessions:[],identities:["email"],refresh_tokens:[]}};});function Ci(e){return !e||e==="main"||e==="public"?"public":e}function On(e,t){return `${Ci(e)}.${t}`}function f_(e,t){let r=new Map(e.map(a=>[On(a.schema,a.name),a])),n=new Map,s=new Map;for(let a of r.keys())n.set(a,new Set),s.set(a,new Set);for(let a of t){let l=On(a.schema,a.table),c=On(a.ref_schema??a.schema,a.ref_table);!n.has(l)||!n.has(c)||(n.get(l).add(c),s.get(c).add(l));}let i=[...n.entries()].filter(([,a])=>a.size===0).map(([a])=>a),o=[];for(let a=0;a<i.length;a++){let l=i[a];o.push(l);for(let c of s.get(l)??[]){let p=n.get(c);p&&(p.delete(l),p.size===0&&i.push(c));}}if(o.length<e.length){console.warn("Warning: cycle detected in user table foreign keys; using best-effort data export order.");let a=new Set(o);for(let l of e){let c=On(l.schema,l.name);a.has(c)||o.push(c);}}return o.map(a=>r.get(a)).filter(Boolean)}function Id(e,t){if(e==null)return "NULL";let r=(t??"").toLowerCase();if(Array.isArray(e)&&r.endsWith("[]")){let n=t?.slice(0,-2);return `ARRAY[${e.map(s=>Id(s,n)).join(", ")}]::${t}`}if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return Number.isFinite(e)?String(e):"NULL";if(r.includes("bool")&&(e===0||e===1||e==="0"||e==="1"))return e===1||e==="1"?"true":"false";if(r.includes("json")){let n=typeof e=="string"?e:JSON.stringify(e),s=r.includes("jsonb")?"::jsonb":"::json";return `${Sr(n)}${s}`}return e instanceof Date?Sr(e.toISOString()):typeof e=="object"?`${Sr(JSON.stringify(e))}::jsonb`:Sr(String(e))}function Sr(e){return `'${e.replace(/'/g,"''")}'`}function Ll(e){return `"${e.replace(/"/g,'""')}"`}function m_(e){let t=e.default_value??e.default;if(typeof t=="string"&&t.trim().toLowerCase().startsWith("nextval("))return true;let r=typeof e.type=="string"?e.type.toLowerCase():"",n=typeof e.pg_type=="string"?e.pg_type.toLowerCase():"";return Nd.has(r)||Nd.has(n)}function d_(e,t,r){let n=`${Ll(e)}.${Ll(t)}`;return `SELECT setval(pg_get_serial_sequence(${Sr(n)}, ${Sr(r)}), COALESCE((SELECT MAX(${Ll(r)}) FROM ${n}), 1));`}async function h_(e){let t=e.connection.config?.translation?.deparse?.schema;if(t instanceof Map&&t.size>0)return t;let r=await ge(e);return r.trim()?(await kn(r)).schema:new Map}async function Ri(e){let t=await e.connection.introspect(),r=e.connection.dialect,n=await h_(e),s=f_(t.tables.filter(o=>!p_.has(Ci(o.schema))),t.foreign_keys),i=[];for(let o of s){let a=Ci(o.schema),l=r==="sqlite"?a==="public"?`"${o.name}"`:`"${a}.${o.name}"`:`"${a}"."${o.name}"`,p=t.columns.filter(E=>E.table===o.name&&Ci(E.schema)===a).filter(E=>!E.generated&&!E.is_generated),u=[];try{u=(await e.connection.exec(`SELECT * FROM ${l}`))?.rows??[];}catch{continue}if(u.length===0)continue;let f=n.get(On(a,o.name)),h=typeof e.connection.deserializeRow=="function"?e.connection.deserializeRow.bind(e.connection):E=>E;u=u.map(E=>{let T=f?f.deserializeRow(E):E;return h(T)});let d=p.map(E=>E.name),m=new Map(p.map(E=>[E.name,E.pg_type??E.type])),w=[];for(let E of u){let T=d.map(v=>Id(E[v],m.get(v)));w.push(`INSERT INTO "${a}"."${o.name}" (${d.map(v=>`"${v}"`).join(", ")}) VALUES (${T.join(", ")}) ON CONFLICT DO NOTHING`);}let y=p.filter(m_).map(E=>d_(a,o.name,E.name));i.push({schema:a,table:o.name,inserts:w,sequenceResets:y});}return i}var p_,Nd,Dl=g(()=>{Si();Ye();p_=new Set(["auth","storage","realtime","supabase_functions","graphql","graphql_public","extensions","pgsodium","pgsodium_masks","vault","information_schema","pg_catalog","pg_toast"]),Nd=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]);});async function Ld(e){let{PGlite:t}=await We("@supabase/lite/pglite","pglite","@electric-sql/pglite"),r=new t,n=[],s=0,i=0,o=0,a=0;try{for(let d of ["anon","authenticated","service_role","supabase_auth_admin"])await r.exec(`CREATE ROLE ${d}`);let l=$t(Ws);for(let d=0;d<l.length;d++)try{await r.exec(l[d]);}catch(m){return n.push({phase:"schema",label:`auth helpers ${d+1}/${l.length}`,statement:l[d],error:String(m)}),{ok:!1,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:n}}if(e.config.auth?.enabled!==!1){let d=$t(kd());s=d.length;for(let m=0;m<d.length;m++)try{await r.exec(d[m]);}catch(w){return n.push({phase:"schema",label:`auth base schema ${m+1}/${d.length}`,statement:d[m],error:String(w)}),{ok:!1,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:n}}}let c=await ge(e),p=$t(c);i=p.length;for(let d=0;d<p.length;d++)try{await r.exec(p[d]);}catch(m){return n.push({phase:"schema",label:`schema ${d+1}/${p.length}`,statement:p[d],error:String(m)}),{ok:!1,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:n}}let u=await Ai(e,{target:"local"}),f=["users","sessions","identities","refresh_tokens"];for(let d of f){let m=u[d];for(let w=0;w<m.length;w++){o++;try{await r.exec(m[w]);}catch(y){n.push({phase:"auth",label:`auth.${d} row ${w+1}/${m.length}`,statement:m[w],error:String(y)});}}}let h=await Ri(e);for(let d of h){for(let m=0;m<d.inserts.length;m++){a++;try{await r.exec(d.inserts[m]);}catch(w){n.push({phase:"data",label:`${d.schema}.${d.table} row ${m+1}/${d.inserts.length}`,statement:d.inserts[m],error:String(w)});}}for(let m=0;m<d.sequenceResets.length;m++)try{await r.exec(d.sequenceResets[m]);}catch(w){n.push({phase:"data",label:`${d.schema}.${d.table} sequence reset ${m+1}/${d.sequenceResets.length}`,statement:d.sequenceResets[m],error:String(w)});}}}finally{await r.close().catch(()=>{});}return {ok:n.length===0,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:n}}var Dd=g(()=>{lr();Ye();Pd();xn();vi();Il();Dl();});function jd(e){if(console.log(N.default.bold("Readiness Report")),console.log(` db reachable: ${e.dbReachable?N.default.green("yes"):N.default.red("no")} schema statements: ${N.default.cyan(e.schemaStatementCount)} schema bytes: ${N.default.cyan(e.schemaBytes)}`),console.log(` auth \u2014 users: ${N.default.cyan(e.auth.users)} sessions: ${N.default.cyan(e.auth.sessions)} identities: ${N.default.cyan(e.auth.identities)} refresh_tokens: ${N.default.cyan(e.auth.refresh_tokens)} jwt_secret: ${e.auth.jwt_secret_set?N.default.green("set"):N.default.yellow("unset")}`),e.tables.length>0){console.log(N.default.dim(" tables:"));for(let t of e.tables){let r=t.issues.length>0?N.default.yellow(` (${t.issues.length} issues)`):"",n=t.schema?`${t.schema}.`:"";console.log(` ${n}${t.table}: ${N.default.cyan(t.rowCount)} rows${r}`);}}if(e.errors.length>0){console.log(N.default.red("Errors:"));for(let t of e.errors)console.log(` ${N.default.red("\u2717")} ${t}`);}if(e.warnings.length>0){console.log(N.default.yellow("Warnings:"));for(let t of e.warnings)console.log(` ${N.default.yellow("!")} ${t}`);}console.log(),console.log(e.ok?N.default.green("Ready to upgrade."):N.default.red("Not ready."));}function Fd(e){if(console.log(),console.log(N.default.bold("Rehearsal (in-memory pglite)")),console.log(` auth schema: ${N.default.cyan(e.baseSchemaStatements)} stmts user schema: ${N.default.cyan(e.schemaStatements)} stmts auth: ${N.default.cyan(e.authInserts)} inserts data: ${N.default.cyan(e.dataInserts)} inserts`),e.failures.length>0){console.log(N.default.red(` ${e.failures.length} failure(s):`));for(let t of e.failures)console.log(N.default.red(` \u2717 [${t.phase}] ${t.label}`)),console.log(N.default.dim(` ${t.statement}`)),console.log(N.default.dim(` ${t.error}`));}console.log(e.ok?N.default.green(" rehearsal passed"):N.default.red(" rehearsal failed"));}function Md(e){console.log(),console.log(N.default.bold("SQLite Shim Audit")),console.log(` fields: ${N.default.cyan(e.summary.total)} passed: ${N.default.green(String(e.summary.passed))} warned: ${N.default.yellow(String(e.summary.warned))} failed: ${N.default.red(String(e.summary.failed))}`),e.results.length===0&&console.log(N.default.dim(" no shim-backed fields found"));for(let t of e.results.filter(r=>r.status!=="pass")){let r=t.status==="fail"?N.default.red:N.default.yellow;if(console.log(` ${r(t.status)} ${t.field} (${t.pg_type}) rows: ${N.default.cyan(t.rows_checked)} affected: ${N.default.cyan(t.affected_rows??0)}`),t.message&&console.log(` ${t.message}`),t.samples?.length)for(let n of t.samples)console.log(N.default.dim(` sample ${JSON.stringify(n.id)} raw=${JSON.stringify(n.raw_value)}`));t.action&&console.log(N.default.dim(` action: ${t.action}`));}console.log(e.summary.upgrade_safe?N.default.green(" shim audit passed"):N.default.red(" shim audit failed"));}function jl(e){if(console.log(),console.log(N.default.bold(N.default.green("Upgrade complete."))),console.log(),console.log(` ${N.default.bold("Project URL:")} ${N.default.cyan(e.projectUrl)}`),console.log(` ${N.default.bold("API URL:")} ${N.default.cyan(e.apiUrl)}`),e.studioUrl&&console.log(` ${N.default.bold("Studio URL:")} ${N.default.cyan(e.studioUrl)}`),console.log(` ${N.default.bold("Ref:")} ${N.default.cyan(e.projectRef)}`),console.log(),console.log(` ${N.default.bold("anon key:")} ${e.anonKey}`),console.log(` ${N.default.bold("service_role key:")} ${e.serviceRoleKey}`),console.log(` ${N.default.bold("db password:")} ${e.dbPassword}`),console.log(),console.log(` migrated auth \u2014 users: ${N.default.cyan(e.auth.users)} sessions: ${N.default.cyan(e.auth.sessions)} identities: ${N.default.cyan(e.auth.identities)} refresh_tokens: ${N.default.cyan(e.auth.refresh_tokens)}`),console.log(` jwt secret: ${e.jwtMigrated?N.default.green("migrated"):N.default.yellow("not migrated \u2014 users must re-authenticate")}`),e.warnings.length>0){console.log(),console.log(N.default.yellow("Warnings:"));for(let t of e.warnings)console.log(` ${N.default.yellow("!")} ${t}`);}console.log(),console.log(N.default.bold("Update your supabase-js client:")),console.log(` url: ${N.default.cyan(e.apiUrl)}`),console.log(` anonKey: ${N.default.cyan(e.anonKey)}`),console.log();}var N,Ud=g(()=>{N=te(ae());});function Bd(e){return {kty:"oct",alg:"HS256",k:Buffer$1.from(e,"utf8").toString("base64url")}}var qd=g(()=>{Mo();});async function Hd(e){let t=e.trim();if(!t)return "";let{PGlite:r}=await We("@supabase/lite/pglite","pglite","@electric-sql/pglite"),n=new r;try{return await n.exec(Et(xt(t))),await n.exec(Ws),await y_(n,t)}finally{await n.close().catch(()=>{});}}async function y_(e,t){return t?(await e.exec(t),await w_(e)):""}async function w_(e){let t=await e.query(`
379
381
  SELECT table_schema, table_name, column_name, is_nullable, data_type,
380
382
  udt_name, udt_schema, character_maximum_length,
381
383
  numeric_precision, numeric_scale, column_default, ordinal_position
@@ -392,30 +394,30 @@ CREATE TABLE IF NOT EXISTS auth.audit_log_entries (
392
394
  WHERE tc.constraint_type = 'PRIMARY KEY'
393
395
  AND tc.table_schema NOT IN ('pg_catalog', 'information_schema', 'pg_toast')
394
396
  ORDER BY kcu.ordinal_position
395
- `),n=new Map;for(let o of r.rows){let a=`${o.table_schema}.${o.table_name}`,l=n.get(a)??[];l.push(o.column_name),n.set(a,l);}let s=new Map;for(let o of t.rows){let a=`${o.table_schema}.${o.table_name}`,l=s.get(a)??[];l.push(o),s.set(a,l);}let i=[];for(let[o,a]of s){let l=a[0].table_schema,c=a[0].table_name,p=n.get(o)??[],u=a.map(f=>w_(f,p));i.push(`CREATE TABLE ${Dl(l)}.${Dl(c)} (
397
+ `),n=new Map;for(let o of r.rows){let a=`${o.table_schema}.${o.table_name}`,l=n.get(a)??[];l.push(o.column_name),n.set(a,l);}let s=new Map;for(let o of t.rows){let a=`${o.table_schema}.${o.table_name}`,l=s.get(a)??[];l.push(o),s.set(a,l);}let i=[];for(let[o,a]of s){let l=a[0].table_schema,c=a[0].table_name,p=n.get(o)??[],u=a.map(f=>b_(f,p));i.push(`CREATE TABLE ${Fl(l)}.${Fl(c)} (
396
398
  ${u.join(`,
397
399
  `)}
398
400
  );`);}return i.join(`
399
401
 
400
- `)}function Dl(e){return /^[a-z_][a-z0-9_]*$/.test(e)?e:`"${e.replace(/"/g,'""')}"`}function w_(e,t){let r=[Dl(e.column_name)];return r.push(b_(e)),e.is_nullable==="NO"&&!t.includes(e.column_name)&&r.push("NOT NULL"),e.column_default!==null&&r.push(`DEFAULT ${e.column_default}`),t.length===1&&t[0]===e.column_name&&r.push("PRIMARY KEY"),r.join(" ")}function b_(e){return e.data_type==="ARRAY"?`${e.udt_name.startsWith("_")?e.udt_name.slice(1):e.udt_name}[]`:e.data_type==="USER-DEFINED"?`${e.udt_schema}.${e.udt_name}`:e.data_type==="character varying"&&e.character_maximum_length?`varchar(${e.character_maximum_length})`:e.data_type==="numeric"&&e.numeric_precision&&e.numeric_scale!==null?`numeric(${e.numeric_precision},${e.numeric_scale})`:e.data_type}var Wd=g(()=>{lr();En();});function Gd(e){return !e||e==="main"?"public":e}function Kt(e){return `"${e.replace(/"/g,'""')}"`}function E_(e,t){return Kt(e==="public"?t:`${e}.${t}`)}function jl(e){return `${e.schema}.${e.table}.${e.column}`}function x_(e){let t=e.filter(s=>s.status==="pass").length,r=e.filter(s=>s.status==="warn").length,n=e.filter(s=>s.status==="fail").length;return {total:e.length,passed:t,warned:r,failed:n,upgrade_safe:n===0}}async function __(e){let t=e.connection.config?.translation?.deparse?.schema;if(t instanceof Map&&t.size>0)return t;let r=await Ns(e),n=await ge(e);if(r.trim()){let i=[await Hd(r),n].filter(o=>o.trim().length>0).join(`
401
- `);return i.trim()?(await Rn(i)).schema:new Map}return n.trim()?(await Rn(n)).schema:new Map}async function $_(e){let t=await __(e),r=[];for(let n of t.values())for(let s of n.all())s.isShimBacked&&r.push({schema:Gd(s.context.schema),table:s.context.table,column:s.context.column,field:s});return r}function v_(e,t){return e==="fail"||t==="fail"?"fail":e==="warn"||t==="warn"?"warn":"pass"}async function T_(e,t,r){return (await e.connection.introspect()).primary_keys.find(i=>Gd(i.schema)===t&&i.table===r)?.columns??[]}async function A_(e,t){if(e.connection.dialect!=="sqlite")return {field:jl(t),pg_type:t.field.context.pgTypeName,status:"warn",rows_checked:0,affected_rows:0,message:"Shim at-rest scan only applies to SQLite-backed projects.",action:"Run this audit against the SQLite Supalite project before upgrading."};let n=E_(t.schema,t.table),s=await T_(e,t.schema,t.table),i=s.length>0?s:["rowid"],a=[...s.length>0?s.map(m=>`${Kt(m)} AS ${Kt(`id_${m}`)}`):[`rowid AS ${Kt("id_rowid")}`],`${Kt(t.column)} AS ${Kt("__lite_value")}`].join(", "),l;try{l=await e.connection.exec(`SELECT ${a} FROM ${n}`);}catch(m){return {field:jl(t),pg_type:Fl(t.field),status:"fail",rows_checked:0,affected_rows:0,message:`Declared shim field could not be scanned in SQLite: ${String(m)}`,action:"Apply the declared schema to the local Supalite database, then rerun the dry-run audit before upgrading."}}let c=l?.rows??[],p="pass",u=0,f=null,h,d=[];for(let m of c){let w=t.field.validateStorage(m.__lite_value);if(p=v_(p,w.status),w.status!=="pass"&&(u++,f??=w.message,h??=w.action,d.length<S_)){let y={};for(let E of i)y[E]=m[`id_${E}`];d.push({id:y,raw_value:m.__lite_value});}}return {field:jl(t),pg_type:Fl(t.field),status:p,rows_checked:c.length,...u>0?{affected_rows:u}:{},message:f,...d.length>0?{samples:d}:{},...h?{action:h}:{}}}function Fl(e){if(e instanceof St)return `${e.elementField?Fl(e.elementField):e.context.pgTypeName}[]`;if(e instanceof Ht&&e.numericPrecision){let{precision:t,scale:r}=e.numericPrecision;return `${e.context.pgTypeName}(${t},${r})`}return e instanceof le&&e.lengthConstraint!==void 0?`${e.context.pgTypeName}(${e.lengthConstraint})`:e.context.pgTypeName}async function Ml(e){let t=await $_(e),r=[];for(let n of t)r.push(await A_(e,n));return {summary:x_(r),results:r}}var S_,zd=g(()=>{Ye();wt();Wd();bi();Bs();Us();qe();S_=3;});function Vd(e){let t=e.auth??{},r={};return typeof t.site_url=="string"&&(r.site_url=t.site_url),Array.isArray(t.additional_redirect_urls)&&(r.uri_allow_list=t.additional_redirect_urls.join(",")),typeof t.jwt_expiry=="number"&&(r.jwt_exp=t.jwt_expiry),typeof t.enable_signup=="boolean"&&(r.disable_signup=!t.enable_signup),typeof t.enable_anonymous_sign_ins=="boolean"&&(r.external_anonymous_users_enabled=t.enable_anonymous_sign_ins),typeof t.minimum_password_length=="number"&&(r.min_password_length=t.minimum_password_length),typeof t.email?.enable_confirmations=="boolean"&&(r.mailer_autoconfirm=!t.email.enable_confirmations),r}var Kd=g(()=>{});function C_(e){if(e.length===0)return "";if(e.length===1)return e[0];let t=e[0].match(Xd);if(!t)return e.map(i=>i.trim().endsWith(";")?i:`${i};`).join(" ");let r=t[1],n=t[3]??"",s=[t[2]];for(let i=1;i<e.length;i++){let o=e[i].match(Xd);if(!o||o[1]!==r||(o[3]??"")!==n)return e.map(a=>a.trim().endsWith(";")?a:`${a};`).join(" ");s.push(o[2]);}return `${r}${s.join(", ")}${n}`}async function Jd(e,t,r={}){let n=r.sizes??[50,10,1],s=[],i=0,o=t.length,a=async(l,c)=>{if(l.length===0)return;let p=n[c]??1;if(l.length===1||p===1){for(let u of l){try{await e.runSql(u);}catch(f){s.push({statement:u,error:String(f)});}i++,r.onProgress?.(i,o);}return}for(let u=0;u<l.length;u+=p){let f=l.slice(u,u+p),h=C_(f);try{await e.runSql(h),i+=f.length,r.onProgress?.(i,o);}catch{await a(f,c+1);}}};return await a(t,0),s}var Xd,Yd=g(()=>{Xd=/^(INSERT INTO [^(]+\([^)]+\)\s*VALUES\s*)(\(.*\))(\s*ON CONFLICT[\s\S]*)?$/i;});async function R_(e,t,r,n){n.onSql?.(t,r);try{await e.runSql(t);}catch(s){throw new Error(`Failed SQL (${r}): ${String(s)}
402
- ${t}`,{cause:s})}}async function Er(e,t,r,n,s={}){if(r.length===0)return;n.onBatchStart?.(t,r.length);let i=await Jd(e,r,{sizes:s.sizes??n.batchSizes,onProgress:(o,a)=>n.onBatchProgress?.(t,o,a)});if(i.length>0)throw n.onBatchFailure?.(t,i),new Error(`${t} had ${i.length} failures`);n.onBatchEnd?.(t,r.length,s.unit??"rows");}async function Ul(e,t,r){let n=await ge(e),s=$t(n);r.onSchemaStart?.(s.length);for(let c=0;c<s.length;c++)r.onSchemaProgress?.(c+1,s.length),await R_(t,s[c],`schema ${c+1}/${s.length}`,r);r.onSchemaEnd?.(s.length);let i=await Ti(e,{target:r.authTarget??"supabase"}),o={users:i.users.length,sessions:r.migrateSessions?i.sessions.length:0,identities:i.identities.length,refresh_tokens:r.migrateSessions?i.refresh_tokens.length:0};await Er(t,"Migrating auth.users",i.users,r),await Er(t,"Migrating auth.identities",i.identities,r),r.migrateSessions?(await Er(t,"Migrating auth.sessions",i.sessions,r),await Er(t,"Migrating auth.refresh_tokens",i.refresh_tokens,r)):(i.sessions.length>0||i.refresh_tokens.length>0)&&r.onSkip?.(`Skipped ${i.sessions.length} sessions and ${i.refresh_tokens.length} refresh tokens (existing tokens will be invalidated).`);let a=await Ci(e),l=a.filter(c=>c.inserts.length>0);l.length===0&&r.onSkip?.("No user data rows to migrate.");for(let c of l)await Er(t,`Migrating ${c.schema}.${c.table}`,c.inserts,r);for(let c of l)await Er(t,`Resetting ${c.schema}.${c.table} sequences`,c.sequenceResets,r,{sizes:[1],unit:"statements"});if(r.syncAuthConfig!==false&&t.updateAuthConfig){let c=Vd(e.config);Object.keys(c).length>0&&(r.onAuthConfigStart?.(),await t.updateAuthConfig(c),r.onAuthConfigEnd?.());}return {schemaStatements:s.length,auth:o,dataTables:a}}var Qd=g(()=>{Ye();Kd();Ol();Il();Yd();$i();});function In(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}function Zd(e,t=new Map){if(!e||typeof e!="object")return t;for(let[r,n]of Object.entries(e))typeof n=="string"?t.set(In(r),n):n&&typeof n=="object"&&Zd(n,t);return t}function On(e,t,r){for(let n of t){let s=e.get(In(n));if(s)return s}throw new Error(`Supabase status JSON is missing ${r}`)}function I_(e){let t=JSON.parse(e),r=Zd(t);return {apiUrl:On(r,["API_URL","api_url","API URL","Project URL"],"API URL"),studioUrl:r.get(In("Studio URL"))??r.get(In("STUDIO_URL"))??r.get(In("studio_url")),dbUrl:On(r,["DB_URL","db_url","DB URL"],"DB URL"),anonKey:On(r,["ANON_KEY","anon_key","anon key","Publishable"],"anon key"),serviceRoleKey:On(r,["SERVICE_ROLE_KEY","service_role_key","service role key","Secret"],"service role key"),jwtSecret:On(r,["JWT_SECRET","jwt_secret","JWT secret"],"JWT secret")}}function eh(e){try{return decodeURIComponent(new URL(e).password)}catch{return ""}}function th(e=process.cwd()){return e}async function L_(){return await new Promise((e,t)=>{let r=k_.createServer();r.once("error",t),r.listen(0,"127.0.0.1",()=>{let n=r.address();r.close(()=>{typeof n=="object"&&n?e(n.port):t(new Error("Could not allocate a free local port"));});});})}async function D_(){let e=new Set,t=async()=>{for(;;){let r=await L_();if(!e.has(r))return e.add(r),r}};return {api:await t(),db:await t(),shadow:await t(),studio:await t(),inbucket:await t(),analytics:await t(),pooler:await t(),edgeInspector:await t()}}async function Nn(e,t={}){let r=process.env.LITE_SUPABASE_CLI?.split(/\s+/).filter(Boolean)??O_,{spawn:n}=await import('node:child_process').catch(()=>{throw new Error("Local Supabase upgrade requires a Node-compatible runtime")}),[s,...i]=r;return await new Promise((o,a)=>{let l=n(s,[...i,...e],{cwd:t.cwd,env:{...process.env,SUPABASE_TELEMETRY_DISABLED:"1",DO_NOT_TRACK:"1"}}),c=[],p=[],u=setTimeout(()=>l.kill(),t.timeoutMs??12e4);l.stdout?.on("data",f=>c.push(Buffer.from(f))),l.stderr?.on("data",f=>p.push(Buffer.from(f))),l.on("error",f=>{clearTimeout(u),a(f);}),l.on("close",f=>{clearTimeout(u);let h=Buffer.concat(c).toString("utf8"),d=Buffer.concat(p).toString("utf8");if(f!==0){a(new Error([`supabase ${e.join(" ")} failed with exit code ${f}`,h,d].filter(Boolean).join(`
402
+ `)}function Fl(e){return /^[a-z_][a-z0-9_]*$/.test(e)?e:`"${e.replace(/"/g,'""')}"`}function b_(e,t){let r=[Fl(e.column_name)];return r.push(S_(e)),e.is_nullable==="NO"&&!t.includes(e.column_name)&&r.push("NOT NULL"),e.column_default!==null&&r.push(`DEFAULT ${e.column_default}`),t.length===1&&t[0]===e.column_name&&r.push("PRIMARY KEY"),r.join(" ")}function S_(e){return e.data_type==="ARRAY"?`${e.udt_name.startsWith("_")?e.udt_name.slice(1):e.udt_name}[]`:e.data_type==="USER-DEFINED"?`${e.udt_schema}.${e.udt_name}`:e.data_type==="character varying"&&e.character_maximum_length?`varchar(${e.character_maximum_length})`:e.data_type==="numeric"&&e.numeric_precision&&e.numeric_scale!==null?`numeric(${e.numeric_precision},${e.numeric_scale})`:e.data_type}var Wd=g(()=>{lr();xn();});function Gd(e){return !e||e==="main"?"public":e}function Kt(e){return `"${e.replace(/"/g,'""')}"`}function x_(e,t){return Kt(e==="public"?t:`${e}.${t}`)}function Ml(e){return `${e.schema}.${e.table}.${e.column}`}function __(e){let t=e.filter(s=>s.status==="pass").length,r=e.filter(s=>s.status==="warn").length,n=e.filter(s=>s.status==="fail").length;return {total:e.length,passed:t,warned:r,failed:n,upgrade_safe:n===0}}async function $_(e){let t=e.connection.config?.translation?.deparse?.schema;if(t instanceof Map&&t.size>0)return t;let r=await Is(e),n=await ge(e);if(r.trim()){let i=[await Hd(r),n].filter(o=>o.trim().length>0).join(`
403
+ `);return i.trim()?(await kn(i)).schema:new Map}return n.trim()?(await kn(n)).schema:new Map}async function v_(e){let t=await $_(e),r=[];for(let n of t.values())for(let s of n.all())s.isShimBacked&&r.push({schema:Gd(s.context.schema),table:s.context.table,column:s.context.column,field:s});return r}function T_(e,t){return e==="fail"||t==="fail"?"fail":e==="warn"||t==="warn"?"warn":"pass"}async function A_(e,t,r){return (await e.connection.introspect()).primary_keys.find(i=>Gd(i.schema)===t&&i.table===r)?.columns??[]}async function C_(e,t){if(e.connection.dialect!=="sqlite")return {field:Ml(t),pg_type:t.field.context.pgTypeName,status:"warn",rows_checked:0,affected_rows:0,message:"Shim at-rest scan only applies to SQLite-backed projects.",action:"Run this audit against the SQLite Supalite project before upgrading."};let n=x_(t.schema,t.table),s=await A_(e,t.schema,t.table),i=s.length>0?s:["rowid"],a=[...s.length>0?s.map(m=>`${Kt(m)} AS ${Kt(`id_${m}`)}`):[`rowid AS ${Kt("id_rowid")}`],`${Kt(t.column)} AS ${Kt("__lite_value")}`].join(", "),l;try{l=await e.connection.exec(`SELECT ${a} FROM ${n}`);}catch(m){return {field:Ml(t),pg_type:Ul(t.field),status:"fail",rows_checked:0,affected_rows:0,message:`Declared shim field could not be scanned in SQLite: ${String(m)}`,action:"Apply the declared schema to the local Supalite database, then rerun the dry-run audit before upgrading."}}let c=l?.rows??[],p="pass",u=0,f=null,h,d=[];for(let m of c){let w=t.field.validateStorage(m.__lite_value);if(p=T_(p,w.status),w.status!=="pass"&&(u++,f??=w.message,h??=w.action,d.length<E_)){let y={};for(let E of i)y[E]=m[`id_${E}`];d.push({id:y,raw_value:m.__lite_value});}}return {field:Ml(t),pg_type:Ul(t.field),status:p,rows_checked:c.length,...u>0?{affected_rows:u}:{},message:f,...d.length>0?{samples:d}:{},...h?{action:h}:{}}}function Ul(e){if(e instanceof St)return `${e.elementField?Ul(e.elementField):e.context.pgTypeName}[]`;if(e instanceof Ht&&e.numericPrecision){let{precision:t,scale:r}=e.numericPrecision;return `${e.context.pgTypeName}(${t},${r})`}return e instanceof le&&e.lengthConstraint!==void 0?`${e.context.pgTypeName}(${e.lengthConstraint})`:e.context.pgTypeName}async function Bl(e){let t=await v_(e),r=[];for(let n of t)r.push(await C_(e,n));return {summary:__(r),results:r}}var E_,zd=g(()=>{Ye();wt();Wd();Si();qs();Bs();qe();E_=3;});function Vd(e){let t=e.auth??{},r={};return typeof t.site_url=="string"&&(r.site_url=t.site_url),Array.isArray(t.additional_redirect_urls)&&(r.uri_allow_list=t.additional_redirect_urls.join(",")),typeof t.jwt_expiry=="number"&&(r.jwt_exp=t.jwt_expiry),typeof t.enable_signup=="boolean"&&(r.disable_signup=!t.enable_signup),typeof t.enable_anonymous_sign_ins=="boolean"&&(r.external_anonymous_users_enabled=t.enable_anonymous_sign_ins),typeof t.minimum_password_length=="number"&&(r.min_password_length=t.minimum_password_length),typeof t.email?.enable_confirmations=="boolean"&&(r.mailer_autoconfirm=!t.email.enable_confirmations),r}var Kd=g(()=>{});function R_(e){if(e.length===0)return "";if(e.length===1)return e[0];let t=e[0].match(Xd);if(!t)return e.map(i=>i.trim().endsWith(";")?i:`${i};`).join(" ");let r=t[1],n=t[3]??"",s=[t[2]];for(let i=1;i<e.length;i++){let o=e[i].match(Xd);if(!o||o[1]!==r||(o[3]??"")!==n)return e.map(a=>a.trim().endsWith(";")?a:`${a};`).join(" ");s.push(o[2]);}return `${r}${s.join(", ")}${n}`}async function Jd(e,t,r={}){let n=r.sizes??[50,10,1],s=[],i=0,o=t.length,a=async(l,c)=>{if(l.length===0)return;let p=n[c]??1;if(l.length===1||p===1){for(let u of l){try{await e.runSql(u);}catch(f){s.push({statement:u,error:String(f)});}i++,r.onProgress?.(i,o);}return}for(let u=0;u<l.length;u+=p){let f=l.slice(u,u+p),h=R_(f);try{await e.runSql(h),i+=f.length,r.onProgress?.(i,o);}catch{await a(f,c+1);}}};return await a(t,0),s}var Xd,Yd=g(()=>{Xd=/^(INSERT INTO [^(]+\([^)]+\)\s*VALUES\s*)(\(.*\))(\s*ON CONFLICT[\s\S]*)?$/i;});async function k_(e,t,r,n){n.onSql?.(t,r);try{await e.runSql(t);}catch(s){throw new Error(`Failed SQL (${r}): ${String(s)}
404
+ ${t}`,{cause:s})}}async function Er(e,t,r,n,s={}){if(r.length===0)return;n.onBatchStart?.(t,r.length);let i=await Jd(e,r,{sizes:s.sizes??n.batchSizes,onProgress:(o,a)=>n.onBatchProgress?.(t,o,a)});if(i.length>0)throw n.onBatchFailure?.(t,i),new Error(`${t} had ${i.length} failures`);n.onBatchEnd?.(t,r.length,s.unit??"rows");}async function ql(e,t,r){let n=await ge(e),s=$t(n);r.onSchemaStart?.(s.length);for(let c=0;c<s.length;c++)r.onSchemaProgress?.(c+1,s.length),await k_(t,s[c],`schema ${c+1}/${s.length}`,r);r.onSchemaEnd?.(s.length);let i=await Ai(e,{target:r.authTarget??"supabase"}),o={users:i.users.length,sessions:r.migrateSessions?i.sessions.length:0,identities:i.identities.length,refresh_tokens:r.migrateSessions?i.refresh_tokens.length:0};await Er(t,"Migrating auth.users",i.users,r),await Er(t,"Migrating auth.identities",i.identities,r),r.migrateSessions?(await Er(t,"Migrating auth.sessions",i.sessions,r),await Er(t,"Migrating auth.refresh_tokens",i.refresh_tokens,r)):(i.sessions.length>0||i.refresh_tokens.length>0)&&r.onSkip?.(`Skipped ${i.sessions.length} sessions and ${i.refresh_tokens.length} refresh tokens (existing tokens will be invalidated).`);let a=await Ri(e),l=a.filter(c=>c.inserts.length>0);l.length===0&&r.onSkip?.("No user data rows to migrate.");for(let c of l)await Er(t,`Migrating ${c.schema}.${c.table}`,c.inserts,r);for(let c of l)await Er(t,`Resetting ${c.schema}.${c.table} sequences`,c.sequenceResets,r,{sizes:[1],unit:"statements"});if(r.syncAuthConfig!==false&&t.updateAuthConfig){let c=Vd(e.config);Object.keys(c).length>0&&(r.onAuthConfigStart?.(),await t.updateAuthConfig(c),r.onAuthConfigEnd?.());}return {schemaStatements:s.length,auth:o,dataTables:a}}var Qd=g(()=>{Ye();Kd();Il();Dl();Yd();vi();});function Ln(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}function Zd(e,t=new Map){if(!e||typeof e!="object")return t;for(let[r,n]of Object.entries(e))typeof n=="string"?t.set(Ln(r),n):n&&typeof n=="object"&&Zd(n,t);return t}function Nn(e,t,r){for(let n of t){let s=e.get(Ln(n));if(s)return s}throw new Error(`Supabase status JSON is missing ${r}`)}function L_(e){let t=JSON.parse(e),r=Zd(t);return {apiUrl:Nn(r,["API_URL","api_url","API URL","Project URL"],"API URL"),studioUrl:r.get(Ln("Studio URL"))??r.get(Ln("STUDIO_URL"))??r.get(Ln("studio_url")),dbUrl:Nn(r,["DB_URL","db_url","DB URL"],"DB URL"),anonKey:Nn(r,["ANON_KEY","anon_key","anon key","Publishable"],"anon key"),serviceRoleKey:Nn(r,["SERVICE_ROLE_KEY","service_role_key","service role key","Secret"],"service role key"),jwtSecret:Nn(r,["JWT_SECRET","jwt_secret","JWT secret"],"JWT secret")}}function eh(e){try{return decodeURIComponent(new URL(e).password)}catch{return ""}}function th(e=process.cwd()){return e}async function D_(){return await new Promise((e,t)=>{let r=P_.createServer();r.once("error",t),r.listen(0,"127.0.0.1",()=>{let n=r.address();r.close(()=>{typeof n=="object"&&n?e(n.port):t(new Error("Could not allocate a free local port"));});});})}async function j_(){let e=new Set,t=async()=>{for(;;){let r=await D_();if(!e.has(r))return e.add(r),r}};return {api:await t(),db:await t(),shadow:await t(),studio:await t(),inbucket:await t(),analytics:await t(),pooler:await t(),edgeInspector:await t()}}async function In(e,t={}){let r=process.env.LITE_SUPABASE_CLI?.split(/\s+/).filter(Boolean)??N_,{spawn:n}=await import('node:child_process').catch(()=>{throw new Error("Local Supabase upgrade requires a Node-compatible runtime")}),[s,...i]=r;return await new Promise((o,a)=>{let l=n(s,[...i,...e],{cwd:t.cwd,env:{...process.env,SUPABASE_TELEMETRY_DISABLED:"1",DO_NOT_TRACK:"1"}}),c=[],p=[],u=setTimeout(()=>l.kill(),t.timeoutMs??12e4);l.stdout?.on("data",f=>c.push(Buffer.from(f))),l.stderr?.on("data",f=>p.push(Buffer.from(f))),l.on("error",f=>{clearTimeout(u),a(f);}),l.on("close",f=>{clearTimeout(u);let h=Buffer.concat(c).toString("utf8"),d=Buffer.concat(p).toString("utf8");if(f!==0){a(new Error([`supabase ${e.join(" ")} failed with exit code ${f}`,h,d].filter(Boolean).join(`
403
405
  `)));return}o({stdout:h,stderr:d});});})}function se(e,t,r,n){let s=new RegExp(`(\\[${t.replace(".","\\.")}\\][\\s\\S]*?)(?=\\n\\[|$)`),i=e.match(s);if(!i)return `${e.trimEnd()}
404
406
 
405
407
  [${t}]
406
408
  ${r} = ${n}
407
409
  `;let o=i[1],a=new RegExp(`(^${r}\\s*=\\s*).*$`,"m"),l=a.test(o)?o.replace(a,`$1${n}`):`${o.trimEnd()}
408
410
  ${r} = ${n}
409
- `;return e.replace(o,l)}function j_(e,t,r){let n=new RegExp(`(\\[${t.replace(".","\\.")}\\][\\s\\S]*?)(?=\\n\\[|$)`),s=e.match(n);if(!s)return e;let i=s[1],o=r.map(l=>l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),a=new RegExp(`^\\s*(${o})\\s*=.*(?:\\n|$)`,"gm");return e.replace(i,i.replace(a,""))}function F_(e){return j_(e,"db",["driver","url"])}function M_(e){let t=e.match(/(\[db\][\s\S]*?)(?=\n\[|$)/)?.[1];return t?/^\s*driver\s*=\s*["'](sqlite|sqlite-postgres|pglite|postgres)["']/m.test(t)?true:/^\s*url\s*=/m.test(t):false}async function Bl(e){return await pe__default.access(e).then(()=>true).catch(()=>false)}async function rh(e){let t=Me__default.join(e,"supabase","config.toml");if(!await Bl(t))return null;let r=await pe__default.readFile(t,"utf-8");if(!M_(r))return null;let n=`${t}.bak`;return await Bl(n)||await pe__default.writeFile(n,r,"utf-8"),n}async function U_(e){let t=Me__default.join(e,"supabase","config.toml");await Bl(t)||(await pe__default.mkdir(e,{recursive:true}),await Nn(["init","--workdir",e,"--yes"],{timeoutMs:6e4}));}async function B_(e,t,r){let n=Me__default.join(e,"supabase","config.toml"),s=F_(await pe__default.readFile(n,"utf-8"));s=s.replace(/^project_id\s*=.*$/m,`project_id = "${t}"`),s=se(s,"api","port",String(r.api)),s=se(s,"db","port",String(r.db)),s=se(s,"db","shadow_port",String(r.shadow)),s=se(s,"db","major_version","15"),s=se(s,"db.seed","enabled","false"),s=se(s,"studio","enabled","true"),s=se(s,"studio","port",String(r.studio)),s=se(s,"inbucket","enabled","false"),s=se(s,"inbucket","port",String(r.inbucket)),s=se(s,"realtime","enabled","false"),s=se(s,"storage","enabled","false"),s=se(s,"edge_runtime","enabled","false"),s=se(s,"edge_runtime","inspector_port",String(r.edgeInspector)),s=se(s,"analytics","enabled","false"),s=se(s,"analytics","port",String(r.analytics)),s=se(s,"db.pooler","enabled","false"),s=se(s,"db.pooler","port",String(r.pooler)),await pe__default.writeFile(n,s,"utf-8");}function nh(e){return JSON.stringify(e)}function q_(e){return `[${e.map(nh).join(", ")}]`}async function H_(e,t){if(!t)return;let r=Me__default.join(e,"supabase","config.toml"),n=await pe__default.readFile(r,"utf-8"),s=t.auth??{},i=s.email??{},o=t.api??{};typeof o.max_rows=="number"&&(n=se(n,"api","max_rows",String(o.max_rows))),typeof s.site_url=="string"&&(n=se(n,"auth","site_url",nh(s.site_url))),Array.isArray(s.additional_redirect_urls)&&(n=se(n,"auth","additional_redirect_urls",q_(s.additional_redirect_urls))),typeof s.jwt_expiry=="number"&&(n=se(n,"auth","jwt_expiry",String(s.jwt_expiry))),typeof s.enable_signup=="boolean"&&(n=se(n,"auth","enable_signup",String(s.enable_signup))),typeof s.enable_anonymous_sign_ins=="boolean"&&(n=se(n,"auth","enable_anonymous_sign_ins",String(s.enable_anonymous_sign_ins))),typeof s.minimum_password_length=="number"&&(n=se(n,"auth","minimum_password_length",String(s.minimum_password_length))),typeof i.enable_confirmations=="boolean"&&(n=se(n,"auth.email","enable_confirmations",String(i.enable_confirmations))),await pe__default.writeFile(r,n,"utf-8");}var O_,N_,Ri,sh=g(()=>{lr();O_=["bunx","supabase@2.98.1"],N_=["mailpit","realtime","storage-api","imgproxy","edge-runtime","logflare","vector","supavisor"];Ri=class e{constructor(t,r,n,s){this.workdir=t;this.projectId=r;this.status=n;this.cleanupOnStop=s;}stopped=false;static async start(t={}){let r=t.workdir??await pe__default.mkdtemp(Me__default.join(Kw.tmpdir(),"lite-local-supa-")),n=t.projectId??`lite-local-${Date.now().toString(36)}`,s=t.cleanupOnStop??!t.workdir,i=await D_();try{await U_(r),await B_(r,n,i),await H_(r,t.sourceConfig),await Nn(["start","--workdir",r,"--yes","--exclude",N_.join(",")],{timeoutMs:5*6e4});let{stdout:o}=await Nn(["status","--workdir",r,"-o","json"],{timeoutMs:6e4});return new e(r,n,I_(o),s)}catch(o){throw await Nn(["stop","--workdir",r,"--no-backup"],{timeoutMs:12e4}).catch(()=>{}),s&&await pe__default.rm(r,{recursive:true,force:true}).catch(()=>{}),o}}async runSql(t){let{createPostgresConnection:r}=await We("@supabase/lite/postgres","postgres","postgres"),n=r({url:this.status.dbUrl});try{await n.exec(t);}finally{await n.close();}}async stop(){this.stopped||(this.stopped=true,await Nn(["stop","--workdir",this.workdir,"--no-backup"],{timeoutMs:12e4}).catch(()=>{}),this.cleanupOnStop&&await pe__default.rm(this.workdir,{recursive:true,force:true}));}};});async function ki(){let e=await Cn({message:"Email",placeholder:"Enter your email",validate:t=>{try{nu(t,{domains:["supabase.io"],panic:!0});return}catch(r){return r}}});return Ee(e)&&process.exit(1),e}async function Pi(e=false){let t=await Tn({message:"Password",validate:r=>{try{su(r,{panic:!0});return}catch(n){return n}}});if(Ee(t)&&process.exit(1),e){let r=await Tn({message:"Confirm Password",validate:n=>{try{if(n!==t)throw new Error("Passwords do not match");return}catch(s){return s}}});Ee(r)&&process.exit(1);}return t}async function ih(){let e=await Cn({message:"Project Name",placeholder:"Enter your project name"});return Ee(e)&&process.exit(1),e}async function Oi(e){let t=await vn({message:e,initialValue:true});return Ee(t)&&process.exit(1),t}var xr=g(()=>{Qe();Lr();});var uh={};de(uh,{isNonInteractive:()=>ql,resolveSessionMigration:()=>ch,resolveTarget:()=>lh,upgrade:()=>Q_});async function G_(e,t){let r=await e.listOrganizations();if(r.length===0)throw new Error("No Supabase organizations found for this token");if(t){let s=r.find(i=>i.id===t||i.slug===t);if(!s)throw new Error(`Organization not found: ${t}`);return s}if(r.length===1)return r[0];let n=await An({message:"Select organization",options:r.map(s=>({value:s.id,label:`${s.name} (${s.slug})`}))});return Ee(n)&&process.exit(1),r.find(s=>s.id===n)}async function V_(e,t,r){if(r)return r;let n=z_;try{let o=(await e.listRegions(t)).regions??[];o.length>0&&(n=o.map(a=>({key:a.key,label:a.display_name??a.name??a.key})));}catch{}let s=await An({message:"Select region",options:n.map(i=>({value:i.key,label:i.label}))});return Ee(s)&&process.exit(1),s}async function K_(e){if(e)return e;let t=await Cn({message:"Project name",placeholder:"my-project",validate:r=>r&&r.trim().length>0?void 0:"Name is required"});return Ee(t)&&process.exit(1),t}function X_(){return W_.randomBytes(24).toString("base64url")}function lh(e){let t=e??"hosted";if(t==="hosted"||t==="local")return t;throw new Error(`Unknown upgrade target '${t}'. Use 'hosted' or 'local'.`)}function ql(){return process.env.CI==="true"||process.env.LITE_NON_INTERACTIVE==="1"||!process.stdin.isTTY}async function J_(e){if(typeof e=="boolean")return e;if(ql())return false;let t=await vn({message:"Migrate existing sessions (transfers JWT secret, sessions, refresh tokens)?",initialValue:false});return Ee(t)&&process.exit(1),t}async function Y_(e){if(e)return e;let t=process.env.SUPABASE_ACCESS_TOKEN;if(t)return t;K.info("Create a personal access token at https://supabase.com/dashboard/account/tokens");let r=await Tn({message:"Supabase access token",validate:n=>n&&n.trim().length>0?void 0:"Token is required"});return Ee(r)&&process.exit(1),r}async function ch(e){if(!e.requested)return {migrateSessions:false,weakReasons:[]};if(!e.jwtSecret)throw new Error("Cannot migrate sessions because auth.jwt_secret is not configured. Re-run with --no-migrate-sessions to skip session migration.");let t=Ud(e.jwtSecret);if(t.strong||e.allowWeakJwtSecret)return {migrateSessions:true,jwtSecret:e.jwtSecret,weakReasons:t.reasons};if(ql())throw new Error(["Cannot migrate sessions because auth.jwt_secret looks weak:",...t.reasons.map(n=>`- ${n}`),"Use --allow-weak-jwt-secret to preserve existing sessions anyway, or --no-migrate-sessions to require users to sign in again."].join(`
411
+ `;return e.replace(o,l)}function F_(e,t,r){let n=new RegExp(`(\\[${t.replace(".","\\.")}\\][\\s\\S]*?)(?=\\n\\[|$)`),s=e.match(n);if(!s)return e;let i=s[1],o=r.map(l=>l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),a=new RegExp(`^\\s*(${o})\\s*=.*(?:\\n|$)`,"gm");return e.replace(i,i.replace(a,""))}function M_(e){return F_(e,"db",["driver","url"])}function U_(e){let t=e.match(/(\[db\][\s\S]*?)(?=\n\[|$)/)?.[1];return t?/^\s*driver\s*=\s*["'](sqlite|sqlite-postgres|pglite|postgres)["']/m.test(t)?true:/^\s*url\s*=/m.test(t):false}async function Hl(e){return await pe__default.access(e).then(()=>true).catch(()=>false)}async function rh(e){let t=Me__default.join(e,"supabase","config.toml");if(!await Hl(t))return null;let r=await pe__default.readFile(t,"utf-8");if(!U_(r))return null;let n=`${t}.bak`;return await Hl(n)||await pe__default.writeFile(n,r,"utf-8"),n}async function B_(e){let t=Me__default.join(e,"supabase","config.toml");await Hl(t)||(await pe__default.mkdir(e,{recursive:true}),await In(["init","--workdir",e,"--yes"],{timeoutMs:6e4}));}async function q_(e,t,r){let n=Me__default.join(e,"supabase","config.toml"),s=M_(await pe__default.readFile(n,"utf-8"));s=s.replace(/^project_id\s*=.*$/m,`project_id = "${t}"`),s=se(s,"api","port",String(r.api)),s=se(s,"db","port",String(r.db)),s=se(s,"db","shadow_port",String(r.shadow)),s=se(s,"db","major_version","15"),s=se(s,"db.seed","enabled","false"),s=se(s,"studio","enabled","true"),s=se(s,"studio","port",String(r.studio)),s=se(s,"inbucket","enabled","false"),s=se(s,"inbucket","port",String(r.inbucket)),s=se(s,"realtime","enabled","false"),s=se(s,"storage","enabled","false"),s=se(s,"edge_runtime","enabled","false"),s=se(s,"edge_runtime","inspector_port",String(r.edgeInspector)),s=se(s,"analytics","enabled","false"),s=se(s,"analytics","port",String(r.analytics)),s=se(s,"db.pooler","enabled","false"),s=se(s,"db.pooler","port",String(r.pooler)),await pe__default.writeFile(n,s,"utf-8");}function nh(e){return JSON.stringify(e)}function H_(e){return `[${e.map(nh).join(", ")}]`}async function W_(e,t){if(!t)return;let r=Me__default.join(e,"supabase","config.toml"),n=await pe__default.readFile(r,"utf-8"),s=t.auth??{},i=s.email??{},o=t.api??{};typeof o.max_rows=="number"&&(n=se(n,"api","max_rows",String(o.max_rows))),typeof s.site_url=="string"&&(n=se(n,"auth","site_url",nh(s.site_url))),Array.isArray(s.additional_redirect_urls)&&(n=se(n,"auth","additional_redirect_urls",H_(s.additional_redirect_urls))),typeof s.jwt_expiry=="number"&&(n=se(n,"auth","jwt_expiry",String(s.jwt_expiry))),typeof s.enable_signup=="boolean"&&(n=se(n,"auth","enable_signup",String(s.enable_signup))),typeof s.enable_anonymous_sign_ins=="boolean"&&(n=se(n,"auth","enable_anonymous_sign_ins",String(s.enable_anonymous_sign_ins))),typeof s.minimum_password_length=="number"&&(n=se(n,"auth","minimum_password_length",String(s.minimum_password_length))),typeof i.enable_confirmations=="boolean"&&(n=se(n,"auth.email","enable_confirmations",String(i.enable_confirmations))),await pe__default.writeFile(r,n,"utf-8");}var N_,I_,ki,sh=g(()=>{lr();N_=["bunx","supabase@2.98.1"],I_=["mailpit","realtime","storage-api","imgproxy","edge-runtime","logflare","vector","supavisor"];ki=class e{constructor(t,r,n,s){this.workdir=t;this.projectId=r;this.status=n;this.cleanupOnStop=s;}stopped=false;static async start(t={}){let r=t.workdir??await pe__default.mkdtemp(Me__default.join(Yw.tmpdir(),"lite-local-supa-")),n=t.projectId??`lite-local-${Date.now().toString(36)}`,s=t.cleanupOnStop??!t.workdir,i=await j_();try{await B_(r),await q_(r,n,i),await W_(r,t.sourceConfig),await In(["start","--workdir",r,"--yes","--exclude",I_.join(",")],{timeoutMs:5*6e4});let{stdout:o}=await In(["status","--workdir",r,"-o","json"],{timeoutMs:6e4});return new e(r,n,L_(o),s)}catch(o){throw await In(["stop","--workdir",r,"--no-backup"],{timeoutMs:12e4}).catch(()=>{}),s&&await pe__default.rm(r,{recursive:true,force:true}).catch(()=>{}),o}}async runSql(t){let{createPostgresConnection:r}=await We("@supabase/lite/postgres","postgres","postgres"),n=r({url:this.status.dbUrl});try{await n.exec(t);}finally{await n.close();}}async stop(){this.stopped||(this.stopped=true,await In(["stop","--workdir",this.workdir,"--no-backup"],{timeoutMs:12e4}).catch(()=>{}),this.cleanupOnStop&&await pe__default.rm(this.workdir,{recursive:true,force:true}));}};});async function Pi(){let e=await Rn({message:"Email",placeholder:"Enter your email",validate:t=>{try{iu(t,{domains:["supabase.io"],panic:!0});return}catch(r){return r}}});return Ee(e)&&process.exit(1),e}async function Oi(e=false){let t=await An({message:"Password",validate:r=>{try{ou(r,{panic:!0});return}catch(n){return n}}});if(Ee(t)&&process.exit(1),e){let r=await An({message:"Confirm Password",validate:n=>{try{if(n!==t)throw new Error("Passwords do not match");return}catch(s){return s}}});Ee(r)&&process.exit(1);}return t}async function ih(){let e=await Rn({message:"Project Name",placeholder:"Enter your project name"});return Ee(e)&&process.exit(1),e}async function Ni(e){let t=await Tn({message:e,initialValue:true});return Ee(t)&&process.exit(1),t}var xr=g(()=>{Qe();Lr();});var uh={};de(uh,{isNonInteractive:()=>Wl,resolveSessionMigration:()=>ch,resolveTarget:()=>lh,upgrade:()=>Z_});async function z_(e,t){let r=await e.listOrganizations();if(r.length===0)throw new Error("No Supabase organizations found for this token");if(t){let s=r.find(i=>i.id===t||i.slug===t);if(!s)throw new Error(`Organization not found: ${t}`);return s}if(r.length===1)return r[0];let n=await Cn({message:"Select organization",options:r.map(s=>({value:s.id,label:`${s.name} (${s.slug})`}))});return Ee(n)&&process.exit(1),r.find(s=>s.id===n)}async function K_(e,t,r){if(r)return r;let n=V_;try{let o=(await e.listRegions(t)).regions??[];o.length>0&&(n=o.map(a=>({key:a.key,label:a.display_name??a.name??a.key})));}catch{}let s=await Cn({message:"Select region",options:n.map(i=>({value:i.key,label:i.label}))});return Ee(s)&&process.exit(1),s}async function X_(e){if(e)return e;let t=await Rn({message:"Project name",placeholder:"my-project",validate:r=>r&&r.trim().length>0?void 0:"Name is required"});return Ee(t)&&process.exit(1),t}function J_(){return G_.randomBytes(24).toString("base64url")}function lh(e){let t=e??"hosted";if(t==="hosted"||t==="local")return t;throw new Error(`Unknown upgrade target '${t}'. Use 'hosted' or 'local'.`)}function Wl(){return process.env.CI==="true"||process.env.LITE_NON_INTERACTIVE==="1"||!process.stdin.isTTY}async function Y_(e){if(typeof e=="boolean")return e;if(Wl())return false;let t=await Tn({message:"Migrate existing sessions (transfers JWT secret, sessions, refresh tokens)?",initialValue:false});return Ee(t)&&process.exit(1),t}async function Q_(e){if(e)return e;let t=process.env.SUPABASE_ACCESS_TOKEN;if(t)return t;K.info("Create a personal access token at https://supabase.com/dashboard/account/tokens");let r=await An({message:"Supabase access token",validate:n=>n&&n.trim().length>0?void 0:"Token is required"});return Ee(r)&&process.exit(1),r}async function ch(e){if(!e.requested)return {migrateSessions:false,weakReasons:[]};if(!e.jwtSecret)throw new Error("Cannot migrate sessions because auth.jwt_secret is not configured. Re-run with --no-migrate-sessions to skip session migration.");let t=qr(e.jwtSecret);if(t.strong||e.allowWeakJwtSecret)return {migrateSessions:true,jwtSecret:e.jwtSecret,weakReasons:t.reasons};if(Wl())throw new Error(["Cannot migrate sessions because auth.jwt_secret looks weak:",...t.reasons.map(n=>`- ${n}`),"Use --allow-weak-jwt-secret to preserve existing sessions anyway, or --no-migrate-sessions to require users to sign in again."].join(`
410
412
  `));K.warning(["auth.jwt_secret looks weak and will become a trusted Supabase signing key:",...t.reasons.map(n=>`- ${n}`)].join(`
411
- `));let r=await vn({message:"Preserve existing sessions anyway by importing this JWT secret?",initialValue:false});return Ee(r)&&process.exit(1),r?{migrateSessions:true,jwtSecret:e.jwtSecret,weakReasons:t.reasons}:{migrateSessions:false,weakReasons:t.reasons}}var _e,z_,Q_,ph=g(()=>{_e=te(ae());Qe();De();Ce();wd();Td();Id();Fd();qd();zd();Qd();sh();xr();Ei();$e();z_=[{key:"us-east-1",label:"East US (N. Virginia)"},{key:"us-east-2",label:"East US (Ohio)"},{key:"us-west-1",label:"West US (N. California)"},{key:"us-west-2",label:"West US (Oregon)"},{key:"ca-central-1",label:"Canada (Central)"},{key:"sa-east-1",label:"South America (S\xE3o Paulo)"},{key:"eu-west-1",label:"West EU (Ireland)"},{key:"eu-west-2",label:"West Europe (London)"},{key:"eu-west-3",label:"West EU (Paris)"},{key:"eu-central-1",label:"Central EU (Frankfurt)"},{key:"eu-central-2",label:"Central Europe (Zurich)"},{key:"eu-north-1",label:"North EU (Stockholm)"},{key:"ap-south-1",label:"South Asia (Mumbai)"},{key:"ap-southeast-1",label:"Southeast Asia (Singapore)"},{key:"ap-southeast-2",label:"Oceania (Sydney)"},{key:"ap-northeast-1",label:"Northeast Asia (Tokyo)"},{key:"ap-northeast-2",label:"Northeast Asia (Seoul)"}];Q_=e=>e.command("upgrade").description("[lite] Upgrade this Supalite project to full Supabase").option("--dry-run","Check readiness without making changes",false).option("--force","Perform the upgrade",false).option("--target <target>","'hosted' or 'local' Supabase target","hosted").option("--mode <mode>","'user' or 'platform' (only 'user' is supported)","user").option("--org-id <id>","Supabase organization ID or slug").option("--region <region>","Project region key").option("--project-name <name>","Name for the new Supabase project").option("--supabase-token <token>","Supabase personal access token").option("--local-dir <path>","Supabase CLI workdir for --target local").option("--migrate-sessions","Transfer existing sessions, refresh tokens, and JWT secret so current tokens keep working").option("--no-migrate-sessions","Skip sessions, refresh tokens, and JWT secret").option("--allow-weak-jwt-secret","Allow --migrate-sessions to import a weak JWT secret non-interactively",false).option("--dump-credentials <path>","Write credentials to a file").option("--config <config>","Path to the local config file").option("--verbose","Echo each SQL statement sent to Supabase",false).option("--json","Emit machine-readable JSON for --dry-run",false).helpGroup("Management APIs:").action(async t=>{let r=t.dryRun&&t.json,n=console.log;r||console.log(),await J(async()=>{await Q(t.config);let s=lh(t.target);if(Rl("upgrade.target",s),Rl("upgrade.dry_run",!!t.dryRun),s==="hosted"&&t.localDir)throw new Error("--local-dir can only be used with --target local.");if(s==="hosted"&&t.mode&&t.mode!=="user")throw new Error(`Mode '${t.mode}' is not yet supported. Only 'user' mode is available.`);if(s==="local"&&t.mode&&t.mode!=="user")throw new Error("--mode only applies to hosted upgrades.");r&&(console.log=()=>{});let i;try{i=await(await z({withSupabaseClient:!1})).project.local.createApp(t.config);}finally{r&&(console.log=n);}if(r){let b=await Ml(i);n(JSON.stringify(b,null,2)),b.summary.upgrade_safe||process.exit(1);return}console.log(_e.default.dim("Running readiness checks..."));let o=await kn("readiness",()=>vd(i));if(Ld(o),!o.ok)throw new Error("Readiness checks failed. See errors above.");let a=async()=>{console.log(_e.default.dim(`
412
- Rehearsing upgrade against in-memory pglite...`));let b=await kn("rehearsal",()=>Nd(i));return Dd(b),b.ok};if(t.dryRun){let b=await Ml(i);jd(b),b.summary.upgrade_safe||process.exit(1),await a()||process.exit(1);return}if(!t.force&&!await Oi("Proceed with upgrade?"))return;if(!await a())throw new Error("Rehearsal failed. Upgrade aborted.");if(s==="local"){if(t.migrateSessions===!0)throw new Error("--target local does not support preserving existing sessions yet. Re-run with --no-migrate-sessions.");let b=Me__default.resolve(t.localDir??th()),D=await rh(b),O=null;if(D){let j=Me__default.relative(process.cwd(),D)||D;O=`Your project's supabase/config.toml was rewritten in place for the local Supabase CLI. The original was backed up to ${j}. To resume supalite dev (bun run dev), restore it: cp ${j} supabase/config.toml (or git checkout supabase/config.toml). Pass --local-dir <separate-dir> next time to keep the local stack isolated.`;}let F=vl(),S,x;try{F.start(`Starting local Supabase in ${b}`),S=await Ri.start({workdir:b,cleanupOnStop:!1,sourceConfig:i.config}),F.stop(`Local Supabase is running at ${S.status.apiUrl}`),x=await kn("apply",()=>Ul(i,S,{migrateSessions:!1,authTarget:"supabase",syncAuthConfig:!1,onSql:(j,ie)=>{t.verbose&&console.log(_e.default.dim(`-- ${ie}
413
+ `));let r=await Tn({message:"Preserve existing sessions anyway by importing this JWT secret?",initialValue:false});return Ee(r)&&process.exit(1),r?{migrateSessions:true,jwtSecret:e.jwtSecret,weakReasons:t.reasons}:{migrateSessions:false,weakReasons:t.reasons}}var _e,V_,Z_,ph=g(()=>{_e=te(ae());Qe();De();Ce();Sd();Cd();Dd();Ud();qd();zd();Qd();sh();xr();xi();$e();V_=[{key:"us-east-1",label:"East US (N. Virginia)"},{key:"us-east-2",label:"East US (Ohio)"},{key:"us-west-1",label:"West US (N. California)"},{key:"us-west-2",label:"West US (Oregon)"},{key:"ca-central-1",label:"Canada (Central)"},{key:"sa-east-1",label:"South America (S\xE3o Paulo)"},{key:"eu-west-1",label:"West EU (Ireland)"},{key:"eu-west-2",label:"West Europe (London)"},{key:"eu-west-3",label:"West EU (Paris)"},{key:"eu-central-1",label:"Central EU (Frankfurt)"},{key:"eu-central-2",label:"Central Europe (Zurich)"},{key:"eu-north-1",label:"North EU (Stockholm)"},{key:"ap-south-1",label:"South Asia (Mumbai)"},{key:"ap-southeast-1",label:"Southeast Asia (Singapore)"},{key:"ap-southeast-2",label:"Oceania (Sydney)"},{key:"ap-northeast-1",label:"Northeast Asia (Tokyo)"},{key:"ap-northeast-2",label:"Northeast Asia (Seoul)"}];Z_=e=>e.command("upgrade").description("[lite] Upgrade this Supalite project to full Supabase").option("--dry-run","Check readiness without making changes",false).option("--force","Perform the upgrade",false).option("--target <target>","'hosted' or 'local' Supabase target","hosted").option("--mode <mode>","'user' or 'platform' (only 'user' is supported)","user").option("--org-id <id>","Supabase organization ID or slug").option("--region <region>","Project region key").option("--project-name <name>","Name for the new Supabase project").option("--supabase-token <token>","Supabase personal access token").option("--local-dir <path>","Supabase CLI workdir for --target local").option("--migrate-sessions","Transfer existing sessions, refresh tokens, and JWT secret so current tokens keep working").option("--no-migrate-sessions","Skip sessions, refresh tokens, and JWT secret").option("--allow-weak-jwt-secret","Allow --migrate-sessions to import a weak JWT secret non-interactively",false).option("--dump-credentials <path>","Write credentials to a file").option("--config <config>","Path to the local config file").option("--verbose","Echo each SQL statement sent to Supabase",false).option("--json","Emit machine-readable JSON for --dry-run",false).helpGroup("Management APIs:").action(async t=>{let r=t.dryRun&&t.json,n=console.log;r||console.log(),await J(async()=>{await Q(t.config);let s=lh(t.target);if(Pl("upgrade.target",s),Pl("upgrade.dry_run",!!t.dryRun),s==="hosted"&&t.localDir)throw new Error("--local-dir can only be used with --target local.");if(s==="hosted"&&t.mode&&t.mode!=="user")throw new Error(`Mode '${t.mode}' is not yet supported. Only 'user' mode is available.`);if(s==="local"&&t.mode&&t.mode!=="user")throw new Error("--mode only applies to hosted upgrades.");r&&(console.log=()=>{});let i;try{i=await(await z({withSupabaseClient:!1})).project.local.createApp(t.config);}finally{r&&(console.log=n);}if(r){let b=await Bl(i);n(JSON.stringify(b,null,2)),b.summary.upgrade_safe||process.exit(1);return}console.log(_e.default.dim("Running readiness checks..."));let o=await Pn("readiness",()=>Ad(i));if(jd(o),!o.ok)throw new Error("Readiness checks failed. See errors above.");let a=async()=>{console.log(_e.default.dim(`
414
+ Rehearsing upgrade against in-memory pglite...`));let b=await Pn("rehearsal",()=>Ld(i));return Fd(b),b.ok};if(t.dryRun){let b=await Bl(i);Md(b),b.summary.upgrade_safe||process.exit(1),await a()||process.exit(1);return}if(!t.force&&!await Ni("Proceed with upgrade?"))return;if(!await a())throw new Error("Rehearsal failed. Upgrade aborted.");if(s==="local"){if(t.migrateSessions===!0)throw new Error("--target local does not support preserving existing sessions yet. Re-run with --no-migrate-sessions.");let b=Me__default.resolve(t.localDir??th()),D=await rh(b),O=null;if(D){let j=Me__default.relative(process.cwd(),D)||D;O=`Your project's supabase/config.toml was rewritten in place for the local Supabase CLI. The original was backed up to ${j}. To resume supalite dev (bun run dev), restore it: cp ${j} supabase/config.toml (or git checkout supabase/config.toml). Pass --local-dir <separate-dir> next time to keep the local stack isolated.`;}let F=Al(),S,x;try{F.start(`Starting local Supabase in ${b}`),S=await ki.start({workdir:b,cleanupOnStop:!1,sourceConfig:i.config}),F.stop(`Local Supabase is running at ${S.status.apiUrl}`),x=await Pn("apply",()=>ql(i,S,{migrateSessions:!1,authTarget:"supabase",syncAuthConfig:!1,onSql:(j,ie)=>{t.verbose&&console.log(_e.default.dim(`-- ${ie}
413
415
  ${j}`));},onSchemaStart:j=>F.start(`Applying schema (0/${j})`),onSchemaProgress:(j,ie)=>F.message(`Applying schema (${j}/${ie})`),onSchemaEnd:j=>F.stop(`Schema applied (${j} statements)`),onBatchStart:(j,ie)=>F.start(`${j} (0/${ie})`),onBatchProgress:(j,ie,ce)=>F.message(`${j} (${ie}/${ce})`),onBatchEnd:(j,ie,ce)=>F.stop(`${j} (${ie} ${ce})`),onBatchFailure:(j,ie)=>{F.stop(_e.default.red(`${j}: ${ie.length} failed`));for(let ce of ie)console.log(_e.default.red(` \u2717 ${ce.error}`)),t.verbose&&console.log(_e.default.dim(` ${ce.statement}`));},onSkip:j=>console.log(_e.default.dim(j))}));}catch(j){throw O&&console.log(_e.default.yellow(`
414
- ${O}`)),j}let Y=["Sessions and JWT secret not migrated. Existing tokens are invalid \u2014 users must re-authenticate.","Management API auth config sync is skipped for --target local; supported local auth settings are written before Supabase starts."];O&&Y.unshift(O),i.config.storage?.enabled&&Y.push("Storage migration is not yet supported."),i.config.realtime?.enabled&&Y.push("Realtime config migration is not yet supported.");let q=eh(S.status.dbUrl);if(t.dumpCredentials){let j=JSON.stringify({target:"local",workdir:S.workdir,projectUrl:S.status.apiUrl,apiUrl:S.status.apiUrl,studioUrl:S.status.studioUrl,dbUrl:S.status.dbUrl,anonKey:S.status.anonKey,serviceRoleKey:S.status.serviceRoleKey,dbPassword:q},null,2);await pe__default.writeFile(t.dumpCredentials,j,"utf-8"),console.log(_e.default.dim(`Credentials written to ${t.dumpCredentials}`));}Ll({projectRef:S.projectId,projectUrl:S.status.apiUrl,apiUrl:S.status.apiUrl,studioUrl:S.status.studioUrl,anonKey:S.status.anonKey,serviceRoleKey:S.status.serviceRoleKey,dbPassword:q,auth:x.auth,jwtMigrated:!1,warnings:[`Local Supabase workdir: ${S.workdir}`,...Y]});return}let c=await Y_(t.supabaseToken),p=new _i(c);try{await p.listOrganizations();}catch(b){throw new Error(`Supabase access token rejected: ${String(b)}`)}let u=await G_(p,t.orgId),f=await V_(p,u.slug,t.region),h=await K_(t.projectName),d=await J_(t.migrateSessions),m=await ch({requested:d,jwtSecret:i.config.auth?.jwt_secret,allowWeakJwtSecret:t.allowWeakJwtSecret}),w=m.migrateSessions,y=X_(),E=vl();E.start("Creating Supabase project");let T=await p.createProject({organization_id:u.id,name:h,db_pass:y,region:f}),v=T.ref??T.id;if(E.stop(`Project created: ${v}`),E.start("Waiting for project to become active"),await p.waitForActive(v,{onTick:b=>E.message(`Project status: ${b}`)}),E.stop("Project is active"),w){E.start("Importing JWT signing key");try{await p.createSigningKey(v,{algorithm:"HS256",status:"in_use",private_jwk:Bd(m.jwtSecret)});}catch(b){throw E.stop(_e.default.red("JWT signing key import failed")),new Error(["Session migration is not available for this Supabase project, token, or plan.","The upgrade cannot preserve existing Supalite sessions without importing auth.jwt_secret as a signing key.","Re-run with --no-migrate-sessions if requiring users to sign in again is acceptable.",`Supabase response: ${String(b)}`].join(" "))}E.stop("JWT signing key imported");}let A=(await kn("apply",()=>Ul(i,{runSql:b=>p.runSql(v,b),updateAuthConfig:b=>p.updateAuthConfig(v,b)},{migrateSessions:w,authTarget:"supabase",onSql:(b,D)=>{t.verbose&&console.log(_e.default.dim(`-- ${D}
415
- ${b}`));},onSchemaStart:b=>E.start(`Applying schema (0/${b})`),onSchemaProgress:(b,D)=>E.message(`Applying schema (${b}/${D})`),onSchemaEnd:b=>E.stop(`Schema applied (${b} statements)`),onBatchStart:(b,D)=>{E.start(`${b} (0/${D})`);},onBatchProgress:(b,D,O)=>E.message(`${b} (${D}/${O})`),onBatchEnd:(b,D,O)=>E.stop(`${b} (${D} ${O})`),onBatchFailure:(b,D)=>{E.stop(_e.default.red(`${b}: ${D.length} failed`));for(let O of D)console.log(_e.default.red(` \u2717 ${O.error}`)),t.verbose&&console.log(_e.default.dim(` ${O.statement}`));},onAuthConfigStart:()=>E.start("Syncing auth config"),onAuthConfigEnd:()=>E.stop("Auth config synced"),onSkip:b=>console.log(_e.default.dim(b))}))).auth,$=yd(await p.getApiKeys(v)),_=`https://${v}.${p.projectDomain}`,I=[];if(w?m.weakReasons.length>0?I.push(`A weak JWT secret was imported to preserve sessions: ${m.weakReasons.join("; ")}.`):I.push("Sessions preserved by importing auth.jwt_secret as a Supabase signing key."):I.push("Sessions and JWT secret not migrated. Existing tokens are invalid \u2014 users must re-authenticate."),i.config.storage?.enabled&&I.push("Storage migration is not yet supported."),i.config.realtime?.enabled&&I.push("Realtime config migration is not yet supported."),t.dumpCredentials){let b=JSON.stringify({ref:v,projectUrl:_,anonKey:$.anon,serviceRoleKey:$.service_role,dbPassword:y},null,2);await pe__default.writeFile(t.dumpCredentials,b,"utf-8"),console.log(_e.default.dim(`Credentials written to ${t.dumpCredentials}`));}Ll({projectRef:v,projectUrl:_,apiUrl:_,anonKey:$.anon,serviceRoleKey:$.service_role,dbPassword:y,auth:A,jwtMigrated:!!(w&&m.jwtSecret),warnings:I});});});});var fh={};de(fh,{login:()=>Z_});var Hl,Z_,mh=g(()=>{Hl=te(ae());Qe();xr();De();Ce();Z_=e=>{e.command("login").description("Login").option("--json","Output in JSON format").helpGroup("Local Development:").action(async t=>{await J(async()=>{let r=await z();K.message(Hl.default.dim("Enter your credentials to login to the cloud"));let n=await ki(),s=await Pi(),{data:i,error:o}=await r.client.auth.signInWithPassword({email:n,password:s});o&&(K.error(o.message),process.exit(1)),t.json?console.log(JSON.stringify(i,null,2)):K.success(`Authenticated as: ${Hl.default.cyan(i.user.email)}`);});});};});var hh={};de(hh,{logout:()=>e$});var dh,e$,gh=g(()=>{dh=te(ae());Ce();Qe();De();e$=e=>{e.command("logout").description("Logout").helpGroup("Local Development:").action(async()=>{console.log(),await J(async()=>{let t=await z(),{error:r}=await t.client.auth.signOut();r&&(K.error(r.message),process.exit(1)),console.log(dh.default.green("Logged out successfully"));});});};});var yh={};de(yh,{signup:()=>t$});var Wl,t$,wh=g(()=>{Wl=te(ae());Qe();xr();De();Ce();ot();t$=e=>{e.command("signup").description(be("Register a supalite cloud account")).option("--json","Output in JSON format").helpGroup("Local Development:").action(async t=>{K.message(Wl.default.dim("Enter your credentials to sign up to the cloud")),await J(async()=>{let r=await z(),n=await ki(),s=await Pi(!0),{data:i,error:o}=await r.client.auth.signUp({email:n,password:s});o&&(K.error(o.message),process.exit(1)),t.json?console.log(JSON.stringify(i,null,2)):K.success(`Signed up as: ${Wl.default.cyan(i.user.email)}`);});});};});var bh={};de(bh,{whoami:()=>r$});var Gl,r$,Sh=g(()=>{Gl=te(ae());Ce();Qe();De();ot();r$=e=>{e.command("whoami").description(be("Show the current authenticated user")).option("--json","Output in JSON format").helpGroup("Local Development:").action(async t=>{console.log(),await J(async()=>{let r=await z(),{data:n,error:s}=await r.client.auth.getUser();t.json?console.log(JSON.stringify(n,null,2)):n&&"user"in n&&n.user&&"email"in n.user?(console.log(`Authenticated as: ${Gl.default.cyan(n.user.email)}`),process.exit(0)):(console.log(Gl.default.yellow("Not authenticated")),process.exit(1)),s&&(K.error(s.message),process.exit(1));});});};});var xh={};de(xh,{link:()=>n$});var Eh,n$,_h=g(()=>{De();Ce();$e();Qe();Eh=te(ae()),n$=e=>e.command("link").description("Link to a Supalite project").option("--project-ref <project-ref>","The reference of the project to link to").option("--json","Output in JSON format").helpGroup("Local Development:").action(async t=>{console.log(),await J(async()=>{await Q();let r=await z();r.project.local.ref()&&K.warning("Project is already linked.");let n=t.projectRef;if(!n){let i=await r.project.remote.list();n=await An({message:"Select a project:",options:i.map(o=>({value:o.id,hint:`name: ${o.name}, created: ${o.created_at}`}))}),Ee(n)&&process.exit(1);}if(!n)throw new Error("No project ref found");console.log("Linking project",n);let s=await r.project.remote.get(n);r.project.local.setRef(s.id),console.log(`Finished linking project ${Eh.default.cyan(s.id)}.`);});});});var $h={};de($h,{unlink:()=>s$});var s$,vh=g(()=>{De();Ce();$e();s$=e=>e.command("unlink").description("Unlink from a Supalite project").option("--json","Output in JSON format").helpGroup("Local Development:").action(async()=>{console.log(),await J(async()=>{await Q(),(await z()).project.local.unlink(),console.log("Finished unlinking project.");});});});var Ah={};de(Ah,{status:()=>i$});var Th,i$,Ch=g(()=>{Ce();De();$e();Th=te(ae());ot();i$=e=>e.command("status").description(be("Show information about the linked project")).helpGroup("Local Development:").action(async()=>{console.log(),await J(async()=>{await Q();let t=await z(),r=await t.project.remote.get();console.log(r),console.log(`Project URL: ${Th.default.cyan(t.project.remote.url(r.id))}`);});});});var kh={};de(kh,{projects:()=>o$});var zl,o$,a$,l$,Ph=g(()=>{xr();Qe();zl=te(ae());De();Ce();De();o$=e=>{e.command("projects").description("Manage Supalite cloud projects").helpGroup("Management APIs:").addCommand(l$).addCommand(a$);},a$=new Command$1().name("list").description("List projects").helpGroup("Projects:").action(async()=>{await J(async()=>{let t=await(await z()).project.remote.list();(!Array.isArray(t)||t.length===0)&&(K.info("No projects found"),process.exit(0)),console.log(jm(t,{omitKeys:["config","user_id"],renderHeader:r=>String(r).split("_").map(n=>n.toUpperCase()).join(" ")}));});}),l$=new Command$1().name("create").description("Create a project").option("--name <name>","The name of the project").helpGroup("Projects:").action(async e=>{await J(async()=>{let t=await z(),r=e.name??await ih(),n=await t.project.remote.create({name:r});K.success(`Project ${zl.default.cyan(n.name)} created: ${zl.default.cyan(n.id)}`);});});});function c$(){try{return qn.statSync("/.dockerenv"),!0}catch{return false}}function u$(){try{return qn.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return false}}function Kl(){return Vl===void 0&&(Vl=c$()||u$()),Vl}var Vl,Nh=g(()=>{});function Xt(){return Xl===void 0&&(Xl=f$()||Kl()),Xl}var Xl,f$,Jl=g(()=>{Nh();f$=()=>{try{return qn.statSync("/run/.containerenv"),!0}catch{return false}};});var Ih,ct,Ql=g(()=>{Jl();Ih=()=>{if(Ge.platform!=="linux")return false;if(Kw.release().toLowerCase().includes("microsoft"))return !Xt();try{if(qn.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return !Xt()}catch{}return qn.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||qn.existsSync("/run/WSL")?!Xt():false},ct=Ge.env.__IS_WSL_TEST__?Ih:Ih();});var y$,Zl,je,ec=g(()=>{y$=promisify(g$.execFile),Zl=()=>`${Ge.env.SYSTEMROOT||Ge.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`,je=async(e,t={})=>{let{powerShellPath:r,...n}=t,s=je.encodeCommand(e);return y$(r??Zl(),[...je.argumentsPrefix,s],{encoding:"utf8",...n})};je.argumentsPrefix=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"];je.encodeCommand=e=>Buffer$1.from(e,"utf16le").toString("base64");je.escapeArgument=e=>`'${String(e).replaceAll("'","''")}'`;});function jh(e){for(let t of e.split(`
416
- `)){if(/^\s*#/.test(t))continue;let r=/^\s*root\s*=\s*(?<mountPoint>"[^"]*"|'[^']*'|[^#]*)/.exec(t);if(r)return r.groups.mountPoint.trim().replaceAll(/^["']|["']$/g,"")}}var Fh=g(()=>{});var S$,E$,x$,Ni,Mh,Bh,qh,Hh,Wh=g(()=>{Ql();ec();Fh();Ql();S$=promisify(g$.execFile),E$=(()=>{let e="/mnt/",t;return async function(){if(t)return t;let r="/etc/wsl.conf",n=false;try{await pe__default.access(r,constants.F_OK),n=!0;}catch{}if(!n)return e;let s=await pe__default.readFile(r,{encoding:"utf8"}),i=jh(s);return i===void 0?e:(t=i,t=t.endsWith("/")?t:`${t}/`,t)}})(),x$=async()=>`${await E$()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Ni=ct?x$:Zl,Bh=async()=>(Mh??=(async()=>{try{let e=await Ni();return await pe__default.access(e,constants.X_OK),!0}catch{return false}})(),Mh),qh=async()=>{let e=await Ni(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,{stdout:r}=await je(t,{powerShellPath:e});return r.trim()},Hh=async e=>{if(/^[a-z]+:\/\//i.test(e))return e;try{let{stdout:t}=await S$("wslpath",["-aw",e],{encoding:"utf8"});return t.trim()}catch{return e}};});function Jt(e,t,r){let n=s=>Object.defineProperty(e,t,{value:s,enumerable:true,writable:true});return Object.defineProperty(e,t,{configurable:true,enumerable:true,get(){let s=r();return n(s),s},set(s){n(s);}}),e}var Gh=g(()=>{});async function rc(){if(Ge.platform!=="darwin")throw new Error("macOS only");let{stdout:e}=await T$("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),r=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e)?.groups.id??"com.apple.Safari";return r==="com.apple.safari"?"com.apple.Safari":r}var T$,zh=g(()=>{T$=promisify(execFile);});async function Vh(e,{humanReadableOutput:t=true,signal:r}={}){if(Ge.platform!=="darwin")throw new Error("macOS only");let n=t?[]:["-ss"],s={};r&&(s.signal=r);let{stdout:i}=await k$("osascript",["-e",e,n],s);return i.trim()}var k$,Kh=g(()=>{k$=promisify(execFile);});async function nc(e){return Vh(`tell application "Finder" to set app_path to application file id "${e}" as string
417
- tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}var Xh=g(()=>{Kh();});async function oc(e=N$){let{stdout:t}=await e("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),r=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(t);if(!r)throw new sc(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:n}=r.groups,s=n.lastIndexOf("."),i=n.lastIndexOf("-"),o=s===-1?void 0:n.slice(0,s),a=i===-1?void 0:n.slice(0,i);return Ii[n]??Ii[o]??Ii[a]??{name:n,id:n}}var N$,Ii,ic,sc,ac=g(()=>{N$=promisify(execFile),Ii={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},ic=new Map(Object.entries(Ii)),sc=class extends Error{};});async function cc(){if(Ge.platform==="darwin"){let e=await rc();return {name:await nc(e),id:e}}if(Ge.platform==="linux"){let{stdout:e}=await D$("xdg-mime",["query","default","x-scheme-handler/http"]),t=e.trim();return {name:j$(t.replace(/.desktop$/,"").replace("-"," ")),id:t}}if(Ge.platform==="win32")return oc();throw new Error("Only macOS, Linux, and Windows are supported")}var D$,j$,Jh=g(()=>{zh();Xh();ac();ac();D$=promisify(execFile),j$=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,t=>t.toUpperCase());});var F$,Yh,Qh=g(()=>{F$=!!(Ge.env.SSH_CONNECTION||Ge.env.SSH_CLIENT||Ge.env.SSH_TTY),Yh=F$;});function rg(e){if(typeof e=="string"||Array.isArray(e))return e;let{[eg]:t}=e;if(!t)throw new Error(`${eg} is not supported`);return t}function Dn({[_r]:e},{wsl:t}={}){if(t&&ct)return rg(t);if(!e)throw new Error(`${_r} is not supported`);return rg(e)}var Li,pc,Zh,_r,eg,tg,Di,H$,$r,ig,og=g(()=>{Wh();ec();Gh();Jh();Jl();Qh();Li=Symbol("fallbackAttempt"),pc=import.meta.url?Me__default.dirname(fileURLToPath(import.meta.url)):"",Zh=Me__default.join(pc,"xdg-open"),{platform:_r,arch:eg}=Ge,tg=async(e,t)=>{if(e.length===0)return;let r=[];for(let n of e)try{return await t(n)}catch(s){r.push(s);}throw new AggregateError(r,"Failed to open in all supported apps")},Di=async e=>{e={wait:false,background:false,newInstance:false,allowNonzeroExitCode:false,...e};let t=e[Li]===true;if(delete e[Li],Array.isArray(e.app))return tg(e.app,c=>Di({...e,app:c,[Li]:true}));let{name:r,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(r))return tg(r,c=>Di({...e,app:{name:c,arguments:n},[Li]:true}));if(r==="browser"||r==="browserPrivate"){let c={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge","com.apple.safari":"safari"},p={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},u;if(ct){let f=await qh();u=ic.get(f)??{};}else u=await cc();if(u.id in c){let f=c[u.id.toLowerCase()];if(r==="browserPrivate"){if(f==="safari")throw new Error("Safari doesn't support opening in private mode via command line");n.push(p[f]);}return Di({...e,app:{name:$r[f],arguments:n}})}throw new Error(`${u.name} is not supported as a default browser`)}let s,i=[],o={},a=false;if(ct&&!Xt()&&!Yh&&!r&&(a=await Bh()),_r==="darwin")s="open",e.wait&&i.push("--wait-apps"),e.background&&i.push("--background"),e.newInstance&&i.push("--new"),r&&i.push("-a",r);else if(_r==="win32"||a){s=await Ni(),i.push(...je.argumentsPrefix),ct||(o.windowsVerbatimArguments=true),ct&&e.target&&(e.target=await Hh(e.target));let c=["$ProgressPreference = 'SilentlyContinue';","Start"];e.wait&&c.push("-Wait"),r?(c.push(je.escapeArgument(r)),e.target&&n.push(e.target)):e.target&&c.push(je.escapeArgument(e.target)),n.length>0&&(n=n.map(p=>je.escapeArgument(p)),c.push("-ArgumentList",n.join(","))),e.target=je.encodeCommand(c.join(" ")),e.wait||(o.stdio="ignore");}else {if(r)s=r;else {let c=!pc||pc==="/",p=false;try{await pe__default.access(Zh,constants.X_OK),p=!0;}catch{}s=Ge.versions.electron??(_r==="android"||c||!p)?"xdg-open":Zh;}n.length>0&&i.push(...n),e.wait||(o.stdio="ignore",o.detached=true);}_r==="darwin"&&n.length>0&&i.push("--args",...n),e.target&&i.push(e.target);let l=g$.spawn(s,i,o);return e.wait?new Promise((c,p)=>{l.once("error",p),l.once("close",u=>{if(!e.allowNonzeroExitCode&&u!==0){p(new Error(`Exited with code ${u}`));return}c(l);});}):t?new Promise((c,p)=>{l.once("error",p),l.once("spawn",()=>{l.once("close",u=>{if(l.off("error",p),u!==0){p(new Error(`Exited with code ${u}`));return}l.unref(),c(l);});});}):(l.unref(),new Promise((c,p)=>{l.once("error",p),l.once("spawn",()=>{l.off("error",p),c(l);});}))},H$=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a `target`");return Di({...t,target:e})};$r={browser:"browser",browserPrivate:"browserPrivate"};Jt($r,"chrome",()=>Dn({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium","chromium-browser"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));Jt($r,"brave",()=>Dn({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));Jt($r,"firefox",()=>Dn({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));Jt($r,"edge",()=>Dn({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));Jt($r,"safari",()=>Dn({darwin:"Safari"}));ig=H$;});var ag={};de(ag,{cloud:()=>V$});var Fe,z$,V$,lg=g(()=>{Fe=te(ae());og();De();Ce();xr();Ye();hi();Yt();$e();ot();z$="Management APIs:",V$=e=>{let t=e.command("cloud").description(be("Supalite cloud operations")).helpGroup(z$);t.command("deploy").description("Push schema + config + seed to the linked supalite cloud project").option("--config <config>","Path to the config file").option("--force","Force the push",false).action(async r=>{console.log();let n=Bi();n.length>0&&(console.error(Fe.default.red(`Cannot deploy: experimental features enabled (${n.join(", ")}). Cloud does not support them yet.`)),process.exit(1)),await J(async()=>{await Q(r.config);let s=await z(),i=await s.project.local.createApp(r.config),o=!1;await wn(i,{force:!0});let a=await s.project.remote.get().catch(async()=>{if(await Oi("No project found. Create a new project?"))return o=!0,await s.project.remote.create().then(m=>s.project.local.link(m));throw new Error("No project found")}),l=await s.project.remote.createApp(a.id),c=await ge(i),p=l.connection.createMigrator(c),u=await p.diff();console.log(),dr(u);let f=l.getInfoJson(),h=i.getInfoJson();if(isEqual(f,h))console.log(Fe.default.dim("Project config is up to date"));else {if(!await s.project.remote.setConfig(a.id,h))throw new Error("Failed to update project config");console.log(Fe.default.green("Project config updated"));}let d=s.project.remote.url(a.id);if(u.plan.steps.length>0)try{if(await measureTime(async()=>{await p.migratePlan(u.plan,{force:r.force??!1});},m=>{console.log(Fe.default.green(`Pushed changes to project in ${m.toFixed(2)}ms.`));}),o)try{let m=await bn(l,{recoveryHint:"Fix `supabase/seed.sql` and rerun `lite cloud deploy` against the new project."});m>0&&console.log(Fe.default.green(`Seeded remote project (${m} statements).`));}catch(m){console.warn(Fe.default.yellow(String(m.message??m)));}console.log(`Project URL: ${Fe.default.cyan(d)}
418
- `),o&&await ig(d);}catch(m){m instanceof di&&(console.warn(Fe.default.yellow("Migration would cause data loss. Rerun with --force to proceed.")),process.exit(1)),console.error(Fe.default.red("Migration error: "+String(m))),process.exit(1);}else console.log(Fe.default.green("No changes to push."));});}),t.command("diff").description("Diff local project against the linked supalite cloud project").option("--config <config>","Path to the config file").option("--sql","Show the SQL for the diff",false).action(async r=>{console.log(),await J(async()=>{await Q(r.config);let n=await z(),s=await n.project.local.createApp(r.config);if(await wn(s,{force:!0}),!n.project.local.ref())throw new Error("No project linked");let i=await n.project.remote.get();if(!i)throw new Error("Project not found");let o=await n.project.remote.createApp(i.id),a=await ge(s),l=await o.connection.createMigrator(a).diff();if(l.plan.steps.length>0)if(r.sql){let c=Qa(l,{colorize:!0});console.log(Fe.default.cyan(c));}else dr(l);else console.log(Fe.default.green("No changes to migrate."));});});};});Mi();var pg=te(ae());Yt();var cg={init:()=>Promise.resolve().then(()=>(Oc(),Pc)).then(e=>e.init),start:()=>Promise.resolve().then(()=>(Bp(),Up)).then(e=>e.start),dev:()=>Promise.resolve().then(()=>(pm(),um)).then(e=>e.dev),repl:()=>Promise.resolve().then(()=>(mm(),fm)).then(e=>e.repl),debug:()=>Promise.resolve().then(()=>(hm(),dm)).then(e=>e.debug),db:()=>Promise.resolve().then(()=>(dd(),md)).then(e=>e.db),migration:()=>Promise.resolve().then(()=>(gd(),hd)).then(e=>e.migration),upgrade:()=>Promise.resolve().then(()=>(ph(),uh)).then(e=>e.upgrade)},K$={login:()=>Promise.resolve().then(()=>(mh(),fh)).then(e=>e.login),logout:()=>Promise.resolve().then(()=>(gh(),hh)).then(e=>e.logout),signup:()=>Promise.resolve().then(()=>(wh(),yh)).then(e=>e.signup),whoami:()=>Promise.resolve().then(()=>(Sh(),bh)).then(e=>e.whoami),link:()=>Promise.resolve().then(()=>(_h(),xh)).then(e=>e.link),unlink:()=>Promise.resolve().then(()=>(vh(),$h)).then(e=>e.unlink),status:()=>Promise.resolve().then(()=>(Ch(),Ah)).then(e=>e.status),projects:()=>Promise.resolve().then(()=>(Ph(),kh)).then(e=>e.projects),cloud:()=>Promise.resolve().then(()=>(lg(),ag)).then(e=>e.cloud)};function X$(){return yc("cloud")?{...cg,...K$}:cg}async function ug(){let e=X$(),t=process.argv[2];return t&&Object.hasOwn(e,t)?[await e[t]()]:Promise.all(Object.values(e).map(r=>r()))}$e();Ei();er();var fc=new Command;function Y$(e){let t=[],r=e;for(;r&&r.name&&r.name()&&r.parent;)t.unshift(r.name()),r=r.parent;return t.join(" ")}async function Q$(){let{version:e,name:t}=await Yn();fc.name("lite").description(`${pg.default.yellowBright("\u26A1")} ${t} v${e}`).version(e).option("--no-telemetry","disable anonymous usage telemetry").option("--verbose","show diagnostic output").hook("preAction",async(r,n)=>{let s=r.opts?.()??{},i=typeof n.opts=="function"?n.opts():{};Rc(s.verbose===true),ld(s.telemetry===false)&&await cd({command:Y$(n),args:i});});for(let r of await ug())r(fc);await fc.parseAsync(),await Si(false);}Q$().then(null).catch(async e=>{console.error(e),await Si(true,e),process.exitCode=1;});
416
+ ${O}`)),j}let Y=["Sessions and JWT secret not migrated. Existing tokens are invalid \u2014 users must re-authenticate.","Management API auth config sync is skipped for --target local; supported local auth settings are written before Supabase starts."];O&&Y.unshift(O),i.config.storage?.enabled&&Y.push("Storage migration is not yet supported."),i.config.realtime?.enabled&&Y.push("Realtime config migration is not yet supported.");let q=eh(S.status.dbUrl);if(t.dumpCredentials){let j=JSON.stringify({target:"local",workdir:S.workdir,projectUrl:S.status.apiUrl,apiUrl:S.status.apiUrl,studioUrl:S.status.studioUrl,dbUrl:S.status.dbUrl,anonKey:S.status.anonKey,serviceRoleKey:S.status.serviceRoleKey,dbPassword:q},null,2);await pe__default.writeFile(t.dumpCredentials,j,"utf-8"),console.log(_e.default.dim(`Credentials written to ${t.dumpCredentials}`));}jl({projectRef:S.projectId,projectUrl:S.status.apiUrl,apiUrl:S.status.apiUrl,studioUrl:S.status.studioUrl,anonKey:S.status.anonKey,serviceRoleKey:S.status.serviceRoleKey,dbPassword:q,auth:x.auth,jwtMigrated:!1,warnings:[`Local Supabase workdir: ${S.workdir}`,...Y]});return}let c=await Q_(t.supabaseToken),p=new $i(c);try{await p.listOrganizations();}catch(b){throw new Error(`Supabase access token rejected: ${String(b)}`)}let u=await z_(p,t.orgId),f=await K_(p,u.slug,t.region),h=await X_(t.projectName),d=await Y_(t.migrateSessions),m=await ch({requested:d,jwtSecret:i.config.auth?.jwt_secret,allowWeakJwtSecret:t.allowWeakJwtSecret}),w=m.migrateSessions,y=J_(),E=Al();E.start("Creating Supabase project");let T=await p.createProject({organization_id:u.id,name:h,db_pass:y,region:f}),v=T.ref??T.id;if(E.stop(`Project created: ${v}`),E.start("Waiting for project to become active"),await p.waitForActive(v,{onTick:b=>E.message(`Project status: ${b}`)}),E.stop("Project is active"),w){E.start("Importing JWT signing key");try{await p.createSigningKey(v,{algorithm:"HS256",status:"in_use",private_jwk:Bd(m.jwtSecret)});}catch(b){throw E.stop(_e.default.red("JWT signing key import failed")),new Error(["Session migration is not available for this Supabase project, token, or plan.","The upgrade cannot preserve existing Supalite sessions without importing auth.jwt_secret as a signing key.","Re-run with --no-migrate-sessions if requiring users to sign in again is acceptable.",`Supabase response: ${String(b)}`].join(" "))}E.stop("JWT signing key imported");}let A=(await Pn("apply",()=>ql(i,{runSql:b=>p.runSql(v,b),updateAuthConfig:b=>p.updateAuthConfig(v,b)},{migrateSessions:w,authTarget:"supabase",onSql:(b,D)=>{t.verbose&&console.log(_e.default.dim(`-- ${D}
417
+ ${b}`));},onSchemaStart:b=>E.start(`Applying schema (0/${b})`),onSchemaProgress:(b,D)=>E.message(`Applying schema (${b}/${D})`),onSchemaEnd:b=>E.stop(`Schema applied (${b} statements)`),onBatchStart:(b,D)=>{E.start(`${b} (0/${D})`);},onBatchProgress:(b,D,O)=>E.message(`${b} (${D}/${O})`),onBatchEnd:(b,D,O)=>E.stop(`${b} (${D} ${O})`),onBatchFailure:(b,D)=>{E.stop(_e.default.red(`${b}: ${D.length} failed`));for(let O of D)console.log(_e.default.red(` \u2717 ${O.error}`)),t.verbose&&console.log(_e.default.dim(` ${O.statement}`));},onAuthConfigStart:()=>E.start("Syncing auth config"),onAuthConfigEnd:()=>E.stop("Auth config synced"),onSkip:b=>console.log(_e.default.dim(b))}))).auth,$=bd(await p.getApiKeys(v)),_=`https://${v}.${p.projectDomain}`,I=[];if(w?m.weakReasons.length>0?I.push(`A weak JWT secret was imported to preserve sessions: ${m.weakReasons.join("; ")}.`):I.push("Sessions preserved by importing auth.jwt_secret as a Supabase signing key."):I.push("Sessions and JWT secret not migrated. Existing tokens are invalid \u2014 users must re-authenticate."),i.config.storage?.enabled&&I.push("Storage migration is not yet supported."),i.config.realtime?.enabled&&I.push("Realtime config migration is not yet supported."),t.dumpCredentials){let b=JSON.stringify({ref:v,projectUrl:_,anonKey:$.anon,serviceRoleKey:$.service_role,dbPassword:y},null,2);await pe__default.writeFile(t.dumpCredentials,b,"utf-8"),console.log(_e.default.dim(`Credentials written to ${t.dumpCredentials}`));}jl({projectRef:v,projectUrl:_,apiUrl:_,anonKey:$.anon,serviceRoleKey:$.service_role,dbPassword:y,auth:A,jwtMigrated:!!(w&&m.jwtSecret),warnings:I});});});});var fh={};de(fh,{login:()=>e$});var Gl,e$,mh=g(()=>{Gl=te(ae());Qe();xr();De();Ce();e$=e=>{e.command("login").description("Login").option("--json","Output in JSON format").helpGroup("Local Development:").action(async t=>{await J(async()=>{let r=await z();K.message(Gl.default.dim("Enter your credentials to login to the cloud"));let n=await Pi(),s=await Oi(),{data:i,error:o}=await r.client.auth.signInWithPassword({email:n,password:s});o&&(K.error(o.message),process.exit(1)),t.json?console.log(JSON.stringify(i,null,2)):K.success(`Authenticated as: ${Gl.default.cyan(i.user.email)}`);});});};});var hh={};de(hh,{logout:()=>t$});var dh,t$,gh=g(()=>{dh=te(ae());Ce();Qe();De();t$=e=>{e.command("logout").description("Logout").helpGroup("Local Development:").action(async()=>{console.log(),await J(async()=>{let t=await z(),{error:r}=await t.client.auth.signOut();r&&(K.error(r.message),process.exit(1)),console.log(dh.default.green("Logged out successfully"));});});};});var yh={};de(yh,{signup:()=>r$});var zl,r$,wh=g(()=>{zl=te(ae());Qe();xr();De();Ce();ot();r$=e=>{e.command("signup").description(be("Register a supalite cloud account")).option("--json","Output in JSON format").helpGroup("Local Development:").action(async t=>{K.message(zl.default.dim("Enter your credentials to sign up to the cloud")),await J(async()=>{let r=await z(),n=await Pi(),s=await Oi(!0),{data:i,error:o}=await r.client.auth.signUp({email:n,password:s});o&&(K.error(o.message),process.exit(1)),t.json?console.log(JSON.stringify(i,null,2)):K.success(`Signed up as: ${zl.default.cyan(i.user.email)}`);});});};});var bh={};de(bh,{whoami:()=>n$});var Vl,n$,Sh=g(()=>{Vl=te(ae());Ce();Qe();De();ot();n$=e=>{e.command("whoami").description(be("Show the current authenticated user")).option("--json","Output in JSON format").helpGroup("Local Development:").action(async t=>{console.log(),await J(async()=>{let r=await z(),{data:n,error:s}=await r.client.auth.getUser();t.json?console.log(JSON.stringify(n,null,2)):n&&"user"in n&&n.user&&"email"in n.user?(console.log(`Authenticated as: ${Vl.default.cyan(n.user.email)}`),process.exit(0)):(console.log(Vl.default.yellow("Not authenticated")),process.exit(1)),s&&(K.error(s.message),process.exit(1));});});};});var xh={};de(xh,{link:()=>s$});var Eh,s$,_h=g(()=>{De();Ce();$e();Qe();Eh=te(ae()),s$=e=>e.command("link").description("Link to a Supalite project").option("--project-ref <project-ref>","The reference of the project to link to").option("--json","Output in JSON format").helpGroup("Local Development:").action(async t=>{console.log(),await J(async()=>{await Q();let r=await z();r.project.local.ref()&&K.warning("Project is already linked.");let n=t.projectRef;if(!n){let i=await r.project.remote.list();n=await Cn({message:"Select a project:",options:i.map(o=>({value:o.id,hint:`name: ${o.name}, created: ${o.created_at}`}))}),Ee(n)&&process.exit(1);}if(!n)throw new Error("No project ref found");console.log("Linking project",n);let s=await r.project.remote.get(n);r.project.local.setRef(s.id),console.log(`Finished linking project ${Eh.default.cyan(s.id)}.`);});});});var $h={};de($h,{unlink:()=>i$});var i$,vh=g(()=>{De();Ce();$e();i$=e=>e.command("unlink").description("Unlink from a Supalite project").option("--json","Output in JSON format").helpGroup("Local Development:").action(async()=>{console.log(),await J(async()=>{await Q(),(await z()).project.local.unlink(),console.log("Finished unlinking project.");});});});var Ah={};de(Ah,{status:()=>o$});var Th,o$,Ch=g(()=>{Ce();De();$e();Th=te(ae());ot();o$=e=>e.command("status").description(be("Show information about the linked project")).helpGroup("Local Development:").action(async()=>{console.log(),await J(async()=>{await Q();let t=await z(),r=await t.project.remote.get();console.log(r),console.log(`Project URL: ${Th.default.cyan(t.project.remote.url(r.id))}`);});});});var kh={};de(kh,{projects:()=>a$});var Kl,a$,l$,c$,Ph=g(()=>{xr();Qe();Kl=te(ae());De();Ce();De();a$=e=>{e.command("projects").description("Manage Supalite cloud projects").helpGroup("Management APIs:").addCommand(c$).addCommand(l$);},l$=new Command$1().name("list").description("List projects").helpGroup("Projects:").action(async()=>{await J(async()=>{let t=await(await z()).project.remote.list();(!Array.isArray(t)||t.length===0)&&(K.info("No projects found"),process.exit(0)),console.log(Mm(t,{omitKeys:["config","user_id"],renderHeader:r=>String(r).split("_").map(n=>n.toUpperCase()).join(" ")}));});}),c$=new Command$1().name("create").description("Create a project").option("--name <name>","The name of the project").helpGroup("Projects:").action(async e=>{await J(async()=>{let t=await z(),r=e.name??await ih(),n=await t.project.remote.create({name:r});K.success(`Project ${Kl.default.cyan(n.name)} created: ${Kl.default.cyan(n.id)}`);});});});function u$(){try{return Hn.statSync("/.dockerenv"),!0}catch{return false}}function p$(){try{return Hn.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return false}}function Jl(){return Xl===void 0&&(Xl=u$()||p$()),Xl}var Xl,Nh=g(()=>{});function Xt(){return Yl===void 0&&(Yl=m$()||Jl()),Yl}var Yl,m$,Ql=g(()=>{Nh();m$=()=>{try{return Hn.statSync("/run/.containerenv"),!0}catch{return false}};});var Ih,ct,ec=g(()=>{Ql();Ih=()=>{if(Ge.platform!=="linux")return false;if(Yw.release().toLowerCase().includes("microsoft"))return !Xt();try{if(Hn.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return !Xt()}catch{}return Hn.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||Hn.existsSync("/run/WSL")?!Xt():false},ct=Ge.env.__IS_WSL_TEST__?Ih:Ih();});var w$,tc,je,rc=g(()=>{w$=promisify(y$.execFile),tc=()=>`${Ge.env.SYSTEMROOT||Ge.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`,je=async(e,t={})=>{let{powerShellPath:r,...n}=t,s=je.encodeCommand(e);return w$(r??tc(),[...je.argumentsPrefix,s],{encoding:"utf8",...n})};je.argumentsPrefix=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"];je.encodeCommand=e=>Buffer$1.from(e,"utf16le").toString("base64");je.escapeArgument=e=>`'${String(e).replaceAll("'","''")}'`;});function jh(e){for(let t of e.split(`
418
+ `)){if(/^\s*#/.test(t))continue;let r=/^\s*root\s*=\s*(?<mountPoint>"[^"]*"|'[^']*'|[^#]*)/.exec(t);if(r)return r.groups.mountPoint.trim().replaceAll(/^["']|["']$/g,"")}}var Fh=g(()=>{});var E$,x$,_$,Ii,Mh,Bh,qh,Hh,Wh=g(()=>{ec();rc();Fh();ec();E$=promisify(y$.execFile),x$=(()=>{let e="/mnt/",t;return async function(){if(t)return t;let r="/etc/wsl.conf",n=false;try{await pe__default.access(r,constants.F_OK),n=!0;}catch{}if(!n)return e;let s=await pe__default.readFile(r,{encoding:"utf8"}),i=jh(s);return i===void 0?e:(t=i,t=t.endsWith("/")?t:`${t}/`,t)}})(),_$=async()=>`${await x$()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Ii=ct?_$:tc,Bh=async()=>(Mh??=(async()=>{try{let e=await Ii();return await pe__default.access(e,constants.X_OK),!0}catch{return false}})(),Mh),qh=async()=>{let e=await Ii(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,{stdout:r}=await je(t,{powerShellPath:e});return r.trim()},Hh=async e=>{if(/^[a-z]+:\/\//i.test(e))return e;try{let{stdout:t}=await E$("wslpath",["-aw",e],{encoding:"utf8"});return t.trim()}catch{return e}};});function Jt(e,t,r){let n=s=>Object.defineProperty(e,t,{value:s,enumerable:true,writable:true});return Object.defineProperty(e,t,{configurable:true,enumerable:true,get(){let s=r();return n(s),s},set(s){n(s);}}),e}var Gh=g(()=>{});async function sc(){if(Ge.platform!=="darwin")throw new Error("macOS only");let{stdout:e}=await A$("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),r=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e)?.groups.id??"com.apple.Safari";return r==="com.apple.safari"?"com.apple.Safari":r}var A$,zh=g(()=>{A$=promisify(execFile);});async function Vh(e,{humanReadableOutput:t=true,signal:r}={}){if(Ge.platform!=="darwin")throw new Error("macOS only");let n=t?[]:["-ss"],s={};r&&(s.signal=r);let{stdout:i}=await P$("osascript",["-e",e,n],s);return i.trim()}var P$,Kh=g(()=>{P$=promisify(execFile);});async function ic(e){return Vh(`tell application "Finder" to set app_path to application file id "${e}" as string
419
+ tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}var Xh=g(()=>{Kh();});async function lc(e=I$){let{stdout:t}=await e("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),r=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(t);if(!r)throw new oc(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:n}=r.groups,s=n.lastIndexOf("."),i=n.lastIndexOf("-"),o=s===-1?void 0:n.slice(0,s),a=i===-1?void 0:n.slice(0,i);return Li[n]??Li[o]??Li[a]??{name:n,id:n}}var I$,Li,ac,oc,cc=g(()=>{I$=promisify(execFile),Li={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},ac=new Map(Object.entries(Li)),oc=class extends Error{};});async function pc(){if(Ge.platform==="darwin"){let e=await sc();return {name:await ic(e),id:e}}if(Ge.platform==="linux"){let{stdout:e}=await j$("xdg-mime",["query","default","x-scheme-handler/http"]),t=e.trim();return {name:F$(t.replace(/.desktop$/,"").replace("-"," ")),id:t}}if(Ge.platform==="win32")return lc();throw new Error("Only macOS, Linux, and Windows are supported")}var j$,F$,Jh=g(()=>{zh();Xh();cc();cc();j$=promisify(execFile),F$=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,t=>t.toUpperCase());});var M$,Yh,Qh=g(()=>{M$=!!(Ge.env.SSH_CONNECTION||Ge.env.SSH_CLIENT||Ge.env.SSH_TTY),Yh=M$;});function rg(e){if(typeof e=="string"||Array.isArray(e))return e;let{[eg]:t}=e;if(!t)throw new Error(`${eg} is not supported`);return t}function jn({[_r]:e},{wsl:t}={}){if(t&&ct)return rg(t);if(!e)throw new Error(`${_r} is not supported`);return rg(e)}var Di,mc,Zh,_r,eg,tg,ji,W$,$r,ig,og=g(()=>{Wh();rc();Gh();Jh();Ql();Qh();Di=Symbol("fallbackAttempt"),mc=import.meta.url?Me__default.dirname(fileURLToPath(import.meta.url)):"",Zh=Me__default.join(mc,"xdg-open"),{platform:_r,arch:eg}=Ge,tg=async(e,t)=>{if(e.length===0)return;let r=[];for(let n of e)try{return await t(n)}catch(s){r.push(s);}throw new AggregateError(r,"Failed to open in all supported apps")},ji=async e=>{e={wait:false,background:false,newInstance:false,allowNonzeroExitCode:false,...e};let t=e[Di]===true;if(delete e[Di],Array.isArray(e.app))return tg(e.app,c=>ji({...e,app:c,[Di]:true}));let{name:r,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(r))return tg(r,c=>ji({...e,app:{name:c,arguments:n},[Di]:true}));if(r==="browser"||r==="browserPrivate"){let c={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge","com.apple.safari":"safari"},p={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},u;if(ct){let f=await qh();u=ac.get(f)??{};}else u=await pc();if(u.id in c){let f=c[u.id.toLowerCase()];if(r==="browserPrivate"){if(f==="safari")throw new Error("Safari doesn't support opening in private mode via command line");n.push(p[f]);}return ji({...e,app:{name:$r[f],arguments:n}})}throw new Error(`${u.name} is not supported as a default browser`)}let s,i=[],o={},a=false;if(ct&&!Xt()&&!Yh&&!r&&(a=await Bh()),_r==="darwin")s="open",e.wait&&i.push("--wait-apps"),e.background&&i.push("--background"),e.newInstance&&i.push("--new"),r&&i.push("-a",r);else if(_r==="win32"||a){s=await Ii(),i.push(...je.argumentsPrefix),ct||(o.windowsVerbatimArguments=true),ct&&e.target&&(e.target=await Hh(e.target));let c=["$ProgressPreference = 'SilentlyContinue';","Start"];e.wait&&c.push("-Wait"),r?(c.push(je.escapeArgument(r)),e.target&&n.push(e.target)):e.target&&c.push(je.escapeArgument(e.target)),n.length>0&&(n=n.map(p=>je.escapeArgument(p)),c.push("-ArgumentList",n.join(","))),e.target=je.encodeCommand(c.join(" ")),e.wait||(o.stdio="ignore");}else {if(r)s=r;else {let c=!mc||mc==="/",p=false;try{await pe__default.access(Zh,constants.X_OK),p=!0;}catch{}s=Ge.versions.electron??(_r==="android"||c||!p)?"xdg-open":Zh;}n.length>0&&i.push(...n),e.wait||(o.stdio="ignore",o.detached=true);}_r==="darwin"&&n.length>0&&i.push("--args",...n),e.target&&i.push(e.target);let l=y$.spawn(s,i,o);return e.wait?new Promise((c,p)=>{l.once("error",p),l.once("close",u=>{if(!e.allowNonzeroExitCode&&u!==0){p(new Error(`Exited with code ${u}`));return}c(l);});}):t?new Promise((c,p)=>{l.once("error",p),l.once("spawn",()=>{l.once("close",u=>{if(l.off("error",p),u!==0){p(new Error(`Exited with code ${u}`));return}l.unref(),c(l);});});}):(l.unref(),new Promise((c,p)=>{l.once("error",p),l.once("spawn",()=>{l.off("error",p),c(l);});}))},W$=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a `target`");return ji({...t,target:e})};$r={browser:"browser",browserPrivate:"browserPrivate"};Jt($r,"chrome",()=>jn({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium","chromium-browser"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));Jt($r,"brave",()=>jn({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));Jt($r,"firefox",()=>jn({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));Jt($r,"edge",()=>jn({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));Jt($r,"safari",()=>jn({darwin:"Safari"}));ig=W$;});var ag={};de(ag,{cloud:()=>K$});var Fe,V$,K$,lg=g(()=>{Fe=te(ae());og();De();Ce();xr();Ye();gi();Yt();$e();ot();V$="Management APIs:",K$=e=>{let t=e.command("cloud").description(be("Supalite cloud operations")).helpGroup(V$);t.command("deploy").description("Push schema + config + seed to the linked supalite cloud project").option("--config <config>","Path to the config file").option("--force","Force the push",false).action(async r=>{console.log();let n=qi().filter(s=>s!=="cloud");n.length>0&&(console.error(Fe.default.red(`Cannot deploy: experimental features enabled (${n.join(", ")}). Cloud does not support them yet.`)),process.exit(1)),await J(async()=>{await Q(r.config);let s=await z(),i=await s.project.local.createApp(r.config),o=!1;await bn(i,{force:!0});let a=await s.project.remote.get().catch(async()=>{if(await Ni("No project found. Create a new project?"))return o=!0,await s.project.remote.create().then(m=>s.project.local.link(m));throw new Error("No project found")}),l=await s.project.remote.createApp(a.id),c=await ge(i),p=l.connection.createMigrator(c),u=await p.diff();console.log(),dr(u);let f=l.getInfoJson(),h=i.getInfoJson();if(isEqual(f,h))console.log(Fe.default.dim("Project config is up to date"));else {if(!await s.project.remote.setConfig(a.id,h))throw new Error("Failed to update project config");console.log(Fe.default.green("Project config updated"));}let d=s.project.remote.url(a.id);if(u.plan.steps.length>0)try{if(await measureTime(async()=>{await p.migratePlan(u.plan,{force:r.force??!1});},m=>{console.log(Fe.default.green(`Pushed changes to project in ${m.toFixed(2)}ms.`));}),o)try{let m=await Sn(l,{recoveryHint:"Fix `supabase/seed.sql` and rerun `lite cloud deploy` against the new project."});m>0&&console.log(Fe.default.green(`Seeded remote project (${m} statements).`));}catch(m){console.warn(Fe.default.yellow(String(m.message??m)));}console.log(`Project URL: ${Fe.default.cyan(d)}
420
+ `),o&&await ig(d);}catch(m){m instanceof hi&&(console.warn(Fe.default.yellow("Migration would cause data loss. Rerun with --force to proceed.")),process.exit(1)),console.error(Fe.default.red("Migration error: "+String(m))),process.exit(1);}else console.log(Fe.default.green("No changes to push."));});}),t.command("diff").description("Diff local project against the linked supalite cloud project").option("--config <config>","Path to the config file").option("--sql","Show the SQL for the diff",false).action(async r=>{console.log(),await J(async()=>{await Q(r.config);let n=await z(),s=await n.project.local.createApp(r.config);if(await bn(s,{force:!0}),!n.project.local.ref())throw new Error("No project linked");let i=await n.project.remote.get();if(!i)throw new Error("Project not found");let o=await n.project.remote.createApp(i.id),a=await ge(s),l=await o.connection.createMigrator(a).diff();if(l.plan.steps.length>0)if(r.sql){let c=el(l,{colorize:!0});console.log(Fe.default.cyan(c));}else dr(l);else console.log(Fe.default.green("No changes to migrate."));});});};});Ui();var pg=te(ae());Yt();var cg={init:()=>Promise.resolve().then(()=>(Ic(),Nc)).then(e=>e.init),start:()=>Promise.resolve().then(()=>(Hp(),qp)).then(e=>e.start),dev:()=>Promise.resolve().then(()=>(mm(),fm)).then(e=>e.dev),repl:()=>Promise.resolve().then(()=>(hm(),dm)).then(e=>e.repl),debug:()=>Promise.resolve().then(()=>(ym(),gm)).then(e=>e.debug),db:()=>Promise.resolve().then(()=>(gd(),hd)).then(e=>e.db),migration:()=>Promise.resolve().then(()=>(wd(),yd)).then(e=>e.migration),upgrade:()=>Promise.resolve().then(()=>(ph(),uh)).then(e=>e.upgrade)},X$={login:()=>Promise.resolve().then(()=>(mh(),fh)).then(e=>e.login),logout:()=>Promise.resolve().then(()=>(gh(),hh)).then(e=>e.logout),signup:()=>Promise.resolve().then(()=>(wh(),yh)).then(e=>e.signup),whoami:()=>Promise.resolve().then(()=>(Sh(),bh)).then(e=>e.whoami),link:()=>Promise.resolve().then(()=>(_h(),xh)).then(e=>e.link),unlink:()=>Promise.resolve().then(()=>(vh(),$h)).then(e=>e.unlink),status:()=>Promise.resolve().then(()=>(Ch(),Ah)).then(e=>e.status),projects:()=>Promise.resolve().then(()=>(Ph(),kh)).then(e=>e.projects),cloud:()=>Promise.resolve().then(()=>(lg(),ag)).then(e=>e.cloud)};function J$(){return bc("cloud")?{...cg,...X$}:cg}async function ug(){let e=J$(),t=process.argv[2];return t&&Object.hasOwn(e,t)?[await e[t]()]:Promise.all(Object.values(e).map(r=>r()))}$e();xi();er();var dc=new Command;function Q$(e){let t=[],r=e;for(;r&&r.name&&r.name()&&r.parent;)t.unshift(r.name()),r=r.parent;return t.join(" ")}async function Z$(){let{version:e,name:t}=await Qn();dc.name("lite").description(`${pg.default.yellowBright("\u26A1")} ${t} v${e}`).version(e).option("--no-telemetry","disable anonymous usage telemetry").option("--verbose","show diagnostic output").hook("preAction",async(r,n)=>{let s=r.opts?.()??{},i=typeof n.opts=="function"?n.opts():{};Pc(s.verbose===true),ud(s.telemetry===false)&&await pd({command:Q$(n),args:i});});for(let r of await ug())r(dc);await dc.parseAsync(),await Ei(false);}Z$().then(null).catch(async e=>{console.error(e),await Ei(true,e),process.exitCode=1;});
419
421
  /*! Bundled license information:
420
422
 
421
423
  smol-toml/dist/error.js: