@supabase/lite 0.2.1-next.1 → 0.3.0
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/README.md +1 -2
- package/STATUS.md +7 -6
- package/dist/{Connection-rAPmec1m.d.ts → Connection-CSVCuMv-.d.ts} +1 -152
- package/dist/cli/index.js +152 -128
- package/dist/cli/lib.js +39 -36
- package/dist/db/browser/index.d.ts +3 -532
- package/dist/db/browser/index.js +3 -207
- package/dist/db/bun/index.d.ts +3 -532
- package/dist/db/bun/index.js +3 -207
- package/dist/db/fallback.d.ts +4 -180
- package/dist/db/fallback.js +2 -205
- package/dist/db/node/index.d.ts +3 -532
- package/dist/db/node/index.js +3 -207
- package/dist/db/postgres/{BasePostgresConnection-B7zHDAib.d.ts → BasePostgresConnection-Clykq58D.d.ts} +1 -1
- package/dist/db/postgres/PostgresConnection.d.ts +1 -1
- package/dist/db/postgres/PostgresConnection.js +21 -25
- package/dist/db/postgres/pglite/PgliteConnection.d.ts +1 -1
- package/dist/db/postgres/pglite/PgliteConnection.js +25 -27
- package/dist/db/workerd/index.d.ts +6 -535
- package/dist/db/workerd/index.js +2 -206
- package/dist/index.d.ts +329 -7
- package/dist/index.js +252 -54
- package/dist/vite/index.js +2 -6
- package/package.json +4 -8
package/dist/cli/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
2
|
+
import In,{statSync,readFileSync}from'node:fs';import*as ce from'node:fs/promises';import ce__default,{stat,constants}from'node:fs/promises';import*as He from'node:path';import He__default,{join}from'node:path';import {fileURLToPath}from'node:url';import {createConnection}from'@supabase/lite/sqlite';import pw from'node:os';import {createClient}from'@supabase/supabase-js';import U0,{createHash}from'node:crypto';import {parse}from'dotenv';import {DataLossError,isEqual,measureTime,splitSqlStatements,ensureVar,App,cloud}from'@supabase/lite';import {createRequire}from'module';import pf,{posix,sep,basename,dirname,resolve,normalize,relative}from'path';import*as er from'fs';import er__default from'fs';import {fileURLToPath as fileURLToPath$1}from'url';import {Deparser,QuoteUtils}from'pgsql-deparser';import XS from'chokidar';import {styleText,promisify}from'node:util';import qe,{stdout,stdin}from'node:process';import*as ht from'node:readline';import ht__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 y0 from'node:net';import {Command as Command$1}from'@commander-js/extra-typings';import m_,{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 Mn,{statSync,readFileSync,stat as stat$1,unwatchFile,watchFile,watch}from
|
|
|
10
10
|
};
|
|
11
11
|
} catch {}
|
|
12
12
|
|
|
13
|
-
var
|
|
13
|
+
var Dh=Object.create;var Ci=Object.defineProperty;var jh=Object.getOwnPropertyDescriptor;var Fh=Object.getOwnPropertyNames;var Mh=Object.getPrototypeOf,Uh=Object.prototype.hasOwnProperty;var y=(e,t)=>()=>(e&&(t=e(e=0)),t);var it=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),fe=(e,t)=>{for(var r in t)Ci(e,r,{get:t[r],enumerable:true});},Bh=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Fh(t))!Uh.call(e,s)&&s!==r&&Ci(e,s,{get:()=>t[s],enumerable:!(n=jh(t,s))||n.enumerable});return e};var ee=(e,t,r)=>(r=e!=null?Dh(Mh(e)):{},Bh(Ci(r,"default",{value:e,enumerable:true}),e));var se=it((Y_,Ri)=>{var On=process||{},Xl=On.argv||[],Nn=On.env||{},qh=!(Nn.NO_COLOR||Xl.includes("--no-color"))&&(!!Nn.FORCE_COLOR||Xl.includes("--color")||On.platform==="win32"||(On.stdout||{}).isTTY&&Nn.TERM!=="dumb"||!!Nn.CI),Hh=(e,t,r=e)=>n=>{let s=""+n,i=s.indexOf(t,e.length);return ~i?e+Wh(s,t,r,i)+t:e+s+t},Wh=(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)},Yl=(e=qh)=>{let t=e?Hh:()=>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")}};Ri.exports=Yl();Ri.exports.createColors=Yl;});function zh(e){let t=typeof process<"u"&&process.env||void 0;return t?t.NODE_ENV==="test"?true:t[Gh[e]]==="1":false}function ec(e){return Zl[e]}function ki(){return Ql.filter(e=>Zl[e])}function Ln(){let e=ki();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 Gh,Ql,Zl,qt=y(()=>{Gh={storage:"EXPERIMENTAL_STORAGE",cloud:"EXPERIMENTAL_CLOUD"},Ql=["storage","cloud"],Zl=Object.fromEntries(Ql.map(e=>[e,zh(e)]));});function Re(e,t){In.existsSync(e)||(In.mkdirSync(e,{recursive:true}),t?.());}function yt(e,t,r){In.existsSync(e)||(In.writeFileSync(e,t),r?.());}var wt=y(()=>{});function Kh(e,t){let r=e.slice(0,t).split(/\r\n|\n|\r/g);return [r.length,r.pop().length+1]}function Jh(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
|
-
`));}return s}var H,
|
|
15
|
+
`));}return s}var H,bt=y(()=>{H=class extends Error{line;column;codeblock;constructor(t,r){let[n,s]=Kh(r.toml,r.ptr),i=Jh(r.toml,n,s);super(`Invalid TOML document: ${t}
|
|
16
16
|
|
|
17
|
-
${i}`,r),this.line=n,this.column=s,this.codeblock=i;}};});function
|
|
18
|
-
`,t);return e[n-1]==="\r"&&n--,n<=r?n:-1}function
|
|
17
|
+
${i}`,r),this.line=n,this.column=s,this.codeblock=i;}};});function Xh(e,t){let r=0;for(;e[t-++r]==="\\";);return --r&&r%2}function Dn(e,t=0,r=e.length){let n=e.indexOf(`
|
|
18
|
+
`,t);return e[n-1]==="\r"&&n--,n<=r?n:-1}function Ht(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 ke(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:ke(e,
|
|
22
|
+
`);)t++;return n||s!=="#"?t:ke(e,Ht(e,t),r)}function rc(e,t,r,n,s=false){if(!n)return t=Dn(e,t),t<0?e.length:t;for(let i=t;i<e.length;i++){let o=e[i];if(o==="#")i=Dn(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
|
|
24
|
+
`))return i}}throw new H("cannot find end of structure",{toml:e,ptr:t})}function jn(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!=="'"&&Xh(e,t));return t>-1&&(t+=n.length,n.length>1&&(e[t]===r&&t++,e[t]===r&&t++)),t}var gr=y(()=>{bt();});var Yh,yr,Pi=y(()=>{Yh=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,yr=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(Yh);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 Fn(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
|
-
`){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 u=e.slice(t,t+=c==="x"?2:c==="u"?4:8);if(!
|
|
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 u=e.slice(t,t+=c==="x"?2:c==="u"?4:8);if(!tg.test(u))throw new H("invalid unicode escape",{toml:e,ptr:i});try{a+=String.fromCodePoint(parseInt(u,16));}catch{throw new H("invalid unicode escape",{toml:e,ptr:i})}}else if(s&&(c===`
|
|
28
28
|
`||c===" "||c===" "||c==="\r")){if(t=ke(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=ke(e,t);}else if(c in
|
|
30
|
-
`,f:"\f",r:"\r",e:"\x1B",'"':'"',"\\":"\\"};});function
|
|
31
|
-
`&&e[o]!=="\r")throw new H("unexpected character encountered",{toml:e,ptr:o});o+=+(e[o]===",");}return [l,o]}o=
|
|
32
|
-
`&&o!=="\r"){let a,l=s,c=false,[u,p]=
|
|
33
|
-
`&&i!=="\r"){let o=
|
|
34
|
-
`&&e[a]!=="\r")throw new H("each key-value declaration must be followed by an end-of-line",{toml:e,ptr:a});a=ke(e,a);}return n}var
|
|
29
|
+
`&&e[t]!=="\r")throw new H("invalid escape: only line-ending whitespace may be escaped",{toml:e,ptr:i});t=ke(e,t);}else if(c in nc)a+=nc[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 sc(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=Qh.test(e);if(s||Zh.test(e)){if(eg.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 yr(e);if(!i.isValid())throw new H("invalid value",{toml:t,ptr:r});return i}var Qh,Zh,eg,tg,nc,Ni=y(()=>{gr();Pi();bt();Qh=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,Zh=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,eg=/^[+-]?0[0-9_]/,tg=/^[0-9a-f]{2,8}$/i,nc={b:"\b",t:" ",n:`
|
|
30
|
+
`,f:"\f",r:"\r",e:"\x1B",'"':'"',"\\":"\\"};});function rg(e,t,r){let n=e.slice(t,r),s=n.indexOf("#");return s>-1&&(Ht(e,s),n=n.slice(0,s)),[n.trimEnd(),s]}function wr(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==="["?oc(e,t,n,s):ic(e,t,n,s);if(r){if(c=ke(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=jn(e,t);let l=Fn(e,t,o);if(r){if(o=ke(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=rc(e,t,",",r);let a=rg(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=ke(e,t+a[1]),o+=+(e[o]===",")),[sc(a[0],e,t,s),o]}var Oi=y(()=>{Ni();Li();gr();bt();});function Mn(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=jn(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=Dn(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(Fn(e,t,a));}else {n=e.indexOf(".",t);let a=e.slice(t,n<0||n>i?i:n);if(!ng.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,ke(e,i+1,true,true)]}function ic(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=Ht(e,t);else if(o!==" "&&o!==" "&&o!==`
|
|
32
|
+
`&&o!=="\r"){let a,l=s,c=false,[u,p]=Mn(e,t-1);for(let d=0;d<u.length;d++){if(d&&(l=c?l[a]:l[a]={}),a=u[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]=wr(e,p,"}",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 oc(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=Ht(e,t);else if(i!==" "&&i!==" "&&i!==`
|
|
33
|
+
`&&i!=="\r"){let o=wr(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 ng,Li=y(()=>{Ni();Oi();gr();bt();ng=/^[a-zA-Z0-9-_]+[ \t]*$/;});function ac(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 u=s.length-1;s=s[u],i=i[u].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 St(e,{maxDepth:t=1e3,integersAsBigInt:r}={}){let n={},s={},i=n,o=s;for(let a=ke(e,0);a<e.length;){if(e[a]==="["){let l=e[++a]==="[",c=Mn(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 u=ac(c[0],n,s,l?2:1);if(!u)throw new H("trying to redefine an already defined table or value",{toml:e,ptr:a});o=u[2],i=u[1],a=c[1];}else {let l=Mn(e,a),c=ac(l[0],i,o,0);if(!c)throw new H("trying to redefine an already defined table or value",{toml:e,ptr:a});let u=wr(e,l[1],void 0,t,r);c[1][c[0]]=u[0],a=u[1];}if(a=ke(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=ke(e,a);}return n}var lc=y(()=>{Li();Oi();gr();bt();});function br(e){let t=typeof e;if(t==="object"){if(Array.isArray(e))return "array";if(e instanceof Date)return "date"}return t}function sg(e){for(let t=0;t<e.length;t++)if(br(e[t])!=="object")return false;return e.length!=0}function Ii(e){return JSON.stringify(e).replace(/\x7f/g,"\\u007f")}function Di(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 Ii(e);if(t==="date"){if(isNaN(e.getTime()))throw new TypeError("cannot serialize invalid date");return e.toISOString()}if(t==="object")return ig(e,r,n);if(t==="array")return og(e,r,n)}function ig(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:Ii(o),s+=" = ",s+=Di(e[o],br(e[o]),t-1,r);}return s+" }"}function og(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+=Di(e[s],br(e[s]),t-1,r);}return n+" ]"}function ag(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+=
|
|
37
|
-
`)+
|
|
38
|
-
`)+
|
|
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 u=br(t[c]);if(u==="symbol"||u==="function")throw new TypeError(`cannot serialize values of type '${u}'`);let p=cc.test(c)?c:Ii(c);if(u==="array"&&sg(t[c]))o+=(o&&`
|
|
37
|
+
`)+ag(t[c],r?`${r}.${p}`:p,n-1,s);else if(u==="object"){let f=r?`${r}.${p}`:p;o+=(o&&`
|
|
38
|
+
`)+ji(f,t[c],f,n-1,s);}else i+=p,i+=" = ",i+=Di(t[c],u,n,s),i+=`
|
|
39
39
|
`;}}return e&&(i||!o)&&(i=i?`[${e}]
|
|
40
40
|
${i}`:`[${e}]`),i&&o?`${i}
|
|
41
|
-
${o}`:i||o}function
|
|
41
|
+
${o}`:i||o}function Fi(e,{maxDepth:t=1e3,numbersAsFloat:r=false}={}){if(br(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
|
|
44
|
-
`);}),
|
|
45
|
-
`);}var
|
|
43
|
+
`:n}var cc,uc=y(()=>{cc=/^[a-z0-9-_]+$/i;});var Sr=y(()=>{lc();uc();Pi();bt();});var _e,Wt=y(()=>{_e={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"};});async function cg(e=""){try{let t=He__default.resolve(Hn(),He__default.join(e,"package.json")),r=await ce__default.readFile(t,"utf-8");if(r)return JSON.parse(r)}catch{}return {}}async function qn(e=""){let t=await cg(e);return t?{name:t.name,version:t.version??"unknown"}:{name:"unknown",version:"unknown"}}function Hn(){let e=He__default.dirname(fileURLToPath(import.meta.url));return He__default.resolve(e,process.env.LOCAL?"../../../":"../../")}function Mi(){return He__default.resolve(Hn(),"dist")}function Wn(){return He__default.relative(process.cwd(),Mi())}async function Er(e){let t=He__default.relative(process.cwd(),_e.config_dir);if(!e)for(let r of ug){let n=He__default.join(t,`config.${r}`);if(await ce__default.access(n).then(()=>true).catch(()=>false)){e=n;break}}return e}async function Y(e){await Er(e)||(console.error(Bn.default.red("No project found. Run `lite init` first.")),process.exit(1));}async function pc(e){let t=await Er(e);if(!t)return {};switch(console.log(Bn.default.dim(`Using config file: ${Bn.default.cyan(`./${t}`)}`)),t.split(".").pop()){case "toml":return St(await ce__default.readFile(t,"utf-8"));case "json":return JSON.parse(await ce__default.readFile(t,"utf-8"));case "ts":case "mts":case "js":case "mjs":case "cjs":try{return (await import(He__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 fc(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 He__default.resolve(process.cwd(),t)}var Bn,ug,we=y(()=>{Sr();Wt();Bn=ee(se());ug=["toml","json","ts","mts","js","mjs","cjs"];});async function Gn(e={}){let t=process.cwd();if(e.recreate){console.log(Bi.default.dim("Recreating database..."));try{let n=await Er();if(n&&!/\.(ts|mts|js|mjs|cjs)$/.test(n)){let i=(await pc(n))?.db?.url,o=i?fc(i):void 0;o&&In.existsSync(o)&&(In.rmSync(o,{recursive:!0,force:!0}),console.log(Bi.default.dim(` \u279C removed ${He__default.relative(t,o)}`)));}}catch{}try{In.rmSync(He__default.join(t,"supabase",".temp"),{recursive:!0,force:!0});}catch{}}if(Re(He__default.join(t,"supabase")),!await Er()){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=He__default.relative(process.cwd(),He__default.join(t,"supabase",".temp","data")));let s=e.configFormat??"toml",i=He__default.join(t,"supabase",`config.${s}`);s==="json"?yt(i,JSON.stringify(n)):yt(i,Fi(n));}Re(He__default.join(t,"supabase",".temp")),Re(He__default.join(t,"supabase","schemas"),()=>{yt(He__default.join(t,"supabase","schemas","schema.sql"),e.template?pg:`-- This is a schema file for the database
|
|
44
|
+
`);}),yt(He__default.join(t,"supabase","seed.sql"),e.template?fg:`-- This is a seed file for the database
|
|
45
|
+
`);}var Bi,pg,fg,qi=y(()=>{wt();Bi=ee(se());Sr();we();pg=`
|
|
46
46
|
create table todos (
|
|
47
47
|
id serial primary key,
|
|
48
48
|
title text not null,
|
|
@@ -55,18 +55,18 @@ create table todos (
|
|
|
55
55
|
create table test (
|
|
56
56
|
id serial primary key,
|
|
57
57
|
name text not null
|
|
58
|
-
)`,
|
|
58
|
+
)`,fg="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 dc={};fe(dc,{init:()=>mg});var Hi,mg,hc=y(()=>{Hi=ee(se());qi();mg=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 Gn({configFormat:t.format,recreate:t.recreate,driver:t.pglite?"pglite":void 0}),console.log(),console.log(Hi.default.green(" \u279C"),"Project initialized",Hi.default.cyan("./"+He__default.relative(process.cwd(),He__default.join(process.cwd(),"supabase"))));});};});var gc=y(()=>{});var yc=y(()=>{});function Wi(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:Wi(e[s],i,r)}catch{if(typeof r<"u")return r;throw new Error(`Invalid path: ${n.join(".")}`)}}var wc=y(()=>{});var bc=y(()=>{});function zn(){try{return !xr()&&global?.process?.release?.name==="node"}catch{return false}}function xr(){try{return typeof Bun<"u"}catch{return false}}async function Vn(e,t){let r=performance.now();await e();let n=performance.now();t(n-r);}var Sc=y(()=>{});function Ec(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
|
|
61
|
-
`;)r+=e[n],n++;continue}if(o==="/"&&a==="*"){for(r+="/*",n+=2;n<s&&!(e[n]==="*"&&e[n+1]==="/");)r+=e[n],n++;n<s&&(r+="*/",n+=2);continue}if(o==="'"){for(r+=o,n++;n<s;){if(e[n]==="'"&&e[n+1]==="'"){r+="''",n+=2;continue}if(r+=e[n],e[n]==="'"){n++;break}n++;}continue}if(o==='"'){for(r+=o,n++;n<s;){if(e[n]==='"'&&e[n+1]==='"'){r+='""',n+=2;continue}if(r+=e[n],e[n]==='"'){n++;break}n++;}continue}if(o==="$"){let l=e.indexOf("$",n+1);if(l!==-1){let c=e.slice(n,l+1);if(/^\$[A-Za-z_][A-Za-z0-9_]*\$$|^\$\$$/.test(c)){r+=c,n=l+1;let p=e.indexOf(c,n);p===-1?(r+=e.slice(n),n=s):(r+=e.slice(n,p+c.length),n=p+c.length);continue}}}if(o===";"){i(r),r="",n++;continue}r+=o,n++;}return i(r),t}function
|
|
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 ro(e){return (e??"").trim().toLowerCase()}function no(e){return (e??"").replace(/\s+/g," ").replace(/"/g,"").trim().toLowerCase()}function so(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 $r=y(()=>{});function Xg(e,t,r=void 0){let n=typeof t=="string"?Vc(t):ao(t);return ts(e,n,r)}function ts(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:ts(e[s],i,r)}catch{if(typeof r<"u")return r;throw new Error(`Invalid path: ${n.join(".")}`)}}function ey(e){return e===null}function he(e){return !Array.isArray(e)&&typeof e=="object"&&e!==null}function ty(e){return Object.prototype.toString.call(e)==="[object Object]"}function Ke(e){return typeof e=="string"}function et(e){return typeof e=="number"}function ry(e){return typeof e=="number"&&Number.isInteger(e)}function uo(e){return typeof e=="boolean"}function ut(e){return Array.isArray(e)}function ny(e){return typeof e!="boolean"}function sy(e){return e!==void 0&&ny(e)&&"type"in e}function Ae(e){return e!==void 0&&he(e)&&Te in e}function iy(e){return Ae(e)&&typeof e.toJSON()=="boolean"}function oy(e,t,r){if(!e)throw new Zg(t,r)}function Kc(e){return Ke(e)?e.normalize("NFC"):e}function Tr(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(!Tr(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(!Tr(e[i],t[i]))return false;return true}return e===t}function ay(e,t){return t.reduce((r,n)=>(n in e&&(r[n]=e[n]),r),{})}function Yc(e){try{return structuredClone(e)}catch{return e}}function ly(e,t,r={}){let n=t;try{n=structuredClone(t);}catch{n=JSON.parse(JSON.stringify(t));}let s={resolver:r.resolver||new po(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 rs(e,t,r={}){return e.map(n=>n.validate(t,es(r)).valid?n:void 0).filter(Boolean)}function By(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 po(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=io[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 io&&e[o]!==void 0){if(s===void 0)continue;let a=io[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 ns(e,t,r){return new class extends tt{type=e}(t,r)}function lo(e){return new qy(e)}function zc(e,t){return Array.isArray(e)?e.map(t):e!==void 0?[t(e)]:[]}function Gc(e,t,r=n=>n){return Object.fromEntries(Object.entries(e).map(([n,s])=>[n,r(t(s,n),n)]))}function Kt(e){if(uo(e))return lo(e);let t=structuredClone(e);if(!he(t))throw new Qg("non-object schemas cannot be converted to a schema",t);"properties"in t&&t.properties&&(t.properties=Gc(t.properties,(i,o)=>{try{return Kt(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]=Gc(t[i],Kt));let n=["additionalProperties","items","prefixItems","propertyNames","contains","not","if","then","else"];for(let i of n)i in t&&typeof t[i]<"u"&&(ut(t[i])?t[i]=zc(t[i],Kt):t[i]=Kt(t[i]));let s=["anyOf","oneOf","allOf"];for(let i of s)if(i in t){let{[i]:o}=t;t[i]=zc(o,Kt);}if(sy(t))switch(t.type){case "string":return Xc(t);case "number":return Zc(t);case "integer":return eu(t);case "boolean":return ru(t);case "object":{let{properties:i,...o}=t;return ss(i,o)}case "array":{let{items:i,...o}=t;return tu(i,o)}}return Jc(t)}function tw(){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(Zy.map(e=>[e,t=>Math.min(...t)])),...Object.fromEntries(ew.map(e=>[e,t=>Math.max(...t)]))}}function rw(e){let t={...tw(),...e.resolvers};function r(n,s){if(Array.isArray(n)&&Array.isArray(s))return [...new Set([...n,...s])];if(co(n)&&co(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):oo(a);}else i[o]=oo(a);return i}return oo(s)}return r}function sw(e,t={}){let r=t.deep!==false,n=rw(t);function s(i){if(Array.isArray(i))return i.map(s);if(!co(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),{}),u=nw(c);if(u!==null)return u;let p={...i};delete p.allOf;let f=n(c,r?s(p):p);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 ao,Vc,Z,D,Yt,es,xt,Qg,Zg,Te,po,cy,uy,py,fy,my,dy,hy,gy,yy,wy,by,Sy,Ey,_y,xy,vy,$y,Ty,Ay,Cy,Ry,Py,ky,Ny,Oy,Iy,Ly,Dy,jy,Fy,My,Wc,Uy,io,tt,Ar,qy,Jc,Hy,Wy,ss,zy,Gy,Vy,Ky,Yy,Xc,Qc,Zc,eu,Jy,tu,ru,Zn,nu,Xy,Qy,co,oo,Zy,ew,nw,iw,su,ow,aw,lw,iu,ou=y(()=>{ao=(e=[],t="")=>"/"+[t,...e.map(r=>String(r).replace(/\./g,"/"))].filter(Boolean).join("/"),Vc=e=>e.split("/").slice(1);Z=(e={},t,r,n)=>({valid:false,errors:[...e.errors??[],{keywordLocation:ao([...e.keywordPath??[],t]),instanceLocation:ao(e.instancePath),error:typeof r=="string"?r:`Invalid value for ${t}`,data:n}]}),D=()=>({valid:true,errors:[]}),Yt=(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}},es=(e={})=>({...e,errors:[]}),xt=class extends Error{constructor(e){super(`Expected ${e}`);}},Qg=class extends Error{constructor(e,t){super(`${e??"Invalid raw schema"}: ${JSON.stringify(t)}`),this.schema=t;}},Zg=class extends Error{constructor(e,t){super(`${e}, got: 'type "${typeof t}": ${JSON.stringify(t)}'`),this.value=t;}},Te=Symbol.for("jsonv-ts:schema");po=class{constructor(e){this.root=e,this.cache=new Map;}cache;hasRef(e,t){return t!==void 0&&"$ref"in e&&Ke(e.$ref)}resolve(e){let t=this.cache.get(e);if(!t){if(t=Xg(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}};cy=({type:e},t,r={})=>{if(e===void 0||t===void 0)return D();let n,s={string:Ke,number:et,integer:ry,object:he,array:ut,boolean:uo,null:ey};if(Array.isArray(e)){for(let i of e){if(!(i in s))throw new xt(`Unknown type: ${i}`);if(s[i](t))return D()}n=`Expected one of: ${e.join(", ")}`;}else {if(!(e in s))throw new xt(`Unknown type: ${e}`);s[e](t)||(n=`Expected ${e}`);}return n?Z(r,"type",n,t):D()},uy=({const:e},t,r={})=>Tr(e,t)?D():Z(r,"const",`Expected const: ${e}`,t),py=({enum:e=[]},t,r={})=>e.some(n=>Tr(n,t))?D():Z(r,"enum",`Expected enum: ${JSON.stringify(e)}`,t);fy=({anyOf:e=[]},t,r={})=>rs(e,t,r).length>0?D():Z(r,"anyOf","Expected at least one to match",t),my=({oneOf:e=[]},t,r={})=>rs(e,t).length===1?D():Z(r,"oneOf","Expected exactly one to match",t),dy=({allOf:e=[]},t,r={})=>rs(e,t,r).length===e.length?D():Z(r,"allOf","Expected all to match",t),hy=({not:e},t,r={})=>t===void 0?D():Ae(e)&&e.validate(t,r).valid?Z(r,"not","Expected not to match",t):D(),gy=({if:e,then:t,else:r},n,s={})=>{if(e&&(t||r)){if(e.validate(n,es(s)).valid)return t?t.validate(n,es(s)):D();if(r)return r.validate(n,es(s))}return D()},yy=({pattern:e=""},t,r={})=>{if(!Ke(t))return D();if(e instanceof RegExp){if(e.test(t))return D()}else if(new RegExp(e,"u").test(t))return D();return Z(r,"pattern",`Expected string matching pattern ${e}`,t)},wy=({minLength:e=0},t,r={})=>Ke(t)?[...Kc(t)].length>=e?D():Z(r,"minLength",`Expected string with minimum length of ${e}`,t):D(),by=({maxLength:e=0},t,r={})=>Ke(t)?[...Kc(t)].length<=e?D():Z(r,"maxLength",`Expected string with maximum length of ${e}`,t):D(),Sy=({multipleOf:e=0},t,r={})=>{if(!et(t))return D();if(!(Number.isFinite(t)&&Number.isFinite(e))||e<=0)throw new xt("number");let n=t/e,s=Number.EPSILON*Math.max(1,Math.abs(n));return Math.abs(n-Math.round(n))<=s?D():Z(r,"multipleOf",`Expected number being a multiple of ${e}`,t)},Ey=({maximum:e=0},t,r={})=>!et(t)||t<=e?D():Z(r,"maximum",`Expected number less than or equal to ${e}`,t),_y=({exclusiveMaximum:e=0},t,r={})=>!et(t)||t<e?D():Z(r,"exclusiveMaximum",`Expected number less than ${e}`,t),xy=({minimum:e=0},t,r={})=>!et(t)||t>=e?D():Z(r,"minimum",`Expected number greater than or equal to ${e}`,t),vy=({exclusiveMinimum:e=0},t,r={})=>!et(t)||t>e?D():Z(r,"exclusiveMinimum",`Expected number greater than ${e}`,t),$y=({properties:e={}},t,r={})=>{if(!he(t))return D();for(let[n,s]of Object.entries(t)){let i=e[n];if(!Ae(i))continue;let o=i.validate(s,Yt(r,["properties",n],n));if(!o.valid)return o}return D()},Ty=({properties:e={},additionalProperties:t,patternProperties:r},n,s={})=>{if(!he(n))return D();if(!Ae(t))throw new xt("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(iy(t)){if(t.toJSON()===true)return D();let l=a.reduce((c,u)=>(c[u]=n[u],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],Yt(s,["additionalProperties"],l));if(!c.valid)return c}}return D()},Ay=({dependentRequired:e},t,r={})=>{if(!he(t))return D();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 D()},Cy=({required:e=[]},t,r={})=>{if(!he(t))return D();let n=Object.keys(t).filter(s=>typeof t[s]!="function");return e.every(s=>n.includes(s))?D():Z(r,"required",`Expected object with required properties ${e.join(", ")}`,t)},Ry=({dependentSchemas:e},t,r={})=>{if(!he(t))return D();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 D()},Py=({minProperties:e=0},t,r={})=>he(t)?Object.keys(t).length>=e?D():Z(r,"minProperties",`Expected object with at least ${e} properties`,t):D(),ky=({maxProperties:e=0},t,r={})=>!he(t)||Object.keys(t).length<=e?D():Z(r,"maxProperties",`Expected object with at most ${e} properties`,t),Ny=({patternProperties:e={}},t,r={})=>{if(!he(t))return D();if(!he(e))throw new xt("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,Yt(r,["patternProperties"],n));if(!a.valid)return a}return D()},Oy=({propertyNames:e},t,r={})=>{if(!he(t)||e===void 0)return D();if(!Ae(e))throw new xt("propertyNames must be a managed schema");for(let n of Object.keys(t)){let s=e.validate(n,Yt(r,["propertyNames"],n));if(!s.valid)return s}return D()},Iy=({items:e,prefixItems:t=[]},r,n={})=>{if(!ut(r)||e===void 0)return D();if(!Ae(e))throw new xt("items must be a managed schema");for(let[s,i]of r.slice(t.length).entries()){let o=e.validate(i,Yt(n,["items"],String(s)));if(!o.valid)return o}return D()},Ly=({minItems:e=0},t,r={})=>!ut(t)||t.length>=e?D():Z(r,"minItems",`Expected array with at least ${e} items`,t),Dy=({maxItems:e=0},t,r={})=>!ut(t)||t.length<=e?D():Z(r,"maxItems",`Expected array with at most ${e} items`,t),jy=({uniqueItems:e=false},t,r={})=>{if(!ut(t)||!e)return D();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(Tr(s,o))return Z(r,"uniqueItems",`Duplicated items at index ${n} and ${i}`,t)}}return D()},Fy=({contains:e,minContains:t,maxContains:r},n,s={})=>{if(!Ae(e))throw new Error("contains must be a managed schema");if(!ut(n))return D();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):D()},My=({prefixItems:e=[]},t,r={})=>{if(!ut(t))return D();for(let n=0;n<t.length;n++){let s=e[n]?.validate(t[n],Yt(r,String(n),String(n)));if(s&&s?.valid!==true)return s}return D()},Wc={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 u=e.charCodeAt(c);if(c===1&&o===58&&u!==58)return false;if(u>=48&&u<=57){if(++n>4)return false}else if(u===46){if(t>6||r>=3||n===0||i)return false;r++,n=0;}else if(u===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(u>=97&&u<=102||u>=65&&u<=70){if(r>0||++n>4)return false;i=true;}else return false;o=u;}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},Uy=({format:e},t,r={})=>!Ke(t)||!e?D():Wc[e]?Wc[e](t)?D():Z(r,"format",`Expected format: ${e}`,t):D(),io={type:cy,const:uy,enum:py,allOf:dy,anyOf:fy,oneOf:my,not:hy,minLength:wy,maxLength:by,pattern:yy,format:Uy,minimum:xy,exclusiveMinimum:vy,maximum:Ey,exclusiveMaximum:_y,multipleOf:Sy,required:Cy,dependentRequired:Ay,dependentSchemas:Ry,minProperties:Py,maxProperties:ky,propertyNames:Oy,properties:$y,patternProperties:Ny,additionalProperties:Ty,minItems:Ly,maxItems:Dy,uniqueItems:jy,contains:Fy,prefixItems:My,items:Iy,if:gy};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:Vc(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 By(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 ly(this,s,r)}optional(){return this[Te].optional=true,this}isOptional(){return this[Te].optional}getResolver(){return this._resolver||(this._resolver=new po(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?Yc(r):r;if(s.includeSelf!==false&&(yield new Ar(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))}},Ar=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=ts(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}};qy=class extends tt{constructor(e){super(),this.bool=e;}toJSON(){return this.bool}validate(e,t){return this.bool?D():Z(t,"","Always fails",e)}};Jc=e=>ns(e?.type,e),Hy=(e,t)=>ns(void 0,{...t,const:e}),Wy=class extends tt{type="object";properties;required;constructor(e,t){let r=[];for(let[s,i]of Object.entries(e||{}))oy(Ae(i),"properties must be managed schemas",i),i[Te].optional||r.push(s);let n=t?.additionalProperties===false?lo(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 u=ts(o,l);if(c.isOptional()&&i?.withOptional!==true&&u===void 0&&s===void 0)continue;let p=c.template(u,i);p!==void 0&&(a[l]=p);}if(!(Object.keys(a).length===0&&!i?.withExtendedOptional))return a},coerce:(s,i)=>{let o=Object.keys(this.properties),a=Yc(s),l=o.length>0&&Object.values(this.properties).every(u=>!u[Te].optional);if(ty(a)&&(i?.dropUnknown===true||l)&&(a=ay(a,o)),typeof a=="string"&&a.match(/^\{/)&&(a=JSON.parse(a)),typeof a!="object"||a===null)return;if(this.properties)for(let[u,p]of Object.entries(this.properties)){let f=a[u];f!==void 0&&(a[u]=p.coerce(f,i));}let c=this.additionalProperties;if(i?.dropUnknown!==true&&(!c||c.validate(null).valid)){let u=he(s)?s:{},p=Object.keys(u).filter(f=>!o.includes(f));for(let f of p)a[f]=c?c.coerce(u[f],i):u[f];}return a}}),this.properties=e,this.required=r;}strict(){return this.additionalProperties=lo(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 Ar(n,e);s.appendInstancePath([r]),s.appendKeywordPath(["properties",r]),t.push(s);}return t}},ss=(e,t)=>new Wy(e,t),zy=(e,t)=>ss(e,t).strict(),Gy=(e,t)=>ss(e,t).partial(),Vy=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 Ar(this.additionalProperties,e);return r.appendKeywordPath(["additionalProperties"]),t.push(r),t}},Ky=(e,t)=>new Vy(e,t),Yy=class extends tt{type="string";constructor(e){super(e,{template:(t,r)=>r?.withExtendedOptional&&(t===void 0||!Ke(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 Yy(e),Qc=(e,t,r)=>ns(e,r,{template:(n,s)=>s?.withExtendedOptional&&(n===void 0||!et(n))?r?.minimum??0:n,coerce:n=>{if(Ke(n)){let s=t.parseFn(n);if(!Number.isNaN(s))return s}return n}}),Zc=e=>Qc("number",{parseFn:Number},e),eu=e=>Qc("integer",{parseFn:Number.parseInt},e),Jy=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 Ar(this.items,e);r.appendKeywordPath(["items"]),t.push(r);}return t}},tu=(e,t)=>new Jy(e,t),ru=e=>ns("boolean",e,{template:(t,r)=>r?.withExtendedOptional&&(t===void 0||!uo(t))?false:t,coerce:t=>{if(Ke(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}}),Zn=Symbol.for("unionType"),nu=class extends tt{[Zn];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=rs(e,n,{ignoreUnsupported:true,resolver:s?.resolver,coerce:true});return o.length>0?o[0].coerce(n,s):n}}),this[Zn]=t;}get schemas(){return this[this[Zn]]}children(e){let t=[];for(let[r,n]of this.schemas.entries()){let s=new Ar(n,e);s.appendKeywordPath([this[Zn],r]),t.push(s);}return t}},Xy=(e,t)=>new nu(e,"anyOf",t),Qy=(e,t)=>new nu(e,"oneOf",t);co=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),oo=e=>typeof globalThis.structuredClone=="function"?globalThis.structuredClone(e):JSON.parse(JSON.stringify(e)),Zy=["maximum","exclusiveMaximum","maxLength","maxItems","maxProperties"],ew=["minimum","exclusiveMinimum","minLength","minItems","minProperties"];nw=e=>e===true||e===false?e:null;iw=(e,t)=>{let r=JSON.parse(JSON.stringify({...t,allOf:e}));return Kt(sw(r))},su=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;}},ow=(e,t)=>new su(e,t),aw=e=>new su(void 0,e),lw=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)}})),iu={boolean:ru,any:Jc,literal:Hy,object:ss,strictObject:zy,partialObject:Gy,record:Ky,string:Xc,number:Zc,integer:eu,array:tu,anyOf:Xy,oneOf:Qy,allOf:iw,ref:ow,refId:aw,recursive:lw};});function au(e,t){if(typeof e!="string"){throw new Error("Email must be a string");}if(!iu.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 lu(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 M(e,t='"'){return `${t}${e}${t}`}function cu(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 Cr=y(()=>{ou();});function fo(e){return typeof e=="number"?e:Number.parseInt(String(e),10)}var uu=y(()=>{});var pu=y(()=>{});var pt=y(()=>{Fc();Mc();Uc();Bc();qc();$r();Cr();uu();pu();});var mo,fu=y(()=>{mo=(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,u;if(e[a]?(u=e[a][0][0],n.req.routeIndex=a):u=a===e.length&&s||void 0,u)try{l=await u(n,()=>o(a+1));}catch(p){if(p instanceof Error&&t)n.error=p,l=await t(p,n),c=true;else throw p}else n.finalized===false&&r&&(l=await r(n));return l&&(n.finalized===false||c)&&(n.res=l),n}};});var mu=y(()=>{});var du,hu=y(()=>{du=Symbol();});async function cw(e,t){let r=await e.formData();return r?uw(r,t):{}}function uw(e,t){let r=Object.create(null);return e.forEach((n,s)=>{t.all||s.endsWith("[]")?pw(r,s,n):r[s]=n;}),t.dot&&Object.entries(r).forEach(([n,s])=>{n.includes(".")&&(fw(r,n,s),delete r[n]);}),r}var gu,pw,fw,yu=y(()=>{ho();gu=async(e,t=Object.create(null))=>{let{all:r=false,dot:n=false}=t,i=(e instanceof is?e.raw.headers:e.headers).get("Content-Type");return i?.startsWith("multipart/form-data")||i?.startsWith("application/x-www-form-urlencoded")?cw(e,{all:r,dot:n}):{}};pw=(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;},fw=(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 yo,wu,mw,dw,os,bu,as,hw,wo,Su,vt,ls,go,Eu,_u,xu,bo,Jt=y(()=>{yo=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},wu=e=>{let{groups:t,path:r}=mw(e),n=yo(r);return dw(n,t)},mw=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let s=`@${n}`;return t.push([s,r]),s}),{groups:t,path:e}},dw=(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},os={},bu=(e,t)=>{if(e==="*")return "*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${e}#${t}`;return os[n]||(r[2]?os[n]=t&&t[0]!==":"&&t[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)]:os[n]=[e,r[1],true]),os[n]}return null},as=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return t(r)}catch{return r}})}},hw=e=>as(e,decodeURI),wo=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 hw(l.includes("%25")?l.replace(/%25/g,"%2525"):l)}else if(s===63||s===35)break}return t.slice(r,n)},Su=e=>{let t=wo(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},vt=(e,t,...r)=>(r.length&&(t=vt(t,...r)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),ls=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)},go=e=>/[%+]/.test(e)?(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),e.indexOf("%")!==-1?as(e,bo):e):e,Eu=(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 go(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=go(l)),i=o,l==="")continue;let c;a===-1?c="":(c=e.slice(a+1,o===-1?void 0:o),n&&(c=go(c))),r?(s[l]&&Array.isArray(s[l])||(s[l]=[]),s[l].push(c)):s[l]??=c;}return t?s[t]:s},_u=Eu,xu=(e,t)=>Eu(e,t,true),bo=decodeURIComponent;});var vu,is,ho=y(()=>{mu();hu();yu();Jt();vu=e=>as(e,bo),is=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)?vu(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)?vu(n):n);}return e}#s(e){return this.#t[1]?this.#t[1][e]:e}query(e){return _u(this.url,e)}queries(e){return xu(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 gu(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[du](){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,Tu,So,Eo=y(()=>{$u={Stringify:1,BeforeStream:2,Stream:3},Tu=(e,t)=>{let r=new String(e);return r.isEscaped=true,r.callbacks=t,r},So=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=>So(l,t,false,n,s))).then(()=>s[0]));return r?Tu(await o,i):o};});var gw,_o,Rr,Au,Cu=y(()=>{ho();Eo();gw="text/plain; charset=UTF-8",_o=(e,t)=>({"Content-Type":e,...t}),Rr=(e,t)=>new Response(e,t),Au=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 is(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||=Rr(null,{headers:this.#a??=new Headers})}set res(e){if(this.#n&&e){e=Rr(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=Rr(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 Rr(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,_o(gw,r));json=(e,t,r)=>this.#o(JSON.stringify(e),t,_o("application/json",r));html=(e,t,r)=>{let n=s=>this.#o(s,t,_o("text/html; charset=UTF-8",r));return typeof e=="object"?So(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??=()=>Rr(),this.#c(this))};});var re,Ru,Pu,cs,us,ft=y(()=>{re="ALL",Ru="all",Pu=["get","post","put","delete","options","patch"],cs="Can not add a route since the matcher is already built.",us=class extends Error{};});var Pr,xo=y(()=>{Pr="__COMPOSED_HANDLER";});var yw,ku,Nu,Iu=y(()=>{fu();Cu();ft();xo();Jt();yw=e=>e.text("404 Not Found",404),ku=(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)},Nu=class Ou{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(t={}){[...Pu,Ru].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(u=>{this.#i(c.toUpperCase(),this.#e,u);});}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??wo:Su;}#t(){let t=new Ou({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=yw;errorHandler=ku;route(t,r){let n=this.basePath(t);return r.routes.map(s=>{let i;r.errorHandler===ku?i=s.handler:(i=async(o,a)=>(await mo([],r.errorHandler)(o,()=>s.handler(o,a))).res,i[Pr]=s.handler),n.#i(s.method,s.path,i);}),this}basePath(t){let r=this.#t();return r._basePath=vt(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=vt(this._basePath,t),c=l==="/"?0:l.length;return u=>{let p=new URL(u.url);return p.pathname=p.pathname.slice(c)||"/",new Request(p,u)}})();let a=async(l,c)=>{let u=await r(s(l.req.raw),...o(l));if(u)return u;await c();};return this.#i(re,vt(t,"*"),a),this}#i(t,r,n){t=t.toUpperCase(),r=vt(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 Au(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(u){return this.#s(u,a)}return c instanceof Promise?c.then(u=>u||(a.finalized?a.res:this.#r(a))).catch(u=>this.#s(u,a)):c??this.#r(a)}let l=mo(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${vt("/",t)}`,r),n,s));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method));});}};});function vo(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 [[],ps];let c=l.indexOf("",1);return [o[1][c],l]});return this.match=n,n(e,t)}var ps,$o=y(()=>{ft();ps=[];});function bw(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===kr||e===Nr?1:t===kr||t===Nr?-1:e===fs?1:t===fs?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var fs,kr,Nr,$t,ww,Lu,Ao=y(()=>{fs="[^/]+",kr=".*",Nr="(?:|/.*)",$t=Symbol(),ww=new Set(".\\+*[^]$()");Lu=class To{#e;#t;#r=Object.create(null);insert(t,r,n,s,i){if(t.length===0){if(this.#e!==void 0)throw $t;if(i)return;this.#e=r;return}let[o,...a]=t,l=o==="*"?a.length===0?["","",kr]:["","",fs]:o==="/*"?["","",Nr]:o.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(l){let u=l[1],p=l[2]||fs;if(u&&l[2]&&(p===".*"||(p=p.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(p))))throw $t;if(c=this.#r[p],!c){if(Object.keys(this.#r).some(f=>f!==kr&&f!==Nr))throw $t;if(i)return;c=this.#r[p]=new To,u!==""&&(c.#t=s.varIndex++);}!i&&u!==""&&n.push([u,c.#t]);}else if(c=this.#r[o],!c){if(Object.keys(this.#r).some(u=>u.length>1&&u!==kr&&u!==Nr))throw $t;if(i)return;c=this.#r[o]=new To;}c.insert(a,r,n,s,i);}buildRegExpStr(){let r=Object.keys(this.#r).sort(bw).map(n=>{let s=this.#r[n];return (typeof s.#t=="number"?`(${n})@${s.#t}`:ww.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 Du,ju=y(()=>{Ao();Du=class{#e={varIndex:0};#t=new Lu;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 Mu(e){return Fu[e]??=new RegExp(e==="*"?"":`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(t,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function Ew(){Fu=Object.create(null);}function _w(e){let t=new Du,r=[];if(e.length===0)return Sw;let n=e.map(c=>[!/\*|\/:/.test(c[0]),...c]).sort(([c,u],[p,f])=>c?1:p?-1:u.length-f.length),s=Object.create(null);for(let c=0,u=-1,p=n.length;c<p;c++){let[f,h,d]=n[c];f?s[h]=[d.map(([b])=>[b,Object.create(null)]),ps]:u++;let m;try{m=t.insert(h,u,f);}catch(b){throw b===$t?new us(h):b}f||(r[u]=d.map(([b,g])=>{let S=Object.create(null);for(g-=1;g>=0;g--){let[A,v]=m[g];S[A]=v;}return [b,S]}));}let[i,o,a]=t.buildRegExp();for(let c=0,u=r.length;c<u;c++)for(let p=0,f=r[c].length;p<f;p++){let h=r[c][p]?.[1];if(!h)continue;let d=Object.keys(h);for(let m=0,b=d.length;m<b;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 Xt(e,t){if(e){for(let r of Object.keys(e).sort((n,s)=>s.length-n.length))if(Mu(r).test(t))return [...e[r]]}}var Sw,Fu,ms,Co=y(()=>{ft();Jt();$o();Ao();ju();Sw=[/^$/,[],Object.create(null)],Fu=Object.create(null);ms=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(cs);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=Mu(t);e===re?Object.keys(n).forEach(l=>{n[l][t]||=Xt(n[l],t)||Xt(n[re],t)||[];}):n[e][t]||=Xt(n[e],t)||Xt(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=ls(t)||[t];for(let a=0,l=o.length;a<l;a++){let c=o[a];Object.keys(s).forEach(u=>{(e===re||e===u)&&(s[u][c]||=[...Xt(n[u],c)||Xt(n[re],c)||[]],s[u][c].push([r,i-l+a+1]));});}}match=vo;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,Ew(),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 Uu=y(()=>{ft();$o();Co();});var Bu=y(()=>{Co();Uu();});var Ro,qu=y(()=>{ft();Ro=class{name="SmartRouter";#e=[];#t=[];constructor(e){this.#e=e.routers;}add(e,t,r){if(!this.#t)throw new Error(cs);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 us)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 Hu=y(()=>{qu();});var Or,xw,Wu,Gu=y(()=>{ft();Jt();Or=Object.create(null),xw=e=>{for(let t in e)return true;return false},Wu=class zu{#e;#t;#r;#i=0;#s=Or;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=wu(r),o=[];for(let a=0,l=i.length;a<l;a++){let c=i[a],u=i[a+1],p=bu(c,u),f=Array.isArray(p)?p[0]:c;if(f in s.#t){s=s.#t[f],p&&o.push(p[1]);continue}s.#t[f]=new zu,p&&(s.#r.push(p),o.push(p[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],u={};if(c!==void 0&&(c.params=Object.create(null),t.push(c),s!==Or||i&&i!==Or))for(let p=0,f=c.possibleKeys.length;p<f;p++){let h=c.possibleKeys[p],d=u[c.score];c.params[h]=i?.[h]&&!d?i[h]:s[h]??i?.[h],u[c.score]=true;}}}search(t,r){let n=[];this.#s=Or;let i=[this],o=yo(r),a=[],l=o.length,c=null;for(let u=0;u<l;u++){let p=o[u],f=u===l-1,h=[];for(let m=0,b=i.length;m<b;m++){let g=i[m],S=g.#t[p];S&&(S.#s=g.#s,f?(S.#t["*"]&&this.#n(n,S.#t["*"],t,g.#s),this.#n(n,S,t,g.#s)):h.push(S));for(let A=0,v=g.#r.length;A<v;A++){let k=g.#r[A],N=g.#s===Or?{}:{...g.#s};if(k==="*"){let L=g.#t["*"];L&&(this.#n(n,L,t,g.#s),L.#s=N,h.push(L));continue}let[$,x,I]=k;if(!p&&!(I instanceof RegExp))continue;let w=g.#t[$];if(I instanceof RegExp){if(c===null){c=new Array(l);let q=r[0]==="/"?1:0;for(let E=0;E<l;E++)c[E]=q,q+=o[E].length+1;}let L=r.substring(c[u]),T=I.exec(L);if(T){if(N[x]=T[0],this.#n(n,w,t,g.#s,N),xw(w.#t)){w.#s=N;let q=T[0].match(/\//)?.length??0;(a[q]||=[]).push(w);}continue}}(I===true||I.test(p))&&(N[x]=p,f?(this.#n(n,w,t,N,g.#s),w.#t["*"]&&this.#n(n,w.#t["*"],t,N,g.#s)):(w.#s=N,h.push(w)));}}let d=a.shift();i=d?h.concat(d):h;}return n.length>1&&n.sort((u,p)=>u.score-p.score),[n.map(({handler:u,params:p})=>[u,p])]}};});var Po,Vu=y(()=>{Jt();Gu();Po=class{name="TrieRouter";#e;constructor(){this.#e=new Wu;}add(e,t,r){let n=ls(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 Ku=y(()=>{Vu();});var ko,Yu=y(()=>{Iu();Bu();Hu();Ku();ko=class extends Nu{constructor(e={}){super(e),this.router=e.router??new Ro({routers:[new ms,new Po]});}};});var Ju=y(()=>{Yu();});function No(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 Oo(e){console.error(),console.error(Ir.default.red(`Cannot start server: Port ${Ir.default.bold(String(e))} is already in use.`)),console.error(Ir.default.red(`Stop the process using that port, or set a different ${Ir.default.bold("api.port")} in your config.`)),console.error(),process.exit(1);}var Ir,Qu=y(()=>{Ir=te(ie());});var Zu,ep=y(()=>{Zu=/^\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 Lo,tp,vw,Io,Do=y(()=>{Lo=(e,t=Io)=>{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},tp=e=>{for(let t in Io)if(Io[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"},Io=vw;});var rp,np=y(()=>{rp=(...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 sp,$w,Tw,ip,op=y(()=>{ep();Do();np();sp={br:".br",zstd:".zst",gzip:".gz"},$w=Object.keys(sp),Tw="index.html",ip=e=>{let t=e.root??"./",r=e.path,n=e.join??rp;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,Tw));let l=e.getContent,c=await l(a,s);if(c instanceof Response)return s.newResponse(c.body,c);if(c){let u=e.mimes&&Lo(a,e.mimes)||Lo(a);if(s.header("Content-Type",u||"application/octet-stream"),e.precompressed&&(!u||Zu.test(u))){let p=new Set(s.req.header("Accept-Encoding")?.split(",").map(f=>f.trim()));for(let f of $w){if(!p.has(f))continue;let h=await l(a+sp[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 ap,lp=y(()=>{op();ap=e=>async function(r,n){return ip({...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(o)).isDirectory();}catch{}return a}})(r,n)};});var cp=y(()=>{});var up,pp=y(()=>{cp();up=(e,t)=>{for(let[r,n]of Object.entries(t)){let s=new RegExp("/:"+r+"(?:{[^/]+})?\\??");e=e.replace(s,n?`/${n}`:"");}return e};});var Rw,fp,mp=y(()=>{Rw=1024,fp=({concurrency:e,interval:t}={})=>{if(e||=Rw,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 dp,jo,hp=y(()=>{xo();dp=e=>e.length>1,jo=e=>e[Pr]?jo(e[Pr]):e;});var gp,Pw,kw,Nw,Ow,Lr,yp,Fo,Mo=y(()=>{ft();hp();gp=e=>e.split(/[\/\\]/).slice(0,-1).join("/"),Pw=e=>e.replace(/(\\)/g,"/").replace(/\/$/g,""),kw=(e,t)=>{e.length===0||t?e.push(".."):e.pop();},Nw=(e,t)=>{e=e.replace(/^\.(?!.)/,""),e!==""&&t.push(e);},Ow=(e,t)=>{let r=false;for(let n of e)n===".."?(kw(t,r),r=true):(Nw(n,t),r=false);},Lr=(...e)=>{e=e.map(Pw);let t=[];return Ow(e.join("/").split("/"),t),(e[0][0]==="/"?"/":"")+t.join("/")},yp=e=>e.routes.reduce((t,{method:r,handler:n,path:s})=>{let i=jo(n);return ["GET",re].includes(r)&&!dp(i)&&t.push({path:s}),t},[]),Fo=e=>e.split("/").some(t=>t.startsWith(":")||t.includes("*"));});var wp,ds,Uo=y(()=>{Mo();wp="HONO_SSG_CONTEXT",ds="x-hono-disable-ssg",(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[ds]:"true"}})}catch{return null}})();});var bp=y(()=>{Eo();});var Bo,qo=y(()=>{bp();Bo=()=>({afterResponseHook:e=>e.status!==200?false:e});});var Iw,Lw,Dw,jw,Fw,Mw,Uw,Bw,qw,Hw,Ww,Sp,zw,Ep,_p=y(()=>{pp();mp();Do();Uo();qo();Mo();Iw=2,Lw="text/plain",Dw="./static",jw=(e,t,r,n)=>{let s=Uw(r,n);return e.endsWith(`.${s}`)?Lr(t,e):e==="/"?Lr(t,`index.${s}`):e.endsWith("/")?Lr(t,e,`index.${s}`):Lr(t,`${e}.${s}`)},Fw=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"}`)}},Mw={"text/html":"html","text/xml":"xml","application/xml":"xml","application/yaml":"yaml"},Uw=(e,t)=>{let r=t||Mw;return e in r?r[e]:tp(e)||"html"},Bw=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,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 Response&&(r=s);}return r}:e,Hw=(e,t,r)=>Array.isArray(e)?async n=>{for(let s of e)await s(n,t,r);}:e,Ww=function*(e,t,r,n){let s="http://localhost",i=fp({concurrency:n});for(let o of yp(e)){let a=new URL(o.path,s).toString(),l=new Request(a);yield new Promise(async(c,u)=>{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(Fo(o.path)){c(void 0);return}l.ssgParams=[{}];}let p={method:l.method,headers:l.headers};c((function*(){for(let f of l.ssgParams)yield new Promise(async(h,d)=>{try{let m=up(o.path,f),b=await i.run(()=>e.request(m,p,{[wp]:!0}));if(b.headers.get(ds)){h(void 0);return}if(r){let A=await r(b);if(!A){h(void 0);return}b=A;}let g=b.headers.get("Content-Type")?.split(";")[0]||Lw,S=await Fw(b);h({routePath:m,mimeType:g,content:S});}catch(m){d(m);}});})());}catch(p){u(p);}});}},Sp=new Set,zw=async(e,t,r,n)=>{let s=await e;if(!s)return;let{routePath:i,content:o,mimeType:a}=s,l=jw(i,r,a,n),c=gp(l);return Sp.has(c)||(await t.mkdir(c,{recursive:true}),Sp.add(c)),typeof o=="string"?await t.writeFile(l,o):o instanceof ArrayBuffer&&await t.writeFile(l,new Uint8Array(o)),l},Ep=async(e,t,r)=>{let n,s=[],i=[],o=r?.plugins||[Bo()],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 u of o)u.beforeRequestHook&&a.push(...Array.isArray(u.beforeRequestHook)?u.beforeRequestHook:[u.beforeRequestHook]),u.afterResponseHook&&l.push(...Array.isArray(u.afterResponseHook)?u.afterResponseHook:[u.afterResponseHook]),u.afterGenerateHook&&c.push(...Array.isArray(u.afterGenerateHook)?u.afterGenerateHook:[u.afterGenerateHook]);try{let u=r?.dir??Dw,p=r?.concurrency??Iw,f=Bw(a.length>0?a:[b=>b]),h=qw(l.length>0?l:[b=>b]),d=Ww(e,f,h,p);for(let b of d)s.push(b.then(g=>{if(g)for(let S of g)i.push(zw(S,t,u,r?.extensionMap).catch(A=>A));}));await Promise.all(s);let m=[];for(let b of i){let g=await b;if(typeof g=="string")m.push(g);else if(g)throw g}n={success:!0,files:m};}catch(u){let p=u instanceof Error?u:new Error(String(u));n={success:false,files:[],error:p};}return c.length>0&&await Hw(c,t,r)(n,t,r),n};});var xp=y(()=>{_p();Uo();qo();});var Gw,Ho,vp,$p=y(()=>{xp();(({write:Gw}=Bun)),Ho={writeFile:async(e,t)=>{await Gw(e,t);},mkdir:async()=>{}},vp=async(e,t)=>Ep(e,Ho,t);});var Tp,Ap,Cp,Rp=y(()=>{Tp=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);}},Ap=e=>new MessageEvent("message",{data:e}),Cp=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 Qt,hs=y(()=>{Qt=e=>"server"in e.env?e.env.server:e.env;});var Wo,zo,Go,Pp,kp=y(()=>{Rp();hs();Wo=e=>new Tp({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);}}),zo=Cp((e,t)=>{let r=Qt(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)}),Go={open(e){let t=e.data.events;t.onOpen&&t.onOpen(new Event("open"),Wo(e));},close(e,t,r){let n=e.data.events;n.onClose&&n.onClose(new CloseEvent("close",{code:t,reason:r}),Wo(e));},message(e,t){let r=e.data.events;if(r.onMessage){let n=typeof t=="string"?t:t.buffer;r.onMessage(Ap(n),Wo(e));}}},Pp=()=>({upgradeWebSocket:zo,websocket:Go});});var Np,Op=y(()=>{hs();Np=e=>{let t=Qt(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 Ip={};de(Ip,{bunFileSystemModule:()=>Ho,createBunWebSocket:()=>Pp,getBunServer:()=>Qt,getConnInfo:()=>Np,serveStatic:()=>ap,toSSG:()=>vp,upgradeWebSocket:()=>zo,websocket:()=>Go});var Lp=y(()=>{lp();$p();kp();Op();hs();});async function gs(e,t={port:3e3}){let r=Kn(),n=t.port??3e3;if(vr()){let s=await Promise.resolve().then(()=>(Lp(),Ip)).then(o=>o.serveStatic),i;try{i=Bun.serve({fetch:jp(e,r,s).fetch,port:n});}catch(o){throw No(o)&&Oo(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:jp(e,r,i).fetch});try{await Xu(o,n);}catch(a){throw No(a)&&Oo(n),a}return ()=>new Promise(a=>{o.close(()=>{a(void 0);});})}}function jp(e,t,r){return new ko().use("/favicon.ico",r({path:z__default.join(t,"static","favicon.ico")})).use("/fonts/*",r({root:z__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 Vo=y(()=>{pt();Ju();Qu();Ee();});var nt,Ko=y(()=>{St();nt=class e{root;constructor(t,r){let n=r??e.projectDir();this.root=z__default.join(n,t??"");}ensureRoot(){Pe(this.root);}static homeDir(){return z__default.join(Vw.homedir(),".lite")}static projectDir(){return z__default.join(process.cwd(),"supabase")}deleteAll(t=false){try{Mn.rmSync(this.root,{recursive:!0});}catch(r){if(!t)throw r}this.ensureRoot();}delete(t,r=false){try{Mn.unlinkSync(z__default.join(this.root,t));}catch(n){if(!r)throw n}}write(t,r,n=false){try{this.ensureRoot(),Mn.writeFileSync(z__default.join(this.root,t),r);}catch(s){if(!n)throw s}}read(t,r=false){try{return Mn.readFileSync(z__default.join(this.root,t),"utf8")}catch(n){if(!r)throw n}}relativePath(t){return t?z__default.relative(process.cwd(),z__default.join(this.root,t)):this.root}path(t){return t?z__default.join(this.root,t):this.root}};});var Dr,Yo=y(()=>{Dr=process.env.SUPALITE_CLOUD_URL??(process.env.LOCAL?"http://localhost:2000":"https://www.lite.dev");});var bs,Fp=y(()=>{St();bs=class{root;constructor(t){this.root=t??z__default.join(Vw.homedir(),".lite","auth"),Pe(this.root);}async getItem(t){try{return Mn.readFileSync(z__default.join(this.root,t+".json"),"utf8")}catch{return null}}async setItem(t,r){Mn.writeFileSync(z__default.join(this.root,t+".json"),r);}async removeItem(t){try{Mn.unlinkSync(z__default.join(this.root,t+".json"));}catch{return}}};});var Zt,Xo=y(()=>{Yo();Ko();Fp();Zt=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 bs(z__default.join(nt.homeDir(),"auth")),this._client=this.config.withSupabaseClient!==false?this.config.client??createClient(this.config.host??Dr,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??Dr);return await fetch(n,{...r,headers:{...r?.headers,Authorization:`Bearer ${this.config.token}`}})}};});var er,Qo=y(()=>{Xo();er=class extends Zt{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 Xw(e){let t=z.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 Es,Mp=y(()=>{pt();Es=class{driver=fe;basePath;constructor(t){this.basePath=z.resolve(t.basePath);}filePath(t,r){return z.join(this.basePath,t,r)}async ensureDir(t){await fe.mkdir(z.dirname(t),{recursive:true});}async getObject(t,r,n,s){let i=this.filePath(t,r),o=await fe.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,u=o.size,p=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;u=d-h+1,c=`bytes ${h}-${d}/${o.size}`,p=206,l=(await fe.open(i,"r")).readableWebStream();}else l=(await fe.open(i,"r")).readableWebStream();}else l=(await fe.open(i,"r")).readableWebStream();return {httpStatusCode:p,metadata:{...this.buildMetadata(o,a,r),contentLength:u,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 p=[],f=s.getReader();for(;;){let{done:h,value:d}=await f.read();if(h)break;p.push(d);}l=Buffer.concat(p);}await fe.writeFile(a,l);let c=await fe.stat(a),u=`"${createHash("md5").update(l).digest("hex")}"`;return {cacheControl:o,contentLength:c.size,size:c.size,mimetype:i,lastModified:c.mtime,eTag:u}}async deleteObject(t,r,n){let s=this.filePath(t,r);await fe.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 fe.copyFile(o,a);let l=await fe.stat(a),c=await fe.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 fe.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:fo(t.size),size:fo(t.size),mimetype:Xw(n),lastModified:t.mtime,eTag:r}}};});async function Ye(e,t,r){try{return await Qw(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 Qw,jr=y(()=>{Qw=new Function("spec","return import(spec)");});function Up(e,t={}){let r=z__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=tb(z__default.resolve(e),r);for(let a of o)for(let l of i){let c=z__default.join(a,l),u;try{u=Mn.readFileSync(c,"utf-8");}catch{continue}let p;try{p=parse(u);}catch(f){throw new Error(`Failed to parse ${c}: ${f.message}`)}for(let[f,h]of Object.entries(p))n[f]===void 0&&(n[f]=h);}}function tb(e,t){let r=[],n=e,s=z__default.parse(n).root;for(;r.push(n),!(n===t||n===s);){let i=z__default.dirname(n);if(i===n)break;n=i;}return r}var Bp=y(()=>{});function qp(e,t=process.env){return Zo(e,t)}function Zo(e,t){if(typeof e=="string"){let r=e.match(rb);return r?t[r[1]]??"":e}if(Array.isArray(e))return e.map(r=>Zo(r,t));if(e&&typeof e=="object"){let r={};for(let[n,s]of Object.entries(e))r[n]=Zo(s,t);return r}return e}var rb,Hp=y(()=>{rb=/^env\((\w+)\)$/;});var Mr,sb,_s,zp=y(()=>{Qo();Vt();Mr=te(ie());_r();zt();Mp();jr();Bp();Hp();sb=["toml","json","ts","mts","js","mjs","cjs"],_s=class extends er{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=z__default.relative(process.cwd(),$e.config_dir);if(!t)for(let n of sb){let s=z__default.join(r,`config.${n}`);if(await fe__default.access(s).then(()=>true).catch(()=>false)){t=s;break}}return t}async readConfig(t){let r=await this.getConfigPath(t);if(!r)return {};console.log(Mr.default.dim(`Using config file: ${Mr.default.cyan(`./${r}`)}`));let n=z__default.dirname(z__default.resolve(r));Up(n);let s=r.split(".").pop(),i;switch(s){case "toml":i=_t(await fe__default.readFile(r,"utf-8"));break;case "json":i=JSON.parse(await fe__default.readFile(r,"utf-8"));break;case "ts":case "mts":case "js":case "mjs":case "cjs":try{i=(await import(z__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 qp(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??$e.default_db_url,n=await createConnection({url:s,ddlDialect:"sqlite"});break;case "pglite":{s=r.db?.url??z__default.join(process.cwd(),$e.default_db_dir);let{createPgliteConnection:i}=await Ye("@supabase/lite/pglite","pglite","@electric-sql/pglite");n=await i({url:s});break}case "postgres":{s=r.db?.url??"";let{createPostgresConnection:i}=await Ye("@supabase/lite/postgres","postgres","postgres");n=await i({url:s});break}default:s=r.db?.url??$e.default_db_url,n=await createConnection({url:s,ddlDialect:"postgres"});break}if(!n)throw new Error("Failed to create connection");return console.log(Mr.default.green(" \u279C"),"Database located at",Mr.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 Es({basePath:z__default.join(process.cwd(),$e.config_dir,".temp/storage")})),await n.init()}};});var xs,Gp=y(()=>{Qo();xs=class extends er{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 vs,Vp=y(()=>{Xo();zp();Gp();vs=class extends Zt{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 _s(t),remote:new xs(t)},this}};});async function K(e={}){return await new vs({host:Dr,root:nt.projectDir(),...e}).init()}var Ce=y(()=>{Ko();Yo();Vp();});var Kp={};de(Kp,{start:()=>ab});var Ur,ab,Yp=y(()=>{Vo();pt();Ur=te(ie());Vt();Ce();Ee();zt();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 Xn(async()=>{let n=await(await K({withSupabaseClient:false})).project.local.createApp(t.config),s=n.config.api?.port??$e.default_api_port;await gs(n,{port:s});console.log(Ur.default.green(" \u279C"),"Server running on ",Ur.default.cyan(`http://localhost:${s}`));let o=Fn();o&&console.log(Ur.default.yellow(` \u26A0 ${o}`)),await n.connection.ping();},r=>{console.log(),console.log(Ur.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 Zp(e,t){return e.replace(hb,t)}function yb(e){return e==="/"||gb.test(e)}function ta(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 Zp(o?e+s:e,s)}function ef(e,t){return t+e}function wb(e,t){return function(r,n){return n.startsWith(e)?n.slice(e.length)+r:Zp(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?ef:bb}function _b(e){return function(t,r){r.push(t.substring(e.length)||".");}}function xb(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?xb(e):_b(e):n&&n.length?$b:vb:Tb}function Ob(e){let{excludeFiles:t,filters:r,onlyCounts:n}=e;return t?Nb:r&&r.length?n?Cb:Rb:n?Pb:kb}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 tf(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 $s(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?zb:Xb:s?t?Vb:Jb:t?Gb:Yb}function tS(e){return e?eS:Zb}function iS(e,t){return new Promise((r,n)=>{sf(e,t,(s,i)=>{if(s)return n(s);r(i);});})}function sf(e,t,r){new nf(e,t,r).start();}function oS(e,t){return new nf(e,t).start()}var Jp,hb,gb,vb,$b,Tb,Cb,Rb,Pb,kb,Nb,Ib,Lb,jb,Fb,Ub,Bb,Wb,zb,Gb,Vb,Kb,Yb,Jb,Xb,rf,Zb,eS,rS,nS,sS,nf,Xp,of,af,lf=y(()=>{Jp=createRequire(import.meta.url);hb=/[\\/]/g;gb=/^[a-z]:[\\/]$/i;vb=(e,t)=>{t.push(e||".");},$b=(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);},Pb=(e,t,r,n)=>{r.files++;},kb=(e,t)=>{t.push(e);},Nb=()=>{};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()&&tf(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()&&tf(e,o,t))return;r(a,o);}catch(o){if(!i)throw o}};Wb=e=>e.counts,zb=e=>e.groups,Gb=e=>e.paths,Vb=e=>e.paths.slice(0,e.options.maxFiles),Kb=(e,t,r)=>($s(t,r,e.counts,e.options.suppressErrors),null),Yb=(e,t,r)=>($s(t,r,e.paths,e.options.suppressErrors),null),Jb=(e,t,r)=>($s(t,r,e.paths.slice(0,e.options.maxFiles),e.options.suppressErrors),null),Xb=(e,t,r)=>($s(t,r,e.groups,e.options.suppressErrors),null);rf={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||".",rf,(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||".",rf);}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;}},nf=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=ta(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||rr},this.joinPath=Eb(this.root,t),this.pushDirectory=Ab(this.root,t),this.pushFile=Ob(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:u,pathSeparator:p},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 b=this.joinPath(m.name,t);this.pushFile(b,h,this.state.counts,s);}else if(m.isDirectory()){let b=Sb(m.name,t,this.state.options.pathSeparator);if(a&&a(m.name,b))continue;this.pushDirectory(b,n,s),this.walkDirectory(this.state,b,b,r-1,this.walk);}else if(this.resolveSymlink&&m.isSymbolicLink()){let b=ef(m.name,t);this.resolveSymlink(b,this.state,(g,S)=>{if(g.isDirectory()){if(S=ta(S,this.state.options),a&&a(m.name,u?S:b+p))return;this.walkDirectory(this.state,S,u?S:b+p,r-1,this.walk);}else {S=u?S:b;let A=basename(S),v=ta(dirname(S),this.state.options);S=this.joinPath(A,v),this.pushFile(S,h,this.state.counts,s);}});}}this.groupFiles(this.state.groups,t,h);}};Xp=class{constructor(e,t){this.root=e,this.options=t;}withPromise(){return iS(this.root,this.options)}withCallback(e){sf(this.root,this.options,e);}sync(){return oS(this.root,this.options)}},of=null;try{Jp.resolve("picomatch"),of=Jp("picomatch");}catch{}af=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 Xp(e||".",this.options)}withGlobFunction(e){return this.globFunction=e,this}crawlWithOptions(e,t){return this.options={...this.options,...t},new Xp(e||".",this.options)}glob(...e){return this.globFunction?this.globWithOptions(e):this.globWithOptions(e,{dot:true})}globWithOptions(e,...t){let r=this.globFunction||of;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 Br=ct((jR,mf)=>{var cf="[^\\\\/]",aS="(?=.)",uf="[^/]",na="(?:\\/|$)",pf="(?:^|\\/)",sa=`\\.{1,2}${na}`,lS="(?!\\.)",cS=`(?!${pf}${sa})`,uS=`(?!\\.{0,1}${na})`,pS=`(?!${sa})`,fS="[^.\\/]",mS=`${uf}*?`,dS="/",ff={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:aS,QMARK:uf,END_ANCHOR:na,DOTS_SLASH:sa,NO_DOT:lS,NO_DOTS:cS,NO_DOT_SLASH:uS,NO_DOTS_SLASH:pS,QMARK_NO_DOT:fS,STAR:mS,START_ANCHOR:pf,SEP:dS},hS={...ff,SLASH_LITERAL:"[\\\\/]",QMARK:cf,STAR:`${cf}*?`,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={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"};mf.exports={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:ff}};});var qr=ct(Ne=>{var{REGEX_BACKSLASH:yS,REGEX_REMOVE_BACKSLASH:wS,REGEX_SPECIAL_CHARS:bS,REGEX_SPECIAL_CHARS_GLOBAL:SS}=Br();Ne.isObject=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);Ne.hasRegexChars=e=>bS.test(e);Ne.isRegexChar=e=>e.length===1&&Ne.hasRegexChars(e);Ne.escapeRegex=e=>e.replace(SS,"\\$1");Ne.toPosixSlashes=e=>e.replace(yS,"/");Ne.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};Ne.removeBackslashes=e=>e.replace(wS,t=>t==="\\"?"":t);Ne.escapeLast=(e,t,r)=>{let n=e.lastIndexOf(t,r);return n===-1?e:e[n-1]==="\\"?Ne.escapeLast(e,t,n-1):`${e.slice(0,n)}\\${e.slice(n)}`};Ne.removePrefix=(e,t={})=>{let r=e;return r.startsWith("./")&&(r=r.slice(2),t.prefix="./"),r};Ne.wrapOutput=(e,t={},r={})=>{let n=r.contains?"":"^",s=r.contains?"":"$",i=`${n}(?:${e})${s}`;return t.negated===true&&(i=`(?:^(?!${i}).*$)`),i};Ne.basename=(e,{windows:t}={})=>{let r=e.split(t?/[\\/]/:"/"),n=r[r.length-1];return n===""?r[r.length-2]:n};});var Ef=ct((MR,Sf)=>{var df=qr(),{CHAR_ASTERISK:ia,CHAR_AT:ES,CHAR_BACKWARD_SLASH:Hr,CHAR_COMMA:_S,CHAR_DOT:oa,CHAR_EXCLAMATION_MARK:aa,CHAR_FORWARD_SLASH:bf,CHAR_LEFT_CURLY_BRACE:la,CHAR_LEFT_PARENTHESES:ca,CHAR_LEFT_SQUARE_BRACKET:xS,CHAR_PLUS:vS,CHAR_QUESTION_MARK:hf,CHAR_RIGHT_CURLY_BRACE:$S,CHAR_RIGHT_PARENTHESES:gf,CHAR_RIGHT_SQUARE_BRACKET:TS}=Br(),yf=e=>e===bf||e===Hr,wf=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,u=0,p=0,f=false,h=false,d=false,m=false,b=false,g=false,S=false,A=false,v=false,k=false,N=0,$,x,I={value:"",depth:0,isGlob:false},w=()=>c>=n,L=()=>l.charCodeAt(c+1),T=()=>($=x,l.charCodeAt(++c));for(;c<n;){x=T();let j;if(x===Hr){S=I.backslashes=true,x=T(),x===la&&(g=true);continue}if(g===true||x===la){for(N++;w()!==true&&(x=T());){if(x===Hr){S=I.backslashes=true,T();continue}if(x===la){N++;continue}if(g!==true&&x===oa&&(x=T())===oa){if(f=I.isBrace=true,d=I.isGlob=true,k=true,s===true)continue;break}if(g!==true&&x===_S){if(f=I.isBrace=true,d=I.isGlob=true,k=true,s===true)continue;break}if(x===$S&&(N--,N===0)){g=false,f=I.isBrace=true,k=true;break}}if(s===true)continue;break}if(x===bf){if(i.push(c),o.push(I),I={value:"",depth:0,isGlob:false},k===true)continue;if($===oa&&c===u+1){u+=2;continue}p=c+1;continue}if(r.noext!==true&&(x===vS||x===ES||x===ia||x===hf||x===aa)===true&&L()===ca){if(d=I.isGlob=true,m=I.isExtglob=true,k=true,x===aa&&c===u&&(v=true),s===true){for(;w()!==true&&(x=T());){if(x===Hr){S=I.backslashes=true,x=T();continue}if(x===gf){d=I.isGlob=true,k=true;break}}continue}break}if(x===ia){if($===ia&&(b=I.isGlobstar=true),d=I.isGlob=true,k=true,s===true)continue;break}if(x===hf){if(d=I.isGlob=true,k=true,s===true)continue;break}if(x===xS){for(;w()!==true&&(j=T());){if(j===Hr){S=I.backslashes=true,T();continue}if(j===TS){h=I.isBracket=true,d=I.isGlob=true,k=true;break}}if(s===true)continue;break}if(r.nonegate!==true&&x===aa&&c===u){A=I.negated=true,u++;continue}if(r.noparen!==true&&x===ca){if(d=I.isGlob=true,s===true){for(;w()!==true&&(x=T());){if(x===ca){S=I.backslashes=true,x=T();continue}if(x===gf){k=true;break}}continue}break}if(d===true){if(k=true,s===true)continue;break}}r.noext===true&&(m=false,d=false);let q=l,E="",_="";u>0&&(E=l.slice(0,u),l=l.slice(u),p-=u),q&&d===true&&p>0?(q=l.slice(0,p),_=l.slice(p)):d===true?(q="",_=l):q=l,q&&q!==""&&q!=="/"&&q!==l&&yf(q.charCodeAt(q.length-1))&&(q=q.slice(0,-1)),r.unescape===true&&(_&&(_=df.removeBackslashes(_)),q&&S===true&&(q=df.removeBackslashes(q)));let U={prefix:E,input:e,start:u,base:q,glob:_,isBrace:f,isBracket:h,isGlob:d,isExtglob:m,isGlobstar:b,negated:A,negatedExtglob:v};if(r.tokens===true&&(U.maxDepth=0,yf(x)||o.push(I),U.tokens=o),r.parts===true||r.tokens===true){let j;for(let V=0;V<i.length;V++){let qe=j?j+1:u,Re=i[V],lt=e.slice(qe,Re);r.tokens&&(V===0&&u!==0?(o[V].isPrefix=true,o[V].value=E):o[V].value=lt,wf(o[V]),U.maxDepth+=o[V].depth),(V!==0||lt!=="")&&a.push(lt),j=Re;}if(j&&j+1<e.length){let V=e.slice(j+1);a.push(V),r.tokens&&(o[o.length-1].value=V,wf(o[o.length-1]),U.maxDepth+=o[o.length-1].depth);}U.slashes=i,U.parts=a;}return U};Sf.exports=AS;});var vf=ct((UR,xf)=>{var Ts=Br(),Je=qr(),{MAX_LENGTH:As,POSIX_REGEX_SOURCE:CS,REGEX_NON_SPECIAL_CHARS:RS,REGEX_SPECIAL_CHARS_BACKREF:PS,REPLACEMENTS:_f}=Ts,kS=(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=>Je.escapeRegex(s)).join("..")}return r},tr=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`,ua=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a string");e=_f[e]||e;let r={...t},n=typeof r.maxLength=="number"?Math.min(As,r.maxLength):As,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=Ts.globChars(r.windows),c=Ts.extglobChars(l),{DOT_LITERAL:u,PLUS_LITERAL:p,SLASH_LITERAL:f,ONE_CHAR:h,DOTS_SLASH:d,NO_DOT:m,NO_DOT_SLASH:b,NO_DOTS_SLASH:g,QMARK:S,QMARK_NO_DOT:A,STAR:v,START_ANCHOR:k}=l,N=O=>`(${a}(?:(?!${k}${O.dot?d:u}).)*?)`,$=r.dot?"":m,x=r.dot?S:A,I=r.bash===true?N(r):v;r.capture&&(I=`(${I})`),typeof r.noext=="boolean"&&(r.noextglob=r.noext);let w={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=Je.removePrefix(e,w),s=e.length;let L=[],T=[],q=[],E=i,_,U=()=>w.index===s-1,j=w.peek=(O=1)=>e[w.index+O],V=w.advance=()=>e[++w.index]||"",qe=()=>e.slice(w.index+1),Re=(O="",ne=0)=>{w.consumed+=O,w.index+=ne;},lt=O=>{w.output+=O.output!=null?O.output:O.value,Re(O.value);},gg=()=>{let O=1;for(;j()==="!"&&(j(2)!=="("||j(3)==="?");)V(),w.start++,O++;return O%2===0?false:(w.negated=true,w.start++,true)},On=O=>{w[O]++,q.push(O);},wt=O=>{w[O]--,q.pop();},G=O=>{if(E.type==="globstar"){let ne=w.braces>0&&(O.type==="comma"||O.type==="brace"),C=O.extglob===true||L.length&&(O.type==="pipe"||O.type==="paren");O.type!=="slash"&&O.type!=="paren"&&!ne&&!C&&(w.output=w.output.slice(0,-E.output.length),E.type="star",E.value="*",E.output=I,w.output+=E.output);}if(L.length&&O.type!=="paren"&&(L[L.length-1].inner+=O.value),(O.value||O.output)&<(O),E&&E.type==="text"&&O.type==="text"){E.output=(E.output||E.value)+O.value,E.value+=O.value;return}O.prev=E,o.push(O),E=O;},In=(O,ne)=>{let C={...c[ne],conditions:1,inner:""};C.prev=E,C.parens=w.parens,C.output=w.output;let W=(r.capture?"(":"")+C.open;On("parens"),G({type:O,value:ne,output:w.output?"":h}),G({type:"paren",extglob:true,value:V(),output:W}),L.push(C);},yg=O=>{let ne=O.close+(r.capture?")":""),C;if(O.type==="negate"){let W=I;if(O.inner&&O.inner.length>1&&O.inner.includes("/")&&(W=N(r)),(W!==I||U()||/^\)+$/.test(qe()))&&(ne=O.close=`)$))${W}`),O.inner.includes("*")&&(C=qe())&&/^\.[^\\/.]+$/.test(C)){let ce=ua(C,{...t,fastpaths:false}).output;ne=O.close=`)${ce})${W})`;}O.prev.type==="bos"&&(w.negatedExtglob=true);}G({type:"paren",extglob:true,value:_,output:ne}),wt("parens");};if(r.fastpaths!==false&&!/(^[*!]|[/()[\]{}"])/.test(e)){let O=false,ne=e.replace(PS,(C,W,ce,ve,me,Fi)=>ve==="\\"?(O=true,C):ve==="?"?W?W+ve+(me?S.repeat(me.length):""):Fi===0?x+(me?S.repeat(me.length):""):S.repeat(ce.length):ve==="."?u.repeat(ce.length):ve==="*"?W?W+ve+(me?I:""):I:W?C:`\\${C}`);return O===true&&(r.unescape===true?ne=ne.replace(/\\/g,""):ne=ne.replace(/\\+/g,C=>C.length%2===0?"\\\\":C?"\\":"")),ne===e&&r.contains===true?(w.output=e,w):(w.output=Je.wrapOutput(ne,w,t),w)}for(;!U();){if(_=V(),_==="\0")continue;if(_==="\\"){let C=j();if(C==="/"&&r.bash!==true||C==="."||C===";")continue;if(!C){_+="\\",G({type:"text",value:_});continue}let W=/^\\+/.exec(qe()),ce=0;if(W&&W[0].length>2&&(ce=W[0].length,w.index+=ce,ce%2!==0&&(_+="\\")),r.unescape===true?_=V():_+=V(),w.brackets===0){G({type:"text",value:_});continue}}if(w.brackets>0&&(_!=="]"||E.value==="["||E.value==="[^")){if(r.posix!==false&&_===":"){let C=E.value.slice(1);if(C.includes("[")&&(E.posix=true,C.includes(":"))){let W=E.value.lastIndexOf("["),ce=E.value.slice(0,W),ve=E.value.slice(W+2),me=CS[ve];if(me){E.value=ce+me,w.backtrack=true,V(),!i.output&&o.indexOf(E)===1&&(i.output=h);continue}}}(_==="["&&j()!==":"||_==="-"&&j()==="]")&&(_=`\\${_}`),_==="]"&&(E.value==="["||E.value==="[^")&&(_=`\\${_}`),r.posix===true&&_==="!"&&E.value==="["&&(_="^"),E.value+=_,lt({value:_});continue}if(w.quotes===1&&_!=='"'){_=Je.escapeRegex(_),E.value+=_,lt({value:_});continue}if(_==='"'){w.quotes=w.quotes===1?0:1,r.keepQuotes===true&&G({type:"text",value:_});continue}if(_==="("){On("parens"),G({type:"paren",value:_});continue}if(_===")"){if(w.parens===0&&r.strictBrackets===true)throw new SyntaxError(tr("opening","("));let C=L[L.length-1];if(C&&w.parens===C.parens+1){yg(L.pop());continue}G({type:"paren",value:_,output:w.parens?")":"\\)"}),wt("parens");continue}if(_==="["){if(r.nobracket===true||!qe().includes("]")){if(r.nobracket!==true&&r.strictBrackets===true)throw new SyntaxError(tr("closing","]"));_=`\\${_}`;}else On("brackets");G({type:"bracket",value:_});continue}if(_==="]"){if(r.nobracket===true||E&&E.type==="bracket"&&E.value.length===1){G({type:"text",value:_,output:`\\${_}`});continue}if(w.brackets===0){if(r.strictBrackets===true)throw new SyntaxError(tr("opening","["));G({type:"text",value:_,output:`\\${_}`});continue}wt("brackets");let C=E.value.slice(1);if(E.posix!==true&&C[0]==="^"&&!C.includes("/")&&(_=`/${_}`),E.value+=_,lt({value:_}),r.literalBrackets===false||Je.hasRegexChars(C))continue;let W=Je.escapeRegex(E.value);if(w.output=w.output.slice(0,-E.value.length),r.literalBrackets===true){w.output+=W,E.value=W;continue}E.value=`(${a}${W}|${E.value})`,w.output+=E.value;continue}if(_==="{"&&r.nobrace!==true){On("braces");let C={type:"brace",value:_,output:"(",outputIndex:w.output.length,tokensIndex:w.tokens.length};T.push(C),G(C);continue}if(_==="}"){let C=T[T.length-1];if(r.nobrace===true||!C){G({type:"text",value:_,output:_});continue}let W=")";if(C.dots===true){let ce=o.slice(),ve=[];for(let me=ce.length-1;me>=0&&(o.pop(),ce[me].type!=="brace");me--)ce[me].type!=="dots"&&ve.unshift(ce[me].value);W=kS(ve,r),w.backtrack=true;}if(C.comma!==true&&C.dots!==true){let ce=w.output.slice(0,C.outputIndex),ve=w.tokens.slice(C.tokensIndex);C.value=C.output="\\{",_=W="\\}",w.output=ce;for(let me of ve)w.output+=me.output||me.value;}G({type:"brace",value:_,output:W}),wt("braces"),T.pop();continue}if(_==="|"){L.length>0&&L[L.length-1].conditions++,G({type:"text",value:_});continue}if(_===","){let C=_,W=T[T.length-1];W&&q[q.length-1]==="braces"&&(W.comma=true,C="|"),G({type:"comma",value:_,output:C});continue}if(_==="/"){if(E.type==="dot"&&w.index===w.start+1){w.start=w.index+1,w.consumed="",w.output="",o.pop(),E=i;continue}G({type:"slash",value:_,output:f});continue}if(_==="."){if(w.braces>0&&E.type==="dot"){E.value==="."&&(E.output=u);let C=T[T.length-1];E.type="dots",E.output+=_,E.value+=_,C.dots=true;continue}if(w.braces+w.parens===0&&E.type!=="bos"&&E.type!=="slash"){G({type:"text",value:_,output:u});continue}G({type:"dot",value:_,output:u});continue}if(_==="?"){if(!(E&&E.value==="(")&&r.noextglob!==true&&j()==="("&&j(2)!=="?"){In("qmark",_);continue}if(E&&E.type==="paren"){let W=j(),ce=_;(E.value==="("&&!/[!=<:]/.test(W)||W==="<"&&!/<([!=]|\w+>)/.test(qe()))&&(ce=`\\${_}`),G({type:"text",value:_,output:ce});continue}if(r.dot!==true&&(E.type==="slash"||E.type==="bos")){G({type:"qmark",value:_,output:A});continue}G({type:"qmark",value:_,output:S});continue}if(_==="!"){if(r.noextglob!==true&&j()==="("&&(j(2)!=="?"||!/[!=<:]/.test(j(3)))){In("negate",_);continue}if(r.nonegate!==true&&w.index===0){gg();continue}}if(_==="+"){if(r.noextglob!==true&&j()==="("&&j(2)!=="?"){In("plus",_);continue}if(E&&E.value==="("||r.regex===false){G({type:"plus",value:_,output:p});continue}if(E&&(E.type==="bracket"||E.type==="paren"||E.type==="brace")||w.parens>0){G({type:"plus",value:_});continue}G({type:"plus",value:p});continue}if(_==="@"){if(r.noextglob!==true&&j()==="("&&j(2)!=="?"){G({type:"at",extglob:true,value:_,output:""});continue}G({type:"text",value:_});continue}if(_!=="*"){(_==="$"||_==="^")&&(_=`\\${_}`);let C=RS.exec(qe());C&&(_+=C[0],w.index+=C[0].length),G({type:"text",value:_});continue}if(E&&(E.type==="globstar"||E.star===true)){E.type="star",E.star=true,E.value+=_,E.output=I,w.backtrack=true,w.globstar=true,Re(_);continue}let O=qe();if(r.noextglob!==true&&/^\([^?]/.test(O)){In("star",_);continue}if(E.type==="star"){if(r.noglobstar===true){Re(_);continue}let C=E.prev,W=C.prev,ce=C.type==="slash"||C.type==="bos",ve=W&&(W.type==="star"||W.type==="globstar");if(r.bash===true&&(!ce||O[0]&&O[0]!=="/")){G({type:"star",value:_,output:""});continue}let me=w.braces>0&&(C.type==="comma"||C.type==="brace"),Fi=L.length&&(C.type==="pipe"||C.type==="paren");if(!ce&&C.type!=="paren"&&!me&&!Fi){G({type:"star",value:_,output:""});continue}for(;O.slice(0,3)==="/**";){let Ln=e[w.index+4];if(Ln&&Ln!=="/")break;O=O.slice(3),Re("/**",3);}if(C.type==="bos"&&U()){E.type="globstar",E.value+=_,E.output=N(r),w.output=E.output,w.globstar=true,Re(_);continue}if(C.type==="slash"&&C.prev.type!=="bos"&&!ve&&U()){w.output=w.output.slice(0,-(C.output+E.output).length),C.output=`(?:${C.output}`,E.type="globstar",E.output=N(r)+(r.strictSlashes?")":"|$)"),E.value+=_,w.globstar=true,w.output+=C.output+E.output,Re(_);continue}if(C.type==="slash"&&C.prev.type!=="bos"&&O[0]==="/"){let Ln=O[1]!==void 0?"|$":"";w.output=w.output.slice(0,-(C.output+E.output).length),C.output=`(?:${C.output}`,E.type="globstar",E.output=`${N(r)}${f}|${f}${Ln})`,E.value+=_,w.output+=C.output+E.output,w.globstar=true,Re(_+V()),G({type:"slash",value:"/",output:""});continue}if(C.type==="bos"&&O[0]==="/"){E.type="globstar",E.value+=_,E.output=`(?:^|${f}|${N(r)}${f})`,w.output=E.output,w.globstar=true,Re(_+V()),G({type:"slash",value:"/",output:""});continue}w.output=w.output.slice(0,-E.output.length),E.type="globstar",E.output=N(r),E.value+=_,w.output+=E.output,w.globstar=true,Re(_);continue}let ne={type:"star",value:_,output:I};if(r.bash===true){ne.output=".*?",(E.type==="bos"||E.type==="slash")&&(ne.output=$+ne.output),G(ne);continue}if(E&&(E.type==="bracket"||E.type==="paren")&&r.regex===true){ne.output=_,G(ne);continue}(w.index===w.start||E.type==="slash"||E.type==="dot")&&(E.type==="dot"?(w.output+=b,E.output+=b):r.dot===true?(w.output+=g,E.output+=g):(w.output+=$,E.output+=$),j()!=="*"&&(w.output+=h,E.output+=h)),G(ne);}for(;w.brackets>0;){if(r.strictBrackets===true)throw new SyntaxError(tr("closing","]"));w.output=Je.escapeLast(w.output,"["),wt("brackets");}for(;w.parens>0;){if(r.strictBrackets===true)throw new SyntaxError(tr("closing",")"));w.output=Je.escapeLast(w.output,"("),wt("parens");}for(;w.braces>0;){if(r.strictBrackets===true)throw new SyntaxError(tr("closing","}"));w.output=Je.escapeLast(w.output,"{"),wt("braces");}if(r.strictSlashes!==true&&(E.type==="star"||E.type==="bracket")&&G({type:"maybe_slash",value:"",output:`${f}?`}),w.backtrack===true){w.output="";for(let O of w.tokens)w.output+=O.output!=null?O.output:O.value,O.suffix&&(w.output+=O.suffix);}return w};ua.fastpaths=(e,t)=>{let r={...t},n=typeof r.maxLength=="number"?Math.min(As,r.maxLength):As,s=e.length;if(s>n)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${n}`);e=_f[e]||e;let{DOT_LITERAL:i,SLASH_LITERAL:o,ONE_CHAR:a,DOTS_SLASH:l,NO_DOT:c,NO_DOTS:u,NO_DOTS_SLASH:p,STAR:f,START_ANCHOR:h}=Ts.globChars(r.windows),d=r.dot?u:c,m=r.dot?p:c,b=r.capture?"":"?:",g={negated:false,prefix:""},S=r.bash===true?".*?":f;r.capture&&(S=`(${S})`);let A=$=>$.noglobstar===true?S:`(${b}(?:(?!${h}${$.dot?l:i}).)*?)`,v=$=>{switch($){case "*":return `${d}${a}${S}`;case ".*":return `${i}${a}${S}`;case "*.*":return `${d}${S}${i}${a}${S}`;case "*/*":return `${d}${S}${o}${a}${m}${S}`;case "**":return d+A(r);case "**/*":return `(?:${d}${A(r)}${o})?${m}${a}${S}`;case "**/*.*":return `(?:${d}${A(r)}${o})?${m}${S}${i}${a}${S}`;case "**/.*":return `(?:${d}${A(r)}${o})?${i}${a}${S}`;default:{let x=/^(.*?)\.(\w+)$/.exec($);if(!x)return;let I=v(x[1]);return I?I+i+x[2]:void 0}}},k=Je.removePrefix(e,g),N=v(k);return N&&r.strictSlashes!==true&&(N+=`${o}?`),N};xf.exports=ua;});var Af=ct((BR,Tf)=>{var NS=Ef(),pa=vf(),$f=qr(),OS=Br(),IS=e=>e&&typeof e=="object"&&!Array.isArray(e),pe=(e,t,r=false)=>{if(Array.isArray(e)){let u=e.map(f=>pe(f,t,r));return f=>{for(let h of u){let d=h(f);if(d)return d}return false}}let n=IS(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?pe.compileRe(e,t):pe.makeRe(e,t,false,true),a=o.state;delete o.state;let l=()=>false;if(s.ignore){let u={...t,ignore:null,onMatch:null,onResult:null};l=pe(s.ignore,u,r);}let c=(u,p=false)=>{let{isMatch:f,match:h,output:d}=pe.test(u,o,t,{glob:e,posix:i}),m={glob:e,state:a,regex:o,posix:i,input:u,output:d,match:h,isMatch:f};return typeof s.onResult=="function"&&s.onResult(m),f===false?(m.isMatch=false,p?m:false):l(u)?(typeof s.onIgnore=="function"&&s.onIgnore(m),m.isMatch=false,p?m:false):(typeof s.onMatch=="function"&&s.onMatch(m),p?m:true)};return r&&(c.state=a),c};pe.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?$f.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=pe.matchBase(e,t,r,s):a=t.exec(l)),{isMatch:!!a,match:a,output:l}};pe.matchBase=(e,t,r)=>(t instanceof RegExp?t:pe.makeRe(t,r)).test($f.basename(e));pe.isMatch=(e,t,r)=>pe(t,r)(e);pe.parse=(e,t)=>Array.isArray(e)?e.map(r=>pe.parse(r,t)):pa(e,{...t,fastpaths:false});pe.scan=(e,t)=>NS(e,t);pe.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=pe.toRegex(a,t);return n===true&&(l.state=e),l};pe.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=pa.fastpaths(e,t)),s.output||(s=pa(e,t)),pe.compileRe(s,t,r,n)};pe.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 /$^/}};pe.constants=OS;Tf.exports=pe;});var kf=ct((qR,Pf)=>{var Cf=Af(),LS=qr();function Rf(e,t,r=false){return t&&(t.windows===null||t.windows===void 0)&&(t={...t,windows:LS.isWindows()}),Cf(e,t,r)}Object.assign(Rf,Cf);Pf.exports=Rf;});function MS(e,t={}){let r=e.length,n=Array(r),s=Array(r),i=!t.noglobstar;for(let o=0;o<r;o++){let a=Lf(e[o]);n[o]=a;let l=a.length,c=Array(l);for(let u=0;u<l;u++)c[u]=(0, sr.default)(a[u],t);s[o]=c;}return o=>{let a=o.split("/");if(a[0]===".."&&FS.test(o))return true;for(let l=0;l<e.length;l++){let c=n[l],u=s[l],p=a.length,f=Math.min(p,c.length),h=0;for(;h<f;){let d=c[h];if(d.includes("/"))return true;if(!u[h](a[h]))break;if(i&&d==="**")return true;h++;}if(h===p)return true}return false}}function Nf(e,t,r){if(e===t||t.startsWith(`${e}/`)){if(r){let s=BS(e)?e.length:e.length+1;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 qS(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.endsWith("/")&&n!==""?`${n}/`:n||"."}}function Lf(e){var t;let r=sr.default.scan(e,HS);return !((t=r.parts)===null||t===void 0)&&t.length?r.parts:[e]}function YS(e,t){let r=sr.default.scan(e);return r.isGlob||r.negated}function nr(...e){console.log(`[tinyglobby ${new Date().toLocaleTimeString("es")}]`,...e);}function fa(e,t,r,n,s){let i=e;e.endsWith("/")&&(i=e.slice(0,-1)),!i.endsWith("*")&&t&&(i+="/**");let o=KS(r);Of.isAbsolute(i.replace(XS,""))?i=posix.relative(o,i):i=posix.normalize(i);let a=JS.exec(i),l=Lf(i);if(a?.[0]){let u=(a[0].length+1)/3,p=0,f=o.split("/");for(;p<u&&l[p+u]===f[f.length+p-u];)i=i.slice(0,(u-p-1)*3)+i.slice((u-p)*3+l[p+u].length+1)||".",p++;let h=posix.join(r,a[0].slice(p*3));!h.startsWith(".")&&n.root.length>h.length&&(n.root=h,n.depthOffset=-u+p);}if(!s&&n.depthOffset>=0){var c;(c=n.commonPath)!==null&&c!==void 0||(n.commonPath=l);let u=[],p=Math.min(n.commonPath.length,l.length);for(let f=0;f<p;f++){let h=l[f];if(h==="**"&&!l[f+1]){u.pop();break}if(h!==n.commonPath[f]||YS(h)||f===l.length-1)break;u.push(h);}n.depthOffset=u.length,n.commonPath=u,n.root=u.length>0?posix.join(r,...u):r;}return i}function QS({patterns:e=["**/*"],ignore:t=[],expandDirectories:r=true},n,s){typeof e=="string"&&(e=[e]),typeof t=="string"&&(t=[t]);let i=[],o=[];for(let a of t)a&&(a[0]!=="!"||a[1]==="(")&&o.push(fa(a,r,n,s,true));for(let a of e)a&&(a[0]!=="!"||a[1]==="("?i.push(fa(a,r,n,s,false)):(a[1]!=="!"||a[2]==="(")&&o.push(fa(a.slice(1),r,n,s,true)));return {match:i,ignore:o}}function ZS(e,t){for(let r=e.length-1;r>=0;r--){let n=e[r];e[r]=t(n);}return e}function eE(e){return e?e instanceof URL?fileURLToPath$1(e).replace(Cs,"/"):Of.resolve(e).replace(Cs,"/"):process.cwd().replace(Cs,"/")}function tE(e,t={}){let r=process.env.TINYGLOBBY_DEBUG?{...t,debug:true}:t,n=eE(r.cwd);if(r.debug&&nr("globbing with:",{patterns:e,options:r,cwd:n}),Array.isArray(e)&&e.length===0)return [{sync:()=>[],withPromise:async()=>[]},false];let s={root:n,commonPath:null,depthOffset:0},i=QS({...r,patterns:e},n,s);r.debug&&nr("internal processing patterns:",i);let o={dot:r.dot,nobrace:r.braceExpansion===false,nocase:r.caseSensitiveMatch===false,noextglob:r.extglob===false,noglobstar:r.globstar===false,posix:true},a=(0, sr.default)(i.match,{...o,ignore:i.ignore}),l=(0, sr.default)(i.ignore,o),c=MS(i.match,o),u=Nf(n,s.root,r.absolute),p=r.absolute?u:Nf(n,s.root,true),f={filters:[r.debug?(m,b)=>{let g=u(m,b),S=a(g);return S&&nr(`matched ${g}`),S}:(m,b)=>a(u(m,b))],exclude:r.debug?(m,b)=>{let g=p(b,true),S=g!=="."&&!c(g)||l(g);return nr(S?`skipped ${b}`:`crawling ${b}`),S}:(m,b)=>{let g=p(b,true);return g!=="."&&!c(g)||l(g)},fs:r.fs?{readdir:r.fs.readdir||rr__default.readdir,readdirSync:r.fs.readdirSync||rr__default.readdirSync,realpath:r.fs.realpath||rr__default.realpath,realpathSync:r.fs.realpathSync||rr__default.realpathSync,stat:r.fs.stat||rr__default.stat,statSync:r.fs.statSync||rr__default.statSync}:void 0,pathSeparator:"/",relativePaths:true,resolveSymlinks:true,signal:r.signal};r.deep!==void 0&&(f.maxDepth=Math.round(r.deep-s.depthOffset)),r.absolute&&(f.relativePaths=false,f.resolvePaths=true,f.includeBasePath=true),r.followSymbolicLinks===false&&(f.resolveSymlinks=false,f.excludeSymlinks=true),r.onlyDirectories?(f.excludeFiles=true,f.includeDirs=true):r.onlyFiles===false&&(f.includeDirs=true),s.root=s.root.replace(Cs,"");let h=s.root;r.debug&&nr("internal properties:",s);let d=n!==h&&!r.absolute&&qS(n,s.root);return [new af(f).crawl(h),d]}async function Wr(e,t){if(e&&t?.patterns)throw new Error("Cannot pass patterns as both an argument and an option");let r=jS(e)||typeof e=="string",n=r?t:e,s=r?e:e.patterns,[i,o]=tE(s,n);return o?ZS(await i.withPromise(),o):i.withPromise()}var sr,jS,If,FS,US,BS,HS,WS,zS,GS,VS,KS,JS,XS,Cs,ma=y(()=>{lf();sr=te(kf()),jS=Array.isArray,If=process.platform==="win32",FS=/^(\/?\.\.)+$/;US=/^[A-Z]:\/$/i,BS=If?e=>US.test(e):e=>e==="/";HS={parts:true};WS=/(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g,zS=/(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g,GS=e=>e.replace(WS,"\\$&"),VS=e=>e.replace(zS,"\\$&"),KS=If?VS:GS;JS=/^(\/?\.\.)+/,XS=/\\(?=[()[\]{}!*+?@|])/g,Cs=/\\/g;});function qf(e,t={}){let r=t.entryType||t.type;if(r==="both"&&(r=Ie.FILE_DIR_TYPE),r&&(t.type=r),e){if(typeof e!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(r&&!Ff.includes(r))throw new Error(`readdirp: Invalid type passed. Use one of ${Ff.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return t.root=e,new ha(t)}var Ie,da,Bf,cE,Ff,uE,pE,fE,mE,Mf,Uf,ha,Hf=y(()=>{Ie={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},da={root:".",fileFilter:e=>true,directoryFilter:e=>true,type:Ie.FILE_TYPE,lstat:false,depth:2147483648,alwaysStat:false,highWaterMark:4096};Object.freeze(da);Bf="READDIRP_RECURSIVE_ERROR",cE=new Set(["ENOENT","EPERM","EACCES","ELOOP",Bf]),Ff=[Ie.DIR_TYPE,Ie.EVERYTHING_TYPE,Ie.FILE_DIR_TYPE,Ie.FILE_TYPE],uE=new Set([Ie.DIR_TYPE,Ie.EVERYTHING_TYPE,Ie.FILE_DIR_TYPE]),pE=new Set([Ie.EVERYTHING_TYPE,Ie.FILE_DIR_TYPE,Ie.FILE_TYPE]),fE=e=>cE.has(e.code),mE=process.platform==="win32",Mf=e=>true,Uf=e=>{if(e===void 0)return Mf;if(typeof e=="function")return e;if(typeof e=="string"){let t=e.trim();return r=>r.basename===t}if(Array.isArray(e)){let t=e.map(r=>r.trim());return r=>t.some(n=>r.basename===n)}return Mf},ha=class extends Readable{parents;reading;parent;_stat;_maxDepth;_wantsDir;_wantsFile;_wantsEverything;_root;_isDirent;_statsProp;_rdOptions;_fileFilter;_directoryFilter;constructor(t={}){super({objectMode:true,autoDestroy:true,highWaterMark:t.highWaterMark});let r={...da,...t},{root:n,type:s}=r;this._fileFilter=Uf(r.fileFilter),this._directoryFilter=Uf(r.directoryFilter);let i=r.lstat?lstat:stat;mE?this._stat=o=>i(o,{bigint:true}):this._stat=i,this._maxDepth=r.depth!=null&&Number.isSafeInteger(r.depth)?r.depth:da.depth,this._wantsDir=s?uE.has(s):false,this._wantsFile=s?pE.has(s):false,this._wantsEverything=s===Ie.EVERYTHING_TYPE,this._root=resolve$1(n),this._isDirent=!r.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(n,1)],this.reading=false,this.parent=void 0;}async _read(t){if(!this.reading){this.reading=true;try{for(;!this.destroyed&&t>0;){let r=this.parent,n=r&&r.files;if(n&&n.length>0){let{path:s,depth:i}=r,o=n.splice(0,t).map(l=>this._formatEntry(l,s)),a=await Promise.all(o);for(let l of a){if(!l)continue;if(this.destroyed)return;let c=await this._getEntryType(l);c==="directory"&&this._directoryFilter(l)?(i<=this._maxDepth&&this.parents.push(this._exploreDir(l.fullPath,i+1)),this._wantsDir&&(this.push(l),t--)):(c==="file"||this._includeAsFile(l))&&this._fileFilter(l)&&this._wantsFile&&(this.push(l),t--);}}else {let s=this.parents.pop();if(!s){this.push(null);break}if(this.parent=await s,this.destroyed)return}}}catch(r){this.destroy(r);}finally{this.reading=false;}}}async _exploreDir(t,r){let n;try{n=await readdir(t,this._rdOptions);}catch(s){this._onError(s);}return {files:n,depth:r,path:t}}async _formatEntry(t,r){let n,s=this._isDirent?t.name:t;try{let i=resolve$1(join(r,s));n={path:relative$1(this._root,i),fullPath:i,basename:s},n[this._statsProp]=this._isDirent?t:await this._stat(i);}catch(i){this._onError(i);return}return n}_onError(t){fE(t)&&!this.destroyed?this.emit("warn",t):this.destroy(t);}async _getEntryType(t){if(!t&&this._statsProp in t)return "";let r=t[this._statsProp];if(r.isFile())return "file";if(r.isDirectory())return "directory";if(r&&r.isSymbolicLink()){let n=t.fullPath;try{let s=await realpath(n),i=await lstat(s);if(i.isFile())return "file";if(i.isDirectory()){let o=s.length;if(n.startsWith(s)&&n.substr(o,1)===sep$1){let a=new Error(`Circular symlink detected: "${n}" points to "${s}"`);return a.code=Bf,this._onError(a)}return "directory"}}catch(s){return this._onError(s),""}}}_includeAsFile(t){let r=t&&t[this._statsProp];return r&&this._wantsEverything&&!r.isDirectory()}};});function zf(e,t,r,n,s){let i=(o,a)=>{r(e),s(o,a,{watchedPath:e}),a&&e!==a&&ks(z.resolve(e,a),Ct,z.join(e,a));};try{return watch(e,{persistent:t.persistent},i)}catch(o){n(o);return}}var bE,ba,Vf,Os,Is,Sa,SE,EE,_E,Kf,ue,He,xE,vE,Ct,Rs,ir,$E,TE,AE,wa,zr,CE,Gr,Yf,Ps,ks,RE,ya,PE,Ns,Jf=y(()=>{bE="data",ba="end",Vf="close",Os=()=>{},Is=process.platform,Sa=Is==="win32",SE=Is==="darwin",EE=Is==="linux",_E=Is==="freebsd",Kf=type()==="OS400",ue={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},He=ue,xE="watch",vE={lstat:lstat,stat:stat},Ct="listeners",Rs="errHandlers",ir="rawEmitters",$E=[Ct,Rs,ir],TE=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),AE=e=>TE.has(z.extname(e).slice(1).toLowerCase()),wa=(e,t)=>{e instanceof Set?e.forEach(t):t(e);},zr=(e,t,r)=>{let n=e[t];n instanceof Set||(e[t]=n=new Set([n])),n.add(r);},CE=e=>t=>{let r=e[t];r instanceof Set?r.clear():delete e[t];},Gr=(e,t,r)=>{let n=e[t];n instanceof Set?n.delete(r):n===r&&delete e[t];},Yf=e=>e instanceof Set?e.size===0:!e,Ps=new Map;ks=(e,t,r,n,s)=>{let i=Ps.get(e);i&&wa(i[t],o=>{o(r,n,s);});},RE=(e,t,r,n)=>{let{listener:s,errHandler:i,rawEmitter:o}=n,a=Ps.get(t),l;if(!r.persistent)return l=zf(e,r,s,i,o),l?l.close.bind(l):void 0;if(a)zr(a,Ct,s),zr(a,Rs,i),zr(a,ir,o);else {if(l=zf(e,r,ks.bind(null,t,Ct),i,ks.bind(null,t,ir)),!l)return;l.on(He.ERROR,async c=>{let u=ks.bind(null,t,Rs);if(a&&(a.watcherUnusable=true),Sa&&c.code==="EPERM")try{await(await open(e,"r")).close(),u(c);}catch{}else u(c);}),a={listeners:s,errHandlers:i,rawEmitters:o,watcher:l},Ps.set(t,a);}return ()=>{Gr(a,Ct,s),Gr(a,Rs,i),Gr(a,ir,o),Yf(a.listeners)&&(a.watcher.close(),Ps.delete(t),$E.forEach(CE(a)),a.watcher=void 0,Object.freeze(a));}},ya=new Map,PE=(e,t,r,n)=>{let{listener:s,rawEmitter:i}=n,o=ya.get(t),a=o&&o.options;return a&&(a.persistent<r.persistent||a.interval>r.interval)&&(unwatchFile(t),o=void 0),o?(zr(o,Ct,s),zr(o,ir,i)):(o={listeners:s,rawEmitters:i,options:r,watcher:watchFile(t,r,(l,c)=>{wa(o.rawEmitters,p=>{p(He.CHANGE,t,{curr:l,prev:c});});let u=l.mtimeMs;(l.size!==c.size||u>c.mtimeMs||u===0)&&wa(o.listeners,p=>p(e,l));})},ya.set(t,o)),()=>{Gr(o,Ct,s),Gr(o,ir,i),Yf(o.listeners)&&(ya.delete(t),unwatchFile(t),o.options=o.watcher=void 0,Object.freeze(o));}},Ns=class{fsw;_boundHandleError;constructor(t){this.fsw=t,this._boundHandleError=r=>t._handleError(r);}_watchWithNodeFs(t,r){let n=this.fsw.options,s=z.dirname(t),i=z.basename(t);this.fsw._getWatchedDir(s).add(i);let a=z.resolve(t),l={persistent:n.persistent};r||(r=Os);let c;if(n.usePolling){let u=n.interval!==n.binaryInterval;l.interval=u&&AE(i)?n.binaryInterval:n.interval,c=PE(t,a,l,{listener:r,rawEmitter:this.fsw._emitRaw});}else c=RE(t,a,l,{listener:r,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return c}_handleFile(t,r,n){if(this.fsw.closed)return;let s=z.dirname(t),i=z.basename(t),o=this.fsw._getWatchedDir(s),a=r;if(o.has(i))return;let l=async(u,p)=>{if(this.fsw._throttle(xE,t,5)){if(!p||p.mtimeMs===0)try{let f=await stat(t);if(this.fsw.closed)return;let h=f.atimeMs,d=f.mtimeMs;if((!h||h<=d||d!==a.mtimeMs)&&this.fsw._emit(He.CHANGE,t,f),(SE||EE||_E)&&a.ino!==f.ino){this.fsw._closeFile(u),a=f;let m=this._watchWithNodeFs(t,l);m&&this.fsw._addPathCloser(u,m);}else a=f;}catch{this.fsw._remove(s,i);}else if(o.has(i)){let f=p.atimeMs,h=p.mtimeMs;(!f||f<=h||h!==a.mtimeMs)&&this.fsw._emit(He.CHANGE,t,p),a=p;}}},c=this._watchWithNodeFs(t,l);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(t)){if(!this.fsw._throttle(He.ADD,t,0))return;this.fsw._emit(He.ADD,t,r);}return c}async _handleSymlink(t,r,n,s){if(this.fsw.closed)return;let i=t.fullPath,o=this.fsw._getWatchedDir(r);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let a;try{a=await realpath(n);}catch{return this.fsw._emitReady(),true}return this.fsw.closed?void 0:(o.has(s)?this.fsw._symlinkPaths.get(i)!==a&&(this.fsw._symlinkPaths.set(i,a),this.fsw._emit(He.CHANGE,n,t.stats)):(o.add(s),this.fsw._symlinkPaths.set(i,a),this.fsw._emit(He.ADD,n,t.stats)),this.fsw._emitReady(),true)}if(this.fsw._symlinkPaths.has(i))return true;this.fsw._symlinkPaths.set(i,true);}_handleRead(t,r,n,s,i,o,a){t=z.join(t,"");let l=s?`${t}:${s}`:t;if(a=this.fsw._throttle("readdir",l,1e3),!a)return;let c=this.fsw._getWatchedDir(n.path),u=new Set,p=this.fsw._readdirp(t,{fileFilter:f=>n.filterPath(f),directoryFilter:f=>n.filterDir(f)});if(p)return p.on(bE,async f=>{if(this.fsw.closed){p=void 0;return}let h=f.path,d=z.join(t,h);if(u.add(h),!(f.stats.isSymbolicLink()&&await this._handleSymlink(f,t,d,h))){if(this.fsw.closed){p=void 0;return}(h===s||!s&&!c.has(h))&&(this.fsw._incrReadyCount(),d=z.join(i,z.relative(i,d)),this._addToNodeFs(d,r,n,o+1));}}).on(He.ERROR,this._boundHandleError),new Promise((f,h)=>{if(!p)return h();p.once(ba,()=>{if(this.fsw.closed){p=void 0;return}let d=a?a.clear():false;f(void 0),c.getChildren().filter(m=>m!==t&&!u.has(m)).forEach(m=>{this.fsw._remove(t,m);}),p=void 0,d&&this._handleRead(t,false,n,s,i,o,a);});})}async _handleDir(t,r,n,s,i,o,a){let l=this.fsw._getWatchedDir(z.dirname(t)),c=l.has(z.basename(t));!(n&&this.fsw.options.ignoreInitial)&&!i&&!c&&this.fsw._emit(He.ADD_DIR,t,r),l.add(z.basename(t)),this.fsw._getWatchedDir(t);let u,p,f=this.fsw.options.depth;if((f==null||s<=f)&&!this.fsw._symlinkPaths.has(a)){if(!i&&(await this._handleRead(t,n,o,i,t,s,u),this.fsw.closed))return;p=this._watchWithNodeFs(t,(h,d)=>{d&&d.mtimeMs===0||this._handleRead(h,false,o,i,t,s,u);});}return p}async _addToNodeFs(t,r,n,s,i){let o=this.fsw._emitReady;if(this.fsw._isIgnored(t)||this.fsw.closed)return o(),false;let a=this.fsw._getWatchHelpers(t);n&&(a.filterPath=l=>n.filterPath(l),a.filterDir=l=>n.filterDir(l));try{let l=await vE[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,l))return o(),!1;let c=this.fsw.options.followSymlinks,u;if(l.isDirectory()){let p=z.resolve(t),f=c?await realpath(t):t;if(this.fsw.closed||(u=await this._handleDir(a.watchPath,l,r,s,i,a,f),this.fsw.closed))return;p!==f&&f!==void 0&&this.fsw._symlinkPaths.set(p,f);}else if(l.isSymbolicLink()){let p=c?await realpath(t):t;if(this.fsw.closed)return;let f=z.dirname(a.watchPath);if(this.fsw._getWatchedDir(f).add(a.watchPath),this.fsw._emit(He.ADD,a.watchPath,l),u=await this._handleDir(f,l,r,s,t,a,p),this.fsw.closed)return;p!==void 0&&this.fsw._symlinkPaths.set(z.resolve(t),p);}else u=this._handleFile(a.watchPath,l,r);return o(),u&&this.fsw._addPathCloser(t,u),!1}catch(l){if(this.fsw._handleError(l))return o(),t}}};});function Ls(e){return Array.isArray(e)?e:[e]}function BE(e){return typeof e=="function"?e:typeof e=="string"?t=>e===t:e instanceof RegExp?t=>e.test(t):typeof e=="object"&&e!==null?t=>{if(e.path===t)return true;if(e.recursive){let r=z.relative(e.path,t);return r?!r.startsWith("..")&&!z.isAbsolute(r):false}return false}:()=>false}function qE(e){if(typeof e!="string")throw new Error("string expected");e=z.normalize(e),e=e.replace(/\\/g,"/");let t=false;return e.startsWith("//")&&(t=true),e=e.replace(rm,"/"),t&&(e="/"+e),e}function Xf(e,t,r){let n=qE(t);for(let s=0;s<e.length;s++){let i=e[s];if(i(n,r))return true}return false}function HE(e,t){if(e==null)throw new TypeError("anymatch: specify first argument");let n=Ls(e).map(s=>BE(s));return t==null?(s,i)=>Xf(n,s,i):Xf(n,t)}function KE(e,t={}){let r=new Ds(t);return r.add(e),r}var Ea,LE,tm,DE,jE,FE,rm,ME,UE,_a,Qf,Zf,nm,em,WE,zE,xa,GE,VE,va,Ds,js,$a=y(()=>{Hf();Jf();Ea="/",LE="//",tm=".",DE="..",jE="string",FE=/\\/g,rm=/\/\//g,ME=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,UE=/^\.[/\\]/;_a=e=>typeof e=="object"&&e!==null&&!(e instanceof RegExp);Qf=e=>{let t=Ls(e).flat();if(!t.every(r=>typeof r===jE))throw new TypeError(`Non-string provided as watch path: ${t}`);return t.map(nm)},Zf=e=>{let t=e.replace(FE,Ea),r=false;return t.startsWith(LE)&&(r=true),t=t.replace(rm,Ea),r&&(t=Ea+t),t},nm=e=>Zf(z.normalize(Zf(e))),em=(e="")=>t=>typeof t=="string"?nm(z.isAbsolute(t)?t:z.join(e,t)):t,WE=(e,t)=>z.isAbsolute(e)?e:z.join(t,e),zE=Object.freeze(new Set),xa=class{path;_removeWatcher;items;constructor(t,r){this.path=t,this._removeWatcher=r,this.items=new Set;}add(t){let{items:r}=this;r&&t!==tm&&t!==DE&&r.add(t);}async remove(t){let{items:r}=this;if(!r||(r.delete(t),r.size>0))return;let n=this.path;try{await readdir(n);}catch{this._removeWatcher&&this._removeWatcher(z.dirname(n),z.basename(n));}}has(t){let{items:r}=this;if(r)return r.has(t)}getChildren(){let{items:t}=this;return t?[...t.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=Os,this.items=zE,Object.freeze(this);}},GE="stat",VE="lstat",va=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(t,r,n){this.fsw=n;let s=t;this.path=t=t.replace(UE,""),this.watchPath=s,this.fullWatchPath=z.resolve(s),this.dirParts=[],this.dirParts.forEach(i=>{i.length>1&&i.pop();}),this.followSymlinks=r,this.statMethod=r?GE:VE;}entryPath(t){return z.join(this.watchPath,z.relative(this.watchPath,t.fullPath))}filterPath(t){let{stats:r}=t;if(r&&r.isSymbolicLink())return this.filterDir(t);let n=this.entryPath(t);return this.fsw._isntIgnored(n,r)&&this.fsw._hasReadPermissions(r)}filterDir(t){return this.fsw._isntIgnored(this.entryPath(t),t.stats)}},Ds=class extends EventEmitter{closed;options;_closers;_ignoredPaths;_throttled;_streams;_symlinkPaths;_watched;_pendingWrites;_pendingUnlinks;_readyCount;_emitReady;_closePromise;_userIgnored;_readyEmitted;_emitRaw;_boundRemove;_nodeFsHandler;constructor(t={}){super(),this.closed=false,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=false;let r=t.awaitWriteFinish,n={stabilityThreshold:2e3,pollInterval:100},s={persistent:true,ignoreInitial:false,ignorePermissionErrors:false,interval:100,binaryInterval:300,followSymlinks:true,usePolling:false,atomic:true,...t,ignored:t.ignored?Ls(t.ignored):Ls([]),awaitWriteFinish:r===true?n:typeof r=="object"?{...n,...r}:false};Kf&&(s.usePolling=true),s.atomic===void 0&&(s.atomic=!s.usePolling);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let l=i.toLowerCase();l==="false"||l==="0"?s.usePolling=false:l==="true"||l==="1"?s.usePolling=true:s.usePolling=!!l;}let o=process.env.CHOKIDAR_INTERVAL;o&&(s.interval=Number.parseInt(o,10));let a=0;this._emitReady=()=>{a++,a>=this._readyCount&&(this._emitReady=Os,this._readyEmitted=true,process.nextTick(()=>this.emit(ue.READY)));},this._emitRaw=(...l)=>this.emit(ue.RAW,...l),this._boundRemove=this._remove.bind(this),this.options=s,this._nodeFsHandler=new Ns(this),Object.freeze(s);}_addIgnoredPath(t){if(_a(t)){for(let r of this._ignoredPaths)if(_a(r)&&r.path===t.path&&r.recursive===t.recursive)return}this._ignoredPaths.add(t);}_removeIgnoredPath(t){if(this._ignoredPaths.delete(t),typeof t=="string")for(let r of this._ignoredPaths)_a(r)&&r.path===t&&this._ignoredPaths.delete(r);}add(t,r,n){let{cwd:s}=this.options;this.closed=false,this._closePromise=void 0;let i=Qf(t);return s&&(i=i.map(o=>WE(o,s))),i.forEach(o=>{this._removeIgnoredPath(o);}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=i.length,Promise.all(i.map(async o=>{let a=await this._nodeFsHandler._addToNodeFs(o,!n,void 0,0,r);return a&&this._emitReady(),a})).then(o=>{this.closed||o.forEach(a=>{a&&this.add(z.dirname(a),z.basename(r||a));});}),this}unwatch(t){if(this.closed)return this;let r=Qf(t),{cwd:n}=this.options;return r.forEach(s=>{!z.isAbsolute(s)&&!this._closers.has(s)&&(n&&(s=z.join(n,s)),s=z.resolve(s)),this._closePath(s),this._addIgnoredPath(s),this._watched.has(s)&&this._addIgnoredPath({path:s,recursive:true}),this._userIgnored=void 0;}),this}close(){if(this._closePromise)return this._closePromise;this.closed=true,this.removeAllListeners();let t=[];return this._closers.forEach(r=>r.forEach(n=>{let s=n();s instanceof Promise&&t.push(s);})),this._streams.forEach(r=>r.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=false,this._watched.forEach(r=>r.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=t.length?Promise.all(t).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let t={};return this._watched.forEach((r,n)=>{let i=(this.options.cwd?z.relative(this.options.cwd,n):n)||tm;t[i]=r.getChildren().sort();}),t}emitWithAll(t,r){this.emit(t,...r),t!==ue.ERROR&&this.emit(ue.ALL,t,...r);}async _emit(t,r,n){if(this.closed)return;let s=this.options;Sa&&(r=z.normalize(r)),s.cwd&&(r=z.relative(s.cwd,r));let i=[r];n!=null&&i.push(n);let o=s.awaitWriteFinish,a;if(o&&(a=this._pendingWrites.get(r)))return a.lastChange=new Date,this;if(s.atomic){if(t===ue.UNLINK)return this._pendingUnlinks.set(r,[t,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((l,c)=>{this.emit(...l),this.emit(ue.ALL,...l),this._pendingUnlinks.delete(c);});},typeof s.atomic=="number"?s.atomic:100),this;t===ue.ADD&&this._pendingUnlinks.has(r)&&(t=ue.CHANGE,this._pendingUnlinks.delete(r));}if(o&&(t===ue.ADD||t===ue.CHANGE)&&this._readyEmitted){let l=(c,u)=>{c?(t=ue.ERROR,i[0]=c,this.emitWithAll(t,i)):u&&(i.length>1?i[1]=u:i.push(u),this.emitWithAll(t,i));};return this._awaitWriteFinish(r,o.stabilityThreshold,t,l),this}if(t===ue.CHANGE&&!this._throttle(ue.CHANGE,r,50))return this;if(s.alwaysStat&&n===void 0&&(t===ue.ADD||t===ue.ADD_DIR||t===ue.CHANGE)){let l=s.cwd?z.join(s.cwd,r):r,c;try{c=await stat(l);}catch{}if(!c||this.closed)return;i.push(c);}return this.emitWithAll(t,i),this}_handleError(t){let r=t&&t.code;return t&&r!=="ENOENT"&&r!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||r!=="EPERM"&&r!=="EACCES")&&this.emit(ue.ERROR,t),t||this.closed}_throttle(t,r,n){this._throttled.has(t)||this._throttled.set(t,new Map);let s=this._throttled.get(t);if(!s)throw new Error("invalid throttle");let i=s.get(r);if(i)return i.count++,false;let o,a=()=>{let c=s.get(r),u=c?c.count:0;return s.delete(r),clearTimeout(o),c&&clearTimeout(c.timeoutObject),u};o=setTimeout(a,n);let l={timeoutObject:o,clear:a,count:0};return s.set(r,l),l}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(t,r,n,s){let i=this.options.awaitWriteFinish;if(typeof i!="object")return;let o=i.pollInterval,a,l=t;this.options.cwd&&!z.isAbsolute(t)&&(l=z.join(this.options.cwd,t));let c=new Date,u=this._pendingWrites;function p(f){stat$1(l,(h,d)=>{if(h||!u.has(t)){h&&h.code!=="ENOENT"&&s(h);return}let m=Number(new Date);f&&d.size!==f.size&&(u.get(t).lastChange=m);let b=u.get(t);m-b.lastChange>=r?(u.delete(t),s(void 0,d)):a=setTimeout(p,o,d);});}u.has(t)||(u.set(t,{lastChange:c,cancelWait:()=>(u.delete(t),clearTimeout(a),n)}),a=setTimeout(p,o));}_isIgnored(t,r){if(this.options.atomic&&ME.test(t))return true;if(!this._userIgnored){let{cwd:n}=this.options,i=(this.options.ignored||[]).map(em(n)),a=[...[...this._ignoredPaths].map(em(n)),...i];this._userIgnored=HE(a,void 0);}return this._userIgnored(t,r)}_isntIgnored(t,r){return !this._isIgnored(t,r)}_getWatchHelpers(t){return new va(t,this.options.followSymlinks,this)}_getWatchedDir(t){let r=z.resolve(t);return this._watched.has(r)||this._watched.set(r,new xa(r,this._boundRemove)),this._watched.get(r)}_hasReadPermissions(t){return this.options.ignorePermissionErrors?true:!!(Number(t.mode)&256)}_remove(t,r,n){let s=z.join(t,r),i=z.resolve(s);if(n=n??(this._watched.has(s)||this._watched.has(i)),!this._throttle("remove",s,100))return;!n&&this._watched.size===1&&this.add(t,r,true),this._getWatchedDir(s).getChildren().forEach(f=>this._remove(s,f));let l=this._getWatchedDir(t),c=l.has(r);l.remove(r),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let u=s;if(this.options.cwd&&(u=z.relative(this.options.cwd,s)),this.options.awaitWriteFinish&&this._pendingWrites.has(u)&&this._pendingWrites.get(u).cancelWait()===ue.ADD)return;this._watched.delete(s),this._watched.delete(i);let p=n?ue.UNLINK_DIR:ue.UNLINK;c&&!this._isIgnored(s)&&this._emit(p,s),this._closePath(s);}_closePath(t){this._closeFile(t);let r=z.dirname(t);this._getWatchedDir(r).remove(z.basename(t));}_closeFile(t){let r=this._closers.get(t);r&&(r.forEach(n=>n()),this._closers.delete(t));}_addPathCloser(t,r){if(!r)return;let n=this._closers.get(t);n||(n=[],this._closers.set(t,n)),n.push(r);}_readdirp(t,r){if(this.closed)return;let n={type:ue.ALL,alwaysStat:true,lstat:true,...r,depth:0},s=qf(t,n);return this._streams.add(s),s.once(Vf,()=>{s=void 0;}),s.once(ba,()=>{s&&(this._streams.delete(s),s=void 0);}),s}};js={watch:KE,FSWatcher:Ds};});function im(e){return e.config?.db?.driver==="sqlite"?"./sqlite-migrations/*.sql":"./migrations/*.sql"}function Rt(e){return z__default.posix.dirname(im(e))}async function Xe(e){let t=z__default.join(process.cwd(),"supabase"),r=await Wr([im(e)],{cwd:t,absolute:true}),n=[];for(let s of r){let i=z__default.basename(s),o=YE.exec(i);if(!o)continue;let a=await fe__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 Fs(e){return (await Xe(e)).map(r=>r.sql).join(`
|
|
63
|
-
`)}function Ta(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 Aa(e,t=Ta()){let r=e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"");return r.length>0?`${t}_${r}.sql`:`${t}.sql`}async function om(e,t,r){let n=z__default.join(process.cwd(),"supabase",Rt(e));Pe(n);let s=Aa(t,r?.ts),i=z__default.join(n,s);return await fe__default.writeFile(i,"",{flag:"wx"}),i}var YE,Pt=y(()=>{ma();St();YE=/^(\d{14})(?:_([^.]+))?\.sql$/;});function Kr(e){if("String"in e)return e.String.sval}function kt(e){return e.map(Kr).filter(t=>t!=null)}function Nt(e){return e==null?[]:e.List!==void 0?e.List.items||[]:Array.isArray(e)?e:[e]}function Ms(e){return QuoteUtils.quoteIdentifier(e)}function or(e){return Object.keys(e)[0]}function am(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 Ot=y(()=>{});function cm(e){let t=e.toLowerCase().trim();if(t.startsWith("_")||t.endsWith("[]"))return "TEXT";let r=QE[t];if(!r)throw new It(`Unsupported PostgreSQL type: "${e}"`);return r}function Us(e){let t=e.toLowerCase();return ["serial","serial4","bigserial","serial8","smallserial","serial2"].includes(t)}function Bs(e){let t=e.toLowerCase();return ["varchar","character varying","char","character","bpchar"].includes(t)}function qs(e){let t=e.toLowerCase();return ["numeric","decimal"].includes(t)}var It,B,QE,lm,ZE,Hs,ar=y(()=>{Ot();It=class extends Error{},B=class extends It{constructor(r,n){super(n??`Unsupported node type: ${or(r)}`);this.node=r;}},QE={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"},lm=["<",">","<=",">=","=","<>","!=","+","-","*","/","%","&","|","<<",">>","||","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","->>"];ZE={CreateEnumStmt:{react:"ignore"},CreateDomainStmt:{react:"warn"},CreateSeqStmt:{react:"error"},AlterSeqStmt:{react:"error"},CreateSchemaStmt:{react:"warn"},CreatePolicyStmt:{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"}},Hs=new Map(Object.entries(ZE));});var Fe,Yr,Ca=y(()=>{Ot();ar();Fe=class extends B{constructor(t,r){super(t,`Unsupported expression: ${r}`);}},Yr=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 Fe({[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 Fe({[r]:t},`deparseValue: ${r}`)}A_Expr(t){if(t.kind==="AEXPR_OP"){let r=t.name?.[0],n=r?Kr(r):void 0;if(!n)throw new Fe({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 Fe({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]?Kr(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 Fe({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 Fe({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 Fe({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),u=this.deparseGroupClause(t.groupClause),p={type:"query",from:r,select:i};return n&&(p.schema=n),Object.keys(s).length>0&&(p.join=s),o&&(p.where=o),a.length>0&&(p.order=a),l!==void 0&&(p.limit=l),c!==void 0&&(p.offset=c),u.length>0&&(p.group=u),p}FuncCall(t){let r=this.isAuthFunc(t.funcname??[]);if(r)return r;throw new Fe({FuncCall:t},`FuncCall: ${kt(t.funcname??[]).join(".")}`)}ColumnRef(t){let r=kt(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 Fe({A_Const:t},"A_Const: unknown variant")}TypeCast(t){if(!t.arg)throw new Fe({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 u=2;for(;`${c}_${u}`in r;)u++;c=`${c}_${u}`;}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=kt(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]?Kr(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 Jr,Ra=y(()=>{Jr=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 Xr,Pa=y(()=>{Xr=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=y(()=>{Pa();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 Xr(this.context.table,this.context.column,t,r)}quoteIfNeeded(t){return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)?t:`"${t}"`}};});var Lt,Ws=y(()=>{st();Lt=class extends we{get sqliteType(){return "INTEGER"}};});var Qr,ka=y(()=>{Ws();Qr=class extends Lt{constructor(t){super({...t,isSerial:true});}};});function e_(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 Dt,zs=y(()=>{st();Dt=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(!e_(t,this.numericPrecision))return this.validationFail(`Does not fit numeric(${r}, ${n}).`,"Patch rows within numeric precision.")}return this.validationPass()}};});var ae,Me=y(()=>{st();ae=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 Zr,Na=y(()=>{st();Zr=class extends we{get sqliteType(){return "BLOB"}};});var en,Oa=y(()=>{st();en=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){return this.isNullish(t)?t:t===1?true:t===0?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 um(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var tn,Ia=y(()=>{st();tn=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=um(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."):um(t).ok?this.validationPass():this.validationFail("Invalid JSON text.","Patch rows with valid JSON.")}};});function t_(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 rn,La=y(()=>{Me();rn=class extends ae{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"||!t_(t)?this.validationFail("Invalid date.","Patch rows with YYYY-MM-DD dates."):this.validationPass()}};});function r_(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 nn,Da=y(()=>{Me();nn=class extends ae{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"||!r_(t)?this.validationFail("Invalid time.","Patch rows with HH:MM[:SS] times."):this.validationPass()}};});function n_(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]),u=new Date(Date.UTC(r,n-1,s)),p=u.getUTCFullYear()===r&&u.getUTCMonth()===n-1&&u.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 p&&f&&h}var sn,ja=y(()=>{Me();sn=class extends ae{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"||!n_(t)?this.validationFail("Invalid timestamp.","Patch rows with ISO timestamps."):this.validationPass()}};});var on,Fa=y(()=>{Me();on=class extends ae{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 an,Ma=y(()=>{Me();an=class extends ae{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 pm(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var dt,Gs=y(()=>{st();dt=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=pm(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=pm(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 fm(e){return i_.test(e.toLowerCase())}var s_,i_,ln,Ua=y(()=>{Me();s_="????????-????-????-????-????????????",i_=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;ln=class extends ae{get isShimBacked(){return true}checkConstraint(){let t=this.quoteIfNeeded(this.context.column);return `${t} IS NULL OR ${t} GLOB '${s_}'`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string")throw this.checkError("uuid_format",t);let r=t.toLowerCase();if(!fm(r))throw this.checkError("uuid_format",t);return r}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!fm(t)?this.validationFail("Invalid UUID.","Patch rows with valid UUIDs."):this.validationPass()}};});function o_(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 a_(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 l_(e){if(!e.includes(":"))return false;try{return new URL(`http://[${e}]/`),!0}catch{return false}}function mm(e){let t=o_(e);return t?a_(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=32:l_(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=128:false:false}var cn,Ba=y(()=>{Me();cn=class extends ae{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(!mm(r))throw this.checkError("inet_format",t);return r}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!mm(t.trim())?this.validationFail("Invalid inet address.","Patch rows with valid inet strings."):this.validationPass()}};});var un,qa=y(()=>{Me();un=class extends ae{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 jt(e,t){if(t?.isArray){let n=jt(e,{...t,isArray:false});return new dt(e,n)}if(t?.enumValues)return new an(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=jt(s);return new dt(e,i)}return u_.has(r)?new Qr(e):c_.has(r)?new Lt(e):d_.has(r)?new en(e):h_.has(r)?new tn(e):b_.has(r)?new rn(e):S_.has(r)?new nn(e):E_.has(r)?new sn(e):__.has(r)?new on(e):m_.has(r)?new Zr(e):p_.has(r)?new Dt(e,t?.numericPrecision):g_.has(r)?new ln(e):y_.has(r)?new ae(e,63):w_.has(r)?new cn(e):f_.has(r)?new ae(e,t?.lengthConstraint):new un(e)}var c_,u_,p_,f_,m_,d_,h_,g_,y_,w_,b_,S_,E_,__,Ha=y(()=>{Ws();ka();zs();Me();Na();Oa();Ia();La();Da();ja();Fa();Ma();Gs();Ua();Ba();qa();c_=new Set(["int2","smallint","int4","integer","int","int8","bigint"]),u_=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]),p_=new Set(["float4","real","float8","double precision","numeric","decimal"]),f_=new Set(["text","varchar","character varying","char","character","bpchar"]),m_=new Set(["bytea"]),d_=new Set(["bool","boolean"]),h_=new Set(["json","jsonb"]),g_=new Set(["uuid"]),y_=new Set(["name"]),w_=new Set(["inet"]),b_=new Set(["date"]),S_=new Set(["time","timetz","time without time zone","time with time zone"]),E_=new Set(["timestamp","timestamptz","timestamp without time zone","timestamp with time zone"]),__=new Set(["interval"]);});function Wa(e,t="auto"){let r=e.toLowerCase(),n=Vs[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 dm,Vs,za=y(()=>{dm="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)))",Vs={gen_random_uuid:{sqlite:()=>dm,js:()=>crypto.randomUUID()},uuid_generate_v4:{sqlite:()=>dm,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 pn,hm=y(()=>{pn=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 gm=y(()=>{st();Pa();Ws();ka();zs();Me();Na();Oa();Ia();La();Da();ja();Fa();Ma();Gs();Ua();Ba();qa();Ha();za();hm();});var Za={};de(Za,{_resetWarnedMissingToClauseForTests:()=>x_,collectComments:()=>Qa,collectEnums:()=>Va,collectPolicies:()=>Ya,collectSchema:()=>Ja,collectTableConstraints:()=>Xa,collectVariables:()=>Ka});function x_(){Ga.clear();}function Va(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=kt(n.typeName??[]).join(".");if(!s||!n.vals)continue;let i=kt(n.vals);t.set(s.toLowerCase(),i);}return t}function Ka(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=am(n.args?.[0]??{});t.set(s,{value:i,local:n.is_local});}return t}function Ya(e){let t=new Yr,r=new Set,n=[];for(let s of e.stmts??[])if(s.stmt){if("CreatePolicyStmt"in s.stmt){let i=s.stmt.CreatePolicyStmt,o=i.table?.relname??"",a=i.table?.schemaname,l={select:"SELECT",insert:"INSERT",update:"UPDATE",delete:"DELETE"},c=i.cmd_name?l[i.cmd_name]??"ALL":"ALL",u=i.permissive===true,p=[],f=false;for(let b of i.roles??[])if("RoleSpec"in b){let g=b.RoleSpec;g.roletype==="ROLESPEC_PUBLIC"?g.location===-1&&(f=true):g.roletype==="ROLESPEC_CSTRING"&&g.rolename&&p.push(g.rolename);}if(f){let b=a?`${a}.${o}`:o,g=i.policy_name??"",S=`${b}::${g}`;Ga.has(S)||(Ga.add(S),console.warn(`[supalite] policy "${g}" on "${b}" has no TO clause \u2014 applies to all roles (PUBLIC). For clarity, prefer an explicit \`TO <role>\` clause (e.g. \`TO authenticated\`).`));}let h=i.qual?t.deparse(i.qual):void 0,d=i.with_check?t.deparse(i.with_check):void 0,m=new Jr({name:i.policy_name??"",table:o,schema:a,command:c,permissive:u,roles:p,using:h,withCheck:d});n.push(m);}if("AlterTableStmt"in s.stmt){let i=s.stmt.AlterTableStmt;if((i.cmds??[]).some(l=>"AlterTableCmd"in l&&(l.AlterTableCmd.subtype==="AT_EnableRowSecurity"||l.AlterTableCmd.subtype==="AT_ForceRowSecurity"))){let l=i.relation?.relname??"";r.add(l);}}}return {policies:n,tables:r}}function Ja(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 pn(i,o);for(let l of s.tableElts??[]){if(!("ColumnDef"in l))continue;let c=l.ColumnDef,u=c.colname;if(!u)continue;let p=c.typeName?.names?.map(T=>T.String?.sval||T.String?.str).filter(Boolean),f=p&&(p.length===2&&p[0]==="pg_catalog"?p[1]:p[0]);if(!f)continue;let h=!!c.typeName?.arrayBounds?.length,d=Array.isArray(c.typeName?.typmods)?c.typeName.typmods:[],m=T=>d[T]?.A_Const?.ival?.ival??d[T]?.A_Const?.val?.ival?.ival,b={isArray:h};if(Bs(f)&&d.length>0){let T=m(0);typeof T=="number"&&T>0&&(b.lengthConstraint=T);}if(qs(f)&&d.length>=2){let T=m(0),q=m(1);typeof T=="number"&&typeof q=="number"&&T>0&&q>=0&&(b.numericPrecision={precision:T,scale:q});}let g=t.get(f.toLowerCase());g&&(b.enumValues=g);let S=Array.isArray(c.constraints)?c.constraints:[],A=S.some(T=>T.Constraint?.contype==="CONSTR_PRIMARY"),v=Us(f)||S.some(T=>T.Constraint?.contype==="CONSTR_IDENTITY"),k=S.some(T=>T.Constraint?.contype==="CONSTR_NOTNULL"),N=S.find(T=>T.Constraint?.contype==="CONSTR_UNIQUE"),$=S.find(T=>T.Constraint?.contype==="CONSTR_GENERATED"),x=S.find(T=>T.Constraint?.contype==="CONSTR_FOREIGN"),I=S.find(T=>T.Constraint?.contype==="CONSTR_CHECK"),w;if(x){let T=x.Constraint,q=T.pktable?.relname,E=T.pktable?.schemaname,_=T.pk_attrs?.[0]?.String?.sval;q&&_&&(w={refSchema:E,refTable:q,refColumn:_,constraintName:T.conname||void 0});}let L={schema:o,table:i,column:u,pgTypeName:f,nullable:!k&&!A,defaultValue:null,defaultFn:null,isPrimaryKey:A,isUnique:!!N,isSerial:v,isGenerated:!!$,fkRef:w,hasCheck:!!I,checkConstraintName:I?.Constraint?.conname||void 0,uniqueConstraintName:N?.Constraint?.conname||void 0};a.set(u,jt(L,b));}r.set(`${o}.${i}`,a);}return r}function Xa(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 u=(l.keys??[]).map(p=>p.String?.sval??p.String?.str).filter(Boolean);if(u.length===0)continue;t.push({schema:i,table:s,kind:"unique",name:l.conname||void 0,columns:u});}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 u=(l.fk_attrs??[]).map(h=>h.String?.sval??h.String?.str).filter(Boolean),p=(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:u,refSchema:l.pktable?.schemaname,refTable:f,refColumns:p});}}}return t}function Qa(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 Ga,el=y(()=>{Ca();Ot();Ra();gm();ar();Ga=new Set;});async function mn(e,t){let r=await e.connection.introspect(),n=tl(r);await _m(e,{...t,dbHasTables:r.tables.length>0,dbFingerprint:n}),r.tables.length===0&&await rl(e);let s=await e.connection.introspect();vm(s,e);}async function $_(e){let t=await Wr(e.config.db?.seed?.sql_paths??["./seed.sql"],{cwd:z__default.join(process.cwd(),"supabase"),absolute:true});return (await Promise.all(t.map(n=>fe__default.readFile(n,"utf-8")))).flatMap(n=>splitSqlStatements(n))}async function dn(e,t){let r=await $_(e);if(r.length===0)return 0;console.log(F.default.dim("Seeding database..."));try{return await e.connection.transaction(r),r.length}catch(n){let s=t?.recoveryHint??"Fix `supabase/seed.sql`, then run `bun run dev --recreate` to reset and reseed.";throw new Error(`Seed failed and was rolled back: ${String(n.message??n)}
|
|
64
|
-
${s}`)}}async function
|
|
60
|
+
`)}function Kn(e){let t=[],r="",n=0,s=e.length,i=o=>{dg(o).length>0&&t.push(o.trim());};for(;n<s;){let o=e[n],a=e[n+1];if(o==="-"&&a==="-"){for(;n<s&&e[n]!==`
|
|
61
|
+
`;)r+=e[n],n++;continue}if(o==="/"&&a==="*"){for(r+="/*",n+=2;n<s&&!(e[n]==="*"&&e[n+1]==="/");)r+=e[n],n++;n<s&&(r+="*/",n+=2);continue}if(o==="'"){for(r+=o,n++;n<s;){if(e[n]==="'"&&e[n+1]==="'"){r+="''",n+=2;continue}if(r+=e[n],e[n]==="'"){n++;break}n++;}continue}if(o==='"'){for(r+=o,n++;n<s;){if(e[n]==='"'&&e[n+1]==='"'){r+='""',n+=2;continue}if(r+=e[n],e[n]==='"'){n++;break}n++;}continue}if(o==="$"){let l=e.indexOf("$",n+1);if(l!==-1){let c=e.slice(n,l+1);if(/^\$[A-Za-z_][A-Za-z0-9_]*\$$|^\$\$$/.test(c)){r+=c,n=l+1;let p=e.indexOf(c,n);p===-1?(r+=e.slice(n),n=s):(r+=e.slice(n,p+c.length),n=p+c.length);continue}}}if(o===";"){i(r),r="",n++;continue}r+=o,n++;}return i(r),t}function dg(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 Gi(e){return (e??"").trim().toLowerCase()}function zi(e){return (e??"").replace(/\s+/g," ").replace(/"/g,"").trim().toLowerCase()}function Vi(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 _r=y(()=>{});function hg(e,t,r=void 0){let n=typeof t=="string"?vc(t):Xi(t);return Yn(e,n,r)}function Yn(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:Yn(e[s],i,r)}catch{if(typeof r<"u")return r;throw new Error(`Invalid path: ${n.join(".")}`)}}function wg(e){return e===null}function me(e){return !Array.isArray(e)&&typeof e=="object"&&e!==null}function bg(e){return Object.prototype.toString.call(e)==="[object Object]"}function Ge(e){return typeof e=="string"}function Xe(e){return typeof e=="number"}function Sg(e){return typeof e=="number"&&Number.isInteger(e)}function Zi(e){return typeof e=="boolean"}function ot(e){return Array.isArray(e)}function Eg(e){return typeof e!="boolean"}function xg(e){return e!==void 0&&Eg(e)&&"type"in e}function ve(e){return e!==void 0&&me(e)&&$e in e}function _g(e){return ve(e)&&typeof e.toJSON()=="boolean"}function $g(e,t,r){if(!e)throw new yg(t,r)}function Tc(e){return Ge(e)?e.normalize("NFC"):e}function $r(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(!$r(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(!$r(e[i],t[i]))return false;return true}return e===t}function vg(e,t){return t.reduce((r,n)=>(n in e&&(r[n]=e[n]),r),{})}function Ac(e){try{return structuredClone(e)}catch{return e}}function Tg(e,t,r={}){let n=t;try{n=structuredClone(t);}catch{n=JSON.parse(JSON.stringify(t));}let s={resolver:r.resolver||new eo(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 Qn(e,t,r={}){return e.map(n=>n.validate(t,Xn(r)).valid?n:void 0).filter(Boolean)}function iy(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 eo(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=Ki[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 Ki&&e[o]!==void 0){if(s===void 0)continue;let a=Ki[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 Zn(e,t,r){return new class extends Ye{type=e}(t,r)}function Yi(e){return new oy(e)}function _c(e,t){return Array.isArray(e)?e.map(t):e!==void 0?[t(e)]:[]}function $c(e,t,r=n=>n){return Object.fromEntries(Object.entries(e).map(([n,s])=>[n,r(t(s,n),n)]))}function Gt(e){if(Zi(e))return Yi(e);let t=structuredClone(e);if(!me(t))throw new gg("non-object schemas cannot be converted to a schema",t);"properties"in t&&t.properties&&(t.properties=$c(t.properties,(i,o)=>{try{return Gt(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]=$c(t[i],Gt));let n=["additionalProperties","items","prefixItems","propertyNames","contains","not","if","then","else"];for(let i of n)i in t&&typeof t[i]<"u"&&(ot(t[i])?t[i]=_c(t[i],Gt):t[i]=Gt(t[i]));let s=["anyOf","oneOf","allOf"];for(let i of s)if(i in t){let{[i]:o}=t;t[i]=_c(o,Gt);}if(xg(t))switch(t.type){case "string":return Rc(t);case "number":return Pc(t);case "integer":return Nc(t);case "boolean":return Lc(t);case "object":{let{properties:i,...o}=t;return es(i,o)}case "array":{let{items:i,...o}=t;return Oc(i,o)}}return Cc(t)}function by(){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(yy.map(e=>[e,t=>Math.min(...t)])),...Object.fromEntries(wy.map(e=>[e,t=>Math.max(...t)]))}}function Sy(e){let t={...by(),...e.resolvers};function r(n,s){if(Array.isArray(n)&&Array.isArray(s))return [...new Set([...n,...s])];if(Qi(n)&&Qi(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):Ji(a);}else i[o]=Ji(a);return i}return Ji(s)}return r}function xy(e,t={}){let r=t.deep!==false,n=Sy(t);function s(i){if(Array.isArray(i))return i.map(s);if(!Qi(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),{}),u=Ey(c);if(u!==null)return u;let p={...i};delete p.allOf;let f=n(c,r?s(p):p);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 Xi,vc,Q,D,zt,Xn,Et,gg,yg,$e,eo,Ag,Cg,Rg,kg,Pg,Ng,Og,Lg,Ig,Dg,jg,Fg,Mg,Ug,Bg,qg,Hg,Wg,Gg,zg,Vg,Kg,Jg,Xg,Yg,Qg,Zg,ey,ty,ry,ny,xc,sy,Ki,Ye,vr,oy,Cc,ay,ly,es,cy,uy,py,fy,my,Rc,kc,Pc,Nc,dy,Oc,Lc,Jn,Ic,hy,gy,Qi,Ji,yy,wy,Ey,_y,Dc,$y,vy,Ty,jc,Fc=y(()=>{Xi=(e=[],t="")=>"/"+[t,...e.map(r=>String(r).replace(/\./g,"/"))].filter(Boolean).join("/"),vc=e=>e.split("/").slice(1);Q=(e={},t,r,n)=>({valid:false,errors:[...e.errors??[],{keywordLocation:Xi([...e.keywordPath??[],t]),instanceLocation:Xi(e.instancePath),error:typeof r=="string"?r:`Invalid value for ${t}`,data:n}]}),D=()=>({valid:true,errors:[]}),zt=(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}},Xn=(e={})=>({...e,errors:[]}),Et=class extends Error{constructor(e){super(`Expected ${e}`);}},gg=class extends Error{constructor(e,t){super(`${e??"Invalid raw schema"}: ${JSON.stringify(t)}`),this.schema=t;}},yg=class extends Error{constructor(e,t){super(`${e}, got: 'type "${typeof t}": ${JSON.stringify(t)}'`),this.value=t;}},$e=Symbol.for("jsonv-ts:schema");eo=class{constructor(e){this.root=e,this.cache=new Map;}cache;hasRef(e,t){return t!==void 0&&"$ref"in e&&Ge(e.$ref)}resolve(e){let t=this.cache.get(e);if(!t){if(t=hg(this.root,e),!ve(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}};Ag=({type:e},t,r={})=>{if(e===void 0||t===void 0)return D();let n,s={string:Ge,number:Xe,integer:Sg,object:me,array:ot,boolean:Zi,null:wg};if(Array.isArray(e)){for(let i of e){if(!(i in s))throw new Et(`Unknown type: ${i}`);if(s[i](t))return D()}n=`Expected one of: ${e.join(", ")}`;}else {if(!(e in s))throw new Et(`Unknown type: ${e}`);s[e](t)||(n=`Expected ${e}`);}return n?Q(r,"type",n,t):D()},Cg=({const:e},t,r={})=>$r(e,t)?D():Q(r,"const",`Expected const: ${e}`,t),Rg=({enum:e=[]},t,r={})=>e.some(n=>$r(n,t))?D():Q(r,"enum",`Expected enum: ${JSON.stringify(e)}`,t);kg=({anyOf:e=[]},t,r={})=>Qn(e,t,r).length>0?D():Q(r,"anyOf","Expected at least one to match",t),Pg=({oneOf:e=[]},t,r={})=>Qn(e,t).length===1?D():Q(r,"oneOf","Expected exactly one to match",t),Ng=({allOf:e=[]},t,r={})=>Qn(e,t,r).length===e.length?D():Q(r,"allOf","Expected all to match",t),Og=({not:e},t,r={})=>t===void 0?D():ve(e)&&e.validate(t,r).valid?Q(r,"not","Expected not to match",t):D(),Lg=({if:e,then:t,else:r},n,s={})=>{if(e&&(t||r)){if(e.validate(n,Xn(s)).valid)return t?t.validate(n,Xn(s)):D();if(r)return r.validate(n,Xn(s))}return D()},Ig=({pattern:e=""},t,r={})=>{if(!Ge(t))return D();if(e instanceof RegExp){if(e.test(t))return D()}else if(new RegExp(e,"u").test(t))return D();return Q(r,"pattern",`Expected string matching pattern ${e}`,t)},Dg=({minLength:e=0},t,r={})=>Ge(t)?[...Tc(t)].length>=e?D():Q(r,"minLength",`Expected string with minimum length of ${e}`,t):D(),jg=({maxLength:e=0},t,r={})=>Ge(t)?[...Tc(t)].length<=e?D():Q(r,"maxLength",`Expected string with maximum length of ${e}`,t):D(),Fg=({multipleOf:e=0},t,r={})=>{if(!Xe(t))return D();if(!(Number.isFinite(t)&&Number.isFinite(e))||e<=0)throw new Et("number");let n=t/e,s=Number.EPSILON*Math.max(1,Math.abs(n));return Math.abs(n-Math.round(n))<=s?D():Q(r,"multipleOf",`Expected number being a multiple of ${e}`,t)},Mg=({maximum:e=0},t,r={})=>!Xe(t)||t<=e?D():Q(r,"maximum",`Expected number less than or equal to ${e}`,t),Ug=({exclusiveMaximum:e=0},t,r={})=>!Xe(t)||t<e?D():Q(r,"exclusiveMaximum",`Expected number less than ${e}`,t),Bg=({minimum:e=0},t,r={})=>!Xe(t)||t>=e?D():Q(r,"minimum",`Expected number greater than or equal to ${e}`,t),qg=({exclusiveMinimum:e=0},t,r={})=>!Xe(t)||t>e?D():Q(r,"exclusiveMinimum",`Expected number greater than ${e}`,t),Hg=({properties:e={}},t,r={})=>{if(!me(t))return D();for(let[n,s]of Object.entries(t)){let i=e[n];if(!ve(i))continue;let o=i.validate(s,zt(r,["properties",n],n));if(!o.valid)return o}return D()},Wg=({properties:e={},additionalProperties:t,patternProperties:r},n,s={})=>{if(!me(n))return D();if(!ve(t))throw new Et("additionalProperties must be a boolean or a managed schema");let i=Object.keys(e),o=me(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(_g(t)){if(t.toJSON()===true)return D();let l=a.reduce((c,u)=>(c[u]=n[u],c),{});return Q(s,"additionalProperties","Additional properties are not allowed",l)}else if(ve(t))for(let l of a){let c=t.validate(n[l],zt(s,["additionalProperties"],l));if(!c.valid)return c}}return D()},Gg=({dependentRequired:e},t,r={})=>{if(!me(t))return D();let n=Object.keys(t).filter(s=>typeof t[s]!="function");if(me(e)){for(let[s,i]of Object.entries(e))if(n.includes(s)){for(let o of i)if(!n.includes(o))return Q(r,"dependentRequired",`Expected dependent required property ${o}`,t)}}return D()},zg=({required:e=[]},t,r={})=>{if(!me(t))return D();let n=Object.keys(t).filter(s=>typeof t[s]!="function");return e.every(s=>n.includes(s))?D():Q(r,"required",`Expected object with required properties ${e.join(", ")}`,t)},Vg=({dependentSchemas:e},t,r={})=>{if(!me(t))return D();let n=Object.keys(t).filter(s=>typeof t[s]!="function");if(me(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 D()},Kg=({minProperties:e=0},t,r={})=>me(t)?Object.keys(t).length>=e?D():Q(r,"minProperties",`Expected object with at least ${e} properties`,t):D(),Jg=({maxProperties:e=0},t,r={})=>!me(t)||Object.keys(t).length<=e?D():Q(r,"maxProperties",`Expected object with at most ${e} properties`,t),Xg=({patternProperties:e={}},t,r={})=>{if(!me(t))return D();if(!me(e))throw new Et("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,zt(r,["patternProperties"],n));if(!a.valid)return a}return D()},Yg=({propertyNames:e},t,r={})=>{if(!me(t)||e===void 0)return D();if(!ve(e))throw new Et("propertyNames must be a managed schema");for(let n of Object.keys(t)){let s=e.validate(n,zt(r,["propertyNames"],n));if(!s.valid)return s}return D()},Qg=({items:e,prefixItems:t=[]},r,n={})=>{if(!ot(r)||e===void 0)return D();if(!ve(e))throw new Et("items must be a managed schema");for(let[s,i]of r.slice(t.length).entries()){let o=e.validate(i,zt(n,["items"],String(s)));if(!o.valid)return o}return D()},Zg=({minItems:e=0},t,r={})=>!ot(t)||t.length>=e?D():Q(r,"minItems",`Expected array with at least ${e} items`,t),ey=({maxItems:e=0},t,r={})=>!ot(t)||t.length<=e?D():Q(r,"maxItems",`Expected array with at most ${e} items`,t),ty=({uniqueItems:e=false},t,r={})=>{if(!ot(t)||!e)return D();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($r(s,o))return Q(r,"uniqueItems",`Duplicated items at index ${n} and ${i}`,t)}}return D()},ry=({contains:e,minContains:t,maxContains:r},n,s={})=>{if(!ve(e))throw new Error("contains must be a managed schema");if(!ot(n))return D();let i=n.filter(o=>e.validate(o).valid).length;return i<(t??1)?Q(s,t?"minContains":"contains",`Expected array to contain at least ${t??1}, but found ${i}`,n):r!==void 0&&i>r?Q(s,"maxContains",`Expected array to contain at most ${r}, but found ${i}`,n):D()},ny=({prefixItems:e=[]},t,r={})=>{if(!ot(t))return D();for(let n=0;n<t.length;n++){let s=e[n]?.validate(t[n],zt(r,String(n),String(n)));if(s&&s?.valid!==true)return s}return D()},xc={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 u=e.charCodeAt(c);if(c===1&&o===58&&u!==58)return false;if(u>=48&&u<=57){if(++n>4)return false}else if(u===46){if(t>6||r>=3||n===0||i)return false;r++,n=0;}else if(u===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(u>=97&&u<=102||u>=65&&u<=70){if(r>0||++n>4)return false;i=true;}else return false;o=u;}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},sy=({format:e},t,r={})=>!Ge(t)||!e?D():xc[e]?xc[e](t)?D():Q(r,"format",`Expected format: ${e}`,t):D(),Ki={type:Ag,const:Cg,enum:Rg,allOf:Ng,anyOf:kg,oneOf:Pg,not:Og,minLength:Dg,maxLength:jg,pattern:Ig,format:sy,minimum:Bg,exclusiveMinimum:qg,maximum:Mg,exclusiveMaximum:Ug,multipleOf:Fg,required:zg,dependentRequired:Gg,dependentSchemas:Vg,minProperties:Kg,maxProperties:Jg,propertyNames:Yg,properties:Hg,patternProperties:Xg,additionalProperties:Wg,minItems:Zg,maxItems:ey,uniqueItems:ty,contains:ry,prefixItems:ny,items:Qg,if:Lg};Ye=class{"~standard";[$e];_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[$e]={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:vc(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[$e].raw?.template){let i=this[$e].raw.template(n,t);i!==void 0&&(n=i);}let s=this[$e].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[$e].raw?.validate;if(n!==void 0){let s=n(e,r);if(!s.valid)return s}return iy(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[$e].raw?.coerce;if(n!==void 0)return n(e,r);let s=this[$e].overrides?.coerce?.(e,r)??e;return Tg(this,s,r)}optional(){return this[$e].optional=true,this}isOptional(){return this[$e].optional}getResolver(){return this._resolver||(this._resolver=new eo(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?Ac(r):r;if(s.includeSelf!==false&&(yield new vr(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))}},vr=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=Yn(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}};oy=class extends Ye{constructor(e){super(),this.bool=e;}toJSON(){return this.bool}validate(e,t){return this.bool?D():Q(t,"","Always fails",e)}};Cc=e=>Zn(e?.type,e),ay=(e,t)=>Zn(void 0,{...t,const:e}),ly=class extends Ye{type="object";properties;required;constructor(e,t){let r=[];for(let[s,i]of Object.entries(e||{}))$g(ve(i),"properties must be managed schemas",i),i[$e].optional||r.push(s);let n=t?.additionalProperties===false?Yi(false):t?.additionalProperties;r=r.length>0?r:void 0,super({...t,additionalProperties:n,properties:e,required:r},{template:(s,i)=>{let o=structuredClone(me(s)?s:{}),a={...o};if(this.properties)for(let[l,c]of Object.entries(this.properties)){let u=Yn(o,l);if(c.isOptional()&&i?.withOptional!==true&&u===void 0&&s===void 0)continue;let p=c.template(u,i);p!==void 0&&(a[l]=p);}if(!(Object.keys(a).length===0&&!i?.withExtendedOptional))return a},coerce:(s,i)=>{let o=Object.keys(this.properties),a=Ac(s),l=o.length>0&&Object.values(this.properties).every(u=>!u[$e].optional);if(bg(a)&&(i?.dropUnknown===true||l)&&(a=vg(a,o)),typeof a=="string"&&a.match(/^\{/)&&(a=JSON.parse(a)),typeof a!="object"||a===null)return;if(this.properties)for(let[u,p]of Object.entries(this.properties)){let f=a[u];f!==void 0&&(a[u]=p.coerce(f,i));}let c=this.additionalProperties;if(i?.dropUnknown!==true&&(!c||c.validate(null).valid)){let u=me(s)?s:{},p=Object.keys(u).filter(f=>!o.includes(f));for(let f of p)a[f]=c?c.coerce(u[f],i):u[f];}return a}}),this.properties=e,this.required=r;}strict(){return this.additionalProperties=Yi(false),this[$e].raw.additionalProperties=false,this}partial(){for(let[,e]of Object.entries(this.properties))e[$e].optional=true;return this.required=void 0,this}children(e){let t=[];for(let[r,n]of Object.entries(this.properties)){let s=new vr(n,e);s.appendInstancePath([r]),s.appendKeywordPath(["properties",r]),t.push(s);}return t}},es=(e,t)=>new ly(e,t),cy=(e,t)=>es(e,t).strict(),uy=(e,t)=>es(e,t).partial(),py=class extends Ye{type="object";additionalProperties;constructor(e,t){super({...t,additionalProperties:e},{template:(r,n)=>n?.withExtendedOptional&&(r===void 0||!me(r))?{}:r}),this.additionalProperties=e;}children(e){let t=[],r=new vr(this.additionalProperties,e);return r.appendKeywordPath(["additionalProperties"]),t.push(r),t}},fy=(e,t)=>new py(e,t),my=class extends Ye{type="string";constructor(e){super(e,{template:(t,r)=>r?.withExtendedOptional&&(t===void 0||!Ge(t))?"":t,coerce:t=>Xe(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}))}},Rc=e=>new my(e),kc=(e,t,r)=>Zn(e,r,{template:(n,s)=>s?.withExtendedOptional&&(n===void 0||!Xe(n))?r?.minimum??0:n,coerce:n=>{if(Ge(n)){let s=t.parseFn(n);if(!Number.isNaN(s))return s}return n}}),Pc=e=>kc("number",{parseFn:Number},e),Nc=e=>kc("integer",{parseFn:Number.parseInt},e),dy=class extends Ye{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(ve(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 vr(this.items,e);r.appendKeywordPath(["items"]),t.push(r);}return t}},Oc=(e,t)=>new dy(e,t),Lc=e=>Zn("boolean",e,{template:(t,r)=>r?.withExtendedOptional&&(t===void 0||!Zi(t))?false:t,coerce:t=>{if(Ge(t)&&["true","false","1","0"].includes(t))return t==="true"||t==="1";if(Xe(t)){if(t===1)return true;if(t===0)return false}return t}}),Jn=Symbol.for("unionType"),Ic=class extends Ye{[Jn];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=Qn(e,n,{ignoreUnsupported:true,resolver:s?.resolver,coerce:true});return o.length>0?o[0].coerce(n,s):n}}),this[Jn]=t;}get schemas(){return this[this[Jn]]}children(e){let t=[];for(let[r,n]of this.schemas.entries()){let s=new vr(n,e);s.appendKeywordPath([this[Jn],r]),t.push(s);}return t}},hy=(e,t)=>new Ic(e,"anyOf",t),gy=(e,t)=>new Ic(e,"oneOf",t);Qi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ji=e=>typeof globalThis.structuredClone=="function"?globalThis.structuredClone(e):JSON.parse(JSON.stringify(e)),yy=["maximum","exclusiveMaximum","maxLength","maxItems","maxProperties"],wy=["minimum","exclusiveMinimum","minLength","minItems","minProperties"];Ey=e=>e===true||e===false?e:null;_y=(e,t)=>{let r=JSON.parse(JSON.stringify({...t,allOf:e}));return Gt(xy(r))},Dc=class extends Ye{$ref;constructor(e,t){if(!t&&!ve(e))throw new Error("Ref not set");if(ve(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(!ve(i))throw new Error(`Ref not found: ${this.$ref}`);return i.coerce(n,s)}}),this.$ref=r;}},$y=(e,t)=>new Dc(e,t),vy=e=>new Dc(void 0,e),Ty=e=>e(new Ye({$ref:"#",coerce:(t,r)=>{let n=r?.resolver?.resolve("#");if(!ve(n))throw new Error("Ref not found: #");return n.coerce(t,r)}})),jc={boolean:Lc,any:Cc,literal:ay,object:es,strictObject:cy,partialObject:uy,record:fy,string:Rc,number:Pc,integer:Nc,array:Oc,anyOf:hy,oneOf:gy,allOf:_y,ref:$y,refId:vy,recursive:Ty};});function Mc(e,t){if(typeof e!="string"){throw new Error("Email must be a string");}if(!jc.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 Uc(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 M(e,t='"'){return `${t}${e}${t}`}function Bc(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 Tr=y(()=>{Fc();});function to(e){return typeof e=="number"?e:Number.parseInt(String(e),10)}var qc=y(()=>{});var Hc=y(()=>{});var at=y(()=>{gc();yc();wc();bc();Sc();_r();Tr();qc();Hc();});var ro,Wc=y(()=>{ro=(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,u;if(e[a]?(u=e[a][0][0],n.req.routeIndex=a):u=a===e.length&&s||void 0,u)try{l=await u(n,()=>o(a+1));}catch(p){if(p instanceof Error&&t)n.error=p,l=await t(p,n),c=true;else throw p}else n.finalized===false&&r&&(l=await r(n));return l&&(n.finalized===false||c)&&(n.res=l),n}};});var Gc=y(()=>{});var zc,Vc=y(()=>{zc=Symbol();});async function Ay(e,t){let r=await e.formData();return r?Cy(r,t):{}}function Cy(e,t){let r=Object.create(null);return e.forEach((n,s)=>{t.all||s.endsWith("[]")?Ry(r,s,n):r[s]=n;}),t.dot&&Object.entries(r).forEach(([n,s])=>{n.includes(".")&&(ky(r,n,s),delete r[n]);}),r}var Kc,Ry,ky,Jc=y(()=>{no();Kc=async(e,t=Object.create(null))=>{let{all:r=false,dot:n=false}=t,i=(e instanceof ts?e.raw.headers:e.headers).get("Content-Type");return i?.startsWith("multipart/form-data")||i?.startsWith("application/x-www-form-urlencoded")?Ay(e,{all:r,dot:n}):{}};Ry=(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;},ky=(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 io,Xc,Py,Ny,rs,Yc,ns,Oy,oo,Qc,xt,ss,so,Zc,eu,tu,ao,Vt=y(()=>{io=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},Xc=e=>{let{groups:t,path:r}=Py(e),n=io(r);return Ny(n,t)},Py=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let s=`@${n}`;return t.push([s,r]),s}),{groups:t,path:e}},Ny=(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},rs={},Yc=(e,t)=>{if(e==="*")return "*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${e}#${t}`;return rs[n]||(r[2]?rs[n]=t&&t[0]!==":"&&t[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)]:rs[n]=[e,r[1],true]),rs[n]}return null},ns=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return t(r)}catch{return r}})}},Oy=e=>ns(e,decodeURI),oo=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 Oy(l.includes("%25")?l.replace(/%25/g,"%2525"):l)}else if(s===63||s===35)break}return t.slice(r,n)},Qc=e=>{let t=oo(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},xt=(e,t,...r)=>(r.length&&(t=xt(t,...r)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),ss=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?ns(e,ao):e):e,Zc=(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},eu=Zc,tu=(e,t)=>Zc(e,t,true),ao=decodeURIComponent;});var ru,ts,no=y(()=>{Gc();Vc();Jc();Vt();ru=e=>ns(e,ao),ts=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)?ru(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)?ru(n):n);}return e}#s(e){return this.#t[1]?this.#t[1][e]:e}query(e){return eu(this.url,e)}queries(e){return tu(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 Kc(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[zc](){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 nu,su,lo,co=y(()=>{nu={Stringify:1,BeforeStream:2,Stream:3},su=(e,t)=>{let r=new String(e);return r.isEscaped=true,r.callbacks=t,r},lo=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=>lo(l,t,false,n,s))).then(()=>s[0]));return r?su(await o,i):o};});var Ly,uo,Ar,iu,ou=y(()=>{no();co();Ly="text/plain; charset=UTF-8",uo=(e,t)=>({"Content-Type":e,...t}),Ar=(e,t)=>new Response(e,t),iu=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 ts(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||=Ar(null,{headers:this.#a??=new Headers})}set res(e){if(this.#n&&e){e=Ar(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=Ar(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 Ar(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,uo(Ly,r));json=(e,t,r)=>this.#o(JSON.stringify(e),t,uo("application/json",r));html=(e,t,r)=>{let n=s=>this.#o(s,t,uo("text/html; charset=UTF-8",r));return typeof e=="object"?lo(e,nu.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??=()=>Ar(),this.#c(this))};});var te,au,lu,is,os,lt=y(()=>{te="ALL",au="all",lu=["get","post","put","delete","options","patch"],is="Can not add a route since the matcher is already built.",os=class extends Error{};});var Cr,po=y(()=>{Cr="__COMPOSED_HANDLER";});var Iy,cu,uu,fu=y(()=>{Wc();ou();lt();po();Vt();Iy=e=>e.text("404 Not Found",404),cu=(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)},uu=class pu{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(t={}){[...lu,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(u=>{this.#i(c.toUpperCase(),this.#e,u);});}return this},this.use=(i,...o)=>(typeof i=="string"?this.#e=i:(this.#e="*",o.unshift(i)),o.forEach(a=>{this.#i(te,this.#e,a);}),this);let{strict:n,...s}=t;Object.assign(this,s),this.getPath=n??true?t.getPath??oo:Qc;}#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=Iy;errorHandler=cu;route(t,r){let n=this.basePath(t);return r.routes.map(s=>{let i;r.errorHandler===cu?i=s.handler:(i=async(o,a)=>(await ro([],r.errorHandler)(o,()=>s.handler(o,a))).res,i[Cr]=s.handler),n.#i(s.method,s.path,i);}),this}basePath(t){let r=this.#t();return r._basePath=xt(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=xt(this._basePath,t),c=l==="/"?0:l.length;return u=>{let p=new URL(u.url);return p.pathname=p.pathname.slice(c)||"/",new Request(p,u)}})();let a=async(l,c)=>{let u=await r(s(l.req.raw),...o(l));if(u)return u;await c();};return this.#i(te,xt(t,"*"),a),this}#i(t,r,n){t=t.toUpperCase(),r=xt(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 iu(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(u){return this.#s(u,a)}return c instanceof Promise?c.then(u=>u||(a.finalized?a.res:this.#r(a))).catch(u=>this.#s(u,a)):c??this.#r(a)}let l=ro(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${xt("/",t)}`,r),n,s));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method));});}};});function fo(e,t){let r=this.buildAllMatchers(),n=((s,i)=>{let o=r[s]||r[te],a=o[2][i];if(a)return a;let l=i.match(o[0]);if(!l)return [[],as];let c=l.indexOf("",1);return [o[1][c],l]});return this.match=n,n(e,t)}var as,mo=y(()=>{lt();as=[];});function jy(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===Rr||e===kr?1:t===Rr||t===kr?-1:e===ls?1:t===ls?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var ls,Rr,kr,_t,Dy,mu,go=y(()=>{ls="[^/]+",Rr=".*",kr="(?:|/.*)",_t=Symbol(),Dy=new Set(".\\+*[^]$()");mu=class ho{#e;#t;#r=Object.create(null);insert(t,r,n,s,i){if(t.length===0){if(this.#e!==void 0)throw _t;if(i)return;this.#e=r;return}let[o,...a]=t,l=o==="*"?a.length===0?["","",Rr]:["","",ls]:o==="/*"?["","",kr]:o.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(l){let u=l[1],p=l[2]||ls;if(u&&l[2]&&(p===".*"||(p=p.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(p))))throw _t;if(c=this.#r[p],!c){if(Object.keys(this.#r).some(f=>f!==Rr&&f!==kr))throw _t;if(i)return;c=this.#r[p]=new ho,u!==""&&(c.#t=s.varIndex++);}!i&&u!==""&&n.push([u,c.#t]);}else if(c=this.#r[o],!c){if(Object.keys(this.#r).some(u=>u.length>1&&u!==Rr&&u!==kr))throw _t;if(i)return;c=this.#r[o]=new ho;}c.insert(a,r,n,s,i);}buildRegExpStr(){let r=Object.keys(this.#r).sort(jy).map(n=>{let s=this.#r[n];return (typeof s.#t=="number"?`(${n})@${s.#t}`:Dy.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 du,hu=y(()=>{go();du=class{#e={varIndex:0};#t=new mu;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 yu(e){return gu[e]??=new RegExp(e==="*"?"":`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(t,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function My(){gu=Object.create(null);}function Uy(e){let t=new du,r=[];if(e.length===0)return Fy;let n=e.map(c=>[!/\*|\/:/.test(c[0]),...c]).sort(([c,u],[p,f])=>c?1:p?-1:u.length-f.length),s=Object.create(null);for(let c=0,u=-1,p=n.length;c<p;c++){let[f,h,d]=n[c];f?s[h]=[d.map(([b])=>[b,Object.create(null)]),as]:u++;let m;try{m=t.insert(h,u,f);}catch(b){throw b===_t?new os(h):b}f||(r[u]=d.map(([b,g])=>{let S=Object.create(null);for(g-=1;g>=0;g--){let[A,$]=m[g];S[A]=$;}return [b,S]}));}let[i,o,a]=t.buildRegExp();for(let c=0,u=r.length;c<u;c++)for(let p=0,f=r[c].length;p<f;p++){let h=r[c][p]?.[1];if(!h)continue;let d=Object.keys(h);for(let m=0,b=d.length;m<b;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 Kt(e,t){if(e){for(let r of Object.keys(e).sort((n,s)=>s.length-n.length))if(yu(r).test(t))return [...e[r]]}}var Fy,gu,cs,yo=y(()=>{lt();Vt();mo();go();hu();Fy=[/^$/,[],Object.create(null)],gu=Object.create(null);cs=class{name="RegExpRouter";#e;#t;constructor(){this.#e={[te]:Object.create(null)},this.#t={[te]:Object.create(null)};}add(e,t,r){let n=this.#e,s=this.#t;if(!n||!s)throw new Error(is);n[e]||[n,s].forEach(a=>{a[e]=Object.create(null),Object.keys(a[te]).forEach(l=>{a[e][l]=[...a[te][l]];});}),t==="/*"&&(t="*");let i=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let a=yu(t);e===te?Object.keys(n).forEach(l=>{n[l][t]||=Kt(n[l],t)||Kt(n[te],t)||[];}):n[e][t]||=Kt(n[e],t)||Kt(n[te],t)||[],Object.keys(n).forEach(l=>{(e===te||e===l)&&Object.keys(n[l]).forEach(c=>{a.test(c)&&n[l][c].push([r,i]);});}),Object.keys(s).forEach(l=>{(e===te||e===l)&&Object.keys(s[l]).forEach(c=>a.test(c)&&s[l][c].push([r,i]));});return}let o=ss(t)||[t];for(let a=0,l=o.length;a<l;a++){let c=o[a];Object.keys(s).forEach(u=>{(e===te||e===u)&&(s[u][c]||=[...Kt(n[u],c)||Kt(n[te],c)||[]],s[u][c].push([r,i-l+a+1]));});}}match=fo;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,My(),e}#r(e){let t=[],r=e===te;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!==te&&t.push(...Object.keys(n[te]).map(i=>[i,n[te][i]]));}),r?Uy(t):null}};});var wu=y(()=>{lt();mo();yo();});var bu=y(()=>{yo();wu();});var wo,Su=y(()=>{lt();wo=class{name="SmartRouter";#e=[];#t=[];constructor(e){this.#e=e.routers;}add(e,t,r){if(!this.#t)throw new Error(is);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 os)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 Eu=y(()=>{Su();});var Pr,By,xu,$u=y(()=>{lt();Vt();Pr=Object.create(null),By=e=>{for(let t in e)return true;return false},xu=class _u{#e;#t;#r;#i=0;#s=Pr;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=Xc(r),o=[];for(let a=0,l=i.length;a<l;a++){let c=i[a],u=i[a+1],p=Yc(c,u),f=Array.isArray(p)?p[0]:c;if(f in s.#t){s=s.#t[f],p&&o.push(p[1]);continue}s.#t[f]=new _u,p&&(s.#r.push(p),o.push(p[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[te],u={};if(c!==void 0&&(c.params=Object.create(null),t.push(c),s!==Pr||i&&i!==Pr))for(let p=0,f=c.possibleKeys.length;p<f;p++){let h=c.possibleKeys[p],d=u[c.score];c.params[h]=i?.[h]&&!d?i[h]:s[h]??i?.[h],u[c.score]=true;}}}search(t,r){let n=[];this.#s=Pr;let i=[this],o=io(r),a=[],l=o.length,c=null;for(let u=0;u<l;u++){let p=o[u],f=u===l-1,h=[];for(let m=0,b=i.length;m<b;m++){let g=i[m],S=g.#t[p];S&&(S.#s=g.#s,f?(S.#t["*"]&&this.#n(n,S.#t["*"],t,g.#s),this.#n(n,S,t,g.#s)):h.push(S));for(let A=0,$=g.#r.length;A<$;A++){let P=g.#r[A],N=g.#s===Pr?{}:{...g.#s};if(P==="*"){let I=g.#t["*"];I&&(this.#n(n,I,t,g.#s),I.#s=N,h.push(I));continue}let[v,_,L]=P;if(!p&&!(L instanceof RegExp))continue;let w=g.#t[v];if(L instanceof RegExp){if(c===null){c=new Array(l);let q=r[0]==="/"?1:0;for(let E=0;E<l;E++)c[E]=q,q+=o[E].length+1;}let I=r.substring(c[u]),T=L.exec(I);if(T){if(N[_]=T[0],this.#n(n,w,t,g.#s,N),By(w.#t)){w.#s=N;let q=T[0].match(/\//)?.length??0;(a[q]||=[]).push(w);}continue}}(L===true||L.test(p))&&(N[_]=p,f?(this.#n(n,w,t,N,g.#s),w.#t["*"]&&this.#n(n,w.#t["*"],t,N,g.#s)):(w.#s=N,h.push(w)));}}let d=a.shift();i=d?h.concat(d):h;}return n.length>1&&n.sort((u,p)=>u.score-p.score),[n.map(({handler:u,params:p})=>[u,p])]}};});var bo,vu=y(()=>{Vt();$u();bo=class{name="TrieRouter";#e;constructor(){this.#e=new xu;}add(e,t,r){let n=ss(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 Tu=y(()=>{vu();});var So,Au=y(()=>{fu();bu();Eu();Tu();So=class extends uu{constructor(e={}){super(e),this.router=e.router??new wo({routers:[new cs,new bo]});}};});var Cu=y(()=>{Au();});function Eo(e){return !e||typeof e!="object"?false:e.code==="EADDRINUSE"}function Ru(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 xo(e){console.error(),console.error(Nr.default.red(`Cannot start server: Port ${Nr.default.bold(String(e))} is already in use.`)),console.error(Nr.default.red(`Stop the process using that port, or set a different ${Nr.default.bold("api.port")} in your config.`)),console.error(),process.exit(1);}var Nr,ku=y(()=>{Nr=ee(se());});var Pu,Nu=y(()=>{Pu=/^\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 $o,Ou,qy,_o,vo=y(()=>{$o=(e,t=_o)=>{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},Ou=e=>{for(let t in _o)if(_o[t]===e)return t},qy={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"},_o=qy;});var Lu,Iu=y(()=>{Lu=(...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 Du,Hy,Wy,ju,Fu=y(()=>{Nu();vo();Iu();Du={br:".br",zstd:".zst",gzip:".gz"},Hy=Object.keys(Du),Wy="index.html",ju=e=>{let t=e.root??"./",r=e.path,n=e.join??Lu;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,Wy));let l=e.getContent,c=await l(a,s);if(c instanceof Response)return s.newResponse(c.body,c);if(c){let u=e.mimes&&$o(a,e.mimes)||$o(a);if(s.header("Content-Type",u||"application/octet-stream"),e.precompressed&&(!u||Pu.test(u))){let p=new Set(s.req.header("Accept-Encoding")?.split(",").map(f=>f.trim()));for(let f of Hy){if(!p.has(f))continue;let h=await l(a+Du[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 Mu,Uu=y(()=>{Fu();Mu=e=>async function(r,n){return ju({...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(o)).isDirectory();}catch{}return a}})(r,n)};});var Bu=y(()=>{});var qu,Hu=y(()=>{Bu();qu=(e,t)=>{for(let[r,n]of Object.entries(t)){let s=new RegExp("/:"+r+"(?:{[^/]+})?\\??");e=e.replace(s,n?`/${n}`:"");}return e};});var Vy,Wu,Gu=y(()=>{Vy=1024,Wu=({concurrency:e,interval:t}={})=>{if(e||=Vy,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 zu,To,Vu=y(()=>{po();zu=e=>e.length>1,To=e=>e[Cr]?To(e[Cr]):e;});var Ku,Ky,Jy,Xy,Yy,Or,Ju,Ao,Co=y(()=>{lt();Vu();Ku=e=>e.split(/[\/\\]/).slice(0,-1).join("/"),Ky=e=>e.replace(/(\\)/g,"/").replace(/\/$/g,""),Jy=(e,t)=>{e.length===0||t?e.push(".."):e.pop();},Xy=(e,t)=>{e=e.replace(/^\.(?!.)/,""),e!==""&&t.push(e);},Yy=(e,t)=>{let r=false;for(let n of e)n===".."?(Jy(t,r),r=true):(Xy(n,t),r=false);},Or=(...e)=>{e=e.map(Ky);let t=[];return Yy(e.join("/").split("/"),t),(e[0][0]==="/"?"/":"")+t.join("/")},Ju=e=>e.routes.reduce((t,{method:r,handler:n,path:s})=>{let i=To(n);return ["GET",te].includes(r)&&!zu(i)&&t.push({path:s}),t},[]),Ao=e=>e.split("/").some(t=>t.startsWith(":")||t.includes("*"));});var Xu,us,Ro=y(()=>{Co();Xu="HONO_SSG_CONTEXT",us="x-hono-disable-ssg",(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[us]:"true"}})}catch{return null}})();});var Yu=y(()=>{co();});var ko,Po=y(()=>{Yu();ko=()=>({afterResponseHook:e=>e.status!==200?false:e});});var Qy,Zy,ew,tw,rw,nw,sw,iw,ow,aw,lw,Qu,cw,Zu,ep=y(()=>{Hu();Gu();vo();Ro();Po();Co();Qy=2,Zy="text/plain",ew="./static",tw=(e,t,r,n)=>{let s=sw(r,n);return e.endsWith(`.${s}`)?Or(t,e):e==="/"?Or(t,`index.${s}`):e.endsWith("/")?Or(t,e,`index.${s}`):Or(t,`${e}.${s}`)},rw=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"}`)}},nw={"text/html":"html","text/xml":"xml","application/xml":"xml","application/yaml":"yaml"},sw=(e,t)=>{let r=t||nw;return e in r?r[e]:Ou(e)||"html"},iw=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,ow=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,aw=(e,t,r)=>Array.isArray(e)?async n=>{for(let s of e)await s(n,t,r);}:e,lw=function*(e,t,r,n){let s="http://localhost",i=Wu({concurrency:n});for(let o of Ju(e)){let a=new URL(o.path,s).toString(),l=new Request(a);yield new Promise(async(c,u)=>{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(Ao(o.path)){c(void 0);return}l.ssgParams=[{}];}let p={method:l.method,headers:l.headers};c((function*(){for(let f of l.ssgParams)yield new Promise(async(h,d)=>{try{let m=qu(o.path,f),b=await i.run(()=>e.request(m,p,{[Xu]:!0}));if(b.headers.get(us)){h(void 0);return}if(r){let A=await r(b);if(!A){h(void 0);return}b=A;}let g=b.headers.get("Content-Type")?.split(";")[0]||Zy,S=await rw(b);h({routePath:m,mimeType:g,content:S});}catch(m){d(m);}});})());}catch(p){u(p);}});}},Qu=new Set,cw=async(e,t,r,n)=>{let s=await e;if(!s)return;let{routePath:i,content:o,mimeType:a}=s,l=tw(i,r,a,n),c=Ku(l);return Qu.has(c)||(await t.mkdir(c,{recursive:true}),Qu.add(c)),typeof o=="string"?await t.writeFile(l,o):o instanceof ArrayBuffer&&await t.writeFile(l,new Uint8Array(o)),l},Zu=async(e,t,r)=>{let n,s=[],i=[],o=r?.plugins||[ko()],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 u of o)u.beforeRequestHook&&a.push(...Array.isArray(u.beforeRequestHook)?u.beforeRequestHook:[u.beforeRequestHook]),u.afterResponseHook&&l.push(...Array.isArray(u.afterResponseHook)?u.afterResponseHook:[u.afterResponseHook]),u.afterGenerateHook&&c.push(...Array.isArray(u.afterGenerateHook)?u.afterGenerateHook:[u.afterGenerateHook]);try{let u=r?.dir??ew,p=r?.concurrency??Qy,f=iw(a.length>0?a:[b=>b]),h=ow(l.length>0?l:[b=>b]),d=lw(e,f,h,p);for(let b of d)s.push(b.then(g=>{if(g)for(let S of g)i.push(cw(S,t,u,r?.extensionMap).catch(A=>A));}));await Promise.all(s);let m=[];for(let b of i){let g=await b;if(typeof g=="string")m.push(g);else if(g)throw g}n={success:!0,files:m};}catch(u){let p=u instanceof Error?u:new Error(String(u));n={success:false,files:[],error:p};}return c.length>0&&await aw(c,t,r)(n,t,r),n};});var tp=y(()=>{ep();Ro();Po();});var uw,No,rp,np=y(()=>{tp();(({write:uw}=Bun)),No={writeFile:async(e,t)=>{await uw(e,t);},mkdir:async()=>{}},rp=async(e,t)=>Zu(e,No,t);});var sp,ip,op,ap=y(()=>{sp=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);}},ip=e=>new MessageEvent("message",{data:e}),op=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 Jt,ps=y(()=>{Jt=e=>"server"in e.env?e.env.server:e.env;});var Oo,Lo,Io,lp,cp=y(()=>{ap();ps();Oo=e=>new sp({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);}}),Lo=op((e,t)=>{let r=Jt(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)}),Io={open(e){let t=e.data.events;t.onOpen&&t.onOpen(new Event("open"),Oo(e));},close(e,t,r){let n=e.data.events;n.onClose&&n.onClose(new CloseEvent("close",{code:t,reason:r}),Oo(e));},message(e,t){let r=e.data.events;if(r.onMessage){let n=typeof t=="string"?t:t.buffer;r.onMessage(ip(n),Oo(e));}}},lp=()=>({upgradeWebSocket:Lo,websocket:Io});});var up,pp=y(()=>{ps();up=e=>{let t=Jt(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 fp={};fe(fp,{bunFileSystemModule:()=>No,createBunWebSocket:()=>lp,getBunServer:()=>Jt,getConnInfo:()=>up,serveStatic:()=>Mu,toSSG:()=>rp,upgradeWebSocket:()=>Lo,websocket:()=>Io});var mp=y(()=>{Uu();np();cp();pp();ps();});async function fs(e,t={port:3e3}){let r=Wn(),n=t.port??3e3;if(xr()){let s=await Promise.resolve().then(()=>(mp(),fp)).then(o=>o.serveStatic),i;try{i=Bun.serve({fetch:hp(e,r,s).fetch,port:n});}catch(o){throw Eo(o)&&xo(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:hp(e,r,i).fetch});try{await Ru(o,n);}catch(a){throw Eo(a)&&xo(n),a}return ()=>new Promise(a=>{o.close(()=>{a(void 0);});})}}function hp(e,t,r){return new So().use("/favicon.ico",r({path:He__default.join(t,"static","favicon.ico")})).use("/fonts/*",r({root:He__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 Do=y(()=>{at();Cu();ku();we();});var Ze,jo=y(()=>{wt();Ze=class e{root;constructor(t,r){let n=r??e.projectDir();this.root=He__default.join(n,t??"");}ensureRoot(){Re(this.root);}static homeDir(){return He__default.join(pw.homedir(),".lite")}static projectDir(){return He__default.join(process.cwd(),"supabase")}deleteAll(t=false){try{In.rmSync(this.root,{recursive:!0});}catch(r){if(!t)throw r}this.ensureRoot();}delete(t,r=false){try{In.unlinkSync(He__default.join(this.root,t));}catch(n){if(!r)throw n}}write(t,r,n=false){try{this.ensureRoot(),In.writeFileSync(He__default.join(this.root,t),r);}catch(s){if(!n)throw s}}read(t,r=false){try{return In.readFileSync(He__default.join(this.root,t),"utf8")}catch(n){if(!r)throw n}}relativePath(t){return t?He__default.relative(process.cwd(),He__default.join(this.root,t)):this.root}path(t){return t?He__default.join(this.root,t):this.root}};});var Lr,Fo=y(()=>{Lr=process.env.SUPALITE_CLOUD_URL??(process.env.LOCAL?"http://localhost:2000":"https://www.lite.dev");});var hs,gp=y(()=>{wt();hs=class{root;constructor(t){this.root=t??He__default.join(pw.homedir(),".lite","auth"),Re(this.root);}async getItem(t){try{return In.readFileSync(He__default.join(this.root,t+".json"),"utf8")}catch{return null}}async setItem(t,r){In.writeFileSync(He__default.join(this.root,t+".json"),r);}async removeItem(t){try{In.unlinkSync(He__default.join(this.root,t+".json"));}catch{return}}};});var Xt,Uo=y(()=>{Fo();jo();gp();Xt=class{constructor(t){this.config=t;this.tempFs=new Ze(".temp",this.config.root),this.projectFs=new Ze("supabase",this.config.root),this.schemaFs=new Ze("schemas",this.config.root),this.authStorage=this.config.authStorage??new hs(He__default.join(Ze.homeDir(),"auth")),this._client=this.config.withSupabaseClient!==false?this.config.client??createClient(this.config.host??Lr,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??Lr);return await fetch(n,{...r,headers:{...r?.headers,Authorization:`Bearer ${this.config.token}`}})}};});var Yt,Bo=y(()=>{Uo();Yt=class extends Xt{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 hw(e){let t=He.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 ys,yp=y(()=>{at();ys=class{driver=ce;basePath;constructor(t){this.basePath=He.resolve(t.basePath);}filePath(t,r){return He.join(this.basePath,t,r)}async ensureDir(t){await ce.mkdir(He.dirname(t),{recursive:true});}async getObject(t,r,n,s){let i=this.filePath(t,r),o=await ce.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,u=o.size,p=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;u=d-h+1,c=`bytes ${h}-${d}/${o.size}`,p=206,l=(await ce.open(i,"r")).readableWebStream();}else l=(await ce.open(i,"r")).readableWebStream();}else l=(await ce.open(i,"r")).readableWebStream();return {httpStatusCode:p,metadata:{...this.buildMetadata(o,a,r),contentLength:u,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 p=[],f=s.getReader();for(;;){let{done:h,value:d}=await f.read();if(h)break;p.push(d);}l=Buffer.concat(p);}await ce.writeFile(a,l);let c=await ce.stat(a),u=`"${createHash("md5").update(l).digest("hex")}"`;return {cacheControl:o,contentLength:c.size,size:c.size,mimetype:i,lastModified:c.mtime,eTag:u}}async deleteObject(t,r,n){let s=this.filePath(t,r);await ce.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 ce.copyFile(o,a);let l=await ce.stat(a),c=await ce.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 ce.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:to(t.size),size:to(t.size),mimetype:hw(n),lastModified:t.mtime,eTag:r}}};});async function Ue(e,t,r){try{return await gw(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 gw,Qt=y(()=>{gw=new Function("spec","return import(spec)");});function wp(e,t={}){let r=He__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=bw(He__default.resolve(e),r);for(let a of o)for(let l of i){let c=He__default.join(a,l),u;try{u=In.readFileSync(c,"utf-8");}catch{continue}let p;try{p=parse(u);}catch(f){throw new Error(`Failed to parse ${c}: ${f.message}`)}for(let[f,h]of Object.entries(p))n[f]===void 0&&(n[f]=h);}}function bw(e,t){let r=[],n=e,s=He__default.parse(n).root;for(;r.push(n),!(n===t||n===s);){let i=He__default.dirname(n);if(i===n)break;n=i;}return r}var bp=y(()=>{});function Sp(e,t=process.env){return qo(e,t)}function qo(e,t){if(typeof e=="string"){let r=e.match(Sw);return r?t[r[1]]??"":e}if(Array.isArray(e))return e.map(r=>qo(r,t));if(e&&typeof e=="object"){let r={};for(let[n,s]of Object.entries(e))r[n]=qo(s,t);return r}return e}var Sw,Ep=y(()=>{Sw=/^env\((\w+)\)$/;});var Dr,xw,ws,_p=y(()=>{Bo();Wt();Dr=ee(se());Sr();qt();yp();Qt();bp();Ep();xw=["toml","json","ts","mts","js","mjs","cjs"],ws=class extends Yt{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=He__default.relative(process.cwd(),_e.config_dir);if(!t)for(let n of xw){let s=He__default.join(r,`config.${n}`);if(await ce__default.access(s).then(()=>true).catch(()=>false)){t=s;break}}return t}async readConfig(t){let r=await this.getConfigPath(t);if(!r)return {};console.log(Dr.default.dim(`Using config file: ${Dr.default.cyan(`./${r}`)}`));let n=He__default.dirname(He__default.resolve(r));wp(n);let s=r.split(".").pop(),i;switch(s){case "toml":i=St(await ce__default.readFile(r,"utf-8"));break;case "json":i=JSON.parse(await ce__default.readFile(r,"utf-8"));break;case "ts":case "mts":case "js":case "mjs":case "cjs":try{i=(await import(He__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 Sp(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??_e.default_db_url,n=await createConnection({url:s,ddlDialect:"sqlite"});break;case "pglite":{s=r.db?.url??He__default.join(process.cwd(),_e.default_db_dir);let{createPgliteConnection:i}=await Ue("@supabase/lite/pglite","pglite","@electric-sql/pglite");n=await i({url:s});break}case "postgres":{s=r.db?.url??"";let{createPostgresConnection:i}=await Ue("@supabase/lite/postgres","postgres","postgres");n=await i({url:s});break}default:s=r.db?.url??_e.default_db_url,n=await createConnection({url:s,ddlDialect:"postgres"});break}if(!n)throw new Error("Failed to create connection");return console.log(Dr.default.green(" \u279C"),"Database located at",Dr.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 ys({basePath:He__default.join(process.cwd(),_e.config_dir,".temp/storage")})),await n.init()}};});var bs,$p=y(()=>{Bo();bs=class extends Yt{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 Ss,vp=y(()=>{Uo();_p();$p();Ss=class extends Xt{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 ws(t),remote:new bs(t)},this}};});async function V(e={}){return await new Ss({host:Lr,root:Ze.projectDir(),...e}).init()}var Te=y(()=>{jo();Fo();vp();});var Tp={};fe(Tp,{start:()=>vw});var jr,vw,Ap=y(()=>{Do();at();jr=ee(se());Wt();Te();we();qt();vw=e=>{e.command("start").option("--config <config>","Path to the config file").description("Start the development server").helpGroup("Local Development:").action(async t=>{await Y(t.config),await Vn(async()=>{let n=await(await V({withSupabaseClient:false})).project.local.createApp(t.config),s=n.config.api?.port??_e.default_api_port;await fs(n,{port:s});console.log(jr.default.green(" \u279C"),"Server running on ",jr.default.cyan(`http://localhost:${s}`));let o=Ln();o&&console.log(jr.default.yellow(` \u26A0 ${o}`)),await n.connection.ping();},r=>{console.log(),console.log(jr.default.green(`Ready in ${r.toFixed(2)}ms`));});});};});function Nw(e){let t=normalize(e);return t.length>1&&t[t.length-1]===sep&&(t=t.substring(0,t.length-1)),t}function Pp(e,t){return e.replace(Ow,t)}function Iw(e){return e==="/"||Lw.test(e)}function Wo(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=Nw(e)),e===".")return "";let o=e[e.length-1]!==s;return Pp(o?e+s:e,s)}function Np(e,t){return t+e}function Dw(e,t){return function(r,n){return n.startsWith(e)?n.slice(e.length)+r:Pp(relative(e,n),t.pathSeparator)+t.pathSeparator+r}}function jw(e){return e}function Fw(e,t,r){return t+e+r}function Mw(e,t){let{relativePaths:r,includeBasePath:n}=t;return r&&e?Dw(e,t):n?Np:jw}function Uw(e){return function(t,r){r.push(t.substring(e.length)||".");}}function Bw(e){return function(t,r,n){let s=t.substring(e.length)||".";n.every(i=>i(s,true))&&r.push(s);}}function Gw(e,t){let{includeDirs:r,filters:n,relativePaths:s}=t;return r?s?n&&n.length?Bw(e):Uw(e):n&&n.length?Hw:qw:Ww}function Yw(e){let{excludeFiles:t,filters:r,onlyCounts:n}=e;return t?Xw:r&&r.length?n?zw:Vw:n?Kw:Jw}function eb(e){return e.group?Zw:Qw}function nb(e){return e.group?tb:rb}function ob(e,t){return !e.resolveSymlinks||e.excludeSymlinks?null:t?ib:sb}function Op(e,t,r){if(r.options.useRealPaths)return ab(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 ab(e,t){return t.visited.includes(e+t.options.pathSeparator)}function Es(e,t,r,n){t(e&&!n?e:null,r);}function gb(e,t){let{onlyCounts:r,group:n,maxFiles:s}=e;return r?t?lb:fb:n?t?cb:hb:s?t?pb:db:t?ub:mb}function bb(e){return e?wb:yb}function _b(e,t){return new Promise((r,n)=>{Dp(e,t,(s,i)=>{if(s)return n(s);r(i);});})}function Dp(e,t,r){new Ip(e,t,r).start();}function $b(e,t){return new Ip(e,t).start()}var Cp,Ow,Lw,qw,Hw,Ww,zw,Vw,Kw,Jw,Xw,Qw,Zw,tb,rb,sb,ib,lb,cb,ub,pb,fb,mb,db,hb,Lp,yb,wb,Sb,Eb,xb,Ip,Rp,jp,Fp,Mp=y(()=>{Cp=createRequire(import.meta.url);Ow=/[\\/]/g;Lw=/^[a-z]:[\\/]$/i;qw=(e,t)=>{t.push(e||".");},Hw=(e,t,r)=>{let n=e||".";r.every(s=>s(n,true))&&t.push(n);},Ww=()=>{};zw=(e,t,r,n)=>{n.every(s=>s(e,false))&&r.files++;},Vw=(e,t,r,n)=>{n.every(s=>s(e,false))&&t.push(e);},Kw=(e,t,r,n)=>{r.files++;},Jw=(e,t)=>{t.push(e);},Xw=()=>{};Qw=e=>e,Zw=()=>[""].slice(0,0);tb=(e,t,r)=>{e.push({directory:t,files:r,dir:t});},rb=()=>{};sb=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()&&Op(e,a,t))return n.dequeue(null,t);r(c,a),n.dequeue(null,t);});});},ib=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()&&Op(e,o,t))return;r(a,o);}catch(o){if(!i)throw o}};lb=e=>e.counts,cb=e=>e.groups,ub=e=>e.paths,pb=e=>e.paths.slice(0,e.options.maxFiles),fb=(e,t,r)=>(Es(t,r,e.counts,e.options.suppressErrors),null),mb=(e,t,r)=>(Es(t,r,e.paths,e.options.suppressErrors),null),db=(e,t,r)=>(Es(t,r,e.paths.slice(0,e.options.maxFiles),e.options.suppressErrors),null),hb=(e,t,r)=>(Es(t,r,e.groups,e.options.suppressErrors),null);Lp={withFileTypes:true},yb=(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||".",Lp,(o,a=[])=>{s(a,r,n),e.queue.dequeue(e.options.suppressErrors?null:o,e);});},wb=(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||".",Lp);}catch(a){if(!e.options.suppressErrors)throw a}s(o,r,n);};Sb=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));}},Eb=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}},xb=class{aborted=false;abort(){this.aborted=true;}},Ip=class{root;isSynchronous;state;joinPath;pushDirectory;pushFile;getArray;groupFiles;resolveSymlink;walkDirectory;callbackInvoker;constructor(e,t,r){this.isSynchronous=!r,this.callbackInvoker=gb(t,this.isSynchronous),this.root=Wo(e,t),this.state={root:Iw(this.root)?this.root:this.root.slice(0,-1),paths:[""].slice(0,0),groups:[],counts:new Eb,options:t,queue:new Sb((n,s)=>this.callbackInvoker(s,n,r)),symlinks:new Map,visited:[""].slice(0,0),controller:new xb,fs:t.fs||er},this.joinPath=Mw(this.root,t),this.pushDirectory=Gw(this.root,t),this.pushFile=Yw(t),this.getArray=eb(t),this.groupFiles=nb(t),this.resolveSymlink=ob(t,this.isSynchronous),this.walkDirectory=bb(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:u,pathSeparator:p},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 b=this.joinPath(m.name,t);this.pushFile(b,h,this.state.counts,s);}else if(m.isDirectory()){let b=Fw(m.name,t,this.state.options.pathSeparator);if(a&&a(m.name,b))continue;this.pushDirectory(b,n,s),this.walkDirectory(this.state,b,b,r-1,this.walk);}else if(this.resolveSymlink&&m.isSymbolicLink()){let b=Np(m.name,t);this.resolveSymlink(b,this.state,(g,S)=>{if(g.isDirectory()){if(S=Wo(S,this.state.options),a&&a(m.name,u?S:b+p))return;this.walkDirectory(this.state,S,u?S:b+p,r-1,this.walk);}else {S=u?S:b;let A=basename(S),$=Wo(dirname(S),this.state.options);S=this.joinPath(A,$),this.pushFile(S,h,this.state.counts,s);}});}}this.groupFiles(this.state.groups,t,h);}};Rp=class{constructor(e,t){this.root=e,this.options=t;}withPromise(){return _b(this.root,this.options)}withCallback(e){Dp(this.root,this.options,e);}sync(){return $b(this.root,this.options)}},jp=null;try{Cp.resolve("picomatch"),jp=Cp("picomatch");}catch{}Fp=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 Rp(e||".",this.options)}withGlobFunction(e){return this.globFunction=e,this}crawlWithOptions(e,t){return this.options={...this.options,...t},new Rp(e||".",this.options)}glob(...e){return this.globFunction?this.globWithOptions(e):this.globWithOptions(e,{dot:true})}globWithOptions(e,...t){let r=this.globFunction||jp;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 Fr=it((_C,Wp)=>{var Up="[^\\\\/]",vb="(?=.)",Bp="[^/]",zo="(?:\\/|$)",qp="(?:^|\\/)",Vo=`\\.{1,2}${zo}`,Tb="(?!\\.)",Ab=`(?!${qp}${Vo})`,Cb=`(?!\\.{0,1}${zo})`,Rb=`(?!${Vo})`,kb="[^.\\/]",Pb=`${Bp}*?`,Nb="/",Hp={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:vb,QMARK:Bp,END_ANCHOR:zo,DOTS_SLASH:Vo,NO_DOT:Tb,NO_DOTS:Ab,NO_DOT_SLASH:Cb,NO_DOTS_SLASH:Rb,QMARK_NO_DOT:kb,STAR:Pb,START_ANCHOR:qp,SEP:Nb},Ob={...Hp,SLASH_LITERAL:"[\\\\/]",QMARK:Up,STAR:`${Up}*?`,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:"\\"},Lb={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"};Wp.exports={MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:Lb,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?Ob:Hp}};});var Mr=it(Pe=>{var{REGEX_BACKSLASH:Ib,REGEX_REMOVE_BACKSLASH:Db,REGEX_SPECIAL_CHARS:jb,REGEX_SPECIAL_CHARS_GLOBAL:Fb}=Fr();Pe.isObject=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);Pe.hasRegexChars=e=>jb.test(e);Pe.isRegexChar=e=>e.length===1&&Pe.hasRegexChars(e);Pe.escapeRegex=e=>e.replace(Fb,"\\$1");Pe.toPosixSlashes=e=>e.replace(Ib,"/");Pe.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};Pe.removeBackslashes=e=>e.replace(Db,t=>t==="\\"?"":t);Pe.escapeLast=(e,t,r)=>{let n=e.lastIndexOf(t,r);return n===-1?e:e[n-1]==="\\"?Pe.escapeLast(e,t,n-1):`${e.slice(0,n)}\\${e.slice(n)}`};Pe.removePrefix=(e,t={})=>{let r=e;return r.startsWith("./")&&(r=r.slice(2),t.prefix="./"),r};Pe.wrapOutput=(e,t={},r={})=>{let n=r.contains?"":"^",s=r.contains?"":"$",i=`${n}(?:${e})${s}`;return t.negated===true&&(i=`(?:^(?!${i}).*$)`),i};Pe.basename=(e,{windows:t}={})=>{let r=e.split(t?/[\\/]/:"/"),n=r[r.length-1];return n===""?r[r.length-2]:n};});var Qp=it((vC,Yp)=>{var Gp=Mr(),{CHAR_ASTERISK:Ko,CHAR_AT:Mb,CHAR_BACKWARD_SLASH:Ur,CHAR_COMMA:Ub,CHAR_DOT:Jo,CHAR_EXCLAMATION_MARK:Xo,CHAR_FORWARD_SLASH:Xp,CHAR_LEFT_CURLY_BRACE:Yo,CHAR_LEFT_PARENTHESES:Qo,CHAR_LEFT_SQUARE_BRACKET:Bb,CHAR_PLUS:qb,CHAR_QUESTION_MARK:zp,CHAR_RIGHT_CURLY_BRACE:Hb,CHAR_RIGHT_PARENTHESES:Vp,CHAR_RIGHT_SQUARE_BRACKET:Wb}=Fr(),Kp=e=>e===Xp||e===Ur,Jp=e=>{e.isPrefix!==true&&(e.depth=e.isGlobstar?1/0:1);},Gb=(e,t)=>{let r=t||{},n=e.length-1,s=r.parts===true||r.scanToEnd===true,i=[],o=[],a=[],l=e,c=-1,u=0,p=0,f=false,h=false,d=false,m=false,b=false,g=false,S=false,A=false,$=false,P=false,N=0,v,_,L={value:"",depth:0,isGlob:false},w=()=>c>=n,I=()=>l.charCodeAt(c+1),T=()=>(v=_,l.charCodeAt(++c));for(;c<n;){_=T();let j;if(_===Ur){S=L.backslashes=true,_=T(),_===Yo&&(g=true);continue}if(g===true||_===Yo){for(N++;w()!==true&&(_=T());){if(_===Ur){S=L.backslashes=true,T();continue}if(_===Yo){N++;continue}if(g!==true&&_===Jo&&(_=T())===Jo){if(f=L.isBrace=true,d=L.isGlob=true,P=true,s===true)continue;break}if(g!==true&&_===Ub){if(f=L.isBrace=true,d=L.isGlob=true,P=true,s===true)continue;break}if(_===Hb&&(N--,N===0)){g=false,f=L.isBrace=true,P=true;break}}if(s===true)continue;break}if(_===Xp){if(i.push(c),o.push(L),L={value:"",depth:0,isGlob:false},P===true)continue;if(v===Jo&&c===u+1){u+=2;continue}p=c+1;continue}if(r.noext!==true&&(_===qb||_===Mb||_===Ko||_===zp||_===Xo)===true&&I()===Qo){if(d=L.isGlob=true,m=L.isExtglob=true,P=true,_===Xo&&c===u&&($=true),s===true){for(;w()!==true&&(_=T());){if(_===Ur){S=L.backslashes=true,_=T();continue}if(_===Vp){d=L.isGlob=true,P=true;break}}continue}break}if(_===Ko){if(v===Ko&&(b=L.isGlobstar=true),d=L.isGlob=true,P=true,s===true)continue;break}if(_===zp){if(d=L.isGlob=true,P=true,s===true)continue;break}if(_===Bb){for(;w()!==true&&(j=T());){if(j===Ur){S=L.backslashes=true,T();continue}if(j===Wb){h=L.isBracket=true,d=L.isGlob=true,P=true;break}}if(s===true)continue;break}if(r.nonegate!==true&&_===Xo&&c===u){A=L.negated=true,u++;continue}if(r.noparen!==true&&_===Qo){if(d=L.isGlob=true,s===true){for(;w()!==true&&(_=T());){if(_===Qo){S=L.backslashes=true,_=T();continue}if(_===Vp){P=true;break}}continue}break}if(d===true){if(P=true,s===true)continue;break}}r.noext===true&&(m=false,d=false);let q=l,E="",x="";u>0&&(E=l.slice(0,u),l=l.slice(u),p-=u),q&&d===true&&p>0?(q=l.slice(0,p),x=l.slice(p)):d===true?(q="",x=l):q=l,q&&q!==""&&q!=="/"&&q!==l&&Kp(q.charCodeAt(q.length-1))&&(q=q.slice(0,-1)),r.unescape===true&&(x&&(x=Gp.removeBackslashes(x)),q&&S===true&&(q=Gp.removeBackslashes(q)));let U={prefix:E,input:e,start:u,base:q,glob:x,isBrace:f,isBracket:h,isGlob:d,isExtglob:m,isGlobstar:b,negated:A,negatedExtglob:$};if(r.tokens===true&&(U.maxDepth=0,Kp(_)||o.push(L),U.tokens=o),r.parts===true||r.tokens===true){let j;for(let z=0;z<i.length;z++){let Me=j?j+1:u,Ce=i[z],st=e.slice(Me,Ce);r.tokens&&(z===0&&u!==0?(o[z].isPrefix=true,o[z].value=E):o[z].value=st,Jp(o[z]),U.maxDepth+=o[z].depth),(z!==0||st!=="")&&a.push(st),j=Ce;}if(j&&j+1<e.length){let z=e.slice(j+1);a.push(z),r.tokens&&(o[o.length-1].value=z,Jp(o[o.length-1]),U.maxDepth+=o[o.length-1].depth);}U.slashes=i,U.parts=a;}return U};Yp.exports=Gb;});var tf=it((TC,ef)=>{var xs=Fr(),ze=Mr(),{MAX_LENGTH:_s,POSIX_REGEX_SOURCE:zb,REGEX_NON_SPECIAL_CHARS:Vb,REGEX_SPECIAL_CHARS_BACKREF:Kb,REPLACEMENTS:Zp}=xs,Jb=(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=>ze.escapeRegex(s)).join("..")}return r},Zt=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`,Zo=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a string");e=Zp[e]||e;let r={...t},n=typeof r.maxLength=="number"?Math.min(_s,r.maxLength):_s,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=xs.globChars(r.windows),c=xs.extglobChars(l),{DOT_LITERAL:u,PLUS_LITERAL:p,SLASH_LITERAL:f,ONE_CHAR:h,DOTS_SLASH:d,NO_DOT:m,NO_DOT_SLASH:b,NO_DOTS_SLASH:g,QMARK:S,QMARK_NO_DOT:A,STAR:$,START_ANCHOR:P}=l,N=O=>`(${a}(?:(?!${P}${O.dot?d:u}).)*?)`,v=r.dot?"":m,_=r.dot?S:A,L=r.bash===true?N(r):$;r.capture&&(L=`(${L})`),typeof r.noext=="boolean"&&(r.noextglob=r.noext);let w={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=ze.removePrefix(e,w),s=e.length;let I=[],T=[],q=[],E=i,x,U=()=>w.index===s-1,j=w.peek=(O=1)=>e[w.index+O],z=w.advance=()=>e[++w.index]||"",Me=()=>e.slice(w.index+1),Ce=(O="",re=0)=>{w.consumed+=O,w.index+=re;},st=O=>{w.output+=O.output!=null?O.output:O.value,Ce(O.value);},Lh=()=>{let O=1;for(;j()==="!"&&(j(2)!=="("||j(3)==="?");)z(),w.start++,O++;return O%2===0?false:(w.negated=true,w.start++,true)},Rn=O=>{w[O]++,q.push(O);},gt=O=>{w[O]--,q.pop();},G=O=>{if(E.type==="globstar"){let re=w.braces>0&&(O.type==="comma"||O.type==="brace"),C=O.extglob===true||I.length&&(O.type==="pipe"||O.type==="paren");O.type!=="slash"&&O.type!=="paren"&&!re&&!C&&(w.output=w.output.slice(0,-E.output.length),E.type="star",E.value="*",E.output=L,w.output+=E.output);}if(I.length&&O.type!=="paren"&&(I[I.length-1].inner+=O.value),(O.value||O.output)&&st(O),E&&E.type==="text"&&O.type==="text"){E.output=(E.output||E.value)+O.value,E.value+=O.value;return}O.prev=E,o.push(O),E=O;},kn=(O,re)=>{let C={...c[re],conditions:1,inner:""};C.prev=E,C.parens=w.parens,C.output=w.output;let W=(r.capture?"(":"")+C.open;Rn("parens"),G({type:O,value:re,output:w.output?"":h}),G({type:"paren",extglob:true,value:z(),output:W}),I.push(C);},Ih=O=>{let re=O.close+(r.capture?")":""),C;if(O.type==="negate"){let W=L;if(O.inner&&O.inner.length>1&&O.inner.includes("/")&&(W=N(r)),(W!==L||U()||/^\)+$/.test(Me()))&&(re=O.close=`)$))${W}`),O.inner.includes("*")&&(C=Me())&&/^\.[^\\/.]+$/.test(C)){let ae=Zo(C,{...t,fastpaths:false}).output;re=O.close=`)${ae})${W})`;}O.prev.type==="bos"&&(w.negatedExtglob=true);}G({type:"paren",extglob:true,value:x,output:re}),gt("parens");};if(r.fastpaths!==false&&!/(^[*!]|[/()[\]{}"])/.test(e)){let O=false,re=e.replace(Kb,(C,W,ae,xe,pe,Ai)=>xe==="\\"?(O=true,C):xe==="?"?W?W+xe+(pe?S.repeat(pe.length):""):Ai===0?_+(pe?S.repeat(pe.length):""):S.repeat(ae.length):xe==="."?u.repeat(ae.length):xe==="*"?W?W+xe+(pe?L:""):L:W?C:`\\${C}`);return O===true&&(r.unescape===true?re=re.replace(/\\/g,""):re=re.replace(/\\+/g,C=>C.length%2===0?"\\\\":C?"\\":"")),re===e&&r.contains===true?(w.output=e,w):(w.output=ze.wrapOutput(re,w,t),w)}for(;!U();){if(x=z(),x==="\0")continue;if(x==="\\"){let C=j();if(C==="/"&&r.bash!==true||C==="."||C===";")continue;if(!C){x+="\\",G({type:"text",value:x});continue}let W=/^\\+/.exec(Me()),ae=0;if(W&&W[0].length>2&&(ae=W[0].length,w.index+=ae,ae%2!==0&&(x+="\\")),r.unescape===true?x=z():x+=z(),w.brackets===0){G({type:"text",value:x});continue}}if(w.brackets>0&&(x!=="]"||E.value==="["||E.value==="[^")){if(r.posix!==false&&x===":"){let C=E.value.slice(1);if(C.includes("[")&&(E.posix=true,C.includes(":"))){let W=E.value.lastIndexOf("["),ae=E.value.slice(0,W),xe=E.value.slice(W+2),pe=zb[xe];if(pe){E.value=ae+pe,w.backtrack=true,z(),!i.output&&o.indexOf(E)===1&&(i.output=h);continue}}}(x==="["&&j()!==":"||x==="-"&&j()==="]")&&(x=`\\${x}`),x==="]"&&(E.value==="["||E.value==="[^")&&(x=`\\${x}`),r.posix===true&&x==="!"&&E.value==="["&&(x="^"),E.value+=x,st({value:x});continue}if(w.quotes===1&&x!=='"'){x=ze.escapeRegex(x),E.value+=x,st({value:x});continue}if(x==='"'){w.quotes=w.quotes===1?0:1,r.keepQuotes===true&&G({type:"text",value:x});continue}if(x==="("){Rn("parens"),G({type:"paren",value:x});continue}if(x===")"){if(w.parens===0&&r.strictBrackets===true)throw new SyntaxError(Zt("opening","("));let C=I[I.length-1];if(C&&w.parens===C.parens+1){Ih(I.pop());continue}G({type:"paren",value:x,output:w.parens?")":"\\)"}),gt("parens");continue}if(x==="["){if(r.nobracket===true||!Me().includes("]")){if(r.nobracket!==true&&r.strictBrackets===true)throw new SyntaxError(Zt("closing","]"));x=`\\${x}`;}else Rn("brackets");G({type:"bracket",value:x});continue}if(x==="]"){if(r.nobracket===true||E&&E.type==="bracket"&&E.value.length===1){G({type:"text",value:x,output:`\\${x}`});continue}if(w.brackets===0){if(r.strictBrackets===true)throw new SyntaxError(Zt("opening","["));G({type:"text",value:x,output:`\\${x}`});continue}gt("brackets");let C=E.value.slice(1);if(E.posix!==true&&C[0]==="^"&&!C.includes("/")&&(x=`/${x}`),E.value+=x,st({value:x}),r.literalBrackets===false||ze.hasRegexChars(C))continue;let W=ze.escapeRegex(E.value);if(w.output=w.output.slice(0,-E.value.length),r.literalBrackets===true){w.output+=W,E.value=W;continue}E.value=`(${a}${W}|${E.value})`,w.output+=E.value;continue}if(x==="{"&&r.nobrace!==true){Rn("braces");let C={type:"brace",value:x,output:"(",outputIndex:w.output.length,tokensIndex:w.tokens.length};T.push(C),G(C);continue}if(x==="}"){let C=T[T.length-1];if(r.nobrace===true||!C){G({type:"text",value:x,output:x});continue}let W=")";if(C.dots===true){let ae=o.slice(),xe=[];for(let pe=ae.length-1;pe>=0&&(o.pop(),ae[pe].type!=="brace");pe--)ae[pe].type!=="dots"&&xe.unshift(ae[pe].value);W=Jb(xe,r),w.backtrack=true;}if(C.comma!==true&&C.dots!==true){let ae=w.output.slice(0,C.outputIndex),xe=w.tokens.slice(C.tokensIndex);C.value=C.output="\\{",x=W="\\}",w.output=ae;for(let pe of xe)w.output+=pe.output||pe.value;}G({type:"brace",value:x,output:W}),gt("braces"),T.pop();continue}if(x==="|"){I.length>0&&I[I.length-1].conditions++,G({type:"text",value:x});continue}if(x===","){let C=x,W=T[T.length-1];W&&q[q.length-1]==="braces"&&(W.comma=true,C="|"),G({type:"comma",value:x,output:C});continue}if(x==="/"){if(E.type==="dot"&&w.index===w.start+1){w.start=w.index+1,w.consumed="",w.output="",o.pop(),E=i;continue}G({type:"slash",value:x,output:f});continue}if(x==="."){if(w.braces>0&&E.type==="dot"){E.value==="."&&(E.output=u);let C=T[T.length-1];E.type="dots",E.output+=x,E.value+=x,C.dots=true;continue}if(w.braces+w.parens===0&&E.type!=="bos"&&E.type!=="slash"){G({type:"text",value:x,output:u});continue}G({type:"dot",value:x,output:u});continue}if(x==="?"){if(!(E&&E.value==="(")&&r.noextglob!==true&&j()==="("&&j(2)!=="?"){kn("qmark",x);continue}if(E&&E.type==="paren"){let W=j(),ae=x;(E.value==="("&&!/[!=<:]/.test(W)||W==="<"&&!/<([!=]|\w+>)/.test(Me()))&&(ae=`\\${x}`),G({type:"text",value:x,output:ae});continue}if(r.dot!==true&&(E.type==="slash"||E.type==="bos")){G({type:"qmark",value:x,output:A});continue}G({type:"qmark",value:x,output:S});continue}if(x==="!"){if(r.noextglob!==true&&j()==="("&&(j(2)!=="?"||!/[!=<:]/.test(j(3)))){kn("negate",x);continue}if(r.nonegate!==true&&w.index===0){Lh();continue}}if(x==="+"){if(r.noextglob!==true&&j()==="("&&j(2)!=="?"){kn("plus",x);continue}if(E&&E.value==="("||r.regex===false){G({type:"plus",value:x,output:p});continue}if(E&&(E.type==="bracket"||E.type==="paren"||E.type==="brace")||w.parens>0){G({type:"plus",value:x});continue}G({type:"plus",value:p});continue}if(x==="@"){if(r.noextglob!==true&&j()==="("&&j(2)!=="?"){G({type:"at",extglob:true,value:x,output:""});continue}G({type:"text",value:x});continue}if(x!=="*"){(x==="$"||x==="^")&&(x=`\\${x}`);let C=Vb.exec(Me());C&&(x+=C[0],w.index+=C[0].length),G({type:"text",value:x});continue}if(E&&(E.type==="globstar"||E.star===true)){E.type="star",E.star=true,E.value+=x,E.output=L,w.backtrack=true,w.globstar=true,Ce(x);continue}let O=Me();if(r.noextglob!==true&&/^\([^?]/.test(O)){kn("star",x);continue}if(E.type==="star"){if(r.noglobstar===true){Ce(x);continue}let C=E.prev,W=C.prev,ae=C.type==="slash"||C.type==="bos",xe=W&&(W.type==="star"||W.type==="globstar");if(r.bash===true&&(!ae||O[0]&&O[0]!=="/")){G({type:"star",value:x,output:""});continue}let pe=w.braces>0&&(C.type==="comma"||C.type==="brace"),Ai=I.length&&(C.type==="pipe"||C.type==="paren");if(!ae&&C.type!=="paren"&&!pe&&!Ai){G({type:"star",value:x,output:""});continue}for(;O.slice(0,3)==="/**";){let Pn=e[w.index+4];if(Pn&&Pn!=="/")break;O=O.slice(3),Ce("/**",3);}if(C.type==="bos"&&U()){E.type="globstar",E.value+=x,E.output=N(r),w.output=E.output,w.globstar=true,Ce(x);continue}if(C.type==="slash"&&C.prev.type!=="bos"&&!xe&&U()){w.output=w.output.slice(0,-(C.output+E.output).length),C.output=`(?:${C.output}`,E.type="globstar",E.output=N(r)+(r.strictSlashes?")":"|$)"),E.value+=x,w.globstar=true,w.output+=C.output+E.output,Ce(x);continue}if(C.type==="slash"&&C.prev.type!=="bos"&&O[0]==="/"){let Pn=O[1]!==void 0?"|$":"";w.output=w.output.slice(0,-(C.output+E.output).length),C.output=`(?:${C.output}`,E.type="globstar",E.output=`${N(r)}${f}|${f}${Pn})`,E.value+=x,w.output+=C.output+E.output,w.globstar=true,Ce(x+z()),G({type:"slash",value:"/",output:""});continue}if(C.type==="bos"&&O[0]==="/"){E.type="globstar",E.value+=x,E.output=`(?:^|${f}|${N(r)}${f})`,w.output=E.output,w.globstar=true,Ce(x+z()),G({type:"slash",value:"/",output:""});continue}w.output=w.output.slice(0,-E.output.length),E.type="globstar",E.output=N(r),E.value+=x,w.output+=E.output,w.globstar=true,Ce(x);continue}let re={type:"star",value:x,output:L};if(r.bash===true){re.output=".*?",(E.type==="bos"||E.type==="slash")&&(re.output=v+re.output),G(re);continue}if(E&&(E.type==="bracket"||E.type==="paren")&&r.regex===true){re.output=x,G(re);continue}(w.index===w.start||E.type==="slash"||E.type==="dot")&&(E.type==="dot"?(w.output+=b,E.output+=b):r.dot===true?(w.output+=g,E.output+=g):(w.output+=v,E.output+=v),j()!=="*"&&(w.output+=h,E.output+=h)),G(re);}for(;w.brackets>0;){if(r.strictBrackets===true)throw new SyntaxError(Zt("closing","]"));w.output=ze.escapeLast(w.output,"["),gt("brackets");}for(;w.parens>0;){if(r.strictBrackets===true)throw new SyntaxError(Zt("closing",")"));w.output=ze.escapeLast(w.output,"("),gt("parens");}for(;w.braces>0;){if(r.strictBrackets===true)throw new SyntaxError(Zt("closing","}"));w.output=ze.escapeLast(w.output,"{"),gt("braces");}if(r.strictSlashes!==true&&(E.type==="star"||E.type==="bracket")&&G({type:"maybe_slash",value:"",output:`${f}?`}),w.backtrack===true){w.output="";for(let O of w.tokens)w.output+=O.output!=null?O.output:O.value,O.suffix&&(w.output+=O.suffix);}return w};Zo.fastpaths=(e,t)=>{let r={...t},n=typeof r.maxLength=="number"?Math.min(_s,r.maxLength):_s,s=e.length;if(s>n)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${n}`);e=Zp[e]||e;let{DOT_LITERAL:i,SLASH_LITERAL:o,ONE_CHAR:a,DOTS_SLASH:l,NO_DOT:c,NO_DOTS:u,NO_DOTS_SLASH:p,STAR:f,START_ANCHOR:h}=xs.globChars(r.windows),d=r.dot?u:c,m=r.dot?p:c,b=r.capture?"":"?:",g={negated:false,prefix:""},S=r.bash===true?".*?":f;r.capture&&(S=`(${S})`);let A=v=>v.noglobstar===true?S:`(${b}(?:(?!${h}${v.dot?l:i}).)*?)`,$=v=>{switch(v){case "*":return `${d}${a}${S}`;case ".*":return `${i}${a}${S}`;case "*.*":return `${d}${S}${i}${a}${S}`;case "*/*":return `${d}${S}${o}${a}${m}${S}`;case "**":return d+A(r);case "**/*":return `(?:${d}${A(r)}${o})?${m}${a}${S}`;case "**/*.*":return `(?:${d}${A(r)}${o})?${m}${S}${i}${a}${S}`;case "**/.*":return `(?:${d}${A(r)}${o})?${i}${a}${S}`;default:{let _=/^(.*?)\.(\w+)$/.exec(v);if(!_)return;let L=$(_[1]);return L?L+i+_[2]:void 0}}},P=ze.removePrefix(e,g),N=$(P);return N&&r.strictSlashes!==true&&(N+=`${o}?`),N};ef.exports=Zo;});var sf=it((AC,nf)=>{var Xb=Qp(),ea=tf(),rf=Mr(),Yb=Fr(),Qb=e=>e&&typeof e=="object"&&!Array.isArray(e),le=(e,t,r=false)=>{if(Array.isArray(e)){let u=e.map(f=>le(f,t,r));return f=>{for(let h of u){let d=h(f);if(d)return d}return false}}let n=Qb(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?le.compileRe(e,t):le.makeRe(e,t,false,true),a=o.state;delete o.state;let l=()=>false;if(s.ignore){let u={...t,ignore:null,onMatch:null,onResult:null};l=le(s.ignore,u,r);}let c=(u,p=false)=>{let{isMatch:f,match:h,output:d}=le.test(u,o,t,{glob:e,posix:i}),m={glob:e,state:a,regex:o,posix:i,input:u,output:d,match:h,isMatch:f};return typeof s.onResult=="function"&&s.onResult(m),f===false?(m.isMatch=false,p?m:false):l(u)?(typeof s.onIgnore=="function"&&s.onIgnore(m),m.isMatch=false,p?m:false):(typeof s.onMatch=="function"&&s.onMatch(m),p?m:true)};return r&&(c.state=a),c};le.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?rf.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=le.matchBase(e,t,r,s):a=t.exec(l)),{isMatch:!!a,match:a,output:l}};le.matchBase=(e,t,r)=>(t instanceof RegExp?t:le.makeRe(t,r)).test(rf.basename(e));le.isMatch=(e,t,r)=>le(t,r)(e);le.parse=(e,t)=>Array.isArray(e)?e.map(r=>le.parse(r,t)):ea(e,{...t,fastpaths:false});le.scan=(e,t)=>Xb(e,t);le.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=le.toRegex(a,t);return n===true&&(l.state=e),l};le.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=ea.fastpaths(e,t)),s.output||(s=ea(e,t)),le.compileRe(s,t,r,n)};le.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 /$^/}};le.constants=Yb;nf.exports=le;});var cf=it((CC,lf)=>{var of=sf(),Zb=Mr();function af(e,t,r=false){return t&&(t.windows===null||t.windows===void 0)&&(t={...t,windows:Zb.isWindows()}),of(e,t,r)}Object.assign(af,of);lf.exports=af;});function nS(e,t={}){let r=e.length,n=Array(r),s=Array(r),i=!t.noglobstar;for(let o=0;o<r;o++){let a=mf(e[o]);n[o]=a;let l=a.length,c=Array(l);for(let u=0;u<l;u++)c[u]=(0, rr.default)(a[u],t);s[o]=c;}return o=>{let a=o.split("/");if(a[0]===".."&&rS.test(o))return true;for(let l=0;l<e.length;l++){let c=n[l],u=s[l],p=a.length,f=Math.min(p,c.length),h=0;for(;h<f;){let d=c[h];if(d.includes("/"))return true;if(!u[h](a[h]))break;if(i&&d==="**")return true;h++;}if(h===p)return true}return false}}function uf(e,t,r){if(e===t||t.startsWith(`${e}/`)){if(r){let s=iS(e)?e.length:e.length+1;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 oS(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.endsWith("/")&&n!==""?`${n}/`:n||"."}}function mf(e){var t;let r=rr.default.scan(e,aS);return !((t=r.parts)===null||t===void 0)&&t.length?r.parts:[e]}function mS(e,t){let r=rr.default.scan(e);return r.isGlob||r.negated}function tr(...e){console.log(`[tinyglobby ${new Date().toLocaleTimeString("es")}]`,...e);}function ta(e,t,r,n,s){let i=e;e.endsWith("/")&&(i=e.slice(0,-1)),!i.endsWith("*")&&t&&(i+="/**");let o=fS(r);pf.isAbsolute(i.replace(hS,""))?i=posix.relative(o,i):i=posix.normalize(i);let a=dS.exec(i),l=mf(i);if(a?.[0]){let u=(a[0].length+1)/3,p=0,f=o.split("/");for(;p<u&&l[p+u]===f[f.length+p-u];)i=i.slice(0,(u-p-1)*3)+i.slice((u-p)*3+l[p+u].length+1)||".",p++;let h=posix.join(r,a[0].slice(p*3));!h.startsWith(".")&&n.root.length>h.length&&(n.root=h,n.depthOffset=-u+p);}if(!s&&n.depthOffset>=0){var c;(c=n.commonPath)!==null&&c!==void 0||(n.commonPath=l);let u=[],p=Math.min(n.commonPath.length,l.length);for(let f=0;f<p;f++){let h=l[f];if(h==="**"&&!l[f+1]){u.pop();break}if(h!==n.commonPath[f]||mS(h)||f===l.length-1)break;u.push(h);}n.depthOffset=u.length,n.commonPath=u,n.root=u.length>0?posix.join(r,...u):r;}return i}function gS({patterns:e=["**/*"],ignore:t=[],expandDirectories:r=true},n,s){typeof e=="string"&&(e=[e]),typeof t=="string"&&(t=[t]);let i=[],o=[];for(let a of t)a&&(a[0]!=="!"||a[1]==="(")&&o.push(ta(a,r,n,s,true));for(let a of e)a&&(a[0]!=="!"||a[1]==="("?i.push(ta(a,r,n,s,false)):(a[1]!=="!"||a[2]==="(")&&o.push(ta(a.slice(1),r,n,s,true)));return {match:i,ignore:o}}function yS(e,t){for(let r=e.length-1;r>=0;r--){let n=e[r];e[r]=t(n);}return e}function wS(e){return e?e instanceof URL?fileURLToPath$1(e).replace($s,"/"):pf.resolve(e).replace($s,"/"):process.cwd().replace($s,"/")}function bS(e,t={}){let r=process.env.TINYGLOBBY_DEBUG?{...t,debug:true}:t,n=wS(r.cwd);if(r.debug&&tr("globbing with:",{patterns:e,options:r,cwd:n}),Array.isArray(e)&&e.length===0)return [{sync:()=>[],withPromise:async()=>[]},false];let s={root:n,commonPath:null,depthOffset:0},i=gS({...r,patterns:e},n,s);r.debug&&tr("internal processing patterns:",i);let o={dot:r.dot,nobrace:r.braceExpansion===false,nocase:r.caseSensitiveMatch===false,noextglob:r.extglob===false,noglobstar:r.globstar===false,posix:true},a=(0, rr.default)(i.match,{...o,ignore:i.ignore}),l=(0, rr.default)(i.ignore,o),c=nS(i.match,o),u=uf(n,s.root,r.absolute),p=r.absolute?u:uf(n,s.root,true),f={filters:[r.debug?(m,b)=>{let g=u(m,b),S=a(g);return S&&tr(`matched ${g}`),S}:(m,b)=>a(u(m,b))],exclude:r.debug?(m,b)=>{let g=p(b,true),S=g!=="."&&!c(g)||l(g);return tr(S?`skipped ${b}`:`crawling ${b}`),S}:(m,b)=>{let g=p(b,true);return g!=="."&&!c(g)||l(g)},fs:r.fs?{readdir:r.fs.readdir||er__default.readdir,readdirSync:r.fs.readdirSync||er__default.readdirSync,realpath:r.fs.realpath||er__default.realpath,realpathSync:r.fs.realpathSync||er__default.realpathSync,stat:r.fs.stat||er__default.stat,statSync:r.fs.statSync||er__default.statSync}:void 0,pathSeparator:"/",relativePaths:true,resolveSymlinks:true,signal:r.signal};r.deep!==void 0&&(f.maxDepth=Math.round(r.deep-s.depthOffset)),r.absolute&&(f.relativePaths=false,f.resolvePaths=true,f.includeBasePath=true),r.followSymbolicLinks===false&&(f.resolveSymlinks=false,f.excludeSymlinks=true),r.onlyDirectories?(f.excludeFiles=true,f.includeDirs=true):r.onlyFiles===false&&(f.includeDirs=true),s.root=s.root.replace($s,"");let h=s.root;r.debug&&tr("internal properties:",s);let d=n!==h&&!r.absolute&&oS(n,s.root);return [new Fp(f).crawl(h),d]}async function Br(e,t){if(e&&t?.patterns)throw new Error("Cannot pass patterns as both an argument and an option");let r=tS(e)||typeof e=="string",n=r?t:e,s=r?e:e.patterns,[i,o]=bS(s,n);return o?yS(await i.withPromise(),o):i.withPromise()}var rr,tS,ff,rS,sS,iS,aS,lS,cS,uS,pS,fS,dS,hS,$s,ra=y(()=>{Mp();rr=ee(cf()),tS=Array.isArray,ff=process.platform==="win32",rS=/^(\/?\.\.)+$/;sS=/^[A-Z]:\/$/i,iS=ff?e=>sS.test(e):e=>e==="/";aS={parts:true};lS=/(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g,cS=/(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g,uS=e=>e.replace(lS,"\\$&"),pS=e=>e.replace(cS,"\\$&"),fS=ff?pS:uS;dS=/^(\/?\.\.)+/,hS=/\\(?=[()[\]{}!*+?@|])/g,$s=/\\/g;});function hf(e){return e.config?.db?.driver==="sqlite"?"./sqlite-migrations/*.sql":"./migrations/*.sql"}function Tt(e){return He__default.posix.dirname(hf(e))}async function Ve(e){let t=He__default.join(process.cwd(),"supabase"),r=await Br([hf(e)],{cwd:t,absolute:true}),n=[];for(let s of r){let i=He__default.basename(s),o=SS.exec(i);if(!o)continue;let a=await ce__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 vs(e){return (await Ve(e)).map(r=>r.sql).join(`
|
|
63
|
+
`)}function na(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 sa(e,t=na()){let r=e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"");return r.length>0?`${t}_${r}.sql`:`${t}.sql`}async function gf(e,t,r){let n=He__default.join(process.cwd(),"supabase",Tt(e));Re(n);let s=sa(t,r?.ts),i=He__default.join(n,s);return await ce__default.writeFile(i,"",{flag:"wx"}),i}var SS,At=y(()=>{ra();wt();SS=/^(\d{14})(?:_([^.]+))?\.sql$/;});function Hr(e){if("String"in e)return e.String.sval}function Ct(e){return e.map(Hr).filter(t=>t!=null)}function Rt(e){return e==null?[]:e.List!==void 0?e.List.items||[]:Array.isArray(e)?e:[e]}function Ts(e){return QuoteUtils.quoteIdentifier(e)}function nr(e){return Object.keys(e)[0]}function yf(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 kt=y(()=>{});function bf(e){let t=e.toLowerCase().trim();if(t.startsWith("_")||t.endsWith("[]"))return "TEXT";let r=_S[t];if(!r)throw new Pt(`Unsupported PostgreSQL type: "${e}"`);return r}function As(e){let t=e.toLowerCase();return ["serial","serial4","bigserial","serial8","smallserial","serial2"].includes(t)}function Cs(e){let t=e.toLowerCase();return ["varchar","character varying","char","character","bpchar"].includes(t)}function Rs(e){let t=e.toLowerCase();return ["numeric","decimal"].includes(t)}var Pt,B,_S,wf,$S,ks,sr=y(()=>{kt();Pt=class extends Error{},B=class extends Pt{constructor(r,n){super(n??`Unsupported node type: ${nr(r)}`);this.node=r;}},_S={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"},wf=["<",">","<=",">=","=","<>","!=","+","-","*","/","%","&","|","<<",">>","||","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","->>"];$S={CreateEnumStmt:{react:"ignore"},CreateDomainStmt:{react:"warn"},CreateSeqStmt:{react:"error"},AlterSeqStmt:{react:"error"},CreateSchemaStmt:{react:"warn"},CreatePolicyStmt:{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"}},ks=new Map(Object.entries($S));});var De,Wr,ia=y(()=>{kt();sr();De=class extends B{constructor(t,r){super(t,`Unsupported expression: ${r}`);}},Wr=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 De({[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 De({[r]:t},`deparseValue: ${r}`)}A_Expr(t){if(t.kind==="AEXPR_OP"){let r=t.name?.[0],n=r?Hr(r):void 0;if(!n)throw new De({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 De({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]?Hr(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 De({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 De({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 De({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),u=this.deparseGroupClause(t.groupClause),p={type:"query",from:r,select:i};return n&&(p.schema=n),Object.keys(s).length>0&&(p.join=s),o&&(p.where=o),a.length>0&&(p.order=a),l!==void 0&&(p.limit=l),c!==void 0&&(p.offset=c),u.length>0&&(p.group=u),p}FuncCall(t){let r=this.isAuthFunc(t.funcname??[]);if(r)return r;throw new De({FuncCall:t},`FuncCall: ${Ct(t.funcname??[]).join(".")}`)}ColumnRef(t){let r=Ct(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 De({A_Const:t},"A_Const: unknown variant")}TypeCast(t){if(!t.arg)throw new De({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 u=2;for(;`${c}_${u}`in r;)u++;c=`${c}_${u}`;}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=Ct(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]?Hr(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 Gr,oa=y(()=>{Gr=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 zr,aa=y(()=>{zr=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 he,et=y(()=>{aa();he=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 zr(this.context.table,this.context.column,t,r)}quoteIfNeeded(t){return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)?t:`"${t}"`}};});var Nt,Ps=y(()=>{et();Nt=class extends he{get sqliteType(){return "INTEGER"}};});var Vr,la=y(()=>{Ps();Vr=class extends Nt{constructor(t){super({...t,isSerial:true});}};});function vS(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 Ot,Ns=y(()=>{et();Ot=class extends he{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(!vS(t,this.numericPrecision))return this.validationFail(`Does not fit numeric(${r}, ${n}).`,"Patch rows within numeric precision.")}return this.validationPass()}};});var ie,je=y(()=>{et();ie=class extends he{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 Kr,ca=y(()=>{et();Kr=class extends he{get sqliteType(){return "BLOB"}};});var Jr,ua=y(()=>{et();Jr=class extends he{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){return this.isNullish(t)?t:t===1?true:t===0?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 Sf(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var Xr,pa=y(()=>{et();Xr=class extends he{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=Sf(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."):Sf(t).ok?this.validationPass():this.validationFail("Invalid JSON text.","Patch rows with valid JSON.")}};});function TS(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 Yr,fa=y(()=>{je();Yr=class extends ie{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"||!TS(t)?this.validationFail("Invalid date.","Patch rows with YYYY-MM-DD dates."):this.validationPass()}};});function AS(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 Qr,ma=y(()=>{je();Qr=class extends ie{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"||!AS(t)?this.validationFail("Invalid time.","Patch rows with HH:MM[:SS] times."):this.validationPass()}};});function CS(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]),u=new Date(Date.UTC(r,n-1,s)),p=u.getUTCFullYear()===r&&u.getUTCMonth()===n-1&&u.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 p&&f&&h}var Zr,da=y(()=>{je();Zr=class extends ie{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"||!CS(t)?this.validationFail("Invalid timestamp.","Patch rows with ISO timestamps."):this.validationPass()}};});var en,ha=y(()=>{je();en=class extends ie{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 tn,ga=y(()=>{je();tn=class extends ie{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 Ef(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var ut,Os=y(()=>{et();ut=class extends he{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=Ef(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=Ef(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 xf(e){return kS.test(e.toLowerCase())}var RS,kS,rn,ya=y(()=>{je();RS="????????-????-????-????-????????????",kS=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;rn=class extends ie{get isShimBacked(){return true}checkConstraint(){let t=this.quoteIfNeeded(this.context.column);return `${t} IS NULL OR ${t} GLOB '${RS}'`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string")throw this.checkError("uuid_format",t);let r=t.toLowerCase();if(!xf(r))throw this.checkError("uuid_format",t);return r}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!xf(t)?this.validationFail("Invalid UUID.","Patch rows with valid UUIDs."):this.validationPass()}};});function PS(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 NS(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 OS(e){if(!e.includes(":"))return false;try{return new URL(`http://[${e}]/`),!0}catch{return false}}function _f(e){let t=PS(e);return t?NS(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=32:OS(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=128:false:false}var nn,wa=y(()=>{je();nn=class extends ie{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(!_f(r))throw this.checkError("inet_format",t);return r}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!_f(t.trim())?this.validationFail("Invalid inet address.","Patch rows with valid inet strings."):this.validationPass()}};});var sn,ba=y(()=>{je();sn=class extends ie{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 Lt(e,t){if(t?.isArray){let n=Lt(e,{...t,isArray:false});return new ut(e,n)}if(t?.enumValues)return new tn(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=Lt(s);return new ut(e,i)}return IS.has(r)?new Vr(e):LS.has(r)?new Nt(e):MS.has(r)?new Jr(e):US.has(r)?new Xr(e):WS.has(r)?new Yr(e):GS.has(r)?new Qr(e):zS.has(r)?new Zr(e):VS.has(r)?new en(e):FS.has(r)?new Kr(e):DS.has(r)?new Ot(e,t?.numericPrecision):BS.has(r)?new rn(e):qS.has(r)?new ie(e,63):HS.has(r)?new nn(e):jS.has(r)?new ie(e,t?.lengthConstraint):new sn(e)}var LS,IS,DS,jS,FS,MS,US,BS,qS,HS,WS,GS,zS,VS,Sa=y(()=>{Ps();la();Ns();je();ca();ua();pa();fa();ma();da();ha();ga();Os();ya();wa();ba();LS=new Set(["int2","smallint","int4","integer","int","int8","bigint"]),IS=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]),DS=new Set(["float4","real","float8","double precision","numeric","decimal"]),jS=new Set(["text","varchar","character varying","char","character","bpchar"]),FS=new Set(["bytea"]),MS=new Set(["bool","boolean"]),US=new Set(["json","jsonb"]),BS=new Set(["uuid"]),qS=new Set(["name"]),HS=new Set(["inet"]),WS=new Set(["date"]),GS=new Set(["time","timetz","time without time zone","time with time zone"]),zS=new Set(["timestamp","timestamptz","timestamp without time zone","timestamp with time zone"]),VS=new Set(["interval"]);});function Ea(e,t="auto"){let r=e.toLowerCase(),n=Ls[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 $f,Ls,xa=y(()=>{$f="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)))",Ls={gen_random_uuid:{sqlite:()=>$f,js:()=>crypto.randomUUID()},uuid_generate_v4:{sqlite:()=>$f,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 on,vf=y(()=>{on=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 Tf=y(()=>{et();aa();Ps();la();Ns();je();ca();ua();pa();fa();ma();da();ha();ga();Os();ya();wa();ba();Sa();xa();vf();});var ka={};fe(ka,{_resetWarnedMissingToClauseForTests:()=>KS,collectComments:()=>Ra,collectEnums:()=>$a,collectPolicies:()=>Ta,collectSchema:()=>Aa,collectTableConstraints:()=>Ca,collectVariables:()=>va});function KS(){_a.clear();}function $a(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=Ct(n.typeName??[]).join(".");if(!s||!n.vals)continue;let i=Ct(n.vals);t.set(s.toLowerCase(),i);}return t}function va(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=yf(n.args?.[0]??{});t.set(s,{value:i,local:n.is_local});}return t}function Ta(e){let t=new Wr,r=new Set,n=[];for(let s of e.stmts??[])if(s.stmt){if("CreatePolicyStmt"in s.stmt){let i=s.stmt.CreatePolicyStmt,o=i.table?.relname??"",a=i.table?.schemaname,l={select:"SELECT",insert:"INSERT",update:"UPDATE",delete:"DELETE"},c=i.cmd_name?l[i.cmd_name]??"ALL":"ALL",u=i.permissive===true,p=[],f=false;for(let b of i.roles??[])if("RoleSpec"in b){let g=b.RoleSpec;g.roletype==="ROLESPEC_PUBLIC"?g.location===-1&&(f=true):g.roletype==="ROLESPEC_CSTRING"&&g.rolename&&p.push(g.rolename);}if(f){let b=a?`${a}.${o}`:o,g=i.policy_name??"",S=`${b}::${g}`;_a.has(S)||(_a.add(S),console.warn(`[supalite] policy "${g}" on "${b}" has no TO clause \u2014 applies to all roles (PUBLIC). For clarity, prefer an explicit \`TO <role>\` clause (e.g. \`TO authenticated\`).`));}let h=i.qual?t.deparse(i.qual):void 0,d=i.with_check?t.deparse(i.with_check):void 0,m=new Gr({name:i.policy_name??"",table:o,schema:a,command:c,permissive:u,roles:p,using:h,withCheck:d});n.push(m);}if("AlterTableStmt"in s.stmt){let i=s.stmt.AlterTableStmt;if((i.cmds??[]).some(l=>"AlterTableCmd"in l&&(l.AlterTableCmd.subtype==="AT_EnableRowSecurity"||l.AlterTableCmd.subtype==="AT_ForceRowSecurity"))){let l=i.relation?.relname??"";r.add(l);}}}return {policies:n,tables:r}}function Aa(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 on(i,o);for(let l of s.tableElts??[]){if(!("ColumnDef"in l))continue;let c=l.ColumnDef,u=c.colname;if(!u)continue;let p=c.typeName?.names?.map(T=>T.String?.sval||T.String?.str).filter(Boolean),f=p&&(p.length===2&&p[0]==="pg_catalog"?p[1]:p[0]);if(!f)continue;let h=!!c.typeName?.arrayBounds?.length,d=Array.isArray(c.typeName?.typmods)?c.typeName.typmods:[],m=T=>d[T]?.A_Const?.ival?.ival??d[T]?.A_Const?.val?.ival?.ival,b={isArray:h};if(Cs(f)&&d.length>0){let T=m(0);typeof T=="number"&&T>0&&(b.lengthConstraint=T);}if(Rs(f)&&d.length>=2){let T=m(0),q=m(1);typeof T=="number"&&typeof q=="number"&&T>0&&q>=0&&(b.numericPrecision={precision:T,scale:q});}let g=t.get(f.toLowerCase());g&&(b.enumValues=g);let S=Array.isArray(c.constraints)?c.constraints:[],A=S.some(T=>T.Constraint?.contype==="CONSTR_PRIMARY"),$=As(f)||S.some(T=>T.Constraint?.contype==="CONSTR_IDENTITY"),P=S.some(T=>T.Constraint?.contype==="CONSTR_NOTNULL"),N=S.find(T=>T.Constraint?.contype==="CONSTR_UNIQUE"),v=S.find(T=>T.Constraint?.contype==="CONSTR_GENERATED"),_=S.find(T=>T.Constraint?.contype==="CONSTR_FOREIGN"),L=S.find(T=>T.Constraint?.contype==="CONSTR_CHECK"),w;if(_){let T=_.Constraint,q=T.pktable?.relname,E=T.pktable?.schemaname,x=T.pk_attrs?.[0]?.String?.sval;q&&x&&(w={refSchema:E,refTable:q,refColumn:x,constraintName:T.conname||void 0});}let I={schema:o,table:i,column:u,pgTypeName:f,nullable:!P&&!A,defaultValue:null,defaultFn:null,isPrimaryKey:A,isUnique:!!N,isSerial:$,isGenerated:!!v,fkRef:w,hasCheck:!!L,checkConstraintName:L?.Constraint?.conname||void 0,uniqueConstraintName:N?.Constraint?.conname||void 0};a.set(u,Lt(I,b));}r.set(`${o}.${i}`,a);}return r}function Ca(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 u=(l.keys??[]).map(p=>p.String?.sval??p.String?.str).filter(Boolean);if(u.length===0)continue;t.push({schema:i,table:s,kind:"unique",name:l.conname||void 0,columns:u});}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 u=(l.fk_attrs??[]).map(h=>h.String?.sval??h.String?.str).filter(Boolean),p=(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:u,refSchema:l.pktable?.schemaname,refTable:f,refColumns:p});}}}return t}function Ra(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 _a,Pa=y(()=>{ia();kt();oa();Tf();sr();_a=new Set;});async function ln(e,t){let r=await e.connection.introspect(),n=Na(r);await Nf(e,{...t,dbHasTables:r.tables.length>0,dbFingerprint:n}),r.tables.length===0&&await Oa(e);let s=await e.connection.introspect();Lf(s,e);}async function YS(e){let t=await Br(e.config.db?.seed?.sql_paths??["./seed.sql"],{cwd:He__default.join(process.cwd(),"supabase"),absolute:true});return (await Promise.all(t.map(n=>ce__default.readFile(n,"utf-8")))).flatMap(n=>splitSqlStatements(n))}async function cn(e,t){let r=await YS(e);if(r.length===0)return 0;console.log(F.default.dim("Seeding database..."));try{return await e.connection.transaction(r),r.length}catch(n){let s=t?.recoveryHint??"Fix `supabase/seed.sql`, then run `bun run dev --recreate` to reset and reseed.";throw new Error(`Seed failed and was rolled back: ${String(n.message??n)}
|
|
64
|
+
${s}`)}}async function Oa(e){await cn(e);}async function ue(e){let t=await Br(e.config?.db?.migrations?.schema_paths??["./schemas/*.sql"],{cwd:He__default.join(process.cwd(),"supabase"),absolute:true}),r=await Promise.all(t.map(async n=>await ce__default.readFile(n,"utf-8"))).then(n=>n.map(s=>s.split(`
|
|
65
65
|
`).filter(i=>i.trim().length>0&&!i.trim().startsWith("--")).join(`
|
|
66
66
|
`)).join(`
|
|
67
|
-
`));return r||""}async function
|
|
67
|
+
`));return r||""}async function Nf(e,t){let r=await ue(e);if(!(!r&&(await Ve(e)).length>0)&&!(!r&&!e.connection.config.baseSchema)){if(t?.dbHasTables&&await ZS(e,r,t.dbFingerprint)){console.log(F.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=Na(o);if(s.plan.steps.length===0){await Cf(e,r,i,a);return}await n.migratePlan(s.plan,{force:t?.force??!1}),La(s);let l=await e.connection.introspect();return await Cf(e,r,i,Na(l)),console.log(""),pt(s),s}catch(n){if(String(n).includes("likely empty"))console.log(F.default.dim("Nothing to migrate."));else {console.error("Migration error: "+String(n));try{await e.connection.exec("rollback");}catch{}}}}}function QS(e){return e.connection.config?.baseSchema??""}function Of(e,t){let r=createHash("sha256");return r.update(JSON.stringify([QS(e),t??""])),r.digest("hex")}function Na(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 ZS(e,t,r){let n=e.connection;if(typeof n.updateDeparseInfo!="function")return false;let s=He__default.join(process.cwd(),kf),i;try{i=await ce__default.readFile(s,"utf-8");}catch{return false}let o;try{o=JSON.parse(i);}catch{return false}if(o.v!==Pf||o.hash!==Of(e,t)||!r||o.dbFingerprint!==r||!o.ast||typeof o.ast!="object")return false;try{let a=await Promise.resolve().then(()=>(Pa(),ka)),l=o.ast,c=a.collectEnums(l),u=a.collectSchema(l,c),p=a.collectVariables(l),f=a.collectTableConstraints(l),h=a.collectComments(l),{policies:d,tables:m}=a.collectPolicies(l);return n.updateDeparseInfo({enums:c,rls:{tables:m,policies:d},schema:u,vars:p,tableConstraints:f,comments:h}),!0}catch{return false}}async function Cf(e,t,r,n){if(!r||typeof r!="object")return;let s={v:Pf,hash:Of(e,t),dbFingerprint:n,ast:r},i=He__default.join(process.cwd(),kf);try{await ce__default.mkdir(He__default.dirname(i),{recursive:!0}),await ce__default.writeFile(i,JSON.stringify(s),"utf-8");}catch{}}function Lf(e,t){console.log();let r=(s,i)=>{let o=l=>{let c=F.default.dim;return typeof l=="number"&&(l>=0&&(c=l>0?F.default.green:F.default.dim),l<0&&(c=F.default.red)),typeof l=="boolean"?l?F.default.green("\u2713"):F.default.red("\u2717"):c(String(l))},a=Object.entries(i).map(([l,c])=>`${l}: ${o(c)}`).join(F.default.dim(" / "));console.log(`${F.default.dim("[")} ${s} ${F.default.dim("]")} ${a}`);};r(F.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(F.default.green("AUTH"),{enabled:!!t.config.auth?.enabled,tables:ensureVar.Set(n.tables).size,policies:ensureVar.Array(n.policies).length});}function If(e,t){setTimeout(()=>{console.log(F.default.dim("Watching for changes...")),XS.watch("./supabase/schemas").on("change",async n=>{console.log(),console.log(F.default.dim(`Schema changed: ${n}`)),await Nf(e,t);let s=await e.connection.introspect();Lf(s,e);});},200);}function un(e,t){let r=t?.colorize?F.default.dim:n=>n;return e.plan.steps.flatMap(n=>[n.description?r(`-- ${n.description}`):"",n.sql+`
|
|
68
68
|
`]).filter(n=>n.trim().length>0).join(`
|
|
69
|
-
`)}function
|
|
69
|
+
`)}function eE(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 La(e,t){let r="./supabase/.temp/migrations";Re(r);let n=eE(),s=un(e);yt(He__default.join(r,n),s),console.log(F.default.dim(`Migration written to ${F.default.cyan(He__default.join(r,n))}`));}function Df(e){let t=e.schema_separator??".",r=e.ddl_dialect==="postgres",n=(a,l)=>r&&a?`${a}${t}${l}`:l;console.log(F.default.bgWhite(F.default.black(" Schema "))),console.log();let s=e.tables.filter(a=>a.type==="table"),i=r?"sqlite-postgres":"sqlite";if(console.log(F.default.dim(`${i}${e.version?` (sqlite ${e.version})`:""} \xB7 ${e.database_name}`)),console.log(),s.length===0){console.log(F.default.dim("No tables."));return}console.log(F.default.dim("Tables:"));for(let a of s){let l=n(a.schema,a.name),c=e.columns.filter(p=>p.table===a.name&&(!r||p.schema===a.schema)).sort((p,f)=>p.ordinal_position-f.ordinal_position),u=a.rows>=0?` ${F.default.dim(`(${a.rows} rows)`)}`:"";console.log(`${F.default.bold(l)}${u}`);for(let p of c){let f=[];p.is_primary_key&&f.push(F.default.green("PK")),p.nullable||f.push(F.default.dim("NOT NULL")),p.default_value!==null&&f.push(F.default.dim(`DEFAULT ${p.default_value}`));let h=f.length?" "+f.join(" "):"";console.log(` ${p.name} ${F.default.cyan(p.type)}${h}`);}console.log();}let o=e.indexes.filter(a=>!a.name.startsWith("sqlite_autoindex_"));if(o.length>0){console.log(F.default.dim("Indexes:"));for(let a of o){let l=a.unique?F.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(F.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} ${F.default.dim(`ON DELETE ${a.on_delete} ON UPDATE ${a.on_update}`)}`);}console.log();}if(e.views.length>0){console.log(F.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(F.default.dim("Triggers:"));for(let a of e.triggers)console.log(` ${a.name} on ${n(a.schema,a.table)}`);console.log();}}function pt({diff:e}){if(typeof e=="string"){console.log(F.default.cyan(e));return}if(!e.has_changes)return;console.log(F.default.bgWhite(F.default.black(" Schema Diff "))),console.log();let t={added:{color:F.default.green,symbol:"+"},removed:{color:F.default.red,symbol:"-"},modified:{color:F.default.yellow,symbol:"~"}};if(e.tables.length>0){console.log(F.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(F.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(F.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(F.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 F,kf,Pf,Be=y(()=>{ra();F=ee(se());wt();At();kf="supabase/.temp/.translation-cache.json",Pf=2;});function Is(e){return e.dialect==="postgres"?"pg":e.config?.ddlDialect==="sqlite"?"sqlite":"pg-flat"}function jf(e){return e==="sqlite"?{schema_migrations:"migrations",seed_files:null}: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 Ia(e){return `'${e.replace(/'/g,"''")}'`}function tE(e){return `'${`{${e.map(n=>`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`).join(",")}}`.replace(/'/g,"''")}'`}function rE(e){return e==="sqlite"?[`CREATE TABLE IF NOT EXISTS migrations (
|
|
70
70
|
version TEXT NOT NULL PRIMARY KEY,
|
|
71
71
|
statements TEXT,
|
|
72
72
|
name TEXT
|
|
@@ -77,111 +77,116 @@ ${s}`)}}async function rl(e){await dn(e);}async function ge(e){let t=await Wr(e.
|
|
|
77
77
|
)`,`CREATE TABLE IF NOT EXISTS supabase_migrations.seed_files (
|
|
78
78
|
path text NOT NULL PRIMARY KEY,
|
|
79
79
|
hash text NOT NULL
|
|
80
|
-
)`]}function
|
|
81
|
-
`)+";",s=await
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
`)))
|
|
87
|
-
|
|
80
|
+
)`]}function Ff(e,t){let{schema_migrations:r}=jf(e),n=t.name===null?"NULL":Ia(t.name),s=e==="pg"?tE(t.statements):Ia(JSON.stringify(t.statements));return `INSERT INTO ${r} (version, statements, name) VALUES (${Ia(t.version)}, ${s}, ${n})`}function nE(e){let{schema_migrations:t}=jf(e);return `SELECT version FROM ${t} ORDER BY version ASC`}async function sE(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 iE(e){return e.split(/;\s*(?:\n|$)/).map(t=>t.trim()).filter(t=>t.length>0)}async function pn(e){let t=Is(e),n=rE(t).map(i=>i.trim()).join(`;
|
|
81
|
+
`)+";",s=await sE(e,n);for(let i of iE(s))await e.exec(i);}async function fn(e){let t=Is(e);return ((await e.exec(nE(t)))?.rows??[]).map(n=>n.version)}var Da=y(()=>{});function oE(e){return e==="service_role"?"NOLOGIN BYPASSRLS":"NOLOGIN"}function ft(e){return e.size===0?"":`DO $$ BEGIN${[...e].map(r=>`
|
|
82
|
+
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '${r}') THEN
|
|
83
|
+
CREATE ROLE ${r} ${oE(r)};
|
|
84
|
+
END IF;`).join("")}
|
|
85
|
+
END $$;
|
|
86
|
+
`}function mn(e,t){return e?e.quoted?e.value===t:e.value.toLowerCase()===t:false}function Ae(e){return e?.quoted?e.value:e?.value.toLowerCase()}function aE(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 lE(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 cE(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 Fa(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]!==`
|
|
87
|
+
`;)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=lE(e,r);continue}if(n==="$"){let i=cE(e,r);if(i!==void 0){r=i;continue}}if(n==='"'){let{token:i,end:o}=aE(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 Bf(e,t){let r=Ae(e[t]),n=Ae(e[t+1]);if((r==="create"||r==="alter")&&(n==="role"||n==="user"||n==="group"))return e[t+2]}function Ds(e){let t=new Set,r=Fa(e);for(let n=0;n<r.length;n++){if(Ae(r[n])!=="create")continue;let s=Bf(r,n);for(let i of ir)mn(s,i)&&t.add(i);}return t}function ja(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=Ae(e[s]);if(!i||n.has(i))return;for(let o of ir)mn(e[s],o)&&r.add(o);}}function uE(e){let t=[],r=[];for(let n of e){if(Ae(n)===";"){r.length>0&&t.push(r),r=[];continue}r.push(n);}return r.length>0&&t.push(r),t}function Mf(e,t){return e.some(r=>Ae(r)===t)}function pE(e){let t=new Set,r=uE(Fa(e));for(let n of r){let s=Ae(n[0]);for(let a=0;a<n.length;a++){let l=Ae(n[a]);l==="to"&&(Mf(n,"grant")||Mf(n,"policy")||Ae(n[a-1])==="owner")&&ja(n,a+1,t),l==="from"&&s==="revoke"&&ja(n,a+1,t);}let i=n.findIndex(a=>Ae(a)==="to"),o=n.findIndex(a=>Ae(a)==="on");s==="grant"&&i>1&&(o===-1||i<o)&&ja(n,1,t);}return t}function mt(e){let t=Ds(e);return new Set([...pE(e)].filter(r=>!t.has(r)))}function qf(e){let t=Ds(e);return new Set(ir.filter(r=>!t.has(r)))}function Hf(e,t){let r=Fa(e);if(r.length===0)return false;let n=Bf(r,0);if(n){for(let o of t)if(mn(n,o))return true;return false}let s=Ae(r[0]),i=Ae(r[1]);if(s==="drop"&&(i==="role"||i==="user"||i==="group")){for(let o of r.slice(2))for(let a of t)if(mn(o,a))return true}if(s==="comment"&&Ae(r[1])==="on"&&Ae(r[2])==="role"){for(let o of t)if(mn(r[3],o))return true}return false}var ir,Uf,js=y(()=>{ir=["anon","authenticated","service_role"];ft(new Set(ir)),Uf=`
|
|
88
|
+
CREATE SCHEMA IF NOT EXISTS auth;
|
|
89
|
+
|
|
90
|
+
CREATE OR REPLACE FUNCTION auth.uid() RETURNS UUID AS $$
|
|
91
|
+
SELECT NULLIF(current_setting('request.jwt.claim.sub', true), '')::uuid;
|
|
92
|
+
$$ LANGUAGE SQL STABLE;
|
|
93
|
+
|
|
94
|
+
CREATE OR REPLACE FUNCTION auth.role() RETURNS TEXT AS $$
|
|
95
|
+
SELECT NULLIF(current_setting('request.jwt.claim.role', true), '');
|
|
96
|
+
$$ LANGUAGE SQL STABLE;
|
|
97
|
+
|
|
98
|
+
CREATE OR REPLACE FUNCTION auth.email() RETURNS TEXT AS $$
|
|
99
|
+
SELECT NULLIF(current_setting('request.jwt.claim.email', true), '');
|
|
100
|
+
$$ LANGUAGE SQL STABLE;
|
|
101
|
+
|
|
102
|
+
CREATE OR REPLACE FUNCTION auth.jwt() RETURNS JSONB AS $$
|
|
103
|
+
SELECT COALESCE(
|
|
104
|
+
NULLIF(current_setting('request.jwt.claims', true), ''),
|
|
105
|
+
'{}'
|
|
106
|
+
)::jsonb;
|
|
107
|
+
$$ LANGUAGE SQL STABLE;
|
|
108
|
+
`;});async function Dt(e){await mE(e),await pn(e.connection);let t=new Set(await fn(e.connection)),r=await Ve(e),n=Is(e.connection),s=[],i=[];for(let o of r){if(t.has(o.version)){i.push(o);continue}let a=Kn(o.sql),l;if(n==="pg-flat"){let u=await e.connection.translateDdl(o.sql),p=typeof u=="string"?u:u.ddl??"";l=Kn(p);}else l=a;let c=Ff(n,{version:o.version,name:o.name,statements:a});if(n==="pg"){let u=ft(mt(o.sql));u&&await e.connection.exec(u);}await e.connection.transaction([...l,c],{intent:"migration"}),s.push(o);}return r.length>0&&n!=="sqlite"&&await fE(e,r),{applied:s,skipped:i}}async function fE(e,t){let r=t.map(o=>o.sql).join(`
|
|
109
|
+
`);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 mE(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 Kn(n))try{await r.exec(s);}catch{}}var Fs=y(()=>{_r();Da();At();js();});function de(e){return `${dE} ${e}`}var dE,Ke=y(()=>{dE="[lite]";});var Wf={};fe(Wf,{dev:()=>yE});var Fe,yE,Gf=y(()=>{qi();Do();at();Fe=ee(se());Wt();Be();Fs();At();Te();we();qt();Ke();yE=e=>{e.command("dev").option("--recreate","Recreate everything",false).option("--template","Create a template for the database",false).option("--config <config>","Path to the config file").description(de("Start the development server with schema watching")).helpGroup("Local Development:").action(async t=>{await Y(t.config),console.log(Fe.default.yellow(" \u26A0 [lite] dev is experimental and works with declarative schema only.")),await Vn(async()=>{await Gn({recreate:t.recreate,template:t.template}),console.log();let n=await(await V({withSupabaseClient:false})).project.local.createApp(t.config),s=n.config.api?.port??_e.default_api_port;if((await Ve(n)).length>0){let c=await Dt(n);for(let u of c.applied)console.log(Fe.default.green(" \u2713"),"Applied migration",Fe.default.cyan(u.filename));}await ln(n,{force:true}),console.log();await fs(n,{port:s});console.log(Fe.default.green(" \u279C"),"Server running on ",Fe.default.cyan(`http://localhost:${s}`));let a=Ln();a&&console.log(Fe.default.yellow(` \u26A0 ${a}`)),await n.connection.ping(),If(n,{translate:true,force:true});let l=He__default.join(process.cwd(),"supabase",Tt(n));setTimeout(()=>{XS.watch(l,{ignoreInitial:true}).on("add",async u=>{console.log(),console.log(Fe.default.dim(`Migration added: ${u}`));try{let p=await Dt(n);for(let f of p.applied)console.log(Fe.default.green(" \u2713"),"Applied",Fe.default.cyan(f.filename));}catch(p){console.error(Fe.default.red("Migration failed: "+String(p.message??p)));}});},200),process.on("SIGINT",async()=>{await n.connection.close(),process.exit(1);});},r=>{console.log(),console.log(Fe.default.green(`Ready in ${r.toFixed(2)}ms`));});});};});async function dt(e){let t=await V({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 console.log("creating app for remote project",r),t.project.remote.createApp(r)}return t.project.local.createApp(e)}var Ma=y(()=>{Te();});var zf={};fe(zf,{repl:()=>wE});var ge,wE,Vf=y(()=>{at();ge=ee(se());Ma();we();Ke();wE=e=>{e.command("repl").option("--config <config>","Path to the config file").option("--remote","Connect REPL to a remote project").description(de("Start a REPL session")).helpGroup("Local Development:").action(async t=>{t.remote||await Y(t.config);let r=await dt(t.remote?true:t.config);zn()||(console.error(ge.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(ge.default.green("Starting a REPL session")),console.log(ge.default.bold("Available variables:"),Object.keys(n).map(o=>ge.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(u=>u.table===c);console.log(a.tables.map(c=>`${ge.default.cyan(c.name)} (${l(c.name).length} columns)`).join(`
|
|
110
|
+
`)),this.displayPrompt();}}),i.defineCommand("table",{help:"Show a table",action:async function(a){let l=await r.connection.introspect(),c=p=>l.columns.filter(f=>f.table===p),u=l.tables.find(p=>p.name===a);u?(console.log(`${ge.default.cyan(u?.name)} (${c(a).length} columns)`),console.log(c(a).map(p=>` - ${ge.default.cyan(p.name)} ${ge.default.yellow(p.type)}`).join(`
|
|
111
|
+
`)),console.log(),console.log(ge.default.dim(u.sql))):(console.log(ge.default.red(`Table ${a} not found`)),console.log(`Available tables:
|
|
112
|
+
`+l.tables.map(p=>`- ${ge.default.cyan(p.name)}`).join(`
|
|
113
|
+
`))),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=>`${ge.default.bold(ge.default.cyan(l.name))} ${l.unique?ge.default.yellow("unique "):""}on ${ge.default.blue(l.table)}(${l.columns.map(c=>ge.default.magenta(c)).join(", ")})`).join(`
|
|
114
|
+
`)),this.displayPrompt();}}),i.defineCommand("config",{help:"Show the current config",action:async function(a){console.log(a?Wi(r.config,a):r.config),this.displayPrompt();}});});};});var Kf={};fe(Kf,{debug:()=>bE});var bE,Jf=y(()=>{at();we();Ke();bE=e=>{e.command("debug").description(de("Print runtime info (bun/node detection, paths)")).helpGroup("Local Development:").action(async()=>{console.log("Debugging the application"),console.log({bun:xr(),node:zn(),cwd:process.cwd(),paths:{root:Hn(),dist:Mi(),relativeDist:Wn()}});});};});var Ba=it((iP,Xf)=>{var Ua={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"},SE={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},EE={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?Ua.up():"");return e&&(t+=Ua.left),t}};Xf.exports={cursor:Ua,scroll:SE,erase:EE,beep:"\x07"};});function Hs(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?Hs(i,t<0?-1:1,r):i}function za(e,t,r){return String(e).normalize().replaceAll(`\r
|
|
88
115
|
`,`
|
|
89
116
|
`).split(`
|
|
90
|
-
`).map(n=>
|
|
91
|
-
`)}function
|
|
117
|
+
`).map(n=>LE(n,t,r)).join(`
|
|
118
|
+
`)}function Ya(e,t){if(typeof e=="string")return Ne.aliases.get(e)===t;for(let r of e)if(r!==void 0&&Ya(r,t))return true;return false}function DE(e,t){if(e===t)return;let r=e.split(`
|
|
92
119
|
`),n=t.split(`
|
|
93
|
-
`),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
|
|
120
|
+
`),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 ye(e){return e===Va}function qs(e,t){let r=e;r.isTTY&&r.setRawMode(t);}function om({input:e=stdin,output:t=stdout,overwrite:r=true,hideCursor:n=true}={}){let s=ht.createInterface({input:e,output:t,prompt:"",tabSize:1});ht.emitKeypressEvents(e,s),e instanceof ReadStream&&e.isTTY&&e.setRawMode(true);let i=(o,{name:a,sequence:l})=>{let c=String(o);if(Ya([c,a,l],"cancel")){n&&t.write(be.cursor.show),process.exit(0);return}if(!r)return;ht.moveCursor(t,a==="return"?0:-1,a==="return"?-1:0,()=>{ht.clearLine(t,1,()=>{e.once("keypress",i);});});};return n&&t.write(be.cursor.hide),e.once("keypress",i),()=>{e.off("keypress",i),n&&t.write(be.cursor.show),e instanceof ReadStream&&e.isTTY&&!jE&&e.setRawMode(false),s.terminal=false,s.close();}}function Xs(e,t,r,n=r){let s=Js(e??stdout);return za(t,s-r.length,{hard:true,trim:false}).split(`
|
|
94
121
|
`).map((i,o)=>`${o===0?n:r}${i}`).join(`
|
|
95
|
-
`)}var
|
|
96
|
-
`),u=c[Symbol.iterator](),p=u.next(),f=u.next(),h=0;for(;!p.done;){let d=p.value,m=f.value;if(n+=d,d===
|
|
97
|
-
`?(i&&(n+=
|
|
98
|
-
`&&(s&&b&&(n+=
|
|
99
|
-
`),
|
|
100
|
-
`).length-1;this.output.write(
|
|
101
|
-
`);this.output.write(a[o]),this._prevFrame=t,this.output.write(
|
|
122
|
+
`)}var be,_E,$E,vE,qa,Ms,Us,Ha,Bs,TE,AE,rm,CE,dn,Ks,nm,RE,Ja,sm,kE,im,Xa,Qf,PE,Zf,em,NE,Wa,OE,LE,IE,Ne,jE,Va,Js,Qa,or,Ws,Gs,zs,Vs,Za=y(()=>{be=ee(Ba());_E=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,$E=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,vE=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,qa=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,Ms=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Us=/\t{1,1000}/y,Ha=/[\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,Bs=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,TE=/\p{M}+/gu,AE={limit:1/0,ellipsis:""},rm=(e,t={},r={})=>{let n=t.limit??1/0,s=t.ellipsis??"",i=t?.ellipsisWidth??(s?rm(s,AE,r).width:0),o=r.ansiWidth??0,a=r.controlWidth??0,l=r.tabWidth??8,c=r.ambiguousWidth??1,u=r.emojiWidth??2,p=r.fullWidthWidth??2,f=r.regularWidth??1,h=r.wideWidth??2,d=0,m=0,b=e.length,g=0,S=false,A=b,$=Math.max(0,n-i),P=0,N=0,v=0,_=0;e:for(;;){if(N>P||m>=b&&m>d){let L=e.slice(P,N)||e.slice(d,m);g=0;for(let w of L.replaceAll(TE,"")){let I=w.codePointAt(0)||0;if($E(I)?_=p:vE(I)?_=h:c!==f&&_E(I)?_=c:_=f,v+_>$&&(A=Math.min(A,Math.max(P,d)+g)),v+_>n){S=true;break e}g+=w.length,v+=_;}P=N=0;}if(m>=b)break;if(Bs.lastIndex=m,Bs.test(e)){if(g=Bs.lastIndex-m,_=g*f,v+_>$&&(A=Math.min(A,m+Math.floor(($-v)/f))),v+_>n){S=true;break}v+=_,P=d,N=m,m=d=Bs.lastIndex;continue}if(qa.lastIndex=m,qa.test(e)){if(v+o>$&&(A=Math.min(A,m)),v+o>n){S=true;break}v+=o,P=d,N=m,m=d=qa.lastIndex;continue}if(Ms.lastIndex=m,Ms.test(e)){if(g=Ms.lastIndex-m,_=g*a,v+_>$&&(A=Math.min(A,m+Math.floor(($-v)/a))),v+_>n){S=true;break}v+=_,P=d,N=m,m=d=Ms.lastIndex;continue}if(Us.lastIndex=m,Us.test(e)){if(g=Us.lastIndex-m,_=g*l,v+_>$&&(A=Math.min(A,m+Math.floor(($-v)/l))),v+_>n){S=true;break}v+=_,P=d,N=m,m=d=Us.lastIndex;continue}if(Ha.lastIndex=m,Ha.test(e)){if(v+u>$&&(A=Math.min(A,m)),v+u>n){S=true;break}v+=u,P=d,N=m,m=d=Ha.lastIndex;continue}m+=1;}return {width:S?$:v,index:S?A:b,truncated:S,ellipsed:S&&n>=i}},CE={limit:1/0,ellipsis:"",ellipsisWidth:0},dn=(e,t={})=>rm(e,CE,t).width,Ks="\x1B",nm="\x9B",RE=39,Ja="\x07",sm="[",kE="]",im="m",Xa=`${kE}8;;`,Qf=new RegExp(`(?:\\${sm}(?<code>\\d+)m|\\${Xa}(?<uri>.*)${Ja})`,"y"),PE=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},Zf=e=>`${Ks}${sm}${e}${im}`,em=e=>`${Ks}${Xa}${e}${Ja}`,NE=e=>e.map(t=>dn(t)),Wa=(e,t,r)=>{let n=t[Symbol.iterator](),s=false,i=false,o=e.at(-1),a=o===void 0?0:dn(o),l=n.next(),c=n.next(),u=0;for(;!l.done;){let p=l.value,f=dn(p);a+f<=r?e[e.length-1]+=p:(e.push(p),a=0),(p===Ks||p===nm)&&(s=true,i=t.startsWith(Xa,u+1)),s?i?p===Ja&&(s=false,i=false):p===im&&(s=false):(a+=f,a===r&&!c.done&&(e.push(""),a=0)),l=c,c=n.next(),u+=p.length;}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop());},OE=e=>{let t=e.split(" "),r=t.length;for(;r>0&&!(dn(t[r-1])>0);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")},LE=(e,t,r={})=>{if(r.trim!==false&&e.trim()==="")return "";let n="",s,i,o=e.split(" "),a=NE(o),l=[""];for(let[d,m]of o.entries()){r.trim!==false&&(l[l.length-1]=(l.at(-1)??"").trimStart());let b=dn(l.at(-1)??"");if(d!==0&&(b>=t&&(r.wordWrap===false||r.trim===false)&&(l.push(""),b=0),(b>0||r.trim===false)&&(l[l.length-1]+=" ",b++)),r.hard&&a[d]>t){let g=t-b,S=1+Math.floor((a[d]-g-1)/t);Math.floor((a[d]-1)/t)<S&&l.push(""),Wa(l,m,t);continue}if(b+a[d]>t&&b>0&&a[d]>0){if(r.wordWrap===false&&b<t){Wa(l,m,t);continue}l.push("");}if(b+a[d]>t&&r.wordWrap===false){Wa(l,m,t);continue}l[l.length-1]+=m;}r.trim!==false&&(l=l.map(d=>OE(d)));let c=l.join(`
|
|
123
|
+
`),u=c[Symbol.iterator](),p=u.next(),f=u.next(),h=0;for(;!p.done;){let d=p.value,m=f.value;if(n+=d,d===Ks||d===nm){Qf.lastIndex=h+1;let g=Qf.exec(c)?.groups;if(g?.code!==void 0){let S=Number.parseFloat(g.code);s=S===RE?void 0:S;}else g?.uri!==void 0&&(i=g.uri.length===0?void 0:g.uri);}let b=s?PE(s):void 0;m===`
|
|
124
|
+
`?(i&&(n+=em("")),s&&b&&(n+=Zf(b))):d===`
|
|
125
|
+
`&&(s&&b&&(n+=Zf(s)),i&&(n+=em(i))),h+=d.length,p=f,f=u.next();}return n};IE=["up","down","left","right","space","enter","cancel"],Ne={actions:new Set(IE),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:true};jE=globalThis.process.platform.startsWith("win"),Va=Symbol("clack:cancel");Js=e=>"columns"in e&&typeof e.columns=="number"?e.columns:80,Qa=e=>"rows"in e&&typeof e.rows=="number"?e.rows:20;or=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(Va);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close();},{once:true});}this.rl=ht__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),qs(this.input,true),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(be.cursor.show),this.output.off("resize",this.render),qs(this.input,false),t(this.value);}),this.once("cancel",()=>{this.output.write(be.cursor.show),this.output.off("resize",this.render),qs(this.input,false),t(Va);});})}_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");}Ya([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(`
|
|
126
|
+
`),qs(this.input,false),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe();}restoreCursor(){let t=za(this._prevFrame,process.stdout.columns,{hard:true,trim:false}).split(`
|
|
127
|
+
`).length-1;this.output.write(be.cursor.move(-999,t*-1));}render(){let t=za(this._render(this)??"",process.stdout.columns,{hard:true,trim:false});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(be.cursor.hide);else {let r=DE(this._prevFrame,t),n=Qa(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(be.cursor.move(0,o-i)),this.output.write(be.erase.lines(1));let a=t.split(`
|
|
128
|
+
`);this.output.write(a[o]),this._prevFrame=t,this.output.write(be.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(be.cursor.move(0,l));}this.output.write(be.erase.down());let a=t.split(`
|
|
102
129
|
`).slice(o);this.output.write(a.join(`
|
|
103
|
-
`)),this._prevFrame=t;return}}this.output.write(
|
|
130
|
+
`)),this._prevFrame=t;return}}this.output.write(be.erase.down());}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t;}}},Ws=class extends or{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(be.cursor.move(0,-1)),this.value=r,this.state="submit",this.close();}),this.on("cursor",()=>{this.value=!this.value;});}},Gs=class extends or{_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 or{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?Hs(n,1,this.options):n,this.changeValue(),this.on("cursor",s=>{switch(s){case "left":case "up":this.cursor=Hs(this.cursor,-1,this.options);break;case "down":case "right":this.cursor=Hs(this.cursor,1,this.options);break}this.changeValue();});}},Vs=class extends or{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 FE(){return qe.platform!=="win32"?qe.env.TERM!=="linux":!!qe.env.CI||!!qe.env.WT_SESSION||!!qe.env.TERMINUS_SUBLIME||qe.env.ConEmuTask==="{cmd::Cmder}"||qe.env.TERM_PROGRAM==="Terminus-Sublime"||qe.env.TERM_PROGRAM==="vscode"||qe.env.TERM==="xterm-256color"||qe.env.TERM==="alacritty"||qe.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}function il(e,t,r){return String(e).normalize().replaceAll(`\r
|
|
104
131
|
`,`
|
|
105
132
|
`).split(`
|
|
106
|
-
`).map(n
|
|
107
|
-
`)}var
|
|
108
|
-
`),u=c[Symbol.iterator](),p=u.next(),f=u.next(),h=0;for(;!p.done;){let d=p.value,m=f.value;if(n+=d,d===
|
|
109
|
-
`?(i&&(n+=
|
|
110
|
-
`&&(s&&b&&(n+=
|
|
111
|
-
`);b.push(N),g+=N.length;}if(g>u){let
|
|
112
|
-
`:""}${
|
|
113
|
-
`,i=this.value?t:r;switch(this.state){case "submit":{let o=n?`${styleText("gray",
|
|
114
|
-
${styleText("gray",
|
|
115
|
-
${styleText("cyan",
|
|
116
|
-
`:` ${styleText("dim","/")} `}${this.value?`${styleText("dim",
|
|
133
|
+
`).map(n=>sx(n,t,r)).join(`
|
|
134
|
+
`)}var hn,nl,ME,X,UE,um,pm,ol,K,ar,sl,ti,BE,qE,HE,WE,GE,ri,zE,VE,KE,JE,el,Ys,Qs,tl,Zs,XE,YE,fm,QE,gn,ni,mm,ZE,al,dm,ex,hm,ll,am,tx,lm,cm,rx,rl,nx,sx,ix,ox,yn,J,wn,ax,cl,ei,bn,Sn,Je=y(()=>{Za();Za();hn=ee(Ba());nl=FE(),ME=()=>process.env.CI==="true",X=(e,t)=>nl?e:t,UE=X("\u25C6","*"),um=X("\u25A0","x"),pm=X("\u25B2","x"),ol=X("\u25C7","o"),X("\u250C","T"),K=X("\u2502","|"),ar=X("\u2514","\u2014"),X("\u2510","T"),X("\u2518","\u2014"),sl=X("\u25CF",">"),ti=X("\u25CB"," "),X("\u25FB","[\u2022]"),X("\u25FC","[+]"),X("\u25FB","[ ]"),BE=X("\u25AA","\u2022"),X("\u2500","-"),X("\u256E","+"),X("\u251C","+"),X("\u256F","+"),X("\u2570","+"),X("\u256D","+"),qE=X("\u25CF","\u2022"),HE=X("\u25C6","*"),WE=X("\u25B2","!"),GE=X("\u25A0","x"),ri=e=>{switch(e){case "initial":case "active":return styleText("cyan",UE);case "cancel":return styleText("red",um);case "error":return styleText("yellow",pm);case "submit":return styleText("green",ol)}},zE=e=>{switch(e){case "initial":case "active":return styleText("cyan",K);case "cancel":return styleText("red",K);case "error":return styleText("yellow",K);case "submit":return styleText("green",K)}},VE=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,KE=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,JE=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,el=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,Ys=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Qs=/\t{1,1000}/y,tl=/[\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,Zs=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,XE=/\p{M}+/gu,YE={limit:1/0,ellipsis:""},fm=(e,t={},r={})=>{let n=t.limit??1/0,s=t.ellipsis??"",i=t?.ellipsisWidth??(s?fm(s,YE,r).width:0),o=r.ansiWidth??0,a=r.controlWidth??0,l=r.tabWidth??8,c=r.ambiguousWidth??1,u=r.emojiWidth??2,p=r.fullWidthWidth??2,f=r.regularWidth??1,h=r.wideWidth??2,d=0,m=0,b=e.length,g=0,S=false,A=b,$=Math.max(0,n-i),P=0,N=0,v=0,_=0;e:for(;;){if(N>P||m>=b&&m>d){let L=e.slice(P,N)||e.slice(d,m);g=0;for(let w of L.replaceAll(XE,"")){let I=w.codePointAt(0)||0;if(KE(I)?_=p:JE(I)?_=h:c!==f&&VE(I)?_=c:_=f,v+_>$&&(A=Math.min(A,Math.max(P,d)+g)),v+_>n){S=true;break e}g+=w.length,v+=_;}P=N=0;}if(m>=b)break;if(Zs.lastIndex=m,Zs.test(e)){if(g=Zs.lastIndex-m,_=g*f,v+_>$&&(A=Math.min(A,m+Math.floor(($-v)/f))),v+_>n){S=true;break}v+=_,P=d,N=m,m=d=Zs.lastIndex;continue}if(el.lastIndex=m,el.test(e)){if(v+o>$&&(A=Math.min(A,m)),v+o>n){S=true;break}v+=o,P=d,N=m,m=d=el.lastIndex;continue}if(Ys.lastIndex=m,Ys.test(e)){if(g=Ys.lastIndex-m,_=g*a,v+_>$&&(A=Math.min(A,m+Math.floor(($-v)/a))),v+_>n){S=true;break}v+=_,P=d,N=m,m=d=Ys.lastIndex;continue}if(Qs.lastIndex=m,Qs.test(e)){if(g=Qs.lastIndex-m,_=g*l,v+_>$&&(A=Math.min(A,m+Math.floor(($-v)/l))),v+_>n){S=true;break}v+=_,P=d,N=m,m=d=Qs.lastIndex;continue}if(tl.lastIndex=m,tl.test(e)){if(v+u>$&&(A=Math.min(A,m)),v+u>n){S=true;break}v+=u,P=d,N=m,m=d=tl.lastIndex;continue}m+=1;}return {width:S?$:v,index:S?A:b,truncated:S,ellipsed:S&&n>=i}},QE={limit:1/0,ellipsis:"",ellipsisWidth:0},gn=(e,t={})=>fm(e,QE,t).width,ni="\x1B",mm="\x9B",ZE=39,al="\x07",dm="[",ex="]",hm="m",ll=`${ex}8;;`,am=new RegExp(`(?:\\${dm}(?<code>\\d+)m|\\${ll}(?<uri>.*)${al})`,"y"),tx=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},lm=e=>`${ni}${dm}${e}${hm}`,cm=e=>`${ni}${ll}${e}${al}`,rx=e=>e.map(t=>gn(t)),rl=(e,t,r)=>{let n=t[Symbol.iterator](),s=false,i=false,o=e.at(-1),a=o===void 0?0:gn(o),l=n.next(),c=n.next(),u=0;for(;!l.done;){let p=l.value,f=gn(p);a+f<=r?e[e.length-1]+=p:(e.push(p),a=0),(p===ni||p===mm)&&(s=true,i=t.startsWith(ll,u+1)),s?i?p===al&&(s=false,i=false):p===hm&&(s=false):(a+=f,a===r&&!c.done&&(e.push(""),a=0)),l=c,c=n.next(),u+=p.length;}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop());},nx=e=>{let t=e.split(" "),r=t.length;for(;r>0&&!(gn(t[r-1])>0);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")},sx=(e,t,r={})=>{if(r.trim!==false&&e.trim()==="")return "";let n="",s,i,o=e.split(" "),a=rx(o),l=[""];for(let[d,m]of o.entries()){r.trim!==false&&(l[l.length-1]=(l.at(-1)??"").trimStart());let b=gn(l.at(-1)??"");if(d!==0&&(b>=t&&(r.wordWrap===false||r.trim===false)&&(l.push(""),b=0),(b>0||r.trim===false)&&(l[l.length-1]+=" ",b++)),r.hard&&a[d]>t){let g=t-b,S=1+Math.floor((a[d]-g-1)/t);Math.floor((a[d]-1)/t)<S&&l.push(""),rl(l,m,t);continue}if(b+a[d]>t&&b>0&&a[d]>0){if(r.wordWrap===false&&b<t){rl(l,m,t);continue}l.push("");}if(b+a[d]>t&&r.wordWrap===false){rl(l,m,t);continue}l[l.length-1]+=m;}r.trim!==false&&(l=l.map(d=>nx(d)));let c=l.join(`
|
|
135
|
+
`),u=c[Symbol.iterator](),p=u.next(),f=u.next(),h=0;for(;!p.done;){let d=p.value,m=f.value;if(n+=d,d===ni||d===mm){am.lastIndex=h+1;let g=am.exec(c)?.groups;if(g?.code!==void 0){let S=Number.parseFloat(g.code);s=S===ZE?void 0:S;}else g?.uri!==void 0&&(i=g.uri.length===0?void 0:g.uri);}let b=s?tx(s):void 0;m===`
|
|
136
|
+
`?(i&&(n+=cm("")),s&&b&&(n+=lm(b))):d===`
|
|
137
|
+
`&&(s&&b&&(n+=lm(s)),i&&(n+=cm(i))),h+=d.length,p=f,f=u.next();}return n};ix=(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}},ox=({cursor:e,options:t,style:r,output:n=process.stdout,maxItems:s=Number.POSITIVE_INFINITY,columnPadding:i=0,rowPadding:o=4})=>{let a=Js(n)-i,l=Qa(n),c=styleText("dim","..."),u=Math.max(l-o,0),p=Math.max(Math.min(s,u),5),f=0;e>=p-3&&(f=Math.max(Math.min(e-p+3,t.length-p),0));let h=p<t.length&&f>0,d=p<t.length&&f+p<t.length,m=Math.min(f+p,t.length),b=[],g=0;h&&g++,d&&g++;let S=f+(h?1:0),A=m-(d?1:0);for(let P=S;P<A;P++){let N=il(r(t[P],P===e),a,{hard:true,trim:false}).split(`
|
|
138
|
+
`);b.push(N),g+=N.length;}if(g>u){let P=0,N=0,v=g,_=e-S,L=(w,I)=>ix(b,v,w,I,u);h?({lineCount:v,removals:P}=L(0,_),v>u&&({lineCount:v,removals:N}=L(_+1,b.length))):({lineCount:v,removals:N}=L(_+1,b.length),v>u&&({lineCount:v,removals:P}=L(0,_))),P>0&&(h=true,b.splice(0,P)),N>0&&(d=true,b.splice(b.length-N,N));}let $=[];h&&$.push(c);for(let P of b)for(let N of P)$.push(N);return d&&$.push(c),$},yn=e=>{let t=e.active??"Yes",r=e.inactive??"No";return new Ws({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",K)}
|
|
139
|
+
`:""}${ri(this.state)} ${e.message}
|
|
140
|
+
`,i=this.value?t:r;switch(this.state){case "submit":{let o=n?`${styleText("gray",K)} `:"";return `${s}${o}${styleText("dim",i)}`}case "cancel":{let o=n?`${styleText("gray",K)} `:"";return `${s}${o}${styleText(["strikethrough","dim"],i)}${n?`
|
|
141
|
+
${styleText("gray",K)}`:""}`}default:{let o=n?`${styleText("cyan",K)} `:"",a=n?styleText("cyan",ar):"";return `${s}${o}${this.value?`${styleText("green",sl)} ${t}`:`${styleText("dim",ti)} ${styleText("dim",t)}`}${e.vertical?n?`
|
|
142
|
+
${styleText("cyan",K)} `:`
|
|
143
|
+
`:` ${styleText("dim","/")} `}${this.value?`${styleText("dim",ti)} ${styleText("dim",r)}`:`${styleText("green",sl)} ${r}`}
|
|
117
144
|
${a}
|
|
118
|
-
`}}}}).prompt()},J={message:(e=[],{symbol:t=styleText("gray",
|
|
145
|
+
`}}}}).prompt()},J={message:(e=[],{symbol:t=styleText("gray",K),secondarySymbol:r=styleText("gray",K),output:n=process.stdout,spacing:s=1,withGuide:i}={})=>{let o=[],a=i??Ne.withGuide,l=a?r:"",c=a?`${t} `:"",u=a?`${r} `:"";for(let f=0;f<s;f++)o.push(l);let p=Array.isArray(e)?e:e.split(`
|
|
119
146
|
`);if(p.length>0){let[f,...h]=p;f.length>0?o.push(`${c}${f}`):o.push(a?t:"");for(let d of h)d.length>0?o.push(`${u}${d}`):o.push(a?r:"");}n.write(`${o.join(`
|
|
120
147
|
`)}
|
|
121
|
-
`);},info:(e,t)=>{J.message(e,{...t,symbol:styleText("blue",
|
|
122
|
-
`:""}${
|
|
123
|
-
`,n=this.userInputWithCursor,s=this.masked;switch(this.state){case "error":{let i=t?`${styleText("yellow",
|
|
148
|
+
`);},info:(e,t)=>{J.message(e,{...t,symbol:styleText("blue",qE)});},success:(e,t)=>{J.message(e,{...t,symbol:styleText("green",HE)});},step:(e,t)=>{J.message(e,{...t,symbol:styleText("green",ol)});},warn:(e,t)=>{J.message(e,{...t,symbol:styleText("yellow",WE)});},warning:(e,t)=>{J.warn(e,t);},error:(e,t)=>{J.message(e,{...t,symbol:styleText("red",GE)});}},wn=e=>new Gs({validate:e.validate,mask:e.mask??BE,signal:e.signal,input:e.input,output:e.output,render(){let t=e.withGuide??Ne.withGuide,r=`${t?`${styleText("gray",K)}
|
|
149
|
+
`:""}${ri(this.state)} ${e.message}
|
|
150
|
+
`,n=this.userInputWithCursor,s=this.masked;switch(this.state){case "error":{let i=t?`${styleText("yellow",K)} `:"",o=t?`${styleText("yellow",ar)} `:"",a=s??"";return e.clearOnError&&this.clear(),`${r.trim()}
|
|
124
151
|
${i}${a}
|
|
125
152
|
${o}${styleText("yellow",this.error)}
|
|
126
|
-
`}case "submit":{let i=t?`${styleText("gray",
|
|
127
|
-
${styleText("gray",
|
|
153
|
+
`}case "submit":{let i=t?`${styleText("gray",K)} `:"",o=s?styleText("dim",s):"";return `${r}${i}${o}`}case "cancel":{let i=t?`${styleText("gray",K)} `:"",o=s?styleText(["strikethrough","dim"],s):"";return `${r}${i}${o}${s&&t?`
|
|
154
|
+
${styleText("gray",K)}`:""}`}default:{let i=t?`${styleText("cyan",K)} `:"",o=t?styleText("cyan",ar):"";return `${r}${i}${n}
|
|
128
155
|
${o}
|
|
129
|
-
`}}}}).prompt(),
|
|
130
|
-
`);let E=
|
|
131
|
-
`);E.length>1&&r.write(
|
|
132
|
-
`);let
|
|
156
|
+
`}}}}).prompt(),ax=e=>styleText("magenta",e),cl=({indicator:e="dots",onCancel:t,output:r=process.stdout,cancelMessage:n,errorMessage:s,frames:i=nl?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:o=nl?80:120,signal:a,...l}={})=>{let c=ME(),u,p,f=false,h=false,d="",m,b=performance.now(),g=Js(r),S=l?.styleFrame??ax,A=E=>{let x=E>1?s??Ne.messages.error:n??Ne.messages.cancel;h=E===1,f&&(q(x,E),h&&typeof t=="function"&&t());},$=()=>A(2),P=()=>A(1),N=()=>{process.on("uncaughtExceptionMonitor",$),process.on("unhandledRejection",$),process.on("SIGINT",P),process.on("SIGTERM",P),process.on("exit",A),a&&a.addEventListener("abort",P);},v=()=>{process.removeListener("uncaughtExceptionMonitor",$),process.removeListener("unhandledRejection",$),process.removeListener("SIGINT",P),process.removeListener("SIGTERM",P),process.removeListener("exit",A),a&&a.removeEventListener("abort",P);},_=()=>{if(m===void 0)return;c&&r.write(`
|
|
157
|
+
`);let E=il(m,g,{hard:true,trim:false}).split(`
|
|
158
|
+
`);E.length>1&&r.write(hn.cursor.up(E.length-1)),r.write(hn.cursor.to(0)),r.write(hn.erase.down());},L=E=>E.replace(/\.+$/,""),w=E=>{let x=(performance.now()-E)/1e3,U=Math.floor(x/60),j=Math.floor(x%60);return U>0?`[${U}m ${j}s]`:`[${j}s]`},I=l.withGuide??Ne.withGuide,T=(E="")=>{f=true,u=om({output:r}),d=L(E),b=performance.now(),I&&r.write(`${styleText("gray",K)}
|
|
159
|
+
`);let x=0,U=0;N(),p=setInterval(()=>{if(c&&d===m)return;_(),m=d;let j=S(i[x]),z;if(c)z=`${j} ${d}...`;else if(e==="timer")z=`${j} ${d} ${w(b)}`;else {let Ce=".".repeat(Math.floor(U)).slice(0,3);z=`${j} ${d}${Ce}`;}let Me=il(z,g,{hard:true,trim:false});r.write(Me),x=x+1<i.length?x+1:0,U=U<4?U+.125:0;},o);},q=(E="",x=0,U=false)=>{if(!f)return;f=false,clearInterval(p),_();let j=x===0?styleText("green",ol):x===1?styleText("red",um):styleText("red",pm);d=E??d,U||(e==="timer"?r.write(`${j} ${d} ${w(b)}
|
|
133
160
|
`):r.write(`${j} ${d}
|
|
134
|
-
`))
|
|
161
|
+
`)),v(),u();};return {start:T,stop:(E="")=>q(E,0),message:(E="")=>{d=L(E??d);},cancel:(E="")=>q(E,1),error:(E="")=>q(E,2),clear:()=>q("",0,true),get isCancelled(){return h}}},{light:X("\u2500","-"),heavy:X("\u2501","="),block:X("\u2588","#")},ei=(e,t)=>e.includes(`
|
|
135
162
|
`)?e.split(`
|
|
136
163
|
`).map(r=>t(r)).join(`
|
|
137
|
-
`):t(e),
|
|
164
|
+
`):t(e),bn=e=>{let t=(r,n)=>{let s=r.label??String(r.value);switch(n){case "disabled":return `${styleText("gray",ti)} ${ei(s,i=>styleText("gray",i))}${r.hint?` ${styleText("dim",`(${r.hint??"disabled"})`)}`:""}`;case "selected":return `${ei(s,i=>styleText("dim",i))}`;case "active":return `${styleText("green",sl)} ${s}${r.hint?` ${styleText("dim",`(${r.hint})`)}`:""}`;case "cancelled":return `${ei(s,i=>styleText(["strikethrough","dim"],i))}`;default:return `${styleText("dim",ti)} ${ei(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=`${ri(this.state)} `,s=`${zE(this.state)} `,i=Xs(e.output,e.message,s,n),o=`${r?`${styleText("gray",K)}
|
|
138
165
|
`:""}${i}
|
|
139
|
-
`;switch(this.state){case "submit":{let a=r?`${styleText("gray",
|
|
140
|
-
${styleText("gray",
|
|
141
|
-
`).length,u=r?2:1;return `${o}${a}${
|
|
166
|
+
`;switch(this.state){case "submit":{let a=r?`${styleText("gray",K)} `:"",l=Xs(e.output,t(this.options[this.cursor],"selected"),a);return `${o}${l}`}case "cancel":{let a=r?`${styleText("gray",K)} `:"",l=Xs(e.output,t(this.options[this.cursor],"cancelled"),a);return `${o}${l}${r?`
|
|
167
|
+
${styleText("gray",K)}`:""}`}default:{let a=r?`${styleText("cyan",K)} `:"",l=r?styleText("cyan",ar):"",c=o.split(`
|
|
168
|
+
`).length,u=r?2:1;return `${o}${a}${ox({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:a.length,rowPadding:c+u,style:(p,f)=>t(p,p.disabled?"disabled":f?"active":"inactive")}).join(`
|
|
142
169
|
${a}`)}
|
|
143
170
|
${l}
|
|
144
|
-
`}}}}).prompt()},`${styleText("gray",
|
|
145
|
-
`:""}${
|
|
146
|
-
`,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",
|
|
171
|
+
`}}}}).prompt()},`${styleText("gray",K)} `,Sn=e=>new Vs({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",K)}
|
|
172
|
+
`:""}${ri(this.state)} `}${e.message}
|
|
173
|
+
`,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",K)} `:"",l=t?styleText("yellow",ar):"";return `${r.trim()}
|
|
147
174
|
${a}${s}
|
|
148
175
|
${l}${o}
|
|
149
|
-
`}case "submit":{let o=i?` ${styleText("dim",i)}`:"",a=t?styleText("gray",
|
|
150
|
-
${a}`:""}`}default:{let o=t?`${styleText("cyan",
|
|
176
|
+
`}case "submit":{let o=i?` ${styleText("dim",i)}`:"",a=t?styleText("gray",K):"";return `${r}${a}${o}`}case "cancel":{let o=i?` ${styleText(["strikethrough","dim"],i)}`:"",a=t?styleText("gray",K):"";return `${r}${a}${o}${i.trim()?`
|
|
177
|
+
${a}`:""}`}default:{let o=t?`${styleText("cyan",K)} `:"",a=t?styleText("cyan",ar):"";return `${r}${o}${s}
|
|
151
178
|
${a}
|
|
152
|
-
`}}}}).prompt();});function
|
|
153
|
-
`.repeat(t?.paddingVertical??1),o=t?.renderCell??((a,l)=>l===null?
|
|
179
|
+
`}}}}).prompt();});function ym(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(u=>String(u[a]).length));return {key:a,header:l,length:c}}),s=" ".repeat(t?.paddingHorizontal??1),i=`
|
|
180
|
+
`.repeat(t?.paddingVertical??1),o=t?.renderCell??((a,l)=>l===null?gm.default.dim("null"):String(l));return `${i}${s}| ${n.map(a=>a.header.padEnd(a.length)).join(" | ")} |
|
|
154
181
|
${s}| ${n.map(a=>"\u2500".repeat(a.length)).join(" | ")} |
|
|
155
182
|
${e.map(a=>`${s}| ${Object.entries(a).filter(([l])=>!t?.omitKeys?.includes(l)).map(([l,c])=>o(l,c).padEnd(n.find(u=>u.key===l)?.length??0)).join(" | ")} |`).join(`
|
|
156
|
-
`)}${i}`}async function
|
|
157
|
-
SELECT table_schema, table_name, column_name, is_nullable, data_type,
|
|
158
|
-
udt_name, udt_schema, character_maximum_length,
|
|
159
|
-
numeric_precision, numeric_scale, column_default, ordinal_position
|
|
160
|
-
FROM information_schema.columns
|
|
161
|
-
WHERE table_schema NOT IN ('pg_catalog', 'information_schema', 'pg_toast')
|
|
162
|
-
ORDER BY table_schema, table_name, ordinal_position
|
|
163
|
-
`),r=await e.query(`
|
|
164
|
-
SELECT kcu.table_schema, kcu.table_name, kcu.column_name
|
|
165
|
-
FROM information_schema.table_constraints tc
|
|
166
|
-
JOIN information_schema.key_column_usage kcu
|
|
167
|
-
ON tc.constraint_name = kcu.constraint_name
|
|
168
|
-
AND tc.table_schema = kcu.table_schema
|
|
169
|
-
AND tc.table_name = kcu.table_name
|
|
170
|
-
WHERE tc.constraint_type = 'PRIMARY KEY'
|
|
171
|
-
AND tc.table_schema NOT IN ('pg_catalog', 'information_schema', 'pg_toast')
|
|
172
|
-
ORDER BY kcu.ordinal_position
|
|
173
|
-
`),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,u=n.get(o)??[],p=a.map(f=>Px(f,u));i.push(`CREATE TABLE ${Nl(l)}.${Nl(c)} (
|
|
174
|
-
${p.join(`,
|
|
175
|
-
`)}
|
|
176
|
-
);`);}return i.join(`
|
|
177
|
-
|
|
178
|
-
`)}function Nl(e){return /^[a-z_][a-z0-9_]*$/.test(e)?e:`"${e.replace(/"/g,'""')}"`}function Px(e,t){let r=[Nl(e.column_name)];return r.push(kx(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 kx(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 Ol=y(()=>{jr();});async function od(e,t){let[r,n]=await sd(e,t),s=id(r),i=id(n),o=[];for(let[a,l]of i){let c=s.get(a);if(!c){o.push(l.createDdl.trim());continue}for(let[u,p]of l.columns)c.columns.has(u)||o.push(`ALTER TABLE ${Nx(l)} ADD COLUMN ${p.ddl};`);}return o.join(`
|
|
183
|
+
`)}${i}`}async function Z(e){try{await e(),process.exit(0);}catch(t){(process.env.LOCAL||process.env.DEBUG)&&console.error(t),J.error(String(t)),process.exit(1);}}var gm,Oe=y(()=>{gm=ee(se());Je();});function bm(e){return typeof e=="object"&&e!==null&&"text"in e&&"values"in e}function ux(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"?wm(e,lx):e;case 1005:case 1007:case 1016:return typeof e=="string"?wm(e,cx):e;default:return e}}function ul(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,ux(a[l.name],l.dataTypeID)])))}}}}var wm,lx,cx,Sm=y(()=>{wm=(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},lx=e=>e==="NULL"?null:e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/\\(.)/g,"$1"):e,cx=e=>e==="NULL"?null:Number.parseInt(e,10);});async function fx(){try{return await import('@supabase/pg-delta')}catch(e){throw new Error("Postgres schema diffing requires pg-delta to be available.",{cause:e})}}function mx(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 dx(e,t){let r=Ds(e),n=new Set([...mt(e),...mt(t)]);return new Set(ir.filter(s=>n.has(s)&&!r.has(s)))}function hx(e){let t=e.trimEnd();return t.endsWith(";")?t:`${t};`}async function Em(e,t){let{createPlan:r,extractCatalog:n}=await fx(),{PgliteConnection:s}=await Ue("@supabase/lite/pglite","pglite","@electric-sql/pglite"),i=new s,o=new s;try{let a=qf(t),l=dx(e,t),c=mt(t);await i.exec(ft(l)),await o.exec(ft(c)),i.config.baseSchema&&await i.exec(i.config.baseSchema),o.config.baseSchema&&await o.exec(o.config.baseSchema),e.trim()&&await i.exec(e),t.trim()&&await o.exec(t);let u=await r(await n(ul(i)),await n(ul(o)));if(!u)return "";if(u.plan.risk?.level==="data_loss")throw new DataLossError(u.plan.risk.statements.map(mx));return u.plan.statements.filter(f=>!Hf(f,a)).map(hx).join(`
|
|
179
184
|
|
|
180
|
-
`)}
|
|
181
|
-
`,{flag:"wx"}),console.log(
|
|
185
|
+
`)}finally{await i.close().catch(()=>{}),await o.close().catch(()=>{});}}var xm=y(()=>{Qt();Sm();js();});var vm={};fe(vm,{checkPendingDeclarativeSchema:()=>$m,db:()=>bx});async function $m(e,t){let r=await ue(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 _m(e){let t=await dt(e),r=await ue(t);if(!r&&!t.connection.config.baseSchema){console.log(Se.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(Se.default.dim("Schema in sync."));return}pt(s);}var Se,wx,bx,Tm=y(()=>{Se=ee(se());Oe();Ma();Be();At();xm();we();Ke();wt();Fs();Be();wx="Local Development:";bx=e=>{let t=e.command("db").description("Database operations").helpGroup(wx);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 Z(async()=>{if(await Y(r.config),!r.file){await _m(r.config);return}let n=await dt(r.config),s=await vs(n),i=await ue(n);if(!i.trim()){console.log(Se.default.dim("No declarative schemas found \u2014 nothing to diff."));return}let o="";try{o=await Em(s,i);}catch(u){if(u instanceof DataLossError){console.log(Se.default.yellow("Declarative diff includes potentially destructive changes.")),console.log(Se.default.dim("Review the schema manually and author an explicit migration for drops or other data-loss changes."));return}throw u}if(!o.trim()){console.log(Se.default.green("Schema in sync \u2014 no migration written."));return}let a=He__default.join(process.cwd(),"supabase",Tt(n));Re(a);let l=sa(r.file,na()),c=He__default.join(a,l);await ce__default.writeFile(c,o+`
|
|
186
|
+
`,{flag:"wx"}),console.log(Se.default.green(" \u279C"),"Wrote migration",Se.default.cyan(He__default.relative(process.cwd(),c)));});}),t.command("reset").description(de("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").action(async r=>{console.log(),await Z(async()=>{await Y(r.config);let n=await dt(r.config),i=(await n.connection.introspect()).tables.filter(p=>p.type==="table"),o=n.connection.dialect==="postgres",a=(p,f)=>o&&p?`"${p}"."${f}"`:`"${p?`${p}.${f}`:f}"`,l=[];for(let p of i)l.push(`DROP TABLE IF EXISTS ${a(p.schema,p.name)}${o?" CASCADE":""}`);l.push("DROP TABLE IF EXISTS migrations"),o?l.push("DROP SCHEMA IF EXISTS supabase_migrations CASCADE"):(l.push('DROP TABLE IF EXISTS "supabase_migrations.schema_migrations"'),l.push('DROP TABLE IF EXISTS "supabase_migrations.seed_files"'));for(let p of l)try{await n.connection.exec(p);}catch{}await n.connection.clearSchemaCache();let c=await Dt(n);for(let p of c.applied)console.log(Se.default.green(" \u2713"),"Applied",Se.default.cyan(p.filename));(await $m(n,c.applied.length)).hint&&(console.log(),console.log(Se.default.yellow("Declarative schemas detected with pending changes.")),console.log(Se.default.dim("Run `lite db diff -f <name>` to generate a migration, then re-run `lite db reset`."))),r.seed!==!1&&await cn(n).catch(p=>console.error(Se.default.yellow("Seed warning: "+String(p)))),console.log(Se.default.green("Database reset."));});}),t.command("query").description("Execute a SQL statement against the local or remote project").argument("<statement>","The statement to execute").option("--remote","Execute the statement on the remote project",false).option("--config <config>","Path to the config file").action(async(r,n)=>{console.log(),await Z(async()=>{n.remote||await Y(n.config);let s=await dt(n.remote?!0:n.config);console.log(`Executing: ${Se.default.cyan(r)}`);let i=await s.connection.exec(r);console.log(i);});}),t.command("schema").description(de("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 Z(async()=>{if(await Y(r.config),r.diff){await _m(r.config);return}let s=await(await dt(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(`;
|
|
182
187
|
|
|
183
|
-
`)+(i.length?";":""));return}
|
|
184
|
-
`&&(o=false),n++;continue}if(a){if(r+=u,u==="*"&&p==="/"){r+=p,n+=2,a=false;continue}n++;continue}if(l){if(r+=u,u==="$"&&e.startsWith(l,n)){r+=e.slice(n+1,n+l.length),n+=l.length,l=null;continue}n++;continue}if(s){if(r+=u,u==="'"&&p==="'"){r+=p,n+=2;continue}u==="'"&&(s=false),n++;continue}if(i){if(r+=u,u==='"'&&p==='"'){r+=p,n+=2;continue}u==='"'&&(i=false),n++;continue}if(u==="-"&&p==="-"){o=true,r+=u,n++;continue}if(u==="/"&&p==="*"){a=true,r+=u,n++;continue}if(u==="'"){s=true,r+=u,n++;continue}if(u==='"'){i=true,r+=u,n++;continue}if(u==="$"){let f=e.slice(n).match(/^\$[A-Za-z0-9_]*\$/);if(f){l=f[0],r+=f[0],n+=f[0].length;continue}}if(u===";"){let f=r.trim();f&&t.push(f),r="",n++;continue}r+=u,n++;}let c=r.trim();return c&&t.push(c),t}var
|
|
188
|
+
`)+(i.length?";":""));return}Df(s);});});};});var Am={};fe(Am,{migration:()=>_x});var oe,xx,_x,Cm=y(()=>{oe=ee(se());Be();At();Fs();Da();Te();we();Ke();xx="Local Development:",_x=e=>{let t=e.command("migration").description("Manage database migrations").helpGroup(xx);t.command("diff").description(de("Diff DB state against schemas/*.sql")).option("--config <config>","Path to the config file").option("--execute","Execute the migration").option("--force","Force the migration",false).option("--sql","Show the SQL for the migration",false).option("--seed","Seed the database with data",false).action(async r=>{await Y(r.config);let s=await(await V({withSupabaseClient:false})).project.local.createApp(r.config),i=await ue(s),o=s.connection.createMigrator(i),a=await o.diff();if(console.log(),a.plan.steps.length>0){pt(a);let l=null;try{r.execute&&(await o.migratePlan(a.plan,{force:r.force??!1}),La(a),console.log());}catch(c){l=c;}if(r.sql){let c=r.execute?l?oe.default.red:oe.default.green:oe.default.cyan;console.log(c(un(a,{colorize:true})));}l&&(l instanceof DataLossError&&(console.log(),console.warn(oe.default.yellow("Migration would potentially cause data loss. Rerun with --force to proceed.")),process.exit(1)),console.error(oe.default.red("Migration error: "+String(l))),process.exit(1)),r.execute||console.log(oe.default.yellow("Migration not executed. Use --execute to execute."));}else console.log(oe.default.green("No changes to migrate."));r.seed&&await Oa(s),process.exit(0);}),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 Y(n.config);let i=await(await V({withSupabaseClient:false})).project.local.createApp(n.config),o=await gf(i,r);console.log(oe.default.green(" \u279C"),"Created",oe.default.cyan(He__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 Y(r.config);let s=await(await V({withSupabaseClient:false})).project.local.createApp(r.config);if(r.dryRun){await pn(s.connection);let i=new Set(await fn(s.connection)),a=(await Ve(s)).filter(l=>!i.has(l.version));a.length===0&&(console.log(oe.default.green("No pending migrations.")),process.exit(0)),console.log(oe.default.dim("Pending:"));for(let l of a)console.log(" "+oe.default.cyan(l.filename));process.exit(0);}try{let i=await Dt(s);if(i.applied.length===0)console.log(oe.default.green("Local database is up to date."));else for(let o of i.applied)console.log(oe.default.green(" \u2713"),"Applied",oe.default.cyan(o.filename));process.exit(0);}catch(i){console.error(oe.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 Y(r.config);let s=await(await V({withSupabaseClient:false})).project.local.createApp(r.config);await pn(s.connection);let i=new Set(await fn(s.connection)),o=await Ve(s);console.log(oe.default.dim(`Migrations in ${Tt(s)}:`)),o.length===0&&console.log(oe.default.dim(" (none)"));for(let c of o){let u=i.has(c.version)?oe.default.green("[applied]"):oe.default.yellow("[pending]");console.log(` ${u} ${oe.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(oe.default.dim("Recorded versions without matching file:"));for(let c of l)console.log(` ${oe.default.red("[orphan]")} ${c}`);}process.exit(0);});};});function vx(e){let t=(e??process.env.SUPABASE_ENDPOINT??$x).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 Rm(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 $x,si,km=y(()=>{$x="https://supabase.com";si=class{constructor(t,r){this.token=t;if(!t)throw new Error("Supabase access token required");let n=vx(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 Ax(e){if(e==null||typeof e!="string")return true;try{return JSON.parse(e),!0}catch{return false}}function Cx(e){return e==null?true:typeof e!="string"?false:Tx.test(e)}function Rx(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 Pm(e){if(!e)return;let t=e.match(/varchar\s*\(\s*(\d+)\s*\)/i);return t?Number(t[1]):void 0}function Nm(e){return e?/jsonb?/i.test(e):false}function Om(e){return e?/\buuid\b/i.test(e):false}function Lm(e){return e?/timestamp(tz)?|timestamp with|timestamp without/i.test(e):false}async function Im(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,u=[];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:u});continue}if(c===0){r.push({table:i,schema:o,rowCount:c,issues:u});continue}let p=l.filter(h=>Nm(h.type)||Om(h.type)||Lm(h.type)||Pm(h.type)!==void 0);if(p.length===0){r.push({table:i,schema:o,rowCount:c,issues:u});continue}let f=p.map(h=>`"${h.name}"`).join(", ");try{let d=(await e.connection.exec(`SELECT ${f} FROM ${a}`))?.rows??[];for(let m of d)for(let b of p){let g=m[b.name];if(Nm(b.type)&&!Ax(g)){u.push({table:i,column:b.name,kind:"invalid_json",message:`row contains non-parseable JSON in ${i}.${b.name}`});continue}if(Om(b.type)&&g!=null&&!Cx(g)){u.push({table:i,column:b.name,kind:"invalid_uuid",message:`row contains invalid UUID in ${i}.${b.name}`});continue}if(Lm(b.type)&&!Rx(g)){u.push({table:i,column:b.name,kind:"invalid_timestamp",message:`row contains unparseable timestamp in ${i}.${b.name}`});continue}let S=Pm(b.type);S!==void 0&&typeof g=="string"&&g.length>S&&u.push({table:i,column:b.name,kind:"varchar_overflow",message:`value exceeds varchar(${S}) in ${i}.${b.name}`});}}catch{}r.push({table:i,schema:o,rowCount:c,issues:u});}return r}var Tx,Dm=y(()=>{Tx=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;});function jt(e){let t=[],r="",n=0,s=false,i=false,o=false,a=false,l=null;for(;n<e.length;){let u=e[n],p=e[n+1];if(o){r+=u,u===`
|
|
189
|
+
`&&(o=false),n++;continue}if(a){if(r+=u,u==="*"&&p==="/"){r+=p,n+=2,a=false;continue}n++;continue}if(l){if(r+=u,u==="$"&&e.startsWith(l,n)){r+=e.slice(n+1,n+l.length),n+=l.length,l=null;continue}n++;continue}if(s){if(r+=u,u==="'"&&p==="'"){r+=p,n+=2;continue}u==="'"&&(s=false),n++;continue}if(i){if(r+=u,u==='"'&&p==='"'){r+=p,n+=2;continue}u==='"'&&(i=false),n++;continue}if(u==="-"&&p==="-"){o=true,r+=u,n++;continue}if(u==="/"&&p==="*"){a=true,r+=u,n++;continue}if(u==="'"){s=true,r+=u,n++;continue}if(u==='"'){i=true,r+=u,n++;continue}if(u==="$"){let f=e.slice(n).match(/^\$[A-Za-z0-9_]*\$/);if(f){l=f[0],r+=f[0],n+=f[0].length;continue}}if(u===";"){let f=r.trim();f&&t.push(f),r="",n++;continue}r+=u,n++;}let c=r.trim();return c&&t.push(c),t}var ii=y(()=>{});async function oi(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 jm(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 ue(e),i=jt(s);i.length===0&&t.push("No schema statements found in supabase/schemas/*.sql");let o=[];if(n)try{o=await Im(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 oi(e,"users"),a.sessions=await oi(e,"sessions"),a.refresh_tokens=await oi(e,"refresh_tokens"),a.identities=await oi(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 Fm=y(()=>{Be();Dm();ii();});var fl,Mm=y(()=>{fl=`-- supabase/auth core schema (Postgres)
|
|
185
190
|
-- Scope: Core Authentication + User Management
|
|
186
191
|
-- Source: GoTrue migrations + runtime analysis
|
|
187
192
|
|
|
@@ -358,31 +363,53 @@ CREATE TABLE IF NOT EXISTS auth.audit_log_entries (
|
|
|
358
363
|
created_at timestamptz DEFAULT now(),
|
|
359
364
|
ip_address varchar(64) DEFAULT ''
|
|
360
365
|
);
|
|
361
|
-
`;});function
|
|
366
|
+
`;});function Um(e=true){return e?Ec(fl):fl}var Bm=y(()=>{_r();Mm();});function Dx(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 `${qm(s)}::jsonb`}return typeof e=="number"?Number.isFinite(e)?String(e):"NULL":typeof e=="boolean"?e?"true":"false":qm(String(e))}function qm(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=Ix[r];for(let o of Nx){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]),u=Ox[o],p=Lx[o];for(let f of l){let h={...f};if(r==="supabase"&&o==="users"){let g=h.confirmed_at;g!=null&&h.email_confirmed_at==null&&(h.email_confirmed_at=g);}let d=Object.keys(h).filter(g=>!c.has(g)),m=d.map(g=>Dx(h[g],g,u,p)),b=`INSERT INTO auth.${o} (${d.map(g=>`"${g}"`).join(", ")}) VALUES (${m.join(", ")}) ON CONFLICT DO NOTHING`;n[o].push(b);}}return n}var Px,Nx,Ox,Lx,Ix,ml=y(()=>{Px=["users","sessions","identities","refresh_tokens"],Nx=Px,Ox={users:["raw_app_meta_data","raw_user_meta_data"],sessions:[],identities:["identity_data"],refresh_tokens:[]},Lx={users:["is_sso_user","is_anonymous"],sessions:[],identities:[],refresh_tokens:["revoked"]},Ix={supabase:{users:["confirmed_at"],sessions:[],identities:["email"],refresh_tokens:["id"]},local:{users:["confirmed_at"],sessions:[],identities:["email"],refresh_tokens:[]}};});async function Hm(e){let{parse:t}=await import('pgsql-parser');return t(e)}var Wm=y(()=>{});var li,Gm=y(()=>{sr();kt();li=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=nr(t),n=ks.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 jx,Fx,Mx,Ux,lr,ci,zm=y(()=>{sr();jx=["DECLARE","IF","ELSIF","ELSE","LOOP","WHILE","FOR","FOREACH","EXCEPTION","RAISE","PERFORM","EXECUTE","SELECT"],Fx=/^NEW\.(\w+)\s*(?::=|=)\s*(.+)$/is,Mx=/^RETURN\s+(NEW|OLD)$/i,Ux=/^(INSERT|UPDATE|DELETE)\b/i,lr=class extends Pt{constructor(r,n,s){super(s??`Unsupported PL/pgSQL: ${r}`);this.hint=r;this.body=n;}},ci=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(Mx);if(l){i=l[1].toUpperCase(),s.push({type:"return",value:i});continue}let c=a.match(Fx);if(c){s.push({type:"assignment",column:c[1],expression:c[2].trim()});continue}if(Ux.test(a)){s.push({type:"dml",sql:a});continue}throw new lr(`"${a.substring(0,80)}" is not translatable to SQLite`,r)}if(!i)throw new Pt("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 lr('"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 lr("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&&jx.includes(r))throw new lr(`"${r}" is not translatable to SQLite`,t)}};});var ui,pi=y(()=>{ui=class extends Error{constructor(r){super(`Migration would cause data loss:
|
|
362
367
|
${r.map(n=>` - ${n.table}: ${n.reason}`).join(`
|
|
363
|
-
`)}`);this.warnings=r;this.name="DataLossError";}};});var
|
|
368
|
+
`)}`);this.warnings=r;this.name="DataLossError";}};});var fi,Vm=y(()=>{_r();fi=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 b=r.tables.find(A=>A.name===m.name);if(!b)continue;let g=zi(m.sql),S=zi(b.sql);g!==S&&n.push({type:"modified",name:m.name,sql:b.sql});}let c=t.tables.filter(m=>l.has(m.name));for(let m of c){let b=t.columns.filter($=>$.table===m.name),g=r.columns.filter($=>$.table===m.name),S=new Map(b.map($=>[$.name,$])),A=new Map(g.map($=>[$.name,$]));for(let[$,P]of A)S.has($)||s.push({type:"added",table:m.name,name:$,column:P});for(let[$]of S)A.has($)||s.push({type:"removed",table:m.name,name:$});for(let[$,P]of S){let N=A.get($);if(!N)continue;let v={};Gi(P.type)!==Gi(N.type)&&(v.type={from:P.type,to:N.type}),P.nullable!==N.nullable&&(v.nullable={from:P.nullable,to:N.nullable}),Vi(P.default_value)!==Vi(N.default_value)&&(v.default_value={from:P.default_value,to:N.default_value}),Object.keys(v).length>0&&s.push({type:"modified",table:m.name,name:$,changes:v});}}let u=new Map(t.indexes.map(m=>[this.makeIndexKey(m),m])),p=new Map(r.indexes.map(m=>[this.makeIndexKey(m),m]));for(let[m,b]of p)u.has(m)||i.push({type:"added",...b});for(let[m,b]of u)p.has(m)||i.push({type:"removed",...b});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,b]of h)f.has(m)||o.push({type:"added",...b});for(let[m,b]of f)h.has(m)||o.push({type:"removed",...b});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 qx,mi,Km=y(()=>{pi();Tr();qx=["CURRENT_TIMESTAMP","CURRENT_TIME","CURRENT_DATE"],mi=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 p of t.tables.filter(f=>f.type==="added")){i.push({sql:`${p.sql};`,description:`CREATE TABLE ${M(p.name)}`,type:"create_table"});let f=n.indexes.filter(h=>h.table===p.name);for(let h of f){let d=h.unique?"UNIQUE ":"",m=h.columns.map(b=>M(b)).join(", ");i.push({sql:`CREATE ${d}INDEX ${M(h.name)} ON ${M(p.name)} (${m});`,description:`Create index ${M(h.name)} on ${M(p.name)}`,type:"add_index"});}}let a=new Set(r.tables.map(p=>p.name)),l=new Set(n.tables.map(p=>p.name)),c=new Set(t.tables.filter(p=>p.type==="modified").map(p=>p.name)),u=[...a].filter(p=>l.has(p));for(let p of u){if(!(c.has(p)||t.columns.some(m=>m.table===p)||t.indexes.some(m=>m.table===p)||t.foreign_keys.some(m=>m.table===p)))continue;let{canAlter:h,addedCols:d}=this.canSimpleAlter(p,t,n);if(h){for(let g of d)i.push({sql:`ALTER TABLE ${M(p)} ADD COLUMN ${this.columnDef(g)};`,description:`Add column ${M(g.name)} to ${M(p)}`,type:"add_column"});let m=t.indexes.filter(g=>g.table===p&&g.type==="added"),b=t.indexes.filter(g=>g.table===p&&g.type==="removed");for(let g of b)i.push({sql:`DROP INDEX IF EXISTS ${M(g.name)};`,description:`Drop index ${M(g.name)}`,type:"drop_index"});for(let g of m){let S=g.unique?"UNIQUE ":"",A=g.columns.map($=>M($)).join(", ");i.push({sql:`CREATE ${S}INDEX ${M(g.name)} ON ${M(p)} (${A});`,description:`Create index ${M(g.name)} on ${M(p)}`,type:"add_index"});}}else {let m=this.rebuildTable(p,r,n,t);i.push(...m.steps),o.push(...m.warnings);}}for(let p of t.tables.filter(f=>f.type==="removed"))i.push({sql:`DROP TABLE ${M(p.name)};`,description:`Drop table ${M(p.name)}`,type:"drop_table"}),o.push({table:p.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(g=>g.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${M(l)}`);i.push({sql:`${c};`,description:`Create temporary table ${M(l)}`,type:"create_table"});let u=r.columns.filter(g=>g.table===t).map(g=>g.name),p=n.columns.filter(g=>g.table===t).map(g=>g.name),f=u.filter(g=>p.includes(g));if(f.length>0){let g=f.map(S=>M(S)).join(", ");i.push({sql:`INSERT INTO ${M(l)} (${g})
|
|
364
369
|
SELECT ${g}
|
|
365
|
-
FROM ${M(t)};`,description:`Copy data from ${M(t)} to ${M(l)}`,type:"copy_data"});}i.push({sql:`DROP TABLE ${M(t)};`,description:`Drop old table ${M(t)}`,type:"drop_table"}),i.push({sql:`ALTER TABLE ${M(l)} RENAME TO ${M(t)};`,description:`Rename ${M(l)} to ${M(t)}`,type:"rename_table"});let h=n.indexes.filter(g=>g.table===t);for(let g of h){let S=g.unique?"UNIQUE ":"",A=g.columns.map(v=>M(v)).join(", ");i.push({sql:`CREATE ${S}INDEX ${M(g.name)} ON ${M(t)} (${A});`,description:`Recreate index ${M(g.name)} on ${M(t)}`,type:"add_index"});}let d=n.triggers?.filter(g=>g.table===t)??[];for(let g of d)i.push({sql:`${g.sql};`,description:`Recreate trigger ${M(g.name)} on ${M(t)}`,type:"create_trigger"});let m=s.columns.filter(g=>g.table===t&&g.type==="removed");for(let g of m)o.push({table:t,reason:`column "${g.name}" will be dropped`});let b=s.columns.filter(g=>g.table===t&&g.type==="modified");for(let g of b)g.changes?.type&&o.push({table:t,reason:`column "${g.name}" type changes from ${g.changes.type.from} to ${g.changes.type.to}`}),g.changes?.nullable&&!g.changes.nullable.to&&o.push({table:t,reason:`column "${g.name}" becomes NOT NULL`});return {steps:i,warnings:o}}canSimpleAlter(t,r,n){let s=r.columns.filter(p=>p.table===t),i=s.filter(p=>p.type==="added"),o=s.filter(p=>p.type==="removed"),a=s.filter(p=>p.type==="modified"),l=r.foreign_keys.some(p=>p.table===t);if(o.length>0||a.length>0||l)return {canAlter:false,addedCols:i};let c=n.tables.find(p=>p.name===t);return c&&/\bCHECK\s*\(/i.test(c.sql)?{canAlter:false,addedCols:i}:{canAlter:i.every(p=>{let f=p.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 l0.includes(r)}columnDef(t){let r=t.column,n=`${M(r.name)} ${r.type||"TEXT"}`;return r.nullable||(n+=" NOT NULL"),r.default_value!=null&&(n+=` DEFAULT ${r.default_value}`),n}};});var $i,Od=y(()=>{ar();Ot();Ot();Rd();pt();Pd();_i();kd();Nd();Cr();Ha();za();$i=class extends Deparser{enums;schemaHandling;warnings=[];helper;config;triggerFunctions=new Map;plpgsqlParser=new Si;introspection;functionResolution;constructor(t,{enums:r,schemaHandling:n,introspection:s,...i}={}){super(t,i),this.schemaHandling=n??"default",this.enums=r??new Map,this.helper=new bi(t),this.config=i,this.introspection=s,this.functionResolution=i?.functionResolution??"translate";}visit(t,r){let n=or(t),s=Hs.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=>cu(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":cm(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,u=false;if(t.typeName){let p=t.typeName.names?.map(d=>d.String?.sval||d.String?.str).filter(Boolean);c=p&&(p.length===2&&p[0]==="pg_catalog"?p[1]:p[0]),i=!!(c&&Us(c)),u=!!(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&&Bs(c)&&f.length>0){let d=h(0);typeof d=="number"&&d>0&&(a={maxLen:d});}if(c&&qs(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 p=Array.isArray(t.constraints)?t.constraints:[],f=p.map(d=>this.visit(d,r));n.push(...f.filter(Boolean));let h=p.some(d=>d.Constraint?.contype==="CONSTR_CHECK");i&&o&&!h&&n.push("AUTOINCREMENT");}if(s&&c){let p={isArray:u};a&&(p.lengthConstraint=a.maxLen),l&&(p.numericPrecision=l);let f=this.enums.get(c.toLowerCase());f&&(p.enumValues=f);let m=jt({schema:"public",table:"",column:s,pgTypeName:c,nullable:true,defaultValue:null,defaultFn:null,isPrimaryKey:o,isUnique:false,isSerial:i},p).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",Ms(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 (${Nt(t.keys).map(i=>this.visit(i,r)).join(", ")})`:"PRIMARY KEY";if(n==="CONSTR_UNIQUE")return t.keys&&t.keys.length>0?`UNIQUE (${Nt(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=Wa(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=Vs[i];if(c?.sqlite){let u=c.sqlite();return u.includes("(")?u:`${u}(${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(!lm.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(Ms(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(Ms(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(p=>p.String?.sval).filter(Boolean)??[],l=a.length===2&&a[0]==="pg_catalog"?a[1]:a[0],u=["text","varchar","character varying","char","bpchar","name","uuid"].includes(l?.toLowerCase());try{let p=this.parsePgArrayLiteral(o,u);return `'${JSON.stringify(p).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=Nt(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=Nt(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(u=>"AlterTableCmd"in u&&!s.includes(u.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 u of i){let p=u.AlterTableCmd.subtype;if(o.includes(p)){let f={...t,cmds:[u]};l.push(super.AlterTableStmt(f,r));}else if(a.includes(p))c.push(u.AlterTableCmd);else throw new B({AlterTableStmt:t},`AlterTableCmd with subtype ${p} is not supported in SQLite`)}if(c.length>0){let u=this.getRelationName(t.relation);l.push(this.generateRebuildSql(u,c));}return l.join(`;
|
|
366
|
-
`)}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=
|
|
367
|
-
`)}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}}translateDml(t,r){return 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");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
|
|
368
|
-
`):""}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(p=>p.name===r);if(n===-1)return;let s=t.columns.filter(p=>p.table===r),i=t.foreign_keys.filter(p=>p.table===r),o=t.check_constraints.filter(p=>p.table===r),a=s.map(p=>{let f=`${M(p.name)} ${p.type||"TEXT"}`;return p.is_primary_key&&(f+=" PRIMARY KEY"),p.nullable||(f+=" NOT NULL"),p.default_value!=null&&(f+=` DEFAULT ${p.default_value}`),f}),l=i.map(p=>`FOREIGN KEY (${M(p.column)}) REFERENCES ${M(p.ref_table)}(${M(p.ref_column)}) ON UPDATE ${p.on_update} ON DELETE ${p.on_delete}`),c=o.map(p=>`CHECK (${p.expression})`),u=[...a,...l,...c];t.tables[n]={...t.tables[n],sql:`CREATE TABLE ${M(r)} (${u.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}};});async function $n(e,t={}){let r=await Ad(e);return {ast:r,...f0(r,t)}}function f0(e,t={}){let r=Va(e),n=Ja(e,r),s=Ka(e),i=Xa(e),o=Qa(e),a=new $i(e,{...t,enums:r}),{policies:l,tables:c}=Ya(e);if(t.strict)for(let u of l){if(!n.get(`${u.data.schema??"public"}.${u.data.table}`))throw new Error(`Policy "${u.data.name}" references unknown table "${u.data.table}"`);if(!c.has(u.data.table))throw new Error(`RLS is not enabled on table "${u.data.table}"`)}return {ddl:a.deparseQuery(),enums:r,rls:{tables:c,policies:l},schema:n,vars:s,tableConstraints:i,comments:o}}var jl=y(()=>{Cd();Od();Ca();el();Ra();});function Ti(e){return !e||e==="main"||e==="public"?"public":e}function Tn(e,t){return `${Ti(e)}.${t}`}function d0(e,t){let r=new Map(e.map(a=>[Tn(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=Tn(a.schema,a.table),c=Tn(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 u=n.get(c);u&&(u.delete(l),u.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=Tn(l.schema,l.name);a.has(c)||o.push(c);}}return o.map(a=>r.get(a)).filter(Boolean)}function Ld(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=>Ld(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 `${pr(n)}${s}`}return e instanceof Date?pr(e.toISOString()):typeof e=="object"?`${pr(JSON.stringify(e))}::jsonb`:pr(String(e))}function pr(e){return `'${e.replace(/'/g,"''")}'`}function Fl(e){return `"${e.replace(/"/g,'""')}"`}function h0(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 Id.has(r)||Id.has(n)}function g0(e,t,r){let n=`${Fl(e)}.${Fl(t)}`;return `SELECT setval(pg_get_serial_sequence(${pr(n)}, ${pr(r)}), COALESCE((SELECT MAX(${Fl(r)}) FROM ${n}), 1));`}async function y0(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 $n(r)).schema:new Map}async function Ai(e){let t=await e.connection.introspect(),r=e.connection.dialect,n=await y0(e),s=d0(t.tables.filter(o=>!m0.has(Ti(o.schema))),t.foreign_keys),i=[];for(let o of s){let a=Ti(o.schema),l=r==="sqlite"?a==="public"?`"${o.name}"`:`"${a}.${o.name}"`:`"${a}"."${o.name}"`,u=t.columns.filter(S=>S.table===o.name&&Ti(S.schema)===a).filter(S=>!S.generated&&!S.is_generated),p=[];try{p=(await e.connection.exec(`SELECT * FROM ${l}`))?.rows??[];}catch{continue}if(p.length===0)continue;let f=n.get(Tn(a,o.name)),h=typeof e.connection.deserializeRow=="function"?e.connection.deserializeRow.bind(e.connection):S=>S;p=p.map(S=>{let A=f?f.deserializeRow(S):S;return h(A)});let d=u.map(S=>S.name),m=new Map(u.map(S=>[S.name,S.pg_type??S.type])),b=[];for(let S of p){let A=d.map(v=>Ld(S[v],m.get(v)));b.push(`INSERT INTO "${a}"."${o.name}" (${d.map(v=>`"${v}"`).join(", ")}) VALUES (${A.join(", ")}) ON CONFLICT DO NOTHING`);}let g=u.filter(h0).map(S=>g0(a,o.name,S.name));i.push({schema:a,table:o.name,inserts:b,sequenceResets:g});}return i}var m0,Id,Ml=y(()=>{jl();We();m0=new Set(["auth","storage","realtime","supabase_functions","graphql","graphql_public","extensions","pgsodium","pgsodium_masks","vault","information_schema","pg_catalog","pg_toast"]),Id=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]);});async function Dd(e){let{PGlite:t}=await Ye("@supabase/lite/pglite","pglite","@electric-sql/pglite"),r=new t,n=[],s=0,i=0,o=0,a=0;try{for(let h of ["anon","authenticated","service_role","supabase_auth_admin"])await r.exec(`CREATE ROLE ${h}`);if(e.config.auth?.enabled!==!1){let h=Ut(vd());s=h.length;for(let d=0;d<h.length;d++)try{await r.exec(h[d]);}catch(m){return n.push({phase:"schema",label:`auth base schema ${d+1}/${h.length}`,statement:h[d],error:String(m)}),{ok:!1,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:n}}}let l=await ge(e),c=Ut(l);i=c.length;for(let h=0;h<c.length;h++)try{await r.exec(c[h]);}catch(d){return n.push({phase:"schema",label:`schema ${h+1}/${c.length}`,statement:c[h],error:String(d)}),{ok:!1,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:n}}let u=await wi(e,{target:"local"}),p=["users","sessions","identities","refresh_tokens"];for(let h of p){let d=u[h];for(let m=0;m<d.length;m++){o++;try{await r.exec(d[m]);}catch(b){n.push({phase:"auth",label:`auth.${h} row ${m+1}/${d.length}`,statement:d[m],error:String(b)});}}}let f=await Ai(e);for(let h of f){for(let d=0;d<h.inserts.length;d++){a++;try{await r.exec(h.inserts[d]);}catch(m){n.push({phase:"data",label:`${h.schema}.${h.table} row ${d+1}/${h.inserts.length}`,statement:h.inserts[d],error:String(m)});}}for(let d=0;d<h.sequenceResets.length;d++)try{await r.exec(h.sequenceResets[d]);}catch(m){n.push({phase:"data",label:`${h.schema}.${h.table} sequence reset ${d+1}/${h.sequenceResets.length}`,statement:h.sequenceResets[d],error:String(m)});}}}finally{await r.close().catch(()=>{});}return {ok:n.length===0,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:n}}var jd=y(()=>{jr();We();$d();gi();Dl();Ml();});function Fd(e){if(console.log(P.default.bold("Readiness Report")),console.log(` db reachable: ${e.dbReachable?P.default.green("yes"):P.default.red("no")} schema statements: ${P.default.cyan(e.schemaStatementCount)} schema bytes: ${P.default.cyan(e.schemaBytes)}`),console.log(` auth \u2014 users: ${P.default.cyan(e.auth.users)} sessions: ${P.default.cyan(e.auth.sessions)} identities: ${P.default.cyan(e.auth.identities)} refresh_tokens: ${P.default.cyan(e.auth.refresh_tokens)} jwt_secret: ${e.auth.jwt_secret_set?P.default.green("set"):P.default.yellow("unset")}`),e.tables.length>0){console.log(P.default.dim(" tables:"));for(let t of e.tables){let r=t.issues.length>0?P.default.yellow(` (${t.issues.length} issues)`):"",n=t.schema?`${t.schema}.`:"";console.log(` ${n}${t.table}: ${P.default.cyan(t.rowCount)} rows${r}`);}}if(e.errors.length>0){console.log(P.default.red("Errors:"));for(let t of e.errors)console.log(` ${P.default.red("\u2717")} ${t}`);}if(e.warnings.length>0){console.log(P.default.yellow("Warnings:"));for(let t of e.warnings)console.log(` ${P.default.yellow("!")} ${t}`);}console.log(),console.log(e.ok?P.default.green("Ready to upgrade."):P.default.red("Not ready."));}function Md(e){if(console.log(),console.log(P.default.bold("Rehearsal (in-memory pglite)")),console.log(` auth schema: ${P.default.cyan(e.baseSchemaStatements)} stmts user schema: ${P.default.cyan(e.schemaStatements)} stmts auth: ${P.default.cyan(e.authInserts)} inserts data: ${P.default.cyan(e.dataInserts)} inserts`),e.failures.length>0){console.log(P.default.red(` ${e.failures.length} failure(s):`));for(let t of e.failures)console.log(P.default.red(` \u2717 [${t.phase}] ${t.label}`)),console.log(P.default.dim(` ${t.statement}`)),console.log(P.default.dim(` ${t.error}`));}console.log(e.ok?P.default.green(" rehearsal passed"):P.default.red(" rehearsal failed"));}function Ud(e){console.log(),console.log(P.default.bold("SQLite Shim Audit")),console.log(` fields: ${P.default.cyan(e.summary.total)} passed: ${P.default.green(String(e.summary.passed))} warned: ${P.default.yellow(String(e.summary.warned))} failed: ${P.default.red(String(e.summary.failed))}`),e.results.length===0&&console.log(P.default.dim(" no shim-backed fields found"));for(let t of e.results.filter(r=>r.status!=="pass")){let r=t.status==="fail"?P.default.red:P.default.yellow;if(console.log(` ${r(t.status)} ${t.field} (${t.pg_type}) rows: ${P.default.cyan(t.rows_checked)} affected: ${P.default.cyan(t.affected_rows??0)}`),t.message&&console.log(` ${t.message}`),t.samples?.length)for(let n of t.samples)console.log(P.default.dim(` sample ${JSON.stringify(n.id)} raw=${JSON.stringify(n.raw_value)}`));t.action&&console.log(P.default.dim(` action: ${t.action}`));}console.log(e.summary.upgrade_safe?P.default.green(" shim audit passed"):P.default.red(" shim audit failed"));}function Ul(e){if(console.log(),console.log(P.default.bold(P.default.green("Upgrade complete."))),console.log(),console.log(` ${P.default.bold("Project URL:")} ${P.default.cyan(e.projectUrl)}`),console.log(` ${P.default.bold("API URL:")} ${P.default.cyan(e.apiUrl)}`),e.studioUrl&&console.log(` ${P.default.bold("Studio URL:")} ${P.default.cyan(e.studioUrl)}`),console.log(` ${P.default.bold("Ref:")} ${P.default.cyan(e.projectRef)}`),console.log(),console.log(` ${P.default.bold("anon key:")} ${e.anonKey}`),console.log(` ${P.default.bold("service_role key:")} ${e.serviceRoleKey}`),console.log(` ${P.default.bold("db password:")} ${e.dbPassword}`),console.log(),console.log(` migrated auth \u2014 users: ${P.default.cyan(e.auth.users)} sessions: ${P.default.cyan(e.auth.sessions)} identities: ${P.default.cyan(e.auth.identities)} refresh_tokens: ${P.default.cyan(e.auth.refresh_tokens)}`),console.log(` jwt secret: ${e.jwtMigrated?P.default.green("migrated"):P.default.yellow("not migrated \u2014 users must re-authenticate")}`),e.warnings.length>0){console.log(),console.log(P.default.yellow("Warnings:"));for(let t of e.warnings)console.log(` ${P.default.yellow("!")} ${t}`);}console.log(),console.log(P.default.bold("Update your supabase-js client:")),console.log(` url: ${P.default.cyan(e.apiUrl)}`),console.log(` anonKey: ${P.default.cyan(e.anonKey)}`),console.log();}var P,Bd=y(()=>{P=te(ie());});function Hd(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};w0.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"):S0(r)&&t.push("contains an obvious repeated pattern");let o=b0.find(a=>n.includes(a));return o&&t.push(`contains placeholder term "${o}"`),{strong:t.length===0,reasons:t}}function Wd(e){return {kty:"oct",alg:"HS256",k:Buffer$1.from(e,"utf8").toString("base64url")}}function S0(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 w0,b0,zd=y(()=>{w0=new Set(["unsafe-secret-change-me","dev-secret-change-me"]),b0=["change-me","changeme","secret","password","passwd","test","dev"];});function Gd(e){return !e||e==="main"?"public":e}function Bt(e){return `"${e.replace(/"/g,'""')}"`}function _0(e,t){return Bt(e==="public"?t:`${e}.${t}`)}function Bl(e){return `${e.schema}.${e.table}.${e.column}`}function x0(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 v0(e){let t=e.connection.config?.translation?.deparse?.schema;if(t instanceof Map&&t.size>0)return t;let r=await Fs(e),n=await ge(e);if(r.trim()){let i=[await nd(r),n].filter(o=>o.trim().length>0).join(`
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
370
|
+
FROM ${M(t)};`,description:`Copy data from ${M(t)} to ${M(l)}`,type:"copy_data"});}i.push({sql:`DROP TABLE ${M(t)};`,description:`Drop old table ${M(t)}`,type:"drop_table"}),i.push({sql:`ALTER TABLE ${M(l)} RENAME TO ${M(t)};`,description:`Rename ${M(l)} to ${M(t)}`,type:"rename_table"});let h=n.indexes.filter(g=>g.table===t);for(let g of h){let S=g.unique?"UNIQUE ":"",A=g.columns.map($=>M($)).join(", ");i.push({sql:`CREATE ${S}INDEX ${M(g.name)} ON ${M(t)} (${A});`,description:`Recreate index ${M(g.name)} on ${M(t)}`,type:"add_index"});}let d=n.triggers?.filter(g=>g.table===t)??[];for(let g of d)i.push({sql:`${g.sql};`,description:`Recreate trigger ${M(g.name)} on ${M(t)}`,type:"create_trigger"});let m=s.columns.filter(g=>g.table===t&&g.type==="removed");for(let g of m)o.push({table:t,reason:`column "${g.name}" will be dropped`});let b=s.columns.filter(g=>g.table===t&&g.type==="modified");for(let g of b)g.changes?.type&&o.push({table:t,reason:`column "${g.name}" type changes from ${g.changes.type.from} to ${g.changes.type.to}`}),g.changes?.nullable&&!g.changes.nullable.to&&o.push({table:t,reason:`column "${g.name}" becomes NOT NULL`});return {steps:i,warnings:o}}canSimpleAlter(t,r,n){let s=r.columns.filter(p=>p.table===t),i=s.filter(p=>p.type==="added"),o=s.filter(p=>p.type==="removed"),a=s.filter(p=>p.type==="modified"),l=r.foreign_keys.some(p=>p.table===t);if(o.length>0||a.length>0||l)return {canAlter:false,addedCols:i};let c=n.tables.find(p=>p.name===t);return c&&/\bCHECK\s*\(/i.test(c.sql)?{canAlter:false,addedCols:i}:{canAlter:i.every(p=>{let f=p.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 qx.includes(r)}columnDef(t){let r=t.column,n=`${M(r.name)} ${r.type||"TEXT"}`;return r.nullable||(n+=" NOT NULL"),r.default_value!=null&&(n+=` DEFAULT ${r.default_value}`),n}};});function Vx(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"&&zx.has(t.objtype)}var zx,di,Jm=y(()=>{sr();kt();kt();Gm();at();zm();pi();Vm();Km();Tr();Sa();xa();zx=new Set(["OBJECT_TABLE","OBJECT_VIEW","OBJECT_SEQUENCE","OBJECT_SCHEMA"]);di=class extends Deparser{enums;schemaHandling;warnings=[];helper;config;triggerFunctions=new Map;plpgsqlParser=new ci;introspection;functionResolution;constructor(t,{enums:r,schemaHandling:n,introspection:s,...i}={}){super(t,i),this.schemaHandling=n??"default",this.enums=r??new Map,this.helper=new li(t),this.config=i,this.introspection=s,this.functionResolution=i?.functionResolution??"translate";}visit(t,r){let n=nr(t);if(n==="GrantStmt"&&Vx(t))return "";let s=ks.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=>Bc(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,u=false;if(t.typeName){let p=t.typeName.names?.map(d=>d.String?.sval||d.String?.str).filter(Boolean);c=p&&(p.length===2&&p[0]==="pg_catalog"?p[1]:p[0]),i=!!(c&&As(c)),u=!!(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&&Cs(c)&&f.length>0){let d=h(0);typeof d=="number"&&d>0&&(a={maxLen:d});}if(c&&Rs(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 p=Array.isArray(t.constraints)?t.constraints:[],f=p.map(d=>this.visit(d,r));n.push(...f.filter(Boolean));let h=p.some(d=>d.Constraint?.contype==="CONSTR_CHECK");i&&o&&!h&&n.push("AUTOINCREMENT");}if(s&&c){let p={isArray:u};a&&(p.lengthConstraint=a.maxLen),l&&(p.numericPrecision=l);let f=this.enums.get(c.toLowerCase());f&&(p.enumValues=f);let m=Lt({schema:"public",table:"",column:s,pgTypeName:c,nullable:true,defaultValue:null,defaultFn:null,isPrimaryKey:o,isUnique:false,isSerial:i},p).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",Ts(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 (${Rt(t.keys).map(i=>this.visit(i,r)).join(", ")})`:"PRIMARY KEY";if(n==="CONSTR_UNIQUE")return t.keys&&t.keys.length>0?`UNIQUE (${Rt(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=Ea(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=Ls[i];if(c?.sqlite){let u=c.sqlite();return u.includes("(")?u:`${u}(${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(!wf.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(Ts(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(Ts(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(p=>p.String?.sval).filter(Boolean)??[],l=a.length===2&&a[0]==="pg_catalog"?a[1]:a[0],u=["text","varchar","character varying","char","bpchar","name","uuid"].includes(l?.toLowerCase());try{let p=this.parsePgArrayLiteral(o,u);return `'${JSON.stringify(p).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=Rt(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=Rt(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(u=>"AlterTableCmd"in u&&!s.includes(u.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 u of i){let p=u.AlterTableCmd.subtype;if(o.includes(p)){let f={...t,cmds:[u]};l.push(super.AlterTableStmt(f,r));}else if(a.includes(p))c.push(u.AlterTableCmd);else throw new B({AlterTableStmt:t},`AlterTableCmd with subtype ${p} is not supported in SQLite`)}if(c.length>0){let u=this.getRelationName(t.relation);l.push(this.generateRebuildSql(u,c));}return l.join(`;
|
|
371
|
+
`)}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=Rt(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=Rt(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(p=>p.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 p=t.columns.map(f=>f.String?.sval).filter(Boolean);l.push(`UPDATE OF ${p.join(", ")}`);}else l.push("UPDATE");let c=l.join(" OR "),u=this.buildTriggerBody(o,s,r);return [`CREATE TRIGGER ${n}`,`${a} ${c} ON ${s}`,"FOR EACH ROW","BEGIN",...u.map(p=>` ${p};`),"END"].join(`
|
|
372
|
+
`)}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}}translateDml(t,r){return 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");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 fi,i=new mi,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(`
|
|
373
|
+
`):""}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(p=>p.name===r);if(n===-1)return;let s=t.columns.filter(p=>p.table===r),i=t.foreign_keys.filter(p=>p.table===r),o=t.check_constraints.filter(p=>p.table===r),a=s.map(p=>{let f=`${M(p.name)} ${p.type||"TEXT"}`;return p.is_primary_key&&(f+=" PRIMARY KEY"),p.nullable||(f+=" NOT NULL"),p.default_value!=null&&(f+=` DEFAULT ${p.default_value}`),f}),l=i.map(p=>`FOREIGN KEY (${M(p.column)}) REFERENCES ${M(p.ref_table)}(${M(p.ref_column)}) ON UPDATE ${p.on_update} ON DELETE ${p.on_delete}`),c=o.map(p=>`CHECK (${p.expression})`),u=[...a,...l,...c];t.tables[n]={...t.tables[n],sql:`CREATE TABLE ${M(r)} (${u.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}};});async function En(e,t={}){let r=await Hm(e);return {ast:r,...Kx(r,t)}}function Kx(e,t={}){let r=$a(e),n=Aa(e,r),s=va(e),i=Ca(e),o=Ra(e),a=new di(e,{...t,enums:r}),{policies:l,tables:c}=Ta(e);if(t.strict)for(let u of l){if(!n.get(`${u.data.schema??"public"}.${u.data.table}`))throw new Error(`Policy "${u.data.name}" references unknown table "${u.data.table}"`);if(!c.has(u.data.table))throw new Error(`RLS is not enabled on table "${u.data.table}"`)}return {ddl:a.deparseQuery(),enums:r,rls:{tables:c,policies:l},schema:n,vars:s,tableConstraints:i,comments:o}}var dl=y(()=>{Wm();Jm();ia();Pa();oa();});function hi(e){return !e||e==="main"||e==="public"?"public":e}function xn(e,t){return `${hi(e)}.${t}`}function Xx(e,t){let r=new Map(e.map(a=>[xn(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=xn(a.schema,a.table),c=xn(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 u=n.get(c);u&&(u.delete(l),u.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=xn(l.schema,l.name);a.has(c)||o.push(c);}}return o.map(a=>r.get(a)).filter(Boolean)}function Ym(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=>Ym(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 `${cr(n)}${s}`}return e instanceof Date?cr(e.toISOString()):typeof e=="object"?`${cr(JSON.stringify(e))}::jsonb`:cr(String(e))}function cr(e){return `'${e.replace(/'/g,"''")}'`}function hl(e){return `"${e.replace(/"/g,'""')}"`}function Yx(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 Xm.has(r)||Xm.has(n)}function Qx(e,t,r){let n=`${hl(e)}.${hl(t)}`;return `SELECT setval(pg_get_serial_sequence(${cr(n)}, ${cr(r)}), COALESCE((SELECT MAX(${hl(r)}) FROM ${n}), 1));`}async function Zx(e){let t=e.connection.config?.translation?.deparse?.schema;if(t instanceof Map&&t.size>0)return t;let r=await ue(e);return r.trim()?(await En(r)).schema:new Map}async function gi(e){let t=await e.connection.introspect(),r=e.connection.dialect,n=await Zx(e),s=Xx(t.tables.filter(o=>!Jx.has(hi(o.schema))),t.foreign_keys),i=[];for(let o of s){let a=hi(o.schema),l=r==="sqlite"?a==="public"?`"${o.name}"`:`"${a}.${o.name}"`:`"${a}"."${o.name}"`,u=t.columns.filter(S=>S.table===o.name&&hi(S.schema)===a).filter(S=>!S.generated&&!S.is_generated),p=[];try{p=(await e.connection.exec(`SELECT * FROM ${l}`))?.rows??[];}catch{continue}if(p.length===0)continue;let f=n.get(xn(a,o.name)),h=typeof e.connection.deserializeRow=="function"?e.connection.deserializeRow.bind(e.connection):S=>S;p=p.map(S=>{let A=f?f.deserializeRow(S):S;return h(A)});let d=u.map(S=>S.name),m=new Map(u.map(S=>[S.name,S.pg_type??S.type])),b=[];for(let S of p){let A=d.map($=>Ym(S[$],m.get($)));b.push(`INSERT INTO "${a}"."${o.name}" (${d.map($=>`"${$}"`).join(", ")}) VALUES (${A.join(", ")}) ON CONFLICT DO NOTHING`);}let g=u.filter(Yx).map(S=>Qx(a,o.name,S.name));i.push({schema:a,table:o.name,inserts:b,sequenceResets:g});}return i}var Jx,Xm,gl=y(()=>{dl();Be();Jx=new Set(["auth","storage","realtime","supabase_functions","graphql","graphql_public","extensions","pgsodium","pgsodium_masks","vault","information_schema","pg_catalog","pg_toast"]),Xm=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]);});async function Qm(e){let{PGlite:t}=await Ue("@supabase/lite/pglite","pglite","@electric-sql/pglite"),r=new t,n=[],s=0,i=0,o=0,a=0;try{for(let h of ["anon","authenticated","service_role","supabase_auth_admin"])await r.exec(`CREATE ROLE ${h}`);if(e.config.auth?.enabled!==!1){let h=jt(Um());s=h.length;for(let d=0;d<h.length;d++)try{await r.exec(h[d]);}catch(m){return n.push({phase:"schema",label:`auth base schema ${d+1}/${h.length}`,statement:h[d],error:String(m)}),{ok:!1,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:n}}}let l=await ue(e),c=jt(l);i=c.length;for(let h=0;h<c.length;h++)try{await r.exec(c[h]);}catch(d){return n.push({phase:"schema",label:`schema ${h+1}/${c.length}`,statement:c[h],error:String(d)}),{ok:!1,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:n}}let u=await ai(e,{target:"local"}),p=["users","sessions","identities","refresh_tokens"];for(let h of p){let d=u[h];for(let m=0;m<d.length;m++){o++;try{await r.exec(d[m]);}catch(b){n.push({phase:"auth",label:`auth.${h} row ${m+1}/${d.length}`,statement:d[m],error:String(b)});}}}let f=await gi(e);for(let h of f){for(let d=0;d<h.inserts.length;d++){a++;try{await r.exec(h.inserts[d]);}catch(m){n.push({phase:"data",label:`${h.schema}.${h.table} row ${d+1}/${h.inserts.length}`,statement:h.inserts[d],error:String(m)});}}for(let d=0;d<h.sequenceResets.length;d++)try{await r.exec(h.sequenceResets[d]);}catch(m){n.push({phase:"data",label:`${h.schema}.${h.table} sequence reset ${d+1}/${h.sequenceResets.length}`,statement:h.sequenceResets[d],error:String(m)});}}}finally{await r.close().catch(()=>{});}return {ok:n.length===0,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:n}}var Zm=y(()=>{Qt();Be();Bm();ii();ml();gl();});function ed(e){if(console.log(k.default.bold("Readiness Report")),console.log(` db reachable: ${e.dbReachable?k.default.green("yes"):k.default.red("no")} schema statements: ${k.default.cyan(e.schemaStatementCount)} schema bytes: ${k.default.cyan(e.schemaBytes)}`),console.log(` auth \u2014 users: ${k.default.cyan(e.auth.users)} sessions: ${k.default.cyan(e.auth.sessions)} identities: ${k.default.cyan(e.auth.identities)} refresh_tokens: ${k.default.cyan(e.auth.refresh_tokens)} jwt_secret: ${e.auth.jwt_secret_set?k.default.green("set"):k.default.yellow("unset")}`),e.tables.length>0){console.log(k.default.dim(" tables:"));for(let t of e.tables){let r=t.issues.length>0?k.default.yellow(` (${t.issues.length} issues)`):"",n=t.schema?`${t.schema}.`:"";console.log(` ${n}${t.table}: ${k.default.cyan(t.rowCount)} rows${r}`);}}if(e.errors.length>0){console.log(k.default.red("Errors:"));for(let t of e.errors)console.log(` ${k.default.red("\u2717")} ${t}`);}if(e.warnings.length>0){console.log(k.default.yellow("Warnings:"));for(let t of e.warnings)console.log(` ${k.default.yellow("!")} ${t}`);}console.log(),console.log(e.ok?k.default.green("Ready to upgrade."):k.default.red("Not ready."));}function td(e){if(console.log(),console.log(k.default.bold("Rehearsal (in-memory pglite)")),console.log(` auth schema: ${k.default.cyan(e.baseSchemaStatements)} stmts user schema: ${k.default.cyan(e.schemaStatements)} stmts auth: ${k.default.cyan(e.authInserts)} inserts data: ${k.default.cyan(e.dataInserts)} inserts`),e.failures.length>0){console.log(k.default.red(` ${e.failures.length} failure(s):`));for(let t of e.failures)console.log(k.default.red(` \u2717 [${t.phase}] ${t.label}`)),console.log(k.default.dim(` ${t.statement}`)),console.log(k.default.dim(` ${t.error}`));}console.log(e.ok?k.default.green(" rehearsal passed"):k.default.red(" rehearsal failed"));}function rd(e){console.log(),console.log(k.default.bold("SQLite Shim Audit")),console.log(` fields: ${k.default.cyan(e.summary.total)} passed: ${k.default.green(String(e.summary.passed))} warned: ${k.default.yellow(String(e.summary.warned))} failed: ${k.default.red(String(e.summary.failed))}`),e.results.length===0&&console.log(k.default.dim(" no shim-backed fields found"));for(let t of e.results.filter(r=>r.status!=="pass")){let r=t.status==="fail"?k.default.red:k.default.yellow;if(console.log(` ${r(t.status)} ${t.field} (${t.pg_type}) rows: ${k.default.cyan(t.rows_checked)} affected: ${k.default.cyan(t.affected_rows??0)}`),t.message&&console.log(` ${t.message}`),t.samples?.length)for(let n of t.samples)console.log(k.default.dim(` sample ${JSON.stringify(n.id)} raw=${JSON.stringify(n.raw_value)}`));t.action&&console.log(k.default.dim(` action: ${t.action}`));}console.log(e.summary.upgrade_safe?k.default.green(" shim audit passed"):k.default.red(" shim audit failed"));}function yl(e){if(console.log(),console.log(k.default.bold(k.default.green("Upgrade complete."))),console.log(),console.log(` ${k.default.bold("Project URL:")} ${k.default.cyan(e.projectUrl)}`),console.log(` ${k.default.bold("API URL:")} ${k.default.cyan(e.apiUrl)}`),e.studioUrl&&console.log(` ${k.default.bold("Studio URL:")} ${k.default.cyan(e.studioUrl)}`),console.log(` ${k.default.bold("Ref:")} ${k.default.cyan(e.projectRef)}`),console.log(),console.log(` ${k.default.bold("anon key:")} ${e.anonKey}`),console.log(` ${k.default.bold("service_role key:")} ${e.serviceRoleKey}`),console.log(` ${k.default.bold("db password:")} ${e.dbPassword}`),console.log(),console.log(` migrated auth \u2014 users: ${k.default.cyan(e.auth.users)} sessions: ${k.default.cyan(e.auth.sessions)} identities: ${k.default.cyan(e.auth.identities)} refresh_tokens: ${k.default.cyan(e.auth.refresh_tokens)}`),console.log(` jwt secret: ${e.jwtMigrated?k.default.green("migrated"):k.default.yellow("not migrated \u2014 users must re-authenticate")}`),e.warnings.length>0){console.log(),console.log(k.default.yellow("Warnings:"));for(let t of e.warnings)console.log(` ${k.default.yellow("!")} ${t}`);}console.log(),console.log(k.default.bold("Update your supabase-js client:")),console.log(` url: ${k.default.cyan(e.apiUrl)}`),console.log(` anonKey: ${k.default.cyan(e.anonKey)}`),console.log();}var k,nd=y(()=>{k=ee(se());});function id(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};e0.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"):r0(r)&&t.push("contains an obvious repeated pattern");let o=t0.find(a=>n.includes(a));return o&&t.push(`contains placeholder term "${o}"`),{strong:t.length===0,reasons:t}}function od(e){return {kty:"oct",alg:"HS256",k:Buffer$1.from(e,"utf8").toString("base64url")}}function r0(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 e0,t0,ad=y(()=>{e0=new Set(["unsafe-secret-change-me","dev-secret-change-me"]),t0=["change-me","changeme","secret","password","passwd","test","dev"];});async function ld(e){let t=e.trim();if(!t)return "";let{PGlite:r}=await Ue("@supabase/lite/pglite","pglite","@electric-sql/pglite"),n=new r;try{return await n.exec(ft(mt(t))),await n.exec(Uf),await n0(n,t)}finally{await n.close().catch(()=>{});}}async function n0(e,t){return t?(await e.exec(t),await s0(e)):""}async function s0(e){let t=await e.query(`
|
|
374
|
+
SELECT table_schema, table_name, column_name, is_nullable, data_type,
|
|
375
|
+
udt_name, udt_schema, character_maximum_length,
|
|
376
|
+
numeric_precision, numeric_scale, column_default, ordinal_position
|
|
377
|
+
FROM information_schema.columns
|
|
378
|
+
WHERE table_schema NOT IN ('pg_catalog', 'information_schema', 'pg_toast')
|
|
379
|
+
ORDER BY table_schema, table_name, ordinal_position
|
|
380
|
+
`),r=await e.query(`
|
|
381
|
+
SELECT kcu.table_schema, kcu.table_name, kcu.column_name
|
|
382
|
+
FROM information_schema.table_constraints tc
|
|
383
|
+
JOIN information_schema.key_column_usage kcu
|
|
384
|
+
ON tc.constraint_name = kcu.constraint_name
|
|
385
|
+
AND tc.table_schema = kcu.table_schema
|
|
386
|
+
AND tc.table_name = kcu.table_name
|
|
387
|
+
WHERE tc.constraint_type = 'PRIMARY KEY'
|
|
388
|
+
AND tc.table_schema NOT IN ('pg_catalog', 'information_schema', 'pg_toast')
|
|
389
|
+
ORDER BY kcu.ordinal_position
|
|
390
|
+
`),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,u=n.get(o)??[],p=a.map(f=>i0(f,u));i.push(`CREATE TABLE ${wl(l)}.${wl(c)} (
|
|
391
|
+
${p.join(`,
|
|
392
|
+
`)}
|
|
393
|
+
);`);}return i.join(`
|
|
394
|
+
|
|
395
|
+
`)}function wl(e){return /^[a-z_][a-z0-9_]*$/.test(e)?e:`"${e.replace(/"/g,'""')}"`}function i0(e,t){let r=[wl(e.column_name)];return r.push(o0(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 o0(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 cd=y(()=>{Qt();js();});function ud(e){return !e||e==="main"?"public":e}function Ft(e){return `"${e.replace(/"/g,'""')}"`}function l0(e,t){return Ft(e==="public"?t:`${e}.${t}`)}function bl(e){return `${e.schema}.${e.table}.${e.column}`}function c0(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 u0(e){let t=e.connection.config?.translation?.deparse?.schema;if(t instanceof Map&&t.size>0)return t;let r=await vs(e),n=await ue(e);if(r.trim()){let i=[await ld(r),n].filter(o=>o.trim().length>0).join(`
|
|
396
|
+
`);return i.trim()?(await En(i)).schema:new Map}return n.trim()?(await En(n)).schema:new Map}async function p0(e){let t=await u0(e),r=[];for(let n of t.values())for(let s of n.all())s.isShimBacked&&r.push({schema:ud(s.context.schema),table:s.context.table,column:s.context.column,field:s});return r}function f0(e,t){return e==="fail"||t==="fail"?"fail":e==="warn"||t==="warn"?"warn":"pass"}async function m0(e,t,r){return (await e.connection.introspect()).primary_keys.find(i=>ud(i.schema)===t&&i.table===r)?.columns??[]}async function d0(e,t){if(e.connection.dialect!=="sqlite")return {field:bl(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=l0(t.schema,t.table),s=await m0(e,t.schema,t.table),i=s.length>0?s:["rowid"],a=[...s.length>0?s.map(m=>`${Ft(m)} AS ${Ft(`id_${m}`)}`):[`rowid AS ${Ft("id_rowid")}`],`${Ft(t.column)} AS ${Ft("__lite_value")}`].join(", "),l;try{l=await e.connection.exec(`SELECT ${a} FROM ${n}`);}catch(m){return {field:bl(t),pg_type:Sl(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??[],u="pass",p=0,f=null,h,d=[];for(let m of c){let b=t.field.validateStorage(m.__lite_value);if(u=f0(u,b.status),b.status!=="pass"&&(p++,f??=b.message,h??=b.action,d.length<a0)){let g={};for(let S of i)g[S]=m[`id_${S}`];d.push({id:g,raw_value:m.__lite_value});}}return {field:bl(t),pg_type:Sl(t.field),status:u,rows_checked:c.length,...p>0?{affected_rows:p}:{},message:f,...d.length>0?{samples:d}:{},...h?{action:h}:{}}}function Sl(e){if(e instanceof ut)return `${e.elementField?Sl(e.elementField):e.context.pgTypeName}[]`;if(e instanceof Ot&&e.numericPrecision){let{precision:t,scale:r}=e.numericPrecision;return `${e.context.pgTypeName}(${t},${r})`}return e instanceof ie&&e.lengthConstraint!==void 0?`${e.context.pgTypeName}(${e.lengthConstraint})`:e.context.pgTypeName}async function El(e){let t=await p0(e),r=[];for(let n of t)r.push(await d0(e,n));return {summary:c0(r),results:r}}var a0,pd=y(()=>{Be();At();cd();dl();Os();Ns();je();a0=3;});function fd(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 md=y(()=>{});function h0(e){if(e.length===0)return "";if(e.length===1)return e[0];let t=e[0].match(dd);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(dd);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 hd(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 u=n[c]??1;if(l.length===1||u===1){for(let p of l){try{await e.runSql(p);}catch(f){s.push({statement:p,error:String(f)});}i++,r.onProgress?.(i,o);}return}for(let p=0;p<l.length;p+=u){let f=l.slice(p,p+u),h=h0(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 dd,gd=y(()=>{dd=/^(INSERT INTO [^(]+\([^)]+\)\s*VALUES\s*)(\(.*\))(\s*ON CONFLICT[\s\S]*)?$/i;});async function g0(e,t,r,n){n.onSql?.(t,r);try{await e.runSql(t);}catch(s){throw new Error(`Failed SQL (${r}): ${String(s)}
|
|
397
|
+
${t}`,{cause:s})}}async function ur(e,t,r,n,s={}){if(r.length===0)return;n.onBatchStart?.(t,r.length);let i=await hd(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 xl(e,t,r){let n=await ue(e),s=jt(n);r.onSchemaStart?.(s.length);for(let c=0;c<s.length;c++)r.onSchemaProgress?.(c+1,s.length),await g0(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 ur(t,"Migrating auth.users",i.users,r),await ur(t,"Migrating auth.identities",i.identities,r),r.migrateSessions?(await ur(t,"Migrating auth.sessions",i.sessions,r),await ur(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 gi(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 ur(t,`Migrating ${c.schema}.${c.table}`,c.inserts,r);for(let c of l)await ur(t,`Resetting ${c.schema}.${c.table} sequences`,c.sequenceResets,r,{sizes:[1],unit:"statements"});if(r.syncAuthConfig!==false&&t.updateAuthConfig){let c=fd(e.config);Object.keys(c).length>0&&(r.onAuthConfigStart?.(),await t.updateAuthConfig(c),r.onAuthConfigEnd?.());}return {schemaStatements:s.length,auth:o,dataTables:a}}var yd=y(()=>{Be();md();ml();gl();gd();ii();});function vn(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}function wd(e,t=new Map){if(!e||typeof e!="object")return t;for(let[r,n]of Object.entries(e))typeof n=="string"?t.set(vn(r),n):n&&typeof n=="object"&&wd(n,t);return t}function _n(e,t,r){for(let n of t){let s=e.get(vn(n));if(s)return s}throw new Error(`Supabase status JSON is missing ${r}`)}function E0(e){let t=JSON.parse(e),r=wd(t);return {apiUrl:_n(r,["API_URL","api_url","API URL","Project URL"],"API URL"),studioUrl:r.get(vn("Studio URL"))??r.get(vn("STUDIO_URL"))??r.get(vn("studio_url")),dbUrl:_n(r,["DB_URL","db_url","DB URL"],"DB URL"),anonKey:_n(r,["ANON_KEY","anon_key","anon key","Publishable"],"anon key"),serviceRoleKey:_n(r,["SERVICE_ROLE_KEY","service_role_key","service role key","Secret"],"service role key"),jwtSecret:_n(r,["JWT_SECRET","jwt_secret","JWT secret"],"JWT secret")}}function bd(e){try{return decodeURIComponent(new URL(e).password)}catch{return ""}}function Sd(e=process.cwd()){return e}async function x0(){return await new Promise((e,t)=>{let r=y0.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 _0(){let e=new Set,t=async()=>{for(;;){let r=await x0();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 $n(e,t={}){let r=process.env.LITE_SUPABASE_CLI?.split(/\s+/).filter(Boolean)??b0,{spawn:n}=await import('bun'),s=n([...r,...e],{cwd:t.cwd,stdout:"pipe",stderr:"pipe",env:{...process.env,SUPABASE_TELEMETRY_DISABLED:"1",DO_NOT_TRACK:"1"}}),i=setTimeout(()=>s.kill(),t.timeoutMs??12e4),[o,a,l]=await Promise.all([new Response(s.stdout).text(),new Response(s.stderr).text(),s.exited]).finally(()=>clearTimeout(i));if(l!==0)throw new Error([`supabase ${e.join(" ")} failed with exit code ${l}`,o,a].filter(Boolean).join(`
|
|
398
|
+
`));return {stdout:o,stderr:a}}function ne(e,t,r,n){let s=new RegExp(`(\\[${t.replace(".","\\.")}\\][\\s\\S]*?)(?=\\n\\[|$)`),i=e.match(s);if(!i)return `${e.trimEnd()}
|
|
372
399
|
|
|
373
400
|
[${t}]
|
|
374
401
|
${r} = ${n}
|
|
375
402
|
`;let o=i[1],a=new RegExp(`(^${r}\\s*=\\s*).*$`,"m"),l=a.test(o)?o.replace(a,`$1${n}`):`${o.trimEnd()}
|
|
376
403
|
${r} = ${n}
|
|
377
|
-
`;return e.replace(o,l)}function F0(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 M0(e){return F0(e,"db",["driver","url"])}async function U0(e){return await fe__default.access(e).then(()=>true).catch(()=>false)}async function B0(e){let t=z__default.join(e,"supabase","config.toml");await U0(t)||(await fe__default.mkdir(e,{recursive:true}),await Cn(["init","--workdir",e,"--yes"],{timeoutMs:6e4}));}async function q0(e,t,r){let n=z__default.join(e,"supabase","config.toml"),s=M0(await fe__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 fe__default.writeFile(n,s,"utf-8");}function nh(e){return JSON.stringify(e)}function H0(e){return `[${e.map(nh).join(", ")}]`}async function W0(e,t){if(!t)return;let r=z__default.join(e,"supabase","config.toml"),n=await fe__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",H0(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 fe__default.writeFile(r,n,"utf-8");}var O0,I0,Ci,sh=y(()=>{jr();O0=["bunx","supabase@2.98.1"],I0=["mailpit","realtime","storage-api","imgproxy","edge-runtime","logflare","vector","supavisor"];Ci=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 fe__default.mkdtemp(z__default.join(Vw.tmpdir(),"lite-local-supa-")),n=t.projectId??`lite-local-${Date.now().toString(36)}`,s=t.cleanupOnStop??!t.workdir,i=await j0();try{await B0(r),await q0(r,n,i),await W0(r,t.sourceConfig),await Cn(["start","--workdir",r,"--yes","--exclude",I0.join(",")],{timeoutMs:5*6e4});let{stdout:o}=await Cn(["status","--workdir",r,"-o","json"],{timeoutMs:6e4});return new e(r,n,L0(o),s)}catch(o){throw await Cn(["stop","--workdir",r,"--no-backup"],{timeoutMs:12e4}).catch(()=>{}),s&&await fe__default.rm(r,{recursive:true,force:true}).catch(()=>{}),o}}async runSql(t){let{createPostgresConnection:r}=await Ye("@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 Cn(["stop","--workdir",this.workdir,"--no-backup"],{timeoutMs:12e4}).catch(()=>{}),this.cleanupOnStop&&await fe__default.rm(this.workdir,{recursive:true,force:true}));}};});async function Pi(){let e=await vn({message:"Email",placeholder:"Enter your email",validate:t=>{try{au(t,{domains:["supabase.io"],panic:!0});return}catch(r){return r}}});return Se(e)&&process.exit(1),e}async function ki(e=false){let t=await _n({message:"Password",validate:r=>{try{lu(r,{panic:!0});return}catch(n){return n}}});if(Se(t)&&process.exit(1),e){let r=await _n({message:"Confirm Password",validate:n=>{try{if(n!==t)throw new Error("Passwords do not match");return}catch(s){return s}}});Se(r)&&process.exit(1);}return t}async function ih(){let e=await vn({message:"Project Name",placeholder:"Enter your project name"});return Se(e)&&process.exit(1),e}async function Ni(e){let t=await En({message:e,initialValue:true});return Se(t)&&process.exit(1),t}var mr=y(()=>{Ze();Cr();});async function V0(){return dr||(dr=await import('@sentry/node')),dr}function K0(){if(ah)return;ah=true;let e=process.exit.bind(process),t=false;process.exit=(r=>{if(t)return;t=true,Oi((r??0)!==0).finally(()=>e(r));});}function uh(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 Y0(){let e=process.versions;return e.bun?"bun":e.deno?"deno":"node"}function J0(){if(process.env.CODESPACES)return "codespaces";if(process.env.REMOTE_CONTAINERS)return "devcontainer";try{return statSync("/.dockerenv"),"docker"}catch{return}}function X0(e){let t=e/1e6;return t<1?"<1MB":t<10?"1-10MB":t<100?"10-100MB":t<1e3?"100MB-1GB":">1GB"}function Q0(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 Z0(){try{let e=z__default.resolve(process.cwd(),$e.config_dir,"config.toml"),t;try{t=readFileSync(e,"utf-8");}catch{return {}}let r;try{r=_t(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??$e.default_db_url,o=Q0(s,i),a;if(o==="file"&&i.startsWith("file:"))try{let l=i.startsWith("file://")?i.slice(7):i.slice(5),c=z__default.resolve(process.cwd(),l);a=statSync(c).size;}catch{}return {driver:s,location:o,sizeBytes:a}}catch{return {}}}async function ph(e){if(Pn)return;Pn=true;let t=await V0(),{version:r}=await Gn();t.init({dsn:G0,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",Y0()),t.setTag("node",process.version),t.setTag("platform",process.platform),t.setTag("arch",process.arch),t.setTag("ci",!!process.env.CI);let n=J0();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=Z0();s.driver&&t.setTag("db.driver",s.driver),s.location&&t.setTag("db.location",s.location),typeof s.sizeBytes=="number"&&t.setTag("db.size",X0(s.sizeBytes));for(let[i,o]of Object.entries(e.args))t.setTag(`arg.${i}`,!!o);t.startSession(),ch=true,qt=t.startInactiveSpan({name:`cli:${e.command}`,op:"cli.command",forceTransaction:true}),K0();}async function Oi(e,t){if(!Pn)return;let r=dr;try{if(e&&(r.setTag("status","failed"),t instanceof Error&&r.setTag("error_class",t.constructor.name)),qt&&(qt.setStatus({code:e?2:1,message:e?"internal_error":"ok"}),qt.end(),qt=void 0),ch){let n=r.getCurrentScope().getSession();n&&e&&(n.status="crashed"),r.endSession();}}finally{await r.flush(2e3).catch(()=>{});}}function kn(e,t){if(!Pn)return Promise.resolve(t());let r=dr,n=()=>r.startSpan({name:e,op:"cli.step"},t);return qt?r.withActiveSpan(qt,n):n()}function zl(e,t){Pn&&dr.setTag(e,t);}var G0,dr,Pn,ch,qt,ah,Gl=y(()=>{_r();Vt();Ee();G0="https://9562525a4ea320539ea7e94859533a17@o398706.ingest.us.sentry.io/4511381939290112";Pn=false,ch=false,ah=false;});var hh={};de(hh,{isNonInteractive:()=>Vl,resolveSessionMigration:()=>dh,resolveTarget:()=>mh,upgrade:()=>cv});async function rv(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 xn({message:"Select organization",options:r.map(s=>({value:s.id,label:`${s.name} (${s.slug})`}))});return Se(n)&&process.exit(1),r.find(s=>s.id===n)}async function sv(e,t,r){if(r)return r;let n=nv;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 xn({message:"Select region",options:n.map(i=>({value:i.key,label:i.label}))});return Se(s)&&process.exit(1),s}async function iv(e){if(e)return e;let t=await vn({message:"Project name",placeholder:"my-project",validate:r=>r&&r.trim().length>0?void 0:"Name is required"});return Se(t)&&process.exit(1),t}function ov(){return ev.randomBytes(24).toString("base64url")}function mh(e){let t=e??"hosted";if(t==="hosted"||t==="local")return t;throw new Error(`Unknown upgrade target '${t}'. Use 'hosted' or 'local'.`)}function Vl(){return process.env.CI==="true"||process.env.LITE_NON_INTERACTIVE==="1"||!process.stdin.isTTY}async function av(e){if(typeof e=="boolean")return e;if(Vl())return false;let t=await En({message:"Migrate existing sessions (transfers JWT secret, sessions, refresh tokens)?",initialValue:false});return Se(t)&&process.exit(1),t}async function lv(e){if(e)return e;let t=process.env.SUPABASE_ACCESS_TOKEN;if(t)return t;J.info("Create a personal access token at https://supabase.com/dashboard/account/tokens");let r=await _n({message:"Supabase access token",validate:n=>n&&n.trim().length>0?void 0:"Token is required"});return Se(r)&&process.exit(1),r}async function dh(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=Hd(e.jwtSecret);if(t.strong||e.allowWeakJwtSecret)return {migrateSessions:true,jwtSecret:e.jwtSecret,weakReasons:t.reasons};if(Vl())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(`
|
|
404
|
+
`;return e.replace(o,l)}function $0(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 v0(e){return $0(e,"db",["driver","url"])}async function T0(e){return await ce__default.access(e).then(()=>true).catch(()=>false)}async function A0(e){let t=He__default.join(e,"supabase","config.toml");await T0(t)||(await ce__default.mkdir(e,{recursive:true}),await $n(["init","--workdir",e,"--yes"],{timeoutMs:6e4}));}async function C0(e,t,r){let n=He__default.join(e,"supabase","config.toml"),s=v0(await ce__default.readFile(n,"utf-8"));s=s.replace(/^project_id\s*=.*$/m,`project_id = "${t}"`),s=ne(s,"api","port",String(r.api)),s=ne(s,"db","port",String(r.db)),s=ne(s,"db","shadow_port",String(r.shadow)),s=ne(s,"db","major_version","15"),s=ne(s,"db.seed","enabled","false"),s=ne(s,"studio","enabled","true"),s=ne(s,"studio","port",String(r.studio)),s=ne(s,"inbucket","enabled","false"),s=ne(s,"inbucket","port",String(r.inbucket)),s=ne(s,"realtime","enabled","false"),s=ne(s,"storage","enabled","false"),s=ne(s,"edge_runtime","enabled","false"),s=ne(s,"edge_runtime","inspector_port",String(r.edgeInspector)),s=ne(s,"analytics","enabled","false"),s=ne(s,"analytics","port",String(r.analytics)),s=ne(s,"db.pooler","enabled","false"),s=ne(s,"db.pooler","port",String(r.pooler)),await ce__default.writeFile(n,s,"utf-8");}function Ed(e){return JSON.stringify(e)}function R0(e){return `[${e.map(Ed).join(", ")}]`}async function k0(e,t){if(!t)return;let r=He__default.join(e,"supabase","config.toml"),n=await ce__default.readFile(r,"utf-8"),s=t.auth??{},i=s.email??{},o=t.api??{};typeof o.max_rows=="number"&&(n=ne(n,"api","max_rows",String(o.max_rows))),typeof s.site_url=="string"&&(n=ne(n,"auth","site_url",Ed(s.site_url))),Array.isArray(s.additional_redirect_urls)&&(n=ne(n,"auth","additional_redirect_urls",R0(s.additional_redirect_urls))),typeof s.jwt_expiry=="number"&&(n=ne(n,"auth","jwt_expiry",String(s.jwt_expiry))),typeof s.enable_signup=="boolean"&&(n=ne(n,"auth","enable_signup",String(s.enable_signup))),typeof s.enable_anonymous_sign_ins=="boolean"&&(n=ne(n,"auth","enable_anonymous_sign_ins",String(s.enable_anonymous_sign_ins))),typeof s.minimum_password_length=="number"&&(n=ne(n,"auth","minimum_password_length",String(s.minimum_password_length))),typeof i.enable_confirmations=="boolean"&&(n=ne(n,"auth.email","enable_confirmations",String(i.enable_confirmations))),await ce__default.writeFile(r,n,"utf-8");}var b0,S0,yi,xd=y(()=>{Qt();b0=["bunx","supabase@2.98.1"],S0=["mailpit","realtime","storage-api","imgproxy","edge-runtime","logflare","vector","supavisor"];yi=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 ce__default.mkdtemp(He__default.join(pw.tmpdir(),"lite-local-supa-")),n=t.projectId??`lite-local-${Date.now().toString(36)}`,s=t.cleanupOnStop??!t.workdir,i=await _0();try{await A0(r),await C0(r,n,i),await k0(r,t.sourceConfig),await $n(["start","--workdir",r,"--yes","--exclude",S0.join(",")],{timeoutMs:5*6e4});let{stdout:o}=await $n(["status","--workdir",r,"-o","json"],{timeoutMs:6e4});return new e(r,n,E0(o),s)}catch(o){throw await $n(["stop","--workdir",r,"--no-backup"],{timeoutMs:12e4}).catch(()=>{}),s&&await ce__default.rm(r,{recursive:true,force:true}).catch(()=>{}),o}}async runSql(t){let{createPostgresConnection:r}=await Ue("@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 $n(["stop","--workdir",this.workdir,"--no-backup"],{timeoutMs:12e4}).catch(()=>{}),this.cleanupOnStop&&await ce__default.rm(this.workdir,{recursive:true,force:true}));}};});async function bi(){let e=await Sn({message:"Email",placeholder:"Enter your email",validate:t=>{try{Mc(t,{domains:["supabase.io"],panic:!0});return}catch(r){return r}}});return ye(e)&&process.exit(1),e}async function Si(e=false){let t=await wn({message:"Password",validate:r=>{try{Uc(r,{panic:!0});return}catch(n){return n}}});if(ye(t)&&process.exit(1),e){let r=await wn({message:"Confirm Password",validate:n=>{try{if(n!==t)throw new Error("Passwords do not match");return}catch(s){return s}}});ye(r)&&process.exit(1);}return t}async function _d(){let e=await Sn({message:"Project Name",placeholder:"Enter your project name"});return ye(e)&&process.exit(1),e}async function Ei(e){let t=await yn({message:e,initialValue:true});return ye(t)&&process.exit(1),t}var pr=y(()=>{Je();Tr();});async function O0(){return fr||(fr=await import('@sentry/node')),fr}function L0(){if(vd)return;vd=true;let e=process.exit.bind(process),t=false;process.exit=(r=>{if(t)return;t=true,xi((r??0)!==0).finally(()=>e(r));});}function Cd(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 I0(){let e=process.versions;return e.bun?"bun":e.deno?"deno":"node"}function D0(){if(process.env.CODESPACES)return "codespaces";if(process.env.REMOTE_CONTAINERS)return "devcontainer";try{return statSync("/.dockerenv"),"docker"}catch{return}}function j0(e){let t=e/1e6;return t<1?"<1MB":t<10?"1-10MB":t<100?"10-100MB":t<1e3?"100MB-1GB":">1GB"}function F0(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 M0(){try{let e=He__default.resolve(process.cwd(),_e.config_dir,"config.toml"),t;try{t=readFileSync(e,"utf-8");}catch{return {}}let r;try{r=St(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??_e.default_db_url,o=F0(s,i),a;if(o==="file"&&i.startsWith("file:"))try{let l=i.startsWith("file://")?i.slice(7):i.slice(5),c=He__default.resolve(process.cwd(),l);a=statSync(c).size;}catch{}return {driver:s,location:o,sizeBytes:a}}catch{return {}}}async function Rd(e){if(Tn)return;Tn=true;let t=await O0(),{version:r}=await qn();t.init({dsn:N0,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",I0()),t.setTag("node",process.version),t.setTag("platform",process.platform),t.setTag("arch",process.arch),t.setTag("ci",!!process.env.CI);let n=D0();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=M0();s.driver&&t.setTag("db.driver",s.driver),s.location&&t.setTag("db.location",s.location),typeof s.sizeBytes=="number"&&t.setTag("db.size",j0(s.sizeBytes));for(let[i,o]of Object.entries(e.args))t.setTag(`arg.${i}`,!!o);t.startSession(),Ad=true,Mt=t.startInactiveSpan({name:`cli:${e.command}`,op:"cli.command",forceTransaction:true}),L0();}async function xi(e,t){if(!Tn)return;let r=fr;try{if(e&&(r.setTag("status","failed"),t instanceof Error&&r.setTag("error_class",t.constructor.name)),Mt&&(Mt.setStatus({code:e?2:1,message:e?"internal_error":"ok"}),Mt.end(),Mt=void 0),Ad){let n=r.getCurrentScope().getSession();n&&e&&(n.status="crashed"),r.endSession();}}finally{await r.flush(2e3).catch(()=>{});}}function An(e,t){if(!Tn)return Promise.resolve(t());let r=fr,n=()=>r.startSpan({name:e,op:"cli.step"},t);return Mt?r.withActiveSpan(Mt,n):n()}function _l(e,t){Tn&&fr.setTag(e,t);}var N0,fr,Tn,Ad,Mt,vd,$l=y(()=>{Sr();Wt();we();N0="https://9562525a4ea320539ea7e94859533a17@o398706.ingest.us.sentry.io/4511381939290112";Tn=false,Ad=false,vd=false;});var Od={};fe(Od,{isNonInteractive:()=>vl,resolveSessionMigration:()=>Nd,resolveTarget:()=>Pd,upgrade:()=>J0});async function q0(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 bn({message:"Select organization",options:r.map(s=>({value:s.id,label:`${s.name} (${s.slug})`}))});return ye(n)&&process.exit(1),r.find(s=>s.id===n)}async function W0(e,t,r){if(r)return r;let n=H0;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 bn({message:"Select region",options:n.map(i=>({value:i.key,label:i.label}))});return ye(s)&&process.exit(1),s}async function G0(e){if(e)return e;let t=await Sn({message:"Project name",placeholder:"my-project",validate:r=>r&&r.trim().length>0?void 0:"Name is required"});return ye(t)&&process.exit(1),t}function z0(){return U0.randomBytes(24).toString("base64url")}function Pd(e){let t=e??"hosted";if(t==="hosted"||t==="local")return t;throw new Error(`Unknown upgrade target '${t}'. Use 'hosted' or 'local'.`)}function vl(){return process.env.CI==="true"||process.env.LITE_NON_INTERACTIVE==="1"||!process.stdin.isTTY}async function V0(e){if(typeof e=="boolean")return e;if(vl())return false;let t=await yn({message:"Migrate existing sessions (transfers JWT secret, sessions, refresh tokens)?",initialValue:false});return ye(t)&&process.exit(1),t}async function K0(e){if(e)return e;let t=process.env.SUPABASE_ACCESS_TOKEN;if(t)return t;J.info("Create a personal access token at https://supabase.com/dashboard/account/tokens");let r=await wn({message:"Supabase access token",validate:n=>n&&n.trim().length>0?void 0:"Token is required"});return ye(r)&&process.exit(1),r}async function Nd(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=id(e.jwtSecret);if(t.strong||e.allowWeakJwtSecret)return {migrateSessions:true,jwtSecret:e.jwtSecret,weakReasons:t.reasons};if(vl())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(`
|
|
378
405
|
`));J.warning(["auth.jwt_secret looks weak and will become a trusted Supabase signing key:",...t.reasons.map(n=>`- ${n}`)].join(`
|
|
379
|
-
`));let r=await
|
|
380
|
-
Rehearsing upgrade against in-memory pglite...`));let w=await
|
|
381
|
-
${U}`));},onSchemaStart:U=>
|
|
382
|
-
${w}`));},onSchemaStart:w=>S.start(`Applying schema (0/${w})`),onSchemaProgress:(w,
|
|
383
|
-
`)){if(/^\s*#/.test(t))continue;let r=/^\s*root\s*=\s*(?<mountPoint>"[^"]*"|'[^']*'|[^#]*)/.exec(t);if(r)return r.groups.mountPoint.trim().replaceAll(/^["']|["']$/g,"")}}var
|
|
384
|
-
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}var
|
|
385
|
-
`),o&&await
|
|
406
|
+
`));let r=await yn({message:"Preserve existing sessions anyway by importing this JWT secret?",initialValue:false});return ye(r)&&process.exit(1),r?{migrateSessions:true,jwtSecret:e.jwtSecret,weakReasons:t.reasons}:{migrateSessions:false,weakReasons:t.reasons}}var Ee,H0,J0,Ld=y(()=>{Ee=ee(se());Je();Oe();Te();km();Fm();Zm();nd();ad();pd();yd();xd();pr();$l();we();H0=[{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)"}];J0=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 Z(async()=>{await Y(t.config);let s=Pd(t.target);if(_l("upgrade.target",s),_l("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 V({withSupabaseClient:!1})).project.local.createApp(t.config);}finally{r&&(console.log=n);}if(r){let w=await El(i);n(JSON.stringify(w,null,2)),w.summary.upgrade_safe||process.exit(1);return}console.log(Ee.default.dim("Running readiness checks..."));let o=await An("readiness",()=>jm(i));if(ed(o),!o.ok)throw new Error("Readiness checks failed. See errors above.");let a=async()=>{console.log(Ee.default.dim(`
|
|
407
|
+
Rehearsing upgrade against in-memory pglite...`));let w=await An("rehearsal",()=>Qm(i));return td(w),w.ok};if(t.dryRun){let w=await El(i);rd(w),w.summary.upgrade_safe||process.exit(1),await a()||process.exit(1);return}if(!t.force&&!await Ei("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 w=He__default.resolve(t.localDir??Sd()),I=cl();I.start(`Starting local Supabase in ${w}`);let T=await yi.start({workdir:w,cleanupOnStop:!1,sourceConfig:i.config});I.stop(`Local Supabase is running at ${T.status.apiUrl}`);let q=await An("apply",()=>xl(i,T,{migrateSessions:!1,authTarget:"supabase",syncAuthConfig:!1,onSql:(U,j)=>{t.verbose&&console.log(Ee.default.dim(`-- ${j}
|
|
408
|
+
${U}`));},onSchemaStart:U=>I.start(`Applying schema (0/${U})`),onSchemaProgress:(U,j)=>I.message(`Applying schema (${U}/${j})`),onSchemaEnd:U=>I.stop(`Schema applied (${U} statements)`),onBatchStart:(U,j)=>I.start(`${U} (0/${j})`),onBatchProgress:(U,j,z)=>I.message(`${U} (${j}/${z})`),onBatchEnd:(U,j,z)=>I.stop(`${U} (${j} ${z})`),onBatchFailure:(U,j)=>{I.stop(Ee.default.red(`${U}: ${j.length} failed`));for(let z of j)console.log(Ee.default.red(` \u2717 ${z.error}`)),t.verbose&&console.log(Ee.default.dim(` ${z.statement}`));},onSkip:U=>console.log(Ee.default.dim(U))})),E=["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."];i.config.storage?.enabled&&E.push("Storage migration is not yet supported."),i.config.realtime?.enabled&&E.push("Realtime config migration is not yet supported.");let x=bd(T.status.dbUrl);if(t.dumpCredentials){let U=JSON.stringify({target:"local",workdir:T.workdir,projectUrl:T.status.apiUrl,apiUrl:T.status.apiUrl,studioUrl:T.status.studioUrl,dbUrl:T.status.dbUrl,anonKey:T.status.anonKey,serviceRoleKey:T.status.serviceRoleKey,dbPassword:x},null,2);await ce__default.writeFile(t.dumpCredentials,U,"utf-8"),console.log(Ee.default.dim(`Credentials written to ${t.dumpCredentials}`));}yl({projectRef:T.projectId,projectUrl:T.status.apiUrl,apiUrl:T.status.apiUrl,studioUrl:T.status.studioUrl,anonKey:T.status.anonKey,serviceRoleKey:T.status.serviceRoleKey,dbPassword:x,auth:q.auth,jwtMigrated:!1,warnings:[`Local Supabase workdir: ${T.workdir}`,...E]});return}let c=await K0(t.supabaseToken),u=new si(c);try{await u.listOrganizations();}catch(w){throw new Error(`Supabase access token rejected: ${String(w)}`)}let p=await q0(u,t.orgId),f=await W0(u,p.slug,t.region),h=await G0(t.projectName),d=await V0(t.migrateSessions),m=await Nd({requested:d,jwtSecret:i.config.auth?.jwt_secret,allowWeakJwtSecret:t.allowWeakJwtSecret}),b=m.migrateSessions,g=z0(),S=cl();S.start("Creating Supabase project");let A=await u.createProject({organization_id:p.id,name:h,db_pass:g,region:f}),$=A.ref??A.id;if(S.stop(`Project created: ${$}`),S.start("Waiting for project to become active"),await u.waitForActive($,{onTick:w=>S.message(`Project status: ${w}`)}),S.stop("Project is active"),b){S.start("Importing JWT signing key");try{await u.createSigningKey($,{algorithm:"HS256",status:"in_use",private_jwk:od(m.jwtSecret)});}catch(w){throw S.stop(Ee.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(w)}`].join(" "))}S.stop("JWT signing key imported");}let N=(await An("apply",()=>xl(i,{runSql:w=>u.runSql($,w),updateAuthConfig:w=>u.updateAuthConfig($,w)},{migrateSessions:b,authTarget:"supabase",onSql:(w,I)=>{t.verbose&&console.log(Ee.default.dim(`-- ${I}
|
|
409
|
+
${w}`));},onSchemaStart:w=>S.start(`Applying schema (0/${w})`),onSchemaProgress:(w,I)=>S.message(`Applying schema (${w}/${I})`),onSchemaEnd:w=>S.stop(`Schema applied (${w} statements)`),onBatchStart:(w,I)=>{S.start(`${w} (0/${I})`);},onBatchProgress:(w,I,T)=>S.message(`${w} (${I}/${T})`),onBatchEnd:(w,I,T)=>S.stop(`${w} (${I} ${T})`),onBatchFailure:(w,I)=>{S.stop(Ee.default.red(`${w}: ${I.length} failed`));for(let T of I)console.log(Ee.default.red(` \u2717 ${T.error}`)),t.verbose&&console.log(Ee.default.dim(` ${T.statement}`));},onAuthConfigStart:()=>S.start("Syncing auth config"),onAuthConfigEnd:()=>S.stop("Auth config synced"),onSkip:w=>console.log(Ee.default.dim(w))}))).auth,v=Rm(await u.getApiKeys($)),_=`https://${$}.${u.projectDomain}`,L=[];if(b?m.weakReasons.length>0?L.push(`A weak JWT secret was imported to preserve sessions: ${m.weakReasons.join("; ")}.`):L.push("Sessions preserved by importing auth.jwt_secret as a Supabase signing key."):L.push("Sessions and JWT secret not migrated. Existing tokens are invalid \u2014 users must re-authenticate."),i.config.storage?.enabled&&L.push("Storage migration is not yet supported."),i.config.realtime?.enabled&&L.push("Realtime config migration is not yet supported."),t.dumpCredentials){let w=JSON.stringify({ref:$,projectUrl:_,anonKey:v.anon,serviceRoleKey:v.service_role,dbPassword:g},null,2);await ce__default.writeFile(t.dumpCredentials,w,"utf-8"),console.log(Ee.default.dim(`Credentials written to ${t.dumpCredentials}`));}yl({projectRef:$,projectUrl:_,apiUrl:_,anonKey:v.anon,serviceRoleKey:v.service_role,dbPassword:g,auth:N,jwtMigrated:!!(b&&m.jwtSecret),warnings:L});});});});var Id={};fe(Id,{login:()=>X0});var Tl,X0,Dd=y(()=>{Tl=ee(se());Je();pr();Oe();Te();X0=e=>{e.command("login").description("Login").option("--json","Output in JSON format").helpGroup("Local Development:").action(async t=>{await Z(async()=>{let r=await V();J.message(Tl.default.dim("Enter your credentials to login to the cloud"));let n=await bi(),s=await Si(),{data:i,error:o}=await r.client.auth.signInWithPassword({email:n,password:s});o&&(J.error(o.message),process.exit(1)),t.json?console.log(JSON.stringify(i,null,2)):J.success(`Authenticated as: ${Tl.default.cyan(i.user.email)}`);});});};});var Fd={};fe(Fd,{logout:()=>Y0});var jd,Y0,Md=y(()=>{jd=ee(se());Te();Je();Oe();Y0=e=>{e.command("logout").description("Logout").helpGroup("Local Development:").action(async()=>{console.log(),await Z(async()=>{let t=await V(),{error:r}=await t.client.auth.signOut();r&&(J.error(r.message),process.exit(1)),console.log(jd.default.green("Logged out successfully"));});});};});var Ud={};fe(Ud,{signup:()=>Q0});var Al,Q0,Bd=y(()=>{Al=ee(se());Je();pr();Oe();Te();Ke();Q0=e=>{e.command("signup").description(de("Register a supalite cloud account")).option("--json","Output in JSON format").helpGroup("Local Development:").action(async t=>{J.message(Al.default.dim("Enter your credentials to sign up to the cloud")),await Z(async()=>{let r=await V(),n=await bi(),s=await Si(!0),{data:i,error:o}=await r.client.auth.signUp({email:n,password:s});o&&(J.error(o.message),process.exit(1)),t.json?console.log(JSON.stringify(i,null,2)):J.success(`Signed up as: ${Al.default.cyan(i.user.email)}`);});});};});var qd={};fe(qd,{whoami:()=>Z0});var Cl,Z0,Hd=y(()=>{Cl=ee(se());Te();Je();Oe();Ke();Z0=e=>{e.command("whoami").description(de("Show the current authenticated user")).option("--json","Output in JSON format").helpGroup("Local Development:").action(async t=>{console.log(),await Z(async()=>{let r=await V(),{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: ${Cl.default.cyan(n.user.email)}`),process.exit(0)):(console.log(Cl.default.yellow("Not authenticated")),process.exit(1)),s&&(J.error(s.message),process.exit(1));});});};});var Gd={};fe(Gd,{link:()=>e_});var Wd,e_,zd=y(()=>{Oe();Te();we();Je();Wd=ee(se()),e_=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 Z(async()=>{await Y();let r=await V();r.project.local.ref()&&J.warning("Project is already linked.");let n=t.projectRef;if(!n){let i=await r.project.remote.list();n=await bn({message:"Select a project:",options:i.map(o=>({value:o.id,hint:`name: ${o.name}, created: ${o.created_at}`}))}),ye(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 ${Wd.default.cyan(s.id)}.`);});});});var Vd={};fe(Vd,{unlink:()=>t_});var t_,Kd=y(()=>{Oe();Te();we();t_=e=>e.command("unlink").description("Unlink from a Supalite project").option("--json","Output in JSON format").helpGroup("Local Development:").action(async()=>{console.log(),await Z(async()=>{await Y(),(await V()).project.local.unlink(),console.log("Finished unlinking project.");});});});var Xd={};fe(Xd,{status:()=>r_});var Jd,r_,Yd=y(()=>{Te();Oe();we();Jd=ee(se());Ke();r_=e=>e.command("status").description(de("Show information about the linked project")).helpGroup("Local Development:").action(async()=>{console.log(),await Z(async()=>{await Y();let t=await V(),r=await t.project.remote.get();console.log(r),console.log(`Project URL: ${Jd.default.cyan(t.project.remote.url(r.id))}`);});});});var Zd={};fe(Zd,{projects:()=>n_});var Rl,n_,s_,i_,eh=y(()=>{pr();Je();Rl=ee(se());Oe();Te();Oe();n_=e=>{e.command("projects").description("Manage Supalite cloud projects").helpGroup("Management APIs:").addCommand(i_).addCommand(s_);},s_=new Command$1().name("list").description("List projects").helpGroup("Projects:").action(async()=>{await Z(async()=>{let t=await(await V()).project.remote.list();(!Array.isArray(t)||t.length===0)&&(J.info("No projects found"),process.exit(0)),console.log(ym(t,{omitKeys:["config","user_id"],renderHeader:r=>String(r).split("_").map(n=>n.toUpperCase()).join(" ")}));});}),i_=new Command$1().name("create").description("Create a project").option("--name <name>","The name of the project").helpGroup("Projects:").action(async e=>{await Z(async()=>{let t=await V(),r=e.name??await _d(),n=await t.project.remote.create({name:r});J.success(`Project ${Rl.default.cyan(n.name)} created: ${Rl.default.cyan(n.id)}`);});});});function o_(){try{return In.statSync("/.dockerenv"),!0}catch{return false}}function a_(){try{return In.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return false}}function Pl(){return kl===void 0&&(kl=o_()||a_()),kl}var kl,rh=y(()=>{});function Ut(){return Nl===void 0&&(Nl=c_()||Pl()),Nl}var Nl,c_,Ol=y(()=>{rh();c_=()=>{try{return In.statSync("/run/.containerenv"),!0}catch{return false}};});var nh,nt,Il=y(()=>{Ol();nh=()=>{if(qe.platform!=="linux")return false;if(pw.release().toLowerCase().includes("microsoft"))return !Ut();try{if(In.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return !Ut()}catch{}return In.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||In.existsSync("/run/WSL")?!Ut():false},nt=qe.env.__IS_WSL_TEST__?nh:nh();});var d_,Dl,Le,jl=y(()=>{d_=promisify(m_.execFile),Dl=()=>`${qe.env.SYSTEMROOT||qe.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`,Le=async(e,t={})=>{let{powerShellPath:r,...n}=t,s=Le.encodeCommand(e);return d_(r??Dl(),[...Le.argumentsPrefix,s],{encoding:"utf8",...n})};Le.argumentsPrefix=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"];Le.encodeCommand=e=>Buffer$1.from(e,"utf16le").toString("base64");Le.escapeArgument=e=>`'${String(e).replaceAll("'","''")}'`;});function oh(e){for(let t of e.split(`
|
|
410
|
+
`)){if(/^\s*#/.test(t))continue;let r=/^\s*root\s*=\s*(?<mountPoint>"[^"]*"|'[^']*'|[^#]*)/.exec(t);if(r)return r.groups.mountPoint.trim().replaceAll(/^["']|["']$/g,"")}}var ah=y(()=>{});var y_,w_,b_,_i,lh,uh,ph,fh,mh=y(()=>{Il();jl();ah();Il();y_=promisify(m_.execFile),w_=(()=>{let e="/mnt/",t;return async function(){if(t)return t;let r="/etc/wsl.conf",n=false;try{await ce__default.access(r,constants.F_OK),n=!0;}catch{}if(!n)return e;let s=await ce__default.readFile(r,{encoding:"utf8"}),i=oh(s);return i===void 0?e:(t=i,t=t.endsWith("/")?t:`${t}/`,t)}})(),b_=async()=>`${await w_()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,_i=nt?b_:Dl,uh=async()=>(lh??=(async()=>{try{let e=await _i();return await ce__default.access(e,constants.X_OK),!0}catch{return false}})(),lh),ph=async()=>{let e=await _i(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,{stdout:r}=await Le(t,{powerShellPath:e});return r.trim()},fh=async e=>{if(/^[a-z]+:\/\//i.test(e))return e;try{let{stdout:t}=await y_("wslpath",["-aw",e],{encoding:"utf8"});return t.trim()}catch{return e}};});function Bt(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 dh=y(()=>{});async function Ml(){if(qe.platform!=="darwin")throw new Error("macOS only");let{stdout:e}=await __("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 __,hh=y(()=>{__=promisify(execFile);});async function gh(e,{humanReadableOutput:t=true,signal:r}={}){if(qe.platform!=="darwin")throw new Error("macOS only");let n=t?[]:["-ss"],s={};r&&(s.signal=r);let{stdout:i}=await A_("osascript",["-e",e,n],s);return i.trim()}var A_,yh=y(()=>{A_=promisify(execFile);});async function Ul(e){return gh(`tell application "Finder" to set app_path to application file id "${e}" as string
|
|
411
|
+
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}var wh=y(()=>{yh();});async function Hl(e=k_){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 Bl(`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 $i[n]??$i[o]??$i[a]??{name:n,id:n}}var k_,$i,ql,Bl,Wl=y(()=>{k_=promisify(execFile),$i={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"}},ql=new Map(Object.entries($i)),Bl=class extends Error{};});async function zl(){if(qe.platform==="darwin"){let e=await Ml();return {name:await Ul(e),id:e}}if(qe.platform==="linux"){let{stdout:e}=await O_("xdg-mime",["query","default","x-scheme-handler/http"]),t=e.trim();return {name:L_(t.replace(/.desktop$/,"").replace("-"," ")),id:t}}if(qe.platform==="win32")return Hl();throw new Error("Only macOS, Linux, and Windows are supported")}var O_,L_,bh=y(()=>{hh();wh();Wl();Wl();O_=promisify(execFile),L_=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,t=>t.toUpperCase());});var I_,Sh,Eh=y(()=>{I_=!!(qe.env.SSH_CONNECTION||qe.env.SSH_CLIENT||qe.env.SSH_TTY),Sh=I_;});function vh(e){if(typeof e=="string"||Array.isArray(e))return e;let{[_h]:t}=e;if(!t)throw new Error(`${_h} is not supported`);return t}function Cn({[mr]:e},{wsl:t}={}){if(t&&nt)return vh(t);if(!e)throw new Error(`${mr} is not supported`);return vh(e)}var vi,Kl,xh,mr,_h,$h,Ti,U_,dr,Ch,Rh=y(()=>{mh();jl();dh();bh();Ol();Eh();vi=Symbol("fallbackAttempt"),Kl=import.meta.url?He__default.dirname(fileURLToPath(import.meta.url)):"",xh=He__default.join(Kl,"xdg-open"),{platform:mr,arch:_h}=qe,$h=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")},Ti=async e=>{e={wait:false,background:false,newInstance:false,allowNonzeroExitCode:false,...e};let t=e[vi]===true;if(delete e[vi],Array.isArray(e.app))return $h(e.app,c=>Ti({...e,app:c,[vi]:true}));let{name:r,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(r))return $h(r,c=>Ti({...e,app:{name:c,arguments:n},[vi]: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"},u={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},p;if(nt){let f=await ph();p=ql.get(f)??{};}else p=await zl();if(p.id in c){let f=c[p.id.toLowerCase()];if(r==="browserPrivate"){if(f==="safari")throw new Error("Safari doesn't support opening in private mode via command line");n.push(u[f]);}return Ti({...e,app:{name:dr[f],arguments:n}})}throw new Error(`${p.name} is not supported as a default browser`)}let s,i=[],o={},a=false;if(nt&&!Ut()&&!Sh&&!r&&(a=await uh()),mr==="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(mr==="win32"||a){s=await _i(),i.push(...Le.argumentsPrefix),nt||(o.windowsVerbatimArguments=true),nt&&e.target&&(e.target=await fh(e.target));let c=["$ProgressPreference = 'SilentlyContinue';","Start"];e.wait&&c.push("-Wait"),r?(c.push(Le.escapeArgument(r)),e.target&&n.push(e.target)):e.target&&c.push(Le.escapeArgument(e.target)),n.length>0&&(n=n.map(u=>Le.escapeArgument(u)),c.push("-ArgumentList",n.join(","))),e.target=Le.encodeCommand(c.join(" ")),e.wait||(o.stdio="ignore");}else {if(r)s=r;else {let c=!Kl||Kl==="/",u=false;try{await ce__default.access(xh,constants.X_OK),u=!0;}catch{}s=qe.versions.electron??(mr==="android"||c||!u)?"xdg-open":xh;}n.length>0&&i.push(...n),e.wait||(o.stdio="ignore",o.detached=true);}mr==="darwin"&&n.length>0&&i.push("--args",...n),e.target&&i.push(e.target);let l=m_.spawn(s,i,o);return e.wait?new Promise((c,u)=>{l.once("error",u),l.once("close",p=>{if(!e.allowNonzeroExitCode&&p!==0){u(new Error(`Exited with code ${p}`));return}c(l);});}):t?new Promise((c,u)=>{l.once("error",u),l.once("spawn",()=>{l.once("close",p=>{if(l.off("error",u),p!==0){u(new Error(`Exited with code ${p}`));return}l.unref(),c(l);});});}):(l.unref(),new Promise((c,u)=>{l.once("error",u),l.once("spawn",()=>{l.off("error",u),c(l);});}))},U_=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a `target`");return Ti({...t,target:e})};dr={browser:"browser",browserPrivate:"browserPrivate"};Bt(dr,"chrome",()=>Cn({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"]}}));Bt(dr,"brave",()=>Cn({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"]}}));Bt(dr,"firefox",()=>Cn({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));Bt(dr,"edge",()=>Cn({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));Bt(dr,"safari",()=>Cn({darwin:"Safari"}));Ch=U_;});var kh={};fe(kh,{cloud:()=>W_});var Ie,H_,W_,Ph=y(()=>{Ie=ee(se());Rh();Oe();Te();pr();Be();pi();qt();we();Ke();H_="Management APIs:",W_=e=>{let t=e.command("cloud").description(de("Supalite cloud operations")).helpGroup(H_);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=ki();n.length>0&&(console.error(Ie.default.red(`Cannot deploy: experimental features enabled (${n.join(", ")}). Cloud does not support them yet.`)),process.exit(1)),await Z(async()=>{await Y(r.config);let s=await V(),i=await s.project.local.createApp(r.config),o=!1;await ln(i,{force:!0});let a=await s.project.remote.get().catch(async()=>{if(await Ei("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 ue(i),u=l.connection.createMigrator(c),p=await u.diff();console.log(),pt(p);let f=l.getInfoJson(),h=i.getInfoJson();if(isEqual(f,h))console.log(Ie.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(Ie.default.green("Project config updated"));}let d=s.project.remote.url(a.id);if(p.plan.steps.length>0)try{if(await measureTime(async()=>{await u.migratePlan(p.plan,{force:r.force??!1});},m=>{console.log(Ie.default.green(`Pushed changes to project in ${m.toFixed(2)}ms.`));}),o)try{let m=await cn(l,{recoveryHint:"Fix `supabase/seed.sql` and rerun `lite cloud deploy` against the new project."});m>0&&console.log(Ie.default.green(`Seeded remote project (${m} statements).`));}catch(m){console.warn(Ie.default.yellow(String(m.message??m)));}console.log(`Project URL: ${Ie.default.cyan(d)}
|
|
412
|
+
`),o&&await Ch(d);}catch(m){m instanceof ui&&(console.warn(Ie.default.yellow("Migration would cause data loss. Rerun with --force to proceed.")),process.exit(1)),console.error(Ie.default.red("Migration error: "+String(m))),process.exit(1);}else console.log(Ie.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 Z(async()=>{await Y(r.config);let n=await V(),s=await n.project.local.createApp(r.config);if(await ln(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 ue(s),l=await o.connection.createMigrator(a).diff();if(l.plan.steps.length>0)if(r.sql){let c=un(l,{colorize:!0});console.log(Ie.default.cyan(c));}else pt(l);else console.log(Ie.default.green("No changes to migrate."));});});};});var hr=ee(se());qt();var Nh={init:()=>Promise.resolve().then(()=>(hc(),dc)).then(e=>e.init),start:()=>Promise.resolve().then(()=>(Ap(),Tp)).then(e=>e.start),dev:()=>Promise.resolve().then(()=>(Gf(),Wf)).then(e=>e.dev),repl:()=>Promise.resolve().then(()=>(Vf(),zf)).then(e=>e.repl),debug:()=>Promise.resolve().then(()=>(Jf(),Kf)).then(e=>e.debug),db:()=>Promise.resolve().then(()=>(Tm(),vm)).then(e=>e.db),migration:()=>Promise.resolve().then(()=>(Cm(),Am)).then(e=>e.migration),upgrade:()=>Promise.resolve().then(()=>(Ld(),Od)).then(e=>e.upgrade)},G_={login:()=>Promise.resolve().then(()=>(Dd(),Id)).then(e=>e.login),logout:()=>Promise.resolve().then(()=>(Md(),Fd)).then(e=>e.logout),signup:()=>Promise.resolve().then(()=>(Bd(),Ud)).then(e=>e.signup),whoami:()=>Promise.resolve().then(()=>(Hd(),qd)).then(e=>e.whoami),link:()=>Promise.resolve().then(()=>(zd(),Gd)).then(e=>e.link),unlink:()=>Promise.resolve().then(()=>(Kd(),Vd)).then(e=>e.unlink),status:()=>Promise.resolve().then(()=>(Yd(),Xd)).then(e=>e.status),projects:()=>Promise.resolve().then(()=>(eh(),Zd)).then(e=>e.projects),cloud:()=>Promise.resolve().then(()=>(Ph(),kh)).then(e=>e.cloud)};function z_(){return ec("cloud")?{...Nh,...G_}:Nh}async function Oh(){let e=z_(),t=process.argv[2];return t&&Object.hasOwn(e,t)?[await e[t]()]:Promise.all(Object.values(e).map(r=>r()))}we();$l();var Jl=new Command;function K_(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 J_(){let{version:e,name:t}=await qn();Jl.name("lite").description(`${hr.default.yellowBright("\u26A1")} ${t} v${e}`).version(e).option("--no-telemetry","disable anonymous usage telemetry").hook("preAction",async(r,n)=>{let s=r.opts?.()??{},i=typeof n.opts=="function"?n.opts():{};i.json&&i.dryRun||console.log(`${hr.default.green("\u26A1"+hr.default.bold("Supalite"))} ${hr.default.dim(hr.default.green("v"+e))}`),Cd(s.telemetry===false)&&await Rd({command:K_(n),args:i});});for(let r of await Oh())r(Jl);await Jl.parseAsync(),await xi(false);}J_().then(null).catch(async e=>{console.error(e),await xi(true,e),process.exitCode=1;});
|
|
386
413
|
/*! Bundled license information:
|
|
387
414
|
|
|
388
415
|
smol-toml/dist/error.js:
|
|
@@ -421,7 +448,4 @@ smol-toml/dist/index.js:
|
|
|
421
448
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
422
449
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
423
450
|
*)
|
|
424
|
-
|
|
425
|
-
chokidar/index.js:
|
|
426
|
-
(*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) *)
|
|
427
451
|
*/
|