@supabase/lite 0.9.1-next.1 → 0.10.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.
Files changed (50) hide show
  1. package/FEATURES.md +6 -6
  2. package/LIMITATIONS.md +8 -6
  3. package/PATTERNS.md +66 -6
  4. package/README.md +15 -8
  5. package/STATUS.md +26 -19
  6. package/dist/{Connection-ZWTDByQ5.d.ts → Connection-f_d5HhQ0.d.ts} +301 -293
  7. package/dist/cli/index.js +127 -124
  8. package/dist/cli/lib.d.ts +1 -12
  9. package/dist/cli/lib.js +44 -39
  10. package/dist/db/fallback.d.ts +1 -1
  11. package/dist/db/postgres/PostgresConnection.js +18 -18
  12. package/dist/db/postgres/pglite/PgliteConnection.js +4 -4
  13. package/dist/index.d.ts +90 -38
  14. package/dist/index.js +181 -73
  15. package/dist/static/.vite/manifest.json +34 -2
  16. package/dist/static/assets/InterVariable-Dx4kXJAl.woff2 +0 -0
  17. package/dist/static/assets/InterVariable-Italic-DpCbqKDY.woff2 +0 -0
  18. package/dist/static/assets/SourceCodePro-Variable-BP8Zz55n.woff2 +0 -0
  19. package/dist/static/assets/SourceCodePro-Variable-Italic-eALmlzX7.woff2 +0 -0
  20. package/dist/static/assets/main-BY4iigay.css +1 -0
  21. package/dist/static/assets/main-BnQ-v4V9.js +199 -0
  22. package/dist/static/assets/manrope-latin-ext-wght-normal-Ch3YOpNY.woff2 +0 -0
  23. package/dist/static/assets/manrope-latin-wght-normal-DHIcAJRg.woff2 +0 -0
  24. package/dist/vite/index.d.ts +601 -29
  25. package/dist/vite/index.js +2 -2
  26. package/docs/auth/overview.mdx +1 -1
  27. package/docs/auth/supported-flows.mdx +4 -4
  28. package/docs/compatibility.mdx +4 -4
  29. package/docs/database/migrations.mdx +2 -0
  30. package/docs/database/rls.mdx +7 -5
  31. package/docs/database/schemas.mdx +1 -1
  32. package/docs/integrations/embedded.mdx +20 -3
  33. package/docs/integrations/frameworks.mdx +1 -1
  34. package/docs/integrations/vite.mdx +4 -2
  35. package/docs/llms.txt +2 -2
  36. package/docs/quickstart.mdx +2 -2
  37. package/docs/running.mdx +20 -10
  38. package/docs/storage/limitations.mdx +2 -11
  39. package/docs/storage/overview.mdx +8 -2
  40. package/package.json +2 -1
  41. package/skills/supalite/SKILL.md +1 -1
  42. package/dist/static/assets/main-1bwWb_1q.js +0 -40996
  43. package/dist/static/assets/main-BDsRycsc.css +0 -4045
  44. package/dist/static/fonts/CustomFont-Black.woff2 +0 -0
  45. package/dist/static/fonts/CustomFont-BlackItalic.woff2 +0 -0
  46. package/dist/static/fonts/CustomFont-Bold.woff2 +0 -0
  47. package/dist/static/fonts/CustomFont-BoldItalic.woff2 +0 -0
  48. package/dist/static/fonts/CustomFont-Book.woff2 +0 -0
  49. package/dist/static/fonts/CustomFont-BookItalic.woff2 +0 -0
  50. package/dist/static/fonts/CustomFont-Medium.woff2 +0 -0
package/dist/cli/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import qr,{statSync,readFileSync}from'node:fs';import*as Ie from'node:path';import Ie__default,{join}from'node:path';import {parse}from'dotenv';import*as de from'node:fs/promises';import de__default,{stat as stat$1}from'node:fs/promises';import {fileURLToPath}from'node:url';import {createConnection}from'@supabase/lite/sqlite';import {s}from'jsonv-ts';import Ny from'node:os';import {createClient}from'@supabase/supabase-js';import Kx,{createHash}from'node:crypto';import {DataLossError,SqliteConnection,isEqual,measureTime,splitSqlStatements,ensureVar,App,cloud}from'@supabase/lite';import {createRequire}from'module';import {resolve,posix,isAbsolute,sep,basename,dirname,normalize,relative}from'path';import*as sb from'fs';import {statSync as statSync$1,stat,realpathSync,realpath,readdirSync,readdir}from'fs';import {fileURLToPath as fileURLToPath$1}from'url';import {Deparser,QuoteUtils}from'pgsql-deparser';import US from'chokidar';import {styleText}from'node:util';import Ve,{stdout,stdin}from'node:process';import*as Et from'node:readline';import Et__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 Lx from'node:net';import {Command as Command$1}from'@commander-js/extra-typings';import {Command}from'commander';try {
2
+ import rs,{statSync,readFileSync}from'node:fs';import*as Fe from'node:path';import Fe__default,{join}from'node:path';import {parse}from'dotenv';import*as he from'node:fs/promises';import he__default,{stat as stat$1}from'node:fs/promises';import {fileURLToPath}from'node:url';import {createConnection}from'@supabase/lite/sqlite';import {s}from'jsonv-ts';import Qy from'node:os';import {createClient}from'@supabase/supabase-js';import kT,{createHash,randomUUID}from'node:crypto';import {DataLossError,SqliteConnection,isEqual,measureTime,splitSqlStatements,ensureVar,App,cloud}from'@supabase/lite';import {createRequire}from'module';import {resolve,posix,isAbsolute,sep,basename,dirname,normalize,relative}from'path';import*as ew from'fs';import {statSync as statSync$1,stat,realpathSync,realpath,readdirSync,readdir}from'fs';import {fileURLToPath as fileURLToPath$1}from'url';import {Deparser,QuoteUtils}from'pgsql-deparser';import jE from'chokidar';import {styleText}from'node:util';import Xe,{stdout,stdin}from'node:process';import*as Rt from'node:readline';import Rt__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 gT from'node:net';import {Command as Command$1}from'@commander-js/extra-typings';import {Command}from'commander';try {
3
3
  /**
4
4
  * Adding this to avoid warnings from node:sqlite being experimental
5
5
  */
@@ -10,42 +10,42 @@ import qr,{statSync,readFileSync}from'node:fs';import*as Ie from'node:path';impo
10
10
  };
11
11
  } catch {}
12
12
 
13
- var Hh=Object.create;var Ui=Object.defineProperty;var Gh=Object.getOwnPropertyDescriptor;var Wh=Object.getOwnPropertyNames;var Vh=Object.getPrototypeOf,Kh=Object.prototype.hasOwnProperty;var b=(e,t)=>()=>(e&&(t=e(e=0)),t);var lt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),fe=(e,t)=>{for(var n in t)Ui(e,n,{get:t[n],enumerable:true});},zh=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Wh(t))!Kh.call(e,s)&&s!==n&&Ui(e,s,{get:()=>t[s],enumerable:!(r=Gh(t,s))||r.enumerable});return e};var V=(e,t,n)=>(n=e!=null?Hh(Vh(e)):{},zh(Ui(n,"default",{value:e,enumerable:true}),e));var Fr,Mi=b(()=>{Fr=process.stdin.isTTY?null:(async()=>{let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")})();Fr&&process.stdin.unref?.();});var z=lt((xT,Bi)=>{var Mr=process||{},sc=Mr.argv||[],Ur=Mr.env||{},Xh=!(Ur.NO_COLOR||sc.includes("--no-color"))&&(!!Ur.FORCE_COLOR||sc.includes("--color")||Mr.platform==="win32"||(Mr.stdout||{}).isTTY&&Ur.TERM!=="dumb"||!!Ur.CI),Yh=(e,t,n=e)=>r=>{let s=""+r,i=s.indexOf(t,e.length);return ~i?e+Jh(s,t,n,i)+t:e+s+t},Jh=(e,t,n,r)=>{let s="",i=0;do s+=e.substring(i,r)+n,i=r+t.length,r=e.indexOf(t,i);while(~r);return s+e.substring(i)},ic=(e=Xh)=>{let t=e?Yh:()=>String;return {isColorSupported:e,reset:t("\x1B[0m","\x1B[0m"),bold:t("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:t("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:t("\x1B[3m","\x1B[23m"),underline:t("\x1B[4m","\x1B[24m"),inverse:t("\x1B[7m","\x1B[27m"),hidden:t("\x1B[8m","\x1B[28m"),strikethrough:t("\x1B[9m","\x1B[29m"),black:t("\x1B[30m","\x1B[39m"),red:t("\x1B[31m","\x1B[39m"),green:t("\x1B[32m","\x1B[39m"),yellow:t("\x1B[33m","\x1B[39m"),blue:t("\x1B[34m","\x1B[39m"),magenta:t("\x1B[35m","\x1B[39m"),cyan:t("\x1B[36m","\x1B[39m"),white:t("\x1B[37m","\x1B[39m"),gray:t("\x1B[90m","\x1B[39m"),bgBlack:t("\x1B[40m","\x1B[49m"),bgRed:t("\x1B[41m","\x1B[49m"),bgGreen:t("\x1B[42m","\x1B[49m"),bgYellow:t("\x1B[43m","\x1B[49m"),bgBlue:t("\x1B[44m","\x1B[49m"),bgMagenta:t("\x1B[45m","\x1B[49m"),bgCyan:t("\x1B[46m","\x1B[49m"),bgWhite:t("\x1B[47m","\x1B[49m"),blackBright:t("\x1B[90m","\x1B[39m"),redBright:t("\x1B[91m","\x1B[39m"),greenBright:t("\x1B[92m","\x1B[39m"),yellowBright:t("\x1B[93m","\x1B[39m"),blueBright:t("\x1B[94m","\x1B[39m"),magentaBright:t("\x1B[95m","\x1B[39m"),cyanBright:t("\x1B[96m","\x1B[39m"),whiteBright:t("\x1B[97m","\x1B[39m"),bgBlackBright:t("\x1B[100m","\x1B[49m"),bgRedBright:t("\x1B[101m","\x1B[49m"),bgGreenBright:t("\x1B[102m","\x1B[49m"),bgYellowBright:t("\x1B[103m","\x1B[49m"),bgBlueBright:t("\x1B[104m","\x1B[49m"),bgMagentaBright:t("\x1B[105m","\x1B[49m"),bgCyanBright:t("\x1B[106m","\x1B[49m"),bgWhiteBright:t("\x1B[107m","\x1B[49m")}};Bi.exports=ic();Bi.exports.createColors=ic;});function Zh(e){let t=typeof process<"u"&&process.env||void 0;return t?t.NODE_ENV==="test"?true:t[Qh[e]]==="1":false}function lc(e){return ac[e]}function qi(){return oc.filter(e=>ac[e])}function Br(){let e=qi();if(e.length===0)return null;let t=e.includes("storage")?" Cloud sync (lite cloud deploy) is disabled.":"";return `EXPERIMENTAL FEATURES ENABLED: ${e.join(", ")} - not supported, do not use in production.${t}`}var Qh,oc,ac,Kt=b(()=>{Qh={storage:"EXPERIMENTAL_STORAGE",cloud:"EXPERIMENTAL_CLOUD"},oc=["storage","cloud"],ac=Object.fromEntries(oc.map(e=>[e,Zh(e)]));});function Ce(e,t){qr.existsSync(e)||(qr.mkdirSync(e,{recursive:true}),t?.());}function xt(e,t,n){qr.existsSync(e)||(qr.writeFileSync(e,t),n?.());}async function Hr(){if(!Fr)throw new Error("No input given \u2014 pass it as an argument or pipe it via stdin.");return process.stdin.ref?.(),Fr}var Tt=b(()=>{Mi();});function tg(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return [n.length,n.pop().length+1]}function ng(e,t,n){let r=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=r[o-1];a&&(s+=o.toString().padEnd(i," "),s+=": ",s+=a,s+=`
13
+ var cg=Object.create;var no=Object.defineProperty;var ug=Object.getOwnPropertyDescriptor;var pg=Object.getOwnPropertyNames;var fg=Object.getPrototypeOf,mg=Object.prototype.hasOwnProperty;var b=(e,t)=>()=>(e&&(t=e(e=0)),t);var dt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),me=(e,t)=>{for(var n in t)no(e,n,{get:t[n],enumerable:true});},dg=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of pg(t))!mg.call(e,s)&&s!==n&&no(e,s,{get:()=>t[s],enumerable:!(r=ug(t,s))||r.enumerable});return e};var K=(e,t,n)=>(n=e!=null?cg(fg(e)):{},dg(no(n,"default",{value:e,enumerable:true}),e));var Zr,ro=b(()=>{Zr=process.stdin.isTTY?null:(async()=>{let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")})();Zr&&process.stdin.unref?.();});var X=dt((oC,so)=>{var ts=process||{},Ec=ts.argv||[],es=ts.env||{},hg=!(es.NO_COLOR||Ec.includes("--no-color"))&&(!!es.FORCE_COLOR||Ec.includes("--color")||ts.platform==="win32"||(ts.stdout||{}).isTTY&&es.TERM!=="dumb"||!!es.CI),gg=(e,t,n=e)=>r=>{let s=""+r,i=s.indexOf(t,e.length);return ~i?e+yg(s,t,n,i)+t:e+s+t},yg=(e,t,n,r)=>{let s="",i=0;do s+=e.substring(i,r)+n,i=r+t.length,r=e.indexOf(t,i);while(~r);return s+e.substring(i)},_c=(e=hg)=>{let t=e?gg:()=>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")}};so.exports=_c();so.exports.createColors=_c;});function wg(e){let t=typeof process<"u"&&process.env||void 0;return t?t.NODE_ENV==="test"?true:t[bg[e]]==="1":false}function Cc(e){return Tc[e]}function io(){return xc.filter(e=>Tc[e])}function ns(){let e=io();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 bg,xc,Tc,Qt=b(()=>{bg={storage:"EXPERIMENTAL_STORAGE",cloud:"EXPERIMENTAL_CLOUD"},xc=["storage","cloud"],Tc=Object.fromEntries(xc.map(e=>[e,wg(e)]));});function ve(e,t){rs.existsSync(e)||(rs.mkdirSync(e,{recursive:true}),t?.());}function kt(e,t,n){rs.existsSync(e)||(rs.writeFileSync(e,t),n?.());}async function ss(){if(!Zr)throw new Error("No input given \u2014 pass it as an argument or pipe it via stdin.");return process.stdin.ref?.(),Zr}var Nt=b(()=>{ro();});function Eg(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return [n.length,n.pop().length+1]}function _g(e,t,n){let r=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=r[o-1];a&&(s+=o.toString().padEnd(i," "),s+=": ",s+=a,s+=`
14
14
  `,o===t&&(s+=" ".repeat(i+n+2),s+=`^
15
- `));}return s}var q,Ct=b(()=>{q=class extends Error{line;column;codeblock;constructor(t,n){let[r,s]=tg(n.toml,n.ptr),i=ng(n.toml,r,s);super(`Invalid TOML document: ${t}
15
+ `));}return s}var H,Pt=b(()=>{H=class extends Error{line;column;codeblock;constructor(t,n){let[r,s]=Eg(n.toml,n.ptr),i=_g(n.toml,r,s);super(`Invalid TOML document: ${t}
16
16
 
17
- ${i}`,n),this.line=r,this.column=s,this.codeblock=i;}};});function rg(e,t){let n=0;for(;e[t-++n]==="\\";);return --n&&n%2}function Gr(e,t=0,n=e.length){let r=e.indexOf(`
18
- `,t);return e[r-1]==="\r"&&r--,r<=n?r:-1}function zt(e,t){for(let n=t;n<e.length;n++){let r=e[n];if(r===`
17
+ ${i}`,n),this.line=r,this.column=s,this.codeblock=i;}};});function xg(e,t){let n=0;for(;e[t-++n]==="\\";);return --n&&n%2}function is(e,t=0,n=e.length){let r=e.indexOf(`
18
+ `,t);return e[r-1]==="\r"&&r--,r<=n?r:-1}function Zt(e,t){for(let n=t;n<e.length;n++){let r=e[n];if(r===`
19
19
  `)return n;if(r==="\r"&&e[n+1]===`
20
- `)return n+1;if(r<" "&&r!==" "||r==="\x7F")throw new q("control characters are not allowed in comments",{toml:e,ptr:t})}return e.length}function Ae(e,t,n,r){let s;for(;(s=e[t])===" "||s===" "||!n&&(s===`
20
+ `)return n+1;if(r<" "&&r!==" "||r==="\x7F")throw new H("control characters are not allowed in comments",{toml:e,ptr:t})}return e.length}function ke(e,t,n,r){let s;for(;(s=e[t])===" "||s===" "||!n&&(s===`
21
21
  `||s==="\r"&&e[t+1]===`
22
- `);)t++;return r||s!=="#"?t:Ae(e,zt(e,t),n)}function uc(e,t,n,r,s=false){if(!r)return t=Gr(e,t),t<0?e.length:t;for(let i=t;i<e.length;i++){let o=e[i];if(o==="#")i=Gr(e,i);else {if(o===n)return i+1;if(o===r||s&&(o===`
22
+ `);)t++;return r||s!=="#"?t:ke(e,Zt(e,t),n)}function $c(e,t,n,r,s=false){if(!r)return t=is(e,t),t<0?e.length:t;for(let i=t;i<e.length;i++){let o=e[i];if(o==="#")i=is(e,i);else {if(o===n)return i+1;if(o===r||s&&(o===`
23
23
  `||o==="\r"&&e[i+1]===`
24
- `))return i}}throw new q("cannot find end of structure",{toml:e,ptr:t})}function Wr(e,t){let n=e[t],r=n===e[t+1]&&e[t+1]===e[t+2]?e.slice(t,t+3):n;t+=r.length-1;do t=e.indexOf(r,++t);while(t>-1&&n!=="'"&&rg(e,t));return t>-1&&(t+=r.length,r.length>1&&(e[t]===n&&t++,e[t]===n&&t++)),t}var _n=b(()=>{Ct();});var sg,xn,Hi=b(()=>{sg=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,xn=class e extends Date{#e=false;#t=false;#n=null;constructor(t){let n=true,r=true,s="Z";if(typeof t=="string"){let i=t.match(sg);i?(i[1]||(n=false,t=`0000-01-01T${t}`),r=!!i[2],r&&t[10]===" "&&(t=t.replace(" ","T")),i[2]&&+i[2]>23?t="":(s=i[3]||null,t=t.toUpperCase(),!s&&r&&(t+="Z"))):t="";}super(t),isNaN(this.getTime())||(this.#e=n,this.#t=r,this.#n=s);}isDateTime(){return this.#e&&this.#t}isLocal(){return !this.#e||!this.#t||!this.#n}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.#n===null)return t.slice(0,-1);if(this.#n==="Z")return t;let n=+this.#n.slice(1,3)*60+ +this.#n.slice(4,6);return n=this.#n[0]==="-"?n:-n,new Date(this.getTime()-n*6e4).toISOString().slice(0,-1)+this.#n}static wrapAsOffsetDateTime(t,n="Z"){let r=new e(t);return r.#n=n,r}static wrapAsLocalDateTime(t){let n=new e(t);return n.#n=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#t=false,n.#n=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#e=false,n.#n=null,n}};});function Vr(e,t=0,n=e.length){let r=e[t]==="'",s=e[t++]===e[t]&&e[t]===e[t+1];s&&(n-=2,e[t+=2]==="\r"&&t++,e[t]===`
24
+ `))return i}}throw new H("cannot find end of structure",{toml:e,ptr:t})}function os(e,t){let n=e[t],r=n===e[t+1]&&e[t+1]===e[t+2]?e.slice(t,t+3):n;t+=r.length-1;do t=e.indexOf(r,++t);while(t>-1&&n!=="'"&&xg(e,t));return t>-1&&(t+=r.length,r.length>1&&(e[t]===n&&t++,e[t]===n&&t++)),t}var Nn=b(()=>{Pt();});var Tg,Pn,oo=b(()=>{Tg=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,Pn=class e extends Date{#e=false;#t=false;#n=null;constructor(t){let n=true,r=true,s="Z";if(typeof t=="string"){let i=t.match(Tg);i?(i[1]||(n=false,t=`0000-01-01T${t}`),r=!!i[2],r&&t[10]===" "&&(t=t.replace(" ","T")),i[2]&&+i[2]>23?t="":(s=i[3]||null,t=t.toUpperCase(),!s&&r&&(t+="Z"))):t="";}super(t),isNaN(this.getTime())||(this.#e=n,this.#t=r,this.#n=s);}isDateTime(){return this.#e&&this.#t}isLocal(){return !this.#e||!this.#t||!this.#n}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.#n===null)return t.slice(0,-1);if(this.#n==="Z")return t;let n=+this.#n.slice(1,3)*60+ +this.#n.slice(4,6);return n=this.#n[0]==="-"?n:-n,new Date(this.getTime()-n*6e4).toISOString().slice(0,-1)+this.#n}static wrapAsOffsetDateTime(t,n="Z"){let r=new e(t);return r.#n=n,r}static wrapAsLocalDateTime(t){let n=new e(t);return n.#n=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#t=false,n.#n=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#e=false,n.#n=null,n}};});function as(e,t=0,n=e.length){let r=e[t]==="'",s=e[t++]===e[t]&&e[t]===e[t+1];s&&(n-=2,e[t+=2]==="\r"&&t++,e[t]===`
25
25
  `&&t++);let i=0,o,a="",l=t;for(;t<n-1;){let c=e[t++];if(c===`
26
26
  `||c==="\r"&&e[t]===`
27
- `){if(!s)throw new q("newlines are not allowed in strings",{toml:e,ptr:t-1})}else if(c<" "&&c!==" "||c==="\x7F")throw new q("control characters are not allowed in strings",{toml:e,ptr:t-1});if(o){if(o=false,c==="x"||c==="u"||c==="U"){let p=e.slice(t,t+=c==="x"?2:c==="u"?4:8);if(!lg.test(p))throw new q("invalid unicode escape",{toml:e,ptr:i});try{a+=String.fromCodePoint(parseInt(p,16));}catch{throw new q("invalid unicode escape",{toml:e,ptr:i})}}else if(s&&(c===`
28
- `||c===" "||c===" "||c==="\r")){if(t=Ae(e,t-1,true),e[t]!==`
29
- `&&e[t]!=="\r")throw new q("invalid escape: only line-ending whitespace may be escaped",{toml:e,ptr:i});t=Ae(e,t);}else if(c in pc)a+=pc[c];else throw new q("unrecognized escape sequence",{toml:e,ptr:i});l=t;}else !r&&c==="\\"&&(i=t-1,o=true,a+=e.slice(l,i));}return a+e.slice(l,n-1)}function fc(e,t,n,r){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 r?0n:0;let s=ig.test(e);if(s||og.test(e)){if(ag.test(e))throw new q("leading zeroes are not allowed",{toml:t,ptr:n});e=e.replace(/_/g,"");let o=+e;if(isNaN(o))throw new q("invalid number",{toml:t,ptr:n});if(s){if((s=!Number.isSafeInteger(o))&&!r)throw new q("integer value cannot be represented losslessly",{toml:t,ptr:n});(s||r===true)&&(o=BigInt(e));}return o}let i=new xn(e);if(!i.isValid())throw new q("invalid value",{toml:t,ptr:n});return i}var ig,og,ag,lg,pc,Gi=b(()=>{_n();Hi();Ct();ig=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,og=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,ag=/^[+-]?0[0-9_]/,lg=/^[0-9a-f]{2,8}$/i,pc={b:"\b",t:" ",n:`
30
- `,f:"\f",r:"\r",e:"\x1B",'"':'"',"\\":"\\"};});function cg(e,t,n){let r=e.slice(t,n),s=r.indexOf("#");return s>-1&&(zt(e,s),r=r.slice(0,s)),[r.trimEnd(),s]}function Tn(e,t,n,r,s){if(r===0)throw new q("document contains excessively nested structures. aborting.",{toml:e,ptr:t});let i=e[t];if(i==="["||i==="{"){let[l,c]=i==="["?dc(e,t,r,s):mc(e,t,r,s);if(n){if(c=Ae(e,c),e[c]===",")c++;else if(e[c]!==n)throw new q("expected comma or end of structure",{toml:e,ptr:c})}return [l,c]}let o;if(i==='"'||i==="'"){o=Wr(e,t);let l=Vr(e,t,o);if(n){if(o=Ae(e,o),e[o]&&e[o]!==","&&e[o]!==n&&e[o]!==`
31
- `&&e[o]!=="\r")throw new q("unexpected character encountered",{toml:e,ptr:o});o+=+(e[o]===",");}return [l,o]}o=uc(e,t,",",n);let a=cg(e,t,o-+(e[o-1]===","));if(!a[0])throw new q("incomplete key-value declaration: no value specified",{toml:e,ptr:t});return n&&a[1]>-1&&(o=Ae(e,t+a[1]),o+=+(e[o]===",")),[fc(a[0],e,t,s),o]}var Wi=b(()=>{Gi();Vi();_n();Ct();});function Kr(e,t,n="="){let r=t-1,s=[],i=e.indexOf(n,t);if(i<0)throw new q("incomplete key-value: cannot find end of key",{toml:e,ptr:t});do{let o=e[t=++r];if(o!==" "&&o!==" ")if(o==='"'||o==="'"){if(o===e[t+1]&&o===e[t+2])throw new q("multiline strings are not allowed in keys",{toml:e,ptr:t});let a=Wr(e,t);if(a<0)throw new q("unfinished string encountered",{toml:e,ptr:t});r=e.indexOf(".",a);let l=e.slice(a,r<0||r>i?i:r),c=Gr(l);if(c>-1)throw new q("newlines are not allowed in keys",{toml:e,ptr:t+r+c});if(l.trimStart())throw new q("found extra tokens after the string part",{toml:e,ptr:a});if(i<a&&(i=e.indexOf(n,a),i<0))throw new q("incomplete key-value: cannot find end of key",{toml:e,ptr:t});s.push(Vr(e,t,a));}else {r=e.indexOf(".",t);let a=e.slice(t,r<0||r>i?i:r);if(!ug.test(a))throw new q("only letter, numbers, dashes and underscores are allowed in keys",{toml:e,ptr:t});s.push(a.trimEnd());}}while(r+1&&r<i);return [s,Ae(e,i+1,true,true)]}function mc(e,t,n,r){let s={},i=new Set,o;for(t++;(o=e[t++])!=="}"&&o;){if(o===",")throw new q("expected value, found comma",{toml:e,ptr:t-1});if(o==="#")t=zt(e,t);else if(o!==" "&&o!==" "&&o!==`
32
- `&&o!=="\r"){let a,l=s,c=false,[p,u]=Kr(e,t-1);for(let d=0;d<p.length;d++){if(d&&(l=c?l[a]:l[a]={}),a=p[d],(c=Object.hasOwn(l,a))&&(typeof l[a]!="object"||i.has(l[a])))throw new q("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 q("trying to redefine an already defined value",{toml:e,ptr:t});let[f,h]=Tn(e,u,"}",n-1,r);i.add(f),l[a]=f,t=h;}}if(!o)throw new q("unfinished table encountered",{toml:e,ptr:t});return [s,t]}function dc(e,t,n,r){let s=[],i;for(t++;(i=e[t++])!=="]"&&i;){if(i===",")throw new q("expected value, found comma",{toml:e,ptr:t-1});if(i==="#")t=zt(e,t);else if(i!==" "&&i!==" "&&i!==`
33
- `&&i!=="\r"){let o=Tn(e,t-1,"]",n-1,r);s.push(o[0]),t=o[1];}}if(!i)throw new q("unfinished array encountered",{toml:e,ptr:t});return [s,t]}var ug,Vi=b(()=>{Gi();Wi();_n();Ct();ug=/^[a-zA-Z0-9-_]+[ \t]*$/;});function hc(e,t,n,r){let s=t,i=n,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,r===0&&(l.t===1||l.t===2))return null;if(l.t===2){let p=s.length-1;s=s[p],i=i[p].c;}}if(o=e[c],(a=Object.hasOwn(s,o))&&i[o]?.t===0&&i[o]?.d)return null;a||(o==="__proto__"&&(Object.defineProperty(s,o,{enumerable:true,configurable:true,writable:true}),Object.defineProperty(i,o,{enumerable:true,configurable:true,writable:true})),i[o]={t:c<e.length-1&&r===2?3:r,d:false,i:0,c:{}});}if(l=i[o],l.t!==r&&!(r===1&&l.t===3)||(r===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,r===1)s=a?s[o]:s[o]={};else if(r===0&&a)return null;return [o,s,l.c]}function At(e,{maxDepth:t=1e3,integersAsBigInt:n}={}){let r={},s={},i=r,o=s;for(let a=Ae(e,0);a<e.length;){if(e[a]==="["){let l=e[++a]==="[",c=Kr(e,a+=+l,"]");if(l){if(e[c[1]-1]!=="]")throw new q("expected end of table declaration",{toml:e,ptr:c[1]-1});c[1]++;}let p=hc(c[0],r,s,l?2:1);if(!p)throw new q("trying to redefine an already defined table or value",{toml:e,ptr:a});o=p[2],i=p[1],a=c[1];}else {let l=Kr(e,a),c=hc(l[0],i,o,0);if(!c)throw new q("trying to redefine an already defined table or value",{toml:e,ptr:a});let p=Tn(e,l[1],void 0,t,n);c[1][c[0]]=p[0],a=p[1];}if(a=Ae(e,a,true),e[a]&&e[a]!==`
34
- `&&e[a]!=="\r")throw new q("each key-value declaration must be followed by an end-of-line",{toml:e,ptr:a});a=Ae(e,a);}return r}var gc=b(()=>{Vi();Wi();_n();Ct();});function Cn(e){let t=typeof e;if(t==="object"){if(Array.isArray(e))return "array";if(e instanceof Date)return "date"}return t}function pg(e){for(let t=0;t<e.length;t++)if(Cn(e[t])!=="object")return false;return e.length!=0}function Ki(e){return JSON.stringify(e).replace(/\x7f/g,"\\u007f")}function zi(e,t,n,r){if(n===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":r&&Number.isInteger(e)?e.toFixed(1):e.toString();if(t==="bigint"||t==="boolean")return e.toString();if(t==="string")return Ki(e);if(t==="date"){if(isNaN(e.getTime()))throw new TypeError("cannot serialize invalid date");return e.toISOString()}if(t==="object")return fg(e,n,r);if(t==="array")return mg(e,n,r)}function fg(e,t,n){let r=Object.keys(e);if(r.length===0)return "{}";let s="{ ";for(let i=0;i<r.length;i++){let o=r[i];i&&(s+=", "),s+=yc.test(o)?o:Ki(o),s+=" = ",s+=zi(e[o],Cn(e[o]),t-1,n);}return s+" }"}function mg(e,t,n){if(e.length===0)return "[]";let r="[ ";for(let s=0;s<e.length;s++){if(s&&(r+=", "),e[s]===null||e[s]===void 0)throw new TypeError("arrays cannot contain null or undefined values");r+=zi(e[s],Cn(e[s]),t-1,n);}return r+" ]"}function dg(e,t,n,r){if(n===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&&`
27
+ `){if(!s)throw new H("newlines are not allowed in strings",{toml:e,ptr:t-1})}else if(c<" "&&c!==" "||c==="\x7F")throw new H("control characters are not allowed in strings",{toml:e,ptr:t-1});if(o){if(o=false,c==="x"||c==="u"||c==="U"){let p=e.slice(t,t+=c==="x"?2:c==="u"?4:8);if(!Rg.test(p))throw new H("invalid unicode escape",{toml:e,ptr:i});try{a+=String.fromCodePoint(parseInt(p,16));}catch{throw new H("invalid unicode escape",{toml:e,ptr:i})}}else if(s&&(c===`
28
+ `||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 Rc)a+=Rc[c];else throw new H("unrecognized escape sequence",{toml:e,ptr:i});l=t;}else !r&&c==="\\"&&(i=t-1,o=true,a+=e.slice(l,i));}return a+e.slice(l,n-1)}function vc(e,t,n,r){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 r?0n:0;let s=Cg.test(e);if(s||Ag.test(e)){if($g.test(e))throw new H("leading zeroes are not allowed",{toml:t,ptr:n});e=e.replace(/_/g,"");let o=+e;if(isNaN(o))throw new H("invalid number",{toml:t,ptr:n});if(s){if((s=!Number.isSafeInteger(o))&&!r)throw new H("integer value cannot be represented losslessly",{toml:t,ptr:n});(s||r===true)&&(o=BigInt(e));}return o}let i=new Pn(e);if(!i.isValid())throw new H("invalid value",{toml:t,ptr:n});return i}var Cg,Ag,$g,Rg,Rc,ao=b(()=>{Nn();oo();Pt();Cg=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,Ag=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,$g=/^[+-]?0[0-9_]/,Rg=/^[0-9a-f]{2,8}$/i,Rc={b:"\b",t:" ",n:`
30
+ `,f:"\f",r:"\r",e:"\x1B",'"':'"',"\\":"\\"};});function vg(e,t,n){let r=e.slice(t,n),s=r.indexOf("#");return s>-1&&(Zt(e,s),r=r.slice(0,s)),[r.trimEnd(),s]}function On(e,t,n,r,s){if(r===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==="["?Nc(e,t,r,s):kc(e,t,r,s);if(n){if(c=ke(e,c),e[c]===",")c++;else if(e[c]!==n)throw new H("expected comma or end of structure",{toml:e,ptr:c})}return [l,c]}let o;if(i==='"'||i==="'"){o=os(e,t);let l=as(e,t,o);if(n){if(o=ke(e,o),e[o]&&e[o]!==","&&e[o]!==n&&e[o]!==`
31
+ `&&e[o]!=="\r")throw new H("unexpected character encountered",{toml:e,ptr:o});o+=+(e[o]===",");}return [l,o]}o=$c(e,t,",",n);let a=vg(e,t,o-+(e[o-1]===","));if(!a[0])throw new H("incomplete key-value declaration: no value specified",{toml:e,ptr:t});return n&&a[1]>-1&&(o=ke(e,t+a[1]),o+=+(e[o]===",")),[vc(a[0],e,t,s),o]}var lo=b(()=>{ao();co();Nn();Pt();});function ls(e,t,n="="){let r=t-1,s=[],i=e.indexOf(n,t);if(i<0)throw new H("incomplete key-value: cannot find end of key",{toml:e,ptr:t});do{let o=e[t=++r];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=os(e,t);if(a<0)throw new H("unfinished string encountered",{toml:e,ptr:t});r=e.indexOf(".",a);let l=e.slice(a,r<0||r>i?i:r),c=is(l);if(c>-1)throw new H("newlines are not allowed in keys",{toml:e,ptr:t+r+c});if(l.trimStart())throw new H("found extra tokens after the string part",{toml:e,ptr:a});if(i<a&&(i=e.indexOf(n,a),i<0))throw new H("incomplete key-value: cannot find end of key",{toml:e,ptr:t});s.push(as(e,t,a));}else {r=e.indexOf(".",t);let a=e.slice(t,r<0||r>i?i:r);if(!kg.test(a))throw new H("only letter, numbers, dashes and underscores are allowed in keys",{toml:e,ptr:t});s.push(a.trimEnd());}}while(r+1&&r<i);return [s,ke(e,i+1,true,true)]}function kc(e,t,n,r){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=Zt(e,t);else if(o!==" "&&o!==" "&&o!==`
32
+ `&&o!=="\r"){let a,l=s,c=false,[p,u]=ls(e,t-1);for(let m=0;m<p.length;m++){if(m&&(l=c?l[a]:l[a]={}),a=p[m],(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]=On(e,u,"}",n-1,r);i.add(f),l[a]=f,t=h;}}if(!o)throw new H("unfinished table encountered",{toml:e,ptr:t});return [s,t]}function Nc(e,t,n,r){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=Zt(e,t);else if(i!==" "&&i!==" "&&i!==`
33
+ `&&i!=="\r"){let o=On(e,t-1,"]",n-1,r);s.push(o[0]),t=o[1];}}if(!i)throw new H("unfinished array encountered",{toml:e,ptr:t});return [s,t]}var kg,co=b(()=>{ao();lo();Nn();Pt();kg=/^[a-zA-Z0-9-_]+[ \t]*$/;});function Pc(e,t,n,r){let s=t,i=n,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,r===0&&(l.t===1||l.t===2))return null;if(l.t===2){let p=s.length-1;s=s[p],i=i[p].c;}}if(o=e[c],(a=Object.hasOwn(s,o))&&i[o]?.t===0&&i[o]?.d)return null;a||(o==="__proto__"&&(Object.defineProperty(s,o,{enumerable:true,configurable:true,writable:true}),Object.defineProperty(i,o,{enumerable:true,configurable:true,writable:true})),i[o]={t:c<e.length-1&&r===2?3:r,d:false,i:0,c:{}});}if(l=i[o],l.t!==r&&!(r===1&&l.t===3)||(r===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,r===1)s=a?s[o]:s[o]={};else if(r===0&&a)return null;return [o,s,l.c]}function Ot(e,{maxDepth:t=1e3,integersAsBigInt:n}={}){let r={},s={},i=r,o=s;for(let a=ke(e,0);a<e.length;){if(e[a]==="["){let l=e[++a]==="[",c=ls(e,a+=+l,"]");if(l){if(e[c[1]-1]!=="]")throw new H("expected end of table declaration",{toml:e,ptr:c[1]-1});c[1]++;}let p=Pc(c[0],r,s,l?2:1);if(!p)throw new H("trying to redefine an already defined table or value",{toml:e,ptr:a});o=p[2],i=p[1],a=c[1];}else {let l=ls(e,a),c=Pc(l[0],i,o,0);if(!c)throw new H("trying to redefine an already defined table or value",{toml:e,ptr:a});let p=On(e,l[1],void 0,t,n);c[1][c[0]]=p[0],a=p[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 r}var Oc=b(()=>{co();lo();Nn();Pt();});function Ln(e){let t=typeof e;if(t==="object"){if(Array.isArray(e))return "array";if(e instanceof Date)return "date"}return t}function Ng(e){for(let t=0;t<e.length;t++)if(Ln(e[t])!=="object")return false;return e.length!=0}function uo(e){return JSON.stringify(e).replace(/\x7f/g,"\\u007f")}function po(e,t,n,r){if(n===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":r&&Number.isInteger(e)?e.toFixed(1):e.toString();if(t==="bigint"||t==="boolean")return e.toString();if(t==="string")return uo(e);if(t==="date"){if(isNaN(e.getTime()))throw new TypeError("cannot serialize invalid date");return e.toISOString()}if(t==="object")return Pg(e,n,r);if(t==="array")return Og(e,n,r)}function Pg(e,t,n){let r=Object.keys(e);if(r.length===0)return "{}";let s="{ ";for(let i=0;i<r.length;i++){let o=r[i];i&&(s+=", "),s+=Lc.test(o)?o:uo(o),s+=" = ",s+=po(e[o],Ln(e[o]),t-1,n);}return s+" }"}function Og(e,t,n){if(e.length===0)return "[]";let r="[ ";for(let s=0;s<e.length;s++){if(s&&(r+=", "),e[s]===null||e[s]===void 0)throw new TypeError("arrays cannot contain null or undefined values");r+=po(e[s],Ln(e[s]),t-1,n);}return r+" ]"}function Lg(e,t,n,r){if(n===0)throw new Error("Could not stringify the object: maximum object depth exceeded");let s="";for(let i=0;i<e.length;i++)s+=`${s&&`
35
35
  `}[[${t}]]
36
- `,s+=Xi(0,e[i],t,n,r);return s}function Xi(e,t,n,r,s){if(r===0)throw new Error("Could not stringify the object: maximum object depth exceeded");let i="",o="",a=Object.keys(t);for(let l=0;l<a.length;l++){let c=a[l];if(t[c]!==null&&t[c]!==void 0){let p=Cn(t[c]);if(p==="symbol"||p==="function")throw new TypeError(`cannot serialize values of type '${p}'`);let u=yc.test(c)?c:Ki(c);if(p==="array"&&pg(t[c]))o+=(o&&`
37
- `)+dg(t[c],n?`${n}.${u}`:u,r-1,s);else if(p==="object"){let f=n?`${n}.${u}`:u;o+=(o&&`
38
- `)+Xi(f,t[c],f,r-1,s);}else i+=u,i+=" = ",i+=zi(t[c],p,r,s),i+=`
36
+ `,s+=fo(0,e[i],t,n,r);return s}function fo(e,t,n,r,s){if(r===0)throw new Error("Could not stringify the object: maximum object depth exceeded");let i="",o="",a=Object.keys(t);for(let l=0;l<a.length;l++){let c=a[l];if(t[c]!==null&&t[c]!==void 0){let p=Ln(t[c]);if(p==="symbol"||p==="function")throw new TypeError(`cannot serialize values of type '${p}'`);let u=Lc.test(c)?c:uo(c);if(p==="array"&&Ng(t[c]))o+=(o&&`
37
+ `)+Lg(t[c],n?`${n}.${u}`:u,r-1,s);else if(p==="object"){let f=n?`${n}.${u}`:u;o+=(o&&`
38
+ `)+fo(f,t[c],f,r-1,s);}else i+=u,i+=" = ",i+=po(t[c],p,r,s),i+=`
39
39
  `;}}return e&&(i||!o)&&(i=i?`[${e}]
40
40
  ${i}`:`[${e}]`),i&&o?`${i}
41
- ${o}`:i||o}function Yi(e,{maxDepth:t=1e3,numbersAsFloat:n=false}={}){if(Cn(e)!=="object")throw new TypeError("stringify can only be called with an object");let r=Xi(0,e,"",t,n);return r[r.length-1]!==`
41
+ ${o}`:i||o}function mo(e,{maxDepth:t=1e3,numbersAsFloat:n=false}={}){if(Ln(e)!=="object")throw new TypeError("stringify can only be called with an object");let r=fo(0,e,"",t,n);return r[r.length-1]!==`
42
42
  `?r+`
43
- `:r}var yc,bc=b(()=>{yc=/^[a-z0-9-_]+$/i;});var An=b(()=>{gc();bc();Hi();Ct();});var ue,$t=b(()=>{ue={config_dir:"supabase",default_api_port:54321,default_config_format:"toml",default_config_path:"config.toml",default_db_url:"file:supabase/.temp/data.db",default_db_dir:"supabase/.temp/data"};});function zr(e,t={}){let n=Ie__default.resolve(t.cwd??process.cwd()),r=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=yg(Ie__default.resolve(e),n);for(let a of o)for(let l of i){let c=Ie__default.join(a,l),p;try{p=qr.readFileSync(c,"utf-8");}catch{continue}let u;try{u=parse(p);}catch(f){throw new Error(`Failed to parse ${c}: ${f.message}`)}for(let[f,h]of Object.entries(u))r[f]===void 0&&(r[f]=h);}}function yg(e,t){let n=[],r=e,s=Ie__default.parse(r).root;for(;n.push(r),!(r===t||r===s);){let i=Ie__default.dirname(r);if(i===r)break;r=i;}return n}var Ji=b(()=>{});function Xr(e,t=process.env){return Qi(e,t)}function Qi(e,t){if(typeof e=="string"){let n=e.match(bg);return n?t[n[1]]??"":e}if(Array.isArray(e))return e.map(n=>Qi(n,t));if(e&&typeof e=="object"){let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)return e;let r={};for(let[s,i]of Object.entries(e))r[s]=Qi(i,t);return r}return e}var bg,Zi=b(()=>{bg=/^env\((\w+)\)$/;});function Sc(e){wc=e||process.env.LITE_VERBOSE==="1";}function Me(...e){wc&&console.error(...e);}var wc,vt=b(()=>{wc=process.env.LITE_VERBOSE==="1";});async function Sg(e=""){try{let t=Ie__default.resolve(Jr(),Ie__default.join(e,"package.json")),n=await de__default.readFile(t,"utf-8");if(n)return JSON.parse(n)}catch{}return {}}async function Yr(e=""){let t=await Sg(e);return t?{name:t.name,version:t.version??"unknown"}:{name:"unknown",version:"unknown"}}function Jr(){let e=Ie__default.dirname(fileURLToPath(import.meta.url));return Ie__default.resolve(e,process.env.LOCAL?"../../../":"../../")}function eo(){return Ie__default.resolve(Jr(),"dist")}function Qr(){return Ie__default.relative(process.cwd(),eo())}async function kn(e){let t=Ie__default.relative(process.cwd(),ue.config_dir);if(!e)for(let n of Eg){let r=Ie__default.join(t,`config.${n}`);if(await de__default.access(r).then(()=>true).catch(()=>false)){e=r;break}}return e}async function ee(e){if(e){await de__default.access(e).then(()=>true).catch(()=>false)||(console.error(Rn.default.red(`Config file not found: ${e}`)),process.exit(1));return}await kn()||(console.error(Rn.default.red("No project found. Run `lite init` first.")),process.exit(1));}async function _g(e){let t=await kn(e);if(!t)return {};switch(Me(Rn.default.dim(`Using config file: ${Rn.default.cyan(`./${t}`)}`)),t.split(".").pop()){case "toml":return At(await de__default.readFile(t,"utf-8"));case "json":return JSON.parse(await de__default.readFile(t,"utf-8"));case "ts":case "mts":case "js":case "mjs":case "cjs":try{return (await import(Ie__default.join(process.cwd(),t))).default}catch(r){throw console.error("Failed to import config file",r),r}default:throw new Error(`Unsupported config file type: ${t}`)}}function xg(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 Ie__default.resolve(process.cwd(),t)}async function Zr(e){let t=await kn(e);t&&zr(Ie__default.dirname(Ie__default.resolve(t)));let n=Xr(await _g(e));if("connection"in n)return;let r=n?.db?.driver;if(r==="postgres")return;let s=n?.db?.url??(r==="pglite"?ue.default_db_dir:ue.default_db_url);return xg(s)}var Rn,Eg,Ee=b(()=>{An();$t();Ji();Zi();Rn=V(z());vt();Eg=["toml","json","ts","mts","js","mjs","cjs"];});function to(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Ec(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return new Uint8Array(n)}async function Xt(e,t=Tg,n){let r=crypto.getRandomValues(new Uint8Array(17)),s=`sb_${e}_`,i=s+to(r).slice(0,22),o=to(await Ec(`${t}|${i}`)).slice(0,8),a=`${i}_${o}`,l=await Cg(a),c=a.slice(0,s.length+5);return {key:a,hash:l,prefix:c,type:e}}async function Cg(e){return to(await Ec(e))}var Tg,no=b(()=>{Tg="supabase-self-hosted";});function es(e,t){let n="";try{n=qr.readFileSync(e,"utf-8");}catch{n="";}let r=n.length>0?n.split(`
44
- `):[];r.length>0&&r[r.length-1]===""&&r.pop();let s=r.filter(i=>{let o=i.match(/^([A-Za-z_][A-Za-z0-9_]*)=/);return !(o&&o[1]in t)});for(let[i,o]of Object.entries(t))s.push(`${i}=${o}`);qr.writeFileSync(e,s.join(`
43
+ `:r}var Lc,Ic=b(()=>{Lc=/^[a-z0-9-_]+$/i;});var In=b(()=>{Oc();Ic();oo();Pt();});var pe,Lt=b(()=>{pe={config_dir:"supabase",default_api_port:54321,default_config_format:"toml",default_config_path:"config.toml",default_db_url:"file:supabase/.temp/data.db",default_db_dir:"supabase/.temp/data"};});function cs(e,t={}){let n=Fe__default.resolve(t.cwd??process.cwd()),r=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=jg(Fe__default.resolve(e),n);for(let a of o)for(let l of i){let c=Fe__default.join(a,l),p;try{p=rs.readFileSync(c,"utf-8");}catch{continue}let u;try{u=parse(p);}catch(f){throw new Error(`Failed to parse ${c}: ${f.message}`)}for(let[f,h]of Object.entries(u))r[f]===void 0&&(r[f]=h);}}function jg(e,t){let n=[],r=e,s=Fe__default.parse(r).root;for(;n.push(r),!(r===t||r===s);){let i=Fe__default.dirname(r);if(i===r)break;r=i;}return n}var ho=b(()=>{});function us(e,t=process.env){return go(e,t)}function go(e,t){if(typeof e=="string"){let n=e.match(Fg);return n?t[n[1]]??"":e}if(Array.isArray(e))return e.map(n=>go(n,t));if(e&&typeof e=="object"){let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)return e;let r={};for(let[s,i]of Object.entries(e))r[s]=go(i,t);return r}return e}var Fg,yo=b(()=>{Fg=/^env\((\w+)\)$/;});function jc(e){Dc=e||process.env.LITE_VERBOSE==="1";}function He(...e){Dc&&console.error(...e);}var Dc,It=b(()=>{Dc=process.env.LITE_VERBOSE==="1";});async function Ug(e=""){try{let t=Fe__default.resolve(fs(),Fe__default.join(e,"package.json")),n=await he__default.readFile(t,"utf-8");if(n)return JSON.parse(n)}catch{}return {}}async function ps(e=""){let t=await Ug(e);return t?{name:t.name,version:t.version??"unknown"}:{name:"unknown",version:"unknown"}}function fs(){let e=Fe__default.dirname(fileURLToPath(import.meta.url));return Fe__default.resolve(e,process.env.LOCAL?"../../../":"../../")}function bo(){return Fe__default.resolve(fs(),"dist")}function ms(){return Fe__default.relative(process.cwd(),bo())}async function Mn(e){let t=Fe__default.relative(process.cwd(),pe.config_dir);if(!e)for(let n of Bg){let r=Fe__default.join(t,`config.${n}`);if(await he__default.access(r).then(()=>true).catch(()=>false)){e=r;break}}return e}async function ne(e){if(e){await he__default.access(e).then(()=>true).catch(()=>false)||(console.error(Fn.default.red(`Config file not found: ${e}`)),process.exit(1));return}await Mn()||(console.error(Fn.default.red("No project found. Run `lite init` first.")),process.exit(1));}async function qg(e){let t=await Mn(e);if(!t)return {};switch(He(Fn.default.dim(`Using config file: ${Fn.default.cyan(`./${t}`)}`)),t.split(".").pop()){case "toml":return Ot(await he__default.readFile(t,"utf-8"));case "json":return JSON.parse(await he__default.readFile(t,"utf-8"));case "ts":case "mts":case "js":case "mjs":case "cjs":try{return (await import(Fe__default.join(process.cwd(),t))).default}catch(r){throw console.error("Failed to import config file",r),r}default:throw new Error(`Unsupported config file type: ${t}`)}}function Hg(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 Fe__default.resolve(process.cwd(),t)}async function ds(e){let t=await Mn(e);t&&cs(Fe__default.dirname(Fe__default.resolve(t)));let n=us(await qg(e));if("connection"in n)return;let r=n?.db?.driver;if(r==="postgres")return;let s=n?.db?.url??(r==="pglite"?pe.default_db_dir:pe.default_db_url);return Hg(s)}var Fn,Bg,Te=b(()=>{In();Lt();ho();yo();Fn=K(X());It();Bg=["toml","json","ts","mts","js","mjs","cjs"];});function wo(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Fc(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return new Uint8Array(n)}async function en(e,t=Gg,n){let r=crypto.getRandomValues(new Uint8Array(17)),s=`sb_${e}_`,i=s+wo(r).slice(0,22),o=wo(await Fc(`${t}|${i}`)).slice(0,8),a=`${i}_${o}`,l=await Wg(a),c=a.slice(0,s.length+5);return {key:a,hash:l,prefix:c,type:e}}async function Wg(e){return wo(await Fc(e))}var Gg,So=b(()=>{Gg="supabase-self-hosted";});function hs(e,t){let n="";try{n=rs.readFileSync(e,"utf-8");}catch{n="";}let r=n.length>0?n.split(`
44
+ `):[];r.length>0&&r[r.length-1]===""&&r.pop();let s=r.filter(i=>{let o=i.match(/^([A-Za-z_][A-Za-z0-9_]*)=/);return !(o&&o[1]in t)});for(let[i,o]of Object.entries(t))s.push(`${i}=${o}`);rs.writeFileSync(e,s.join(`
45
45
  `)+`
46
- `);}function _c(e,t){let n;try{n=qr.readFileSync(e,"utf-8");}catch{return [...t]}return t.filter(r=>!n.match(new RegExp(`^${r}=(.+)$`,"m"))?.[1]?.replace(/^"(.*)"$|^'(.*)'$/,(o,a,l)=>a??l??"")?.trim())}var so=b(()=>{});async function rs(e={}){let t=process.cwd();if(e.recreate){console.log(oo.default.dim("Recreating database..."));try{let a=await Zr();a&&qr.existsSync(a)&&(qr.rmSync(a,{recursive:!0,force:!0}),console.log(oo.default.dim(` \u279C removed ${Ie__default.relative(t,a)}`)));}catch{}try{qr.rmSync(Ie__default.join(t,"supabase",".temp"),{recursive:!0,force:!0});}catch{}}Ce(Ie__default.join(t,"supabase"));let n=await kn(),r=!n;if(!n){let a={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,publishable_key:`env(${ts})`,secret_key:`env(${ns})`,email:{enable_confirmations:false}}};e.driver==="pglite"&&(a.db.driver="pglite",a.db.url=Ie__default.relative(process.cwd(),Ie__default.join(t,"supabase",".temp","data")));let l=e.configFormat??"toml",c=Ie__default.join(t,"supabase",`config.${l}`);l==="json"?xt(c,JSON.stringify(a)):xt(c,Yi(a));}Ce(Ie__default.join(t,"supabase",".temp")),Ce(Ie__default.join(t,"supabase","schemas"),()=>{xt(Ie__default.join(t,"supabase","schemas","schema.sql"),e.template?Ag:`-- This is a schema file for the database
47
- `);}),xt(Ie__default.join(t,"supabase","seed.sql"),e.template?$g:`-- This is a seed file for the database
48
- `);let s=Ie__default.join(t,".env"),i=_c(s,[ts,ns]),o;if(i.length>0){let a={};if(o={},i.includes(ts)){let l=await Xt("publishable");a[ts]=l.key,o.publishable=l.key;}if(i.includes(ns)){let l=await Xt("secret");a[ns]=l.key,o.secret=l.key;}es(s,a);}return {generatedKeys:o,created:r}}var oo,ts,ns,Ag,$g,ao=b(()=>{Tt();oo=V(z());An();Ee();no();so();ts="SUPABASE_PUBLISHABLE_KEY",ns="SUPABASE_SECRET_KEY";Ag=`
46
+ `);}function Mc(e,t){let n;try{n=rs.readFileSync(e,"utf-8");}catch{return [...t]}return t.filter(r=>!n.match(new RegExp(`^${r}=(.+)$`,"m"))?.[1]?.replace(/^"(.*)"$|^'(.*)'$/,(o,a,l)=>a??l??"")?.trim())}var _o=b(()=>{});async function bs(e={}){let t=process.cwd();if(e.recreate){console.log(To.default.dim("Recreating database..."));try{let a=await ds();a&&rs.existsSync(a)&&(rs.rmSync(a,{recursive:!0,force:!0}),console.log(To.default.dim(` \u279C removed ${Fe__default.relative(t,a)}`)));}catch{}try{rs.rmSync(Fe__default.join(t,"supabase",".temp"),{recursive:!0,force:!0});}catch{}}ve(Fe__default.join(t,"supabase"));let n=await Mn(),r=!n;if(!n){let a={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,publishable_key:`env(${gs})`,secret_key:`env(${ys})`,email:{enable_confirmations:false}}};e.driver==="pglite"&&(a.db.driver="pglite",a.db.url=Fe__default.relative(process.cwd(),Fe__default.join(t,"supabase",".temp","data")));let l=e.configFormat??"toml",c=Fe__default.join(t,"supabase",`config.${l}`);l==="json"?kt(c,JSON.stringify(a)):kt(c,mo(a));}ve(Fe__default.join(t,"supabase",".temp")),ve(Fe__default.join(t,"supabase","schemas"),()=>{kt(Fe__default.join(t,"supabase","schemas","schema.sql"),e.template?Vg:`-- This is a schema file for the database
47
+ `);}),kt(Fe__default.join(t,"supabase","seed.sql"),e.template?Kg:`-- This is a seed file for the database
48
+ `);let s=Fe__default.join(t,".env"),i=Mc(s,[gs,ys]),o;if(i.length>0){let a={};if(o={},i.includes(gs)){let l=await en("publishable");a[gs]=l.key,o.publishable=l.key;}if(i.includes(ys)){let l=await en("secret");a[ys]=l.key,o.secret=l.key;}hs(s,a);}return {generatedKeys:o,created:r}}var To,gs,ys,Vg,Kg,Co=b(()=>{Nt();To=K(X());In();Te();So();_o();gs="SUPABASE_PUBLISHABLE_KEY",ys="SUPABASE_SECRET_KEY";Vg=`
49
49
  create table todos (
50
50
  id serial primary key,
51
51
  title text not null,
@@ -58,14 +58,18 @@ create table todos (
58
58
  create table test (
59
59
  id serial primary key,
60
60
  name text not null
61
- )`,$g="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 Tc={};fe(Tc,{init:()=>vg});var Ze,vg,Cc=b(()=>{Ze=V(z());ao();vg=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=>{let{generatedKeys:n}=await rs({configFormat:t.format,recreate:t.recreate,driver:t.pglite?"pglite":void 0});console.log(),console.log(Ze.default.green(" \u279C"),"Project initialized",Ze.default.cyan("./"+Ie__default.relative(process.cwd(),Ie__default.join(process.cwd(),"supabase")))),(n?.publishable||n?.secret)&&(console.error(Ze.default.green(" \u279C"),"Generated API keys, written to",Ze.default.cyan("./.env")),n.publishable&&console.log(Ze.default.green(" \u279C"),"Publishable key".padEnd(19),Ze.default.cyan(n.publishable)),n.secret&&console.log(Ze.default.green(" \u279C"),"Secret key".padEnd(19),Ze.default.cyan(n.secret)));});};});function me(e){return `${Rg} ${e}`}var Rg,Ye=b(()=>{Rg="[lite]";});var Ac={};fe(Ac,{generateKeys:()=>Lg});var lo,Ng,Pg,Lg,$c=b(()=>{lo=V(z());Ye();no();so();Ng="SUPABASE_PUBLISHABLE_KEY",Pg="SUPABASE_SECRET_KEY",Lg=e=>{e.command("generate-keys").description(me("Generate a new publishable/secret API key pair")).helpGroup("Local Development:").action(async()=>{let[t,n]=await Promise.all([Xt("publishable"),Xt("secret")]),r=Ie__default.join(process.cwd(),".env");es(r,{[Ng]:t.key,[Pg]:n.key}),console.error(lo.default.green(" \u279C"),"Wrote new API keys to",lo.default.cyan("./.env")),console.log(t.key),console.log(n.key);});};});var vc=b(()=>{});var Rc=b(()=>{});function co(e,t,n=void 0){let r=typeof t=="string"?t.split(/[.[\]"]+/).filter(s=>s):t;if(r.length===0)return e;try{let[s,...i]=r;return !s||!(s in e)?n:co(e[s],i,n)}catch{if(typeof n<"u")return n;throw new Error(`Invalid path: ${r.join(".")}`)}}var kc=b(()=>{});var Nc=b(()=>{});function ss(){try{return !Nn()&&global?.process?.release?.name==="node"}catch{return false}}function Nn(){try{return typeof Bun<"u"}catch{return false}}async function is(e,t){let n=performance.now();await e();let r=performance.now();t(r-n);}var Pc=b(()=>{});function Oc(e,t={}){return e.split(`
61
+ )`,Kg="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 Bc={};me(Bc,{init:()=>zg});var st,zg,qc=b(()=>{st=K(X());Co();zg=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=>{let{generatedKeys:n}=await bs({configFormat:t.format,recreate:t.recreate,driver:t.pglite?"pglite":void 0});console.log(),console.log(st.default.green(" \u279C"),"Project initialized",st.default.cyan("./"+Fe__default.relative(process.cwd(),Fe__default.join(process.cwd(),"supabase")))),(n?.publishable||n?.secret)&&(console.error(st.default.green(" \u279C"),"Generated API keys, written to",st.default.cyan("./.env")),n.publishable&&console.log(st.default.green(" \u279C"),"Publishable key".padEnd(19),st.default.cyan(n.publishable)),n.secret&&console.log(st.default.green(" \u279C"),"Secret key".padEnd(19),st.default.cyan(n.secret)));});};});function de(e){return `${Xg} ${e}`}var Xg,Ze=b(()=>{Xg="[lite]";});var Hc={};me(Hc,{generateKeys:()=>Zg});var Ao,Yg,Qg,Zg,Gc=b(()=>{Ao=K(X());Ze();So();_o();Yg="SUPABASE_PUBLISHABLE_KEY",Qg="SUPABASE_SECRET_KEY",Zg=e=>{e.command("generate-keys").description(de("Generate a new publishable/secret API key pair")).helpGroup("Local Development:").action(async()=>{let[t,n]=await Promise.all([en("publishable"),en("secret")]),r=Fe__default.join(process.cwd(),".env");hs(r,{[Yg]:t.key,[Qg]:n.key}),console.error(Ao.default.green(" \u279C"),"Wrote new API keys to",Ao.default.cyan("./.env")),console.log(t.key),console.log(n.key);});};});var Wc=b(()=>{});var Vc=b(()=>{});function $o(e,t,n=void 0){let r=typeof t=="string"?t.split(/[.[\]"]+/).filter(s=>s):t;if(r.length===0)return e;try{let[s,...i]=r;return !s||!(s in e)?n:$o(e[s],i,n)}catch{if(typeof n<"u")return n;throw new Error(`Invalid path: ${r.join(".")}`)}}var Kc=b(()=>{});var zc=b(()=>{});function ws(){try{return !Un()&&global?.process?.release?.name==="node"}catch{return false}}function Un(){try{return typeof Bun<"u"}catch{return false}}async function Ss(e,t){let n=performance.now();await e();let r=performance.now();t(r-n);}var Xc=b(()=>{});function Yc(e,t={}){return e.split(`
62
62
  `).map(n=>n.trim()).filter(n=>n.length>0).filter(n=>!n.startsWith(t.comments??"--")).join(`
63
- `)}function Rt(e){let t=[],n="",r=0,s=e.length,i=false,o=false,a=0,l=/^create(\s+or\s+replace)?(\s+temp(orary)?)?$/i,c=u=>{Lc(u).length>0&&t.push(u.trim());},p=()=>{i=false,o=false,a=0;};for(;r<s;){let u=e[r],f=e[r+1];if(u==="-"&&f==="-"){for(;r<s&&e[r]!==`
64
- `;)n+=e[r],r++;continue}if(u==="/"&&f==="*"){for(n+="/*",r+=2;r<s&&!(e[r]==="*"&&e[r+1]==="/");)n+=e[r],r++;r<s&&(n+="*/",r+=2);continue}if(u==="'"){for(n+=u,r++;r<s;){if(e[r]==="'"&&e[r+1]==="'"){n+="''",r+=2;continue}if(n+=e[r],e[r]==="'"){r++;break}r++;}continue}if(u==='"'){for(n+=u,r++;r<s;){if(e[r]==='"'&&e[r+1]==='"'){n+='""',r+=2;continue}if(n+=e[r],e[r]==='"'){r++;break}r++;}continue}if(u==="$"){let h=e.indexOf("$",r+1);if(h!==-1){let d=e.slice(r,h+1);if(/^\$[A-Za-z_][A-Za-z0-9_]*\$$|^\$\$$/.test(d)){n+=d,r=h+1;let g=e.indexOf(d,r);g===-1?(n+=e.slice(r),r=s):(n+=e.slice(r,g+d.length),r=g+d.length);continue}}}if(/[A-Za-z_]/.test(u)){let h=r;for(;h<s&&/[A-Za-z0-9_]/.test(e[h]);)h++;let d=e.slice(r,h),m=d.toLowerCase();if(m==="trigger"&&l.test(Lc(n))?i=true:i&&m==="begin"?(o=true,a++):i&&o&&m==="case"?a++:i&&o&&m==="end"&&a>0&&a--,n+=d,r=h,i&&o&&a===0){let g=r;for(;g<s&&/\s/.test(e[g]);)g++;e[g]===";"&&(r=g+1),c(n),n="",p();}continue}if(u===";"){if(i&&o&&a>0){n+=u,r++;continue}c(n),n="",p(),r++;continue}n+=u,r++;}return c(n),t}function Lc(e){let t="",n=0,r=e.length;for(;n<r;){let s=e[n],i=e[n+1];if(s==="-"&&i==="-"){for(;n<r&&e[n]!==`
65
- `;)n++;continue}if(s==="/"&&i==="*"){for(n+=2;n<r&&!(e[n]==="*"&&e[n+1]==="/");)n++;n+=2;continue}t+=s,n++;}return t.trim()}function po(e){return (e??"").trim().toLowerCase()}function Ic(e,t){let n=t.toLowerCase();return e.startsWith("'")?n.includes("text")||n.includes("char")||n.includes("clob"):/^-?\d+$/.test(e)?n.includes("int"):n.includes("real")||n.includes("floa")||n.includes("doub")||n.includes("num")||n.includes("dec")}function os(e){let t=(e??"").replace(/\s+/g," ").replace(/"/g,"").trim().toLowerCase(),n;do n=t,t=t.replace(Og,(r,s,i)=>Ic(s,i)?s:r);while(t!==n);do n=t,t=t.replace(Ig,"$1");while(t!==n);return t}function Fg(e,t,n){let r=0;for(let s=t;s<e.length;s++){let i=e[s];if(i==="'"){for(s++;s<e.length;){if(e[s]==="'"&&e[s+1]==="'"){s+=2;continue}if(e[s]==="'")break;s++;}continue}if(i==="("?r++:i===")"&&r--,r!==0)continue;let o=e[s-1];if(!(o&&/[a-z0-9_]/.test(o)))for(let a of n){if(e.slice(s,s+a.length)!==a)continue;let l=e[s+a.length];if(!(l&&/[a-z0-9_]/.test(l)))return {index:s,kw:a}}}return null}function Ug(e){let t=[],n=0;for(;;){let c=Fg(e,n,jg);if(!c)break;t.push(c),n=c.index+c.kw.length;}if(t.length===0)return {head:e,checks:[],uniques:[]};let r=e.slice(0,t[0].index).trim(),s=r.split(/\s+/)[0]??"",i=[],o=[],a=0;for(let c=0;c<t.length;c++){let p=t[c].index,u=c+1<t.length?t[c+1].index:e.length,f=e.slice(p,u).trim();t[c].kw==="check"?o.push(f):t[c].kw==="unique"&&!f.includes("(")?a++:i.push(f);}i.sort();let l=s?Array(a).fill(`unique (${s})`):[];return {head:[r,...i].join(" ").trim(),checks:o,uniques:l}}function fo(e){let t=os(e),n=t.indexOf("(");if(n===-1)return null;let r=uo(t,n);if(r===-1)return null;let s=t.slice(n+1,r),i=t.slice(r+1).replace(/\s+/g," ").trim(),o=[];/\bstrict\b/.test(i)&&o.push("strict"),/\bwithout\s+rowid\b/.test(i)&&o.push("without rowid");let a=[],l=0,c="";for(let u=0;u<s.length;u++){let f=s[u];if(f==="'"){for(c+=f,u++;u<s.length;){if(s[u]==="'"&&s[u+1]==="'"){c+="''",u+=2;continue}if(c+=s[u],s[u]==="'")break;u++;}continue}if(f==="("?l++:f===")"&&l--,f===","&&l===0){a.push(c.trim()),c="";continue}c+=f;}c.trim().length>0&&a.push(c.trim());let p=[];for(let u of a){let f=u.replace(Dg,"");if(/^(primary key|unique|check|foreign key)\b/i.test(f)){p.push(f);continue}let{head:h,checks:d,uniques:m}=Ug(f);p.push(h,...d,...m);}return o.length>0&&p.push(`table options: ${o.join(", ")}`),p}function uo(e,t){let n=0;for(let r=t;r<e.length;r++){let s=e[r];if(s==="'"){for(r++;r<e.length;){if(e[r]==="'"&&e[r+1]==="'"){r+=2;continue}if(e[r]==="'")break;r++;}continue}if(s==="(")n++;else if(s===")"&&(n--,n===0))return r}return -1}function Mg(e){let t=0,n=-1;for(let r=0;r<e.length;r++){let s=e[r];if(s==="'"){for(r++;r<e.length;){if(e[r]==="'"&&e[r+1]==="'"){r+=2;continue}if(e[r]==="'")break;r++;}continue}s==="("?t++:s===")"?t--:t===0&&/^\s+as\s/i.test(e.slice(r))&&(n=r);}return n}function Bg(e){return e.startsWith("'")&&e.endsWith("'")&&e.length>=2||/^-?\d+(\.\d+)?$/.test(e)}function Dc(e){let t=e.trim();for(;;){if(t.startsWith("(")&&uo(t,0)===t.length-1){t=t.slice(1,-1).trim();continue}if(/^cast\s*\(/i.test(t)){let n=t.indexOf("(");if(uo(t,n)===t.length-1){let r=t.slice(n+1,-1),s=Mg(r);if(s!==-1){let i=r.slice(0,s).trim(),o=r.slice(s).replace(/^\s+as\s+/i,"").trim(),a=Dc(i);if(Bg(a)&&Ic(a,o)){t=a;continue}}}}break}return t}function mo(e){if(e==null)return null;let t=Dc(e);if(t.startsWith("'")&&t.endsWith("'")&&t.length>=2){let n=t.slice(1,-1);/(?<!')'(?!')/.test(n)||(t=n);}else if(t.startsWith('"')&&t.endsWith('"')&&t.length>=2){let n=t.slice(1,-1);n.includes('"')||(t=n);}return t}var Og,Ig,Dg,jg,kt=b(()=>{Og=/\bcast\s*\(\s*('(?:[^']|'')*'|-?\d+(?:\.\d+)?)\s+as\s+([a-z][a-z0-9 ]*)\)/g,Ig=/\(\s*('(?:[^']|'')*'|-?\d+(?:\.\d+)?)\s*\)/g;Dg=/\bconstraint\s+\S+\s+(?=(primary key|unique|check|foreign key|references)\b)/gi,jg=["generated always as","not null","primary key","foreign key","references","default","unique","check","collate","null"];});function jc(e,t){if(typeof e!="string"){throw new Error("Email must be a string");}if(!s.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 Fc(e,{panic:t=true,length:n=8,numbers:r=0,special:s=0}={}){try{if(typeof e!="string"){if(t)throw new Error("Password must be a string");return !1}if(e.length<n){if(t)throw new Error(`Password must be at least ${n} characters long`);return !1}if((e.match(/[0-9]/g)?.length??0)<r){if(t)throw new Error(`Password must contain at least ${r} numbers`);return !1}if((e.match(/[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/g)?.length??0)<s){if(t)throw new Error(`Password must contain at least ${s} special characters`);return !1}return !0}catch(i){if(t)throw i;return false}}function U(e,t='"'){return `${t}${e}${t}`}function Uc(e,t,n){if(t instanceof RegExp)return t.test(e);if(typeof t=="string")switch(!n&&t.startsWith("/")&&(n="regex"),n){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 Pn=b(()=>{});function ho(e){return typeof e=="number"?e:Number.parseInt(String(e),10)}var Mc=b(()=>{});var Bc=b(()=>{});var ct=b(()=>{vc();Rc();kc();Nc();Pc();kt();Pn();Mc();Bc();});var go,qc=b(()=>{go=(e,t,n)=>(r,s)=>{let i=-1;return o(0);async function o(a){if(a<=i)throw new Error("next() called multiple times");i=a;let l,c=false,p;if(e[a]?(p=e[a][0][0],r.req.routeIndex=a):p=a===e.length&&s||void 0,p)try{l=await p(r,()=>o(a+1));}catch(u){if(u instanceof Error&&t)r.error=u,l=await t(u,r),c=true;else throw u}else r.finalized===false&&n&&(l=await n(r));return l&&(r.finalized===false||c)&&(r.res=l),r}};});var Hc=b(()=>{});var Gc,Wc=b(()=>{Gc=Symbol();});async function Hg(e,t){let n=await e.formData();return n?Gg(n,t):{}}function Gg(e,t){let n=Object.create(null);return e.forEach((r,s)=>{t.all||s.endsWith("[]")?Wg(n,s,r):n[s]=r;}),t.dot&&Object.entries(n).forEach(([r,s])=>{r.includes(".")&&(Vg(n,r,s),delete n[r]);}),n}var Vc,Wg,Vg,Kc=b(()=>{yo();Vc=async(e,t=Object.create(null))=>{let{all:n=false,dot:r=false}=t,i=(e instanceof as?e.raw.headers:e.headers).get("Content-Type");return i?.startsWith("multipart/form-data")||i?.startsWith("application/x-www-form-urlencoded")?Hg(e,{all:n,dot:r}):{}};Wg=(e,t,n)=>{e[t]!==void 0?Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]:t.endsWith("[]")?e[t]=[n]:e[t]=n;},Vg=(e,t,n)=>{let r=e,s=t.split(".");s.forEach((i,o)=>{o===s.length-1?r[i]=n:((!r[i]||typeof r[i]!="object"||Array.isArray(r[i])||r[i]instanceof File)&&(r[i]=Object.create(null)),r=r[i]);});};});var wo,zc,Kg,zg,ls,Xc,cs,Xg,So,Yc,Nt,us,bo,Jc,Qc,Zc,Eo,Yt=b(()=>{wo=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},zc=e=>{let{groups:t,path:n}=Kg(e),r=wo(n);return zg(r,t)},Kg=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(n,r)=>{let s=`@${r}`;return t.push([s,n]),s}),{groups:t,path:e}},zg=(e,t)=>{for(let n=t.length-1;n>=0;n--){let[r]=t[n];for(let s=e.length-1;s>=0;s--)if(e[s].includes(r)){e[s]=e[s].replace(r,t[n][1]);break}}return e},ls={},Xc=(e,t)=>{if(e==="*")return "*";let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;return ls[r]||(n[2]?ls[r]=t&&t[0]!==":"&&t[0]!=="*"?[r,n[1],new RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],new RegExp(`^${n[2]}$`)]:ls[r]=[e,n[1],true]),ls[r]}return null},cs=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,n=>{try{return t(n)}catch{return n}})}},Xg=e=>cs(e,decodeURI),So=e=>{let t=e.url,n=t.indexOf("/",t.indexOf(":")+4),r=n;for(;r<t.length;r++){let s=t.charCodeAt(r);if(s===37){let i=t.indexOf("?",r),o=t.indexOf("#",r),a=i===-1?o===-1?void 0:o:o===-1?i:Math.min(i,o),l=t.slice(n,a);return Xg(l.includes("%25")?l.replace(/%25/g,"%2525"):l)}else if(s===63||s===35)break}return t.slice(n,r)},Yc=e=>{let t=So(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},Nt=(e,t,...n)=>(n.length&&(t=Nt(t,...n)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),us=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),n=[],r="";return t.forEach(s=>{if(s!==""&&!/\:/.test(s))r+="/"+s;else if(/\:/.test(s))if(/\?/.test(s)){n.length===0&&r===""?n.push("/"):n.push(r);let i=s.replace("?","");r+="/"+i,n.push(r);}else r+="/"+s;}),n.filter((s,i,o)=>o.indexOf(s)===i)},bo=e=>/[%+]/.test(e)?(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),e.indexOf("%")!==-1?cs(e,Eo):e):e,Jc=(e,t,n)=>{let r;if(!n&&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 bo(e.slice(l,c===-1?void 0:c))}else if(a==38||isNaN(a))return "";o=e.indexOf(`&${t}`,o+1);}if(r=/[%+]/.test(e),!r)return}let s={};r??=/[%+]/.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(r&&(l=bo(l)),i=o,l==="")continue;let c;a===-1?c="":(c=e.slice(a+1,o===-1?void 0:o),r&&(c=bo(c))),n?(s[l]&&Array.isArray(s[l])||(s[l]=[]),s[l].push(c)):s[l]??=c;}return t?s[t]:s},Qc=Jc,Zc=(e,t)=>Jc(e,t,true),Eo=decodeURIComponent;});var eu,as,yo=b(()=>{Hc();Wc();Kc();Yt();eu=e=>cs(e,Eo),as=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(e,t="/",n=[[]]){this.raw=e,this.path=t,this.#t=n,this.#e={};}param(e){return e?this.#n(e):this.#i()}#n(e){let t=this.#t[0][this.routeIndex][1][e],n=this.#s(t);return n&&/\%/.test(n)?eu(n):n}#i(){let e={},t=Object.keys(this.#t[0][this.routeIndex][1]);for(let n of t){let r=this.#s(this.#t[0][this.routeIndex][1][n]);r!==void 0&&(e[n]=/\%/.test(r)?eu(r):r);}return e}#s(e){return this.#t[1]?this.#t[1][e]:e}query(e){return Qc(this.url,e)}queries(e){return Zc(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((n,r)=>{t[r]=n;}),t}async parseBody(e){return this.bodyCache.parsedBody??=await Vc(this,e)}#r=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let s=Object.keys(t)[0];return s?t[s].then(i=>(s==="json"&&(i=JSON.stringify(i)),new Response(i)[e]())):t[e]=n[e]()};json(){return this.#r("text").then(e=>JSON.parse(e))}text(){return this.#r("text")}arrayBuffer(){return this.#r("arrayBuffer")}blob(){return this.#r("blob")}formData(){return this.#r("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[Gc](){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 tu,nu,_o,xo=b(()=>{tu={Stringify:1,BeforeStream:2,Stream:3},nu=(e,t)=>{let n=new String(e);return n.isEscaped=true,n.callbacks=t,n},_o=async(e,t,n,r,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:r}))).then(a=>Promise.all(a.filter(Boolean).map(l=>_o(l,t,false,r,s))).then(()=>s[0]));return n?nu(await o,i):o};});var Yg,To,Ln,ru,su=b(()=>{yo();xo();Yg="text/plain; charset=UTF-8",To=(e,t)=>({"Content-Type":e,...t}),Ln=(e,t)=>new Response(e,t),ru=class{#e;#t;env={};#n;finalized=false;error;#i;#s;#r;#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 as(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.#r||=Ln(null,{headers:this.#a??=new Headers})}set res(e){if(this.#r&&e){e=Ln(e.body,e);for(let[t,n]of this.#r.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let r=this.#r.headers.getSetCookie();e.headers.delete("set-cookie");for(let s of r)e.headers.append("set-cookie",s);}else e.headers.set(t,n);}this.#r=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,n)=>{this.finalized&&(this.#r=Ln(this.#r.body,this.#r));let r=this.#r?this.#r.headers:this.#a??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t);};status=e=>{this.#i=e;};set=(e,t)=>{this.#n??=new Map,this.#n.set(e,t);};get=e=>this.#n?this.#n.get(e):void 0;get var(){return this.#n?Object.fromEntries(this.#n):{}}#o(e,t,n){let r=this.#r?new Headers(this.#r.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"?r.append(o,a):r.set(o,a);}if(n)for(let[i,o]of Object.entries(n))if(typeof o=="string")r.set(i,o);else {r.delete(i);for(let a of o)r.append(i,a);}let s=typeof t=="number"?t:t?.status??this.#i;return Ln(e,{status:s,headers:r})}newResponse=(...e)=>this.#o(...e);body=(e,t,n)=>this.#o(e,t,n);text=(e,t,n)=>!this.#a&&!this.#i&&!t&&!n&&!this.finalized?new Response(e):this.#o(e,t,To(Yg,n));json=(e,t,n)=>this.#o(JSON.stringify(e),t,To("application/json",n));html=(e,t,n)=>{let r=s=>this.#o(s,t,To("text/html; charset=UTF-8",n));return typeof e=="object"?_o(e,tu.Stringify,false,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header("Location",/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#c??=()=>Ln(),this.#c(this))};});var ne,iu,ou,ps,fs,ut=b(()=>{ne="ALL",iu="all",ou=["get","post","put","delete","options","patch"],ps="Can not add a route since the matcher is already built.",fs=class extends Error{};});var On,Co=b(()=>{On="__COMPOSED_HANDLER";});var Jg,au,lu,uu=b(()=>{qc();su();ut();Co();Yt();Jg=e=>e.text("404 Not Found",404),au=(e,t)=>{if("getResponse"in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text("Internal Server Error",500)},lu=class cu{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(t={}){[...ou,iu].forEach(i=>{this[i]=(o,...a)=>(typeof o=="string"?this.#e=o:this.#i(i,this.#e,o),a.forEach(l=>{this.#i(i,this.#e,l);}),this);}),this.on=(i,o,...a)=>{for(let l of [o].flat()){this.#e=l;for(let c of [i].flat())a.map(p=>{this.#i(c.toUpperCase(),this.#e,p);});}return this},this.use=(i,...o)=>(typeof i=="string"?this.#e=i:(this.#e="*",o.unshift(i)),o.forEach(a=>{this.#i(ne,this.#e,a);}),this);let{strict:r,...s}=t;Object.assign(this,s),this.getPath=r??true?t.getPath??So:Yc;}#t(){let t=new cu({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#n=this.#n,t.routes=this.routes,t}#n=Jg;errorHandler=au;route(t,n){let r=this.basePath(t);return n.routes.map(s=>{let i;n.errorHandler===au?i=s.handler:(i=async(o,a)=>(await go([],n.errorHandler)(o,()=>s.handler(o,a))).res,i[On]=s.handler),r.#i(s.method,s.path,i);}),this}basePath(t){let n=this.#t();return n._basePath=Nt(this._basePath,t),n}onError=t=>(this.errorHandler=t,this);notFound=t=>(this.#n=t,this);mount(t,n,r){let s,i;r&&(typeof r=="function"?i=r:(i=r.optionHandler,r.replaceRequest===false?s=l=>l:s=r.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=Nt(this._basePath,t),c=l==="/"?0:l.length;return p=>{let u=new URL(p.url);return u.pathname=u.pathname.slice(c)||"/",new Request(u,p)}})();let a=async(l,c)=>{let p=await n(s(l.req.raw),...o(l));if(p)return p;await c();};return this.#i(ne,Nt(t,"*"),a),this}#i(t,n,r){t=t.toUpperCase(),n=Nt(this._basePath,n);let s={basePath:this._basePath,path:n,method:t,handler:r};this.router.add(t,n,[r,s]),this.routes.push(s);}#s(t,n){if(t instanceof Error)return this.errorHandler(t,n);throw t}#r(t,n,r,s){if(s==="HEAD")return (async()=>new Response(null,await this.#r(t,n,r,"GET")))();let i=this.getPath(t,{env:r}),o=this.router.match(s,i),a=new ru(t,{path:i,matchResult:o,env:r,executionCtx:n,notFoundHandler:this.#n});if(o[0].length===1){let c;try{c=o[0][0][0][0](a,async()=>{a.res=await this.#n(a);});}catch(p){return this.#s(p,a)}return c instanceof Promise?c.then(p=>p||(a.finalized?a.res:this.#n(a))).catch(p=>this.#s(p,a)):c??this.#n(a)}let l=go(o[0],this.errorHandler,this.#n);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,...n)=>this.#r(t,n[1],n[0],t.method);request=(t,n,r,s)=>t instanceof Request?this.fetch(n?new Request(t,n):t,r,s):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${Nt("/",t)}`,n),r,s));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#r(t.request,t,void 0,t.request.method));});}};});function Ao(e,t){let n=this.buildAllMatchers(),r=((s,i)=>{let o=n[s]||n[ne],a=o[2][i];if(a)return a;let l=i.match(o[0]);if(!l)return [[],ms];let c=l.indexOf("",1);return [o[1][c],l]});return this.match=r,r(e,t)}var ms,$o=b(()=>{ut();ms=[];});function Zg(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===In||e===Dn?1:t===In||t===Dn?-1:e===ds?1:t===ds?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var ds,In,Dn,Pt,Qg,pu,Ro=b(()=>{ds="[^/]+",In=".*",Dn="(?:|/.*)",Pt=Symbol(),Qg=new Set(".\\+*[^]$()");pu=class vo{#e;#t;#n=Object.create(null);insert(t,n,r,s,i){if(t.length===0){if(this.#e!==void 0)throw Pt;if(i)return;this.#e=n;return}let[o,...a]=t,l=o==="*"?a.length===0?["","",In]:["","",ds]:o==="/*"?["","",Dn]:o.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(l){let p=l[1],u=l[2]||ds;if(p&&l[2]&&(u===".*"||(u=u.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(u))))throw Pt;if(c=this.#n[u],!c){if(Object.keys(this.#n).some(f=>f!==In&&f!==Dn))throw Pt;if(i)return;c=this.#n[u]=new vo,p!==""&&(c.#t=s.varIndex++);}!i&&p!==""&&r.push([p,c.#t]);}else if(c=this.#n[o],!c){if(Object.keys(this.#n).some(p=>p.length>1&&p!==In&&p!==Dn))throw Pt;if(i)return;c=this.#n[o]=new vo;}c.insert(a,n,r,s,i);}buildRegExpStr(){let n=Object.keys(this.#n).sort(Zg).map(r=>{let s=this.#n[r];return (typeof s.#t=="number"?`(${r})@${s.#t}`:Qg.has(r)?`\\${r}`:r)+s.buildRegExpStr()});return typeof this.#e=="number"&&n.unshift(`#${this.#e}`),n.length===0?"":n.length===1?n[0]:"(?:"+n.join("|")+")"}};});var fu,mu=b(()=>{Ro();fu=class{#e={varIndex:0};#t=new pu;insert(e,t,n){let r=[],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,r,this.#e,n),r}buildRegExp(){let e=this.#t.buildRegExpStr();if(e==="")return [/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(s,i,o)=>i!==void 0?(n[++t]=Number(i),"$()"):(o!==void 0&&(r[Number(o)]=++t),"")),[new RegExp(`^${e}`),n,r]}};});function hu(e){return du[e]??=new RegExp(e==="*"?"":`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(t,n)=>n?`\\${n}`:"(?:|/.*)")}$`)}function ty(){du=Object.create(null);}function ny(e){let t=new fu,n=[];if(e.length===0)return ey;let r=e.map(c=>[!/\*|\/:/.test(c[0]),...c]).sort(([c,p],[u,f])=>c?1:u?-1:p.length-f.length),s=Object.create(null);for(let c=0,p=-1,u=r.length;c<u;c++){let[f,h,d]=r[c];f?s[h]=[d.map(([g])=>[g,Object.create(null)]),ms]:p++;let m;try{m=t.insert(h,p,f);}catch(g){throw g===Pt?new fs(h):g}f||(n[p]=d.map(([g,y])=>{let E=Object.create(null);for(y-=1;y>=0;y--){let[A,C]=m[y];E[A]=C;}return [g,E]}));}let[i,o,a]=t.buildRegExp();for(let c=0,p=n.length;c<p;c++)for(let u=0,f=n[c].length;u<f;u++){let h=n[c][u]?.[1];if(!h)continue;let d=Object.keys(h);for(let m=0,g=d.length;m<g;m++)h[d[m]]=a[h[d[m]]];}let l=[];for(let c in o)l[c]=n[o[c]];return [i,l,s]}function Jt(e,t){if(e){for(let n of Object.keys(e).sort((r,s)=>s.length-r.length))if(hu(n).test(t))return [...e[n]]}}var ey,du,hs,ko=b(()=>{ut();Yt();$o();Ro();mu();ey=[/^$/,[],Object.create(null)],du=Object.create(null);hs=class{name="RegExpRouter";#e;#t;constructor(){this.#e={[ne]:Object.create(null)},this.#t={[ne]:Object.create(null)};}add(e,t,n){let r=this.#e,s=this.#t;if(!r||!s)throw new Error(ps);r[e]||[r,s].forEach(a=>{a[e]=Object.create(null),Object.keys(a[ne]).forEach(l=>{a[e][l]=[...a[ne][l]];});}),t==="/*"&&(t="*");let i=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let a=hu(t);e===ne?Object.keys(r).forEach(l=>{r[l][t]||=Jt(r[l],t)||Jt(r[ne],t)||[];}):r[e][t]||=Jt(r[e],t)||Jt(r[ne],t)||[],Object.keys(r).forEach(l=>{(e===ne||e===l)&&Object.keys(r[l]).forEach(c=>{a.test(c)&&r[l][c].push([n,i]);});}),Object.keys(s).forEach(l=>{(e===ne||e===l)&&Object.keys(s[l]).forEach(c=>a.test(c)&&s[l][c].push([n,i]));});return}let o=us(t)||[t];for(let a=0,l=o.length;a<l;a++){let c=o[a];Object.keys(s).forEach(p=>{(e===ne||e===p)&&(s[p][c]||=[...Jt(r[p],c)||Jt(r[ne],c)||[]],s[p][c].push([n,i-l+a+1]));});}}match=Ao;buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#t).concat(Object.keys(this.#e)).forEach(t=>{e[t]||=this.#n(t);}),this.#e=this.#t=void 0,ty(),e}#n(e){let t=[],n=e===ne;return [this.#e,this.#t].forEach(r=>{let s=r[e]?Object.keys(r[e]).map(i=>[i,r[e][i]]):[];s.length!==0?(n||=true,t.push(...s)):e!==ne&&t.push(...Object.keys(r[ne]).map(i=>[i,r[ne][i]]));}),n?ny(t):null}};});var gu=b(()=>{ut();$o();ko();});var yu=b(()=>{ko();gu();});var No,bu=b(()=>{ut();No=class{name="SmartRouter";#e=[];#t=[];constructor(e){this.#e=e.routers;}add(e,t,n){if(!this.#t)throw new Error(ps);this.#t.push([e,t,n]);}match(e,t){if(!this.#t)throw new Error("Fatal error");let n=this.#e,r=this.#t,s=n.length,i=0,o;for(;i<s;i++){let a=n[i];try{for(let l=0,c=r.length;l<c;l++)a.add(...r[l]);o=a.match(e,t);}catch(l){if(l instanceof fs)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 wu=b(()=>{bu();});var jn,ry,Su,_u=b(()=>{ut();Yt();jn=Object.create(null),ry=e=>{for(let t in e)return true;return false},Su=class Eu{#e;#t;#n;#i=0;#s=jn;constructor(t,n,r){if(this.#t=r||Object.create(null),this.#e=[],t&&n){let s=Object.create(null);s[t]={handler:n,possibleKeys:[],score:0},this.#e=[s];}this.#n=[];}insert(t,n,r){this.#i=++this.#i;let s=this,i=zc(n),o=[];for(let a=0,l=i.length;a<l;a++){let c=i[a],p=i[a+1],u=Xc(c,p),f=Array.isArray(u)?u[0]:c;if(f in s.#t){s=s.#t[f],u&&o.push(u[1]);continue}s.#t[f]=new Eu,u&&(s.#n.push(u),o.push(u[1])),s=s.#t[f];}return s.#e.push({[t]:{handler:r,possibleKeys:o.filter((a,l,c)=>c.indexOf(a)===l),score:this.#i}}),s}#r(t,n,r,s,i){for(let o=0,a=n.#e.length;o<a;o++){let l=n.#e[o],c=l[r]||l[ne],p={};if(c!==void 0&&(c.params=Object.create(null),t.push(c),s!==jn||i&&i!==jn))for(let u=0,f=c.possibleKeys.length;u<f;u++){let h=c.possibleKeys[u],d=p[c.score];c.params[h]=i?.[h]&&!d?i[h]:s[h]??i?.[h],p[c.score]=true;}}}search(t,n){let r=[];this.#s=jn;let i=[this],o=wo(n),a=[],l=o.length,c=null;for(let p=0;p<l;p++){let u=o[p],f=p===l-1,h=[];for(let m=0,g=i.length;m<g;m++){let y=i[m],E=y.#t[u];E&&(E.#s=y.#s,f?(E.#t["*"]&&this.#r(r,E.#t["*"],t,y.#s),this.#r(r,E,t,y.#s)):h.push(E));for(let A=0,C=y.#n.length;A<C;A++){let v=y.#n[A],$=y.#s===jn?{}:{...y.#s};if(v==="*"){let I=y.#t["*"];I&&(this.#r(r,I,t,y.#s),I.#s=$,h.push(I));continue}let[T,x,O]=v;if(!u&&!(O instanceof RegExp))continue;let w=y.#t[T];if(O instanceof RegExp){if(c===null){c=new Array(l);let j=n[0]==="/"?1:0;for(let S=0;S<l;S++)c[S]=j,j+=o[S].length+1;}let I=n.substring(c[p]),P=O.exec(I);if(P){if($[x]=P[0],this.#r(r,w,t,y.#s,$),ry(w.#t)){w.#s=$;let j=P[0].match(/\//)?.length??0;(a[j]||=[]).push(w);}continue}}(O===true||O.test(u))&&($[x]=u,f?(this.#r(r,w,t,$,y.#s),w.#t["*"]&&this.#r(r,w.#t["*"],t,$,y.#s)):(w.#s=$,h.push(w)));}}let d=a.shift();i=d?h.concat(d):h;}return r.length>1&&r.sort((p,u)=>p.score-u.score),[r.map(({handler:p,params:u})=>[p,u])]}};});var Po,xu=b(()=>{Yt();_u();Po=class{name="TrieRouter";#e;constructor(){this.#e=new Su;}add(e,t,n){let r=us(t);if(r){for(let s=0,i=r.length;s<i;s++)this.#e.insert(e,r[s],n);return}this.#e.insert(e,t,n);}match(e,t){return this.#e.search(e,t)}};});var Tu=b(()=>{xu();});var Lo,Cu=b(()=>{uu();yu();wu();Tu();Lo=class extends lu{constructor(e={}){super(e),this.router=e.router??new No({routers:[new hs,new Po]});}};});var Au=b(()=>{Cu();});function Oo(e){return !e||typeof e!="object"?false:e.code==="EADDRINUSE"}function $u(e,t){return new Promise((n,r)=>{let s=o=>{e.off("listening",i),r(o);},i=()=>{e.off("error",s),n();};e.once("error",s),e.once("listening",i),e.listen(t);})}function Io(e){console.error(),console.error(Fn.default.red(`Cannot start server: Port ${Fn.default.bold(String(e))} is already in use.`)),console.error(Fn.default.red(`Stop the process using that port, or set a different ${Fn.default.bold("api.port")} in your config.`)),console.error(),process.exit(1);}var Fn,vu=b(()=>{Fn=V(z());});function Un(e){let t=[],n=e??"",r=n.toLowerCase(),s=new TextEncoder().encode(n).length;if(!n)return t.push("auth.jwt_secret is empty"),{strong:false,reasons:t};sy.has(n)&&t.push(`matches Supalite development default "${n}"`),s<32&&t.push(`is ${s} bytes; use at least 32 bytes for production secrets`),[/[a-z]/.test(n),/[A-Z]/.test(n),/[0-9]/.test(n),/[^A-Za-z0-9]/.test(n)].filter(Boolean).length<3&&t.push("uses too little character variety"),/^(.)\1{7,}$/.test(n)?t.push("is one repeated character"):oy(n)&&t.push("contains an obvious repeated pattern");let o=iy.find(a=>r.includes(a));return o&&t.push(`contains placeholder term "${o}"`),{strong:t.length===0,reasons:t}}function oy(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 sy,iy,Do=b(()=>{sy=new Set(["unsafe-secret-change-me","dev-secret-change-me"]),iy=["change-me","changeme","secret","password","passwd","test","dev"];});function jo(e,t){t&&Object.defineProperty(e,ay,{value:t,enumerable:false,configurable:false,writable:false});}var ay,Ru=b(()=>{ay=Symbol("lite-peer-address");});var ku,Nu=b(()=>{ku=/^\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 Uo,Pu,ly,Fo,Mo=b(()=>{Uo=(e,t=Fo)=>{let n=/\.([a-zA-Z0-9]+?)$/,r=e.match(n);if(!r)return;let s=t[r[1]];return s&&s.startsWith("text")&&(s+="; charset=utf-8"),s},Pu=e=>{for(let t in Fo)if(Fo[t]===e)return t},ly={aac:"audio/aac",avi:"video/x-msvideo",avif:"image/avif",av1:"video/av1",bin:"application/octet-stream",bmp:"image/bmp",css:"text/css",csv:"text/csv",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gif:"image/gif",gz:"application/gzip",htm:"text/html",html:"text/html",ico:"image/x-icon",ics:"text/calendar",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript",json:"application/json",jsonld:"application/ld+json",map:"application/json",mid:"audio/x-midi",midi:"audio/x-midi",mjs:"text/javascript",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",pdf:"application/pdf",png:"image/png",rtf:"application/rtf",svg:"image/svg+xml",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain",wasm:"application/wasm",webm:"video/webm",weba:"audio/webm",webmanifest:"application/manifest+json",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xml:"application/xml",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2",gltf:"model/gltf+json",glb:"model/gltf-binary"},Fo=ly;});var Lu,Ou=b(()=>{Lu=(...e)=>{let t=e.filter(s=>s!=="").join("/");t=t.replace(/(?<=\/)\/+/g,"");let n=t.split("/"),r=[];for(let s of n)s===".."&&r.length>0&&r.at(-1)!==".."?r.pop():s!=="."&&r.push(s);return r.join("/")||"."};});var Iu,cy,uy,Du,ju=b(()=>{Nu();Mo();Ou();Iu={br:".br",zstd:".zst",gzip:".gz"},cy=Object.keys(Iu),uy="index.html",Du=e=>{let t=e.root??"./",n=e.path,r=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=r(t,!n&&e.rewriteRequestPath?e.rewriteRequestPath(o):o);e.isDir&&await e.isDir(a)&&(a=r(a,uy));let l=e.getContent,c=await l(a,s);if(c instanceof Response)return s.newResponse(c.body,c);if(c){let p=e.mimes&&Uo(a,e.mimes)||Uo(a);if(s.header("Content-Type",p||"application/octet-stream"),e.precompressed&&(!p||ku.test(p))){let u=new Set(s.req.header("Accept-Encoding")?.split(",").map(f=>f.trim()));for(let f of cy){if(!u.has(f))continue;let h=await l(a+Iu[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 Fu,Uu=b(()=>{ju();Fu=e=>async function(n,r){return Du({...e,getContent:async o=>{let a=Bun.file(o);return await a.exists()?a:null},join:join,isDir:async o=>{let a;try{a=(await stat$1(o)).isDirectory();}catch{}return a}})(n,r)};});var Mu=b(()=>{});var Bu,qu=b(()=>{Mu();Bu=(e,t)=>{for(let[n,r]of Object.entries(t)){let s=new RegExp("/:"+n+"(?:{[^/]+})?\\??");e=e.replace(s,r?`/${r}`:"");}return e};});var my,Hu,Gu=b(()=>{my=1024,Hu=({concurrency:e,interval:t}={})=>{if(e||=my,e===1/0)return {run:async s=>s()};let n=new Set,r=async(s,i,o)=>{if(n.size>=e)return i||=new Promise(c=>o=c),setTimeout(()=>r(s,i,o)),i;let a={};n.add(a);let l=await s();return t?setTimeout(()=>n.delete(a),t):n.delete(a),o?(o(l),i):l};return {run:r}};});var Wu,Bo,Vu=b(()=>{Co();Wu=e=>e.length>1,Bo=e=>e[On]?Bo(e[On]):e;});var Ku,dy,hy,gy,yy,Mn,zu,qo,Ho=b(()=>{ut();Vu();Ku=e=>e.split(/[\/\\]/).slice(0,-1).join("/"),dy=e=>e.replace(/(\\)/g,"/").replace(/\/$/g,""),hy=(e,t)=>{e.length===0||t?e.push(".."):e.pop();},gy=(e,t)=>{e=e.replace(/^\.(?!.)/,""),e!==""&&t.push(e);},yy=(e,t)=>{let n=false;for(let r of e)r===".."?(hy(t,n),n=true):(gy(r,t),n=false);},Mn=(...e)=>{e=e.map(dy);let t=[];return yy(e.join("/").split("/"),t),(e[0][0]==="/"?"/":"")+t.join("/")},zu=e=>e.routes.reduce((t,{method:n,handler:r,path:s})=>{let i=Bo(r);return ["GET",ne].includes(n)&&!Wu(i)&&t.push({path:s}),t},[]),qo=e=>e.split("/").some(t=>t.startsWith(":")||t.includes("*"));});var Xu,gs,Go=b(()=>{Ho();Xu="HONO_SSG_CONTEXT",gs="x-hono-disable-ssg",(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[gs]:"true"}})}catch{return null}})();});var Yu=b(()=>{xo();});var Wo,Vo=b(()=>{Yu();Wo=()=>({afterResponseHook:e=>e.status!==200?false:e});});var by,wy,Sy,Ey,_y,xy,Ty,Cy,Ay,$y,vy,Ju,Ry,Qu,Zu=b(()=>{qu();Gu();Mo();Go();Vo();Ho();by=2,wy="text/plain",Sy="./static",Ey=(e,t,n,r)=>{let s=Ty(n,r);return e.endsWith(`.${s}`)?Mn(t,e):e==="/"?Mn(t,`index.${s}`):e.endsWith("/")?Mn(t,e,`index.${s}`):Mn(t,`${e}.${s}`)},_y=async e=>{let t=e.headers.get("Content-Type");try{return t?.includes("text")||t?.includes("json")?await e.text():await e.arrayBuffer()}catch(n){throw new Error(`Error processing response: ${n instanceof Error?n.message:"Unknown error"}`)}},xy={"text/html":"html","text/xml":"xml","application/xml":"xml","application/yaml":"yaml"},Ty=(e,t)=>{let n=t||xy;return e in n?n[e]:Pu(e)||"html"},Cy=e=>Array.isArray(e)?async t=>{let n=t;for(let r of e){let s=await r(n);if(s===false)return false;s instanceof Request&&(n=s);}return n}:e,Ay=e=>Array.isArray(e)?async t=>{let n=t;for(let r of e){let s=await r(n);if(s===false)return false;s instanceof Response&&(n=s);}return n}:e,$y=(e,t,n)=>Array.isArray(e)?async r=>{for(let s of e)await s(r,t,n);}:e,vy=function*(e,t,n,r){let s="http://localhost",i=Hu({concurrency:r});for(let o of zu(e)){let a=new URL(o.path,s).toString(),l=new Request(a);yield new Promise(async(c,p)=>{try{if(t){let f=await t(l);if(!f){c(void 0);return}l=f;}if(await i.run(()=>e.fetch(l)),!l.ssgParams){if(qo(o.path)){c(void 0);return}l.ssgParams=[{}];}let u={method:l.method,headers:l.headers};c((function*(){for(let f of l.ssgParams)yield new Promise(async(h,d)=>{try{let m=Bu(o.path,f),g=await i.run(()=>e.request(m,u,{[Xu]:!0}));if(g.headers.get(gs)){h(void 0);return}if(n){let A=await n(g);if(!A){h(void 0);return}g=A;}let y=g.headers.get("Content-Type")?.split(";")[0]||wy,E=await _y(g);h({routePath:m,mimeType:y,content:E});}catch(m){d(m);}});})());}catch(u){p(u);}});}},Ju=new Set,Ry=async(e,t,n,r)=>{let s=await e;if(!s)return;let{routePath:i,content:o,mimeType:a}=s,l=Ey(i,n,a,r),c=Ku(l);return Ju.has(c)||(await t.mkdir(c,{recursive:true}),Ju.add(c)),typeof o=="string"?await t.writeFile(l,o):o instanceof ArrayBuffer&&await t.writeFile(l,new Uint8Array(o)),l},Qu=async(e,t,n)=>{let r,s=[],i=[],o=n?.plugins||[Wo()],a=[],l=[],c=[];n?.beforeRequestHook&&a.push(...Array.isArray(n.beforeRequestHook)?n.beforeRequestHook:[n.beforeRequestHook]),n?.afterResponseHook&&l.push(...Array.isArray(n.afterResponseHook)?n.afterResponseHook:[n.afterResponseHook]),n?.afterGenerateHook&&c.push(...Array.isArray(n.afterGenerateHook)?n.afterGenerateHook:[n.afterGenerateHook]);for(let p of o)p.beforeRequestHook&&a.push(...Array.isArray(p.beforeRequestHook)?p.beforeRequestHook:[p.beforeRequestHook]),p.afterResponseHook&&l.push(...Array.isArray(p.afterResponseHook)?p.afterResponseHook:[p.afterResponseHook]),p.afterGenerateHook&&c.push(...Array.isArray(p.afterGenerateHook)?p.afterGenerateHook:[p.afterGenerateHook]);try{let p=n?.dir??Sy,u=n?.concurrency??by,f=Cy(a.length>0?a:[g=>g]),h=Ay(l.length>0?l:[g=>g]),d=vy(e,f,h,u);for(let g of d)s.push(g.then(y=>{if(y)for(let E of y)i.push(Ry(E,t,p,n?.extensionMap).catch(A=>A));}));await Promise.all(s);let m=[];for(let g of i){let y=await g;if(typeof y=="string")m.push(y);else if(y)throw y}r={success:!0,files:m};}catch(p){let u=p instanceof Error?p:new Error(String(p));r={success:false,files:[],error:u};}return c.length>0&&await $y(c,t,n)(r,t,n),r};});var ep=b(()=>{Zu();Go();Vo();});var ky,Ko,tp,np=b(()=>{ep();(({write:ky}=Bun)),Ko={writeFile:async(e,t)=>{await ky(e,t);},mkdir:async()=>{}},tp=async(e,t)=>Qu(e,Ko,t);});var rp,sp,ip,op=b(()=>{rp=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);}},sp=e=>new MessageEvent("message",{data:e}),ip=e=>((...t)=>{if(typeof t[0]=="function"){let[n,r]=t;return async function(i,o){let a=await n(i),l=await e(i,a,r);if(l)return l;await o();}}else {let[n,r,s]=t;return (async()=>{let i=await e(n,r,s);if(!i)throw new Error("Failed to upgrade WebSocket");return i})()}});});var Qt,ys=b(()=>{Qt=e=>"server"in e.env?e.env.server:e.env;});var zo,Xo,Yo,ap,lp=b(()=>{op();ys();zo=e=>new rp({send:(t,n)=>{e.send(t,n?.compress);},raw:e,readyState:e.readyState,url:e.data.url,protocol:e.data.protocol,close(t,n){e.close(t,n);}}),Xo=ip((e,t)=>{let n=Qt(e);if(!n)throw new TypeError("env has to include the 2nd argument of fetch.");if(n.upgrade(e.req.raw,{data:{events:t,url:new URL(e.req.url),protocol:e.req.url}}))return new Response(null)}),Yo={open(e){let t=e.data.events;t.onOpen&&t.onOpen(new Event("open"),zo(e));},close(e,t,n){let r=e.data.events;r.onClose&&r.onClose(new CloseEvent("close",{code:t,reason:n}),zo(e));},message(e,t){let n=e.data.events;if(n.onMessage){let r=typeof t=="string"?t:t.buffer;n.onMessage(sp(r),zo(e));}}},ap=()=>({upgradeWebSocket:Xo,websocket:Yo});});var cp,up=b(()=>{ys();cp=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 n=t.requestIP(e.req.raw);return n?{remote:{address:n.address,addressType:n.family==="IPv6"||n.family==="IPv4"?n.family:void 0,port:n.port}}:{remote:{}}};});var pp={};fe(pp,{bunFileSystemModule:()=>Ko,createBunWebSocket:()=>ap,getBunServer:()=>Qt,getConnInfo:()=>cp,serveStatic:()=>Fu,toSSG:()=>tp,upgradeWebSocket:()=>Xo,websocket:()=>Yo});var fp=b(()=>{Uu();np();lp();up();ys();});async function bs(e,t={port:3e3}){if(e.config.auth?.enabled){let s=Un(e.config.auth.jwt_secret);s.strong||console.warn(hp.default.yellow(`[auth] auth.jwt_secret is weak \u2014 do not use it in production:
66
- `+s.reasons.map(i=>` - it ${i}`).join(`
63
+ `)}function et(e){let t=[],n="",r=0,s=e.length,i=false,o=false,a=0,l=/^create(\s+or\s+replace)?(\s+temp(orary)?)?$/i,c=u=>{Jc(u).length>0&&t.push(u.trim());},p=()=>{i=false,o=false,a=0;};for(;r<s;){let u=e[r],f=e[r+1];if(u==="-"&&f==="-"){for(;r<s&&e[r]!==`
64
+ `;)n+=e[r],r++;continue}if(u==="/"&&f==="*"){for(n+="/*",r+=2;r<s&&!(e[r]==="*"&&e[r+1]==="/");)n+=e[r],r++;r<s&&(n+="*/",r+=2);continue}if(u==="'"){for(n+=u,r++;r<s;){if(e[r]==="'"&&e[r+1]==="'"){n+="''",r+=2;continue}if(n+=e[r],e[r]==="'"){r++;break}r++;}continue}if(u==='"'){for(n+=u,r++;r<s;){if(e[r]==='"'&&e[r+1]==='"'){n+='""',r+=2;continue}if(n+=e[r],e[r]==='"'){r++;break}r++;}continue}if(u==="$"){let h=e.indexOf("$",r+1);if(h!==-1){let m=e.slice(r,h+1);if(/^\$[A-Za-z_][A-Za-z0-9_]*\$$|^\$\$$/.test(m)){n+=m,r=h+1;let g=e.indexOf(m,r);g===-1?(n+=e.slice(r),r=s):(n+=e.slice(r,g+m.length),r=g+m.length);continue}}}if(/[A-Za-z_]/.test(u)){let h=r;for(;h<s&&/[A-Za-z0-9_]/.test(e[h]);)h++;let m=e.slice(r,h),d=m.toLowerCase();if(d==="trigger"&&l.test(Jc(n))?i=true:i&&d==="begin"?(o=true,a++):i&&o&&d==="case"?a++:i&&o&&d==="end"&&a>0&&a--,n+=m,r=h,i&&o&&a===0){let g=r;for(;g<s&&/\s/.test(e[g]);)g++;e[g]===";"&&(r=g+1),c(n),n="",p();}continue}if(u===";"){if(i&&o&&a>0){n+=u,r++;continue}c(n),n="",p(),r++;continue}n+=u,r++;}return c(n),t}function Jc(e){let t="",n=0,r=e.length;for(;n<r;){let s=e[n],i=e[n+1];if(s==="-"&&i==="-"){for(;n<r&&e[n]!==`
65
+ `;)n++;continue}if(s==="/"&&i==="*"){for(n+=2;n<r&&!(e[n]==="*"&&e[n+1]==="/");)n++;n+=2;continue}t+=s,n++;}return t.trim()}function vo(e){return (e??"").trim().toLowerCase()}function Qc(e,t){let n=t.toLowerCase();return e.startsWith("'")?n.includes("text")||n.includes("char")||n.includes("clob"):/^-?\d+$/.test(e)?n.includes("int"):n.includes("real")||n.includes("floa")||n.includes("doub")||n.includes("num")||n.includes("dec")}function Es(e){let t=(e??"").replace(/\s+/g," ").replace(/"/g,"").trim().toLowerCase(),n;do n=t,t=t.replace(ey,(r,s,i)=>Qc(s,i)?s:r);while(t!==n);do n=t,t=t.replace(ty,"$1");while(t!==n);return t}function sy(e,t,n){let r=0;for(let s=t;s<e.length;s++){let i=e[s];if(i==="'"){for(s++;s<e.length;){if(e[s]==="'"&&e[s+1]==="'"){s+=2;continue}if(e[s]==="'")break;s++;}continue}if(i==="("?r++:i===")"&&r--,r!==0)continue;let o=e[s-1];if(!(o&&/[a-z0-9_]/.test(o)))for(let a of n){if(e.slice(s,s+a.length)!==a)continue;let l=e[s+a.length];if(!(l&&/[a-z0-9_]/.test(l)))return {index:s,kw:a}}}return null}function iy(e){let t=[],n=0;for(;;){let c=sy(e,n,ry);if(!c)break;t.push(c),n=c.index+c.kw.length;}if(t.length===0)return {head:e,checks:[],uniques:[]};let r=e.slice(0,t[0].index).trim(),s=r.split(/\s+/)[0]??"",i=[],o=[],a=0;for(let c=0;c<t.length;c++){let p=t[c].index,u=c+1<t.length?t[c+1].index:e.length,f=e.slice(p,u).trim();t[c].kw==="check"?o.push(f):t[c].kw==="unique"&&!f.includes("(")?a++:i.push(f);}i.sort();let l=s?Array(a).fill(`unique (${s})`):[];return {head:[r,...i].join(" ").trim(),checks:o,uniques:l}}function ko(e){let t=Es(e),n=t.indexOf("(");if(n===-1)return null;let r=Ro(t,n);if(r===-1)return null;let s=t.slice(n+1,r),i=t.slice(r+1).replace(/\s+/g," ").trim(),o=[];/\bstrict\b/.test(i)&&o.push("strict"),/\bwithout\s+rowid\b/.test(i)&&o.push("without rowid");let a=[],l=0,c="";for(let u=0;u<s.length;u++){let f=s[u];if(f==="'"){for(c+=f,u++;u<s.length;){if(s[u]==="'"&&s[u+1]==="'"){c+="''",u+=2;continue}if(c+=s[u],s[u]==="'")break;u++;}continue}if(f==="("?l++:f===")"&&l--,f===","&&l===0){a.push(c.trim()),c="";continue}c+=f;}c.trim().length>0&&a.push(c.trim());let p=[];for(let u of a){let f=u.replace(ny,"");if(/^(primary key|unique|check|foreign key)\b/i.test(f)){p.push(f);continue}let{head:h,checks:m,uniques:d}=iy(f);p.push(h,...m,...d);}return o.length>0&&p.push(`table options: ${o.join(", ")}`),p}function Ro(e,t){let n=0;for(let r=t;r<e.length;r++){let s=e[r];if(s==="'"){for(r++;r<e.length;){if(e[r]==="'"&&e[r+1]==="'"){r+=2;continue}if(e[r]==="'")break;r++;}continue}if(s==="(")n++;else if(s===")"&&(n--,n===0))return r}return -1}function oy(e){let t=0,n=-1;for(let r=0;r<e.length;r++){let s=e[r];if(s==="'"){for(r++;r<e.length;){if(e[r]==="'"&&e[r+1]==="'"){r+=2;continue}if(e[r]==="'")break;r++;}continue}s==="("?t++:s===")"?t--:t===0&&/^\s+as\s/i.test(e.slice(r))&&(n=r);}return n}function ay(e){return e.startsWith("'")&&e.endsWith("'")&&e.length>=2||/^-?\d+(\.\d+)?$/.test(e)}function Zc(e){let t=e.trim();for(;;){if(t.startsWith("(")&&Ro(t,0)===t.length-1){t=t.slice(1,-1).trim();continue}if(/^cast\s*\(/i.test(t)){let n=t.indexOf("(");if(Ro(t,n)===t.length-1){let r=t.slice(n+1,-1),s=oy(r);if(s!==-1){let i=r.slice(0,s).trim(),o=r.slice(s).replace(/^\s+as\s+/i,"").trim(),a=Zc(i);if(ay(a)&&Qc(a,o)){t=a;continue}}}}break}return t}function No(e){if(e==null)return null;let t=Zc(e);if(t.startsWith("'")&&t.endsWith("'")&&t.length>=2){let n=t.slice(1,-1);/(?<!')'(?!')/.test(n)||(t=n);}else if(t.startsWith('"')&&t.endsWith('"')&&t.length>=2){let n=t.slice(1,-1);n.includes('"')||(t=n);}return t}var ey,ty,ny,ry,ht=b(()=>{ey=/\bcast\s*\(\s*('(?:[^']|'')*'|-?\d+(?:\.\d+)?)\s+as\s+([a-z][a-z0-9 ]*)\)/g,ty=/\(\s*('(?:[^']|'')*'|-?\d+(?:\.\d+)?)\s*\)/g;ny=/\bconstraint\s+\S+\s+(?=(primary key|unique|check|foreign key|references)\b)/gi,ry=["generated always as","not null","primary key","foreign key","references","default","unique","check","collate","null"];});function eu(e,t){if(typeof e!="string"){throw new Error("Email must be a string");}if(!s.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 tu(e,{panic:t=true,length:n=8,numbers:r=0,special:s=0}={}){try{if(typeof e!="string"){if(t)throw new Error("Password must be a string");return !1}if(e.length<n){if(t)throw new Error(`Password must be at least ${n} characters long`);return !1}if((e.match(/[0-9]/g)?.length??0)<r){if(t)throw new Error(`Password must contain at least ${r} 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 B(e,t='"'){return `${t}${e}${t}`}function nu(e,t,n){if(t instanceof RegExp)return t.test(e);if(typeof t=="string")switch(!n&&t.startsWith("/")&&(n="regex"),n){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 Bn=b(()=>{});function Po(e){return typeof e=="number"?e:Number.parseInt(String(e),10)}var ru=b(()=>{});var su=b(()=>{});function cy(e){let t=e.trim().toLowerCase();if(t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1)),t=t.split("%")[0],t==="::1")return true;t.startsWith("::ffff:")&&(t=t.slice(7));let n=t.split(".");return n.length===4&&n.every(r=>/^\d{1,3}$/.test(r)&&Number(r)<=255)&&Number(n[0])===127}function iu(e){let t=e.trim().toLowerCase();return t==="localhost"||cy(t)}var Oo=b(()=>{});var gt=b(()=>{Wc();Vc();Kc();zc();Xc();ht();Bn();ru();su();Oo();});var Lo,ou=b(()=>{Lo=(e,t,n)=>(r,s)=>{let i=-1;return o(0);async function o(a){if(a<=i)throw new Error("next() called multiple times");i=a;let l,c=false,p;if(e[a]?(p=e[a][0][0],r.req.routeIndex=a):p=a===e.length&&s||void 0,p)try{l=await p(r,()=>o(a+1));}catch(u){if(u instanceof Error&&t)r.error=u,l=await t(u,r),c=true;else throw u}else r.finalized===false&&n&&(l=await n(r));return l&&(r.finalized===false||c)&&(r.res=l),r}};});var au=b(()=>{});var lu,cu=b(()=>{lu=Symbol();});async function uy(e,t){let n=await e.formData();return n?py(n,t):{}}function py(e,t){let n=Object.create(null);return e.forEach((r,s)=>{t.all||s.endsWith("[]")?fy(n,s,r):n[s]=r;}),t.dot&&Object.entries(n).forEach(([r,s])=>{r.includes(".")&&(my(n,r,s),delete n[r]);}),n}var uu,fy,my,pu=b(()=>{Io();uu=async(e,t=Object.create(null))=>{let{all:n=false,dot:r=false}=t,i=(e instanceof _s?e.raw.headers:e.headers).get("Content-Type");return i?.startsWith("multipart/form-data")||i?.startsWith("application/x-www-form-urlencoded")?uy(e,{all:n,dot:r}):{}};fy=(e,t,n)=>{e[t]!==void 0?Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]:t.endsWith("[]")?e[t]=[n]:e[t]=n;},my=(e,t,n)=>{let r=e,s=t.split(".");s.forEach((i,o)=>{o===s.length-1?r[i]=n:((!r[i]||typeof r[i]!="object"||Array.isArray(r[i])||r[i]instanceof File)&&(r[i]=Object.create(null)),r=r[i]);});};});var jo,fu,dy,hy,xs,mu,Ts,gy,Fo,du,Dt,Cs,Do,hu,gu,yu,Mo,tn=b(()=>{jo=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},fu=e=>{let{groups:t,path:n}=dy(e),r=jo(n);return hy(r,t)},dy=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(n,r)=>{let s=`@${r}`;return t.push([s,n]),s}),{groups:t,path:e}},hy=(e,t)=>{for(let n=t.length-1;n>=0;n--){let[r]=t[n];for(let s=e.length-1;s>=0;s--)if(e[s].includes(r)){e[s]=e[s].replace(r,t[n][1]);break}}return e},xs={},mu=(e,t)=>{if(e==="*")return "*";let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;return xs[r]||(n[2]?xs[r]=t&&t[0]!==":"&&t[0]!=="*"?[r,n[1],new RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],new RegExp(`^${n[2]}$`)]:xs[r]=[e,n[1],true]),xs[r]}return null},Ts=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,n=>{try{return t(n)}catch{return n}})}},gy=e=>Ts(e,decodeURI),Fo=e=>{let t=e.url,n=t.indexOf("/",t.indexOf(":")+4),r=n;for(;r<t.length;r++){let s=t.charCodeAt(r);if(s===37){let i=t.indexOf("?",r),o=t.indexOf("#",r),a=i===-1?o===-1?void 0:o:o===-1?i:Math.min(i,o),l=t.slice(n,a);return gy(l.includes("%25")?l.replace(/%25/g,"%2525"):l)}else if(s===63||s===35)break}return t.slice(n,r)},du=e=>{let t=Fo(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},Dt=(e,t,...n)=>(n.length&&(t=Dt(t,...n)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),Cs=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),n=[],r="";return t.forEach(s=>{if(s!==""&&!/\:/.test(s))r+="/"+s;else if(/\:/.test(s))if(/\?/.test(s)){n.length===0&&r===""?n.push("/"):n.push(r);let i=s.replace("?","");r+="/"+i,n.push(r);}else r+="/"+s;}),n.filter((s,i,o)=>o.indexOf(s)===i)},Do=e=>/[%+]/.test(e)?(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),e.indexOf("%")!==-1?Ts(e,Mo):e):e,hu=(e,t,n)=>{let r;if(!n&&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 Do(e.slice(l,c===-1?void 0:c))}else if(a==38||isNaN(a))return "";o=e.indexOf(`&${t}`,o+1);}if(r=/[%+]/.test(e),!r)return}let s={};r??=/[%+]/.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(r&&(l=Do(l)),i=o,l==="")continue;let c;a===-1?c="":(c=e.slice(a+1,o===-1?void 0:o),r&&(c=Do(c))),n?(s[l]&&Array.isArray(s[l])||(s[l]=[]),s[l].push(c)):s[l]??=c;}return t?s[t]:s},gu=hu,yu=(e,t)=>hu(e,t,true),Mo=decodeURIComponent;});var bu,_s,Io=b(()=>{au();cu();pu();tn();bu=e=>Ts(e,Mo),_s=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(e,t="/",n=[[]]){this.raw=e,this.path=t,this.#t=n,this.#e={};}param(e){return e?this.#n(e):this.#i()}#n(e){let t=this.#t[0][this.routeIndex][1][e],n=this.#s(t);return n&&/\%/.test(n)?bu(n):n}#i(){let e={},t=Object.keys(this.#t[0][this.routeIndex][1]);for(let n of t){let r=this.#s(this.#t[0][this.routeIndex][1][n]);r!==void 0&&(e[n]=/\%/.test(r)?bu(r):r);}return e}#s(e){return this.#t[1]?this.#t[1][e]:e}query(e){return gu(this.url,e)}queries(e){return yu(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((n,r)=>{t[r]=n;}),t}async parseBody(e){return this.bodyCache.parsedBody??=await uu(this,e)}#r=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let s=Object.keys(t)[0];return s?t[s].then(i=>(s==="json"&&(i=JSON.stringify(i)),new Response(i)[e]())):t[e]=n[e]()};json(){return this.#r("text").then(e=>JSON.parse(e))}text(){return this.#r("text")}arrayBuffer(){return this.#r("arrayBuffer")}blob(){return this.#r("blob")}formData(){return this.#r("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[lu](){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 wu,Su,Uo,Bo=b(()=>{wu={Stringify:1,BeforeStream:2,Stream:3},Su=(e,t)=>{let n=new String(e);return n.isEscaped=true,n.callbacks=t,n},Uo=async(e,t,n,r,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:r}))).then(a=>Promise.all(a.filter(Boolean).map(l=>Uo(l,t,false,r,s))).then(()=>s[0]));return n?Su(await o,i):o};});var yy,qo,qn,Eu,_u=b(()=>{Io();Bo();yy="text/plain; charset=UTF-8",qo=(e,t)=>({"Content-Type":e,...t}),qn=(e,t)=>new Response(e,t),Eu=class{#e;#t;env={};#n;finalized=false;error;#i;#s;#r;#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 _s(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.#r||=qn(null,{headers:this.#a??=new Headers})}set res(e){if(this.#r&&e){e=qn(e.body,e);for(let[t,n]of this.#r.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let r=this.#r.headers.getSetCookie();e.headers.delete("set-cookie");for(let s of r)e.headers.append("set-cookie",s);}else e.headers.set(t,n);}this.#r=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,n)=>{this.finalized&&(this.#r=qn(this.#r.body,this.#r));let r=this.#r?this.#r.headers:this.#a??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t);};status=e=>{this.#i=e;};set=(e,t)=>{this.#n??=new Map,this.#n.set(e,t);};get=e=>this.#n?this.#n.get(e):void 0;get var(){return this.#n?Object.fromEntries(this.#n):{}}#o(e,t,n){let r=this.#r?new Headers(this.#r.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"?r.append(o,a):r.set(o,a);}if(n)for(let[i,o]of Object.entries(n))if(typeof o=="string")r.set(i,o);else {r.delete(i);for(let a of o)r.append(i,a);}let s=typeof t=="number"?t:t?.status??this.#i;return qn(e,{status:s,headers:r})}newResponse=(...e)=>this.#o(...e);body=(e,t,n)=>this.#o(e,t,n);text=(e,t,n)=>!this.#a&&!this.#i&&!t&&!n&&!this.finalized?new Response(e):this.#o(e,t,qo(yy,n));json=(e,t,n)=>this.#o(JSON.stringify(e),t,qo("application/json",n));html=(e,t,n)=>{let r=s=>this.#o(s,t,qo("text/html; charset=UTF-8",n));return typeof e=="object"?Uo(e,wu.Stringify,false,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header("Location",/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#c??=()=>qn(),this.#c(this))};});var ie,xu,Tu,As,$s,yt=b(()=>{ie="ALL",xu="all",Tu=["get","post","put","delete","options","patch"],As="Can not add a route since the matcher is already built.",$s=class extends Error{};});var Hn,Ho=b(()=>{Hn="__COMPOSED_HANDLER";});var by,Cu,Au,Ru=b(()=>{ou();_u();yt();Ho();tn();by=e=>e.text("404 Not Found",404),Cu=(e,t)=>{if("getResponse"in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text("Internal Server Error",500)},Au=class $u{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(t={}){[...Tu,xu].forEach(i=>{this[i]=(o,...a)=>(typeof o=="string"?this.#e=o:this.#i(i,this.#e,o),a.forEach(l=>{this.#i(i,this.#e,l);}),this);}),this.on=(i,o,...a)=>{for(let l of [o].flat()){this.#e=l;for(let c of [i].flat())a.map(p=>{this.#i(c.toUpperCase(),this.#e,p);});}return this},this.use=(i,...o)=>(typeof i=="string"?this.#e=i:(this.#e="*",o.unshift(i)),o.forEach(a=>{this.#i(ie,this.#e,a);}),this);let{strict:r,...s}=t;Object.assign(this,s),this.getPath=r??true?t.getPath??Fo:du;}#t(){let t=new $u({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#n=this.#n,t.routes=this.routes,t}#n=by;errorHandler=Cu;route(t,n){let r=this.basePath(t);return n.routes.map(s=>{let i;n.errorHandler===Cu?i=s.handler:(i=async(o,a)=>(await Lo([],n.errorHandler)(o,()=>s.handler(o,a))).res,i[Hn]=s.handler),r.#i(s.method,s.path,i);}),this}basePath(t){let n=this.#t();return n._basePath=Dt(this._basePath,t),n}onError=t=>(this.errorHandler=t,this);notFound=t=>(this.#n=t,this);mount(t,n,r){let s,i;r&&(typeof r=="function"?i=r:(i=r.optionHandler,r.replaceRequest===false?s=l=>l:s=r.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=Dt(this._basePath,t),c=l==="/"?0:l.length;return p=>{let u=new URL(p.url);return u.pathname=u.pathname.slice(c)||"/",new Request(u,p)}})();let a=async(l,c)=>{let p=await n(s(l.req.raw),...o(l));if(p)return p;await c();};return this.#i(ie,Dt(t,"*"),a),this}#i(t,n,r){t=t.toUpperCase(),n=Dt(this._basePath,n);let s={basePath:this._basePath,path:n,method:t,handler:r};this.router.add(t,n,[r,s]),this.routes.push(s);}#s(t,n){if(t instanceof Error)return this.errorHandler(t,n);throw t}#r(t,n,r,s){if(s==="HEAD")return (async()=>new Response(null,await this.#r(t,n,r,"GET")))();let i=this.getPath(t,{env:r}),o=this.router.match(s,i),a=new Eu(t,{path:i,matchResult:o,env:r,executionCtx:n,notFoundHandler:this.#n});if(o[0].length===1){let c;try{c=o[0][0][0][0](a,async()=>{a.res=await this.#n(a);});}catch(p){return this.#s(p,a)}return c instanceof Promise?c.then(p=>p||(a.finalized?a.res:this.#n(a))).catch(p=>this.#s(p,a)):c??this.#n(a)}let l=Lo(o[0],this.errorHandler,this.#n);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,...n)=>this.#r(t,n[1],n[0],t.method);request=(t,n,r,s)=>t instanceof Request?this.fetch(n?new Request(t,n):t,r,s):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${Dt("/",t)}`,n),r,s));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#r(t.request,t,void 0,t.request.method));});}};});function Go(e,t){let n=this.buildAllMatchers(),r=((s,i)=>{let o=n[s]||n[ie],a=o[2][i];if(a)return a;let l=i.match(o[0]);if(!l)return [[],Rs];let c=l.indexOf("",1);return [o[1][c],l]});return this.match=r,r(e,t)}var Rs,Wo=b(()=>{yt();Rs=[];});function Sy(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===Gn||e===Wn?1:t===Gn||t===Wn?-1:e===vs?1:t===vs?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var vs,Gn,Wn,jt,wy,vu,Ko=b(()=>{vs="[^/]+",Gn=".*",Wn="(?:|/.*)",jt=Symbol(),wy=new Set(".\\+*[^]$()");vu=class Vo{#e;#t;#n=Object.create(null);insert(t,n,r,s,i){if(t.length===0){if(this.#e!==void 0)throw jt;if(i)return;this.#e=n;return}let[o,...a]=t,l=o==="*"?a.length===0?["","",Gn]:["","",vs]:o==="/*"?["","",Wn]:o.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(l){let p=l[1],u=l[2]||vs;if(p&&l[2]&&(u===".*"||(u=u.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(u))))throw jt;if(c=this.#n[u],!c){if(Object.keys(this.#n).some(f=>f!==Gn&&f!==Wn))throw jt;if(i)return;c=this.#n[u]=new Vo,p!==""&&(c.#t=s.varIndex++);}!i&&p!==""&&r.push([p,c.#t]);}else if(c=this.#n[o],!c){if(Object.keys(this.#n).some(p=>p.length>1&&p!==Gn&&p!==Wn))throw jt;if(i)return;c=this.#n[o]=new Vo;}c.insert(a,n,r,s,i);}buildRegExpStr(){let n=Object.keys(this.#n).sort(Sy).map(r=>{let s=this.#n[r];return (typeof s.#t=="number"?`(${r})@${s.#t}`:wy.has(r)?`\\${r}`:r)+s.buildRegExpStr()});return typeof this.#e=="number"&&n.unshift(`#${this.#e}`),n.length===0?"":n.length===1?n[0]:"(?:"+n.join("|")+")"}};});var ku,Nu=b(()=>{Ko();ku=class{#e={varIndex:0};#t=new vu;insert(e,t,n){let r=[],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,r,this.#e,n),r}buildRegExp(){let e=this.#t.buildRegExpStr();if(e==="")return [/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(s,i,o)=>i!==void 0?(n[++t]=Number(i),"$()"):(o!==void 0&&(r[Number(o)]=++t),"")),[new RegExp(`^${e}`),n,r]}};});function Ou(e){return Pu[e]??=new RegExp(e==="*"?"":`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(t,n)=>n?`\\${n}`:"(?:|/.*)")}$`)}function _y(){Pu=Object.create(null);}function xy(e){let t=new ku,n=[];if(e.length===0)return Ey;let r=e.map(c=>[!/\*|\/:/.test(c[0]),...c]).sort(([c,p],[u,f])=>c?1:u?-1:p.length-f.length),s=Object.create(null);for(let c=0,p=-1,u=r.length;c<u;c++){let[f,h,m]=r[c];f?s[h]=[m.map(([g])=>[g,Object.create(null)]),Rs]:p++;let d;try{d=t.insert(h,p,f);}catch(g){throw g===jt?new $s(h):g}f||(n[p]=m.map(([g,y])=>{let E=Object.create(null);for(y-=1;y>=0;y--){let[A,C]=d[y];E[A]=C;}return [g,E]}));}let[i,o,a]=t.buildRegExp();for(let c=0,p=n.length;c<p;c++)for(let u=0,f=n[c].length;u<f;u++){let h=n[c][u]?.[1];if(!h)continue;let m=Object.keys(h);for(let d=0,g=m.length;d<g;d++)h[m[d]]=a[h[m[d]]];}let l=[];for(let c in o)l[c]=n[o[c]];return [i,l,s]}function nn(e,t){if(e){for(let n of Object.keys(e).sort((r,s)=>s.length-r.length))if(Ou(n).test(t))return [...e[n]]}}var Ey,Pu,ks,zo=b(()=>{yt();tn();Wo();Ko();Nu();Ey=[/^$/,[],Object.create(null)],Pu=Object.create(null);ks=class{name="RegExpRouter";#e;#t;constructor(){this.#e={[ie]:Object.create(null)},this.#t={[ie]:Object.create(null)};}add(e,t,n){let r=this.#e,s=this.#t;if(!r||!s)throw new Error(As);r[e]||[r,s].forEach(a=>{a[e]=Object.create(null),Object.keys(a[ie]).forEach(l=>{a[e][l]=[...a[ie][l]];});}),t==="/*"&&(t="*");let i=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let a=Ou(t);e===ie?Object.keys(r).forEach(l=>{r[l][t]||=nn(r[l],t)||nn(r[ie],t)||[];}):r[e][t]||=nn(r[e],t)||nn(r[ie],t)||[],Object.keys(r).forEach(l=>{(e===ie||e===l)&&Object.keys(r[l]).forEach(c=>{a.test(c)&&r[l][c].push([n,i]);});}),Object.keys(s).forEach(l=>{(e===ie||e===l)&&Object.keys(s[l]).forEach(c=>a.test(c)&&s[l][c].push([n,i]));});return}let o=Cs(t)||[t];for(let a=0,l=o.length;a<l;a++){let c=o[a];Object.keys(s).forEach(p=>{(e===ie||e===p)&&(s[p][c]||=[...nn(r[p],c)||nn(r[ie],c)||[]],s[p][c].push([n,i-l+a+1]));});}}match=Go;buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#t).concat(Object.keys(this.#e)).forEach(t=>{e[t]||=this.#n(t);}),this.#e=this.#t=void 0,_y(),e}#n(e){let t=[],n=e===ie;return [this.#e,this.#t].forEach(r=>{let s=r[e]?Object.keys(r[e]).map(i=>[i,r[e][i]]):[];s.length!==0?(n||=true,t.push(...s)):e!==ie&&t.push(...Object.keys(r[ie]).map(i=>[i,r[ie][i]]));}),n?xy(t):null}};});var Lu=b(()=>{yt();Wo();zo();});var Iu=b(()=>{zo();Lu();});var Xo,Du=b(()=>{yt();Xo=class{name="SmartRouter";#e=[];#t=[];constructor(e){this.#e=e.routers;}add(e,t,n){if(!this.#t)throw new Error(As);this.#t.push([e,t,n]);}match(e,t){if(!this.#t)throw new Error("Fatal error");let n=this.#e,r=this.#t,s=n.length,i=0,o;for(;i<s;i++){let a=n[i];try{for(let l=0,c=r.length;l<c;l++)a.add(...r[l]);o=a.match(e,t);}catch(l){if(l instanceof $s)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 ju=b(()=>{Du();});var Vn,Ty,Fu,Uu=b(()=>{yt();tn();Vn=Object.create(null),Ty=e=>{for(let t in e)return true;return false},Fu=class Mu{#e;#t;#n;#i=0;#s=Vn;constructor(t,n,r){if(this.#t=r||Object.create(null),this.#e=[],t&&n){let s=Object.create(null);s[t]={handler:n,possibleKeys:[],score:0},this.#e=[s];}this.#n=[];}insert(t,n,r){this.#i=++this.#i;let s=this,i=fu(n),o=[];for(let a=0,l=i.length;a<l;a++){let c=i[a],p=i[a+1],u=mu(c,p),f=Array.isArray(u)?u[0]:c;if(f in s.#t){s=s.#t[f],u&&o.push(u[1]);continue}s.#t[f]=new Mu,u&&(s.#n.push(u),o.push(u[1])),s=s.#t[f];}return s.#e.push({[t]:{handler:r,possibleKeys:o.filter((a,l,c)=>c.indexOf(a)===l),score:this.#i}}),s}#r(t,n,r,s,i){for(let o=0,a=n.#e.length;o<a;o++){let l=n.#e[o],c=l[r]||l[ie],p={};if(c!==void 0&&(c.params=Object.create(null),t.push(c),s!==Vn||i&&i!==Vn))for(let u=0,f=c.possibleKeys.length;u<f;u++){let h=c.possibleKeys[u],m=p[c.score];c.params[h]=i?.[h]&&!m?i[h]:s[h]??i?.[h],p[c.score]=true;}}}search(t,n){let r=[];this.#s=Vn;let i=[this],o=jo(n),a=[],l=o.length,c=null;for(let p=0;p<l;p++){let u=o[p],f=p===l-1,h=[];for(let d=0,g=i.length;d<g;d++){let y=i[d],E=y.#t[u];E&&(E.#s=y.#s,f?(E.#t["*"]&&this.#r(r,E.#t["*"],t,y.#s),this.#r(r,E,t,y.#s)):h.push(E));for(let A=0,C=y.#n.length;A<C;A++){let $=y.#n[A],R=y.#s===Vn?{}:{...y.#s};if($==="*"){let D=y.#t["*"];D&&(this.#r(r,D,t,y.#s),D.#s=R,h.push(D));continue}let[T,x,O]=$;if(!u&&!(O instanceof RegExp))continue;let w=y.#t[T];if(O instanceof RegExp){if(c===null){c=new Array(l);let U=n[0]==="/"?1:0;for(let S=0;S<l;S++)c[S]=U,U+=o[S].length+1;}let D=n.substring(c[p]),q=O.exec(D);if(q){if(R[x]=q[0],this.#r(r,w,t,y.#s,R),Ty(w.#t)){w.#s=R;let U=q[0].match(/\//)?.length??0;(a[U]||=[]).push(w);}continue}}(O===true||O.test(u))&&(R[x]=u,f?(this.#r(r,w,t,R,y.#s),w.#t["*"]&&this.#r(r,w.#t["*"],t,R,y.#s)):(w.#s=R,h.push(w)));}}let m=a.shift();i=m?h.concat(m):h;}return r.length>1&&r.sort((p,u)=>p.score-u.score),[r.map(({handler:p,params:u})=>[p,u])]}};});var Jo,Bu=b(()=>{tn();Uu();Jo=class{name="TrieRouter";#e;constructor(){this.#e=new Fu;}add(e,t,n){let r=Cs(t);if(r){for(let s=0,i=r.length;s<i;s++)this.#e.insert(e,r[s],n);return}this.#e.insert(e,t,n);}match(e,t){return this.#e.search(e,t)}};});var qu=b(()=>{Bu();});var Yo,Hu=b(()=>{Ru();Iu();ju();qu();Yo=class extends Au{constructor(e={}){super(e),this.router=e.router??new Xo({routers:[new ks,new Jo]});}};});var Gu=b(()=>{Hu();});function Qo(e){return !e||typeof e!="object"?false:e.code==="EADDRINUSE"}function Wu(e,t,n){return new Promise((r,s)=>{let i=a=>{e.off("listening",o),s(a);},o=()=>{e.off("error",i),r();};e.once("error",i),e.once("listening",o),e.listen(t,n);})}function Zo(e){console.error(),console.error(Kn.default.red(`Cannot start server: Port ${Kn.default.bold(String(e))} is already in use.`)),console.error(Kn.default.red(`Stop the process using that port, or set a different ${Kn.default.bold("api.port")} in your config.`)),console.error(),process.exit(1);}var Kn,Vu=b(()=>{Kn=K(X());});function zn(e){let t=[],n=e??"",r=n.toLowerCase(),s=new TextEncoder().encode(n).length;if(!n)return t.push("auth.jwt_secret is empty"),{strong:false,reasons:t};Cy.has(n)&&t.push(`matches Supalite development default "${n}"`),s<32&&t.push(`is ${s} bytes; use at least 32 bytes for production secrets`),[/[a-z]/.test(n),/[A-Z]/.test(n),/[0-9]/.test(n),/[^A-Za-z0-9]/.test(n)].filter(Boolean).length<3&&t.push("uses too little character variety"),/^(.)\1{7,}$/.test(n)?t.push("is one repeated character"):$y(n)&&t.push("contains an obvious repeated pattern");let o=Ay.find(a=>r.includes(a));return o&&t.push(`contains placeholder term "${o}"`),{strong:t.length===0,reasons:t}}function $y(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 Cy,Ay,ea=b(()=>{Cy=new Set(["unsafe-secret-change-me","dev-secret-change-me"]),Ay=["change-me","changeme","secret","password","passwd","test","dev"];});var Ku,zu=b(()=>{Ku=/^\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 na,Xu,Ry,ta,ra=b(()=>{na=(e,t=ta)=>{let n=/\.([a-zA-Z0-9]+?)$/,r=e.match(n);if(!r)return;let s=t[r[1]];return s&&s.startsWith("text")&&(s+="; charset=utf-8"),s},Xu=e=>{for(let t in ta)if(ta[t]===e)return t},Ry={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"},ta=Ry;});var Ju,Yu=b(()=>{Ju=(...e)=>{let t=e.filter(s=>s!=="").join("/");t=t.replace(/(?<=\/)\/+/g,"");let n=t.split("/"),r=[];for(let s of n)s===".."&&r.length>0&&r.at(-1)!==".."?r.pop():s!=="."&&r.push(s);return r.join("/")||"."};});var Qu,vy,ky,Zu,ep=b(()=>{zu();ra();Yu();Qu={br:".br",zstd:".zst",gzip:".gz"},vy=Object.keys(Qu),ky="index.html",Zu=e=>{let t=e.root??"./",n=e.path,r=e.join??Ju;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=r(t,!n&&e.rewriteRequestPath?e.rewriteRequestPath(o):o);e.isDir&&await e.isDir(a)&&(a=r(a,ky));let l=e.getContent,c=await l(a,s);if(c instanceof Response)return s.newResponse(c.body,c);if(c){let p=e.mimes&&na(a,e.mimes)||na(a);if(s.header("Content-Type",p||"application/octet-stream"),e.precompressed&&(!p||Ku.test(p))){let u=new Set(s.req.header("Accept-Encoding")?.split(",").map(f=>f.trim()));for(let f of vy){if(!u.has(f))continue;let h=await l(a+Qu[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 tp,np=b(()=>{ep();tp=e=>async function(n,r){return Zu({...e,getContent:async o=>{let a=Bun.file(o);return await a.exists()?a:null},join:join,isDir:async o=>{let a;try{a=(await stat$1(o)).isDirectory();}catch{}return a}})(n,r)};});var rp=b(()=>{});var sp,ip=b(()=>{rp();sp=(e,t)=>{for(let[n,r]of Object.entries(t)){let s=new RegExp("/:"+n+"(?:{[^/]+})?\\??");e=e.replace(s,r?`/${r}`:"");}return e};});var Oy,op,ap=b(()=>{Oy=1024,op=({concurrency:e,interval:t}={})=>{if(e||=Oy,e===1/0)return {run:async s=>s()};let n=new Set,r=async(s,i,o)=>{if(n.size>=e)return i||=new Promise(c=>o=c),setTimeout(()=>r(s,i,o)),i;let a={};n.add(a);let l=await s();return t?setTimeout(()=>n.delete(a),t):n.delete(a),o?(o(l),i):l};return {run:r}};});var lp,sa,cp=b(()=>{Ho();lp=e=>e.length>1,sa=e=>e[Hn]?sa(e[Hn]):e;});var up,Ly,Iy,Dy,jy,Xn,pp,ia,oa=b(()=>{yt();cp();up=e=>e.split(/[\/\\]/).slice(0,-1).join("/"),Ly=e=>e.replace(/(\\)/g,"/").replace(/\/$/g,""),Iy=(e,t)=>{e.length===0||t?e.push(".."):e.pop();},Dy=(e,t)=>{e=e.replace(/^\.(?!.)/,""),e!==""&&t.push(e);},jy=(e,t)=>{let n=false;for(let r of e)r===".."?(Iy(t,n),n=true):(Dy(r,t),n=false);},Xn=(...e)=>{e=e.map(Ly);let t=[];return jy(e.join("/").split("/"),t),(e[0][0]==="/"?"/":"")+t.join("/")},pp=e=>e.routes.reduce((t,{method:n,handler:r,path:s})=>{let i=sa(r);return ["GET",ie].includes(n)&&!lp(i)&&t.push({path:s}),t},[]),ia=e=>e.split("/").some(t=>t.startsWith(":")||t.includes("*"));});var fp,Ns,aa=b(()=>{oa();fp="HONO_SSG_CONTEXT",Ns="x-hono-disable-ssg",(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[Ns]:"true"}})}catch{return null}})();});var mp=b(()=>{Bo();});var la,ca=b(()=>{mp();la=()=>({afterResponseHook:e=>e.status!==200?false:e});});var Fy,My,Uy,By,qy,Hy,Gy,Wy,Vy,Ky,zy,dp,Xy,hp,gp=b(()=>{ip();ap();ra();aa();ca();oa();Fy=2,My="text/plain",Uy="./static",By=(e,t,n,r)=>{let s=Gy(n,r);return e.endsWith(`.${s}`)?Xn(t,e):e==="/"?Xn(t,`index.${s}`):e.endsWith("/")?Xn(t,e,`index.${s}`):Xn(t,`${e}.${s}`)},qy=async e=>{let t=e.headers.get("Content-Type");try{return t?.includes("text")||t?.includes("json")?await e.text():await e.arrayBuffer()}catch(n){throw new Error(`Error processing response: ${n instanceof Error?n.message:"Unknown error"}`)}},Hy={"text/html":"html","text/xml":"xml","application/xml":"xml","application/yaml":"yaml"},Gy=(e,t)=>{let n=t||Hy;return e in n?n[e]:Xu(e)||"html"},Wy=e=>Array.isArray(e)?async t=>{let n=t;for(let r of e){let s=await r(n);if(s===false)return false;s instanceof Request&&(n=s);}return n}:e,Vy=e=>Array.isArray(e)?async t=>{let n=t;for(let r of e){let s=await r(n);if(s===false)return false;s instanceof Response&&(n=s);}return n}:e,Ky=(e,t,n)=>Array.isArray(e)?async r=>{for(let s of e)await s(r,t,n);}:e,zy=function*(e,t,n,r){let s="http://localhost",i=op({concurrency:r});for(let o of pp(e)){let a=new URL(o.path,s).toString(),l=new Request(a);yield new Promise(async(c,p)=>{try{if(t){let f=await t(l);if(!f){c(void 0);return}l=f;}if(await i.run(()=>e.fetch(l)),!l.ssgParams){if(ia(o.path)){c(void 0);return}l.ssgParams=[{}];}let u={method:l.method,headers:l.headers};c((function*(){for(let f of l.ssgParams)yield new Promise(async(h,m)=>{try{let d=sp(o.path,f),g=await i.run(()=>e.request(d,u,{[fp]:!0}));if(g.headers.get(Ns)){h(void 0);return}if(n){let A=await n(g);if(!A){h(void 0);return}g=A;}let y=g.headers.get("Content-Type")?.split(";")[0]||My,E=await qy(g);h({routePath:d,mimeType:y,content:E});}catch(d){m(d);}});})());}catch(u){p(u);}});}},dp=new Set,Xy=async(e,t,n,r)=>{let s=await e;if(!s)return;let{routePath:i,content:o,mimeType:a}=s,l=By(i,n,a,r),c=up(l);return dp.has(c)||(await t.mkdir(c,{recursive:true}),dp.add(c)),typeof o=="string"?await t.writeFile(l,o):o instanceof ArrayBuffer&&await t.writeFile(l,new Uint8Array(o)),l},hp=async(e,t,n)=>{let r,s=[],i=[],o=n?.plugins||[la()],a=[],l=[],c=[];n?.beforeRequestHook&&a.push(...Array.isArray(n.beforeRequestHook)?n.beforeRequestHook:[n.beforeRequestHook]),n?.afterResponseHook&&l.push(...Array.isArray(n.afterResponseHook)?n.afterResponseHook:[n.afterResponseHook]),n?.afterGenerateHook&&c.push(...Array.isArray(n.afterGenerateHook)?n.afterGenerateHook:[n.afterGenerateHook]);for(let p of o)p.beforeRequestHook&&a.push(...Array.isArray(p.beforeRequestHook)?p.beforeRequestHook:[p.beforeRequestHook]),p.afterResponseHook&&l.push(...Array.isArray(p.afterResponseHook)?p.afterResponseHook:[p.afterResponseHook]),p.afterGenerateHook&&c.push(...Array.isArray(p.afterGenerateHook)?p.afterGenerateHook:[p.afterGenerateHook]);try{let p=n?.dir??Uy,u=n?.concurrency??Fy,f=Wy(a.length>0?a:[g=>g]),h=Vy(l.length>0?l:[g=>g]),m=zy(e,f,h,u);for(let g of m)s.push(g.then(y=>{if(y)for(let E of y)i.push(Xy(E,t,p,n?.extensionMap).catch(A=>A));}));await Promise.all(s);let d=[];for(let g of i){let y=await g;if(typeof y=="string")d.push(y);else if(y)throw y}r={success:!0,files:d};}catch(p){let u=p instanceof Error?p:new Error(String(p));r={success:false,files:[],error:u};}return c.length>0&&await Ky(c,t,n)(r,t,n),r};});var yp=b(()=>{gp();aa();ca();});var Jy,ua,bp,wp=b(()=>{yp();(({write:Jy}=Bun)),ua={writeFile:async(e,t)=>{await Jy(e,t);},mkdir:async()=>{}},bp=async(e,t)=>hp(e,ua,t);});var Sp,Ep,_p,xp=b(()=>{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);}},Ep=e=>new MessageEvent("message",{data:e}),_p=e=>((...t)=>{if(typeof t[0]=="function"){let[n,r]=t;return async function(i,o){let a=await n(i),l=await e(i,a,r);if(l)return l;await o();}}else {let[n,r,s]=t;return (async()=>{let i=await e(n,r,s);if(!i)throw new Error("Failed to upgrade WebSocket");return i})()}});});var rn,Ps=b(()=>{rn=e=>"server"in e.env?e.env.server:e.env;});var pa,fa,ma,Tp,Cp=b(()=>{xp();Ps();pa=e=>new Sp({send:(t,n)=>{e.send(t,n?.compress);},raw:e,readyState:e.readyState,url:e.data.url,protocol:e.data.protocol,close(t,n){e.close(t,n);}}),fa=_p((e,t)=>{let n=rn(e);if(!n)throw new TypeError("env has to include the 2nd argument of fetch.");if(n.upgrade(e.req.raw,{data:{events:t,url:new URL(e.req.url),protocol:e.req.url}}))return new Response(null)}),ma={open(e){let t=e.data.events;t.onOpen&&t.onOpen(new Event("open"),pa(e));},close(e,t,n){let r=e.data.events;r.onClose&&r.onClose(new CloseEvent("close",{code:t,reason:n}),pa(e));},message(e,t){let n=e.data.events;if(n.onMessage){let r=typeof t=="string"?t:t.buffer;n.onMessage(Ep(r),pa(e));}}},Tp=()=>({upgradeWebSocket:fa,websocket:ma});});var Ap,$p=b(()=>{Ps();Ap=e=>{let t=rn(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 n=t.requestIP(e.req.raw);return n?{remote:{address:n.address,addressType:n.family==="IPv6"||n.family==="IPv4"?n.family:void 0,port:n.port}}:{remote:{}}};});var Rp={};me(Rp,{bunFileSystemModule:()=>ua,createBunWebSocket:()=>Tp,getBunServer:()=>rn,getConnInfo:()=>Ap,serveStatic:()=>tp,toSSG:()=>bp,upgradeWebSocket:()=>fa,websocket:()=>ma});var vp=b(()=>{np();wp();Cp();$p();Ps();});async function Os(e,t={}){if(e.config.auth?.enabled){let i=zn(e.config.auth.jwt_secret);i.strong||console.warn(Np.default.yellow(`[auth] auth.jwt_secret is weak \u2014 do not use it in production:
66
+ `+i.reasons.map(o=>` - it ${o}`).join(`
67
67
  `)+`
68
- `));}let n=Qr(),r=t.port??3e3;if(Nn()){let s=await Promise.resolve().then(()=>(fp(),pp)).then(o=>o.serveStatic),i;try{let o=dp(e,n,s);i=Bun.serve({fetch:a=>(jo(a,i?.requestIP(a)?.address),o.fetch(a)),port:r});}catch(o){throw Oo(o)&&Io(r),o}return async()=>{await i.stop();}}else {let{createAdaptorServer:s}=await import('@hono/node-server'),i=await import('@hono/node-server/serve-static').then(l=>l.serveStatic),o=dp(e,n,i),a=s({fetch:(l,...c)=>{let p=c[0]?.incoming;return jo(l,p?.socket?.remoteAddress),o.fetch(l)}});try{await $u(a,r);}catch(l){throw Oo(l)&&Io(r),l}return ()=>new Promise(l=>{a.close(()=>{l(void 0);});})}}function dp(e,t,n){return new Lo().use("/favicon.ico",n({path:Ie__default.join(t,"static","favicon.ico")})).use("/fonts/*",n({root:Ie__default.join(t,"static"),onNotFound:r=>{console.log("fonts not found",r,process.cwd());}})).use("/static/*",n({root:t,onNotFound(r){console.log("not found",r,process.cwd());}})).all("*",async r=>e.fetch(r.req.raw))}var hp,Jo=b(()=>{ct();Au();vu();Ee();Do();Ru();hp=V(z());});var tt,Qo=b(()=>{Tt();tt=class e{root;constructor(t,n){let r=n??e.projectDir();this.root=Ie__default.join(r,t??"");}ensureRoot(){Ce(this.root);}static homeDir(){return Ie__default.join(Ny.homedir(),".lite")}static projectDir(){return Ie__default.join(process.cwd(),"supabase")}deleteAll(t=false){try{qr.rmSync(this.root,{recursive:!0});}catch(n){if(!t)throw n}this.ensureRoot();}delete(t,n=false){try{qr.unlinkSync(Ie__default.join(this.root,t));}catch(r){if(!n)throw r}}write(t,n,r=false){try{this.ensureRoot(),qr.writeFileSync(Ie__default.join(this.root,t),n);}catch(s){if(!r)throw s}}read(t,n=false){try{return qr.readFileSync(Ie__default.join(this.root,t),"utf8")}catch(r){if(!n)throw r}}relativePath(t){return t?Ie__default.relative(process.cwd(),Ie__default.join(this.root,t)):this.root}path(t){return t?Ie__default.join(this.root,t):this.root}};});var Bn,Ss,Es=b(()=>{Bn=process.env.LITE_CLOUD_URL??(process.env.LOCAL?"http://localhost:2001":"https://api.lite.dev"),Ss=process.env.LITE_CLOUD_PROJECTS_URL??(process.env.LOCAL?"http://supalite.local":"https://lite.black");});var xs,gp=b(()=>{Tt();xs=class{root;constructor(t){this.root=t??Ie__default.join(Ny.homedir(),".lite","auth"),Ce(this.root);}async getItem(t){try{return qr.readFileSync(Ie__default.join(this.root,t+".json"),"utf8")}catch{return null}}async setItem(t,n){qr.writeFileSync(Ie__default.join(this.root,t+".json"),n);}async removeItem(t){try{qr.unlinkSync(Ie__default.join(this.root,t+".json"));}catch{return}}};});var Zt,ea=b(()=>{Es();Qo();gp();Zt=class{constructor(t){this.config=t;this.tempFs=new tt(".temp",this.config.root),this.projectFs=new tt("supabase",this.config.root),this.schemaFs=new tt("schemas",this.config.root),this.authStorage=this.config.authStorage??new xs(Ie__default.join(tt.homeDir(),"auth")),this._client=this.config.withSupabaseClient!==false?this.config.client??createClient(this.config.host??Bn,process.env.LITE_CLOUD_ANON_KEY??"...",{auth:{storage:this.authStorage}}):void 0;}tempFs;projectFs;schemaFs;_client;authStorage;async fetch(t,n){if(!this.config.token)throw new Error("Not authenticated, sign in first.");let r=t instanceof URL?t:new URL(t,this.config.host??Bn);return await fetch(r,{...n,headers:{...n?.headers,Authorization:`Bearer ${this.config.token}`}})}};});var en,ta=b(()=>{ea();Es();en=class extends Zt{constructor(n){super(n);this.config=n;}get client(){if(!this._client)throw new Error("Supabase client not initialized");return this._client}projectRef(){return this.tempFs.read("project-ref",true)}projectUrl(n){let r=new URL(this.config.projectsHost??Ss),s=r.hostname.replace(/^www\./,"");return `${r.protocol}//${n}.${s}${r.port?`:${r.port}`:""}`}};});function Iy(e){let t=Ie.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 Cs,yp=b(()=>{ct();Cs=class{driver=de;basePath;constructor(t){this.basePath=Ie.resolve(t.basePath);}filePath(t,n){return Ie.join(this.basePath,t,n)}async ensureDir(t){await de.mkdir(Ie.dirname(t),{recursive:true});}async getObject(t,n,r,s){let i=this.filePath(t,n),o=await de.stat(i),a=`"${createHash("md5").update(`${i}:${o.mtimeMs}`).digest("hex")}"`;if(s?.ifNoneMatch===a)return {httpStatusCode:304,metadata:this.buildMetadata(o,a,n)};if(s?.ifModifiedSince){let f=new Date(s.ifModifiedSince);if(o.mtime<=f)return {httpStatusCode:304,metadata:this.buildMetadata(o,a,n)}}let l,c,p=o.size,u=200;if(s?.range){let f=s.range.match(/^bytes=(\d+)-(\d*)$/);if(f){let h=Number.parseInt(f[1],10),d=f[2]?Number.parseInt(f[2],10):o.size-1;p=d-h+1,c=`bytes ${h}-${d}/${o.size}`,u=206,l=(await de.open(i,"r")).readableWebStream();}else l=(await de.open(i,"r")).readableWebStream();}else l=(await de.open(i,"r")).readableWebStream();return {httpStatusCode:u,metadata:{...this.buildMetadata(o,a,n),contentLength:p,contentRange:c},body:l}}async uploadObject(t,n,r,s,i,o){let a=this.filePath(t,n);await this.ensureDir(a);let l;if(s instanceof Uint8Array||Buffer.isBuffer(s))l=s;else {let u=[],f=s.getReader();for(;;){let{done:h,value:d}=await f.read();if(h)break;u.push(d);}l=Buffer.concat(u);}await de.writeFile(a,l);let c=await de.stat(a),p=`"${createHash("md5").update(l).digest("hex")}"`;return {cacheControl:o,contentLength:c.size,size:c.size,mimetype:i,lastModified:c.mtime,eTag:p}}async deleteObject(t,n,r){let s=this.filePath(t,n);await de.unlink(s).catch(i=>{if(i.code!=="ENOENT")throw i});}async deleteObjects(t,n){for(let r of n)await this.deleteObject(t,r,void 0);}async copyObject(t,n,r,s,i){let o=this.filePath(t,n),a=this.filePath(t,s);await this.ensureDir(a),await de.copyFile(o,a);let l=await de.stat(a),c=await de.readFile(a);return {httpStatusCode:200,eTag:`"${createHash("md5").update(c).digest("hex")}"`,lastModified:l.mtime}}async headObject(t,n,r){let s=this.filePath(t,n),i=await de.stat(s),o=`"${createHash("md5").update(`${s}:${i.mtimeMs}`).digest("hex")}"`;return this.buildMetadata(i,o,n)}async privateAssetUrl(t,n,r){return `file://${this.filePath(t,n)}`}buildMetadata(t,n,r){return {cacheControl:"no-cache",contentLength:ho(t.size),size:ho(t.size),mimetype:Iy(r),lastModified:t.mtime,eTag:n}}};});async function qe(e,t,n){try{return await Dy(e)}catch(r){throw r?.code==="ERR_MODULE_NOT_FOUND"||/Cannot find package/.test(String(r?.message))?new Error(`Driver '${t}' selected but '${n}' is not installed. Run: bun add ${n}`):r}}var Dy,tn=b(()=>{Dy=new Function("spec","return import(spec)");});var qn,Fy,As,wp=b(()=>{ta();$t();qn=V(z());An();Kt();yp();tn();Ji();Zi();vt();Fy=["toml","json","ts","mts","js","mjs","cjs"],As=class extends en{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 n=Ie__default.relative(process.cwd(),ue.config_dir);if(!t)for(let r of Fy){let s=Ie__default.join(n,`config.${r}`);if(await de__default.access(s).then(()=>true).catch(()=>false)){t=s;break}}return t}async readConfig(t){let n=await this.getConfigPath(t);if(!n)return {};Me(qn.default.dim(`Using config file: ${qn.default.cyan(`./${n}`)}`));let r=Ie__default.dirname(Ie__default.resolve(n));zr(r);let s=n.split(".").pop(),i;switch(s){case "toml":i=At(await de__default.readFile(n,"utf-8"));break;case "json":i=JSON.parse(await de__default.readFile(n,"utf-8"));break;case "ts":case "mts":case "js":case "mjs":case "cjs":try{i=(await import(Ie__default.join(process.cwd(),n))).default;break}catch(o){throw console.error("Failed to import config file",o),o}default:throw new Error(`Unsupported config file type: ${n}`)}return Xr(i)}async createConnection(){throw new Error("Not implemented")}async getConfig(t){let n=await this.readConfig(t);if("connection"in n)return {...n,connection:await n.connection};let r,s;switch(n.db?.driver){case "sqlite":s=n.db?.url??ue.default_db_url,r=await createConnection({url:s,ddlDialect:"sqlite"});break;case "pglite":{s=n.db?.url??Ie__default.join(process.cwd(),ue.default_db_dir);let{createPgliteConnection:i}=await qe("@supabase/lite/pglite","pglite","@electric-sql/pglite");r=await i({url:s});break}case "postgres":{s=n.db?.url??"";let{createPostgresConnection:i}=await qe("@supabase/lite/postgres","postgres","postgres");r=await i({url:s});break}default:s=n.db?.url??ue.default_db_url,r=await createConnection({url:s,ddlDialect:"postgres"});break}if(!r)throw new Error("Failed to create connection");return Me(qn.default.green(" \u279C"),"Database located at",qn.default.cyan(s??"in-memory")),{...n,connection:r}}async createApp(t,n){let r=await this.getConfig(t),s=new App({...r,options:{...r.options,server:{...r.options?.server,admin:n?.admin??r.options?.server?.admin??n?.adminDefault}}});return s.config.storage?.enabled&&process.env.EXPERIMENTAL_STORAGE==="1"&&!s._storageAdapter&&(s._storageAdapter=new Cs({basePath:Ie__default.join(process.cwd(),ue.config_dir,".temp/storage")})),await s.init()}};});var $s,Sp=b(()=>{ta();$s=class extends en{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 n=await t.json();if(!Array.isArray(n))throw new Error("Failed to list projects");return n}async get(t){if(t=t??this.projectRef(),!t)throw new Error("No project ref found");let n=await this.fetch(`/v1/projects/${t}`);if(!n.ok)throw new Error(`Failed to get project: ${n.status} ${n.statusText}`);let r=await n.json();if(!r||!r.id)throw new Error("Failed to get project");return r}async create(t){if(!t.name)throw new Error("Project name is required");let n=await this.fetch("/v1/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){let s=await n.text().catch(()=>"");throw new Error(`Failed to create project: ${n.status} ${n.statusText}${s?` \u2014 ${s}`:""}`)}let r=await n.json();if(!r||!r.id)throw new Error("Failed to create project");return r}async getConfig(t){let n=await this.fetch(`/v1/projects/${t}/config`);if(!n.ok)throw new Error(`Failed to get project config: ${n.status} ${n.statusText}`);let r=await n.json();if(!r)throw new Error("Failed to get project config");return r}async setConfig(t,n){let r=await this.fetch(`/v1/projects/${t}/config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok)throw new Error(`Failed to set project config: ${r.status} ${r.statusText}`);return true}async createApp(t){if(!this.config.host)throw new Error("No host specified");let{data:n,error:r}=await this.client.auth.getSession();if(r)throw r;if(!n?.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:n.session.access_token,host:this.config.host})}).init()}};});var vs,Ep=b(()=>{ea();wp();Sp();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:n}=await this.getSession();if(n)throw n;return t?.session?.access_token}async requireSession(){let t=await this.getAccessToken();if(!t)throw new Error("Not authenticated, sign in first.");return t}async init(){let t={...this.config};return this.config.withSupabaseClient!==false&&(t.client=this.client,t.token=await this.getAccessToken()),this.project={local:new As(t),remote:new $s(t)},this}};});async function W(e={}){return await new vs({host:Bn,projectsHost:Ss,root:tt.projectDir(),...e}).init()}var Te=b(()=>{Qo();Es();Ep();});function Rs(e){let t=false,n=async()=>{if(!t){t=true;try{await e();}catch(r){Me(r);}process.exit(0);}};process.on("SIGINT",n),process.on("SIGTERM",n);}var ra=b(()=>{vt();});function ks(e){let t=e.auth?.publishable_key,n=e.auth?.secret_key;if(!t&&!n){console.log(He.default.dim(He.default.yellow(" \u26A0\uFE0E no API keys configured \u2014 run `lite generate-keys` (any apikey accepted)")));return}console.log(He.default.green(" \u279C"),"Publishable key".padEnd(19),He.default.cyan(t??"(not set)")),console.log(He.default.green(" \u279C"),"Secret key".padEnd(19),He.default.cyan(n??"(not set)"));}function Ns(e){if(!e){console.log(He.default.dim(" \u279C admin mode off \u2014 keyless requests are not elevated; normal auth rules apply"));return}console.log(He.default.green(" \u279C"),"Studio admin mode".padEnd(19),He.default.cyan("on"),He.default.dim("(keyless same-origin localhost as service_role)"));}var He,sa=b(()=>{He=V(z());});function Ps(e,t){return {admin:t.getOptionValueSource?.("admin")==="cli"?e.admin:void 0,adminDefault:true}}var ia=b(()=>{});function _e(e){return e.dialect==="postgres"?"pg":e.config?.ddlDialect==="sqlite"?"sqlite":"pg-flat"}function ft(e){return e==="sqlite"?{schema_migrations:"migrations",seed_files:"seed_files"}:e==="pg-flat"?{schema_migrations:'"supabase_migrations.schema_migrations"',seed_files:'"supabase_migrations.seed_files"'}:{schema_migrations:"supabase_migrations.schema_migrations",seed_files:"supabase_migrations.seed_files"}}function Hn(e){return `'${e.replace(/'/g,"''")}'`}function By(e){return `'${`{${e.map(r=>`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`).join(",")}}`.replace(/'/g,"''")}'`}function _p(e,t){return t==null?"NULL":e==="pg"?By(t):Hn(JSON.stringify(t))}function oa(e){return e==null?"NULL":Hn(e)}function xp(e){if(e==null)return [];if(Array.isArray(e))return e;if(typeof e=="string"){let t=e.trim();if(t==="")return [];try{let n=JSON.parse(t);return Array.isArray(n)?n:[]}catch{return []}}return []}function qy(e){return {version:String(e.version),name:e.name??null,statements:xp(e.statements),rollback:xp(e.rollback),created_by:e.created_by??null,idempotency_key:e.idempotency_key??null}}function Gy(e){let{schema_migrations:t,seed_files:n}=ft(e);return e==="pg"?["CREATE SCHEMA IF NOT EXISTS supabase_migrations",`CREATE TABLE IF NOT EXISTS ${t} (
68
+ `));}let n=ms(),r=t.port??3e3,s=t.host??"127.0.0.1";if(Un()){let i=await Promise.resolve().then(()=>(vp(),Rp)).then(a=>a.serveStatic),o;try{let a=kp(e,n,i);o=Bun.serve({fetch:l=>a.fetch(l,{peerAddress:o?.requestIP(l)?.address??null}),hostname:s,port:r});}catch(a){throw Qo(a)&&Zo(r),a}return async()=>{await o.stop();}}else {let{createAdaptorServer:i}=await import('@hono/node-server'),o=await import('@hono/node-server/serve-static').then(c=>c.serveStatic),a=kp(e,n,o),l=i({fetch:(c,...p)=>{let u=p[0]?.incoming;return a.fetch(c,{peerAddress:u?.socket?.remoteAddress??null})}});try{await Wu(l,r,s);}catch(c){throw Qo(c)&&Zo(r),c}return ()=>new Promise(c=>{l.close(()=>{c(void 0);});})}}function kp(e,t,n){return new Yo().use("/favicon.ico",n({path:Fe__default.join(t,"static","favicon.ico")})).use("/static/*",n({root:t,onNotFound(r){console.log("not found",r,process.cwd());}})).all("*",async r=>e.fetch(r.req.raw,r.env))}var Np,da=b(()=>{gt();Gu();Vu();Te();ea();Np=K(X());});var ot,ha=b(()=>{Nt();ot=class e{root;constructor(t,n){let r=n??e.projectDir();this.root=Fe__default.join(r,t??"");}ensureRoot(){ve(this.root);}static homeDir(){return Fe__default.join(Qy.homedir(),".lite")}static projectDir(){return Fe__default.join(process.cwd(),"supabase")}deleteAll(t=false){try{rs.rmSync(this.root,{recursive:!0});}catch(n){if(!t)throw n}this.ensureRoot();}delete(t,n=false){try{rs.unlinkSync(Fe__default.join(this.root,t));}catch(r){if(!n)throw r}}write(t,n,r=false){try{this.ensureRoot(),rs.writeFileSync(Fe__default.join(this.root,t),n);}catch(s){if(!r)throw s}}read(t,n=false){try{return rs.readFileSync(Fe__default.join(this.root,t),"utf8")}catch(r){if(!n)throw r}}relativePath(t){return t?Fe__default.relative(process.cwd(),Fe__default.join(this.root,t)):this.root}path(t){return t?Fe__default.join(this.root,t):this.root}};});var Jn,Is,Ds=b(()=>{Jn=process.env.LITE_CLOUD_URL??(process.env.LOCAL?"http://localhost:2001":"https://api.lite.dev"),Is=process.env.LITE_CLOUD_PROJECTS_URL??(process.env.LOCAL?"http://supalite.local":"https://lite.black");});var Fs,Pp=b(()=>{Nt();Fs=class{root;constructor(t){this.root=t??Fe__default.join(Qy.homedir(),".lite","auth"),ve(this.root);}async getItem(t){try{return rs.readFileSync(Fe__default.join(this.root,t+".json"),"utf8")}catch{return null}}async setItem(t,n){rs.writeFileSync(Fe__default.join(this.root,t+".json"),n);}async removeItem(t){try{rs.unlinkSync(Fe__default.join(this.root,t+".json"));}catch{return}}};});var sn,ya=b(()=>{Ds();ha();Pp();sn=class{constructor(t){this.config=t;this.tempFs=new ot(".temp",this.config.root),this.projectFs=new ot("supabase",this.config.root),this.schemaFs=new ot("schemas",this.config.root),this.authStorage=this.config.authStorage??new Fs(Fe__default.join(ot.homeDir(),"auth")),this._client=this.config.withSupabaseClient!==false?this.config.client??createClient(this.config.host??Jn,process.env.LITE_CLOUD_ANON_KEY??"...",{auth:{storage:this.authStorage}}):void 0;}tempFs;projectFs;schemaFs;_client;authStorage;async fetch(t,n){if(!this.config.token)throw new Error("Not authenticated, sign in first.");let r=t instanceof URL?t:new URL(t,this.config.host??Jn);return await fetch(r,{...n,headers:{...n?.headers,Authorization:`Bearer ${this.config.token}`}})}};});var on,ba=b(()=>{ya();Ds();on=class extends sn{constructor(n){super(n);this.config=n;}get client(){if(!this._client)throw new Error("Supabase client not initialized");return this._client}projectRef(){return this.tempFs.read("project-ref",true)}projectUrl(n){let r=new URL(this.config.projectsHost??Is),s=r.hostname.replace(/^www\./,"");return `${r.protocol}//${n}.${s}${r.port?`:${r.port}`:""}`}};});function nb(e){let t=Fe.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 Us,Op=b(()=>{gt();Us=class{driver=he;basePath;constructor(t){this.basePath=Fe.resolve(t.basePath);}filePath(t,n){return Fe.join(this.basePath,t,n)}async ensureDir(t){await he.mkdir(Fe.dirname(t),{recursive:true});}async getObject(t,n,r,s){let i=this.filePath(t,n),o=await he.stat(i),a=`"${createHash("md5").update(`${i}:${o.mtimeMs}`).digest("hex")}"`;if(s?.ifNoneMatch===a)return {httpStatusCode:304,metadata:this.buildMetadata(o,a,n)};if(s?.ifModifiedSince){let f=new Date(s.ifModifiedSince);if(o.mtime<=f)return {httpStatusCode:304,metadata:this.buildMetadata(o,a,n)}}let l,c,p=o.size,u=200;if(s?.range){let f=s.range.match(/^bytes=(\d+)-(\d*)$/);if(f){let h=Number.parseInt(f[1],10),m=f[2]?Number.parseInt(f[2],10):o.size-1;p=m-h+1,c=`bytes ${h}-${m}/${o.size}`,u=206,l=(await he.open(i,"r")).readableWebStream();}else l=(await he.open(i,"r")).readableWebStream();}else l=(await he.open(i,"r")).readableWebStream();return {httpStatusCode:u,metadata:{...this.buildMetadata(o,a,n),contentLength:p,contentRange:c},body:l}}async uploadObject(t,n,r,s,i,o){let a=this.filePath(t,n);await this.ensureDir(a);let l;if(s instanceof Uint8Array||Buffer.isBuffer(s))l=s;else {let u=[],f=s.getReader();for(;;){let{done:h,value:m}=await f.read();if(h)break;u.push(m);}l=Buffer.concat(u);}await he.writeFile(a,l);let c=await he.stat(a),p=`"${createHash("md5").update(l).digest("hex")}"`;return {cacheControl:o,contentLength:c.size,size:c.size,mimetype:i,lastModified:c.mtime,eTag:p}}async deleteObject(t,n,r){let s=this.filePath(t,n);await he.unlink(s).catch(i=>{if(i.code!=="ENOENT")throw i});}async deleteObjects(t,n){for(let r of n)await this.deleteObject(t,r,void 0);}async copyObject(t,n,r,s,i,o){let a=this.filePath(t,n),l=this.filePath(s,i);await this.ensureDir(l),await he.copyFile(a,l);let c=await he.stat(l),p=await he.readFile(l);return {httpStatusCode:200,eTag:`"${createHash("md5").update(p).digest("hex")}"`,lastModified:c.mtime}}async headObject(t,n,r){let s=this.filePath(t,n),i=await he.stat(s),o=`"${createHash("md5").update(`${s}:${i.mtimeMs}`).digest("hex")}"`;return this.buildMetadata(i,o,n)}async privateAssetUrl(t,n,r){return `file://${this.filePath(t,n)}`}buildMetadata(t,n,r){return {cacheControl:"no-cache",contentLength:Po(t.size),size:Po(t.size),mimetype:nb(r),lastModified:t.mtime,eTag:n}}};});async function We(e,t,n){try{return await rb(e)}catch(r){throw r?.code==="ERR_MODULE_NOT_FOUND"||/Cannot find package/.test(String(r?.message))?new Error(`Driver '${t}' selected but '${n}' is not installed. Run: bun add ${n}`):r}}var rb,an=b(()=>{rb=new Function("spec","return import(spec)");});var Yn,ib,Bs,Ip=b(()=>{ba();Lt();Yn=K(X());In();Qt();Op();an();ho();yo();It();ib=["toml","json","ts","mts","js","mjs","cjs"],Bs=class extends on{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 n=Fe__default.relative(process.cwd(),pe.config_dir);if(!t)for(let r of ib){let s=Fe__default.join(n,`config.${r}`);if(await he__default.access(s).then(()=>true).catch(()=>false)){t=s;break}}return t}async readConfig(t){let n=await this.getConfigPath(t);if(!n)return {};He(Yn.default.dim(`Using config file: ${Yn.default.cyan(`./${n}`)}`));let r=Fe__default.dirname(Fe__default.resolve(n));cs(r);let s=n.split(".").pop(),i;switch(s){case "toml":i=Ot(await he__default.readFile(n,"utf-8"));break;case "json":i=JSON.parse(await he__default.readFile(n,"utf-8"));break;case "ts":case "mts":case "js":case "mjs":case "cjs":try{i=(await import(Fe__default.join(process.cwd(),n))).default;break}catch(o){throw console.error("Failed to import config file",o),o}default:throw new Error(`Unsupported config file type: ${n}`)}return us(i)}async createConnection(){throw new Error("Not implemented")}async getConfig(t){let n=await this.readConfig(t);if("connection"in n)return {...n,connection:await n.connection};let r,s;switch(n.db?.driver){case "sqlite":s=n.db?.url??pe.default_db_url,r=await createConnection({url:s,ddlDialect:"sqlite"});break;case "pglite":{s=n.db?.url??Fe__default.join(process.cwd(),pe.default_db_dir);let{createPgliteConnection:i}=await We("@supabase/lite/pglite","pglite","@electric-sql/pglite");r=await i({url:s});break}case "postgres":{s=n.db?.url??"";let{createPostgresConnection:i}=await We("@supabase/lite/postgres","postgres","postgres");r=await i({url:s});break}default:s=n.db?.url??pe.default_db_url,r=await createConnection({url:s,ddlDialect:"postgres"});break}if(!r)throw new Error("Failed to create connection");return He(Yn.default.green(" \u279C"),"Database located at",Yn.default.cyan(s??"in-memory")),{...n,connection:r}}async createApp(t,n){let r=await this.getConfig(t),s=new App({...r,options:{...r.options,server:{...r.options?.server,admin:n?.admin??r.options?.server?.admin??n?.adminDefault}}});return s.config.storage?.enabled&&process.env.EXPERIMENTAL_STORAGE==="1"&&!s._storageAdapter&&(s._storageAdapter=new Us({basePath:Fe__default.join(process.cwd(),pe.config_dir,".temp/storage")})),await s.init()}};});var qs,Dp=b(()=>{ba();qs=class extends on{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 n=await t.json();if(!Array.isArray(n))throw new Error("Failed to list projects");return n}async get(t){if(t=t??this.projectRef(),!t)throw new Error("No project ref found");let n=await this.fetch(`/v1/projects/${t}`);if(!n.ok)throw new Error(`Failed to get project: ${n.status} ${n.statusText}`);let r=await n.json();if(!r||!r.id)throw new Error("Failed to get project");return r}async create(t){if(!t.name)throw new Error("Project name is required");let n=await this.fetch("/v1/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){let s=await n.text().catch(()=>"");throw new Error(`Failed to create project: ${n.status} ${n.statusText}${s?` \u2014 ${s}`:""}`)}let r=await n.json();if(!r||!r.id)throw new Error("Failed to create project");return r}async getConfig(t){let n=await this.fetch(`/v1/projects/${t}/config`);if(!n.ok)throw new Error(`Failed to get project config: ${n.status} ${n.statusText}`);let r=await n.json();if(!r)throw new Error("Failed to get project config");return r}async setConfig(t,n){let r=await this.fetch(`/v1/projects/${t}/config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok)throw new Error(`Failed to set project config: ${r.status} ${r.statusText}`);return true}async createApp(t){if(!this.config.host)throw new Error("No host specified");let{data:n,error:r}=await this.client.auth.getSession();if(r)throw r;if(!n?.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:n.session.access_token,host:this.config.host})}).init()}};});var Hs,jp=b(()=>{ya();Ip();Dp();Hs=class extends sn{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:n}=await this.getSession();if(n)throw n;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 Bs(t),remote:new qs(t)},this}};});async function V(e={}){return await new Hs({host:Jn,projectsHost:Is,root:ot.projectDir(),...e}).init()}var Re=b(()=>{ha();Ds();jp();});function Gs(e){let t=false,n=async()=>{if(!t){t=true;try{await e();}catch(r){He(r);}process.exit(0);}};process.on("SIGINT",n),process.on("SIGTERM",n);}var Sa=b(()=>{It();});function Ws(e){let t=e.auth?.publishable_key,n=e.auth?.secret_key;if(!t&&!n){console.log(ye.default.dim(ye.default.yellow(" \u26A0\uFE0E no API keys configured \u2014 run `lite generate-keys` (any apikey accepted)")));return}console.log(ye.default.green(" \u279C"),"Publishable key".padEnd(19),ye.default.cyan(t??"(not set)")),console.log(ye.default.green(" \u279C"),"Secret key".padEnd(19),ye.default.cyan(n??"(not set)"));}function Vs(e){if(!e){console.log(ye.default.dim(" \u279C admin mode off \u2014 keyless requests are not elevated; normal auth rules apply"));return}console.log(ye.default.green(" \u279C"),"Studio admin mode".padEnd(19),ye.default.cyan("on"),ye.default.dim("(keyless same-origin localhost as service_role)"));}function Ks(e,t){let n=e.includes(":")&&!e.startsWith("[")?`[${e}]`:e;if(e==="0.0.0.0"||e==="::"||e==="[::]"){console.log(ye.default.green(" \u279C"),"Server listening on ",ye.default.cyan(`${n}:${t} (all interfaces)`)),console.log(ye.default.green(" \u279C"),"Local URL".padEnd(19),ye.default.cyan(`http://127.0.0.1:${t}`));return}console.log(ye.default.green(" \u279C"),"Server running on ",ye.default.cyan(`http://${n}:${t}`));}function zs(){console.log(ye.default.yellow(" \u26A0 Admin mode is disabled because the server is exposed."),ye.default.dim("Pass --admin to enable peer-scoped local admin access, or --no-admin to keep it explicitly disabled."));}var ye,Ea=b(()=>{ye=K(X());});function Xs(e,t){let n=e.host===true?cb:e.host||lb,r=!iu(n),s=t.getOptionValueSource?.("admin")==="cli";return {host:n,exposed:r,admin:s?e.admin:r?false:void 0,adminDefault:!r,warnAdminDisabled:r&&t.getOptionValueSource?.("host")==="cli"&&!s}}var lb,cb,_a=b(()=>{Oo();lb="127.0.0.1",cb="0.0.0.0";});function ub(e,t){if(e.includes(Fp)||t.includes(Fp))return true;let n=ko(e),r=ko(t);return !n||!r?Es(e)!==Es(t):[...n].sort().join("\0")!==[...r].sort().join("\0")}var Fp,Qn,xa=b(()=>{ht();Fp="/* modified */";Qn=class{makeIndexKey(t){return `${t.table}:${t.name}:${t.unique}:${t.columns.join(",")}`}makeForeignKeyKey(t){let n=(t.on_update??"NO ACTION").toUpperCase(),r=(t.on_delete??"NO ACTION").toUpperCase();return `${t.table}:${t.column}:${t.ref_table}:${t.ref_column}:${n}:${r}`}diff(t,n){let r=[],s=[],i=[],o=[],a=new Set(t.tables.map(d=>d.name)),l=new Set(n.tables.map(d=>d.name));for(let d of n.tables)a.has(d.name)||r.push({type:"added",name:d.name,sql:d.sql});for(let d of t.tables)l.has(d.name)||r.push({type:"removed",name:d.name});for(let d of t.tables){let g=n.tables.find(y=>y.name===d.name);g&&ub(d.sql,g.sql)&&r.push({type:"modified",name:d.name,sql:g.sql});}let c=t.tables.filter(d=>l.has(d.name));for(let d of c){let g=t.columns.filter(C=>C.table===d.name),y=n.columns.filter(C=>C.table===d.name),E=new Map(g.map(C=>[C.name,C])),A=new Map(y.map(C=>[C.name,C]));for(let[C,$]of A)E.has(C)||s.push({type:"added",table:d.name,name:C,column:$});for(let[C]of E)A.has(C)||s.push({type:"removed",table:d.name,name:C});for(let[C,$]of E){let R=A.get(C);if(!R)continue;let T={};vo($.type)!==vo(R.type)&&(T.type={from:$.type,to:R.type}),!($.is_primary_key&&R.is_primary_key)&&$.nullable!==R.nullable&&(T.nullable={from:$.nullable,to:R.nullable}),No($.default_value)!==No(R.default_value)&&(T.default_value={from:$.default_value,to:R.default_value}),Object.keys(T).length>0&&s.push({type:"modified",table:d.name,name:C,changes:T});}}let p=new Map(t.indexes.map(d=>[this.makeIndexKey(d),d])),u=new Map(n.indexes.map(d=>[this.makeIndexKey(d),d]));for(let[d,g]of u)p.has(d)||i.push({type:"added",...g});for(let[d,g]of p)u.has(d)||i.push({type:"removed",...g});let f=new Map(t.foreign_keys.map(d=>[this.makeForeignKeyKey(d),d])),h=new Map(n.foreign_keys.map(d=>[this.makeForeignKeyKey(d),d]));for(let[d,g]of h)f.has(d)||o.push({type:"added",...g});for(let[d,g]of f)h.has(d)||o.push({type:"removed",...g});let m=r.length>0||s.length>0||i.length>0||o.length>0;return {tables:r,columns:s,indexes:i,foreign_keys:o,has_changes:m}}};});var Js,Ys=b(()=>{Js=class extends Error{constructor(n){super(`Migration would cause data loss:
69
+ ${n.map(r=>` - ${r.table}: ${r.reason}`).join(`
70
+ `)}`);this.warnings=n;this.name="DataLossError";}};});var fb,Zn,Ta=b(()=>{Ys();Bn();fb=["CURRENT_TIMESTAMP","CURRENT_TIME","CURRENT_DATE"],Zn=class{plan(t,n,r,s){if(!t.has_changes)return {steps:[],warnings:[],unsafe:false};let i=[],o=[];i.push({sql:"PRAGMA foreign_keys=OFF;",description:"Disable foreign key checks",type:"disable_foreign_keys"}),i.push({sql:"BEGIN;",description:"Begin transaction",type:"begin_transaction"});for(let u of t.tables.filter(f=>f.type==="added")){i.push({sql:`${u.sql};`,description:`CREATE TABLE ${B(u.name)}`,type:"create_table"});let f=r.indexes.filter(h=>h.table===u.name);for(let h of f){let m=h.unique?"UNIQUE ":"",d=h.columns.map(g=>B(g)).join(", ");i.push({sql:`CREATE ${m}INDEX ${B(h.name)} ON ${B(u.name)} (${d});`,description:`Create index ${B(h.name)} on ${B(u.name)}`,type:"add_index"});}}let a=new Set(n.tables.map(u=>u.name)),l=new Set(r.tables.map(u=>u.name)),c=new Set(t.tables.filter(u=>u.type==="modified").map(u=>u.name)),p=[...a].filter(u=>l.has(u));for(let u of p){if(!(c.has(u)||t.columns.some(d=>d.table===u)||t.indexes.some(d=>d.table===u)||t.foreign_keys.some(d=>d.table===u)))continue;let{canAlter:h,addedCols:m}=this.canSimpleAlter(u,t,r);if(h){for(let y of m)i.push({sql:`ALTER TABLE ${B(u)} ADD COLUMN ${this.columnDef(y)};`,description:`Add column ${B(y.name)} to ${B(u)}`,type:"add_column"});let d=t.indexes.filter(y=>y.table===u&&y.type==="added"),g=t.indexes.filter(y=>y.table===u&&y.type==="removed");for(let y of g)i.push({sql:`DROP INDEX IF EXISTS ${B(y.name)};`,description:`Drop index ${B(y.name)}`,type:"drop_index"});for(let y of d){let E=y.unique?"UNIQUE ":"",A=y.columns.map(C=>B(C)).join(", ");i.push({sql:`CREATE ${E}INDEX ${B(y.name)} ON ${B(u)} (${A});`,description:`Create index ${B(y.name)} on ${B(u)}`,type:"add_index"});}}else {let d=this.rebuildTable(u,n,r,t);i.push(...d.steps),o.push(...d.warnings);}}for(let u of t.tables.filter(f=>f.type==="removed"))i.push({sql:`DROP TABLE ${B(u.name)};`,description:`Drop table ${B(u.name)}`,type:"drop_table"}),o.push({table:u.name,reason:"table will be dropped"});return i.push({sql:"COMMIT;",description:"Commit transaction",type:"commit_transaction"}),i.push({sql:"PRAGMA foreign_keys=ON;",description:"Re-enable foreign key checks",type:"enable_foreign_keys"}),{steps:i,warnings:o,unsafe:o.length>0}}rebuildTable(t,n,r,s){let i=[],o=[],a=r.tables.find(y=>y.name===t);if(!a)return {steps:i,warnings:o};let l=`_${t}_migrate_new`,c=a.sql.replace(new RegExp(`(CREATE\\s+TABLE\\s+)(?:"${t}"|${t})`,"i"),`$1${B(l)}`);i.push({sql:`${c};`,description:`Create temporary table ${B(l)}`,type:"create_table"});let p=n.columns.filter(y=>y.table===t).map(y=>y.name),u=r.columns.filter(y=>y.table===t).map(y=>y.name),f=p.filter(y=>u.includes(y));if(f.length>0){let y=f.map(E=>B(E)).join(", ");i.push({sql:`INSERT INTO ${B(l)} (${y})
71
+ SELECT ${y}
72
+ FROM ${B(t)};`,description:`Copy data from ${B(t)} to ${B(l)}`,type:"copy_data"});}i.push({sql:`DROP TABLE ${B(t)};`,description:`Drop old table ${B(t)}`,type:"drop_table"}),i.push({sql:`ALTER TABLE ${B(l)} RENAME TO ${B(t)};`,description:`Rename ${B(l)} to ${B(t)}`,type:"rename_table"});let h=r.indexes.filter(y=>y.table===t);for(let y of h){let E=y.unique?"UNIQUE ":"",A=y.columns.map(C=>B(C)).join(", ");i.push({sql:`CREATE ${E}INDEX ${B(y.name)} ON ${B(t)} (${A});`,description:`Recreate index ${B(y.name)} on ${B(t)}`,type:"add_index"});}let m=r.triggers?.filter(y=>y.table===t)??[];for(let y of m)i.push({sql:`${y.sql};`,description:`Recreate trigger ${B(y.name)} on ${B(t)}`,type:"create_trigger"});let d=s.columns.filter(y=>y.table===t&&y.type==="removed");for(let y of d)o.push({table:t,reason:`column "${y.name}" will be dropped`});let g=s.columns.filter(y=>y.table===t&&y.type==="modified");for(let y of g)y.changes?.type&&o.push({table:t,reason:`column "${y.name}" type changes from ${y.changes.type.from} to ${y.changes.type.to}`}),y.changes?.nullable&&!y.changes.nullable.to&&o.push({table:t,reason:`column "${y.name}" becomes NOT NULL`});return {steps:i,warnings:o}}canSimpleAlter(t,n,r){let s=n.columns.filter(u=>u.table===t),i=s.filter(u=>u.type==="added"),o=s.filter(u=>u.type==="removed"),a=s.filter(u=>u.type==="modified"),l=n.foreign_keys.some(u=>u.table===t);if(o.length>0||a.length>0||l)return {canAlter:false,addedCols:i};let c=r.tables.find(u=>u.name===t);return c&&/\bCHECK\s*\(/i.test(c.sql)?{canAlter:false,addedCols:i}:{canAlter:i.every(u=>{let f=u.column;return this.hasNonConstantDefault(f.default_value)?false:f.nullable||f.default_value!=null})&&i.length>0,addedCols:i}}hasNonConstantDefault(t){if(t==null)return false;let n=t.trim().toUpperCase();return fb.includes(n)}columnDef(t){let n=t.column,r=`${B(n.name)} ${n.type||"TEXT"}`;return n.nullable||(r+=" NOT NULL"),n.default_value!=null&&(r+=` DEFAULT ${n.default_value}`),r}};});function mb(e,t){return e==="migrations"||e==="supabase_migrations.schema_migrations"||e==="supabase_migrations.seed_files"||t==="sqlite"&&e==="seed_files"}function Qs(e,t){let n=r=>mb(r,t);return {...e,tables:e.tables.filter(r=>!n(r.name)),columns:e.columns.filter(r=>!n(r.table)),indexes:e.indexes.filter(r=>!n(r.table)),foreign_keys:e.foreign_keys.filter(r=>!n(r.table)),primary_keys:e.primary_keys.filter(r=>!n(r.table))}}var Ca=b(()=>{xa();Ta();});function Ce(e){return e.dialect==="postgres"?"pg":e.config?.ddlDialect==="sqlite"?"sqlite":"pg-flat"}function wt(e){return e==="sqlite"?{schema_migrations:"migrations",seed_files:"seed_files"}:e==="pg-flat"?{schema_migrations:'"supabase_migrations.schema_migrations"',seed_files:'"supabase_migrations.seed_files"'}:{schema_migrations:"supabase_migrations.schema_migrations",seed_files:"supabase_migrations.seed_files"}}function er(e){return `'${e.replace(/'/g,"''")}'`}function db(e){return `'${`{${e.map(r=>`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`).join(",")}}`.replace(/'/g,"''")}'`}function Mp(e,t){return t==null?"NULL":e==="pg"?db(t):er(JSON.stringify(t))}function Aa(e){return e==null?"NULL":er(e)}function Up(e){if(e==null)return [];if(Array.isArray(e))return e;if(typeof e=="string"){let t=e.trim();if(t==="")return [];try{let n=JSON.parse(t);return Array.isArray(n)?n:[]}catch{return []}}return []}function hb(e,t){let n=()=>{throw new Error(`Migration history ${String(t)} has invalid statements`)};if(e==null)return n();let r=e;if(typeof e=="string")try{r=JSON.parse(e);}catch{return n()}return !Array.isArray(r)||!r.every(s=>typeof s=="string")?n():r}function gb(e){return {version:String(e.version),name:e.name??null,statements:Up(e.statements),rollback:Up(e.rollback),created_by:e.created_by??null,idempotency_key:e.idempotency_key??null}}function yb(e){return {...gb(e),statements:hb(e.statements,e.version)}}function wb(e){let{schema_migrations:t,seed_files:n}=wt(e);return e==="pg"?["CREATE SCHEMA IF NOT EXISTS supabase_migrations",`CREATE TABLE IF NOT EXISTS ${t} (
69
73
  version text NOT NULL PRIMARY KEY,
70
74
  statements text[],
71
75
  name text,
@@ -85,22 +89,26 @@ create table test (
85
89
  )`,`CREATE TABLE IF NOT EXISTS ${n} (
86
90
  path TEXT NOT NULL PRIMARY KEY,
87
91
  hash TEXT NOT NULL
88
- )`]}function Wy(e){let{schema_migrations:t}=ft(e);return [`CREATE UNIQUE INDEX IF NOT EXISTS ${e==="sqlite"?"migrations_idempotency_key_idx":"schema_migrations_idempotency_key_idx"} ON ${t} (idempotency_key)`]}function Tp(e,t){let{schema_migrations:n}=ft(e);return `INSERT INTO ${n} (version, name, statements, rollback, created_by, idempotency_key) VALUES (${Hn(t.version)}, ${oa(t.name)}, ${_p(e,t.statements)}, ${_p(e,t.rollback??null)}, ${oa(t.created_by??null)}, ${oa(t.idempotency_key??null)}) ON CONFLICT (idempotency_key) DO UPDATE SET version = EXCLUDED.version, name = EXCLUDED.name, statements = EXCLUDED.statements, rollback = EXCLUDED.rollback, created_by = EXCLUDED.created_by`}function Vy(e){let{schema_migrations:t}=ft(e);return `SELECT version FROM ${t} ORDER BY version ASC`}function zy(e){let{schema_migrations:t}=ft(e);return `SELECT ${Ky} FROM ${t} ORDER BY version ASC`}function Xy(e){let{seed_files:t}=ft(e);return t?`SELECT path, hash FROM ${t}`:null}function Cp(e,t){let{seed_files:n}=ft(e);return n?`INSERT INTO ${n} (path, hash) VALUES (${Hn(t.path)}, ${Hn(t.hash)}) ON CONFLICT (path) DO UPDATE SET hash = EXCLUDED.hash`:null}async function Yy(e,t){let{schema_migrations:n}=ft(t);for(let r of Hy){let s=t==="pg"?r.pgType:r.sqliteType;if(t==="pg")await e.exec(`ALTER TABLE ${n} ADD COLUMN IF NOT EXISTS ${r.name} ${s}`);else try{await e.exec(`ALTER TABLE ${n} ADD COLUMN ${r.name} ${s}`);}catch{}}}async function nn(e){let t=_e(e);for(let n of Gy(t))await e.exec(n);await Yy(e,t);for(let n of Wy(t))await e.exec(n);}async function Gn(e){let t=_e(e);return ((await e.exec(Vy(t)))?.rows??[]).map(r=>r.version)}async function Wn(e){let t=_e(e);return ((await e.exec(zy(t)))?.rows??[]).map(qy)}async function Ap(e){let t=_e(e),n=Xy(t);return n?((await e.exec(n))?.rows??[]).map(s=>({path:s.path,hash:s.hash})):[]}var Hy,Ky,mt=b(()=>{Hy=[{name:"created_by",pgType:"text",sqliteType:"TEXT"},{name:"idempotency_key",pgType:"text",sqliteType:"TEXT"},{name:"rollback",pgType:"text[]",sqliteType:"TEXT"}];Ky="version, name, statements, rollback, created_by, idempotency_key";});function Jy(e){return e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/--.*$/gm,"")}function Qy(e){let t=e.trim();return t.startsWith('"')?t.replace(/^"(.*)"$/,"$1"):t.toLowerCase()}function Ls(e){let t=e.split(".");return Qy(t[t.length-1]??e)}function ua(e){let t=[...e].sort((i,o)=>i.version.localeCompare(o.version)),n=Jy(t.flatMap(i=>i.statements??[]).join(`
89
- `)),r=new Set;la.lastIndex=0;let s=la.exec(n);for(;s!==null;){let[,i,o,a,l]=s;if(i&&o){let c=Ls(i);o.toUpperCase()==="ENABLE"?r.add(c):r.delete(c);}else if(i&&a)r.delete(Ls(i))&&r.add(Ls(a));else if(l)for(let c of l.split(","))r.delete(Ls(c));s=la.exec(n);}return r}async function $p(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(r=>r.toString(16).padStart(2,"0")).join("")}async function vp(e){let t=[...e].sort((r,s)=>r.version.localeCompare(s.version)),n=await Promise.all(t.map(async r=>{let s=await $p((r.statements??[]).join(";"));return [r.version,s]}));return $p(JSON.stringify(n))}var ca,aa,la,Rp=b(()=>{ca='(?:"[^"]+"|[A-Za-z_][\\w$]*)',aa=`${ca}(?:\\s*\\.\\s*${ca})?`,la=new RegExp([`\\bALTER\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?(?:ONLY\\s+)?(${aa})\\s+(?:(ENABLE|DISABLE)\\s+ROW\\s+LEVEL\\s+SECURITY\\b|RENAME\\s+TO\\s+(${ca}))`,`\\bDROP\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?(${aa}(?:\\s*,\\s*${aa})*)`].join("|"),"gi");});function ib(e){let t=normalize(e);return t.length>1&&t[t.length-1]===sep&&(t=t.substring(0,t.length-1)),t}function Lp(e,t){return e.replace(ob,t)}function lb(e){return e==="/"||ab.test(e)}function pa(e,t){let{resolvePaths:n,normalizePath:r,pathSeparator:s}=t,i=process.platform==="win32"&&e.includes("/")||e.startsWith(".");if(n&&(e=resolve(e)),(r||i)&&(e=ib(e)),e===".")return "";let o=e[e.length-1]!==s;return Lp(o?e+s:e,s)}function Op(e,t){return t+e}function cb(e,t){return function(n,r){return r.startsWith(e)?r.slice(e.length)+n:Lp(relative(e,r),t.pathSeparator)+t.pathSeparator+n}}function ub(e){return e}function pb(e,t,n){return t+e+n}function fb(e,t){let{relativePaths:n,includeBasePath:r}=t;return n&&e?cb(e,t):r?Op:ub}function mb(e){return function(t,n){n.push(t.substring(e.length)||".");}}function db(e){return function(t,n,r){let s=t.substring(e.length)||".";r.every(i=>i(s,true))&&n.push(s);}}function bb(e,t){let{includeDirs:n,filters:r,relativePaths:s}=t;return n?s?r&&r.length?db(e):mb(e):r&&r.length?gb:hb:yb}function Tb(e){let{excludeFiles:t,filters:n,onlyCounts:r}=e;return t?xb:n&&n.length?r?wb:Sb:r?Eb:_b}function $b(e){return e.group?Ab:Cb}function kb(e){return e.group?vb:Rb}function Lb(e,t){return !e.resolveSymlinks||e.excludeSymlinks?null:t?Pb:Nb}function Ip(e,t,n){if(n.options.useRealPaths)return Ob(t,n);let r=dirname(e),s=1;for(;r!==n.root&&s<2;){let i=n.symlinks.get(r);!!i&&(i===t||i.startsWith(t)||t.startsWith(i))?s++:r=dirname(r);}return n.symlinks.set(e,t),s>1}function Ob(e,t){return t.visited.includes(e+t.options.pathSeparator)}function Os(e,t,n,r){t(e&&!r?e:null,n);}function Hb(e,t){let{onlyCounts:n,group:r,maxFiles:s}=e;return n?t?Ib:Ub:r?t?Db:qb:s?t?Fb:Bb:t?jb:Mb}function Vb(e){return e?Wb:Gb}function Yb(e,t){return new Promise((n,r)=>{Fp(e,t,(s,i)=>{if(s)return r(s);n(i);});})}function Fp(e,t,n){new jp(e,t,n).start();}function Jb(e,t){return new jp(e,t).start()}var kp,ob,ab,hb,gb,yb,wb,Sb,Eb,_b,xb,Cb,Ab,vb,Rb,Nb,Pb,Ib,Db,jb,Fb,Ub,Mb,Bb,qb,Dp,Gb,Wb,Kb,zb,Xb,jp,Np,Up,Mp,Bp=b(()=>{kp=createRequire(import.meta.url);ob=/[\\/]/g;ab=/^[a-z]:[\\/]$/i;hb=(e,t)=>{t.push(e||".");},gb=(e,t,n)=>{let r=e||".";n.every(s=>s(r,true))&&t.push(r);},yb=()=>{};wb=(e,t,n,r)=>{r.every(s=>s(e,false))&&n.files++;},Sb=(e,t,n,r)=>{r.every(s=>s(e,false))&&t.push(e);},Eb=(e,t,n,r)=>{n.files++;},_b=(e,t)=>{t.push(e);},xb=()=>{};Cb=e=>e,Ab=()=>[""].slice(0,0);vb=(e,t,n)=>{e.push({directory:t,files:n,dir:t});},Rb=()=>{};Nb=function(e,t,n){let{queue:r,fs:s,options:{suppressErrors:i}}=t;r.enqueue(),s.realpath(e,(o,a)=>{if(o)return r.dequeue(i?null:o,t);s.stat(a,(l,c)=>{if(l)return r.dequeue(i?null:l,t);if(c.isDirectory()&&Ip(e,a,t))return r.dequeue(null,t);n(c,a),r.dequeue(null,t);});});},Pb=function(e,t,n){let{queue:r,fs:s,options:{suppressErrors:i}}=t;r.enqueue();try{let o=s.realpathSync(e),a=s.statSync(o);if(a.isDirectory()&&Ip(e,o,t))return;n(a,o);}catch(o){if(!i)throw o}};Ib=e=>e.counts,Db=e=>e.groups,jb=e=>e.paths,Fb=e=>e.paths.slice(0,e.options.maxFiles),Ub=(e,t,n)=>(Os(t,n,e.counts,e.options.suppressErrors),null),Mb=(e,t,n)=>(Os(t,n,e.paths,e.options.suppressErrors),null),Bb=(e,t,n)=>(Os(t,n,e.paths.slice(0,e.options.maxFiles),e.options.suppressErrors),null),qb=(e,t,n)=>(Os(t,n,e.groups,e.options.suppressErrors),null);Dp={withFileTypes:true},Gb=(e,t,n,r,s)=>{if(e.queue.enqueue(),r<0)return e.queue.dequeue(null,e);let{fs:i}=e;e.visited.push(t),e.counts.directories++,i.readdir(t||".",Dp,(o,a=[])=>{s(a,n,r),e.queue.dequeue(e.options.suppressErrors?null:o,e);});},Wb=(e,t,n,r,s)=>{let{fs:i}=e;if(r<0)return;e.visited.push(t),e.counts.directories++;let o=[];try{o=i.readdirSync(t||".",Dp);}catch(a){if(!e.options.suppressErrors)throw a}s(o,n,r);};Kb=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));}},zb=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;}},jp=class{root;isSynchronous;state;joinPath;pushDirectory;pushFile;getArray;groupFiles;resolveSymlink;walkDirectory;callbackInvoker;constructor(e,t,n){this.isSynchronous=!n,this.callbackInvoker=Hb(t,this.isSynchronous),this.root=pa(e,t),this.state={root:lb(this.root)?this.root:this.root.slice(0,-1),paths:[""].slice(0,0),groups:[],counts:new zb,options:t,queue:new Kb((r,s)=>this.callbackInvoker(s,r,n)),symlinks:new Map,visited:[""].slice(0,0),controller:new Xb,fs:t.fs||sb},this.joinPath=fb(this.root,t),this.pushDirectory=bb(this.root,t),this.pushFile=Tb(t),this.getArray=$b(t),this.groupFiles=kb(t),this.resolveSymlink=Lb(t,this.isSynchronous),this.walkDirectory=Vb(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,n)=>{let{paths:r,options:{filters:s,resolveSymlinks:i,excludeSymlinks:o,exclude:a,maxFiles:l,signal:c,useRealPaths:p,pathSeparator:u},controller:f}=this.state;if(f.aborted||c&&c.aborted||l&&r.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 g=this.joinPath(m.name,t);this.pushFile(g,h,this.state.counts,s);}else if(m.isDirectory()){let g=pb(m.name,t,this.state.options.pathSeparator);if(a&&a(m.name,g))continue;this.pushDirectory(g,r,s),this.walkDirectory(this.state,g,g,n-1,this.walk);}else if(this.resolveSymlink&&m.isSymbolicLink()){let g=Op(m.name,t);this.resolveSymlink(g,this.state,(y,E)=>{if(y.isDirectory()){if(E=pa(E,this.state.options),a&&a(m.name,p?E:g+u))return;this.walkDirectory(this.state,E,p?E:g+u,n-1,this.walk);}else {E=p?E:g;let A=basename(E),C=pa(dirname(E),this.state.options);E=this.joinPath(A,C),this.pushFile(E,h,this.state.counts,s);}});}}this.groupFiles(this.state.groups,t,h);}};Np=class{constructor(e,t){this.root=e,this.options=t;}withPromise(){return Yb(this.root,this.options)}withCallback(e){Fp(this.root,this.options,e);}sync(){return Jb(this.root,this.options)}},Up=null;try{kp.resolve("picomatch"),Up=kp("picomatch");}catch{}Mp=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 Np(e||".",this.options)}withGlobFunction(e){return this.globFunction=e,this}crawlWithOptions(e,t){return this.options={...this.options,...t},new Np(e||".",this.options)}glob(...e){return this.globFunction?this.globWithOptions(e):this.globWithOptions(e,{dot:true})}globWithOptions(e,...t){let n=this.globFunction||Up;if(!n)throw new Error("Please specify a glob function to use glob matching.");var r=this.globCache[e.join("\0")];return r||(r=n(e,...t),this.globCache[e.join("\0")]=r),this.options.filters.push(s=>r(s)),this}};});var Vn=lt((tR,Vp)=>{var qp="[^\\\\/]",Qb="(?=.)",Hp="[^/]",ma="(?:\\/|$)",Gp="(?:^|\\/)",da=`\\.{1,2}${ma}`,Zb="(?!\\.)",ew=`(?!${Gp}${da})`,tw=`(?!\\.{0,1}${ma})`,nw=`(?!${da})`,rw="[^.\\/]",sw=`${Hp}*?`,iw="/",Wp={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:Qb,QMARK:Hp,END_ANCHOR:ma,DOTS_SLASH:da,NO_DOT:Zb,NO_DOTS:ew,NO_DOT_SLASH:tw,NO_DOTS_SLASH:nw,QMARK_NO_DOT:rw,STAR:sw,START_ANCHOR:Gp,SEP:iw},ow={...Wp,SLASH_LITERAL:"[\\\\/]",QMARK:qp,STAR:`${qp}*?`,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:"\\"},aw={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};Vp.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:aw,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?ow:Wp}};});var Kn=lt($e=>{var{REGEX_BACKSLASH:lw,REGEX_REMOVE_BACKSLASH:cw,REGEX_SPECIAL_CHARS:uw,REGEX_SPECIAL_CHARS_GLOBAL:pw}=Vn();$e.isObject=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);$e.hasRegexChars=e=>uw.test(e);$e.isRegexChar=e=>e.length===1&&$e.hasRegexChars(e);$e.escapeRegex=e=>e.replace(pw,"\\$1");$e.toPosixSlashes=e=>e.replace(lw,"/");$e.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};$e.removeBackslashes=e=>e.replace(cw,t=>t==="\\"?"":t);$e.escapeLast=(e,t,n)=>{let r=e.lastIndexOf(t,n);return r===-1?e:e[r-1]==="\\"?$e.escapeLast(e,t,r-1):`${e.slice(0,r)}\\${e.slice(r)}`};$e.removePrefix=(e,t={})=>{let n=e;return n.startsWith("./")&&(n=n.slice(2),t.prefix="./"),n};$e.wrapOutput=(e,t={},n={})=>{let r=n.contains?"":"^",s=n.contains?"":"$",i=`${r}(?:${e})${s}`;return t.negated===true&&(i=`(?:^(?!${i}).*$)`),i};$e.basename=(e,{windows:t}={})=>{let n=e.split(t?/[\\/]/:"/"),r=n[n.length-1];return r===""?n[n.length-2]:r};});var ef=lt((rR,Zp)=>{var Kp=Kn(),{CHAR_ASTERISK:ha,CHAR_AT:fw,CHAR_BACKWARD_SLASH:zn,CHAR_COMMA:mw,CHAR_DOT:ga,CHAR_EXCLAMATION_MARK:ya,CHAR_FORWARD_SLASH:Qp,CHAR_LEFT_CURLY_BRACE:ba,CHAR_LEFT_PARENTHESES:wa,CHAR_LEFT_SQUARE_BRACKET:dw,CHAR_PLUS:hw,CHAR_QUESTION_MARK:zp,CHAR_RIGHT_CURLY_BRACE:gw,CHAR_RIGHT_PARENTHESES:Xp,CHAR_RIGHT_SQUARE_BRACKET:yw}=Vn(),Yp=e=>e===Qp||e===zn,Jp=e=>{e.isPrefix!==true&&(e.depth=e.isGlobstar?1/0:1);},bw=(e,t)=>{let n=t||{},r=e.length-1,s=n.parts===true||n.scanToEnd===true,i=[],o=[],a=[],l=e,c=-1,p=0,u=0,f=false,h=false,d=false,m=false,g=false,y=false,E=false,A=false,C=false,v=false,$=0,T,x,O={value:"",depth:0,isGlob:false},w=()=>c>=r,I=()=>l.charCodeAt(c+1),P=()=>(T=x,l.charCodeAt(++c));for(;c<r;){x=P();let B;if(x===zn){E=O.backslashes=true,x=P(),x===ba&&(y=true);continue}if(y===true||x===ba){for($++;w()!==true&&(x=P());){if(x===zn){E=O.backslashes=true,P();continue}if(x===ba){$++;continue}if(y!==true&&x===ga&&(x=P())===ga){if(f=O.isBrace=true,d=O.isGlob=true,v=true,s===true)continue;break}if(y!==true&&x===mw){if(f=O.isBrace=true,d=O.isGlob=true,v=true,s===true)continue;break}if(x===gw&&($--,$===0)){y=false,f=O.isBrace=true,v=true;break}}if(s===true)continue;break}if(x===Qp){if(i.push(c),o.push(O),O={value:"",depth:0,isGlob:false},v===true)continue;if(T===ga&&c===p+1){p+=2;continue}u=c+1;continue}if(n.noext!==true&&(x===hw||x===fw||x===ha||x===zp||x===ya)===true&&I()===wa){if(d=O.isGlob=true,m=O.isExtglob=true,v=true,x===ya&&c===p&&(C=true),s===true){for(;w()!==true&&(x=P());){if(x===zn){E=O.backslashes=true,x=P();continue}if(x===Xp){d=O.isGlob=true,v=true;break}}continue}break}if(x===ha){if(T===ha&&(g=O.isGlobstar=true),d=O.isGlob=true,v=true,s===true)continue;break}if(x===zp){if(d=O.isGlob=true,v=true,s===true)continue;break}if(x===dw){for(;w()!==true&&(B=P());){if(B===zn){E=O.backslashes=true,P();continue}if(B===yw){h=O.isBracket=true,d=O.isGlob=true,v=true;break}}if(s===true)continue;break}if(n.nonegate!==true&&x===ya&&c===p){A=O.negated=true,p++;continue}if(n.noparen!==true&&x===wa){if(d=O.isGlob=true,s===true){for(;w()!==true&&(x=P());){if(x===wa){E=O.backslashes=true,x=P();continue}if(x===Xp){v=true;break}}continue}break}if(d===true){if(v=true,s===true)continue;break}}n.noext===true&&(m=false,d=false);let j=l,S="",_="";p>0&&(S=l.slice(0,p),l=l.slice(p),u-=p),j&&d===true&&u>0?(j=l.slice(0,u),_=l.slice(u)):d===true?(j="",_=l):j=l,j&&j!==""&&j!=="/"&&j!==l&&Yp(j.charCodeAt(j.length-1))&&(j=j.slice(0,-1)),n.unescape===true&&(_&&(_=Kp.removeBackslashes(_)),j&&E===true&&(j=Kp.removeBackslashes(j)));let Z={prefix:S,input:e,start:p,base:j,glob:_,isBrace:f,isBracket:h,isGlob:d,isExtglob:m,isGlobstar:g,negated:A,negatedExtglob:C};if(n.tokens===true&&(Z.maxDepth=0,Yp(x)||o.push(O),Z.tokens=o),n.parts===true||n.tokens===true){let B;for(let D=0;D<i.length;D++){let oe=B?B+1:p,ce=i[D],ot=e.slice(oe,ce);n.tokens&&(D===0&&p!==0?(o[D].isPrefix=true,o[D].value=S):o[D].value=ot,Jp(o[D]),Z.maxDepth+=o[D].depth),(D!==0||ot!=="")&&a.push(ot),B=ce;}if(B&&B+1<e.length){let D=e.slice(B+1);a.push(D),n.tokens&&(o[o.length-1].value=D,Jp(o[o.length-1]),Z.maxDepth+=o[o.length-1].depth);}Z.slashes=i,Z.parts=a;}return Z};Zp.exports=bw;});var of=lt((sR,sf)=>{var Xn=Vn(),Pe=Kn(),{MAX_LENGTH:Is,POSIX_REGEX_SOURCE:ww,REGEX_NON_SPECIAL_CHARS:Sw,REGEX_SPECIAL_CHARS_BACKREF:Ew,REPLACEMENTS:tf}=Xn,_w=(e,t)=>{if(typeof t.expandRange=="function")return t.expandRange(...e,t);e.sort();let n=`[${e.join("-")}]`;try{new RegExp(n);}catch{return e.map(s=>Pe.escapeRegex(s)).join("..")}return n},rn=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`,nf=e=>{let t=[],n=0,r=0,s=0,i="",o=false;for(let a of e){if(o===true){i+=a,o=false;continue}if(a==="\\"){i+=a,o=true;continue}if(a==='"'){s=s===1?0:1,i+=a;continue}if(s===0){if(a==="[")n++;else if(a==="]"&&n>0)n--;else if(n===0){if(a==="(")r++;else if(a===")"&&r>0)r--;else if(a==="|"&&r===0){t.push(i),i="";continue}}}i+=a;}return t.push(i),t},xw=e=>{let t=false;for(let n of e){if(t===true){t=false;continue}if(n==="\\"){t=true;continue}if(/[?*+@!()[\]{}]/.test(n))return false}return true},rf=e=>{let t=e.trim(),n=true;for(;n===true;)n=false,/^@\([^\\()[\]{}|]+\)$/.test(t)&&(t=t.slice(2,-1),n=true);if(xw(t))return t.replace(/\\(.)/g,"$1")},Tw=e=>{let t=e.map(rf).filter(Boolean);for(let n=0;n<t.length;n++)for(let r=n+1;r<t.length;r++){let s=t[n],i=t[r],o=s[0];if(!(!o||s!==o.repeat(s.length)||i!==o.repeat(i.length))&&(s===i||s.startsWith(i)||i.startsWith(s)))return true}return false},Sa=(e,t=true)=>{if(e[0]!=="+"&&e[0]!=="*"||e[1]!=="(")return;let n=0,r=0,s=0,i=false;for(let o=1;o<e.length;o++){let a=e[o];if(i===true){i=false;continue}if(a==="\\"){i=true;continue}if(a==='"'){s=s===1?0:1;continue}if(s!==1){if(a==="["){n++;continue}if(a==="]"&&n>0){n--;continue}if(!(n>0)){if(a==="("){r++;continue}if(a===")"&&(r--,r===0))return t===true&&o!==e.length-1?void 0:{type:e[0],body:e.slice(2,o),end:o}}}}},Cw=e=>{let t=0,n=[];for(;t<e.length;){let s=Sa(e.slice(t),false);if(!s||s.type!=="*")return;let i=nf(s.body).map(a=>a.trim());if(i.length!==1)return;let o=rf(i[0]);if(!o||o.length!==1)return;n.push(o),t+=s.end+1;}return n.length<1?void 0:`${n.length===1?Pe.escapeRegex(n[0]):`[${n.map(s=>Pe.escapeRegex(s)).join("")}]`}*`},Aw=e=>{let t=0,n=e.trim(),r=Sa(n);for(;r;)t++,n=r.body.trim(),r=Sa(n);return t},$w=(e,t)=>{if(t.maxExtglobRecursion===false)return {risky:false};let n=typeof t.maxExtglobRecursion=="number"?t.maxExtglobRecursion:Xn.DEFAULT_MAX_EXTGLOB_RECURSION,r=nf(e).map(s=>s.trim());if(r.length>1&&(r.some(s=>s==="")||r.some(s=>/^[*?]+$/.test(s))||Tw(r)))return {risky:true};for(let s of r){let i=Cw(s);if(i)return {risky:true,safeOutput:i};if(Aw(s)>n)return {risky:true}}return {risky:false}},Ea=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a string");e=tf[e]||e;let n={...t},r=typeof n.maxLength=="number"?Math.min(Is,n.maxLength):Is,s=e.length;if(s>r)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${r}`);let i={type:"bos",value:"",output:n.prepend||""},o=[i],a=n.capture?"":"?:",l=Xn.globChars(n.windows),c=Xn.extglobChars(l),{DOT_LITERAL:p,PLUS_LITERAL:u,SLASH_LITERAL:f,ONE_CHAR:h,DOTS_SLASH:d,NO_DOT:m,NO_DOT_SLASH:g,NO_DOTS_SLASH:y,QMARK:E,QMARK_NO_DOT:A,STAR:C,START_ANCHOR:v}=l,$=N=>`(${a}(?:(?!${v}${N.dot?d:p}).)*?)`,T=n.dot?"":m,x=n.dot?E:A,O=n.bash===true?$(n):C;n.capture&&(O=`(${O})`),typeof n.noext=="boolean"&&(n.noextglob=n.noext);let w={input:e,index:-1,start:0,dot:n.dot===true,consumed:"",output:"",prefix:"",backtrack:false,negated:false,brackets:0,braces:0,parens:0,quotes:0,globstar:false,tokens:o};e=Pe.removePrefix(e,w),s=e.length;let I=[],P=[],j=[],S=i,_,Z=()=>w.index===s-1,B=w.peek=(N=1)=>e[w.index+N],D=w.advance=()=>e[++w.index]||"",oe=()=>e.slice(w.index+1),ce=(N="",ae=0)=>{w.consumed+=N,w.index+=ae;},ot=N=>{w.output+=N.output!=null?N.output:N.value,ce(N.value);},Bh=()=>{let N=1;for(;B()==="!"&&(B(2)!=="("||B(3)==="?");)D(),w.start++,N++;return N%2===0?false:(w.negated=true,w.start++,true)},Dr=N=>{w[N]++,j.push(N);},at=N=>{w[N]--,j.pop();},H=N=>{if(S.type==="globstar"){let ae=w.braces>0&&(N.type==="comma"||N.type==="brace"),R=N.extglob===true||I.length&&(N.type==="pipe"||N.type==="paren");N.type!=="slash"&&N.type!=="paren"&&!ae&&!R&&(w.output=w.output.slice(0,-S.output.length),S.type="star",S.value="*",S.output=O,w.output+=S.output);}if(I.length&&N.type!=="paren"&&(I[I.length-1].inner+=N.value),(N.value||N.output)&&ot(N),S&&S.type==="text"&&N.type==="text"){S.output=(S.output||S.value)+N.value,S.value+=N.value;return}N.prev=S,o.push(N),S=N;},jr=(N,ae)=>{let R={...c[ae],conditions:1,inner:""};R.prev=S,R.parens=w.parens,R.output=w.output,R.startIndex=w.index,R.tokensIndex=o.length;let G=(n.capture?"(":"")+R.open;Dr("parens"),H({type:N,value:ae,output:w.output?"":h}),H({type:"paren",extglob:true,value:D(),output:G}),I.push(R);},qh=N=>{let ae=e.slice(N.startIndex,w.index+1),R=e.slice(N.startIndex+2,w.index),G=$w(R,n);if((N.type==="plus"||N.type==="star")&&G.risky){let te=G.safeOutput?(N.output?"":h)+(n.capture?`(${G.safeOutput})`:G.safeOutput):void 0,ze=o[N.tokensIndex];ze.type="text",ze.value=ae,ze.output=te||Pe.escapeRegex(ae);for(let Xe=N.tokensIndex+1;Xe<o.length;Xe++)o[Xe].value="",o[Xe].output="",delete o[Xe].suffix;w.output=N.output+ze.output,w.backtrack=true,H({type:"paren",extglob:true,value:_,output:""}),at("parens");return}let se=N.close+(n.capture?")":""),he;if(N.type==="negate"){let te=O;if(N.inner&&N.inner.length>1&&N.inner.includes("/")&&(te=$(n)),(te!==O||Z()||/^\)+$/.test(oe()))&&(se=N.close=`)$))${te}`),N.inner.includes("*")&&(he=oe())&&/^\.[^\\/.]+$/.test(he)){let ze=Ea(he,{...t,fastpaths:false}).output;se=N.close=`)${ze})${te})`;}N.prev.type==="bos"&&(w.negatedExtglob=true);}H({type:"paren",extglob:true,value:_,output:se}),at("parens");};if(n.fastpaths!==false&&!/(^[*!]|[/()[\]{}"])/.test(e)){let N=false,ae=e.replace(Ew,(R,G,se,he,te,ze)=>he==="\\"?(N=true,R):he==="?"?G?G+he+(te?E.repeat(te.length):""):ze===0?x+(te?E.repeat(te.length):""):E.repeat(se.length):he==="."?p.repeat(se.length):he==="*"?G?G+he+(te?O:""):O:G?R:`\\${R}`);return N===true&&(n.unescape===true?ae=ae.replace(/\\/g,""):ae=ae.replace(/\\+/g,R=>R.length%2===0?"\\\\":R?"\\":"")),ae===e&&n.contains===true?(w.output=e,w):(w.output=Pe.wrapOutput(ae,w,t),w)}for(;!Z();){if(_=D(),_==="\0")continue;if(_==="\\"){let R=B();if(R==="/"&&n.bash!==true||R==="."||R===";")continue;if(!R){_+="\\",H({type:"text",value:_});continue}let G=/^\\+/.exec(oe()),se=0;if(G&&G[0].length>2&&(se=G[0].length,w.index+=se,se%2!==0&&(_+="\\")),n.unescape===true?_=D():_+=D(),w.brackets===0){H({type:"text",value:_});continue}}if(w.brackets>0&&(_!=="]"||S.value==="["||S.value==="[^")){if(n.posix!==false&&_===":"){let R=S.value.slice(1);if(R.includes("[")&&(S.posix=true,R.includes(":"))){let G=S.value.lastIndexOf("["),se=S.value.slice(0,G),he=S.value.slice(G+2),te=ww[he];if(te){S.value=se+te,w.backtrack=true,D(),!i.output&&o.indexOf(S)===1&&(i.output=h);continue}}}(_==="["&&B()!==":"||_==="-"&&B()==="]")&&(_=`\\${_}`),_==="]"&&(S.value==="["||S.value==="[^")&&(_=`\\${_}`),n.posix===true&&_==="!"&&S.value==="["&&(_="^"),S.value+=_,ot({value:_});continue}if(w.quotes===1&&_!=='"'){_=Pe.escapeRegex(_),S.value+=_,ot({value:_});continue}if(_==='"'){w.quotes=w.quotes===1?0:1,n.keepQuotes===true&&H({type:"text",value:_});continue}if(_==="("){Dr("parens"),H({type:"paren",value:_});continue}if(_===")"){if(w.parens===0&&n.strictBrackets===true)throw new SyntaxError(rn("opening","("));let R=I[I.length-1];if(R&&w.parens===R.parens+1){qh(I.pop());continue}H({type:"paren",value:_,output:w.parens?")":"\\)"}),at("parens");continue}if(_==="["){if(n.nobracket===true||!oe().includes("]")){if(n.nobracket!==true&&n.strictBrackets===true)throw new SyntaxError(rn("closing","]"));_=`\\${_}`;}else Dr("brackets");H({type:"bracket",value:_});continue}if(_==="]"){if(n.nobracket===true||S&&S.type==="bracket"&&S.value.length===1){H({type:"text",value:_,output:`\\${_}`});continue}if(w.brackets===0){if(n.strictBrackets===true)throw new SyntaxError(rn("opening","["));H({type:"text",value:_,output:`\\${_}`});continue}at("brackets");let R=S.value.slice(1);if(S.posix!==true&&R[0]==="^"&&!R.includes("/")&&(_=`/${_}`),S.value+=_,ot({value:_}),n.literalBrackets===false||Pe.hasRegexChars(R))continue;let G=Pe.escapeRegex(S.value);if(w.output=w.output.slice(0,-S.value.length),n.literalBrackets===true){w.output+=G,S.value=G;continue}S.value=`(${a}${G}|${S.value})`,w.output+=S.value;continue}if(_==="{"&&n.nobrace!==true){Dr("braces");let R={type:"brace",value:_,output:"(",outputIndex:w.output.length,tokensIndex:w.tokens.length};P.push(R),H(R);continue}if(_==="}"){let R=P[P.length-1];if(n.nobrace===true||!R){H({type:"text",value:_,output:_});continue}let G=")";if(R.dots===true){let se=o.slice(),he=[];for(let te=se.length-1;te>=0&&(o.pop(),se[te].type!=="brace");te--)se[te].type!=="dots"&&he.unshift(se[te].value);G=_w(he,n),w.backtrack=true;}if(R.comma!==true&&R.dots!==true){let se=w.output.slice(0,R.outputIndex),he=w.tokens.slice(R.tokensIndex);R.value=R.output="\\{",_=G="\\}",w.output=se;for(let te of he)w.output+=te.output||te.value;}H({type:"brace",value:_,output:G}),at("braces"),P.pop();continue}if(_==="|"){I.length>0&&I[I.length-1].conditions++,H({type:"text",value:_});continue}if(_===","){let R=_,G=P[P.length-1];G&&j[j.length-1]==="braces"&&(G.comma=true,R="|"),H({type:"comma",value:_,output:R});continue}if(_==="/"){if(S.type==="dot"&&w.index===w.start+1){w.start=w.index+1,w.consumed="",w.output="",o.pop(),S=i;continue}H({type:"slash",value:_,output:f});continue}if(_==="."){if(w.braces>0&&S.type==="dot"){S.value==="."&&(S.output=p);let R=P[P.length-1];S.type="dots",S.output+=_,S.value+=_,R.dots=true;continue}if(w.braces+w.parens===0&&S.type!=="bos"&&S.type!=="slash"){H({type:"text",value:_,output:p});continue}H({type:"dot",value:_,output:p});continue}if(_==="?"){if(!(S&&S.value==="(")&&n.noextglob!==true&&B()==="("&&B(2)!=="?"){jr("qmark",_);continue}if(S&&S.type==="paren"){let G=B(),se=_;(S.value==="("&&!/[!=<:]/.test(G)||G==="<"&&!/<([!=]|\w+>)/.test(oe()))&&(se=`\\${_}`),H({type:"text",value:_,output:se});continue}if(n.dot!==true&&(S.type==="slash"||S.type==="bos")){H({type:"qmark",value:_,output:A});continue}H({type:"qmark",value:_,output:E});continue}if(_==="!"){if(n.noextglob!==true&&B()==="("&&(B(2)!=="?"||!/[!=<:]/.test(B(3)))){jr("negate",_);continue}if(n.nonegate!==true&&w.index===0){Bh();continue}}if(_==="+"){if(n.noextglob!==true&&B()==="("&&B(2)!=="?"){jr("plus",_);continue}if(S&&S.value==="("||n.regex===false){H({type:"plus",value:_,output:u});continue}if(S&&(S.type==="bracket"||S.type==="paren"||S.type==="brace")||w.parens>0){H({type:"plus",value:_});continue}H({type:"plus",value:u});continue}if(_==="@"){if(n.noextglob!==true&&B()==="("&&B(2)!=="?"){H({type:"at",extglob:true,value:_,output:""});continue}H({type:"text",value:_});continue}if(_!=="*"){(_==="$"||_==="^")&&(_=`\\${_}`);let R=Sw.exec(oe());R&&(_+=R[0],w.index+=R[0].length),H({type:"text",value:_});continue}if(S&&(S.type==="globstar"||S.star===true)){S.type="star",S.star=true,S.value+=_,S.output=O,w.backtrack=true,w.globstar=true,ce(_);continue}let N=oe();if(n.noextglob!==true&&/^\([^?]/.test(N)){jr("star",_);continue}if(S.type==="star"){if(n.noglobstar===true){ce(_);continue}let R=S.prev,G=R.prev,se=R.type==="slash"||R.type==="bos",he=G&&(G.type==="star"||G.type==="globstar");if(n.bash===true&&(!se||N[0]&&N[0]!=="/")){H({type:"star",value:_,output:""});continue}let te=w.braces>0&&(R.type==="comma"||R.type==="brace"),ze=I.length&&(R.type==="pipe"||R.type==="paren");if(!se&&R.type!=="paren"&&!te&&!ze){H({type:"star",value:_,output:""});continue}for(;N.slice(0,3)==="/**";){let Xe=e[w.index+4];if(Xe&&Xe!=="/")break;N=N.slice(3),ce("/**",3);}if(R.type==="bos"&&Z()){S.type="globstar",S.value+=_,S.output=$(n),w.output=S.output,w.globstar=true,ce(_);continue}if(R.type==="slash"&&R.prev.type!=="bos"&&!he&&Z()){w.output=w.output.slice(0,-(R.output+S.output).length),R.output=`(?:${R.output}`,S.type="globstar",S.output=$(n)+(n.strictSlashes?")":"|$)"),S.value+=_,w.globstar=true,w.output+=R.output+S.output,ce(_);continue}if(R.type==="slash"&&R.prev.type!=="bos"&&N[0]==="/"){let Xe=N[1]!==void 0?"|$":"";w.output=w.output.slice(0,-(R.output+S.output).length),R.output=`(?:${R.output}`,S.type="globstar",S.output=`${$(n)}${f}|${f}${Xe})`,S.value+=_,w.output+=R.output+S.output,w.globstar=true,ce(_+D()),H({type:"slash",value:"/",output:""});continue}if(R.type==="bos"&&N[0]==="/"){S.type="globstar",S.value+=_,S.output=`(?:^|${f}|${$(n)}${f})`,w.output=S.output,w.globstar=true,ce(_+D()),H({type:"slash",value:"/",output:""});continue}w.output=w.output.slice(0,-S.output.length),S.type="globstar",S.output=$(n),S.value+=_,w.output+=S.output,w.globstar=true,ce(_);continue}let ae={type:"star",value:_,output:O};if(n.bash===true){ae.output=".*?",(S.type==="bos"||S.type==="slash")&&(ae.output=T+ae.output),H(ae);continue}if(S&&(S.type==="bracket"||S.type==="paren")&&n.regex===true){ae.output=_,H(ae);continue}(w.index===w.start||S.type==="slash"||S.type==="dot")&&(S.type==="dot"?(w.output+=g,S.output+=g):n.dot===true?(w.output+=y,S.output+=y):(w.output+=T,S.output+=T),B()!=="*"&&(w.output+=h,S.output+=h)),H(ae);}for(;w.brackets>0;){if(n.strictBrackets===true)throw new SyntaxError(rn("closing","]"));w.output=Pe.escapeLast(w.output,"["),at("brackets");}for(;w.parens>0;){if(n.strictBrackets===true)throw new SyntaxError(rn("closing",")"));w.output=Pe.escapeLast(w.output,"("),at("parens");}for(;w.braces>0;){if(n.strictBrackets===true)throw new SyntaxError(rn("closing","}"));w.output=Pe.escapeLast(w.output,"{"),at("braces");}if(n.strictSlashes!==true&&(S.type==="star"||S.type==="bracket")&&H({type:"maybe_slash",value:"",output:`${f}?`}),w.backtrack===true){w.output="";for(let N of w.tokens)w.output+=N.output!=null?N.output:N.value,N.suffix&&(w.output+=N.suffix);}return w};Ea.fastpaths=(e,t)=>{let n={...t},r=typeof n.maxLength=="number"?Math.min(Is,n.maxLength):Is,s=e.length;if(s>r)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${r}`);e=tf[e]||e;let{DOT_LITERAL:i,SLASH_LITERAL:o,ONE_CHAR:a,DOTS_SLASH:l,NO_DOT:c,NO_DOTS:p,NO_DOTS_SLASH:u,STAR:f,START_ANCHOR:h}=Xn.globChars(n.windows),d=n.dot?p:c,m=n.dot?u:c,g=n.capture?"":"?:",y={negated:false,prefix:""},E=n.bash===true?".*?":f;n.capture&&(E=`(${E})`);let A=T=>T.noglobstar===true?E:`(${g}(?:(?!${h}${T.dot?l:i}).)*?)`,C=T=>{switch(T){case "*":return `${d}${a}${E}`;case ".*":return `${i}${a}${E}`;case "*.*":return `${d}${E}${i}${a}${E}`;case "*/*":return `${d}${E}${o}${a}${m}${E}`;case "**":return d+A(n);case "**/*":return `(?:${d}${A(n)}${o})?${m}${a}${E}`;case "**/*.*":return `(?:${d}${A(n)}${o})?${m}${E}${i}${a}${E}`;case "**/.*":return `(?:${d}${A(n)}${o})?${i}${a}${E}`;default:{let x=/^(.*?)\.(\w+)$/.exec(T);if(!x)return;let O=C(x[1]);return O?O+i+x[2]:void 0}}},v=Pe.removePrefix(e,y),$=C(v);return $&&n.strictSlashes!==true&&($+=`${o}?`),$};sf.exports=Ea;});var cf=lt((iR,lf)=>{var vw=ef(),_a=of(),af=Kn(),Rw=Vn(),kw=e=>e&&typeof e=="object"&&!Array.isArray(e),pe=(e,t,n=false)=>{if(Array.isArray(e)){let p=e.map(f=>pe(f,t,n));return f=>{for(let h of p){let d=h(f);if(d)return d}return false}}let r=kw(e)&&e.tokens&&e.input;if(e===""||typeof e!="string"&&!r)throw new TypeError("Expected pattern to be a non-empty string");let s=t||{},i=s.windows,o=r?pe.compileRe(e,t):pe.makeRe(e,t,false,true),a=o.state;delete o.state;let l=()=>false;if(s.ignore){let p={...t,ignore:null,onMatch:null,onResult:null};l=pe(s.ignore,p,n);}let c=(p,u=false)=>{let{isMatch:f,match:h,output:d}=pe.test(p,o,t,{glob:e,posix:i}),m={glob:e,state:a,regex:o,posix:i,input:p,output:d,match:h,isMatch:f};return typeof s.onResult=="function"&&s.onResult(m),f===false?(m.isMatch=false,u?m:false):l(p)?(typeof s.onIgnore=="function"&&s.onIgnore(m),m.isMatch=false,u?m:false):(typeof s.onMatch=="function"&&s.onMatch(m),u?m:true)};return n&&(c.state=a),c};pe.test=(e,t,n,{glob:r,posix:s}={})=>{if(typeof e!="string")throw new TypeError("Expected input to be a string");if(e==="")return {isMatch:false,output:""};let i=n||{},o=i.format||(s?af.toPosixSlashes:null),a=e===r,l=a&&o?o(e):e;return a===false&&(l=o?o(e):e,a=l===r),(a===false||i.capture===true)&&(i.matchBase===true||i.basename===true?a=pe.matchBase(e,t,n,s):a=t.exec(l)),{isMatch:!!a,match:a,output:l}};pe.matchBase=(e,t,n)=>(t instanceof RegExp?t:pe.makeRe(t,n)).test(af.basename(e));pe.isMatch=(e,t,n)=>pe(t,n)(e);pe.parse=(e,t)=>Array.isArray(e)?e.map(n=>pe.parse(n,t)):_a(e,{...t,fastpaths:false});pe.scan=(e,t)=>vw(e,t);pe.compileRe=(e,t,n=false,r=false)=>{if(n===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 r===true&&(l.state=e),l};pe.makeRe=(e,t={},n=false,r=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=_a.fastpaths(e,t)),s.output||(s=_a(e,t)),pe.compileRe(s,t,n,r)};pe.toRegex=(e,t)=>{try{let n=t||{};return new RegExp(e,n.flags||(n.nocase?"i":""))}catch(n){if(t&&t.debug===true)throw n;return /$^/}};pe.constants=Rw;lf.exports=pe;});var mf=lt((oR,ff)=>{var uf=cf(),Nw=Kn();function pf(e,t,n=false){return t&&(t.windows===null||t.windows===void 0)&&(t={...t,windows:Nw.isWindows()}),uf(e,t,n)}Object.assign(pf,uf);ff.exports=pf;});function Gw(e,t={}){let n=e.length,r=Array(n),s=Array(n),i,o;for(i=0;i<n;i++){let a=wf(e[i]);r[i]=a;let l=a.length,c=Array(l);for(o=0;o<l;o++)c[o]=(0, sn.default)(a[o],t);s[i]=c;}return a=>{let l=a.split("/");if(l[0]===".."&&Hw.test(a))return true;for(i=0;i<n;i++){let c=r[i],p=s[i],u=l.length,f=Math.min(u,c.length);for(o=0;o<f;){let h=c[o];if(h.includes("/"))return true;if(!p[o](l[o]))break;if(!t.noglobstar&&h==="**")return true;o++;}if(o===u)return true}return false}}function df(e,t,n){if(e===t||t.startsWith(`${e}/`)){if(n){let s=e.length+ +!Vw(e);return (i,o)=>i.slice(s,o?-1:void 0)||"."}let r=t.slice(e.length+1);return r?(s,i)=>{if(s===".")return r;let o=`${r}/${s}`;return i?o.slice(0,-1):o}:(s,i)=>i&&s!=="."?s.slice(0,-1):s}return n?r=>posix.relative(e,r)||".":r=>posix.relative(e,`${t}/${r}`)||"."}function Kw(e,t){if(t.startsWith(`${e}/`)){let n=t.slice(e.length+1);return r=>`${n}/${r}`}return n=>{let r=posix.relative(e,`${t}/${n}`);return n[n.length-1]==="/"&&r!==""?`${r}/`:r||"."}}function hf(e){return e.replace(qw,t=>`${t}/`)}function wf(e){var t;let n=sn.default.scan(e,zw);return !((t=n.parts)===null||t===void 0)&&t.length?n.parts:[e]}function eS(e,t){let n=sn.default.scan(e);return n.isGlob||n.negated}function Yn(...e){console.log(`[tinyglobby ${new Date().toLocaleTimeString("es")}]`,...e);}function Sf(e){return typeof e=="string"?[e]:e??[]}function xa(e,t,n,r){var s;let i=t.cwd,o=e;e[e.length-1]==="/"&&(o=e.slice(0,-1)),o[o.length-1]!=="*"&&t.expandDirectories&&(o+="/**");let a=Zw(i);o=isAbsolute(o.replace(nS,""))?posix.relative(a,o):posix.normalize(o);let l=(s=tS.exec(o))===null||s===void 0?void 0:s[0],c=wf(o);if(l){let u=(l.length+1)/3,f=0,h=a.split("/");for(;f<u&&c[f+u]===h[h.length+f-u];)o=o.slice(0,(u-f-1)*3)+o.slice((u-f)*3+c[f+u].length+1)||".",f++;let d=posix.join(i,l.slice(f*3));d[0]!=="."&&n.root.length>d.length&&(n.root=hf(d),n.depthOffset=-u+f);}if(!r&&n.depthOffset>=0){var p;(p=n.commonPath)!==null&&p!==void 0||(n.commonPath=c);let u=[],f=Math.min(n.commonPath.length,c.length);for(let h=0;h<f;h++){let d=c[h];if(d==="**"&&!c[h+1]){u.pop();break}if(h===c.length-1||d!==n.commonPath[h]||eS(d))break;u.push(d);}n.depthOffset=u.length,n.commonPath=u,n.root=hf(u.length>0?posix.join(i,...u):i);}return o}function rS(e,t,n){let r=[],s=[];for(let i of e.ignore)i&&(i[0]!=="!"||i[1]==="(")&&s.push(xa(i,e,n,true));for(let i of t)i&&(i[0]!=="!"||i[1]==="("?r.push(xa(i,e,n,false)):(i[1]!=="!"||i[2]==="(")&&s.push(xa(i.slice(1),e,n,true)));return {match:r,ignore:s}}function sS(e,t){let n=e.cwd,r={root:n,depthOffset:0},s=rS(e,t,r);e.debug&&Yn("internal processing patterns:",s);let{absolute:i,caseSensitiveMatch:o,debug:a,dot:l,followSymbolicLinks:c,onlyDirectories:p}=e,u=r.root.replace(yf,""),f={dot:l,nobrace:e.braceExpansion===false,nocase:!o,noextglob:e.extglob===false,noglobstar:e.globstar===false,posix:true},h=(0, sn.default)(s.match,f),d=(0, sn.default)(s.ignore,f),m=Gw(s.match,f),g=df(n,u,i),y=i?g:df(n,u,true),E=(v,$)=>{let T=y($,true);return T!=="."&&!m(T)||d(T)},A;e.deep!==void 0&&(A=Math.round(e.deep-r.depthOffset));let C=new Mp({filters:[a?(v,$)=>{let T=g(v,$),x=h(T)&&!d(T);return x&&Yn(`matched ${T}`),x}:(v,$)=>{let T=g(v,$);return h(T)&&!d(T)}],exclude:a?(v,$)=>{let T=E(v,$);return Yn(`${T?"skipped":"crawling"} ${$}`),T}:E,fs:e.fs,pathSeparator:"/",relativePaths:!i,resolvePaths:i,includeBasePath:i,resolveSymlinks:c,excludeSymlinks:!c,excludeFiles:p,includeDirs:p||!e.onlyFiles,maxDepth:A,signal:e.signal}).crawl(u);return e.debug&&Yn("internal properties:",{...r,root:u}),[C,n!==u&&!i&&Kw(n,u)]}function iS(e,t){if(t)for(let n=e.length-1;n>=0;n--)e[n]=t(e[n]);return e}function oS(e){let t=Object.assign({},e);for(let n in gf)t[n]===void 0&&Object.assign(t,{[n]:gf[n]});return t.cwd=(t.cwd instanceof URL?fileURLToPath$1(t.cwd):resolve(t.cwd||process.cwd())).replace(yf,"/"),t.ignore=Sf(t.ignore),t.fs&&(t.fs={readdir:t.fs.readdir||readdir,readdirSync:t.fs.readdirSync||readdirSync,realpath:t.fs.realpath||realpath,realpathSync:t.fs.realpathSync||realpathSync,stat:t.fs.stat||stat,statSync:t.fs.statSync||statSync$1}),t.debug&&Yn("globbing with options:",t),t}function aS(e,t={}){var n;if(e&&t?.patterns)throw new Error("Cannot pass patterns as both an argument and an option");let r=Bw(e)||typeof e=="string",s=Sf((n=r?e:e.patterns)!==null&&n!==void 0?n:"**/*"),i=oS(r?t:e);return s.length>0?sS(i,s):[]}async function Jn(e,t){let[n,r]=aS(e,t);return n?iS(await n.withPromise(),r):[]}var sn,Bw,yf,qw,bf,Hw,Ww,Vw,zw,Xw,Yw,Jw,Qw,Zw,tS,nS,gf,Ta=b(()=>{Bp();sn=V(mf()),Bw=Array.isArray,yf=/\\/g,qw=/^[A-Za-z]:$/,bf=process.platform==="win32",Hw=/^(\/?\.\.)+$/;Ww=/^[A-Z]:\/$/i,Vw=bf?e=>Ww.test(e):e=>e==="/";zw={parts:true};Xw=/(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g,Yw=/(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g,Jw=e=>e.replace(Xw,"\\$&"),Qw=e=>e.replace(Yw,"\\$&"),Zw=bf?Qw:Jw;tS=/^(\/?\.\.)+/,nS=/\\(?=[()[\]{}!*+?@|])/g;gf={caseSensitiveMatch:true,debug:!!process.env.TINYGLOBBY_DEBUG,expandDirectories:true,followSymbolicLinks:true,onlyFiles:true};});function _f(e){return _e(e.connection)==="sqlite"?"./sqlite-migrations/*.sql":"./migrations/*.sql"}function It(e){return Ie__default.posix.dirname(_f(e))}async function De(e){let t=Ie__default.join(process.cwd(),"supabase"),n=await Jn([_f(e)],{cwd:t,absolute:true}),r=[];for(let s of n){let i=Ie__default.basename(s),o=lS.exec(i);if(!o)continue;let a=await de__default.readFile(s,"utf-8");r.push({version:o[1],name:o[2]??null,filename:i,path:s,sql:a});}return r.sort((s,i)=>s.version.localeCompare(i.version))}async function Zn(e){return (await De(e)).map(n=>n.sql).join(`
90
- `)}function Ca(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=Ca()){let n=e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"");return n.length>0?`${t}_${n}.sql`:`${t}.sql`}async function xf(e,t,n){let r=Ie__default.join(process.cwd(),"supabase",It(e));Ce(r);let s=Aa(t,n?.ts),i=Ie__default.join(r,s);return await de__default.writeFile(i,"",{flag:"wx"}),i}var lS,dt=b(()=>{Ta();mt();Tt();lS=/^(\d{14})(?:_([^.]+))?\.sql$/;});function er(e){if("String"in e)return e.String.sval}function nt(e){return e.map(er).filter(t=>t!=null)}function ht(e){return e==null?[]:e.List!==void 0?e.List.items||[]:Array.isArray(e)?e:[e]}function Ds(e){return QuoteUtils.quoteIdentifier(e)}function on(e){return Object.keys(e)[0]}function Tf(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 Dt=b(()=>{});function Af(e){let t=e.toLowerCase().trim();if(t.startsWith("_")||t.endsWith("[]"))return "TEXT";let n=pS[t];if(!n)throw new jt(`Unsupported PostgreSQL type: "${e}"`);return n}function js(e){let t=e.toLowerCase();return ["serial","serial4","bigserial","serial8","smallserial","serial2"].includes(t)}function Fs(e){let t=e.toLowerCase();return ["varchar","character varying","char","character","bpchar"].includes(t)}function Us(e){let t=e.toLowerCase();return ["numeric","decimal"].includes(t)}var jt,M,pS,Cf,fS,Ms,an=b(()=>{Dt();jt=class extends Error{},M=class extends jt{constructor(n,r){super(r??`Unsupported node type: ${on(n)}`);this.node=n;}},pS={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"},Cf=["<",">","<=",">=","=","<>","!=","+","-","*","/","%","&","|","<<",">>","||","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","->>"];fS={CreateEnumStmt:{react:"ignore"},CreateDomainStmt:{react:"warn"},CreateSeqStmt:{react:"ignore"},AlterSeqStmt:{react:"ignore"},CreateSchemaStmt:{react:"warn"},CreatePolicyStmt:{react:"ignore"},AlterPolicyStmt:{react:"ignore"},PartitionElem:{react:"error"},PartitionCmd:{react:"error"},VariableSetStmt:{react:"ignore"},CompositeTypeStmt:{react:"error"},AlterEnumStmt:{react:"error"},AlterObjectSchemaStmt:{react:"error"},AlterOwnerStmt:{react:"error"},AlterTypeStmt:{react:"error"},AlterFunctionStmt:{react:"error"},AlterDefaultPrivilegesStmt:{react:"error"},GrantStmt:{react:"error"},GrantRoleStmt:{react:"error"},CopyStmt:{react:"error"},CreateCastStmt:{react:"error"},AlterOpFamilyStmt:{react:"error"},AlterOperatorStmt:{react:"error"},TruncateStmt:{react:"error"},A_Indirection:{react:"error"},XmlExpr:{react:"error"},XmlSerialize:{react:"error"},RangeTableSample:{react:"error"},GroupingSet:{react:"error"}},Ms=new Map(Object.entries(fS));});var je,tr,$a=b(()=>{Dt();an();je=class extends M{constructor(t,n){super(t,`Unsupported expression: ${n}`);}},tr=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 n=Object.keys(t)[0],r=this[n];if(!r)throw new je({[n]:t},`Unsupported expression: ${n}`);return r.call(this,t[n])}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 r=this.isJwtAccessor(t.A_Expr);return r||this.A_Expr(t.A_Expr)}if("BoolExpr"in t)return this.BoolExpr(t.BoolExpr);let n=Object.keys(t)[0];throw new je({[n]:t},`deparseValue: ${n}`)}A_Expr(t){if(t.kind==="AEXPR_OP"){let n=t.name?.[0],r=n?er(n):void 0;if(!r)throw new je({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(r);if(!a)throw new je({A_Expr:t},`Unsupported operator: ${r}`);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 n=t.lexpr?this.deparseValue(t.lexpr):void 0,r=t.rexpr?this.deparseValue(t.rexpr):void 0,i=(t.name?.[0]?er(t.name[0]):"~~")==="!~~"?"$notLike":"$like";return {[n]:{[i]:r}}}if(t.kind==="AEXPR_IN"){let n=t.lexpr?this.deparseValue(t.lexpr):void 0,r=t.rexpr&&"List"in t.rexpr&&t.rexpr.List.items?t.rexpr.List.items.map(s=>this.deparseValue(s)):[];return {[n]:{$in:r}}}throw new je({A_Expr:t},`A_Expr kind: ${t.kind}`)}BoolExpr(t){let n=t.args??[];switch(t.boolop){case "AND_EXPR":return {$and:n.map(r=>this.deparse(r))};case "OR_EXPR":return {$or:n.map(r=>this.deparse(r))};case "NOT_EXPR":return {$not:this.deparse(n[0])};default:throw new je({BoolExpr:t},`BoolExpr op: ${t.boolop}`)}}NullTest(t){let n=t.arg?this.deparseValue(t.arg):void 0;return t.nulltesttype==="IS_NULL"?{[n]:{$is:null}}:{[n]:{$isNot:null}}}SubLink(t){if(t.subLinkType==="ANY_SUBLINK"){let n=t.testexpr?this.deparseValue(t.testexpr):void 0,r=t.subselect?this.SelectStmt(t.subselect.SelectStmt):void 0;return {[n]:{$in:r}}}if(t.subLinkType==="EXISTS_SUBLINK")return {$exists:t.subselect?this.SelectStmt(t.subselect.SelectStmt):void 0};if(t.subLinkType==="EXPR_SUBLINK"){let n=t.subselect?t.subselect.SelectStmt:void 0;if(n?.fromClause?.length)return this.SelectStmt(n);if(n?.targetList?.[0]){let r=n.targetList[0],s="ResTarget"in r?r.ResTarget:void 0;if(s?.val){let i=this.deparseValue(s.val);return i}}}throw new je({SubLink:t},`SubLink type: ${t.subLinkType}`)}SelectStmt(t){let{from:n,schema:r,join:s}=this.deparseFromClause(t.fromClause??[]),i=[];for(let f of t.targetList??[]){let h="ResTarget"in f?f.ResTarget:void 0;if(h?.val){let d=this.deparseValue(h.val);Array.isArray(d)?i.push(...d.map(String)):d!=null&&d!==""&&i.push(String(d));}}let o=t.whereClause?this.deparse(t.whereClause):void 0,a=this.deparseSortClause(t.sortClause),l=this.deparseLimit(t.limitCount),c=this.deparseLimit(t.limitOffset),p=this.deparseGroupClause(t.groupClause),u={type:"query",from:n,select:i};return r&&(u.schema=r),Object.keys(s).length>0&&(u.join=s),o&&(u.where=o),a.length>0&&(u.order=a),l!==void 0&&(u.limit=l),c!==void 0&&(u.offset=c),p.length>0&&(u.group=p),u}FuncCall(t){let n=this.isAuthFunc(t.funcname??[]);if(n)return n;throw new je({FuncCall:t},`FuncCall: ${nt(t.funcname??[]).join(".")}`)}ColumnRef(t){let n=nt(t.fields??[]);return n.length===1?n[0]:n.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 je({A_Const:t},"A_Const: unknown variant")}TypeCast(t){if(!t.arg)throw new je({TypeCast:t},"TypeCast: missing arg");return this.deparseValue(t.arg)}BooleanTest(t){let n=t.arg?this.deparseValue(t.arg):void 0;return t.booltesttype==="IS_TRUE"?{[n]:{$eq:true}}:{[n]:{$eq:false}}}deparseFromClause(t){let n={};if(t.length===0)return {from:"",join:n};let r=t[0];if("RangeVar"in r){let s=r.RangeVar;return {from:s.relname??"",schema:s.schemaname,join:n}}if("JoinExpr"in r){let{from:s,schema:i}=this.walkJoinExpr(r.JoinExpr,n);return {from:s,schema:i,join:n}}return {from:"",join:n}}walkJoinExpr(t,n){let r={from:""};if(t.larg)if("RangeVar"in t.larg){let s=t.larg.RangeVar;r={from:s.relname??"",schema:s.schemaname};}else "JoinExpr"in t.larg&&(r=this.walkJoinExpr(t.larg.JoinExpr,n));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 n){let p=2;for(;`${c}_${p}`in n;)p++;c=`${c}_${p}`;}n[c]=l;}return r}deparseSortClause(t){if(!t)return [];let n=[];for(let r of t){if(!("SortBy"in r))continue;let s=r.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),n.push(a);}return n}deparseLimit(t){if(!t)return;let n=this.deparseValue(t);return typeof n=="number"?n:Number(n)}deparseGroupClause(t){return t?t.map(n=>String(this.deparseValue(n))):[]}isAuthFunc(t){let n=nt(t);if(n.length===2&&n[0]==="auth"){if(n[1]==="uid")return "{{auth.uid}}";if(n[1]==="jwt")return "{{auth.jwt}}";if(n[1]==="role")return "{{auth.role}}";throw new Error(`Unsupported auth function: "${n.slice(1).join(".")}"`)}return null}isJwtAccessor(t){if(t.kind!=="AEXPR_OP")return null;let n=t.name?.[0]?er(t.name[0]):void 0;if(n!=="->"&&n!=="->>")return null;let r=t.rexpr&&"A_Const"in t.rexpr?t.rexpr.A_Const.sval?.sval:void 0;if(r===void 0)return null;if(t.lexpr&&"FuncCall"in t.lexpr)return this.isAuthFunc(t.lexpr.FuncCall.funcname??[])==="{{auth.jwt}}"?`{{auth.jwt.${r}}}`:null;if(t.lexpr&&"A_Expr"in t.lexpr){let s=this.isJwtAccessor(t.lexpr.A_Expr);if(s)return `${s.slice(0,-2)}.${r}}}`}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 gt,va=b(()=>{gt=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 nr,Ra=b(()=>{nr=class extends Error{constructor(n,r,s,i){super(`check constraint "${s}" violated for ${n}.${r}`);this.table=n;this.column=r;this.constraint=s;this.value=i;this.name="CheckConstraintError";}};});var ge,rt=b(()=>{Ra();ge=class{context;factoryExtra;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,n){return {status:"fail",message:t,action:n}}validationPass(){return {status:"pass",message:null}}isNullish(t){return t==null}toColumnDDL(t){let{includeNullable:n=true}=t??{},r=[],s=this.context.column;r.push(this.quoteIfNeeded(s)),r.push(this.sqliteType),this.context.isPrimaryKey&&r.push("PRIMARY KEY"),this.context.isSerial&&this.context.isPrimaryKey&&r.push("AUTOINCREMENT"),n&&!this.context.nullable&&!this.context.isPrimaryKey&&r.push("NOT NULL"),this.context.isUnique&&!this.context.isPrimaryKey&&r.push("UNIQUE"),this.context.defaultValue!==null&&r.push(`DEFAULT ${this.context.defaultValue}`);let i=this.checkConstraint();return i&&r.push(`CHECK (${i})`),r.join(" ")}checkError(t,n){return new nr(this.context.table,this.context.column,t,n)}quoteIfNeeded(t){return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)?t:`"${t}"`}};});var Ft,Bs=b(()=>{rt();Ft=class extends ge{get sqliteType(){return "INTEGER"}};});var rr,ka=b(()=>{Bs();rr=class extends Ft{constructor(t){super({...t,isSerial:true});}};});function mS(e,t){let{precision:n,scale:r}=t,s=10**r,i=10**(n-r);return Math.abs(Math.round(e*s)-e*s)<1e-4&&Math.abs(e)<i}var Ut,qs=b(()=>{rt();Ut=class extends ge{numericPrecision;constructor(t,n){super(t),this.numericPrecision=n;}get isShimBacked(){return this.numericPrecision!==void 0}get sqliteType(){return "REAL"}checkConstraint(){if(this.numericPrecision){let{precision:t,scale:n}=this.numericPrecision,r=this.context.column,s=10**n,i=10**(t-n);return `ABS(ROUND(${r} * ${s}) - ${r} * ${s}) < 0.0001 AND ABS(${r}) < ${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:n,scale:r}=this.numericPrecision;if(!mS(t,this.numericPrecision))return this.validationFail(`Does not fit numeric(${n}, ${r}).`,"Patch rows within numeric precision.")}return this.validationPass()}};});var le,Fe=b(()=>{rt();le=class extends ge{lengthConstraint;constructor(t,n){super(t),this.lengthConstraint=n;}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 sr,Na=b(()=>{rt();sr=class extends ge{get sqliteType(){return "BLOB"}};});var ir,Pa=b(()=>{rt();ir=class extends ge{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}checkConstraint(){return `${this.context.column} IN (0, 1)`}serialize(t){if(this.isNullish(t))return t;if(t===true||t===1)return 1;if(t===false||t===0)return 0;throw this.checkError("boolean_range",t)}deserialize(t){if(this.isNullish(t)||t===true||t===false)return t;if(typeof t=="number"&&Number.isFinite(t)){if(t===1)return true;if(t===0)return false}return t===1n?true:t===0n?false:t==="1"||t==="true"?true:t==="0"||t==="false"?false:t}validateStorage(t){return this.isNullish(t)?this.validationPass():t===1||t===0?this.validationPass():this.validationFail("Expected 0 or 1.","Patch rows with boolean values.")}};});function $f(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var or,La=b(()=>{rt();or=class extends ge{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 n=$f(t);return n.ok?n.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."):$f(t).ok?this.validationPass():this.validationFail("Invalid JSON text.","Patch rows with valid JSON.")}};});function dS(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 ar,Oa=b(()=>{Fe();ar=class extends le{get isShimBacked(){return true}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR date(${t}) IS NOT NULL`}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!dS(t)?this.validationFail("Invalid date.","Patch rows with YYYY-MM-DD dates."):this.validationPass()}};});function hS(e){let t=e.match(/^(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?([+-](\d{2}):?(\d{2}))?$/);if(!t)return false;let n=Number(t[1]),r=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 n<=24&&r<=59&&s<=59&&(n!==24||r===0&&s===0)&&a}var lr,Ia=b(()=>{Fe();lr=class extends le{get isShimBacked(){return true}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR time(${t}) IS NOT NULL`}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!hS(t)?this.validationFail("Invalid time.","Patch rows with HH:MM[:SS] times."):this.validationPass()}};});function gS(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 n=Number(t[1]),r=Number(t[2]),s=Number(t[3]),i=Number(t[4]),o=Number(t[5]),a=t[6]===void 0?0:Number(t[6]),l=t[8]===void 0?null:Number(t[8]),c=t[9]===void 0?null:Number(t[9]),p=new Date(Date.UTC(n,r-1,s)),u=p.getUTCFullYear()===n&&p.getUTCMonth()===r-1&&p.getUTCDate()===s,f=i<=24&&o<=59&&a<=59&&(i!==24||o===0&&a===0),h=l===null||c!==null&&l<=15&&c<=59;return u&&f&&h}var cr,Da=b(()=>{Fe();cr=class extends le{get isShimBacked(){return true}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR datetime(${t}) IS NOT NULL`}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!gS(t)?this.validationFail("Invalid timestamp.","Patch rows with ISO timestamps."):this.validationPass()}};});var ur,ja=b(()=>{Fe();ur=class extends le{get isShimBacked(){return true}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||t.trim().length===0?this.validationFail("Expected interval text.","Patch rows with interval strings."):/^-?\d+(?:\.\d+)?$/.test(t.trim())?this.validationFail("Ambiguous numeric interval.","Patch rows with explicit interval strings."):this.validationPass()}};});var pr,Fa=b(()=>{Fe();pr=class extends le{enumValues;constructor(t,n){super(t),this.enumValues=n;}get isShimBacked(){return true}checkConstraint(){let t=this.context.column,n=this.enumValues.map(r=>`'${r.replace(/'/g,"''")}'`).join(", ");return `${t} IN (${n})`}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 vf(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var yt,Hs=b(()=>{rt();yt=class extends ge{elementField;constructor(t,n){super(t),this.elementField=n;}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(n=>this.elementField.serialize(n))):JSON.stringify(t)}deserialize(t){if(this.isNullish(t))return t;if(typeof t=="string"){let n=vf(t);if(n.ok&&Array.isArray(n.value))return this.elementField?n.value.map(r=>this.elementField.deserialize(r)):n.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 n=vf(t);if(!n.ok)return this.validationFail("Invalid JSON array text.","Patch rows with array values.");if(!Array.isArray(n.value))return this.validationFail("Expected JSON array.","Patch rows with array values.");if(this.elementField)for(let r of n.value){let s=this.elementField.validateStorage(r);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 Rf(e){return bS.test(e.toLowerCase())}var yS,bS,fr,Ua=b(()=>{Fe();yS="????????-????-????-????-????????????",bS=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;fr=class extends le{get isShimBacked(){return true}checkConstraint(){let t=this.quoteIfNeeded(this.context.column);return `${t} IS NULL OR ${t} GLOB '${yS}'`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string")throw this.checkError("uuid_format",t);let n=t.toLowerCase();if(!Rf(n))throw this.checkError("uuid_format",t);return n}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!Rf(t)?this.validationFail("Invalid UUID.","Patch rows with valid UUIDs."):this.validationPass()}};});function wS(e){let t=e.split("/");if(t.length>2)return null;let n=t[0];if(!n)return null;if(t.length===1)return {address:n,prefix:null};let r=t[1];return !r||!/^\d+$/.test(r)?null:{address:n,prefix:Number(r)}}function SS(e){let t=e.split(".");return t.length!==4?false:t.every(n=>{if(!/^\d+$/.test(n))return false;let r=Number(n);return r>=0&&r<=255})}function ES(e){if(!e.includes(":"))return false;try{return new URL(`http://[${e}]/`),!0}catch{return false}}function kf(e){let t=wS(e);return t?SS(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=32:ES(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=128:false:false}var mr,Ma=b(()=>{Fe();mr=class extends le{get isShimBacked(){return true}checkConstraint(){let t=this.quoteIfNeeded(this.context.column);return `${t} IS NULL OR (length(${t}) BETWEEN 3 AND 49 AND (instr(${t}, '.') > 0 OR instr(${t}, ':') > 0))`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string")throw this.checkError("inet_format",t);let n=t.trim();if(!kf(n))throw this.checkError("inet_format",t);return n}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!kf(t.trim())?this.validationFail("Invalid inet address.","Patch rows with valid inet strings."):this.validationPass()}};});var dr,Ba=b(()=>{Fe();dr=class extends le{serialize(t){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}deserialize(t){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}toColumnDDL(){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}};});function Mt(e,t){let n=DS(e,t);if(t){let{enumValues:r,...s}=t;n.factoryExtra=s;}return n}function DS(e,t){if(t?.isArray){let r=Mt(e,{...t,isArray:false});return new yt(e,r)}if(t?.enumValues)return new pr(e,t.enumValues);let n=e.pgTypeName.toLowerCase().trim();if(n.startsWith("_")||n.endsWith("[]")){let r=n.startsWith("_")?n.slice(1):n.slice(0,-2),s={...e,pgTypeName:r},i=Mt(s);return new yt(e,i)}return xS.has(n)?new rr(e):_S.has(n)?new Ft(e):$S.has(n)?new ir(e):vS.has(n)?new or(e):PS.has(n)?new ar(e):LS.has(n)?new lr(e):OS.has(n)?new cr(e):IS.has(n)?new ur(e):AS.has(n)?new sr(e):TS.has(n)?new Ut(e,t?.numericPrecision):RS.has(n)?new fr(e):kS.has(n)?new le(e,63):NS.has(n)?new mr(e):CS.has(n)?new le(e,t?.lengthConstraint):new dr(e)}var _S,xS,TS,CS,AS,$S,vS,RS,kS,NS,PS,LS,OS,IS,qa=b(()=>{Bs();ka();qs();Fe();Na();Pa();La();Oa();Ia();Da();ja();Fa();Hs();Ua();Ma();Ba();_S=new Set(["int2","smallint","int4","integer","int","int8","bigint"]),xS=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]),TS=new Set(["float4","real","float8","double precision","numeric","decimal"]),CS=new Set(["text","varchar","character varying","char","character","bpchar"]),AS=new Set(["bytea"]),$S=new Set(["bool","boolean"]),vS=new Set(["json","jsonb"]),RS=new Set(["uuid"]),kS=new Set(["name"]),NS=new Set(["inet"]),PS=new Set(["date"]),LS=new Set(["time","timetz","time without time zone","time with time zone"]),OS=new Set(["timestamp","timestamptz","timestamp without time zone","timestamp with time zone"]),IS=new Set(["interval"]);});function Ha(e,t="auto"){let n=e.toLowerCase(),r=Gs[n];if(!r)return null;switch(t){case "translate":{if(!r.sqlite)throw new Error(`No SQLite translation for function "${e}"`);return {sqliteExpr:r.sqlite(),jsFn:null}}case "synthetic":{if(!r.js)throw new Error(`No JS implementation for function "${e}"`);return {sqliteExpr:null,jsFn:r.js}}case "auto":return r.js?{sqliteExpr:null,jsFn:r.js}:r.sqlite?{sqliteExpr:r.sqlite(),jsFn:null}:null}}var Nf,Gs,Ga=b(()=>{Nf="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)))",Gs={gen_random_uuid:{sqlite:()=>Nf,js:()=>crypto.randomUUID()},uuid_generate_v4:{sqlite:()=>Nf,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 hr,Pf=b(()=>{hr=class{table;schema;fields;constructor(t,n="public",r=new Map){this.table=t,this.schema=n,this.fields=r;}get(t){return this.fields.get(t)}has(t){return this.fields.has(t)}set(t,n){this.fields.set(t,n);}columns(){return Array.from(this.fields.keys())}all(){return Array.from(this.fields.values())}serializeRow(t){let n={};for(let[r,s]of Object.entries(t)){let i=this.fields.get(r);n[r]=i?i.serialize(s):s;}return n}deserializeRow(t){let n={};for(let[r,s]of Object.entries(t)){let i=this.fields.get(r);n[r]=i?i.deserialize(s):s;}return n}applyDefaults(t){let n={...t};for(let[r,s]of this.fields)!(r in n)&&s.context.defaultFn&&(n[r]=s.context.defaultFn());return n}};});var Lf=b(()=>{rt();Ra();Bs();ka();qs();Fe();Na();Pa();La();Oa();Ia();Da();ja();Fa();Hs();Ua();Ma();Ba();qa();Ga();Pf();});var el={};fe(el,{_resetWarnedMissingToClauseForTests:()=>jS,collectComments:()=>Za,collectEnums:()=>za,collectPolicies:()=>Ya,collectSchema:()=>Ja,collectTableConstraints:()=>Qa,collectVariables:()=>Xa,lookupEnumValue:()=>ln});function jS(){Ka.clear();}function za(e){let t=new Map;for(let n of e.stmts??[]){if(!n.stmt||!("CreateEnumStmt"in n.stmt))continue;let r=n.stmt.CreateEnumStmt,s=nt(r.typeName??[]).join(".");if(!s||!r.vals)continue;let i=nt(r.vals),o=s.toLowerCase();t.set(o,i),o.startsWith("public.")&&t.set(o.slice(7),i);}return t}function ln(e,t){let n=t.toLowerCase(),r=e.get(n);return r||(n.startsWith("public.")?e.get(n.slice(7)):e.get(`public.${n}`))}function Xa(e){let t=new Map;for(let n of e.stmts??[]){if(!n.stmt||!("VariableSetStmt"in n.stmt))continue;let r=n.stmt.VariableSetStmt,s=r.name,i=Tf(r.args?.[0]??{});t.set(s,{value:i,local:r.is_local});}return t}function Of(e){let t=[],n=false;for(let r of e??[])if("RoleSpec"in r){let s=r.RoleSpec;s.roletype==="ROLESPEC_PUBLIC"?s.location===-1&&(n=true):s.roletype==="ROLESPEC_CSTRING"&&s.rolename&&t.push(s.rolename);}return {roles:t,implicitPublic:n}}function Ws(e,t){return e&&e.length>0?e:t}function Wa(e,t,n){return e.findIndex(r=>r.data.name===t.name&&r.data.table===t.table&&Ws(r.data.schema,n)===Ws(t.schema,n))}function Va(e,t){return new Error(`policy "${e}" for table "${t}" does not exist`)}function If(e,t,n,r){return e.data.table===t&&Ws(e.data.schema,r)===Ws(n,r)}function Ya(e,t={}){let n=t.defaultSchema||"public",r=t.validateMutations===true,s=new tr,i=new Set,o=[];for(let a of e.stmts??[])if(a.stmt){if("CreatePolicyStmt"in a.stmt){let l=a.stmt.CreatePolicyStmt,c=l.table?.relname??"",p=l.table?.schemaname,u={select:"SELECT",insert:"INSERT",update:"UPDATE",delete:"DELETE"},f=l.cmd_name?u[l.cmd_name]??"ALL":"ALL",h=l.permissive===true,{roles:d,implicitPublic:m}=Of(l.roles),g=l.qual?s.deparse(l.qual):void 0,y=l.with_check?s.deparse(l.with_check):void 0;if(m){let A=p?`${p}.${c}`:c,C=l.policy_name??"",v=`${A}::${C}`;if(!Ka.has(v)){Ka.add(v);let $=JSON.stringify(g)+JSON.stringify(y);/\{\{auth\.(uid|jwt|role)/i.test($)||console.warn(`[supalite] policy "${C}" on "${A}" has no TO clause \u2014 applies to all roles (PUBLIC). For clarity, prefer an explicit \`TO <role>\` clause (e.g. \`TO authenticated\`).`);}}let E=new gt({name:l.policy_name??"",table:c,schema:p,command:f,permissive:h,roles:d,using:g,withCheck:y});o.push(E);}if("DropStmt"in a.stmt&&a.stmt.DropStmt.removeType==="OBJECT_POLICY"){let l=a.stmt.DropStmt,c=l.objects?.[0];if(c&&"List"in c){let p=nt(c.List.items??[]),u=p[p.length-1],f=p[p.length-2],h=p.length>=3?p[p.length-3]:void 0;if(u&&f){let d=Wa(o,{name:u,table:f,schema:h},n);if(d!==-1)o.splice(d,1);else if(r&&!l.missing_ok)throw Va(u,f)}}}if("AlterPolicyStmt"in a.stmt){let l=a.stmt.AlterPolicyStmt,c=l.policy_name??"",p=l.table?.relname??"",u=l.table?.schemaname,f=Wa(o,{name:c,table:p,schema:u},n);if(f===-1){if(r)throw Va(c,p);continue}let h=o[f].data,d=l.roles?Of(l.roles).roles:h.roles,m=l.qual?s.deparse(l.qual):h.using,g=l.with_check?s.deparse(l.with_check):h.withCheck;o[f]=new gt({...h,roles:d,using:m,withCheck:g});}if("RenameStmt"in a.stmt&&a.stmt.RenameStmt.renameType==="OBJECT_POLICY"){let l=a.stmt.RenameStmt,c=l.subname??"",p=l.relation?.relname??"",u=l.relation?.schemaname,f=Wa(o,{name:c,table:p,schema:u},n);if(f===-1){if(r)throw Va(c,p);continue}l.newname&&(o[f]=new gt({...o[f].data,name:l.newname}));}if("RenameStmt"in a.stmt&&a.stmt.RenameStmt.renameType==="OBJECT_TABLE"){let l=a.stmt.RenameStmt,c=l.relation?.relname??"",p=l.newname??"",u=l.relation?.schemaname;if(c&&p&&c!==p){i.delete(c)&&i.add(p);for(let f=0;f<o.length;f++)If(o[f],c,u,n)&&(o[f]=new gt({...o[f].data,table:p}));}}if("DropStmt"in a.stmt&&a.stmt.DropStmt.removeType==="OBJECT_TABLE")for(let l of a.stmt.DropStmt.objects??[]){if(!("List"in l))continue;let c=nt(l.List.items??[]),p=c[c.length-1],u=c.length>=2?c[c.length-2]:void 0;if(p){i.delete(p);for(let f=o.length-1;f>=0;f--)If(o[f],p,u,n)&&o.splice(f,1);}}if("AlterTableStmt"in a.stmt){let l=a.stmt.AlterTableStmt,c=l.relation?.relname??"";for(let p of l.cmds??[]){if(!("AlterTableCmd"in p))continue;let u=p.AlterTableCmd.subtype;u==="AT_EnableRowSecurity"?i.add(c):u==="AT_DisableRowSecurity"&&i.delete(c);}}}return {policies:o,tables:i}}function Ja(e,t){let n=new Map;for(let r of e.stmts??[]){if(!r.stmt||!("CreateStmt"in r.stmt))continue;let s=r.stmt.CreateStmt,i=s.relation?.relname??"",o=s.relation?.schemaname??"public";if(!i)continue;let a=new hr(i,o);for(let l of s.tableElts??[]){if(!("ColumnDef"in l))continue;let c=l.ColumnDef,p=c.colname;if(!p)continue;let u=c.typeName?.names?.map(P=>P.String?.sval||P.String?.str).filter(Boolean),f=u&&u.length>0?u.length===2&&u[0]==="pg_catalog"?u[1]:u.join("."):void 0;if(!f)continue;let h=!!c.typeName?.arrayBounds?.length,d=Array.isArray(c.typeName?.typmods)?c.typeName.typmods:[],m=P=>d[P]?.A_Const?.ival?.ival??d[P]?.A_Const?.val?.ival?.ival,g={isArray:h};if(Fs(f)&&d.length>0){let P=m(0);typeof P=="number"&&P>0&&(g.lengthConstraint=P);}if(Us(f)&&d.length>=2){let P=m(0),j=m(1);typeof P=="number"&&typeof j=="number"&&P>0&&j>=0&&(g.numericPrecision={precision:P,scale:j});}let y=ln(t,f);y&&(g.enumValues=y);let E=Array.isArray(c.constraints)?c.constraints:[],A=E.some(P=>P.Constraint?.contype==="CONSTR_PRIMARY"),C=js(f)||E.some(P=>P.Constraint?.contype==="CONSTR_IDENTITY"),v=E.some(P=>P.Constraint?.contype==="CONSTR_NOTNULL"),$=E.find(P=>P.Constraint?.contype==="CONSTR_UNIQUE"),T=E.find(P=>P.Constraint?.contype==="CONSTR_GENERATED"),x=E.find(P=>P.Constraint?.contype==="CONSTR_FOREIGN"),O=E.find(P=>P.Constraint?.contype==="CONSTR_CHECK"),w;if(x){let P=x.Constraint,j=P.pktable?.relname,S=P.pktable?.schemaname,_=P.pk_attrs?.[0]?.String?.sval;j&&_&&(w={refSchema:S,refTable:j,refColumn:_,constraintName:P.conname||void 0});}let I={schema:o,table:i,column:p,pgTypeName:f,nullable:!v&&!A,defaultValue:null,defaultFn:null,isPrimaryKey:A,isUnique:!!$,isSerial:C,isGenerated:!!T,fkRef:w,hasCheck:!!O,checkConstraintName:O?.Constraint?.conname||void 0,uniqueConstraintName:$?.Constraint?.conname||void 0};a.set(p,Mt(I,g));}n.set(`${o}.${i}`,a);}return n}function Qa(e){let t=[];for(let n of e.stmts??[]){if(!n.stmt||!("CreateStmt"in n.stmt))continue;let r=n.stmt.CreateStmt,s=r.relation?.relname??"",i=r.relation?.schemaname??"public";if(s)for(let o of r.tableElts??[]){if("ColumnDef"in o){let p=o.ColumnDef,u=p?.colname;if(!u)continue;for(let f of p.constraints??[]){let h=f?.Constraint;if(!h||h.contype!=="CONSTR_FOREIGN")continue;let d=h.pktable?.relname;if(!d)continue;let m=(h.pk_attrs??[]).map(g=>g.String?.sval??g.String?.str).filter(Boolean);t.push({schema:i,table:s,kind:"foreign_key",name:h.conname||void 0,columns:[u],refSchema:h.pktable?.schemaname,refTable:d,refColumns:m});}continue}let a=o;if(!a.Constraint)continue;let l=a.Constraint,c=l.contype;if(c==="CONSTR_UNIQUE"){let p=(l.keys??[]).map(u=>u.String?.sval??u.String?.str).filter(Boolean);if(p.length===0)continue;t.push({schema:i,table:s,kind:"unique",name:l.conname||void 0,columns:p});}else if(c==="CONSTR_CHECK")t.push({schema:i,table:s,kind:"check",name:l.conname||void 0,columns:[]});else if(c==="CONSTR_FOREIGN"){let p=(l.fk_attrs??[]).map(h=>h.String?.sval??h.String?.str).filter(Boolean),u=(l.pk_attrs??[]).map(h=>h.String?.sval??h.String?.str).filter(Boolean),f=l.pktable?.relname;if(!f)continue;t.push({schema:i,table:s,kind:"foreign_key",name:l.conname||void 0,columns:p,refSchema:l.pktable?.schemaname,refTable:f,refColumns:u});}}}return t}function Za(e){let t=[];for(let n of e.stmts??[]){if(!n.stmt||!("CommentStmt"in n.stmt))continue;let r=n.stmt.CommentStmt,s=r.comment??"";if(!s)continue;let i=r.objtype,o=(r.object?.List?.items??r.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 Ka,Vs=b(()=>{$a();Dt();va();Lf();an();Ka=new Set;});async function gr(e,t){let n=await e.connection.introspect(),r=tl(n);await Mf(e,{...t,dbHasTables:n.tables.length>0,dbFingerprint:r}),await qS(e);let s=await e.connection.introspect();qf(s,e);}async function MS(e){return Jn(e.config.db?.seed?.sql_paths??["./seed.sql"],{cwd:Ie__default.join(process.cwd(),"supabase"),absolute:true})}async function BS(e){let t=await MS(e);return Promise.all(t.map(async n=>{let r=await de__default.readFile(n,"utf-8"),s=createHash("sha256").update(r).digest("hex");return {path:Ie__default.relative(process.cwd(),n),hash:s,statements:splitSqlStatements(r)}}))}async function yr(e,t){if(e.config.db?.seed?.enabled===false)return 0;let r=(await BS(e)).filter(l=>l.statements.length>0);if(r.length===0)return 0;await nn(e.connection);let s=_e(e.connection),i=new Map((await Ap(e.connection)).map(l=>[l.path,l.hash])),o=r.filter(l=>i.get(l.path)!==l.hash);if(o.length===0)return 0;console.log(F.default.dim("Seeding database..."));let a=[];for(let l of o){a.push(...l.statements);let c=Cp(s,{path:l.path,hash:l.hash});c&&a.push(c);}try{await e.connection.transaction(a);}catch(l){let c=t?.recoveryHint??"Fix `supabase/seed.sql`, then re-run `lite dev` to reapply the schema and reseed.";throw new Error(`Seed failed and was rolled back: ${String(l.message??l)}
91
- ${c}`)}return o.reduce((l,c)=>l+c.statements.length,0)}async function qS(e){await yr(e);}async function re(e){let t=await Jn(e.config?.db?.migrations?.schema_paths??Ff,{cwd:Ie__default.join(process.cwd(),ue.config_dir),absolute:true}),n=await Promise.all(t.map(async r=>await de__default.readFile(r,"utf-8"))).then(r=>r.map(s=>s.split(`
92
+ )`]}function Sb(e){let{schema_migrations:t}=wt(e);return [`CREATE UNIQUE INDEX IF NOT EXISTS ${e==="sqlite"?"migrations_idempotency_key_idx":"schema_migrations_idempotency_key_idx"} ON ${t} (idempotency_key)`]}function Bp(e,t){let{schema_migrations:n}=wt(e);return `INSERT INTO ${n} (version, name, statements, rollback, created_by, idempotency_key) VALUES (${er(t.version)}, ${Aa(t.name)}, ${Mp(e,t.statements)}, ${Mp(e,t.rollback??null)}, ${Aa(t.created_by??null)}, ${Aa(t.idempotency_key??null)}) ON CONFLICT (idempotency_key) DO UPDATE SET version = EXCLUDED.version, name = EXCLUDED.name, statements = EXCLUDED.statements, rollback = EXCLUDED.rollback, created_by = EXCLUDED.created_by`}function Eb(e){let{schema_migrations:t}=wt(e);return `SELECT version FROM ${t} ORDER BY version ASC`}function xb(e){let{schema_migrations:t}=wt(e);return `SELECT ${_b} FROM ${t} ORDER BY version ASC`}function Tb(e){let{seed_files:t}=wt(e);return t?`SELECT path, hash FROM ${t}`:null}function qp(e,t){let{seed_files:n}=wt(e);return n?`INSERT INTO ${n} (path, hash) VALUES (${er(t.path)}, ${er(t.hash)}) ON CONFLICT (path) DO UPDATE SET hash = EXCLUDED.hash`:null}async function Cb(e,t){let{schema_migrations:n}=wt(t);for(let r of bb){let s=t==="pg"?r.pgType:r.sqliteType;if(t==="pg")await e.exec(`ALTER TABLE ${n} ADD COLUMN IF NOT EXISTS ${r.name} ${s}`);else try{await e.exec(`ALTER TABLE ${n} ADD COLUMN ${r.name} ${s}`);}catch{}}}async function ln(e){let t=Ce(e);for(let n of wb(t))await e.exec(n);await Cb(e,t);for(let n of Sb(t))await e.exec(n);}async function tr(e){let t=Ce(e);return ((await e.exec(Eb(t)))?.rows??[]).map(r=>r.version)}async function Hp(e){let t=Ce(e);return ((await e.exec(xb(t)))?.rows??[]).map(yb)}async function Gp(e){let t=Ce(e),n=Tb(t);return n?((await e.exec(n))?.rows??[]).map(s=>({path:s.path,hash:s.hash})):[]}var bb,_b,St=b(()=>{bb=[{name:"created_by",pgType:"text",sqliteType:"TEXT"},{name:"idempotency_key",pgType:"text",sqliteType:"TEXT"},{name:"rollback",pgType:"text[]",sqliteType:"TEXT"}];_b="version, name, statements, rollback, created_by, idempotency_key";});function at(e){let t=(r,s)=>[...r].sort((i,o)=>s(i).localeCompare(s(o))),n={tables:t(e.tables??[],r=>`${r.schema??""}.${r.name}`).map(r=>({schema:r.schema,name:r.name,type:r.type,sql:r.sql})),columns:t(e.columns??[],r=>`${r.schema??""}.${r.table}.${r.name}`).map(r=>({schema:r.schema,table:r.table,name:r.name,type:r.type,nullable:r.nullable,default_value:r.default_value,is_primary_key:r.is_primary_key})),indexes:t(e.indexes??[],r=>`${r.schema??""}.${r.table}.${r.name}`).map(r=>({schema:r.schema,table:r.table,name:r.name,unique:r.unique,columns:r.columns,sql:r.sql})),foreign_keys:t(e.foreign_keys??[],r=>`${r.schema??""}.${r.table}.${r.column}->${r.ref_table}.${r.ref_column}`).map(r=>({schema:r.schema,table:r.table,column:r.column,ref_schema:r.ref_schema,ref_table:r.ref_table,ref_column:r.ref_column})),primary_keys:t(e.primary_keys??[],r=>`${r.schema??""}.${r.table}`).map(r=>({schema:r.schema,table:r.table,columns:r.columns})),check_constraints:t(e.check_constraints??[],r=>`${r.schema??""}.${r.table}.${r.name??""}.${r.column??""}`).map(r=>({schema:r.schema,table:r.table,name:r.name,column:r.column,expression:r.expression})),unique_constraints:t(e.unique_constraints??[],r=>`${r.schema??""}.${r.table}.${r.name}`).map(r=>({schema:r.schema,table:r.table,name:r.name,columns:r.columns})),views:t(e.views??[],r=>`${r.schema??""}.${r.name}`).map(r=>({schema:r.schema,name:r.name,sql:r.sql})),triggers:t(e.triggers??[],r=>`${r.schema??""}.${r.table}.${r.name}`).map(r=>({schema:r.schema,table:r.table,name:r.name,sql:r.sql})),custom_types:t(e.custom_types??[],r=>`${r.schema??""}.${r.type}`).map(r=>({schema:r.schema,type:r.type,kind:r.kind,values:r.values,fields:r.fields}))};return createHash("sha256").update(JSON.stringify(n)).digest("hex")}var nr=b(()=>{});function Vp(e){return createHash("sha256").update(JSON.stringify(e)).digest("hex")}function $a(e){return e.connection.config.baseSchema??""}function Kp(e){return {...e.connection.config.translation?.schemas??{}}}function Rb(e){return Vp(e.map(({version:t,statements:n})=>({version:t,statements:n})))}function Ra(e){return Vp({baseSchema:$a(e),translationSchemas:Kp(e)})}function vb(e){return String(e).toLowerCase().includes("no such table")}async function kb(e){try{return await Hp(e.connection)}catch(t){if(vb(t))return [];throw new Me("invalid-history",`Applied migration history is invalid: ${String(t)}`,{cause:t})}}async function zp(e){let t=await e.introspect({postprocess:false}),n=e.config.ddlDialect;return at(Qs(t,n))}async function rr(e){let t=await kb(e);return {rows:t,sourceHash:Rb(t),runtimeHash:Ra(e),dbFingerprint:await zp(e.connection)}}function Nb(e){return e.map(t=>t.statements.join(`;
93
+ `)).filter(t=>t.trim().length>0).join(`;
94
+
95
+ `)}async function Xp(e){let{createConnection:t}=await import('@supabase/lite/sqlite');return await t({url:":memory:",ddlDialect:"postgres",translation:{schemas:Kp(e)}})}async function Pb(e,t){if(!t.trim())return;let n=await e.translateDdl(t,{strict:true}),r=typeof n=="string"?n:n.ddl??"";for(let s of et(r))try{await e.exec(s);}catch{}}async function Ob(e,t){let n=await Xp(e);try{await Pb(n,$a(e));for(let r of t){let s=r.statements.join(`;
96
+ `);if(!s.trim())continue;let i=await n.translateDdl(s),o=typeof i=="string"?i:i.ddl??"";await n.transaction(et(o),{intent:"migration"});}return await zp(n)}finally{await n.close();}}async function Lb(e,t){let n=await Xp(e);try{let r=[$a(e),Nb(t)].filter(i=>i.trim()).join(`
97
+
98
+ `),s=await n.translateDdl(r,{strict:!0});return SqliteConnection.serializeDeparseInfo(typeof s=="string"?void 0:s)}finally{await n.close();}}async function Jp(e,t){let n=t??await rr(e);try{let[r,s]=await Promise.all([Lb(e,n.rows),Ob(e,n.rows)]);if(s!==n.dbFingerprint)throw new Me("drift","The live database structure differs from the applied migration history.");return {...n,deparse:r}}catch(r){throw r instanceof Me?r:new Me("translation",`Applied migration history could not be replayed: ${String(r)}`,{cause:r})}}function va(e,t){let n=e.connection;typeof n.updateDeparseInfo=="function"&&n.updateDeparseInfo(SqliteConnection.parseDeparseInfo(t,{strict:true}));}function Zs(e){return Ce(e.connection)==="pg-flat"}var Me,Yp=b(()=>{ht();Ca();St();nr();Me=class extends Error{constructor(n,r,s){super(r,s);this.failure=n;this.name="AppliedMetadataError";}};});function Pa(){return Fe__default.join(process.cwd(),Qp)}function ef(e){return createHash("sha256").update(JSON.stringify(e)).digest("hex")}async function Fb(e){let t=e.connection,n=await t.introspect({postprocess:false});return at(Qs(n,t.config.ddlDialect))}async function Mb(e,t,n=he__default){let r=Fe__default.join(Fe__default.dirname(e),`.${Fe__default.basename(e)}.${process.pid}.${randomUUID()}.tmp`);await n.mkdir(Fe__default.dirname(e),{recursive:true});try{await n.writeFile(r,t,"utf-8"),await n.rename(r,e);}catch(s){throw await n.unlink(r).catch(()=>{}),s}}async function ir(e,t){if(!Zs(e))return false;try{let n=e.connection,r=t.metadata??SqliteConnection.serializeDeparseInfo(n.config?.translation?.deparse),s={v:Zp,workflow:t.workflow,sourceHash:t.sourceHash,runtimeHash:t.runtimeHash??Ra(e),dbFingerprint:t.dbFingerprint??await Fb(e),payloadChecksum:ef(r),metadata:r};return await Mb(Pa(),JSON.stringify(s)),!0}catch(n){return console.warn(ti.default.yellow(`Could not write ${Qp}: ${String(n)}`)),false}}function Ub(e){return !Ve(e)||e.v!==Zp||e.workflow!=="migrations"&&e.workflow!=="declarative"||!ei(e.sourceHash)||!ei(e.runtimeHash)||!ei(e.dbFingerprint)||!ei(e.payloadChecksum)||!tf(e.metadata)?false:ef(e.metadata)===e.payloadChecksum}async function Bb(e,t){if(typeof e.connection.updateDeparseInfo!="function")return false;let r;try{r=JSON.parse(await he__default.readFile(Pa(),"utf-8"));}catch{return false}if(!Ub(r)||r.workflow!=="migrations")return false;let s=t??await rr(e);if(r.sourceHash!==s.sourceHash||r.runtimeHash!==s.runtimeHash||r.dbFingerprint!==s.dbFingerprint)return false;try{return va(e,r.metadata),!0}catch{return false}}function Gb(e){return !Ve(e)||!Ne(e.name)||!Mt(e.table)||!lt(e.schema,Ne)||!Ne(e.command)||!qb.has(e.command)||typeof e.permissive!="boolean"||!ni(e.roles)||!lt(e.using,t=>typeof t=="object")?false:lt(e.withCheck,t=>typeof t=="object")}function Wb(e){if(!Ve(e)||!Ve(e.context))return false;let t=e.context;return !Ne(t.schema)||!Mt(t.table)||!Mt(t.column)||!Mt(t.pgTypeName)||typeof t.nullable!="boolean"||typeof t.isPrimaryKey!="boolean"||typeof t.isUnique!="boolean"||typeof t.isSerial!="boolean"||!(t.defaultValue===null||Ne(t.defaultValue))?false:lt(e.extra,Ve)}function Vb(e){return !Ve(e)||!Ne(e.schema)||!Mt(e.table)||!Ne(e.kind)||!Hb.has(e.kind)||!ni(e.columns)||!lt(e.name,Ne)||!lt(e.refSchema,Ne)||!lt(e.refTable,Ne)?false:lt(e.refColumns,ni)}function Kb(e){return !Ve(e)||!Ne(e.schema)||!Mt(e.table)||!Ne(e.text)?false:lt(e.column,Ne)}function tf(e){return !(!Ve(e)||!Ve(e.rls)||!Array.isArray(e.rls.tables)||!e.rls.tables.every(Mt)||!Array.isArray(e.rls.policies)||!e.rls.policies.every(Gb)||!ka(e.vars,Ve)||!ka(e.enums,ni)||!ka(e.schema,t=>Array.isArray(t)&&t.every(Wb))||!Array.isArray(e.tableConstraints)||!e.tableConstraints.every(Vb)||!Array.isArray(e.comments)||!e.comments.every(Kb))}async function nf(e,t){let n=await Jp(e,t);if(!tf(n.deparse))throw new Me("translation","Rebuilt runtime metadata is incomplete.");return va(e,n.deparse),await ir(e,{workflow:"migrations",sourceHash:n.sourceHash,runtimeHash:n.runtimeHash,dbFingerprint:n.dbFingerprint,metadata:n.deparse}),n}async function un(e){if(!Zs(e))return true;try{let t=await rr(e);return await nf(e,t),cn.delete(e),!0}catch(t){let n=t instanceof Me?t:new Me("translation",String(t),{cause:t});return cn.set(e,n),false}}async function rf(e){if(!Zs(e))return "skipped";try{let t=await rr(e);return await Bb(e,t)?(cn.delete(e),console.log(ti.default.dim("Runtime metadata restored from supabase/.temp/.runtime-metadata-cache.json")),"restored"):(await nf(e,t),cn.delete(e),console.log(ti.default.dim("Runtime metadata rebuilt from applied migrations.")),"recalculated")}catch(t){let n=t instanceof Me?t:new Me("translation",String(t),{cause:t});return cn.set(e,n),"failed"}}async function sf(e){let t=cn.get(e);return t?.failure==="invalid-history"?[t.message,"Run `lite db reset` to recreate the database from valid migration files."]:t?.failure==="drift"?[t.message,"Run `lite db reset` to replay the applied migrations onto a fresh database."]:[t?.message??"Applied migration metadata could not be reconstructed.","Run `lite db reset` to rebuild the database and runtime metadata."]}async function of(){try{await he__default.unlink(Pa());}catch{}}var ti,Qp,Zp,cn,qb,Hb,Ve,Ne,Mt,ni,lt,ka,ei,or=b(()=>{ti=K(X());Yp();nr();Ca();Qp="supabase/.temp/.runtime-metadata-cache.json",Zp=3,cn=new WeakMap;qb=new Set(["SELECT","INSERT","UPDATE","DELETE","ALL"]),Hb=new Set(["unique","check","foreign_key"]),Ve=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ne=e=>typeof e=="string",Mt=e=>typeof e=="string"&&e.length>0,ni=e=>Array.isArray(e)&&e.every(Ne),lt=(e,t)=>e==null||t(e),ka=(e,t)=>Ve(e)&&Object.values(e).every(t),ei=e=>typeof e=="string"&&/^[a-f0-9]{64}$/.test(e);});var af={};me(af,{start:()=>zb});var ar,zb,lf=b(()=>{da();gt();ar=K(X());Lt();Re();Te();Qt();Sa();Ea();_a();or();zb=e=>{e.command("start").option("--config <config>","Path to the config file").option("--host [host]","Specify hostname (use without a value to expose all interfaces)").option("--admin","Enable local admin mode explicitly").option("--no-admin","Disable local admin mode (keyless requests are no longer elevated; normal authentication rules apply)").description("Start the development server").helpGroup("Local Development:").action(async(t,n)=>{await ne(t.config),await Ss(async()=>{let r=Xs(t,n),i=await(await V({withSupabaseClient:false})).project.local.createApp(t.config,{admin:r.admin,adminDefault:r.adminDefault});if(i.hasEnabledSystemBaseSchema()&&await i.ensureSystemSchema(),await rf(i)==="failed"){console.error(ar.default.red("Runtime metadata could not be loaded or rebuilt for this project."));for(let p of await sf(i))console.error(ar.default.dim(p));process.exit(1);}let a=i.config.api?.port??pe.default_api_port,l=await Os(i,{port:a,host:r.host});Ks(r.host,a),Ws(i.config),Vs(i.adminMode),r.warnAdminDisabled&&zs();let c=ns();c&&console.log(ar.default.yellow(` \u26A0 ${c}`)),await i.connection.ping(),Gs(async()=>{await l(),await i.connection.close();});},r=>{console.log(),console.log(ar.default.green(`Ready in ${r.toFixed(2)}ms`));});});};});function tw(e){let t=normalize(e);return t.length>1&&t[t.length-1]===sep&&(t=t.substring(0,t.length-1)),t}function ff(e,t){return e.replace(nw,t)}function sw(e){return e==="/"||rw.test(e)}function Oa(e,t){let{resolvePaths:n,normalizePath:r,pathSeparator:s}=t,i=process.platform==="win32"&&e.includes("/")||e.startsWith(".");if(n&&(e=resolve(e)),(r||i)&&(e=tw(e)),e===".")return "";let o=e[e.length-1]!==s;return ff(o?e+s:e,s)}function mf(e,t){return t+e}function iw(e,t){return function(n,r){return r.startsWith(e)?r.slice(e.length)+n:ff(relative(e,r),t.pathSeparator)+t.pathSeparator+n}}function ow(e){return e}function aw(e,t,n){return t+e+n}function lw(e,t){let{relativePaths:n,includeBasePath:r}=t;return n&&e?iw(e,t):r?mf:ow}function cw(e){return function(t,n){n.push(t.substring(e.length)||".");}}function uw(e){return function(t,n,r){let s=t.substring(e.length)||".";r.every(i=>i(s,true))&&n.push(s);}}function dw(e,t){let{includeDirs:n,filters:r,relativePaths:s}=t;return n?s?r&&r.length?uw(e):cw(e):r&&r.length?fw:pw:mw}function Sw(e){let{excludeFiles:t,filters:n,onlyCounts:r}=e;return t?ww:n&&n.length?r?hw:gw:r?yw:bw}function xw(e){return e.group?_w:Ew}function Aw(e){return e.group?Tw:Cw}function vw(e,t){return !e.resolveSymlinks||e.excludeSymlinks?null:t?Rw:$w}function df(e,t,n){if(n.options.useRealPaths)return kw(t,n);let r=dirname(e),s=1;for(;r!==n.root&&s<2;){let i=n.symlinks.get(r);!!i&&(i===t||i.startsWith(t)||t.startsWith(i))?s++:r=dirname(r);}return n.symlinks.set(e,t),s>1}function kw(e,t){return t.visited.includes(e+t.options.pathSeparator)}function ri(e,t,n,r){t(e&&!r?e:null,n);}function Mw(e,t){let{onlyCounts:n,group:r,maxFiles:s}=e;return n?t?Nw:Iw:r?t?Pw:Fw:s?t?Lw:jw:t?Ow:Dw}function qw(e){return e?Bw:Uw}function Vw(e,t){return new Promise((n,r)=>{yf(e,t,(s,i)=>{if(s)return r(s);n(i);});})}function yf(e,t,n){new gf(e,t,n).start();}function Kw(e,t){return new gf(e,t).start()}var cf,nw,rw,pw,fw,mw,hw,gw,yw,bw,ww,Ew,_w,Tw,Cw,$w,Rw,Nw,Pw,Ow,Lw,Iw,Dw,jw,Fw,hf,Uw,Bw,Hw,Gw,Ww,gf,uf,bf,wf,Sf=b(()=>{cf=createRequire(import.meta.url);nw=/[\\/]/g;rw=/^[a-z]:[\\/]$/i;pw=(e,t)=>{t.push(e||".");},fw=(e,t,n)=>{let r=e||".";n.every(s=>s(r,true))&&t.push(r);},mw=()=>{};hw=(e,t,n,r)=>{r.every(s=>s(e,false))&&n.files++;},gw=(e,t,n,r)=>{r.every(s=>s(e,false))&&t.push(e);},yw=(e,t,n,r)=>{n.files++;},bw=(e,t)=>{t.push(e);},ww=()=>{};Ew=e=>e,_w=()=>[""].slice(0,0);Tw=(e,t,n)=>{e.push({directory:t,files:n,dir:t});},Cw=()=>{};$w=function(e,t,n){let{queue:r,fs:s,options:{suppressErrors:i}}=t;r.enqueue(),s.realpath(e,(o,a)=>{if(o)return r.dequeue(i?null:o,t);s.stat(a,(l,c)=>{if(l)return r.dequeue(i?null:l,t);if(c.isDirectory()&&df(e,a,t))return r.dequeue(null,t);n(c,a),r.dequeue(null,t);});});},Rw=function(e,t,n){let{queue:r,fs:s,options:{suppressErrors:i}}=t;r.enqueue();try{let o=s.realpathSync(e),a=s.statSync(o);if(a.isDirectory()&&df(e,o,t))return;n(a,o);}catch(o){if(!i)throw o}};Nw=e=>e.counts,Pw=e=>e.groups,Ow=e=>e.paths,Lw=e=>e.paths.slice(0,e.options.maxFiles),Iw=(e,t,n)=>(ri(t,n,e.counts,e.options.suppressErrors),null),Dw=(e,t,n)=>(ri(t,n,e.paths,e.options.suppressErrors),null),jw=(e,t,n)=>(ri(t,n,e.paths.slice(0,e.options.maxFiles),e.options.suppressErrors),null),Fw=(e,t,n)=>(ri(t,n,e.groups,e.options.suppressErrors),null);hf={withFileTypes:true},Uw=(e,t,n,r,s)=>{if(e.queue.enqueue(),r<0)return e.queue.dequeue(null,e);let{fs:i}=e;e.visited.push(t),e.counts.directories++,i.readdir(t||".",hf,(o,a=[])=>{s(a,n,r),e.queue.dequeue(e.options.suppressErrors?null:o,e);});},Bw=(e,t,n,r,s)=>{let{fs:i}=e;if(r<0)return;e.visited.push(t),e.counts.directories++;let o=[];try{o=i.readdirSync(t||".",hf);}catch(a){if(!e.options.suppressErrors)throw a}s(o,n,r);};Hw=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));}},Gw=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}},Ww=class{aborted=false;abort(){this.aborted=true;}},gf=class{root;isSynchronous;state;joinPath;pushDirectory;pushFile;getArray;groupFiles;resolveSymlink;walkDirectory;callbackInvoker;constructor(e,t,n){this.isSynchronous=!n,this.callbackInvoker=Mw(t,this.isSynchronous),this.root=Oa(e,t),this.state={root:sw(this.root)?this.root:this.root.slice(0,-1),paths:[""].slice(0,0),groups:[],counts:new Gw,options:t,queue:new Hw((r,s)=>this.callbackInvoker(s,r,n)),symlinks:new Map,visited:[""].slice(0,0),controller:new Ww,fs:t.fs||ew},this.joinPath=lw(this.root,t),this.pushDirectory=dw(this.root,t),this.pushFile=Sw(t),this.getArray=xw(t),this.groupFiles=Aw(t),this.resolveSymlink=vw(t,this.isSynchronous),this.walkDirectory=qw(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,n)=>{let{paths:r,options:{filters:s,resolveSymlinks:i,excludeSymlinks:o,exclude:a,maxFiles:l,signal:c,useRealPaths:p,pathSeparator:u},controller:f}=this.state;if(f.aborted||c&&c.aborted||l&&r.length>l)return;let h=this.getArray(this.state.paths);for(let m=0;m<e.length;++m){let d=e[m];if(d.isFile()||d.isSymbolicLink()&&!i&&!o){let g=this.joinPath(d.name,t);this.pushFile(g,h,this.state.counts,s);}else if(d.isDirectory()){let g=aw(d.name,t,this.state.options.pathSeparator);if(a&&a(d.name,g))continue;this.pushDirectory(g,r,s),this.walkDirectory(this.state,g,g,n-1,this.walk);}else if(this.resolveSymlink&&d.isSymbolicLink()){let g=mf(d.name,t);this.resolveSymlink(g,this.state,(y,E)=>{if(y.isDirectory()){if(E=Oa(E,this.state.options),a&&a(d.name,p?E:g+u))return;this.walkDirectory(this.state,E,p?E:g+u,n-1,this.walk);}else {E=p?E:g;let A=basename(E),C=Oa(dirname(E),this.state.options);E=this.joinPath(A,C),this.pushFile(E,h,this.state.counts,s);}});}}this.groupFiles(this.state.groups,t,h);}};uf=class{constructor(e,t){this.root=e,this.options=t;}withPromise(){return Vw(this.root,this.options)}withCallback(e){yf(this.root,this.options,e);}sync(){return Kw(this.root,this.options)}},bf=null;try{cf.resolve("picomatch"),bf=cf("picomatch");}catch{}wf=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 uf(e||".",this.options)}withGlobFunction(e){return this.globFunction=e,this}crawlWithOptions(e,t){return this.options={...this.options,...t},new uf(e||".",this.options)}glob(...e){return this.globFunction?this.globWithOptions(e):this.globWithOptions(e,{dot:true})}globWithOptions(e,...t){let n=this.globFunction||bf;if(!n)throw new Error("Please specify a glob function to use glob matching.");var r=this.globCache[e.join("\0")];return r||(r=n(e,...t),this.globCache[e.join("\0")]=r),this.options.filters.push(s=>r(s)),this}};});var lr=dt((T1,Cf)=>{var Ef="[^\\\\/]",zw="(?=.)",_f="[^/]",Ia="(?:\\/|$)",xf="(?:^|\\/)",Da=`\\.{1,2}${Ia}`,Xw="(?!\\.)",Jw=`(?!${xf}${Da})`,Yw=`(?!\\.{0,1}${Ia})`,Qw=`(?!${Da})`,Zw="[^.\\/]",eS=`${_f}*?`,tS="/",Tf={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:zw,QMARK:_f,END_ANCHOR:Ia,DOTS_SLASH:Da,NO_DOT:Xw,NO_DOTS:Jw,NO_DOT_SLASH:Yw,NO_DOTS_SLASH:Qw,QMARK_NO_DOT:Zw,STAR:eS,START_ANCHOR:xf,SEP:tS},nS={...Tf,SLASH_LITERAL:"[\\\\/]",QMARK:Ef,STAR:`${Ef}*?`,DOTS_SLASH:"\\.{1,2}(?:[\\\\/]|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:[\\\\/]|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:[\\\\/]|$))",QMARK_NO_DOT:"[^.\\\\/]",START_ANCHOR:"(?:^|[\\\\/])",END_ANCHOR:"(?:[\\\\/]|$)",SEP:"\\"},rS={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};Cf.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:rS,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?nS:Tf}};});var cr=dt(Pe=>{var{REGEX_BACKSLASH:sS,REGEX_REMOVE_BACKSLASH:iS,REGEX_SPECIAL_CHARS:oS,REGEX_SPECIAL_CHARS_GLOBAL:aS}=lr();Pe.isObject=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);Pe.hasRegexChars=e=>oS.test(e);Pe.isRegexChar=e=>e.length===1&&Pe.hasRegexChars(e);Pe.escapeRegex=e=>e.replace(aS,"\\$1");Pe.toPosixSlashes=e=>e.replace(sS,"/");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(iS,t=>t==="\\"?"":t);Pe.escapeLast=(e,t,n)=>{let r=e.lastIndexOf(t,n);return r===-1?e:e[r-1]==="\\"?Pe.escapeLast(e,t,r-1):`${e.slice(0,r)}\\${e.slice(r)}`};Pe.removePrefix=(e,t={})=>{let n=e;return n.startsWith("./")&&(n=n.slice(2),t.prefix="./"),n};Pe.wrapOutput=(e,t={},n={})=>{let r=n.contains?"":"^",s=n.contains?"":"$",i=`${r}(?:${e})${s}`;return t.negated===true&&(i=`(?:^(?!${i}).*$)`),i};Pe.basename=(e,{windows:t}={})=>{let n=e.split(t?/[\\/]/:"/"),r=n[n.length-1];return r===""?n[n.length-2]:r};});var Of=dt((A1,Pf)=>{var Af=cr(),{CHAR_ASTERISK:ja,CHAR_AT:lS,CHAR_BACKWARD_SLASH:ur,CHAR_COMMA:cS,CHAR_DOT:Fa,CHAR_EXCLAMATION_MARK:Ma,CHAR_FORWARD_SLASH:Nf,CHAR_LEFT_CURLY_BRACE:Ua,CHAR_LEFT_PARENTHESES:Ba,CHAR_LEFT_SQUARE_BRACKET:uS,CHAR_PLUS:pS,CHAR_QUESTION_MARK:$f,CHAR_RIGHT_CURLY_BRACE:fS,CHAR_RIGHT_PARENTHESES:Rf,CHAR_RIGHT_SQUARE_BRACKET:mS}=lr(),vf=e=>e===Nf||e===ur,kf=e=>{e.isPrefix!==true&&(e.depth=e.isGlobstar?1/0:1);},dS=(e,t)=>{let n=t||{},r=e.length-1,s=n.parts===true||n.scanToEnd===true,i=[],o=[],a=[],l=e,c=-1,p=0,u=0,f=false,h=false,m=false,d=false,g=false,y=false,E=false,A=false,C=false,$=false,R=0,T,x,O={value:"",depth:0,isGlob:false},w=()=>c>=r,D=()=>l.charCodeAt(c+1),q=()=>(T=x,l.charCodeAt(++c));for(;c<r;){x=q();let j;if(x===ur){E=O.backslashes=true,x=q(),x===Ua&&(y=true);continue}if(y===true||x===Ua){for(R++;w()!==true&&(x=q());){if(x===ur){E=O.backslashes=true,q();continue}if(x===Ua){R++;continue}if(y!==true&&x===Fa&&(x=q())===Fa){if(f=O.isBrace=true,m=O.isGlob=true,$=true,s===true)continue;break}if(y!==true&&x===cS){if(f=O.isBrace=true,m=O.isGlob=true,$=true,s===true)continue;break}if(x===fS&&(R--,R===0)){y=false,f=O.isBrace=true,$=true;break}}if(s===true)continue;break}if(x===Nf){if(i.push(c),o.push(O),O={value:"",depth:0,isGlob:false},$===true)continue;if(T===Fa&&c===p+1){p+=2;continue}u=c+1;continue}if(n.noext!==true&&(x===pS||x===lS||x===ja||x===$f||x===Ma)===true&&D()===Ba){if(m=O.isGlob=true,d=O.isExtglob=true,$=true,x===Ma&&c===p&&(C=true),s===true){for(;w()!==true&&(x=q());){if(x===ur){E=O.backslashes=true,x=q();continue}if(x===Rf){m=O.isGlob=true,$=true;break}}continue}break}if(x===ja){if(T===ja&&(g=O.isGlobstar=true),m=O.isGlob=true,$=true,s===true)continue;break}if(x===$f){if(m=O.isGlob=true,$=true,s===true)continue;break}if(x===uS){for(;w()!==true&&(j=q());){if(j===ur){E=O.backslashes=true,q();continue}if(j===mS){h=O.isBracket=true,m=O.isGlob=true,$=true;break}}if(s===true)continue;break}if(n.nonegate!==true&&x===Ma&&c===p){A=O.negated=true,p++;continue}if(n.noparen!==true&&x===Ba){if(m=O.isGlob=true,s===true){for(;w()!==true&&(x=q());){if(x===Ba){E=O.backslashes=true,x=q();continue}if(x===Rf){$=true;break}}continue}break}if(m===true){if($=true,s===true)continue;break}}n.noext===true&&(d=false,m=false);let U=l,S="",_="";p>0&&(S=l.slice(0,p),l=l.slice(p),u-=p),U&&m===true&&u>0?(U=l.slice(0,u),_=l.slice(u)):m===true?(U="",_=l):U=l,U&&U!==""&&U!=="/"&&U!==l&&vf(U.charCodeAt(U.length-1))&&(U=U.slice(0,-1)),n.unescape===true&&(_&&(_=Af.removeBackslashes(_)),U&&E===true&&(U=Af.removeBackslashes(U)));let L={prefix:S,input:e,start:p,base:U,glob:_,isBrace:f,isBracket:h,isGlob:m,isExtglob:d,isGlobstar:g,negated:A,negatedExtglob:C};if(n.tokens===true&&(L.maxDepth=0,vf(x)||o.push(O),L.tokens=o),n.parts===true||n.tokens===true){let j;for(let I=0;I<i.length;I++){let te=j?j+1:p,ue=i[I],ft=e.slice(te,ue);n.tokens&&(I===0&&p!==0?(o[I].isPrefix=true,o[I].value=S):o[I].value=ft,kf(o[I]),L.maxDepth+=o[I].depth),(I!==0||ft!=="")&&a.push(ft),j=ue;}if(j&&j+1<e.length){let I=e.slice(j+1);a.push(I),n.tokens&&(o[o.length-1].value=I,kf(o[o.length-1]),L.maxDepth+=o[o.length-1].depth);}L.slashes=i,L.parts=a;}return L};Pf.exports=dS;});var Ff=dt(($1,jf)=>{var pr=lr(),Le=cr(),{MAX_LENGTH:si,POSIX_REGEX_SOURCE:hS,REGEX_NON_SPECIAL_CHARS:gS,REGEX_SPECIAL_CHARS_BACKREF:yS,REPLACEMENTS:Lf}=pr,bS=(e,t)=>{if(typeof t.expandRange=="function")return t.expandRange(...e,t);e.sort();let n=`[${e.join("-")}]`;try{new RegExp(n);}catch{return e.map(s=>Le.escapeRegex(s)).join("..")}return n},pn=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`,If=e=>{let t=[],n=0,r=0,s=0,i="",o=false;for(let a of e){if(o===true){i+=a,o=false;continue}if(a==="\\"){i+=a,o=true;continue}if(a==='"'){s=s===1?0:1,i+=a;continue}if(s===0){if(a==="[")n++;else if(a==="]"&&n>0)n--;else if(n===0){if(a==="(")r++;else if(a===")"&&r>0)r--;else if(a==="|"&&r===0){t.push(i),i="";continue}}}i+=a;}return t.push(i),t},wS=e=>{let t=false;for(let n of e){if(t===true){t=false;continue}if(n==="\\"){t=true;continue}if(/[?*+@!()[\]{}]/.test(n))return false}return true},Df=e=>{let t=e.trim(),n=true;for(;n===true;)n=false,/^@\([^\\()[\]{}|]+\)$/.test(t)&&(t=t.slice(2,-1),n=true);if(wS(t))return t.replace(/\\(.)/g,"$1")},SS=e=>{let t=e.map(Df).filter(Boolean);for(let n=0;n<t.length;n++)for(let r=n+1;r<t.length;r++){let s=t[n],i=t[r],o=s[0];if(!(!o||s!==o.repeat(s.length)||i!==o.repeat(i.length))&&(s===i||s.startsWith(i)||i.startsWith(s)))return true}return false},qa=(e,t=true)=>{if(e[0]!=="+"&&e[0]!=="*"||e[1]!=="(")return;let n=0,r=0,s=0,i=false;for(let o=1;o<e.length;o++){let a=e[o];if(i===true){i=false;continue}if(a==="\\"){i=true;continue}if(a==='"'){s=s===1?0:1;continue}if(s!==1){if(a==="["){n++;continue}if(a==="]"&&n>0){n--;continue}if(!(n>0)){if(a==="("){r++;continue}if(a===")"&&(r--,r===0))return t===true&&o!==e.length-1?void 0:{type:e[0],body:e.slice(2,o),end:o}}}}},ES=e=>{let t=0,n=[];for(;t<e.length;){let s=qa(e.slice(t),false);if(!s||s.type!=="*")return;let i=If(s.body).map(a=>a.trim());if(i.length!==1)return;let o=Df(i[0]);if(!o||o.length!==1)return;n.push(o),t+=s.end+1;}return n.length<1?void 0:`${n.length===1?Le.escapeRegex(n[0]):`[${n.map(s=>Le.escapeRegex(s)).join("")}]`}*`},_S=e=>{let t=0,n=e.trim(),r=qa(n);for(;r;)t++,n=r.body.trim(),r=qa(n);return t},xS=(e,t)=>{if(t.maxExtglobRecursion===false)return {risky:false};let n=typeof t.maxExtglobRecursion=="number"?t.maxExtglobRecursion:pr.DEFAULT_MAX_EXTGLOB_RECURSION,r=If(e).map(s=>s.trim());if(r.length>1&&(r.some(s=>s==="")||r.some(s=>/^[*?]+$/.test(s))||SS(r)))return {risky:true};for(let s of r){let i=ES(s);if(i)return {risky:true,safeOutput:i};if(_S(s)>n)return {risky:true}}return {risky:false}},Ha=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a string");e=Lf[e]||e;let n={...t},r=typeof n.maxLength=="number"?Math.min(si,n.maxLength):si,s=e.length;if(s>r)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${r}`);let i={type:"bos",value:"",output:n.prepend||""},o=[i],a=n.capture?"":"?:",l=pr.globChars(n.windows),c=pr.extglobChars(l),{DOT_LITERAL:p,PLUS_LITERAL:u,SLASH_LITERAL:f,ONE_CHAR:h,DOTS_SLASH:m,NO_DOT:d,NO_DOT_SLASH:g,NO_DOTS_SLASH:y,QMARK:E,QMARK_NO_DOT:A,STAR:C,START_ANCHOR:$}=l,R=N=>`(${a}(?:(?!${$}${N.dot?m:p}).)*?)`,T=n.dot?"":d,x=n.dot?E:A,O=n.bash===true?R(n):C;n.capture&&(O=`(${O})`),typeof n.noext=="boolean"&&(n.noextglob=n.noext);let w={input:e,index:-1,start:0,dot:n.dot===true,consumed:"",output:"",prefix:"",backtrack:false,negated:false,brackets:0,braces:0,parens:0,quotes:0,globstar:false,tokens:o};e=Le.removePrefix(e,w),s=e.length;let D=[],q=[],U=[],S=i,_,L=()=>w.index===s-1,j=w.peek=(N=1)=>e[w.index+N],I=w.advance=()=>e[++w.index]||"",te=()=>e.slice(w.index+1),ue=(N="",le=0)=>{w.consumed+=N,w.index+=le;},ft=N=>{w.output+=N.output!=null?N.output:N.value,ue(N.value);},ag=()=>{let N=1;for(;j()==="!"&&(j(2)!=="("||j(3)==="?");)I(),w.start++,N++;return N%2===0?false:(w.negated=true,w.start++,true)},Yr=N=>{w[N]++,U.push(N);},mt=N=>{w[N]--,U.pop();},G=N=>{if(S.type==="globstar"){let le=w.braces>0&&(N.type==="comma"||N.type==="brace"),v=N.extglob===true||D.length&&(N.type==="pipe"||N.type==="paren");N.type!=="slash"&&N.type!=="paren"&&!le&&!v&&(w.output=w.output.slice(0,-S.output.length),S.type="star",S.value="*",S.output=O,w.output+=S.output);}if(D.length&&N.type!=="paren"&&(D[D.length-1].inner+=N.value),(N.value||N.output)&&ft(N),S&&S.type==="text"&&N.type==="text"){S.output=(S.output||S.value)+N.value,S.value+=N.value;return}N.prev=S,o.push(N),S=N;},Qr=(N,le)=>{let v={...c[le],conditions:1,inner:""};v.prev=S,v.parens=w.parens,v.output=w.output,v.startIndex=w.index,v.tokensIndex=o.length;let W=(n.capture?"(":"")+v.open;Yr("parens"),G({type:N,value:le,output:w.output?"":h}),G({type:"paren",extglob:true,value:I(),output:W}),D.push(v);},lg=N=>{let le=e.slice(N.startIndex,w.index+1),v=e.slice(N.startIndex+2,w.index),W=xS(v,n);if((N.type==="plus"||N.type==="star")&&W.risky){let se=W.safeOutput?(N.output?"":h)+(n.capture?`(${W.safeOutput})`:W.safeOutput):void 0,Ye=o[N.tokensIndex];Ye.type="text",Ye.value=le,Ye.output=se||Le.escapeRegex(le);for(let Qe=N.tokensIndex+1;Qe<o.length;Qe++)o[Qe].value="",o[Qe].output="",delete o[Qe].suffix;w.output=N.output+Ye.output,w.backtrack=true,G({type:"paren",extglob:true,value:_,output:""}),mt("parens");return}let oe=N.close+(n.capture?")":""),ge;if(N.type==="negate"){let se=O;if(N.inner&&N.inner.length>1&&N.inner.includes("/")&&(se=R(n)),(se!==O||L()||/^\)+$/.test(te()))&&(oe=N.close=`)$))${se}`),N.inner.includes("*")&&(ge=te())&&/^\.[^\\/.]+$/.test(ge)){let Ye=Ha(ge,{...t,fastpaths:false}).output;oe=N.close=`)${Ye})${se})`;}N.prev.type==="bos"&&(w.negatedExtglob=true);}G({type:"paren",extglob:true,value:_,output:oe}),mt("parens");};if(n.fastpaths!==false&&!/(^[*!]|[/()[\]{}"])/.test(e)){let N=false,le=e.replace(yS,(v,W,oe,ge,se,Ye)=>ge==="\\"?(N=true,v):ge==="?"?W?W+ge+(se?E.repeat(se.length):""):Ye===0?x+(se?E.repeat(se.length):""):E.repeat(oe.length):ge==="."?p.repeat(oe.length):ge==="*"?W?W+ge+(se?O:""):O:W?v:`\\${v}`);return N===true&&(n.unescape===true?le=le.replace(/\\/g,""):le=le.replace(/\\+/g,v=>v.length%2===0?"\\\\":v?"\\":"")),le===e&&n.contains===true?(w.output=e,w):(w.output=Le.wrapOutput(le,w,t),w)}for(;!L();){if(_=I(),_==="\0")continue;if(_==="\\"){let v=j();if(v==="/"&&n.bash!==true||v==="."||v===";")continue;if(!v){_+="\\",G({type:"text",value:_});continue}let W=/^\\+/.exec(te()),oe=0;if(W&&W[0].length>2&&(oe=W[0].length,w.index+=oe,oe%2!==0&&(_+="\\")),n.unescape===true?_=I():_+=I(),w.brackets===0){G({type:"text",value:_});continue}}if(w.brackets>0&&(_!=="]"||S.value==="["||S.value==="[^")){if(n.posix!==false&&_===":"){let v=S.value.slice(1);if(v.includes("[")&&(S.posix=true,v.includes(":"))){let W=S.value.lastIndexOf("["),oe=S.value.slice(0,W),ge=S.value.slice(W+2),se=hS[ge];if(se){S.value=oe+se,w.backtrack=true,I(),!i.output&&o.indexOf(S)===1&&(i.output=h);continue}}}(_==="["&&j()!==":"||_==="-"&&j()==="]")&&(_=`\\${_}`),_==="]"&&(S.value==="["||S.value==="[^")&&(_=`\\${_}`),n.posix===true&&_==="!"&&S.value==="["&&(_="^"),S.value+=_,ft({value:_});continue}if(w.quotes===1&&_!=='"'){_=Le.escapeRegex(_),S.value+=_,ft({value:_});continue}if(_==='"'){w.quotes=w.quotes===1?0:1,n.keepQuotes===true&&G({type:"text",value:_});continue}if(_==="("){Yr("parens"),G({type:"paren",value:_});continue}if(_===")"){if(w.parens===0&&n.strictBrackets===true)throw new SyntaxError(pn("opening","("));let v=D[D.length-1];if(v&&w.parens===v.parens+1){lg(D.pop());continue}G({type:"paren",value:_,output:w.parens?")":"\\)"}),mt("parens");continue}if(_==="["){if(n.nobracket===true||!te().includes("]")){if(n.nobracket!==true&&n.strictBrackets===true)throw new SyntaxError(pn("closing","]"));_=`\\${_}`;}else Yr("brackets");G({type:"bracket",value:_});continue}if(_==="]"){if(n.nobracket===true||S&&S.type==="bracket"&&S.value.length===1){G({type:"text",value:_,output:`\\${_}`});continue}if(w.brackets===0){if(n.strictBrackets===true)throw new SyntaxError(pn("opening","["));G({type:"text",value:_,output:`\\${_}`});continue}mt("brackets");let v=S.value.slice(1);if(S.posix!==true&&v[0]==="^"&&!v.includes("/")&&(_=`/${_}`),S.value+=_,ft({value:_}),n.literalBrackets===false||Le.hasRegexChars(v))continue;let W=Le.escapeRegex(S.value);if(w.output=w.output.slice(0,-S.value.length),n.literalBrackets===true){w.output+=W,S.value=W;continue}S.value=`(${a}${W}|${S.value})`,w.output+=S.value;continue}if(_==="{"&&n.nobrace!==true){Yr("braces");let v={type:"brace",value:_,output:"(",outputIndex:w.output.length,tokensIndex:w.tokens.length};q.push(v),G(v);continue}if(_==="}"){let v=q[q.length-1];if(n.nobrace===true||!v){G({type:"text",value:_,output:_});continue}let W=")";if(v.dots===true){let oe=o.slice(),ge=[];for(let se=oe.length-1;se>=0&&(o.pop(),oe[se].type!=="brace");se--)oe[se].type!=="dots"&&ge.unshift(oe[se].value);W=bS(ge,n),w.backtrack=true;}if(v.comma!==true&&v.dots!==true){let oe=w.output.slice(0,v.outputIndex),ge=w.tokens.slice(v.tokensIndex);v.value=v.output="\\{",_=W="\\}",w.output=oe;for(let se of ge)w.output+=se.output||se.value;}G({type:"brace",value:_,output:W}),mt("braces"),q.pop();continue}if(_==="|"){D.length>0&&D[D.length-1].conditions++,G({type:"text",value:_});continue}if(_===","){let v=_,W=q[q.length-1];W&&U[U.length-1]==="braces"&&(W.comma=true,v="|"),G({type:"comma",value:_,output:v});continue}if(_==="/"){if(S.type==="dot"&&w.index===w.start+1){w.start=w.index+1,w.consumed="",w.output="",o.pop(),S=i;continue}G({type:"slash",value:_,output:f});continue}if(_==="."){if(w.braces>0&&S.type==="dot"){S.value==="."&&(S.output=p);let v=q[q.length-1];S.type="dots",S.output+=_,S.value+=_,v.dots=true;continue}if(w.braces+w.parens===0&&S.type!=="bos"&&S.type!=="slash"){G({type:"text",value:_,output:p});continue}G({type:"dot",value:_,output:p});continue}if(_==="?"){if(!(S&&S.value==="(")&&n.noextglob!==true&&j()==="("&&j(2)!=="?"){Qr("qmark",_);continue}if(S&&S.type==="paren"){let W=j(),oe=_;(S.value==="("&&!/[!=<:]/.test(W)||W==="<"&&!/<([!=]|\w+>)/.test(te()))&&(oe=`\\${_}`),G({type:"text",value:_,output:oe});continue}if(n.dot!==true&&(S.type==="slash"||S.type==="bos")){G({type:"qmark",value:_,output:A});continue}G({type:"qmark",value:_,output:E});continue}if(_==="!"){if(n.noextglob!==true&&j()==="("&&(j(2)!=="?"||!/[!=<:]/.test(j(3)))){Qr("negate",_);continue}if(n.nonegate!==true&&w.index===0){ag();continue}}if(_==="+"){if(n.noextglob!==true&&j()==="("&&j(2)!=="?"){Qr("plus",_);continue}if(S&&S.value==="("||n.regex===false){G({type:"plus",value:_,output:u});continue}if(S&&(S.type==="bracket"||S.type==="paren"||S.type==="brace")||w.parens>0){G({type:"plus",value:_});continue}G({type:"plus",value:u});continue}if(_==="@"){if(n.noextglob!==true&&j()==="("&&j(2)!=="?"){G({type:"at",extglob:true,value:_,output:""});continue}G({type:"text",value:_});continue}if(_!=="*"){(_==="$"||_==="^")&&(_=`\\${_}`);let v=gS.exec(te());v&&(_+=v[0],w.index+=v[0].length),G({type:"text",value:_});continue}if(S&&(S.type==="globstar"||S.star===true)){S.type="star",S.star=true,S.value+=_,S.output=O,w.backtrack=true,w.globstar=true,ue(_);continue}let N=te();if(n.noextglob!==true&&/^\([^?]/.test(N)){Qr("star",_);continue}if(S.type==="star"){if(n.noglobstar===true){ue(_);continue}let v=S.prev,W=v.prev,oe=v.type==="slash"||v.type==="bos",ge=W&&(W.type==="star"||W.type==="globstar");if(n.bash===true&&(!oe||N[0]&&N[0]!=="/")){G({type:"star",value:_,output:""});continue}let se=w.braces>0&&(v.type==="comma"||v.type==="brace"),Ye=D.length&&(v.type==="pipe"||v.type==="paren");if(!oe&&v.type!=="paren"&&!se&&!Ye){G({type:"star",value:_,output:""});continue}for(;N.slice(0,3)==="/**";){let Qe=e[w.index+4];if(Qe&&Qe!=="/")break;N=N.slice(3),ue("/**",3);}if(v.type==="bos"&&L()){S.type="globstar",S.value+=_,S.output=R(n),w.output=S.output,w.globstar=true,ue(_);continue}if(v.type==="slash"&&v.prev.type!=="bos"&&!ge&&L()){w.output=w.output.slice(0,-(v.output+S.output).length),v.output=`(?:${v.output}`,S.type="globstar",S.output=R(n)+(n.strictSlashes?")":"|$)"),S.value+=_,w.globstar=true,w.output+=v.output+S.output,ue(_);continue}if(v.type==="slash"&&v.prev.type!=="bos"&&N[0]==="/"){let Qe=N[1]!==void 0?"|$":"";w.output=w.output.slice(0,-(v.output+S.output).length),v.output=`(?:${v.output}`,S.type="globstar",S.output=`${R(n)}${f}|${f}${Qe})`,S.value+=_,w.output+=v.output+S.output,w.globstar=true,ue(_+I()),G({type:"slash",value:"/",output:""});continue}if(v.type==="bos"&&N[0]==="/"){S.type="globstar",S.value+=_,S.output=`(?:^|${f}|${R(n)}${f})`,w.output=S.output,w.globstar=true,ue(_+I()),G({type:"slash",value:"/",output:""});continue}w.output=w.output.slice(0,-S.output.length),S.type="globstar",S.output=R(n),S.value+=_,w.output+=S.output,w.globstar=true,ue(_);continue}let le={type:"star",value:_,output:O};if(n.bash===true){le.output=".*?",(S.type==="bos"||S.type==="slash")&&(le.output=T+le.output),G(le);continue}if(S&&(S.type==="bracket"||S.type==="paren")&&n.regex===true){le.output=_,G(le);continue}(w.index===w.start||S.type==="slash"||S.type==="dot")&&(S.type==="dot"?(w.output+=g,S.output+=g):n.dot===true?(w.output+=y,S.output+=y):(w.output+=T,S.output+=T),j()!=="*"&&(w.output+=h,S.output+=h)),G(le);}for(;w.brackets>0;){if(n.strictBrackets===true)throw new SyntaxError(pn("closing","]"));w.output=Le.escapeLast(w.output,"["),mt("brackets");}for(;w.parens>0;){if(n.strictBrackets===true)throw new SyntaxError(pn("closing",")"));w.output=Le.escapeLast(w.output,"("),mt("parens");}for(;w.braces>0;){if(n.strictBrackets===true)throw new SyntaxError(pn("closing","}"));w.output=Le.escapeLast(w.output,"{"),mt("braces");}if(n.strictSlashes!==true&&(S.type==="star"||S.type==="bracket")&&G({type:"maybe_slash",value:"",output:`${f}?`}),w.backtrack===true){w.output="";for(let N of w.tokens)w.output+=N.output!=null?N.output:N.value,N.suffix&&(w.output+=N.suffix);}return w};Ha.fastpaths=(e,t)=>{let n={...t},r=typeof n.maxLength=="number"?Math.min(si,n.maxLength):si,s=e.length;if(s>r)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${r}`);e=Lf[e]||e;let{DOT_LITERAL:i,SLASH_LITERAL:o,ONE_CHAR:a,DOTS_SLASH:l,NO_DOT:c,NO_DOTS:p,NO_DOTS_SLASH:u,STAR:f,START_ANCHOR:h}=pr.globChars(n.windows),m=n.dot?p:c,d=n.dot?u:c,g=n.capture?"":"?:",y={negated:false,prefix:""},E=n.bash===true?".*?":f;n.capture&&(E=`(${E})`);let A=T=>T.noglobstar===true?E:`(${g}(?:(?!${h}${T.dot?l:i}).)*?)`,C=T=>{switch(T){case "*":return `${m}${a}${E}`;case ".*":return `${i}${a}${E}`;case "*.*":return `${m}${E}${i}${a}${E}`;case "*/*":return `${m}${E}${o}${a}${d}${E}`;case "**":return m+A(n);case "**/*":return `(?:${m}${A(n)}${o})?${d}${a}${E}`;case "**/*.*":return `(?:${m}${A(n)}${o})?${d}${E}${i}${a}${E}`;case "**/.*":return `(?:${m}${A(n)}${o})?${i}${a}${E}`;default:{let x=/^(.*?)\.(\w+)$/.exec(T);if(!x)return;let O=C(x[1]);return O?O+i+x[2]:void 0}}},$=Le.removePrefix(e,y),R=C($);return R&&n.strictSlashes!==true&&(R+=`${o}?`),R};jf.exports=Ha;});var Bf=dt((R1,Uf)=>{var TS=Of(),Ga=Ff(),Mf=cr(),CS=lr(),AS=e=>e&&typeof e=="object"&&!Array.isArray(e),fe=(e,t,n=false)=>{if(Array.isArray(e)){let p=e.map(f=>fe(f,t,n));return f=>{for(let h of p){let m=h(f);if(m)return m}return false}}let r=AS(e)&&e.tokens&&e.input;if(e===""||typeof e!="string"&&!r)throw new TypeError("Expected pattern to be a non-empty string");let s=t||{},i=s.windows,o=r?fe.compileRe(e,t):fe.makeRe(e,t,false,true),a=o.state;delete o.state;let l=()=>false;if(s.ignore){let p={...t,ignore:null,onMatch:null,onResult:null};l=fe(s.ignore,p,n);}let c=(p,u=false)=>{let{isMatch:f,match:h,output:m}=fe.test(p,o,t,{glob:e,posix:i}),d={glob:e,state:a,regex:o,posix:i,input:p,output:m,match:h,isMatch:f};return typeof s.onResult=="function"&&s.onResult(d),f===false?(d.isMatch=false,u?d:false):l(p)?(typeof s.onIgnore=="function"&&s.onIgnore(d),d.isMatch=false,u?d:false):(typeof s.onMatch=="function"&&s.onMatch(d),u?d:true)};return n&&(c.state=a),c};fe.test=(e,t,n,{glob:r,posix:s}={})=>{if(typeof e!="string")throw new TypeError("Expected input to be a string");if(e==="")return {isMatch:false,output:""};let i=n||{},o=i.format||(s?Mf.toPosixSlashes:null),a=e===r,l=a&&o?o(e):e;return a===false&&(l=o?o(e):e,a=l===r),(a===false||i.capture===true)&&(i.matchBase===true||i.basename===true?a=fe.matchBase(e,t,n,s):a=t.exec(l)),{isMatch:!!a,match:a,output:l}};fe.matchBase=(e,t,n)=>(t instanceof RegExp?t:fe.makeRe(t,n)).test(Mf.basename(e));fe.isMatch=(e,t,n)=>fe(t,n)(e);fe.parse=(e,t)=>Array.isArray(e)?e.map(n=>fe.parse(n,t)):Ga(e,{...t,fastpaths:false});fe.scan=(e,t)=>TS(e,t);fe.compileRe=(e,t,n=false,r=false)=>{if(n===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=fe.toRegex(a,t);return r===true&&(l.state=e),l};fe.makeRe=(e,t={},n=false,r=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=Ga.fastpaths(e,t)),s.output||(s=Ga(e,t)),fe.compileRe(s,t,n,r)};fe.toRegex=(e,t)=>{try{let n=t||{};return new RegExp(e,n.flags||(n.nocase?"i":""))}catch(n){if(t&&t.debug===true)throw n;return /$^/}};fe.constants=CS;Uf.exports=fe;});var Wf=dt((v1,Gf)=>{var qf=Bf(),$S=cr();function Hf(e,t,n=false){return t&&(t.windows===null||t.windows===void 0)&&(t={...t,windows:$S.isWindows()}),qf(e,t,n)}Object.assign(Hf,qf);Gf.exports=Hf;});function US(e,t={}){let n=e.length,r=Array(n),s=Array(n),i,o;for(i=0;i<n;i++){let a=Yf(e[i]);r[i]=a;let l=a.length,c=Array(l);for(o=0;o<l;o++)c[o]=(0, fn.default)(a[o],t);s[i]=c;}return a=>{let l=a.split("/");if(l[0]===".."&&MS.test(a))return true;for(i=0;i<n;i++){let c=r[i],p=s[i],u=l.length,f=Math.min(u,c.length);for(o=0;o<f;){let h=c[o];if(h.includes("/"))return true;if(!p[o](l[o]))break;if(!t.noglobstar&&h==="**")return true;o++;}if(o===u)return true}return false}}function Vf(e,t,n){if(e===t||t.startsWith(`${e}/`)){if(n){let s=e.length+ +!qS(e);return (i,o)=>i.slice(s,o?-1:void 0)||"."}let r=t.slice(e.length+1);return r?(s,i)=>{if(s===".")return r;let o=`${r}/${s}`;return i?o.slice(0,-1):o}:(s,i)=>i&&s!=="."?s.slice(0,-1):s}return n?r=>posix.relative(e,r)||".":r=>posix.relative(e,`${t}/${r}`)||"."}function HS(e,t){if(t.startsWith(`${e}/`)){let n=t.slice(e.length+1);return r=>`${n}/${r}`}return n=>{let r=posix.relative(e,`${t}/${n}`);return n[n.length-1]==="/"&&r!==""?`${r}/`:r||"."}}function Kf(e){return e.replace(FS,t=>`${t}/`)}function Yf(e){var t;let n=fn.default.scan(e,GS);return !((t=n.parts)===null||t===void 0)&&t.length?n.parts:[e]}function JS(e,t){let n=fn.default.scan(e);return n.isGlob||n.negated}function fr(...e){console.log(`[tinyglobby ${new Date().toLocaleTimeString("es")}]`,...e);}function Qf(e){return typeof e=="string"?[e]:e??[]}function Wa(e,t,n,r){var s;let i=t.cwd,o=e;e[e.length-1]==="/"&&(o=e.slice(0,-1)),o[o.length-1]!=="*"&&t.expandDirectories&&(o+="/**");let a=XS(i);o=isAbsolute(o.replace(QS,""))?posix.relative(a,o):posix.normalize(o);let l=(s=YS.exec(o))===null||s===void 0?void 0:s[0],c=Yf(o);if(l){let u=(l.length+1)/3,f=0,h=a.split("/");for(;f<u&&c[f+u]===h[h.length+f-u];)o=o.slice(0,(u-f-1)*3)+o.slice((u-f)*3+c[f+u].length+1)||".",f++;let m=posix.join(i,l.slice(f*3));m[0]!=="."&&n.root.length>m.length&&(n.root=Kf(m),n.depthOffset=-u+f);}if(!r&&n.depthOffset>=0){var p;(p=n.commonPath)!==null&&p!==void 0||(n.commonPath=c);let u=[],f=Math.min(n.commonPath.length,c.length);for(let h=0;h<f;h++){let m=c[h];if(m==="**"&&!c[h+1]){u.pop();break}if(h===c.length-1||m!==n.commonPath[h]||JS(m))break;u.push(m);}n.depthOffset=u.length,n.commonPath=u,n.root=Kf(u.length>0?posix.join(i,...u):i);}return o}function ZS(e,t,n){let r=[],s=[];for(let i of e.ignore)i&&(i[0]!=="!"||i[1]==="(")&&s.push(Wa(i,e,n,true));for(let i of t)i&&(i[0]!=="!"||i[1]==="("?r.push(Wa(i,e,n,false)):(i[1]!=="!"||i[2]==="(")&&s.push(Wa(i.slice(1),e,n,true)));return {match:r,ignore:s}}function eE(e,t){let n=e.cwd,r={root:n,depthOffset:0},s=ZS(e,t,r);e.debug&&fr("internal processing patterns:",s);let{absolute:i,caseSensitiveMatch:o,debug:a,dot:l,followSymbolicLinks:c,onlyDirectories:p}=e,u=r.root.replace(Xf,""),f={dot:l,nobrace:e.braceExpansion===false,nocase:!o,noextglob:e.extglob===false,noglobstar:e.globstar===false,posix:true},h=(0, fn.default)(s.match,f),m=(0, fn.default)(s.ignore,f),d=US(s.match,f),g=Vf(n,u,i),y=i?g:Vf(n,u,true),E=($,R)=>{let T=y(R,true);return T!=="."&&!d(T)||m(T)},A;e.deep!==void 0&&(A=Math.round(e.deep-r.depthOffset));let C=new wf({filters:[a?($,R)=>{let T=g($,R),x=h(T)&&!m(T);return x&&fr(`matched ${T}`),x}:($,R)=>{let T=g($,R);return h(T)&&!m(T)}],exclude:a?($,R)=>{let T=E($,R);return fr(`${T?"skipped":"crawling"} ${R}`),T}:E,fs:e.fs,pathSeparator:"/",relativePaths:!i,resolvePaths:i,includeBasePath:i,resolveSymlinks:c,excludeSymlinks:!c,excludeFiles:p,includeDirs:p||!e.onlyFiles,maxDepth:A,signal:e.signal}).crawl(u);return e.debug&&fr("internal properties:",{...r,root:u}),[C,n!==u&&!i&&HS(n,u)]}function tE(e,t){if(t)for(let n=e.length-1;n>=0;n--)e[n]=t(e[n]);return e}function nE(e){let t=Object.assign({},e);for(let n in zf)t[n]===void 0&&Object.assign(t,{[n]:zf[n]});return t.cwd=(t.cwd instanceof URL?fileURLToPath$1(t.cwd):resolve(t.cwd||process.cwd())).replace(Xf,"/"),t.ignore=Qf(t.ignore),t.fs&&(t.fs={readdir:t.fs.readdir||readdir,readdirSync:t.fs.readdirSync||readdirSync,realpath:t.fs.realpath||realpath,realpathSync:t.fs.realpathSync||realpathSync,stat:t.fs.stat||stat,statSync:t.fs.statSync||statSync$1}),t.debug&&fr("globbing with options:",t),t}function rE(e,t={}){var n;if(e&&t?.patterns)throw new Error("Cannot pass patterns as both an argument and an option");let r=jS(e)||typeof e=="string",s=Qf((n=r?e:e.patterns)!==null&&n!==void 0?n:"**/*"),i=nE(r?t:e);return s.length>0?eE(i,s):[]}async function mr(e,t){let[n,r]=rE(e,t);return n?tE(await n.withPromise(),r):[]}var fn,jS,Xf,FS,Jf,MS,BS,qS,GS,WS,VS,KS,zS,XS,YS,QS,zf,Va=b(()=>{Sf();fn=K(Wf()),jS=Array.isArray,Xf=/\\/g,FS=/^[A-Za-z]:$/,Jf=process.platform==="win32",MS=/^(\/?\.\.)+$/;BS=/^[A-Z]:\/$/i,qS=Jf?e=>BS.test(e):e=>e==="/";GS={parts:true};WS=/(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g,VS=/(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g,KS=e=>e.replace(WS,"\\$&"),zS=e=>e.replace(VS,"\\$&"),XS=Jf?zS:KS;YS=/^(\/?\.\.)+/,QS=/\\(?=[()[\]{}!*+?@|])/g;zf={caseSensitiveMatch:true,debug:!!process.env.TINYGLOBBY_DEBUG,expandDirectories:true,followSymbolicLinks:true,onlyFiles:true};});function mn(e){if("String"in e)return e.String.sval}function J(e){return e.map(mn).filter(t=>t!=null)}function Et(e){return e==null?[]:e.List!==void 0?e.List.items||[]:Array.isArray(e)?e:[e]}function dr(e){return QuoteUtils.quoteIdentifier(e)}function dn(e){return Object.keys(e)[0]}function Zf(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 Bt=b(()=>{});function tm(e){let t=e.toLowerCase().trim();if(t.startsWith("_")||t.endsWith("[]"))return "TEXT";let n=oE[t];if(!n)throw new qt(`Unsupported PostgreSQL type: "${e}"`);return n}function ii(e){let t=e.toLowerCase();return ["serial","serial4","bigserial","serial8","smallserial","serial2"].includes(t)}function oi(e){let t=e.toLowerCase();return ["varchar","character varying","char","character","bpchar"].includes(t)}function ai(e){let t=e.toLowerCase();return ["numeric","decimal"].includes(t)}var qt,F,oE,em,aE,li,hn=b(()=>{Bt();qt=class extends Error{},F=class extends qt{constructor(n,r){super(r??`Unsupported node type: ${dn(n)}`);this.node=n;}},oE={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"},em=["<",">","<=",">=","=","<>","!=","+","-","*","/","%","&","|","<<",">>","||","BETWEEN","NOT BETWEEN","IN","NOT IN","LIKE","NOT LIKE","IS NULL","IS NOT NULL","IS TRUE","IS NOT TRUE","IS FALSE","IS NOT FALSE","IS UNKNOWN","IS NOT UNKNOWN","AND","OR","NOT","->>"];aE={CreateEnumStmt:{react:"ignore"},CreateDomainStmt:{react:"warn"},CreateSeqStmt:{react:"ignore"},AlterSeqStmt:{react:"ignore"},CreateSchemaStmt:{react:"warn"},CreatePolicyStmt:{react:"ignore"},AlterPolicyStmt:{react:"ignore"},PartitionElem:{react:"error"},PartitionCmd:{react:"error"},VariableSetStmt:{react:"ignore"},CompositeTypeStmt:{react:"error"},AlterEnumStmt:{react:"error"},AlterObjectSchemaStmt:{react:"error"},AlterOwnerStmt:{react:"error"},AlterTypeStmt:{react:"error"},AlterFunctionStmt:{react:"error"},AlterDefaultPrivilegesStmt:{react:"error"},GrantStmt:{react:"error"},GrantRoleStmt:{react:"error"},CopyStmt:{react:"error"},CreateCastStmt:{react:"error"},AlterOpFamilyStmt:{react:"error"},AlterOperatorStmt:{react:"error"},TruncateStmt:{react:"error"},A_Indirection:{react:"error"},XmlExpr:{react:"error"},XmlSerialize:{react:"error"},RangeTableSample:{react:"error"},GroupingSet:{react:"error"}},li=new Map(Object.entries(aE));});function _t(e){return e!=null&&typeof e=="object"&&e.kind==="storage.foldername"}function xt(e){if(e==null||typeof e!="object")return false;let t=e.kind;return t==="storage.filename"||t==="storage.extension"}function hr(e,t,n){return {$storageObject:{function:e.kind.slice(8),column:e.column,ops:{[t]:n}}}}function lE(e){return e.startsWith("storage.")?e.slice(8):e}function cE(e){return e==="{{storage.operation}}"}function uE(e){switch(e){case "~~":return "$like";case "!~~":return "$notLike";case "~~*":return "$ilike";case "!~~*":return "$notIlike";default:return}}function Ka(e){switch(e){case "$gt":return "$lt";case "$gte":return "$lte";case "$lt":return "$gt";case "$lte":return "$gte";default:return e}}function ci(e,t){return e?"TypeCast"in e&&e.TypeCast.arg?ci(e.TypeCast.arg,t):"A_Const"in e?true:typeof t=="string"&&t.startsWith("{{")&&t.endsWith("}}"):false}var re,gr,za=b(()=>{Bt();hn();re=class extends F{constructor(t,n){super(t,`Unsupported expression: ${n}`);}},gr=class{deparse(t){if("A_Const"in t){let s=t.A_Const;if(s.boolval!==void 0)return s.boolval.boolval?{}:{$always:false}}if("FuncCall"in t){let s=this.storageOperationPredicate(t.FuncCall);if(s)return s}let n=Object.keys(t)[0],r=this[n];if(!r)throw new re({[n]:t},`Unsupported expression: ${n}`);return r.call(this,t[n])}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_Indirection"in t)return this.A_Indirection(t.A_Indirection);if("A_Expr"in t){let r=this.isJwtAccessor(t.A_Expr);return r||this.A_Expr(t.A_Expr)}if("BoolExpr"in t)return this.BoolExpr(t.BoolExpr);let n=Object.keys(t)[0];throw new re({[n]:t},`deparseValue: ${n}`)}A_Expr(t){if(t.kind==="AEXPR_OP"){let n=t.name?.[0],r=n?mn(n):void 0;if(!r)throw new re({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(r);if(!a)throw new re({A_Expr:t},`Unsupported operator: ${r}`);if(_t(i)&&_t(o))throw new re({A_Expr:t},"comparisons between storage.foldername expressions are unsupported");if(_t(i))return {$storageFolder:{column:i.column,index:i.index,ops:{[a]:o}}};if(_t(o)){if(!ci(t.lexpr,i))throw new re({A_Expr:t},"storage.foldername RHS comparisons require a literal or auth placeholder");return {$storageFolder:{column:o.column,index:o.index,ops:{[Ka(a)]:i}}}}if(xt(i)&&xt(o))throw new re({A_Expr:t},"comparisons between Storage object helper expressions are unsupported");if(xt(i))return hr(i,a,o);if(xt(o)){if(!ci(t.lexpr,i))throw new re({A_Expr:t},"Storage object helper RHS comparisons require a literal or auth placeholder");return hr(o,Ka(a),i)}if(cE(o)){if(!ci(t.lexpr,i))throw new re({A_Expr:t},"storage.operation RHS comparisons require a literal or auth placeholder");return {[o]:{[Ka(a)]:i}}}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 n=t.lexpr?this.deparseValue(t.lexpr):void 0,r=t.rexpr?this.deparseValue(t.rexpr):void 0,s=t.kind==="AEXPR_ILIKE"?"~~*":"~~",i=t.name?.[0]?mn(t.name[0])??s:s,o=uE(i);if(!o)throw new re({A_Expr:t},`Unsupported pattern operator: ${i}`);if(_t(r))throw new re({A_Expr:t},"storage.foldername on the right of a pattern predicate is unsupported");if(_t(n))return {$storageFolder:{column:n.column,index:n.index,ops:{[o]:r}}};if(xt(r))throw new re({A_Expr:t},"Storage object helpers on the right of a pattern predicate are unsupported");return xt(n)?hr(n,o,r):{[n]:{[o]:r}}}if(t.kind==="AEXPR_IN"){let n=t.lexpr?this.deparseValue(t.lexpr):void 0,s=(t.name?.[0]?mn(t.name[0]):"=")==="<>"?"$notIn":"$in",i=t.rexpr&&"List"in t.rexpr&&t.rexpr.List.items?t.rexpr.List.items.map(o=>this.deparseValue(o)):[];return _t(n)?{$storageFolder:{column:n.column,index:n.index,ops:{[s]:i}}}:xt(n)?hr(n,s,i):{[n]:{[s]:i}}}throw new re({A_Expr:t},`A_Expr kind: ${t.kind}`)}BoolExpr(t){let n=t.args??[];switch(t.boolop){case "AND_EXPR":return {$and:n.map(r=>this.deparse(r))};case "OR_EXPR":return {$or:n.map(r=>this.deparse(r))};case "NOT_EXPR":return {$not:this.deparse(n[0])};default:throw new re({BoolExpr:t},`BoolExpr op: ${t.boolop}`)}}NullTest(t){let n=t.arg?this.deparseValue(t.arg):void 0,r=t.nulltesttype==="IS_NULL"?"$is":"$isNot";return _t(n)?{$storageFolder:{column:n.column,index:n.index,ops:{[r]:null}}}:xt(n)?hr(n,r,null):{[n]:{[r]:null}}}SubLink(t){if(t.subLinkType==="ANY_SUBLINK"){let n=t.testexpr?this.deparseValue(t.testexpr):void 0,r=t.subselect?this.SelectStmt(t.subselect.SelectStmt):void 0;return {[n]:{$in:r}}}if(t.subLinkType==="EXISTS_SUBLINK")return {$exists:t.subselect?this.SelectStmt(t.subselect.SelectStmt):void 0};if(t.subLinkType==="EXPR_SUBLINK"){let n=t.subselect?t.subselect.SelectStmt:void 0;if(n?.fromClause?.length)return this.SelectStmt(n);if(n?.targetList?.[0]){let r=n.targetList[0],s="ResTarget"in r?r.ResTarget:void 0;if(s?.val){let i=this.deparseValue(s.val);return i}}}throw new re({SubLink:t},`SubLink type: ${t.subLinkType}`)}SelectStmt(t){let{from:n,schema:r,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 m=this.deparseValue(h.val);Array.isArray(m)?i.push(...m.map(String)):m!=null&&m!==""&&i.push(String(m));}}let o=t.whereClause?this.deparse(t.whereClause):void 0,a=this.deparseSortClause(t.sortClause),l=this.deparseLimit(t.limitCount),c=this.deparseLimit(t.limitOffset),p=this.deparseGroupClause(t.groupClause),u={type:"query",from:n,select:i};return r&&(u.schema=r),Object.keys(s).length>0&&(u.join=s),o&&(u.where=o),a.length>0&&(u.order=a),l!==void 0&&(u.limit=l),c!==void 0&&(u.offset=c),p.length>0&&(u.group=p),u}FuncCall(t){let n=this.isAuthFunc(t.funcname??[]);if(n)return n;let r=J(t.funcname??[]);if(r.length===2&&r[0]==="storage"&&r[1]==="operation"&&(t.args?.length??0)===0)return "{{storage.operation}}";if(r.length===2&&r[0]==="storage"&&(r[1]==="filename"||r[1]==="extension")){let s=t.args?.[0];if(t.args?.length!==1||!s||!("ColumnRef"in s))throw new re({FuncCall:t},`storage.${r[1]} requires one column argument`);let i=this.ColumnRef(s.ColumnRef);if(i!=="name")throw new re({FuncCall:t},`only storage.${r[1]}(name) is supported`);return {kind:`storage.${r[1]}`,column:i}}throw new re({FuncCall:t},`FuncCall: ${J(t.funcname??[]).join(".")}`)}storageOperationPredicate(t){let n=J(t.funcname??[]);if(n.length!==2||n[0]!=="storage"||n[1]!=="allow_only_operation"&&n[1]!=="allow_any_operation")return null;let r=t.args?.[0],s;if(n[1]==="allow_only_operation"&&t.args?.length===1&&r)s=[this.deparseValue(r)];else if(n[1]==="allow_any_operation"&&t.args?.length===1&&r)if("A_ArrayExpr"in r)s=(r.A_ArrayExpr.elements??[]).map(o=>this.deparseValue(o));else if(this.deparseValue(r)===null)s=[];else throw new re({FuncCall:t},`storage.${n[1]} requires its canonical operation argument`);else throw new re({FuncCall:t},`storage.${n[1]} requires its canonical operation argument`);if(!s.every(o=>o===null||typeof o=="string"))throw new re({FuncCall:t},`storage.${n[1]} requires text operation names`);let i=s.filter(o=>typeof o=="string"&&o!=="").map(lE);return n[1]==="allow_only_operation"&&i.length===0?{$always:false}:{"{{storage.normalizedOperation}}":n[1]==="allow_only_operation"?{$eq:i[0]}:{$in:i.filter(Boolean)}}}ColumnRef(t){let n=J(t.fields??[]);return n.length===1?n[0]:n.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 re({A_Const:t},"A_Const: unknown variant")}TypeCast(t){if(!t.arg)throw new re({TypeCast:t},"TypeCast: missing arg");return this.deparseValue(t.arg)}A_Indirection(t){let n=t.arg?.FuncCall,r=n?J(n.funcname??[]):[],s=t.indirection??[],i=s[0]?.A_Indices,o=i?.uidx?.A_Const,a=o?this.A_Const(o):void 0,l=n?.args?.[0];if(r.length!==2||r[0]!=="storage"||r[1]!=="foldername"||!l||!("ColumnRef"in l)||s.length!==1||i?.is_slice===true||i?.lidx!=null||typeof a!="number"||!Number.isInteger(a)||a<1)throw new re({A_Indirection:t},"only indexed storage.foldername(column) expressions are supported");let c=this.ColumnRef(l.ColumnRef);if(c!=="name")throw new re({A_Indirection:t},"only indexed storage.foldername(name) expressions are supported");return {kind:"storage.foldername",column:c,index:a}}BooleanTest(t){let n=t.arg?this.deparseValue(t.arg):void 0;return t.booltesttype==="IS_TRUE"?{[n]:{$eq:true}}:{[n]:{$eq:false}}}deparseFromClause(t){let n={};if(t.length===0)return {from:"",join:n};let r=t[0];if("RangeVar"in r){let s=r.RangeVar;return {from:s.relname??"",schema:s.schemaname,join:n}}if("JoinExpr"in r){let{from:s,schema:i}=this.walkJoinExpr(r.JoinExpr,n);return {from:s,schema:i,join:n}}return {from:"",join:n}}walkJoinExpr(t,n){let r={from:""};if(t.larg)if("RangeVar"in t.larg){let s=t.larg.RangeVar;r={from:s.relname??"",schema:s.schemaname};}else "JoinExpr"in t.larg&&(r=this.walkJoinExpr(t.larg.JoinExpr,n));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 n){let p=2;for(;`${c}_${p}`in n;)p++;c=`${c}_${p}`;}n[c]=l;}return r}deparseSortClause(t){if(!t)return [];let n=[];for(let r of t){if(!("SortBy"in r))continue;let s=r.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),n.push(a);}return n}deparseLimit(t){if(!t)return;let n=this.deparseValue(t);return typeof n=="number"?n:Number(n)}deparseGroupClause(t){return t?t.map(n=>String(this.deparseValue(n))):[]}isAuthFunc(t){let n=J(t);if(n.length===2&&n[0]==="auth"){if(n[1]==="uid")return "{{auth.uid}}";if(n[1]==="jwt")return "{{auth.jwt}}";if(n[1]==="role")return "{{auth.role}}";throw new Error(`Unsupported auth function: "${n.slice(1).join(".")}"`)}return null}isJwtAccessor(t){if(t.kind!=="AEXPR_OP")return null;let n=t.name?.[0]?mn(t.name[0]):void 0;if(n!=="->"&&n!=="->>")return null;let r=t.rexpr&&"A_Const"in t.rexpr?t.rexpr.A_Const.sval?.sval:void 0;if(r===void 0)return null;if(t.lexpr&&"FuncCall"in t.lexpr)return this.isAuthFunc(t.lexpr.FuncCall.funcname??[])==="{{auth.jwt}}"?`{{auth.jwt.${r}}}`:null;if(t.lexpr&&"A_Expr"in t.lexpr){let s=this.isJwtAccessor(t.lexpr.A_Expr);if(s)return `${s.slice(0,-2)}.${r}}}`}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 Tt,Xa=b(()=>{Tt=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 yr,Ja=b(()=>{yr=class extends Error{constructor(n,r,s,i){super(`check constraint "${s}" violated for ${n}.${r}`);this.table=n;this.column=r;this.constraint=s;this.value=i;this.name="CheckConstraintError";}};});var we,ct=b(()=>{Ja();we=class{context;factoryExtra;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,n){return {status:"fail",message:t,action:n}}validationPass(){return {status:"pass",message:null}}isNullish(t){return t==null}toColumnDDL(t){let{includeNullable:n=true}=t??{},r=[],s=this.context.column;r.push(this.quoteIfNeeded(s)),r.push(this.sqliteType),this.context.isPrimaryKey&&r.push("PRIMARY KEY"),this.context.isSerial&&this.context.isPrimaryKey&&r.push("AUTOINCREMENT"),n&&!this.context.nullable&&!this.context.isPrimaryKey&&r.push("NOT NULL"),this.context.isUnique&&!this.context.isPrimaryKey&&r.push("UNIQUE"),this.context.defaultValue!==null&&r.push(`DEFAULT ${this.context.defaultValue}`);let i=this.checkConstraint();return i&&r.push(`CHECK (${i})`),r.join(" ")}checkError(t,n){return new yr(this.context.table,this.context.column,t,n)}quoteIfNeeded(t){return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)?t:`"${t}"`}};});var Ht,ui=b(()=>{ct();Ht=class extends we{get sqliteType(){return "INTEGER"}};});var br,Ya=b(()=>{ui();br=class extends Ht{constructor(t){super({...t,isSerial:true});}};});function pE(e,t){let{precision:n,scale:r}=t,s=10**r,i=10**(n-r);return Math.abs(Math.round(e*s)-e*s)<1e-4&&Math.abs(e)<i}var Gt,pi=b(()=>{ct();Gt=class extends we{numericPrecision;constructor(t,n){super(t),this.numericPrecision=n;}get isShimBacked(){return this.numericPrecision!==void 0}get sqliteType(){return "REAL"}checkConstraint(){if(this.numericPrecision){let{precision:t,scale:n}=this.numericPrecision,r=this.context.column,s=10**n,i=10**(t-n);return `ABS(ROUND(${r} * ${s}) - ${r} * ${s}) < 0.0001 AND ABS(${r}) < ${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:n,scale:r}=this.numericPrecision;if(!pE(t,this.numericPrecision))return this.validationFail(`Does not fit numeric(${n}, ${r}).`,"Patch rows within numeric precision.")}return this.validationPass()}};});var ce,Ue=b(()=>{ct();ce=class extends we{lengthConstraint;constructor(t,n){super(t),this.lengthConstraint=n;}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 wr,Qa=b(()=>{ct();wr=class extends we{get sqliteType(){return "BLOB"}};});var Sr,Za=b(()=>{ct();Sr=class extends we{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}checkConstraint(){return `${this.context.column} IN (0, 1)`}serialize(t){if(this.isNullish(t))return t;if(t===true||t===1)return 1;if(t===false||t===0)return 0;throw this.checkError("boolean_range",t)}deserialize(t){if(this.isNullish(t)||t===true||t===false)return t;if(typeof t=="number"&&Number.isFinite(t)){if(t===1)return true;if(t===0)return false}return t===1n?true:t===0n?false:t==="1"||t==="true"?true:t==="0"||t==="false"?false:t}validateStorage(t){return this.isNullish(t)?this.validationPass():t===1||t===0?this.validationPass():this.validationFail("Expected 0 or 1.","Patch rows with boolean values.")}};});function nm(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var Er,el=b(()=>{ct();Er=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 n=nm(t);return n.ok?n.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."):nm(t).ok?this.validationPass():this.validationFail("Invalid JSON text.","Patch rows with valid JSON.")}};});function fE(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 _r,tl=b(()=>{Ue();_r=class extends ce{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"||!fE(t)?this.validationFail("Invalid date.","Patch rows with YYYY-MM-DD dates."):this.validationPass()}};});function mE(e){let t=e.match(/^(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?([+-](\d{2}):?(\d{2}))?$/);if(!t)return false;let n=Number(t[1]),r=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 n<=24&&r<=59&&s<=59&&(n!==24||r===0&&s===0)&&a}var xr,nl=b(()=>{Ue();xr=class extends ce{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"||!mE(t)?this.validationFail("Invalid time.","Patch rows with HH:MM[:SS] times."):this.validationPass()}};});function dE(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 n=Number(t[1]),r=Number(t[2]),s=Number(t[3]),i=Number(t[4]),o=Number(t[5]),a=t[6]===void 0?0:Number(t[6]),l=t[8]===void 0?null:Number(t[8]),c=t[9]===void 0?null:Number(t[9]),p=new Date(Date.UTC(n,r-1,s)),u=p.getUTCFullYear()===n&&p.getUTCMonth()===r-1&&p.getUTCDate()===s,f=i<=24&&o<=59&&a<=59&&(i!==24||o===0&&a===0),h=l===null||c!==null&&l<=15&&c<=59;return u&&f&&h}var Tr,rl=b(()=>{Ue();Tr=class extends ce{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"||!dE(t)?this.validationFail("Invalid timestamp.","Patch rows with ISO timestamps."):this.validationPass()}};});var Cr,sl=b(()=>{Ue();Cr=class extends ce{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 Ar,il=b(()=>{Ue();Ar=class extends ce{enumValues;constructor(t,n){super(t),this.enumValues=n;}get isShimBacked(){return true}checkConstraint(){let t=this.context.column,n=this.enumValues.map(r=>`'${r.replace(/'/g,"''")}'`).join(", ");return `${t} IN (${n})`}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 rm(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var Ct,fi=b(()=>{ct();Ct=class extends we{elementField;constructor(t,n){super(t),this.elementField=n;}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(n=>this.elementField.serialize(n))):JSON.stringify(t)}deserialize(t){if(this.isNullish(t))return t;if(typeof t=="string"){let n=rm(t);if(n.ok&&Array.isArray(n.value))return this.elementField?n.value.map(r=>this.elementField.deserialize(r)):n.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 n=rm(t);if(!n.ok)return this.validationFail("Invalid JSON array text.","Patch rows with array values.");if(!Array.isArray(n.value))return this.validationFail("Expected JSON array.","Patch rows with array values.");if(this.elementField)for(let r of n.value){let s=this.elementField.validateStorage(r);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 sm(e){return gE.test(e.toLowerCase())}var hE,gE,$r,ol=b(()=>{Ue();hE="????????-????-????-????-????????????",gE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;$r=class extends ce{get isShimBacked(){return true}checkConstraint(){let t=this.quoteIfNeeded(this.context.column);return `${t} IS NULL OR ${t} GLOB '${hE}'`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string")throw this.checkError("uuid_format",t);let n=t.toLowerCase();if(!sm(n))throw this.checkError("uuid_format",t);return n}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!sm(t)?this.validationFail("Invalid UUID.","Patch rows with valid UUIDs."):this.validationPass()}};});function yE(e){let t=e.split("/");if(t.length>2)return null;let n=t[0];if(!n)return null;if(t.length===1)return {address:n,prefix:null};let r=t[1];return !r||!/^\d+$/.test(r)?null:{address:n,prefix:Number(r)}}function bE(e){let t=e.split(".");return t.length!==4?false:t.every(n=>{if(!/^\d+$/.test(n))return false;let r=Number(n);return r>=0&&r<=255})}function wE(e){if(!e.includes(":"))return false;try{return new URL(`http://[${e}]/`),!0}catch{return false}}function im(e){let t=yE(e);return t?bE(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=32:wE(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=128:false:false}var Rr,al=b(()=>{Ue();Rr=class extends ce{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 n=t.trim();if(!im(n))throw this.checkError("inet_format",t);return n}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!im(t.trim())?this.validationFail("Invalid inet address.","Patch rows with valid inet strings."):this.validationPass()}};});var vr,ll=b(()=>{Ue();vr=class extends ce{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 Ie(e,t){let n=LE(e,t);if(t){let{enumValues:r,...s}=t;n.factoryExtra=s;}return n}function LE(e,t){if(t?.isArray){let r=Ie(e,{...t,isArray:false});return new Ct(e,r)}if(t?.enumValues)return new Ar(e,t.enumValues);let n=e.pgTypeName.toLowerCase().trim();if(n.startsWith("_")||n.endsWith("[]")){let r=n.startsWith("_")?n.slice(1):n.slice(0,-2),s={...e,pgTypeName:r},i=Ie(s);return new Ct(e,i)}return EE.has(n)?new br(e):SE.has(n)?new Ht(e):CE.has(n)?new Sr(e):AE.has(n)?new Er(e):kE.has(n)?new _r(e):NE.has(n)?new xr(e):PE.has(n)?new Tr(e):OE.has(n)?new Cr(e):TE.has(n)?new wr(e):_E.has(n)?new Gt(e,t?.numericPrecision):$E.has(n)?new $r(e):RE.has(n)?new ce(e,63):vE.has(n)?new Rr(e):xE.has(n)?new ce(e,t?.lengthConstraint):new vr(e)}var SE,EE,_E,xE,TE,CE,AE,$E,RE,vE,kE,NE,PE,OE,cl=b(()=>{ui();Ya();pi();Ue();Qa();Za();el();tl();nl();rl();sl();il();fi();ol();al();ll();SE=new Set(["int2","smallint","int4","integer","int","int8","bigint"]),EE=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]),_E=new Set(["float4","real","float8","double precision","numeric","decimal"]),xE=new Set(["text","varchar","character varying","char","character","bpchar"]),TE=new Set(["bytea"]),CE=new Set(["bool","boolean"]),AE=new Set(["json","jsonb"]),$E=new Set(["uuid"]),RE=new Set(["name"]),vE=new Set(["inet"]),kE=new Set(["date"]),NE=new Set(["time","timetz","time without time zone","time with time zone"]),PE=new Set(["timestamp","timestamptz","timestamp without time zone","timestamp with time zone"]),OE=new Set(["interval"]);});function ul(e,t="auto"){let n=e.toLowerCase(),r=mi[n];if(!r)return null;switch(t){case "translate":{if(!r.sqlite)throw new Error(`No SQLite translation for function "${e}"`);return {sqliteExpr:r.sqlite(),jsFn:null}}case "synthetic":{if(!r.js)throw new Error(`No JS implementation for function "${e}"`);return {sqliteExpr:null,jsFn:r.js}}case "auto":return r.js?{sqliteExpr:null,jsFn:r.js}:r.sqlite?{sqliteExpr:r.sqlite(),jsFn:null}:null}}var om,mi,pl=b(()=>{om="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)))",mi={gen_random_uuid:{sqlite:()=>om,js:()=>crypto.randomUUID()},uuid_generate_v4:{sqlite:()=>om,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 Wt,am=b(()=>{Wt=class{table;schema;fields;constructor(t,n="public",r=new Map){this.table=t,this.schema=n,this.fields=r;}get(t){return this.fields.get(t)}has(t){return this.fields.has(t)}set(t,n){this.fields.set(t,n);}columns(){return Array.from(this.fields.keys())}all(){return Array.from(this.fields.values())}serializeRow(t){let n={};for(let[r,s]of Object.entries(t)){let i=this.fields.get(r);n[r]=i?i.serialize(s):s;}return n}deserializeRow(t){let n={};for(let[r,s]of Object.entries(t)){let i=this.fields.get(r);n[r]=i?i.deserialize(s):s;}return n}applyDefaults(t){let n={...t};for(let[r,s]of this.fields)!(r in n)&&s.context.defaultFn&&(n[r]=s.context.defaultFn());return n}};});var lm=b(()=>{ct();Ja();ui();Ya();pi();Ue();Qa();Za();el();tl();nl();rl();sl();il();fi();ol();al();ll();cl();pl();am();});var Sl={};me(Sl,{_resetWarnedMissingToClauseForTests:()=>IE,collectComments:()=>wl,collectEnums:()=>hl,collectPolicies:()=>yl,collectSchema:()=>kr,collectTableConstraints:()=>bl,collectVariables:()=>gl,lookupEnumValue:()=>Be});function IE(){dl.clear();}function hl(e){let t=new Map,n=i=>{let o=i.toLowerCase();return o.startsWith("public.")?[o,o.slice(7)]:o.includes(".")?[o]:[o,`public.${o}`]},r=(i,o)=>{for(let a of n(i))t.set(a,o);},s=i=>{for(let o of n(i))t.delete(o);};for(let i of e.stmts??[])if(i.stmt){if("CreateEnumStmt"in i.stmt){let o=i.stmt.CreateEnumStmt,a=J(o.typeName??[]).join(".");a&&o.vals&&r(a,J(o.vals));continue}if("AlterEnumStmt"in i.stmt){let o=i.stmt.AlterEnumStmt,a=J(o.typeName??[]).join("."),l=Be(t,a);if(!a||!l||!o.newVal)continue;let c=[...l];if(o.oldVal){let f=c.indexOf(o.oldVal);f!==-1&&(c[f]=o.newVal),r(a,c);continue}if(l.includes(o.newVal))continue;let p=o.newValNeighbor?c.indexOf(o.newValNeighbor):-1,u=p===-1?c.length:p+(o.newValIsAfter===true?1:0);c.splice(u,0,o.newVal),r(a,c);continue}if("RenameStmt"in i.stmt&&i.stmt.RenameStmt.renameType==="OBJECT_TYPE"){let o=i.stmt.RenameStmt,a=o.object&&"List"in o.object?J(o.object.List.items??[]):[],l=a.join("."),c=Be(t,l);if(!l||!o.newname||!c)continue;s(l),r([...a.slice(0,-1),o.newname].join("."),c);continue}if("DropStmt"in i.stmt&&i.stmt.DropStmt.removeType==="OBJECT_TYPE")for(let o of i.stmt.DropStmt.objects??[])"TypeName"in o&&s(J(o.TypeName.names??[]).join("."));}return t}function Be(e,t){let n=t.toLowerCase(),r=e.get(n);return r||(n.startsWith("public.")?e.get(n.slice(7)):e.get(`public.${n}`))}function gl(e){let t=new Map;for(let n of e.stmts??[]){if(!n.stmt||!("VariableSetStmt"in n.stmt))continue;let r=n.stmt.VariableSetStmt,s=r.name,i=Zf(r.args?.[0]??{});t.set(s,{value:i,local:r.is_local});}return t}function cm(e){let t=[],n=false;for(let r of e??[])if("RoleSpec"in r){let s=r.RoleSpec;s.roletype==="ROLESPEC_PUBLIC"?s.location===-1&&(n=true):s.roletype==="ROLESPEC_CSTRING"&&s.rolename&&t.push(s.rolename);}return {roles:t,implicitPublic:n}}function di(e,t){return e&&e.length>0?e:t}function fl(e,t,n){return e.findIndex(r=>r.data.name===t.name&&r.data.table===t.table&&di(r.data.schema,n)===di(t.schema,n))}function ml(e,t){return new Error(`policy "${e}" for table "${t}" does not exist`)}function um(e,t,n,r){return e.data.table===t&&di(e.data.schema,r)===di(n,r)}function yl(e,t={}){let n=t.defaultSchema||"public",r=t.validateMutations===true,s=new gr,i=new Set,o=[];for(let a of e.stmts??[])if(a.stmt){if("CreatePolicyStmt"in a.stmt){let l=a.stmt.CreatePolicyStmt,c=l.table?.relname??"",p=l.table?.schemaname,u={select:"SELECT",insert:"INSERT",update:"UPDATE",delete:"DELETE"},f=l.cmd_name?u[l.cmd_name]??"ALL":"ALL",h=l.permissive===true,{roles:m,implicitPublic:d}=cm(l.roles),g=l.qual?s.deparse(l.qual):void 0,y=l.with_check?s.deparse(l.with_check):void 0;if(d){let A=p?`${p}.${c}`:c,C=l.policy_name??"",$=`${A}::${C}`;if(!dl.has($)){dl.add($);let R=JSON.stringify(g)+JSON.stringify(y);/\{\{auth\.(uid|jwt|role)/i.test(R)||console.warn(`[supalite] policy "${C}" on "${A}" has no TO clause \u2014 applies to all roles (PUBLIC). For clarity, prefer an explicit \`TO <role>\` clause (e.g. \`TO authenticated\`).`);}}let E=new Tt({name:l.policy_name??"",table:c,schema:p,command:f,permissive:h,roles:m,using:g,withCheck:y});o.push(E);}if("DropStmt"in a.stmt&&a.stmt.DropStmt.removeType==="OBJECT_POLICY"){let l=a.stmt.DropStmt,c=l.objects?.[0];if(c&&"List"in c){let p=J(c.List.items??[]),u=p[p.length-1],f=p[p.length-2],h=p.length>=3?p[p.length-3]:void 0;if(u&&f){let m=fl(o,{name:u,table:f,schema:h},n);if(m!==-1)o.splice(m,1);else if(r&&!l.missing_ok)throw ml(u,f)}}}if("AlterPolicyStmt"in a.stmt){let l=a.stmt.AlterPolicyStmt,c=l.policy_name??"",p=l.table?.relname??"",u=l.table?.schemaname,f=fl(o,{name:c,table:p,schema:u},n);if(f===-1){if(r)throw ml(c,p);continue}let h=o[f].data,m=l.roles?cm(l.roles).roles:h.roles,d=l.qual?s.deparse(l.qual):h.using,g=l.with_check?s.deparse(l.with_check):h.withCheck;o[f]=new Tt({...h,roles:m,using:d,withCheck:g});}if("RenameStmt"in a.stmt&&a.stmt.RenameStmt.renameType==="OBJECT_POLICY"){let l=a.stmt.RenameStmt,c=l.subname??"",p=l.relation?.relname??"",u=l.relation?.schemaname,f=fl(o,{name:c,table:p,schema:u},n);if(f===-1){if(r)throw ml(c,p);continue}l.newname&&(o[f]=new Tt({...o[f].data,name:l.newname}));}if("RenameStmt"in a.stmt&&a.stmt.RenameStmt.renameType==="OBJECT_TABLE"){let l=a.stmt.RenameStmt,c=l.relation?.relname??"",p=l.newname??"",u=l.relation?.schemaname;if(c&&p&&c!==p){i.delete(c)&&i.add(p);for(let f=0;f<o.length;f++)um(o[f],c,u,n)&&(o[f]=new Tt({...o[f].data,table:p}));}}if("DropStmt"in a.stmt&&a.stmt.DropStmt.removeType==="OBJECT_TABLE")for(let l of a.stmt.DropStmt.objects??[]){if(!("List"in l))continue;let c=J(l.List.items??[]),p=c[c.length-1],u=c.length>=2?c[c.length-2]:void 0;if(p){i.delete(p);for(let f=o.length-1;f>=0;f--)um(o[f],p,u,n)&&o.splice(f,1);}}if("AlterTableStmt"in a.stmt){let l=a.stmt.AlterTableStmt,c=l.relation?.relname??"";for(let p of l.cmds??[]){if(!("AlterTableCmd"in p))continue;let u=p.AlterTableCmd.subtype;u==="AT_EnableRowSecurity"?i.add(c):u==="AT_DisableRowSecurity"&&i.delete(c);}}}return {policies:o,tables:i}}function gn(e,t=new Set){if(Array.isArray(e)){for(let s of e)gn(s,t);return t}if(!e||typeof e!="object")return t;let n=e,r=n.ColumnRef;if(r?.fields){let s=J(r.fields),i=s[s.length-1];i&&i!=="*"&&t.add(i);}for(let s of Object.values(n))gn(s,t);return t}function Ae(e,t,n){if(n.length===0)return;let r=t==="unique"?"key":t==="foreign_key"?"fkey":"check";return `${e}_${n.join("_")}_${r}`}function kr(e,t,n){let r=new Map;for(let s of e.stmts??[])if(s.stmt){if("CreateStmt"in s.stmt){let i=s.stmt.CreateStmt,o=i.relation?.relname??"",a=i.relation?.schemaname??"public";if(!o)continue;let l=`${a}.${o}`;if(i.if_not_exists&&r.has(l))continue;let c=new Wt(o,a);for(let u of i.tableElts??[]){if(!("ColumnDef"in u))continue;let f=u.ColumnDef,h=f.colname;if(!h)continue;let m=f.typeName?.names?.map(L=>L.String?.sval||L.String?.str).filter(Boolean),d=m&&m.length>0?m.length===2&&m[0]==="pg_catalog"?m[1]:m.join("."):void 0;if(!d)continue;let g=!!f.typeName?.arrayBounds?.length,y=Array.isArray(f.typeName?.typmods)?f.typeName.typmods:[],E=L=>y[L]?.A_Const?.ival?.ival??y[L]?.A_Const?.val?.ival?.ival,A={isArray:g};if(oi(d)&&y.length>0){let L=E(0);typeof L=="number"&&L>0&&(A.lengthConstraint=L);}if(ai(d)&&y.length>=2){let L=E(0),j=E(1);typeof L=="number"&&typeof j=="number"&&L>0&&j>=0&&(A.numericPrecision={precision:L,scale:j});}let C=Be(t,d);C&&(A.enumValues=C);let $=Array.isArray(f.constraints)?f.constraints:[],R=$.some(L=>L.Constraint?.contype==="CONSTR_PRIMARY"),T=$.find(L=>L.Constraint?.contype==="CONSTR_DEFAULT"),x=ii(d)||n?.has(f)===true||$.some(L=>L.Constraint?.contype==="CONSTR_IDENTITY")||J(T?.Constraint?.raw_expr?.FuncCall?.funcname??[]).join(".")==="nextval",O=$.some(L=>L.Constraint?.contype==="CONSTR_NOTNULL"),w=$.find(L=>L.Constraint?.contype==="CONSTR_UNIQUE"),D=$.find(L=>L.Constraint?.contype==="CONSTR_GENERATED"),q=$.find(L=>L.Constraint?.contype==="CONSTR_FOREIGN"),U=$.find(L=>L.Constraint?.contype==="CONSTR_CHECK"),S;if(q){let L=q.Constraint,j=L.pktable?.relname,I=L.pktable?.schemaname,te=L.pk_attrs?.[0]?.String?.sval;j&&te&&(S={refSchema:I,refTable:j,refColumn:te,constraintName:L.conname||Ae(o,"foreign_key",[h])});}let _={schema:a,table:o,column:h,pgTypeName:d,nullable:!O&&!R,defaultValue:null,defaultFn:null,isPrimaryKey:R,isUnique:!!w,isSerial:x,isGenerated:!!D,fkRef:S,hasCheck:!!U,checkConstraintName:U?U.Constraint?.conname||Ae(o,"check",[h]):void 0,uniqueConstraintName:w?w.Constraint?.conname||Ae(o,"unique",[h]):void 0};c.set(h,Ie(_,A));}let p=(u,f)=>{let h=c.get(u);if(!h)return;let m={...h.context,...f},d=Be(t,m.pgTypeName);c.set(u,Ie(m,{...h.factoryExtra,...d?{enumValues:d}:{}}));};for(let u of i.tableElts??[]){if(!("Constraint"in u))continue;let f=u.Constraint,h=J(f.keys??[]);if(f.contype==="CONSTR_PRIMARY")for(let m of h)p(m,{isPrimaryKey:true,nullable:false});else if(f.contype==="CONSTR_UNIQUE"&&h.length===1)p(h[0],{isUnique:true,uniqueConstraintName:f.conname||Ae(o,"unique",h)});else if(f.contype==="CONSTR_FOREIGN"&&h.length===1){let m=f.pktable?.relname,d=J(f.pk_attrs??[])[0];m&&d&&p(h[0],{fkRef:{refSchema:f.pktable?.schemaname,refTable:m,refColumn:d,constraintName:f.conname||Ae(o,"foreign_key",h)}});}else if(f.contype==="CONSTR_CHECK"){let m=[...gn(f.raw_expr)];m.length===1&&p(m[0],{hasCheck:true,checkConstraintName:f.conname||Ae(o,"check",m)});}}r.set(l,c);continue}if("RenameStmt"in s.stmt){let i=s.stmt.RenameStmt,o=i.relation?.schemaname??"public",a=i.relation?.relname??"",l=r.get(`${o}.${a}`);if(!l)continue;let c=i.renameType==="OBJECT_TABLE"?i.newname:void 0,p=i.renameType==="OBJECT_COLUMN"?i.newname:void 0,u=i.renameType==="OBJECT_COLUMN"?i.subname:void 0;if(!c&&!(p&&u))continue;let f=c??a,h=new Wt(f,o);for(let m of l.all()){let d=m.context.column===u?p:m.context.column,g={...m.context,table:f,column:d},y=Be(t,g.pgTypeName);h.set(d,Ie(g,{...m.factoryExtra,...y?{enumValues:y}:{}}));}r.delete(`${o}.${a}`),r.set(`${o}.${f}`,h);for(let m of r.values())for(let d of m.all()){let g=d.context.fkRef;if(!g||(g.refSchema??"public")!==o||g.refTable!==a)continue;let y=u&&g.refColumn===u?p:g.refColumn,E={...d.context,fkRef:{...g,refTable:f,refColumn:y}},A=Be(t,E.pgTypeName);m.set(E.column,Ie(E,{...d.factoryExtra,...A?{enumValues:A}:{}}));}continue}if("AlterTableStmt"in s.stmt){let i=s.stmt.AlterTableStmt,o=i.relation?.relname??"",a=i.relation?.schemaname??"public",l=`${a}.${o}`,c=r.get(l);if(!c)continue;let p=(u,f,h)=>{let m=c.get(u);if(!m)return;let d={...m.context,...f},g=Be(t,d.pgTypeName);c.set(u,Ie(d,{...h??m.factoryExtra,...g?{enumValues:g}:{}}));};for(let u of i.cmds??[]){if(!("AlterTableCmd"in u))continue;let f=u.AlterTableCmd;if(f.subtype==="AT_AddColumn"&&f.def&&"ColumnDef"in f.def){let h=kr({stmts:[{stmt:{CreateStmt:{relation:i.relation,tableElts:[f.def]}}}]},t,n).get(l)?.all()[0];h&&c.set(h.context.column,h);continue}if(f.subtype==="AT_AlterColumnType"&&f.name&&f.def&&"ColumnDef"in f.def){let h=kr({stmts:[{stmt:{CreateStmt:{relation:i.relation,tableElts:[{ColumnDef:{...f.def.ColumnDef,colname:f.name}}]}}}]},t,n).get(l)?.get(f.name);h&&p(f.name,{pgTypeName:h.context.pgTypeName,isSerial:h.context.isSerial},h.factoryExtra);continue}if(f.subtype==="AT_SetNotNull"&&f.name){p(f.name,{nullable:false});continue}if(f.subtype==="AT_DropNotNull"&&f.name){let h=c.get(f.name);p(f.name,{nullable:!h?.context.isPrimaryKey});continue}if(f.subtype==="AT_AddConstraint"&&f.def&&"Constraint"in f.def){let h=f.def.Constraint,m=J(h.keys??h.fk_attrs??[]);if(h.contype==="CONSTR_PRIMARY")for(let d of m)p(d,{isPrimaryKey:true,nullable:false});else if(h.contype==="CONSTR_UNIQUE"&&m.length===1)p(m[0],{isUnique:true,uniqueConstraintName:h.conname||Ae(o,"unique",m)});else if(h.contype==="CONSTR_FOREIGN"&&m.length===1){let d=h.pktable?.relname,g=J(h.pk_attrs??[])[0];d&&g&&p(m[0],{fkRef:{refSchema:h.pktable?.schemaname,refTable:d,refColumn:g,constraintName:h.conname||Ae(o,"foreign_key",m)}});}else if(h.contype==="CONSTR_CHECK"){let d=[...gn(h.raw_expr)];d.length===1&&p(d[0],{hasCheck:true,checkConstraintName:h.conname||Ae(o,"check",d)});}continue}if(f.subtype==="AT_DropConstraint"&&f.name){for(let h of c.all()){let m=h.context;m.uniqueConstraintName===f.name&&p(m.column,{isUnique:false,uniqueConstraintName:void 0}),m.checkConstraintName===f.name&&p(m.column,{hasCheck:false,checkConstraintName:void 0}),m.fkRef?.constraintName===f.name&&p(m.column,{fkRef:void 0});}continue}if(f.subtype==="AT_DropColumn"&&f.name){let h=new Wt(o,a);for(let m of c.all())m.context.column!==f.name&&h.set(m.context.column,m);c=h,r.set(l,h);for(let m of r.values())for(let d of m.all()){let g=d.context.fkRef;if((g?.refSchema??"public")===a&&g?.refTable===o&&g.refColumn===f.name){let y={...d.context,fkRef:void 0};m.set(y.column,Ie(y,d.factoryExtra));}}}}continue}if("DropStmt"in s.stmt&&s.stmt.DropStmt.removeType==="OBJECT_TABLE")for(let i of s.stmt.DropStmt.objects??[]){if(!("List"in i))continue;let o=J(i.List.items??[]),a=o[o.length-1],l=o.length>=2?o[o.length-2]:"public";if(a){r.delete(`${l}.${a}`);for(let c of r.values())for(let p of c.all()){let u=p.context.fkRef;if((u?.refSchema??"public")===l&&u?.refTable===a){let f={...p.context,fkRef:void 0};c.set(f.column,Ie(f,p.factoryExtra));}}}}}return r}function bl(e){let t=[],n=new Set,r=(s,i,o)=>{let a=s.contype,l=J(s.keys??s.fk_attrs??[]);if(a==="CONSTR_UNIQUE"&&l.length>0)t.push({schema:i,table:o,kind:"unique",name:s.conname||Ae(o,"unique",l),columns:l});else if(a==="CONSTR_CHECK"){let c=[...gn(s.raw_expr)];t.push({schema:i,table:o,kind:"check",name:s.conname||Ae(o,"check",c),columns:c});}else if(a==="CONSTR_FOREIGN"){let c=s.pktable?.relname;if(!c)return;t.push({schema:i,table:o,kind:"foreign_key",name:s.conname||Ae(o,"foreign_key",l),columns:l,refSchema:s.pktable?.schemaname,refTable:c,refColumns:J(s.pk_attrs??[])});}};for(let s of e.stmts??[]){if(!s.stmt)continue;if("RenameStmt"in s.stmt){let c=s.stmt.RenameStmt,p=c.relation?.schemaname??"public",u=c.relation?.relname;if(!u||!c.newname)continue;if(c.renameType==="OBJECT_TABLE"){n.delete(`${p}.${u}`),n.add(`${p}.${c.newname}`);for(let f of t)f.schema===p&&f.table===u&&(f.table=c.newname),(f.refSchema??"public")===p&&f.refTable===u&&(f.refTable=c.newname);}else if(c.renameType==="OBJECT_COLUMN"&&c.subname)for(let f of t)f.schema===p&&f.table===u&&(f.columns=f.columns.map(h=>h===c.subname?c.newname:h)),(f.refSchema??"public")===p&&f.refTable===u&&(f.refColumns=f.refColumns?.map(h=>h===c.subname?c.newname:h));continue}if("AlterTableStmt"in s.stmt){let c=s.stmt.AlterTableStmt,p=c.relation?.schemaname??"public",u=c.relation?.relname??"";for(let f of c.cmds??[]){if(!("AlterTableCmd"in f))continue;let h=f.AlterTableCmd;if(h.subtype==="AT_AddConstraint"&&h.def&&"Constraint"in h.def)r(h.def.Constraint,p,u);else if(h.subtype==="AT_DropConstraint"&&h.name)for(let m=t.length-1;m>=0;m--){let d=t[m];d.schema===p&&d.table===u&&d.name===h.name&&t.splice(m,1);}else if(h.subtype==="AT_DropColumn"&&h.name)for(let m=t.length-1;m>=0;m--){let d=t[m];(d.schema===p&&d.table===u&&d.columns.includes(h.name)||(d.refSchema??"public")===p&&d.refTable===u&&d.refColumns?.includes(h.name))&&t.splice(m,1);}}continue}if("DropStmt"in s.stmt&&s.stmt.DropStmt.removeType==="OBJECT_TABLE"){for(let c of s.stmt.DropStmt.objects??[]){if(!("List"in c))continue;let p=J(c.List.items??[]),u=p[p.length-1],f=p.length>=2?p[p.length-2]:"public";u&&n.delete(`${f}.${u}`);for(let h=t.length-1;h>=0;h--){let m=t[h];(m.schema===f&&m.table===u||(m.refSchema??"public")===f&&m.refTable===u)&&t.splice(h,1);}}continue}if(!("CreateStmt"in s.stmt))continue;let i=s.stmt.CreateStmt,o=i.relation?.relname??"",a=i.relation?.schemaname??"public";if(!o)continue;let l=`${a}.${o}`;if(!(i.if_not_exists&&n.has(l))){n.add(l);for(let c of i.tableElts??[]){if("ColumnDef"in c){let h=c.ColumnDef,m=h?.colname;if(!m)continue;for(let d of h.constraints??[]){let g=d?.Constraint;if(!g||g.contype!=="CONSTR_FOREIGN")continue;let y=g.pktable?.relname;if(!y)continue;let E=(g.pk_attrs??[]).map(A=>A.String?.sval??A.String?.str).filter(Boolean);t.push({schema:a,table:o,kind:"foreign_key",name:g.conname||Ae(o,"foreign_key",[m]),columns:[m],refSchema:g.pktable?.schemaname,refTable:y,refColumns:E});}continue}let p=c;if(!p.Constraint)continue;let u=p.Constraint,f=u.contype;if(f==="CONSTR_UNIQUE"){let h=(u.keys??[]).map(m=>m.String?.sval??m.String?.str).filter(Boolean);if(h.length===0)continue;t.push({schema:a,table:o,kind:"unique",name:u.conname||Ae(o,"unique",h),columns:h});}else if(f==="CONSTR_CHECK"){let h=[...gn(u.raw_expr)];t.push({schema:a,table:o,kind:"check",name:u.conname||Ae(o,"check",h),columns:h});}else if(f==="CONSTR_FOREIGN"){let h=(u.fk_attrs??[]).map(g=>g.String?.sval??g.String?.str).filter(Boolean),m=(u.pk_attrs??[]).map(g=>g.String?.sval??g.String?.str).filter(Boolean),d=u.pktable?.relname;if(!d)continue;t.push({schema:a,table:o,kind:"foreign_key",name:u.conname||Ae(o,"foreign_key",h),columns:h,refSchema:u.pktable?.schemaname,refTable:d,refColumns:m});}}}}return t}function wl(e){let t=new Map,n=r=>`${r.schema}.${r.table}.${r.column??""}`;for(let r of e.stmts??[]){if(!r.stmt)continue;if("RenameStmt"in r.stmt){let c=r.stmt.RenameStmt,p=c.relation?.schemaname??"public",u=c.relation?.relname;if(!u||!c.newname)continue;let f=new Map;for(let h of t.values()){if(h.schema!==p||h.table!==u){f.set(n(h),h);continue}let m={...h,table:c.renameType==="OBJECT_TABLE"?c.newname:h.table,column:c.renameType==="OBJECT_COLUMN"&&h.column===c.subname?c.newname:h.column};f.set(n(m),m);}t.clear();for(let[h,m]of f)t.set(h,m);continue}if("AlterTableStmt"in r.stmt){let c=r.stmt.AlterTableStmt,p=c.relation?.schemaname??"public",u=c.relation?.relname??"";for(let f of c.cmds??[])"AlterTableCmd"in f&&f.AlterTableCmd.subtype==="AT_DropColumn"&&f.AlterTableCmd.name&&t.delete(n({schema:p,table:u,column:f.AlterTableCmd.name}));continue}if("DropStmt"in r.stmt&&(r.stmt.DropStmt.removeType==="OBJECT_TABLE"||r.stmt.DropStmt.removeType==="OBJECT_VIEW")){for(let c of r.stmt.DropStmt.objects??[]){if(!("List"in c))continue;let p=J(c.List.items??[]),u=p[p.length-1],f=p.length>=2?p[p.length-2]:"public";for(let[h,m]of t)m.schema===f&&m.table===u&&t.delete(h);}continue}if(!("CommentStmt"in r.stmt))continue;let s=r.stmt.CommentStmt,i=s.objtype,o=(s.object?.List?.items??s.object?.items??[]).map(c=>c.String?.sval??c.String?.str).filter(Boolean);if(o.length===0)continue;let a;if(i==="OBJECT_TABLE"||i==="OBJECT_VIEW"){let[c,p]=o.length>=2?o:["public",o[0]];a={schema:c,table:p};}else if(i==="OBJECT_COLUMN"){let c="public",p,u;o.length>=3?[c,p,u]=o:[p,u]=o,a={schema:c,table:p,column:u};}if(!a)continue;let l=n(a);s.comment===null||s.comment===void 0?t.delete(l):t.set(l,{...a,text:String(s.comment)});}return [...t.values()]}var dl,hi=b(()=>{za();Bt();Xa();lm();hn();dl=new Set;});async function bn(e,t){let n=await e.connection.introspect(),r=at(n);await gm(e,{...t,dbHasTables:n.tables.length>0,dbFingerprint:r}),await UE(e);let s=await e.connection.introspect();bm(s,e);}async function FE(e){return mr(e.config.db?.seed?.sql_paths??["./seed.sql"],{cwd:Fe__default.join(process.cwd(),"supabase"),absolute:true})}async function ME(e){let t=await FE(e);return Promise.all(t.map(async n=>{let r=await he__default.readFile(n,"utf-8"),s=createHash("sha256").update(r).digest("hex");return {path:Fe__default.relative(process.cwd(),n),hash:s,statements:splitSqlStatements(r)}}))}async function Pr(e,t){if(e.config.db?.seed?.enabled===false)return 0;let r=(await ME(e)).filter(l=>l.statements.length>0);if(r.length===0)return 0;await ln(e.connection);let s=Ce(e.connection),i=new Map((await Gp(e.connection)).map(l=>[l.path,l.hash])),o=r.filter(l=>i.get(l.path)!==l.hash);if(o.length===0)return 0;console.log(M.default.dim("Seeding database..."));let a=[];for(let l of o){a.push(...l.statements);let c=qp(s,{path:l.path,hash:l.hash});c&&a.push(c);}try{await e.connection.transaction(a);}catch(l){let c=t?.recoveryHint??"Fix `supabase/seed.sql`, then re-run `lite dev` to reapply the schema and reseed.";throw new Error(`Seed failed and was rolled back: ${String(l.message??l)}
99
+ ${c}`)}return o.reduce((l,c)=>l+c.statements.length,0)}async function UE(e){await Pr(e);}async function be(e){let t=await mr(e.config?.db?.migrations?.schema_paths??dm,{cwd:Fe__default.join(process.cwd(),pe.config_dir),absolute:true}),n=await Promise.all(t.map(async r=>await he__default.readFile(r,"utf-8"))).then(r=>r.map(s=>s.split(`
92
100
  `).filter(i=>i.trim().length>0&&!i.trim().startsWith("--")).join(`
93
101
  `)).join(`
94
- `));return n||""}async function Mf(e,t){let n=await re(e);if(!(!n&&(await De(e)).length>0)&&!(!n&&!e.connection.config.baseSchema)){if(t?.dbHasTables&&await GS(e,n,t.dbFingerprint)){console.log(F.default.dim("Schema unchanged \u2014 skipping translation.")),await bt(e);return}try{let r=e.connection.createMigrator(n),s=await r.diff(),i=r.translationResult?.ast,o=await e.connection.introspect(),a=tl(o);if(s.plan.steps.length===0){await jf(e,n,i,a),await bt(e);return}await r.migratePlan(s.plan,{force:t?.force??!1}),KS(s);let l=await e.connection.introspect();return await jf(e,n,i,tl(l)),await bt(e),console.log(""),un(s),s}catch(r){if(String(r).includes("likely empty"))console.log(F.default.dim("Nothing to migrate."));else {console.error("Migration error: "+String(r));try{await e.connection.exec("rollback");}catch{}}}}}function HS(e){return e.connection.config?.baseSchema??""}function br(e,t){let n=createHash("sha256");return n.update(JSON.stringify([HS(e),t??""])),n.digest("hex")}function tl(e){let t=(r,s)=>[...r].sort((i,o)=>s(i).localeCompare(s(o))),n={tables:t(e.tables??[],r=>`${r.schema??""}.${r.name}`).map(r=>({schema:r.schema,name:r.name,type:r.type,sql:r.sql})),columns:t(e.columns??[],r=>`${r.schema??""}.${r.table}.${r.name}`).map(r=>({schema:r.schema,table:r.table,name:r.name,type:r.type,nullable:r.nullable,default_value:r.default_value,is_primary_key:r.is_primary_key})),indexes:t(e.indexes??[],r=>`${r.schema??""}.${r.table}.${r.name}`).map(r=>({schema:r.schema,table:r.table,name:r.name,unique:r.unique,columns:r.columns})),foreign_keys:t(e.foreign_keys??[],r=>`${r.schema??""}.${r.table}.${r.column}->${r.ref_table}.${r.ref_column}`).map(r=>({schema:r.schema,table:r.table,column:r.column,ref_schema:r.ref_schema,ref_table:r.ref_table,ref_column:r.ref_column})),primary_keys:t(e.primary_keys??[],r=>`${r.schema??""}.${r.table}`).map(r=>({schema:r.schema,table:r.table,columns:r.columns})),check_constraints:t(e.check_constraints??[],r=>`${r.schema??""}.${r.table}.${r.name??""}.${r.column??""}`).map(r=>({schema:r.schema,table:r.table,name:r.name,column:r.column,expression:r.expression})),unique_constraints:t(e.unique_constraints??[],r=>`${r.schema??""}.${r.table}.${r.name}`).map(r=>({schema:r.schema,table:r.table,name:r.name,columns:r.columns})),views:t(e.views??[],r=>`${r.schema??""}.${r.name}`).map(r=>({schema:r.schema,name:r.name,sql:r.sql})),triggers:t(e.triggers??[],r=>`${r.schema??""}.${r.table}.${r.name}`).map(r=>({schema:r.schema,table:r.table,name:r.name,sql:r.sql})),custom_types:t(e.custom_types??[],r=>`${r.schema??""}.${r.type}`).map(r=>({schema:r.schema,type:r.type,kind:r.kind,values:r.values,fields:r.fields}))};return createHash("sha256").update(JSON.stringify(n)).digest("hex")}async function GS(e,t,n){let r=e.connection;if(typeof r.updateDeparseInfo!="function")return false;let s=Ie__default.join(process.cwd(),rl),i;try{i=await de__default.readFile(s,"utf-8");}catch{return false}let o;try{o=JSON.parse(i);}catch{return false}if(o.v!==Uf||o.hash!==br(e,t)||!n||o.dbFingerprint!==n||!o.ast||typeof o.ast!="object")return false;try{let a=await Promise.resolve().then(()=>(Vs(),el)),l=o.ast,c=a.collectEnums(l),p=a.collectSchema(l,c),u=a.collectVariables(l),f=a.collectTableConstraints(l),h=a.collectComments(l),d=r.config?.translation?.schemas?.defaultSchema,{policies:m,tables:g}=a.collectPolicies(l,{defaultSchema:d});return r.updateDeparseInfo({enums:c,rls:{tables:g,policies:m},schema:p,vars:u,tableConstraints:f,comments:h}),!0}catch{return false}}async function jf(e,t,n,r){if(!n||typeof n!="object")return;let s={v:Uf,hash:br(e,t),dbFingerprint:r,ast:n},i=Ie__default.join(process.cwd(),rl);try{await de__default.mkdir(Ie__default.dirname(i),{recursive:!0}),await de__default.writeFile(i,JSON.stringify(s),"utf-8");}catch{}}async function Bf(){let e=Ie__default.join(process.cwd(),rl);try{await de__default.unlink(e);}catch{}}function qf(e,t){console.log();let n=(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}`);};n(F.default.green("DATA"),{tables:e.tables.length,columns:e.columns.length,indexes:e.indexes.length});let r=t.config.rls??t.connection.config.translation?.deparse?.rls??{tables:new Set([]),policies:[]};n(F.default.green("AUTH"),{enabled:!!t.config.auth?.enabled,tables:ensureVar.Set(r.tables).size,policies:ensureVar.Array(r.policies).length});}function WS(e){let t=Ie__default.join(process.cwd(),ue.config_dir),r=(e.config?.db?.migrations?.schema_paths??Ff).map(s=>{let i=s.split("/"),o=i.findIndex(l=>/[*?[{]/.test(l)),a=(o===-1?i.slice(0,-1):i.slice(0,o)).join("/");return Ie__default.resolve(t,a||".")});return [...new Set(r)]}function Hf(e,t){let n,r=setTimeout(()=>{console.log(F.default.dim("Watching for changes...")),n=US.watch(WS(e),{ignoreInitial:true});let s=async i=>{if(!i.endsWith(".sql"))return;console.log(),console.log(F.default.dim(`Schema changed: ${i}`)),await Mf(e,t);let o=await e.connection.introspect();qf(o,e);};n.on("change",s),n.on("add",s);},200);return async()=>{clearTimeout(r),await n?.close();}}function sl(e,t){let n=t?.colorize?F.default.dim:r=>r;return e.plan.steps.flatMap(r=>[r.description?n(`-- ${r.description}`):"",r.sql+`
102
+ `));return n||""}async function gm(e,t){let n=await be(e);if(!n){if(!await un(e))throw new Error("Applied migration metadata could not be rebuilt. Run `lite db reset`.");return}if(t?.dbHasTables&&await qE(e,n,t.dbFingerprint)){console.log(M.default.dim("Schema unchanged \u2014 skipping translation.")),await ir(e,{workflow:"declarative",sourceHash:Nr(e,n)});return}try{let r=e.connection.createMigrator(n),s=await r.diff(),i=r.translationResult?.ast,o=await e.connection.introspect(),a=at(o);if(s.plan.steps.length===0){await fm(e,n,i,a),await ir(e,{workflow:"declarative",sourceHash:Nr(e,n)});return}await r.migratePlan(s.plan,{force:t?.force??!1}),WE(s);let l=await e.connection.introspect();return await fm(e,n,i,at(l)),await ir(e,{workflow:"declarative",sourceHash:Nr(e,n)}),console.log(""),wn(s),s}catch(r){if(String(r).includes("likely empty"))console.log(M.default.dim("Nothing to migrate."));else {console.error("Migration error: "+String(r));try{await e.connection.exec("rollback");}catch{}}}}function BE(e){return e.connection.config?.baseSchema??""}function Nr(e,t){let n=createHash("sha256");return n.update(JSON.stringify([BE(e),t??""])),n.digest("hex")}async function qE(e,t,n){let r=e.connection;if(typeof r.updateDeparseInfo!="function")return false;let s=Fe__default.join(process.cwd(),El),i;try{i=await he__default.readFile(s,"utf-8");}catch{return false}let o;try{o=JSON.parse(i);}catch{return false}if(o.v!==hm||o.hash!==Nr(e,t)||!n||o.dbFingerprint!==n||!o.ast||typeof o.ast!="object")return false;try{let a=await Promise.resolve().then(()=>(hi(),Sl)),l=o.ast,c=a.collectEnums(l),p=a.collectSchema(l,c),u=a.collectVariables(l),f=a.collectTableConstraints(l),h=a.collectComments(l),m=r.config?.translation?.schemas?.defaultSchema,{policies:d,tables:g}=a.collectPolicies(l,{defaultSchema:m});return r.updateDeparseInfo({enums:c,rls:{tables:g,policies:d},schema:p,vars:u,tableConstraints:f,comments:h}),!0}catch{return false}}async function fm(e,t,n,r){if(!n||typeof n!="object")return;let s={v:hm,hash:Nr(e,t),dbFingerprint:r,ast:n},i=Fe__default.join(process.cwd(),El);try{await he__default.mkdir(Fe__default.dirname(i),{recursive:!0}),await he__default.writeFile(i,JSON.stringify(s),"utf-8");}catch{}}async function ym(){let e=Fe__default.join(process.cwd(),El);try{await he__default.unlink(e);}catch{}}function bm(e,t){console.log();let n=(s,i)=>{let o=l=>{let c=M.default.dim;return typeof l=="number"&&(l>=0&&(c=l>0?M.default.green:M.default.dim),l<0&&(c=M.default.red)),typeof l=="boolean"?l?M.default.green("\u2713"):M.default.red("\u2717"):c(String(l))},a=Object.entries(i).map(([l,c])=>`${l}: ${o(c)}`).join(M.default.dim(" / "));console.log(`${M.default.dim("[")} ${s} ${M.default.dim("]")} ${a}`);};n(M.default.green("DATA"),{tables:e.tables.length,columns:e.columns.length,indexes:e.indexes.length});let r=t.config.rls??t.connection.config.translation?.deparse?.rls??{tables:new Set([]),policies:[]};n(M.default.green("AUTH"),{enabled:!!t.config.auth?.enabled,tables:ensureVar.Set(r.tables).size,policies:ensureVar.Array(r.policies).length});}function HE(e){let t=Fe__default.join(process.cwd(),pe.config_dir),r=(e.config?.db?.migrations?.schema_paths??dm).map(s=>{let i=s.split("/"),o=i.findIndex(l=>/[*?[{]/.test(l)),a=(o===-1?i.slice(0,-1):i.slice(0,o)).join("/");return Fe__default.resolve(t,a||".")});return [...new Set(r)]}function wm(e,t){let n,r=setTimeout(()=>{console.log(M.default.dim("Watching for changes...")),n=jE.watch(HE(e),{ignoreInitial:true});let s=async i=>{if(!i.endsWith(".sql"))return;console.log(),console.log(M.default.dim(`Schema changed: ${i}`)),await gm(e,t);let o=await e.connection.introspect();bm(o,e);};n.on("change",s),n.on("add",s);},200);return async()=>{clearTimeout(r),await n?.close();}}function _l(e,t){let n=t?.colorize?M.default.dim:r=>r;return e.plan.steps.flatMap(r=>[r.description?n(`-- ${r.description}`):"",r.sql+`
95
103
  `]).filter(r=>r.trim().length>0).join(`
96
- `)}function VS(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 KS(e,t){let n="./supabase/.temp/migrations";Ce(n);let r=VS(),s=sl(e);xt(Ie__default.join(n,r),s),console.log(F.default.dim(`Migration written to ${F.default.cyan(Ie__default.join(n,r))}`));}function Gf(e){let t=e.schema_separator??".",n=e.ddl_dialect==="postgres",r=(a,l)=>n&&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=n?"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=r(a.schema,a.name),c=e.columns.filter(u=>u.table===a.name&&(!n||u.schema===a.schema)).sort((u,f)=>u.ordinal_position-f.ordinal_position),p=a.rows>=0?` ${F.default.dim(`(${a.rows} rows)`)}`:"";console.log(`${F.default.bold(l)}${p}`);for(let u of c){let f=[];u.is_primary_key&&f.push(F.default.green("PK")),u.nullable||f.push(F.default.dim("NOT NULL")),u.default_value!==null&&f.push(F.default.dim(`DEFAULT ${u.default_value}`));let h=f.length?" "+f.join(" "):"";console.log(` ${u.name} ${F.default.cyan(u.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 ${r(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=`${r(a.schema,a.table)}.${a.column}`,c=`${r(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(` ${r(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 ${r(a.schema,a.table)}`);console.log();}}function un({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 n of e.tables){let{color:r,symbol:s}=t[n.type];console.log(r(`${s} ${n.name}`));}console.log();}if(e.columns.length>0){console.log(F.default.dim("Columns:"));for(let n of e.columns){let{color:r,symbol:s}=t[n.type],i="";n.changes&&(i=Object.entries(n.changes).map(([o,a])=>`${o}: ${a.from} \u2192 ${a.to}`).join(", ")),console.log(r(`${s} ${n.table}.${n.name}${i?` (${i})`:""}`));}console.log();}if(e.indexes.length>0){console.log(F.default.dim("Indexes:"));for(let n of e.indexes){let{color:r,symbol:s}=t[n.type];console.log(r(`${s} ${n.name} on ${n.table}`));}console.log();}if(e.foreign_keys.length>0){console.log(F.default.dim("Foreign Keys:"));for(let n of e.foreign_keys){let{color:r,symbol:s}=t[n.type];console.log(r(`${s} ${n.table}.${n.column} \u2192 ${n.ref_table}.${n.ref_column}`));}console.log();}}var F,Ff,rl,Uf,Ue=b(()=>{Ta();F=V(z());Tt();dt();wr();mt();$t();Ff=["./schemas/*.sql"],rl="supabase/.temp/.translation-cache.json",Uf=3;});async function zS(e){try{return await Wn(e.connection)}catch{return []}}function zf(e){return _e(e.connection)==="pg-flat"}function al(){return Ie__default.join(process.cwd(),XS)}async function Xf(e){let t=[];try{t=await Wn(e.connection);}catch(n){if(!String(n).includes("no such table"))throw n}return vp(t)}async function bt(e){if(zf(e))try{let t=e.connection,n=SqliteConnection.serializeDeparseInfo(t.config?.translation?.deparse),[r,s]=await Promise.all([Xf(e),br(e,await re(e))]),i={v:Kf,fingerprint:r,schemaHash:s,deparse:n},o=al();await de__default.mkdir(Ie__default.dirname(o),{recursive:!0}),await de__default.writeFile(o,JSON.stringify(i),"utf-8");}catch{}}async function YS(e,t){let n;try{n=ua(await Wn(e.connection));}catch{return true}if(n.size===0)return true;let r=new Set(t.rls?.tables??[]);for(let s of n)if(!r.has(s))return false;return true}async function JS(e){let t=e.connection;if(typeof t.updateDeparseInfo!="function")return false;let n;try{n=await de__default.readFile(al(),"utf-8");}catch{return false}let r;try{r=JSON.parse(n);}catch{return false}if(r.v!==Kf)return false;let[s,i]=await Promise.all([Xf(e),br(e,await re(e))]);if(r.fingerprint!==s||r.schemaHash!==i||!sE(r.deparse)||!await YS(e,r.deparse))return false;try{return t.updateDeparseInfo(SqliteConnection.parseDeparseInfo(r.deparse,{strict:!0})),!0}catch{return false}}function eE(e){return !(!Je(e)||!ve(e.name)||!Bt(e.table)||!Re(e.schema,ve)||!ve(e.command)||!QS.has(e.command)||typeof e.permissive!="boolean"||!zs(e.roles)||!Re(e.using,t=>typeof t=="object")||!Re(e.withCheck,t=>typeof t=="object"))}function tE(e){if(!Je(e))return false;let t=e.context;return !(!Je(t)||!ve(t.schema)||!Bt(t.table)||!Bt(t.column)||!Bt(t.pgTypeName)||typeof t.nullable!="boolean"||typeof t.isPrimaryKey!="boolean"||typeof t.isUnique!="boolean"||typeof t.isSerial!="boolean"||!(t.defaultValue===null||ve(t.defaultValue))||!Re(e.extra,Je))}function nE(e){return !(!Je(e)||!ve(e.schema)||!Bt(e.table)||!ve(e.kind)||!ZS.has(e.kind)||!zs(e.columns)||!Re(e.name,ve)||!Re(e.refSchema,ve)||!Re(e.refTable,ve)||!Re(e.refColumns,zs))}function rE(e){return !(!Je(e)||!ve(e.schema)||!Bt(e.table)||!ve(e.text)||!Re(e.column,ve))}function sE(e){if(!Je(e))return false;let t=e.rls;return !(!Je(t)||!Array.isArray(t.tables)||!t.tables.every(Bt)||!Array.isArray(t.policies)||!t.policies.every(eE)||!Re(e.vars,n=>il(n,Je))||!Re(e.enums,n=>il(n,zs))||!Re(e.schema,n=>il(n,r=>Array.isArray(r)&&r.every(tE)))||!Re(e.tableConstraints,n=>Array.isArray(n)&&n.every(nE))||!Re(e.comments,n=>Array.isArray(n)&&n.every(rE)))}async function iE(e){let t=e.connection;if(typeof t.translateDdl!="function"||typeof t.updateDeparseInfo!="function")return false;let n=[];try{n=await Wn(e.connection);}catch(a){if(!String(a).includes("no such table"))throw a}if(n.length===0)return false;let s=[...n].sort((a,l)=>a.version.localeCompare(l.version)).flatMap(a=>a.statements??[]).filter(a=>a.trim().length>0).join(`;
97
- `);if(!s.trim())return false;let i=await t.translateDdl(s),o=t.config?.translation?.deparse??{};return t.updateDeparseInfo({...o,...i}),await bt(e),true}async function Yf(e){if(!zf(e))return "skipped";if(await JS(e))return console.log(ol.default.dim("RLS metadata restored from supabase/.temp/.deparse-cache.json")),"restored";let t="";try{t=await re(e);}catch{t="";}if(t.trim())return "failed";let n=false;try{n=await iE(e),n&&console.log(ol.default.dim("RLS metadata recalculated from migrations."));}catch{n=false;}return n?"recalculated":ua(await zS(e)).size>0?"failed":"skipped"}async function Jf(e){let t="";try{t=await re(e);}catch{t="";}return t.trim()?["`lite start` runs the migrations workflow and never applies `supabase/schemas/*.sql`, so it cannot rebuild RLS metadata for a declarative project on its own.","Ship the declarative schema as a migration, then start again:"," lite db diff -f <name> # write the pending schema changes as a migration"," lite db reset # replay the migrations onto a fresh database","Or develop declaratively with `lite dev` (or the Vite plugin), which applies the schema and rewrites the cache `lite start` restores."]:["The applied migration history no longer explains this database's RLS state.","Reapply the migrations: `lite migration up`, or `lite db reset` to replay them onto a fresh database."]}async function Qf(){try{await de__default.unlink(al());}catch{}}var ol,XS,Kf,QS,ZS,Je,ve,Bt,zs,Re,il,wr=b(()=>{ol=V(z());mt();Rp();Ue();XS="supabase/.temp/.deparse-cache.json",Kf=2;QS=new Set(["SELECT","INSERT","UPDATE","DELETE","ALL"]),ZS=new Set(["unique","check","foreign_key"]),Je=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ve=e=>typeof e=="string",Bt=e=>typeof e=="string"&&e.length>0,zs=e=>Array.isArray(e)&&e.every(ve),Re=(e,t)=>e==null||t(e),il=(e,t)=>Je(e)&&Object.values(e).every(t);});var Zf={};fe(Zf,{start:()=>oE});var qt,oE,em=b(()=>{Jo();ct();qt=V(z());$t();Te();Ee();Kt();ra();sa();ia();wr();oE=e=>{e.command("start").option("--config <config>","Path to the config file").option("--no-admin","Disable local admin mode (keyless requests are no longer elevated; normal authentication rules apply)").description("Start the development server").helpGroup("Local Development:").action(async(t,n)=>{await ee(t.config),await is(async()=>{let s=await(await W({withSupabaseClient:false})).project.local.createApp(t.config,{...Ps(t,n)});if(await Yf(s)==="failed"){console.error(qt.default.red("RLS metadata could not be loaded or recalculated for this project."));for(let c of await Jf(s))console.error(qt.default.dim(c));process.exit(1);}let o=s.config.api?.port??ue.default_api_port,a=await bs(s,{port:o});console.log(qt.default.green(" \u279C"),"Server running on ",qt.default.cyan(`http://localhost:${o}`)),ks(s.config),Ns(s.adminMode);let l=Br();l&&console.log(qt.default.yellow(` \u26A0 ${l}`)),await s.connection.ping(),Rs(async()=>{await a(),await s.connection.close();});},r=>{console.log(),console.log(qt.default.green(`Ready in ${r.toFixed(2)}ms`));});});};});function aE(e){return e==="service_role"?"NOLOGIN BYPASSRLS":"NOLOGIN"}function wt(e){return e.size===0?"":`DO $$ BEGIN${[...e].map(n=>`
104
+ `)}function GE(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 WE(e,t){let n="./supabase/.temp/migrations";ve(n);let r=GE(),s=_l(e);kt(Fe__default.join(n,r),s),console.log(M.default.dim(`Migration written to ${M.default.cyan(Fe__default.join(n,r))}`));}function Sm(e){let t=e.schema_separator??".",n=e.ddl_dialect==="postgres",r=(a,l)=>n&&a?`${a}${t}${l}`:l;console.log(M.default.bgWhite(M.default.black(" Schema "))),console.log();let s=e.tables.filter(a=>a.type==="table"),i=n?"sqlite-postgres":"sqlite";if(console.log(M.default.dim(`${i}${e.version?` (sqlite ${e.version})`:""} \xB7 ${e.database_name}`)),console.log(),s.length===0){console.log(M.default.dim("No tables."));return}console.log(M.default.dim("Tables:"));for(let a of s){let l=r(a.schema,a.name),c=e.columns.filter(u=>u.table===a.name&&(!n||u.schema===a.schema)).sort((u,f)=>u.ordinal_position-f.ordinal_position),p=a.rows>=0?` ${M.default.dim(`(${a.rows} rows)`)}`:"";console.log(`${M.default.bold(l)}${p}`);for(let u of c){let f=[];u.is_primary_key&&f.push(M.default.green("PK")),u.nullable||f.push(M.default.dim("NOT NULL")),u.default_value!==null&&f.push(M.default.dim(`DEFAULT ${u.default_value}`));let h=f.length?" "+f.join(" "):"";console.log(` ${u.name} ${M.default.cyan(u.type)}${h}`);}console.log();}let o=e.indexes.filter(a=>!a.name.startsWith("sqlite_autoindex_"));if(o.length>0){console.log(M.default.dim("Indexes:"));for(let a of o){let l=a.unique?M.default.yellow("UNIQUE "):"";console.log(` ${a.name} on ${r(a.schema,a.table)} ${l}(${a.columns.join(", ")})`);}console.log();}if(e.foreign_keys.length>0){console.log(M.default.dim("Foreign Keys:"));for(let a of e.foreign_keys){let l=`${r(a.schema,a.table)}.${a.column}`,c=`${r(a.ref_schema,a.ref_table)}.${a.ref_column}`;console.log(` ${l} \u2192 ${c} ${M.default.dim(`ON DELETE ${a.on_delete} ON UPDATE ${a.on_update}`)}`);}console.log();}if(e.views.length>0){console.log(M.default.dim("Views:"));for(let a of e.views)console.log(` ${r(a.schema,a.name)}`);console.log();}if(e.triggers.length>0){console.log(M.default.dim("Triggers:"));for(let a of e.triggers)console.log(` ${a.name} on ${r(a.schema,a.table)}`);console.log();}}function wn({diff:e}){if(typeof e=="string"){console.log(M.default.cyan(e));return}if(!e.has_changes)return;console.log(M.default.bgWhite(M.default.black(" Schema Diff "))),console.log();let t={added:{color:M.default.green,symbol:"+"},removed:{color:M.default.red,symbol:"-"},modified:{color:M.default.yellow,symbol:"~"}};if(e.tables.length>0){console.log(M.default.dim("Tables:"));for(let n of e.tables){let{color:r,symbol:s}=t[n.type];console.log(r(`${s} ${n.name}`));}console.log();}if(e.columns.length>0){console.log(M.default.dim("Columns:"));for(let n of e.columns){let{color:r,symbol:s}=t[n.type],i="";n.changes&&(i=Object.entries(n.changes).map(([o,a])=>`${o}: ${a.from} \u2192 ${a.to}`).join(", ")),console.log(r(`${s} ${n.table}.${n.name}${i?` (${i})`:""}`));}console.log();}if(e.indexes.length>0){console.log(M.default.dim("Indexes:"));for(let n of e.indexes){let{color:r,symbol:s}=t[n.type];console.log(r(`${s} ${n.name} on ${n.table}`));}console.log();}if(e.foreign_keys.length>0){console.log(M.default.dim("Foreign Keys:"));for(let n of e.foreign_keys){let{color:r,symbol:s}=t[n.type];console.log(r(`${s} ${n.table}.${n.column} \u2192 ${n.ref_table}.${n.ref_column}`));}console.log();}}var M,dm,El,hm,tt=b(()=>{Va();M=K(X());Nt();or();St();Lt();nr();nr();dm=["./schemas/*.sql"],El="supabase/.temp/.translation-cache.json",hm=3;});function _m(e){return Ce(e.connection)==="sqlite"?"./sqlite-migrations/*.sql":"./migrations/*.sql"}function Vt(e){return Fe__default.posix.dirname(_m(e))}async function nt(e){let t=Fe__default.join(process.cwd(),"supabase"),n=await mr([_m(e)],{cwd:t,absolute:true}),r=[];for(let s of n){let i=Fe__default.basename(s),o=VE.exec(i);if(!o)continue;let a=await he__default.readFile(s,"utf-8");r.push({version:o[1],name:o[2]??null,filename:i,path:s,sql:a});}return r.sort((s,i)=>s.version.localeCompare(i.version))}async function Lr(e){return (await nt(e)).map(n=>n.sql).join(`
105
+ `)}function xl(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 Tl(e,t=xl()){let n=e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"");return n.length>0?`${t}_${n}.sql`:`${t}.sql`}async function xm(e,t,n){let r=Fe__default.join(process.cwd(),"supabase",Vt(e));ve(r);let s=Tl(t,n?.ts),i=Fe__default.join(r,s);return await he__default.writeFile(i,"",{flag:"wx"}),i}var VE,Kt=b(()=>{Va();St();Nt();VE=/^(\d{14})(?:_([^.]+))?\.sql$/;});function KE(e){return e==="service_role"?"NOLOGIN BYPASSRLS":"NOLOGIN"}function At(e){return e.size===0?"":`DO $$ BEGIN${[...e].map(n=>`
98
106
  IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '${n}') THEN
99
- CREATE ROLE ${n} ${aE(n)};
107
+ CREATE ROLE ${n} ${KE(n)};
100
108
  END IF;`).join("")}
101
109
  END $$;
102
- `}function nm(e,t){return e?e.quoted?e.value===t:e.value.toLowerCase()===t:false}function We(e){return e?.quoted?e.value:e?.value.toLowerCase()}function lE(e,t){let n="",r=t+1;for(;r<e.length;){if(e[r]==='"'&&e[r+1]==='"'){n+='"',r+=2;continue}if(e[r]==='"')return {token:{value:n,quoted:true},end:r+1};n+=e[r],r++;}return {token:{value:n,quoted:true},end:r}}function cE(e,t){let n=t+1;for(;n<e.length;){if(e[n]==="'"&&e[n+1]==="'"){n+=2;continue}if(e[n]==="'")return n+1;n++;}return n}function uE(e,t){let n=/^\$[A-Za-z_][A-Za-z0-9_]*\$|^\$\$/.exec(e.slice(t))?.[0];if(!n)return;let r=t+n.length,s=e.indexOf(n,r);return s===-1?e.length:s+n.length}function rm(e){let t=[],n=0;for(;n<e.length;){let r=e[n],s=e[n+1];if(/\s/.test(r)){n++;continue}if(r==="-"&&s==="-"){for(n+=2;n<e.length&&e[n]!==`
103
- `;)n++;continue}if(r==="/"&&s==="*"){for(n+=2;n<e.length&&!(e[n]==="*"&&e[n+1]==="/");)n++;n=n<e.length?n+2:n;continue}if(r==="'"){n=cE(e,n);continue}if(r==="$"){let i=uE(e,n);if(i!==void 0){n=i;continue}}if(r==='"'){let{token:i,end:o}=lE(e,n);t.push(i),n=o;continue}if(r===","||r===";"){t.push({value:r,quoted:false}),n++;continue}if(/[A-Za-z_]/.test(r)){let i=n;for(n++;n<e.length&&/[A-Za-z0-9_$]/.test(e[n]);)n++;t.push({value:e.slice(i,n).toLowerCase(),quoted:false});continue}n++;}return t}function pE(e,t){let n=We(e[t]),r=We(e[t+1]);if((n==="create"||n==="alter")&&(r==="role"||r==="user"||r==="group"))return e[t+2]}function Ys(e){let t=new Set,n=rm(e);for(let r=0;r<n.length;r++){if(We(n[r])!=="create")continue;let s=pE(n,r);for(let i of pn)nm(s,i)&&t.add(i);}return t}function ll(e,t,n){let r=new Set([";","as","by","check","for","granted","in","on","option","using","where","with"]);for(let s=t;s<e.length;s++){let i=We(e[s]);if(!i||r.has(i))return;for(let o of pn)nm(e[s],o)&&n.add(o);}}function fE(e){let t=[],n=[];for(let r of e){if(We(r)===";"){n.length>0&&t.push(n),n=[];continue}n.push(r);}return n.length>0&&t.push(n),t}function tm(e,t){return e.some(n=>We(n)===t)}function mE(e){let t=new Set,n=fE(rm(e));for(let r of n){let s=We(r[0]);for(let a=0;a<r.length;a++){let l=We(r[a]);l==="to"&&(tm(r,"grant")||tm(r,"policy")||We(r[a-1])==="owner")&&ll(r,a+1,t),l==="from"&&s==="revoke"&&ll(r,a+1,t);}let i=r.findIndex(a=>We(a)==="to"),o=r.findIndex(a=>We(a)==="on");s==="grant"&&i>1&&(o===-1||i<o)&&ll(r,1,t);}return t}function St(e){let t=Ys(e);return new Set([...mE(e)].filter(n=>!t.has(n)))}function sm(e){let t=Ys(e);return new Set(pn.filter(n=>!t.has(n)))}var pn,Xs,Sr=b(()=>{pn=["anon","authenticated","service_role"];wt(new Set(pn)),Xs=`
110
+ `}function Cm(e,t){return e?e.quoted?e.value===t:e.value.toLowerCase()===t:false}function ze(e){return e?.quoted?e.value:e?.value.toLowerCase()}function zE(e,t){let n="",r=t+1;for(;r<e.length;){if(e[r]==='"'&&e[r+1]==='"'){n+='"',r+=2;continue}if(e[r]==='"')return {token:{value:n,quoted:true},end:r+1};n+=e[r],r++;}return {token:{value:n,quoted:true},end:r}}function XE(e,t){let n=t+1;for(;n<e.length;){if(e[n]==="'"&&e[n+1]==="'"){n+=2;continue}if(e[n]==="'")return n+1;n++;}return n}function JE(e,t){let n=/^\$[A-Za-z_][A-Za-z0-9_]*\$|^\$\$/.exec(e.slice(t))?.[0];if(!n)return;let r=t+n.length,s=e.indexOf(n,r);return s===-1?e.length:s+n.length}function Am(e){let t=[],n=0;for(;n<e.length;){let r=e[n],s=e[n+1];if(/\s/.test(r)){n++;continue}if(r==="-"&&s==="-"){for(n+=2;n<e.length&&e[n]!==`
111
+ `;)n++;continue}if(r==="/"&&s==="*"){for(n+=2;n<e.length&&!(e[n]==="*"&&e[n+1]==="/");)n++;n=n<e.length?n+2:n;continue}if(r==="'"){n=XE(e,n);continue}if(r==="$"){let i=JE(e,n);if(i!==void 0){n=i;continue}}if(r==='"'){let{token:i,end:o}=zE(e,n);t.push(i),n=o;continue}if(r===","||r===";"){t.push({value:r,quoted:false}),n++;continue}if(/[A-Za-z_]/.test(r)){let i=n;for(n++;n<e.length&&/[A-Za-z0-9_$]/.test(e[n]);)n++;t.push({value:e.slice(i,n).toLowerCase(),quoted:false});continue}n++;}return t}function YE(e,t){let n=ze(e[t]),r=ze(e[t+1]);if((n==="create"||n==="alter")&&(r==="role"||r==="user"||r==="group"))return e[t+2]}function yi(e){let t=new Set,n=Am(e);for(let r=0;r<n.length;r++){if(ze(n[r])!=="create")continue;let s=YE(n,r);for(let i of Sn)Cm(s,i)&&t.add(i);}return t}function Cl(e,t,n){let r=new Set([";","as","by","check","for","granted","in","on","option","using","where","with"]);for(let s=t;s<e.length;s++){let i=ze(e[s]);if(!i||r.has(i))return;for(let o of Sn)Cm(e[s],o)&&n.add(o);}}function QE(e){let t=[],n=[];for(let r of e){if(ze(r)===";"){n.length>0&&t.push(n),n=[];continue}n.push(r);}return n.length>0&&t.push(n),t}function Tm(e,t){return e.some(n=>ze(n)===t)}function ZE(e){let t=new Set,n=QE(Am(e));for(let r of n){let s=ze(r[0]);for(let a=0;a<r.length;a++){let l=ze(r[a]);l==="to"&&(Tm(r,"grant")||Tm(r,"policy")||ze(r[a-1])==="owner")&&Cl(r,a+1,t),l==="from"&&s==="revoke"&&Cl(r,a+1,t);}let i=r.findIndex(a=>ze(a)==="to"),o=r.findIndex(a=>ze(a)==="on");s==="grant"&&i>1&&(o===-1||i<o)&&Cl(r,1,t);}return t}function $t(e){let t=yi(e);return new Set([...ZE(e)].filter(n=>!t.has(n)))}function $m(e){let t=yi(e);return new Set(Sn.filter(n=>!t.has(n)))}var Sn,gi,Ir=b(()=>{Sn=["anon","authenticated","service_role"];At(new Set(Sn)),gi=`
104
112
  CREATE SCHEMA IF NOT EXISTS auth;
105
113
 
106
114
  CREATE OR REPLACE FUNCTION auth.uid() RETURNS UUID AS $$
@@ -121,101 +129,96 @@ CREATE OR REPLACE FUNCTION auth.jwt() RETURNS JSONB AS $$
121
129
  '{}'
122
130
  )::jsonb;
123
131
  $$ LANGUAGE SQL STABLE;
124
- `;});async function Ht(e,t={}){await e.ensureSystemSchema();let n=new Set(await Gn(e.connection)),r=await De(e),s=_e(e.connection),i=[],o=[];for(let l of r){if(n.has(l.version)){o.push(l);continue}let c=Rt(l.sql),p;if(s==="pg-flat"){let f=await e.connection.translateDdl(l.sql),h=typeof f=="string"?f:f.ddl??"";p=Rt(h);}else p=c;let u=Tp(s,{version:l.version,name:l.name,statements:c});if(s==="pg"){let f=wt(St(l.sql));f&&await e.connection.exec(f);}await e.connection.transaction([...p,u],{intent:"migration"}),i.push(l);}let a=true;return s==="pg-flat"&&!t.persistWithDeclarative&&(await re(e)).trim()&&(a=false),s!=="sqlite"&&(r.length>0?await dE(e,r,{persist:a}):s==="pg-flat"&&a&&await bt(e)),{applied:i,skipped:o}}async function dE(e,t,n){let r=t.map(a=>a.sql).join(`
125
- `);if(!r.trim())return;let s=e.connection;if(typeof s.translateDdl!="function"||typeof s.updateDeparseInfo!="function")return;let i=await s.translateDdl(r),o=s.config?.translation?.deparse??{};s.updateDeparseInfo({...o,...i}),n?.persist!==false&&await bt(e);}var Js=b(()=>{kt();mt();dt();Sr();wr();Ue();});var im={};fe(im,{dev:()=>yE});var ke,yE,om=b(()=>{ao();Jo();ct();ke=V(z());$t();Ue();Js();dt();Te();Ee();Kt();Ye();ra();sa();ia();yE=e=>{e.command("dev").option("--template","Create a template for the database",false).option("--config <config>","Path to the config file").option("--no-admin","Disable local admin mode (keyless requests are no longer elevated; normal authentication rules apply)").description(me("Start the development server with schema watching")).helpGroup("Local Development:").action(async(t,n)=>{t.config&&await ee(t.config),console.log(ke.default.yellow(" \u26A0 [lite] dev is experimental and works with declarative schema only.")),await is(async()=>{let{created:r}=await rs({template:t.template});r&&console.log(ke.default.green(" \u279C"),"Initialized project",ke.default.cyan(`./${ue.config_dir}`)),console.log();let i=await(await W({withSupabaseClient:false})).project.local.createApp(t.config,{...Ps(t,n)}),o=i.config.api?.port??ue.default_api_port;if((await De(i)).length>0){let d=await Ht(i);for(let m of d.applied)console.log(ke.default.green(" \u2713"),"Applied migration",ke.default.cyan(m.filename));}await gr(i,{force:true}),console.log();let l=await bs(i,{port:o});console.log(ke.default.green(" \u279C"),"Server running on ",ke.default.cyan(`http://localhost:${o}`)),ks(i.config),Ns(i.adminMode);let c=Br();c&&console.log(ke.default.yellow(` \u26A0 ${c}`)),await i.connection.ping();let p=Hf(i,{translate:true,force:true}),u=Ie__default.join(process.cwd(),"supabase",It(i)),f,h=setTimeout(()=>{f=US.watch(u,{ignoreInitial:true}),f.on("add",async d=>{console.log(),console.log(ke.default.dim(`Migration added: ${d}`));try{let m=await Ht(i);for(let g of m.applied)console.log(ke.default.green(" \u2713"),"Applied",ke.default.cyan(g.filename));}catch(m){console.error(ke.default.red("Migration failed: "+String(m.message??m)));}});},200);Rs(async()=>{clearTimeout(h),await Promise.all([p(),f?.close()]),await l(),await i.connection.close();});},r=>{console.log(),console.log(ke.default.green(`Ready in ${r.toFixed(2)}ms`));});});};});async function st(e){let t=e===true,n=await W({withSupabaseClient:t}),r=n.project.local.ref();if(t){if(!r)throw new Error("No project linked");if(!await n.project.remote.ping())throw new Error("Remote project is not reachable");return Me("creating app for remote project",r),n.project.remote.createApp(r)}return n.project.local.createApp(e)}var cl=b(()=>{Te();vt();});var am={};fe(am,{repl:()=>bE});var ye,bE,lm=b(()=>{ct();ye=V(z());cl();Ee();Ye();bE=e=>{e.command("repl").option("--config <config>","Path to the config file").option("--remote","Connect REPL to a remote project").description(me("Start a REPL session")).helpGroup("Local Development:").action(async t=>{t.remote||await ee(t.config);let n=await st(t.remote?true:t.config);ss()||(console.error(ye.default.red("REPL is only supported on Node.js")),process.exit(1));let r={app:n,client:n.getClient(),conn:n.connection,db:n.connection.driver};console.log(ye.default.green("Starting a REPL session")),console.log(ye.default.bold("Available variables:"),Object.keys(r).map(o=>ye.default.cyan(o)).join(", "));let i=(await import('node:repl')).start("> ");i.on("exit",async()=>{await n.connection.close(),process.exit();});for(let o of Object.keys(r))Object.defineProperty(i.context,o,{configurable:false,enumerable:true,value:r[o]});i.defineCommand("tables",{help:"List all tables",action:async function(){let a=await n.connection.introspect(),l=c=>a.columns.filter(p=>p.table===c);console.log(a.tables.map(c=>`${ye.default.cyan(c.name)} (${l(c.name).length} columns)`).join(`
126
- `)),this.displayPrompt();}}),i.defineCommand("table",{help:"Show a table",action:async function(a){let l=await n.connection.introspect(),c=u=>l.columns.filter(f=>f.table===u),p=l.tables.find(u=>u.name===a);p?(console.log(`${ye.default.cyan(p?.name)} (${c(a).length} columns)`),console.log(c(a).map(u=>` - ${ye.default.cyan(u.name)} ${ye.default.yellow(u.type)}`).join(`
127
- `)),console.log(),console.log(ye.default.dim(p.sql))):(console.log(ye.default.red(`Table ${a} not found`)),console.log(`Available tables:
128
- `+l.tables.map(u=>`- ${ye.default.cyan(u.name)}`).join(`
129
- `))),this.displayPrompt();}}),i.defineCommand("indexes",{help:"List all indexes",action:async function(){let a=await n.connection.introspect().then(l=>l.indexes);console.log(a.map(l=>`${ye.default.bold(ye.default.cyan(l.name))} ${l.unique?ye.default.yellow("unique "):""}on ${ye.default.blue(l.table)}(${l.columns.map(c=>ye.default.magenta(c)).join(", ")})`).join(`
130
- `)),this.displayPrompt();}}),i.defineCommand("config",{help:"Show the current config",action:async function(a){console.log(a?co(n.config,a):n.config),this.displayPrompt();}});});};});var cm={};fe(cm,{debug:()=>wE});var wE,um=b(()=>{ct();Ee();Ye();wE=e=>{e.command("debug").description(me("Print runtime info (bun/node detection, paths)")).helpGroup("Local Development:").action(async()=>{console.log("Debugging the application"),console.log({bun:Nn(),node:ss(),cwd:process.cwd(),paths:{root:Jr(),dist:eo(),relativeDist:Qr()}});});};});var pl=lt((lN,pm)=>{var ul={to(e,t){return t?`\x1B[${t+1};${e+1}H`:`\x1B[${e+1}G`},move(e,t){let n="";return e<0?n+=`\x1B[${-e}D`:e>0&&(n+=`\x1B[${e}C`),t<0?n+=`\x1B[${-t}A`:t>0&&(n+=`\x1B[${t}B`),n},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 n=0;n<e;n++)t+=this.line+(n<e-1?ul.up():"");return e&&(t+=ul.left),t}};pm.exports={cursor:ul,scroll:SE,erase:EE,beep:"\x07"};});function ni(e,t,n){if(!n.some(o=>!o.disabled))return e;let r=e+t,s=Math.max(n.length-1,0),i=r<0?s:r>s?0:r;return n[i].disabled?ni(i,t<0?-1:1,n):i}function gl(e,t,n){return String(e).normalize().replaceAll(`\r
132
+ `;});async function zt(e){await e.ensureSystemSchema();let t=new Set(await tr(e.connection)),n=await nt(e),r=Ce(e.connection),s=[],i=[];for(let o of n){if(t.has(o.version)){i.push(o);continue}let a=et(o.sql),l;if(r==="pg-flat"){let p=await e.connection.translateDdl(o.sql),u=typeof p=="string"?p:p.ddl??"";l=et(u);}else l=a;let c=Bp(r,{version:o.version,name:o.name,statements:a});if(r==="pg"){let p=At($t(o.sql));p&&await e.connection.exec(p);}await e.connection.transaction([...l,c],{intent:"migration"}),s.push(o);}return {applied:s,skipped:i}}var bi=b(()=>{ht();St();Kt();Ir();});var Rm={};me(Rm,{dev:()=>n_});var qe,n_,vm=b(()=>{Co();da();gt();qe=K(X());Lt();tt();bi();Kt();Re();Te();Qt();Ze();Sa();Ea();_a();n_=e=>{e.command("dev").option("--template","Create a template for the database",false).option("--config <config>","Path to the config file").option("--host [host]","Specify hostname (use without a value to expose all interfaces)").option("--admin","Enable local admin mode explicitly").option("--no-admin","Disable local admin mode (keyless requests are no longer elevated; normal authentication rules apply)").description(de("Start the development server with schema watching")).helpGroup("Local Development:").action(async(t,n)=>{t.config&&await ne(t.config),console.log(qe.default.yellow(" \u26A0 [lite] dev is experimental and works with declarative schema only.")),await Ss(async()=>{let r=Xs(t,n),{created:s}=await bs({template:t.template});s&&console.log(qe.default.green(" \u279C"),"Initialized project",qe.default.cyan(`./${pe.config_dir}`)),console.log();let o=await(await V({withSupabaseClient:false})).project.local.createApp(t.config,{admin:r.admin,adminDefault:r.adminDefault}),a=o.config.api?.port??pe.default_api_port;if((await nt(o)).length>0){let d=await zt(o);for(let g of d.applied)console.log(qe.default.green(" \u2713"),"Applied migration",qe.default.cyan(g.filename));}else o.hasEnabledSystemBaseSchema()&&await o.ensureSystemSchema();await bn(o,{force:true}),console.log();let c=await Os(o,{port:a,host:r.host});Ks(r.host,a),Ws(o.config),Vs(o.adminMode),r.warnAdminDisabled&&zs();let p=ns();p&&console.log(qe.default.yellow(` \u26A0 ${p}`)),await o.connection.ping();let u=wm(o,{translate:true,force:true}),f=Fe__default.join(process.cwd(),"supabase",Vt(o)),h,m=setTimeout(()=>{h=jE.watch(f,{ignoreInitial:true}),h.on("add",async d=>{console.log(),console.log(qe.default.dim(`Migration added: ${d}`));try{let g=await zt(o);for(let y of g.applied)console.log(qe.default.green(" \u2713"),"Applied",qe.default.cyan(y.filename));await bn(o,{force:!0});}catch(g){console.error(qe.default.red("Migration failed: "+String(g.message??g)));}});},200);Gs(async()=>{clearTimeout(m),await Promise.all([u(),h?.close()]),await c(),await o.connection.close();});},r=>{console.log(),console.log(qe.default.green(`Ready in ${r.toFixed(2)}ms`));});});};});async function ut(e){let t=e===true,n=await V({withSupabaseClient:t}),r=n.project.local.ref();if(t){if(!r)throw new Error("No project linked");if(!await n.project.remote.ping())throw new Error("Remote project is not reachable");return He("creating app for remote project",r),n.project.remote.createApp(r)}return n.project.local.createApp(e)}var Al=b(()=>{Re();It();});var km={};me(km,{repl:()=>r_});var Se,r_,Nm=b(()=>{gt();Se=K(X());Al();Te();Ze();r_=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 ne(t.config);let n=await ut(t.remote?true:t.config);ws()||(console.error(Se.default.red("REPL is only supported on Node.js")),process.exit(1));let r={app:n,client:n.getClient(),conn:n.connection,db:n.connection.driver};console.log(Se.default.green("Starting a REPL session")),console.log(Se.default.bold("Available variables:"),Object.keys(r).map(o=>Se.default.cyan(o)).join(", "));let i=(await import('node:repl')).start("> ");i.on("exit",async()=>{await n.connection.close(),process.exit();});for(let o of Object.keys(r))Object.defineProperty(i.context,o,{configurable:false,enumerable:true,value:r[o]});i.defineCommand("tables",{help:"List all tables",action:async function(){let a=await n.connection.introspect(),l=c=>a.columns.filter(p=>p.table===c);console.log(a.tables.map(c=>`${Se.default.cyan(c.name)} (${l(c.name).length} columns)`).join(`
133
+ `)),this.displayPrompt();}}),i.defineCommand("table",{help:"Show a table",action:async function(a){let l=await n.connection.introspect(),c=u=>l.columns.filter(f=>f.table===u),p=l.tables.find(u=>u.name===a);p?(console.log(`${Se.default.cyan(p?.name)} (${c(a).length} columns)`),console.log(c(a).map(u=>` - ${Se.default.cyan(u.name)} ${Se.default.yellow(u.type)}`).join(`
134
+ `)),console.log(),console.log(Se.default.dim(p.sql))):(console.log(Se.default.red(`Table ${a} not found`)),console.log(`Available tables:
135
+ `+l.tables.map(u=>`- ${Se.default.cyan(u.name)}`).join(`
136
+ `))),this.displayPrompt();}}),i.defineCommand("indexes",{help:"List all indexes",action:async function(){let a=await n.connection.introspect().then(l=>l.indexes);console.log(a.map(l=>`${Se.default.bold(Se.default.cyan(l.name))} ${l.unique?Se.default.yellow("unique "):""}on ${Se.default.blue(l.table)}(${l.columns.map(c=>Se.default.magenta(c)).join(", ")})`).join(`
137
+ `)),this.displayPrompt();}}),i.defineCommand("config",{help:"Show the current config",action:async function(a){console.log(a?$o(n.config,a):n.config),this.displayPrompt();}});});};});var Pm={};me(Pm,{debug:()=>s_});var s_,Om=b(()=>{gt();Te();Ze();s_=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:Un(),node:ws(),cwd:process.cwd(),paths:{root:fs(),dist:bo(),relativeDist:ms()}});});};});var Rl=dt((mP,Lm)=>{var $l={to(e,t){return t?`\x1B[${t+1};${e+1}H`:`\x1B[${e+1}G`},move(e,t){let n="";return e<0?n+=`\x1B[${-e}D`:e>0&&(n+=`\x1B[${e}C`),t<0?n+=`\x1B[${-t}A`:t>0&&(n+=`\x1B[${t}B`),n},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"},i_={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},o_={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 n=0;n<e;n++)t+=this.line+(n<e-1?$l.up():"");return e&&(t+=$l.left),t}};Lm.exports={cursor:$l,scroll:i_,erase:o_,beep:"\x07"};});function xi(e,t,n){if(!n.some(o=>!o.disabled))return e;let r=e+t,s=Math.max(n.length-1,0),i=r<0?s:r>s?0:r;return n[i].disabled?xi(i,t<0?-1:1,n):i}function Ol(e,t,n){return String(e).normalize().replaceAll(`\r
131
138
  `,`
132
139
  `).split(`
133
- `).map(r=>OE(r,t,n)).join(`
134
- `)}function El(e,t){if(typeof e=="string")return Ne.aliases.get(e)===t;for(let n of e)if(n!==void 0&&El(n,t))return true;return false}function DE(e,t){if(e===t)return;let n=e.split(`
140
+ `).map(r=>w_(r,t,n)).join(`
141
+ `)}function Fl(e,t){if(typeof e=="string")return Oe.aliases.get(e)===t;for(let n of e)if(n!==void 0&&Fl(n,t))return true;return false}function E_(e,t){if(e===t)return;let n=e.split(`
135
142
  `),r=t.split(`
136
- `),s=Math.max(n.length,r.length),i=[];for(let o=0;o<s;o++)n[o]!==r[o]&&i.push(o);return {lines:i,numLinesBefore:n.length,numLinesAfter:r.length,numLines:s}}function be(e){return e===yl}function ti(e,t){let n=e;n.isTTY&&n.setRawMode(t);}function Em({input:e=stdin,output:t=stdout,overwrite:n=true,hideCursor:r=true}={}){let s=Et.createInterface({input:e,output:t,prompt:"",tabSize:1});Et.emitKeypressEvents(e,s),e instanceof ReadStream&&e.isTTY&&e.setRawMode(true);let i=(o,{name:a,sequence:l})=>{let c=String(o);if(El([c,a,l],"cancel")){r&&t.write(xe.cursor.show),process.exit(0);return}if(!n)return;Et.moveCursor(t,a==="return"?0:-1,a==="return"?-1:0,()=>{Et.clearLine(t,1,()=>{e.once("keypress",i);});});};return r&&t.write(xe.cursor.hide),e.once("keypress",i),()=>{e.off("keypress",i),r&&t.write(xe.cursor.show),e instanceof ReadStream&&e.isTTY&&!jE&&e.setRawMode(false),s.terminal=false,s.close();}}function ci(e,t,n,r=n){let s=li(e??stdout);return gl(t,s-n.length,{hard:true,trim:false}).split(`
143
+ `),s=Math.max(n.length,r.length),i=[];for(let o=0;o<s;o++)n[o]!==r[o]&&i.push(o);return {lines:i,numLinesBefore:n.length,numLinesAfter:r.length,numLines:s}}function Ee(e){return e===Ll}function _i(e,t){let n=e;n.isTTY&&n.setRawMode(t);}function Gm({input:e=stdin,output:t=stdout,overwrite:n=true,hideCursor:r=true}={}){let s=Rt.createInterface({input:e,output:t,prompt:"",tabSize:1});Rt.emitKeypressEvents(e,s),e instanceof ReadStream&&e.isTTY&&e.setRawMode(true);let i=(o,{name:a,sequence:l})=>{let c=String(o);if(Fl([c,a,l],"cancel")){r&&t.write($e.cursor.show),process.exit(0);return}if(!n)return;Rt.moveCursor(t,a==="return"?0:-1,a==="return"?-1:0,()=>{Rt.clearLine(t,1,()=>{e.once("keypress",i);});});};return r&&t.write($e.cursor.hide),e.once("keypress",i),()=>{e.off("keypress",i),r&&t.write($e.cursor.show),e instanceof ReadStream&&e.isTTY&&!__&&e.setRawMode(false),s.terminal=false,s.close();}}function ki(e,t,n,r=n){let s=vi(e??stdout);return Ol(t,s-n.length,{hard:true,trim:false}).split(`
137
144
  `).map((i,o)=>`${o===0?r:n}${i}`).join(`
138
- `)}var xe,xE,TE,CE,fl,Qs,Zs,ml,ei,AE,$E,ym,vE,Er,ai,bm,RE,wl,wm,kE,Sm,Sl,mm,NE,dm,hm,PE,dl,LE,OE,IE,Ne,jE,yl,li,_l,fn,ri,si,ii,oi,xl=b(()=>{xe=V(pl());xE=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,TE=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,CE=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,fl=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,Qs=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Zs=/\t{1,1000}/y,ml=/[\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,ei=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,AE=/\p{M}+/gu,$E={limit:1/0,ellipsis:""},ym=(e,t={},n={})=>{let r=t.limit??1/0,s=t.ellipsis??"",i=t?.ellipsisWidth??(s?ym(s,$E,n).width:0),o=n.ansiWidth??0,a=n.controlWidth??0,l=n.tabWidth??8,c=n.ambiguousWidth??1,p=n.emojiWidth??2,u=n.fullWidthWidth??2,f=n.regularWidth??1,h=n.wideWidth??2,d=0,m=0,g=e.length,y=0,E=false,A=g,C=Math.max(0,r-i),v=0,$=0,T=0,x=0;e:for(;;){if($>v||m>=g&&m>d){let O=e.slice(v,$)||e.slice(d,m);y=0;for(let w of O.replaceAll(AE,"")){let I=w.codePointAt(0)||0;if(TE(I)?x=u:CE(I)?x=h:c!==f&&xE(I)?x=c:x=f,T+x>C&&(A=Math.min(A,Math.max(v,d)+y)),T+x>r){E=true;break e}y+=w.length,T+=x;}v=$=0;}if(m>=g)break;if(ei.lastIndex=m,ei.test(e)){if(y=ei.lastIndex-m,x=y*f,T+x>C&&(A=Math.min(A,m+Math.floor((C-T)/f))),T+x>r){E=true;break}T+=x,v=d,$=m,m=d=ei.lastIndex;continue}if(fl.lastIndex=m,fl.test(e)){if(T+o>C&&(A=Math.min(A,m)),T+o>r){E=true;break}T+=o,v=d,$=m,m=d=fl.lastIndex;continue}if(Qs.lastIndex=m,Qs.test(e)){if(y=Qs.lastIndex-m,x=y*a,T+x>C&&(A=Math.min(A,m+Math.floor((C-T)/a))),T+x>r){E=true;break}T+=x,v=d,$=m,m=d=Qs.lastIndex;continue}if(Zs.lastIndex=m,Zs.test(e)){if(y=Zs.lastIndex-m,x=y*l,T+x>C&&(A=Math.min(A,m+Math.floor((C-T)/l))),T+x>r){E=true;break}T+=x,v=d,$=m,m=d=Zs.lastIndex;continue}if(ml.lastIndex=m,ml.test(e)){if(T+p>C&&(A=Math.min(A,m)),T+p>r){E=true;break}T+=p,v=d,$=m,m=d=ml.lastIndex;continue}m+=1;}return {width:E?C:T,index:E?A:g,truncated:E,ellipsed:E&&r>=i}},vE={limit:1/0,ellipsis:"",ellipsisWidth:0},Er=(e,t={})=>ym(e,vE,t).width,ai="\x1B",bm="\x9B",RE=39,wl="\x07",wm="[",kE="]",Sm="m",Sl=`${kE}8;;`,mm=new RegExp(`(?:\\${wm}(?<code>\\d+)m|\\${Sl}(?<uri>.*)${wl})`,"y"),NE=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},dm=e=>`${ai}${wm}${e}${Sm}`,hm=e=>`${ai}${Sl}${e}${wl}`,PE=e=>e.map(t=>Er(t)),dl=(e,t,n)=>{let r=t[Symbol.iterator](),s=false,i=false,o=e.at(-1),a=o===void 0?0:Er(o),l=r.next(),c=r.next(),p=0;for(;!l.done;){let u=l.value,f=Er(u);a+f<=n?e[e.length-1]+=u:(e.push(u),a=0),(u===ai||u===bm)&&(s=true,i=t.startsWith(Sl,p+1)),s?i?u===wl&&(s=false,i=false):u===Sm&&(s=false):(a+=f,a===n&&!c.done&&(e.push(""),a=0)),l=c,c=r.next(),p+=u.length;}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop());},LE=e=>{let t=e.split(" "),n=t.length;for(;n>0&&!(Er(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(" ")+t.slice(n).join("")},OE=(e,t,n={})=>{if(n.trim!==false&&e.trim()==="")return "";let r="",s,i,o=e.split(" "),a=PE(o),l=[""];for(let[d,m]of o.entries()){n.trim!==false&&(l[l.length-1]=(l.at(-1)??"").trimStart());let g=Er(l.at(-1)??"");if(d!==0&&(g>=t&&(n.wordWrap===false||n.trim===false)&&(l.push(""),g=0),(g>0||n.trim===false)&&(l[l.length-1]+=" ",g++)),n.hard&&a[d]>t){let y=t-g,E=1+Math.floor((a[d]-y-1)/t);Math.floor((a[d]-1)/t)<E&&l.push(""),dl(l,m,t);continue}if(g+a[d]>t&&g>0&&a[d]>0){if(n.wordWrap===false&&g<t){dl(l,m,t);continue}l.push("");}if(g+a[d]>t&&n.wordWrap===false){dl(l,m,t);continue}l[l.length-1]+=m;}n.trim!==false&&(l=l.map(d=>LE(d)));let c=l.join(`
139
- `),p=c[Symbol.iterator](),u=p.next(),f=p.next(),h=0;for(;!u.done;){let d=u.value,m=f.value;if(r+=d,d===ai||d===bm){mm.lastIndex=h+1;let y=mm.exec(c)?.groups;if(y?.code!==void 0){let E=Number.parseFloat(y.code);s=E===RE?void 0:E;}else y?.uri!==void 0&&(i=y.uri.length===0?void 0:y.uri);}let g=s?NE(s):void 0;m===`
140
- `?(i&&(r+=hm("")),s&&g&&(r+=dm(g))):d===`
141
- `&&(s&&g&&(r+=dm(s)),i&&(r+=hm(i))),h+=d.length,u=f,f=p.next();}return r};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"),yl=Symbol("clack:cancel");li=e=>"columns"in e&&typeof e.columns=="number"?e.columns:80,_l=e=>"rows"in e&&typeof e.rows=="number"?e.rows:20;fn=class{input;output;_abortSignal;rl;opts;_render;_track=false;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(t,n=true){let{input:r=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=n,this._abortSignal=o,this.input=r,this.output=s;}unsubscribe(){this._subscribers.clear();}setSubscriber(t,n){let r=this._subscribers.get(t)??[];r.push(n),this._subscribers.set(t,r);}on(t,n){this.setSubscriber(t,{cb:n});}once(t,n){this.setSubscriber(t,{cb:n,once:true});}emit(t,...n){let r=this._subscribers.get(t)??[],s=[];for(let i of r)i.cb(...n),i.once&&s.push(()=>r.splice(r.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(yl);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close();},{once:true});}this.rl=Et__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),ti(this.input,true),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(xe.cursor.show),this.output.off("resize",this.render),ti(this.input,false),t(this.value);}),this.once("cancel",()=>{this.output.write(xe.cursor.show),this.output.off("resize",this.render),ti(this.input,false),t(yl);});})}_isActionKey(t,n){return t===" "}_setValue(t){this.value=t,this.emit("value",this.value);}_setUserInput(t,n){this.userInput=t??"",this.emit("userInput",this.userInput),n&&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,n){if(this._track&&n.name!=="return"&&(n.name&&this._isActionKey(t,n)&&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"),n?.name&&(!this._track&&Ne.aliases.has(n.name)&&this.emit("cursor",Ne.aliases.get(n.name)),Ne.actions.has(n.name)&&this.emit("cursor",n.name)),t&&(t.toLowerCase()==="y"||t.toLowerCase()==="n")&&this.emit("confirm",t.toLowerCase()==="y"),this.emit("key",t?.toLowerCase(),n),n?.name==="return"){if(this.opts.validate){let r=this.opts.validate(this.value);r&&(this.error=r instanceof Error?r.message:r,this.state="error",this.rl?.write(this.userInput));}this.state!=="error"&&(this.state="submit");}El([t,n?.name,n?.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(`
142
- `),ti(this.input,false),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe();}restoreCursor(){let t=gl(this._prevFrame,process.stdout.columns,{hard:true,trim:false}).split(`
143
- `).length-1;this.output.write(xe.cursor.move(-999,t*-1));}render(){let t=gl(this._render(this)??"",process.stdout.columns,{hard:true,trim:false});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(xe.cursor.hide);else {let n=DE(this._prevFrame,t),r=_l(this.output);if(this.restoreCursor(),n){let s=Math.max(0,n.numLinesAfter-r),i=Math.max(0,n.numLinesBefore-r),o=n.lines.find(a=>a>=s);if(o===void 0){this._prevFrame=t;return}if(n.lines.length===1){this.output.write(xe.cursor.move(0,o-i)),this.output.write(xe.erase.lines(1));let a=t.split(`
144
- `);this.output.write(a[o]),this._prevFrame=t,this.output.write(xe.cursor.move(0,a.length-o-1));return}else if(n.lines.length>1){if(s<i)o=s;else {let l=o-i;l>0&&this.output.write(xe.cursor.move(0,l));}this.output.write(xe.erase.down());let a=t.split(`
145
+ `)}var $e,l_,c_,u_,vl,wi,Si,kl,Ei,p_,f_,Um,m_,Dr,Ri,Bm,d_,Dl,qm,h_,Hm,jl,Dm,g_,jm,Fm,y_,Nl,b_,w_,S_,Oe,__,Ll,vi,Ml,En,Ti,Ci,Ai,$i,Ul=b(()=>{$e=K(Rl());l_=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,c_=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,u_=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,vl=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,wi=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Si=/\t{1,1000}/y,kl=/[\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,Ei=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,p_=/\p{M}+/gu,f_={limit:1/0,ellipsis:""},Um=(e,t={},n={})=>{let r=t.limit??1/0,s=t.ellipsis??"",i=t?.ellipsisWidth??(s?Um(s,f_,n).width:0),o=n.ansiWidth??0,a=n.controlWidth??0,l=n.tabWidth??8,c=n.ambiguousWidth??1,p=n.emojiWidth??2,u=n.fullWidthWidth??2,f=n.regularWidth??1,h=n.wideWidth??2,m=0,d=0,g=e.length,y=0,E=false,A=g,C=Math.max(0,r-i),$=0,R=0,T=0,x=0;e:for(;;){if(R>$||d>=g&&d>m){let O=e.slice($,R)||e.slice(m,d);y=0;for(let w of O.replaceAll(p_,"")){let D=w.codePointAt(0)||0;if(c_(D)?x=u:u_(D)?x=h:c!==f&&l_(D)?x=c:x=f,T+x>C&&(A=Math.min(A,Math.max($,m)+y)),T+x>r){E=true;break e}y+=w.length,T+=x;}$=R=0;}if(d>=g)break;if(Ei.lastIndex=d,Ei.test(e)){if(y=Ei.lastIndex-d,x=y*f,T+x>C&&(A=Math.min(A,d+Math.floor((C-T)/f))),T+x>r){E=true;break}T+=x,$=m,R=d,d=m=Ei.lastIndex;continue}if(vl.lastIndex=d,vl.test(e)){if(T+o>C&&(A=Math.min(A,d)),T+o>r){E=true;break}T+=o,$=m,R=d,d=m=vl.lastIndex;continue}if(wi.lastIndex=d,wi.test(e)){if(y=wi.lastIndex-d,x=y*a,T+x>C&&(A=Math.min(A,d+Math.floor((C-T)/a))),T+x>r){E=true;break}T+=x,$=m,R=d,d=m=wi.lastIndex;continue}if(Si.lastIndex=d,Si.test(e)){if(y=Si.lastIndex-d,x=y*l,T+x>C&&(A=Math.min(A,d+Math.floor((C-T)/l))),T+x>r){E=true;break}T+=x,$=m,R=d,d=m=Si.lastIndex;continue}if(kl.lastIndex=d,kl.test(e)){if(T+p>C&&(A=Math.min(A,d)),T+p>r){E=true;break}T+=p,$=m,R=d,d=m=kl.lastIndex;continue}d+=1;}return {width:E?C:T,index:E?A:g,truncated:E,ellipsed:E&&r>=i}},m_={limit:1/0,ellipsis:"",ellipsisWidth:0},Dr=(e,t={})=>Um(e,m_,t).width,Ri="\x1B",Bm="\x9B",d_=39,Dl="\x07",qm="[",h_="]",Hm="m",jl=`${h_}8;;`,Dm=new RegExp(`(?:\\${qm}(?<code>\\d+)m|\\${jl}(?<uri>.*)${Dl})`,"y"),g_=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},jm=e=>`${Ri}${qm}${e}${Hm}`,Fm=e=>`${Ri}${jl}${e}${Dl}`,y_=e=>e.map(t=>Dr(t)),Nl=(e,t,n)=>{let r=t[Symbol.iterator](),s=false,i=false,o=e.at(-1),a=o===void 0?0:Dr(o),l=r.next(),c=r.next(),p=0;for(;!l.done;){let u=l.value,f=Dr(u);a+f<=n?e[e.length-1]+=u:(e.push(u),a=0),(u===Ri||u===Bm)&&(s=true,i=t.startsWith(jl,p+1)),s?i?u===Dl&&(s=false,i=false):u===Hm&&(s=false):(a+=f,a===n&&!c.done&&(e.push(""),a=0)),l=c,c=r.next(),p+=u.length;}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop());},b_=e=>{let t=e.split(" "),n=t.length;for(;n>0&&!(Dr(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(" ")+t.slice(n).join("")},w_=(e,t,n={})=>{if(n.trim!==false&&e.trim()==="")return "";let r="",s,i,o=e.split(" "),a=y_(o),l=[""];for(let[m,d]of o.entries()){n.trim!==false&&(l[l.length-1]=(l.at(-1)??"").trimStart());let g=Dr(l.at(-1)??"");if(m!==0&&(g>=t&&(n.wordWrap===false||n.trim===false)&&(l.push(""),g=0),(g>0||n.trim===false)&&(l[l.length-1]+=" ",g++)),n.hard&&a[m]>t){let y=t-g,E=1+Math.floor((a[m]-y-1)/t);Math.floor((a[m]-1)/t)<E&&l.push(""),Nl(l,d,t);continue}if(g+a[m]>t&&g>0&&a[m]>0){if(n.wordWrap===false&&g<t){Nl(l,d,t);continue}l.push("");}if(g+a[m]>t&&n.wordWrap===false){Nl(l,d,t);continue}l[l.length-1]+=d;}n.trim!==false&&(l=l.map(m=>b_(m)));let c=l.join(`
146
+ `),p=c[Symbol.iterator](),u=p.next(),f=p.next(),h=0;for(;!u.done;){let m=u.value,d=f.value;if(r+=m,m===Ri||m===Bm){Dm.lastIndex=h+1;let y=Dm.exec(c)?.groups;if(y?.code!==void 0){let E=Number.parseFloat(y.code);s=E===d_?void 0:E;}else y?.uri!==void 0&&(i=y.uri.length===0?void 0:y.uri);}let g=s?g_(s):void 0;d===`
147
+ `?(i&&(r+=Fm("")),s&&g&&(r+=jm(g))):m===`
148
+ `&&(s&&g&&(r+=jm(s)),i&&(r+=Fm(i))),h+=m.length,u=f,f=p.next();}return r};S_=["up","down","left","right","space","enter","cancel"],Oe={actions:new Set(S_),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:true};__=globalThis.process.platform.startsWith("win"),Ll=Symbol("clack:cancel");vi=e=>"columns"in e&&typeof e.columns=="number"?e.columns:80,Ml=e=>"rows"in e&&typeof e.rows=="number"?e.rows:20;En=class{input;output;_abortSignal;rl;opts;_render;_track=false;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(t,n=true){let{input:r=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=n,this._abortSignal=o,this.input=r,this.output=s;}unsubscribe(){this._subscribers.clear();}setSubscriber(t,n){let r=this._subscribers.get(t)??[];r.push(n),this._subscribers.set(t,r);}on(t,n){this.setSubscriber(t,{cb:n});}once(t,n){this.setSubscriber(t,{cb:n,once:true});}emit(t,...n){let r=this._subscribers.get(t)??[],s=[];for(let i of r)i.cb(...n),i.once&&s.push(()=>r.splice(r.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(Ll);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close();},{once:true});}this.rl=Rt__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),_i(this.input,true),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write($e.cursor.show),this.output.off("resize",this.render),_i(this.input,false),t(this.value);}),this.once("cancel",()=>{this.output.write($e.cursor.show),this.output.off("resize",this.render),_i(this.input,false),t(Ll);});})}_isActionKey(t,n){return t===" "}_setValue(t){this.value=t,this.emit("value",this.value);}_setUserInput(t,n){this.userInput=t??"",this.emit("userInput",this.userInput),n&&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,n){if(this._track&&n.name!=="return"&&(n.name&&this._isActionKey(t,n)&&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"),n?.name&&(!this._track&&Oe.aliases.has(n.name)&&this.emit("cursor",Oe.aliases.get(n.name)),Oe.actions.has(n.name)&&this.emit("cursor",n.name)),t&&(t.toLowerCase()==="y"||t.toLowerCase()==="n")&&this.emit("confirm",t.toLowerCase()==="y"),this.emit("key",t?.toLowerCase(),n),n?.name==="return"){if(this.opts.validate){let r=this.opts.validate(this.value);r&&(this.error=r instanceof Error?r.message:r,this.state="error",this.rl?.write(this.userInput));}this.state!=="error"&&(this.state="submit");}Fl([t,n?.name,n?.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(`
149
+ `),_i(this.input,false),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe();}restoreCursor(){let t=Ol(this._prevFrame,process.stdout.columns,{hard:true,trim:false}).split(`
150
+ `).length-1;this.output.write($e.cursor.move(-999,t*-1));}render(){let t=Ol(this._render(this)??"",process.stdout.columns,{hard:true,trim:false});if(t!==this._prevFrame){if(this.state==="initial")this.output.write($e.cursor.hide);else {let n=E_(this._prevFrame,t),r=Ml(this.output);if(this.restoreCursor(),n){let s=Math.max(0,n.numLinesAfter-r),i=Math.max(0,n.numLinesBefore-r),o=n.lines.find(a=>a>=s);if(o===void 0){this._prevFrame=t;return}if(n.lines.length===1){this.output.write($e.cursor.move(0,o-i)),this.output.write($e.erase.lines(1));let a=t.split(`
151
+ `);this.output.write(a[o]),this._prevFrame=t,this.output.write($e.cursor.move(0,a.length-o-1));return}else if(n.lines.length>1){if(s<i)o=s;else {let l=o-i;l>0&&this.output.write($e.cursor.move(0,l));}this.output.write($e.erase.down());let a=t.split(`
145
152
  `).slice(o);this.output.write(a.join(`
146
- `)),this._prevFrame=t;return}}this.output.write(xe.erase.down());}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t;}}},ri=class extends fn{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",n=>{this.output.write(xe.cursor.move(0,-1)),this.value=n,this.state="submit",this.close();}),this.on("cursor",()=>{this.value=!this.value;});}},si=class extends fn{_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 n=this.masked,r=n.slice(0,this.cursor),s=n.slice(this.cursor);return `${r}${styleText("inverse",s[0])}${s.slice(1)}`}clear(){this._clearUserInput();}constructor({mask:t,...n}){super(n),this._mask=t??"\u2022",this.on("userInput",r=>{this._setValue(r);});}},ii=class extends fn{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 n=this.options.findIndex(({value:s})=>s===t.initialValue),r=n===-1?0:n;this.cursor=this.options[r].disabled?ni(r,1,this.options):r,this.changeValue(),this.on("cursor",s=>{switch(s){case "left":case "up":this.cursor=ni(this.cursor,-1,this.options);break;case "down":case "right":this.cursor=ni(this.cursor,1,this.options);break}this.changeValue();});}},oi=class extends fn{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return `${this.userInput}\u2588`;let n=t.slice(0,this.cursor),[r,...s]=t.slice(this.cursor);return `${n}${styleText("inverse",r)}${s.join("")}`}get cursor(){return this._cursor}constructor(t){super({...t,initialUserInput:t.initialUserInput??t.initialValue}),this.on("userInput",n=>{this._setValue(n);}),this.on("finalize",()=>{this.value||(this.value=t.defaultValue),this.value===void 0&&(this.value="");});}};});function FE(){return Ve.platform!=="win32"?Ve.env.TERM!=="linux":!!Ve.env.CI||!!Ve.env.WT_SESSION||!!Ve.env.TERMINUS_SUBLIME||Ve.env.ConEmuTask==="{cmd::Cmder}"||Ve.env.TERM_PROGRAM==="Terminus-Sublime"||Ve.env.TERM_PROGRAM==="vscode"||Ve.env.TERM==="xterm-256color"||Ve.env.TERM==="alacritty"||Ve.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}function Rl(e,t,n){return String(e).normalize().replaceAll(`\r
153
+ `)),this._prevFrame=t;return}}this.output.write($e.erase.down());}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t;}}},Ti=class extends En{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",n=>{this.output.write($e.cursor.move(0,-1)),this.value=n,this.state="submit",this.close();}),this.on("cursor",()=>{this.value=!this.value;});}},Ci=class extends En{_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 n=this.masked,r=n.slice(0,this.cursor),s=n.slice(this.cursor);return `${r}${styleText("inverse",s[0])}${s.slice(1)}`}clear(){this._clearUserInput();}constructor({mask:t,...n}){super(n),this._mask=t??"\u2022",this.on("userInput",r=>{this._setValue(r);});}},Ai=class extends En{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 n=this.options.findIndex(({value:s})=>s===t.initialValue),r=n===-1?0:n;this.cursor=this.options[r].disabled?xi(r,1,this.options):r,this.changeValue(),this.on("cursor",s=>{switch(s){case "left":case "up":this.cursor=xi(this.cursor,-1,this.options);break;case "down":case "right":this.cursor=xi(this.cursor,1,this.options);break}this.changeValue();});}},$i=class extends En{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return `${this.userInput}\u2588`;let n=t.slice(0,this.cursor),[r,...s]=t.slice(this.cursor);return `${n}${styleText("inverse",r)}${s.join("")}`}get cursor(){return this._cursor}constructor(t){super({...t,initialUserInput:t.initialUserInput??t.initialValue}),this.on("userInput",n=>{this._setValue(n);}),this.on("finalize",()=>{this.value||(this.value=t.defaultValue),this.value===void 0&&(this.value="");});}};});function x_(){return Xe.platform!=="win32"?Xe.env.TERM!=="linux":!!Xe.env.CI||!!Xe.env.WT_SESSION||!!Xe.env.TERMINUS_SUBLIME||Xe.env.ConEmuTask==="{cmd::Cmder}"||Xe.env.TERM_PROGRAM==="Terminus-Sublime"||Xe.env.TERM_PROGRAM==="vscode"||Xe.env.TERM==="xterm-256color"||Xe.env.TERM==="alacritty"||Xe.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}function Vl(e,t,n){return String(e).normalize().replaceAll(`\r
147
154
  `,`
148
155
  `).split(`
149
- `).map(r=>s_(r,t,n)).join(`
150
- `)}var _r,$l,UE,Y,ME,Cm,Am,kl,K,mn,vl,di,BE,qE,HE,GE,WE,hi,VE,KE,zE,XE,Tl,ui,pi,Cl,fi,YE,JE,$m,QE,xr,gi,vm,ZE,Nl,Rm,e_,km,Pl,_m,t_,xm,Tm,n_,Al,r_,s_,i_,o_,Tr,X,Cr,a_,Ll,mi,Ar,$r,Qe=b(()=>{xl();xl();_r=V(pl());$l=FE(),UE=()=>process.env.CI==="true",Y=(e,t)=>$l?e:t,ME=Y("\u25C6","*"),Cm=Y("\u25A0","x"),Am=Y("\u25B2","x"),kl=Y("\u25C7","o"),Y("\u250C","T"),K=Y("\u2502","|"),mn=Y("\u2514","\u2014"),Y("\u2510","T"),Y("\u2518","\u2014"),vl=Y("\u25CF",">"),di=Y("\u25CB"," "),Y("\u25FB","[\u2022]"),Y("\u25FC","[+]"),Y("\u25FB","[ ]"),BE=Y("\u25AA","\u2022"),Y("\u2500","-"),Y("\u256E","+"),Y("\u251C","+"),Y("\u256F","+"),Y("\u2570","+"),Y("\u256D","+"),qE=Y("\u25CF","\u2022"),HE=Y("\u25C6","*"),GE=Y("\u25B2","!"),WE=Y("\u25A0","x"),hi=e=>{switch(e){case "initial":case "active":return styleText("cyan",ME);case "cancel":return styleText("red",Cm);case "error":return styleText("yellow",Am);case "submit":return styleText("green",kl)}},VE=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)}},KE=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,zE=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,XE=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,Tl=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,ui=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,pi=/\t{1,1000}/y,Cl=/[\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,fi=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,YE=/\p{M}+/gu,JE={limit:1/0,ellipsis:""},$m=(e,t={},n={})=>{let r=t.limit??1/0,s=t.ellipsis??"",i=t?.ellipsisWidth??(s?$m(s,JE,n).width:0),o=n.ansiWidth??0,a=n.controlWidth??0,l=n.tabWidth??8,c=n.ambiguousWidth??1,p=n.emojiWidth??2,u=n.fullWidthWidth??2,f=n.regularWidth??1,h=n.wideWidth??2,d=0,m=0,g=e.length,y=0,E=false,A=g,C=Math.max(0,r-i),v=0,$=0,T=0,x=0;e:for(;;){if($>v||m>=g&&m>d){let O=e.slice(v,$)||e.slice(d,m);y=0;for(let w of O.replaceAll(YE,"")){let I=w.codePointAt(0)||0;if(zE(I)?x=u:XE(I)?x=h:c!==f&&KE(I)?x=c:x=f,T+x>C&&(A=Math.min(A,Math.max(v,d)+y)),T+x>r){E=true;break e}y+=w.length,T+=x;}v=$=0;}if(m>=g)break;if(fi.lastIndex=m,fi.test(e)){if(y=fi.lastIndex-m,x=y*f,T+x>C&&(A=Math.min(A,m+Math.floor((C-T)/f))),T+x>r){E=true;break}T+=x,v=d,$=m,m=d=fi.lastIndex;continue}if(Tl.lastIndex=m,Tl.test(e)){if(T+o>C&&(A=Math.min(A,m)),T+o>r){E=true;break}T+=o,v=d,$=m,m=d=Tl.lastIndex;continue}if(ui.lastIndex=m,ui.test(e)){if(y=ui.lastIndex-m,x=y*a,T+x>C&&(A=Math.min(A,m+Math.floor((C-T)/a))),T+x>r){E=true;break}T+=x,v=d,$=m,m=d=ui.lastIndex;continue}if(pi.lastIndex=m,pi.test(e)){if(y=pi.lastIndex-m,x=y*l,T+x>C&&(A=Math.min(A,m+Math.floor((C-T)/l))),T+x>r){E=true;break}T+=x,v=d,$=m,m=d=pi.lastIndex;continue}if(Cl.lastIndex=m,Cl.test(e)){if(T+p>C&&(A=Math.min(A,m)),T+p>r){E=true;break}T+=p,v=d,$=m,m=d=Cl.lastIndex;continue}m+=1;}return {width:E?C:T,index:E?A:g,truncated:E,ellipsed:E&&r>=i}},QE={limit:1/0,ellipsis:"",ellipsisWidth:0},xr=(e,t={})=>$m(e,QE,t).width,gi="\x1B",vm="\x9B",ZE=39,Nl="\x07",Rm="[",e_="]",km="m",Pl=`${e_}8;;`,_m=new RegExp(`(?:\\${Rm}(?<code>\\d+)m|\\${Pl}(?<uri>.*)${Nl})`,"y"),t_=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},xm=e=>`${gi}${Rm}${e}${km}`,Tm=e=>`${gi}${Pl}${e}${Nl}`,n_=e=>e.map(t=>xr(t)),Al=(e,t,n)=>{let r=t[Symbol.iterator](),s=false,i=false,o=e.at(-1),a=o===void 0?0:xr(o),l=r.next(),c=r.next(),p=0;for(;!l.done;){let u=l.value,f=xr(u);a+f<=n?e[e.length-1]+=u:(e.push(u),a=0),(u===gi||u===vm)&&(s=true,i=t.startsWith(Pl,p+1)),s?i?u===Nl&&(s=false,i=false):u===km&&(s=false):(a+=f,a===n&&!c.done&&(e.push(""),a=0)),l=c,c=r.next(),p+=u.length;}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop());},r_=e=>{let t=e.split(" "),n=t.length;for(;n>0&&!(xr(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(" ")+t.slice(n).join("")},s_=(e,t,n={})=>{if(n.trim!==false&&e.trim()==="")return "";let r="",s,i,o=e.split(" "),a=n_(o),l=[""];for(let[d,m]of o.entries()){n.trim!==false&&(l[l.length-1]=(l.at(-1)??"").trimStart());let g=xr(l.at(-1)??"");if(d!==0&&(g>=t&&(n.wordWrap===false||n.trim===false)&&(l.push(""),g=0),(g>0||n.trim===false)&&(l[l.length-1]+=" ",g++)),n.hard&&a[d]>t){let y=t-g,E=1+Math.floor((a[d]-y-1)/t);Math.floor((a[d]-1)/t)<E&&l.push(""),Al(l,m,t);continue}if(g+a[d]>t&&g>0&&a[d]>0){if(n.wordWrap===false&&g<t){Al(l,m,t);continue}l.push("");}if(g+a[d]>t&&n.wordWrap===false){Al(l,m,t);continue}l[l.length-1]+=m;}n.trim!==false&&(l=l.map(d=>r_(d)));let c=l.join(`
151
- `),p=c[Symbol.iterator](),u=p.next(),f=p.next(),h=0;for(;!u.done;){let d=u.value,m=f.value;if(r+=d,d===gi||d===vm){_m.lastIndex=h+1;let y=_m.exec(c)?.groups;if(y?.code!==void 0){let E=Number.parseFloat(y.code);s=E===ZE?void 0:E;}else y?.uri!==void 0&&(i=y.uri.length===0?void 0:y.uri);}let g=s?t_(s):void 0;m===`
152
- `?(i&&(r+=Tm("")),s&&g&&(r+=xm(g))):d===`
153
- `&&(s&&g&&(r+=xm(s)),i&&(r+=Tm(i))),h+=d.length,u=f,f=p.next();}return r};i_=(e,t,n,r,s)=>{let i=t,o=0;for(let a=n;a<r;a++){let l=e[a];if(i=i-l.length,o++,i<=s)break}return {lineCount:i,removals:o}},o_=({cursor:e,options:t,style:n,output:r=process.stdout,maxItems:s=Number.POSITIVE_INFINITY,columnPadding:i=0,rowPadding:o=4})=>{let a=li(r)-i,l=_l(r),c=styleText("dim","..."),p=Math.max(l-o,0),u=Math.max(Math.min(s,p),5),f=0;e>=u-3&&(f=Math.max(Math.min(e-u+3,t.length-u),0));let h=u<t.length&&f>0,d=u<t.length&&f+u<t.length,m=Math.min(f+u,t.length),g=[],y=0;h&&y++,d&&y++;let E=f+(h?1:0),A=m-(d?1:0);for(let v=E;v<A;v++){let $=Rl(n(t[v],v===e),a,{hard:true,trim:false}).split(`
154
- `);g.push($),y+=$.length;}if(y>p){let v=0,$=0,T=y,x=e-E,O=(w,I)=>i_(g,T,w,I,p);h?({lineCount:T,removals:v}=O(0,x),T>p&&({lineCount:T,removals:$}=O(x+1,g.length))):({lineCount:T,removals:$}=O(x+1,g.length),T>p&&({lineCount:T,removals:v}=O(0,x))),v>0&&(h=true,g.splice(0,v)),$>0&&(d=true,g.splice(g.length-$,$));}let C=[];h&&C.push(c);for(let v of g)for(let $ of v)C.push($);return d&&C.push(c),C},Tr=e=>{let t=e.active??"Yes",n=e.inactive??"No";return new ri({active:t,inactive:n,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??true,render(){let r=e.withGuide??Ne.withGuide,s=`${r?`${styleText("gray",K)}
155
- `:""}${hi(this.state)} ${e.message}
156
- `,i=this.value?t:n;switch(this.state){case "submit":{let o=r?`${styleText("gray",K)} `:"";return `${s}${o}${styleText("dim",i)}`}case "cancel":{let o=r?`${styleText("gray",K)} `:"";return `${s}${o}${styleText(["strikethrough","dim"],i)}${r?`
157
- ${styleText("gray",K)}`:""}`}default:{let o=r?`${styleText("cyan",K)} `:"",a=r?styleText("cyan",mn):"";return `${s}${o}${this.value?`${styleText("green",vl)} ${t}`:`${styleText("dim",di)} ${styleText("dim",t)}`}${e.vertical?r?`
158
- ${styleText("cyan",K)} `:`
159
- `:` ${styleText("dim","/")} `}${this.value?`${styleText("dim",di)} ${styleText("dim",n)}`:`${styleText("green",vl)} ${n}`}
156
+ `).map(r=>H_(r,t,n)).join(`
157
+ `)}var jr,Gl,T_,Q,C_,zm,Xm,Kl,z,_n,Wl,Ii,A_,$_,R_,v_,k_,Di,N_,P_,O_,L_,Bl,Ni,Pi,ql,Oi,I_,D_,Jm,j_,Fr,ji,Ym,F_,zl,Qm,M_,Zm,Xl,Wm,U_,Vm,Km,B_,Hl,q_,H_,G_,W_,Mr,Y,Ur,V_,Jl,Li,Br,qr,rt=b(()=>{Ul();Ul();jr=K(Rl());Gl=x_(),T_=()=>process.env.CI==="true",Q=(e,t)=>Gl?e:t,C_=Q("\u25C6","*"),zm=Q("\u25A0","x"),Xm=Q("\u25B2","x"),Kl=Q("\u25C7","o"),Q("\u250C","T"),z=Q("\u2502","|"),_n=Q("\u2514","\u2014"),Q("\u2510","T"),Q("\u2518","\u2014"),Wl=Q("\u25CF",">"),Ii=Q("\u25CB"," "),Q("\u25FB","[\u2022]"),Q("\u25FC","[+]"),Q("\u25FB","[ ]"),A_=Q("\u25AA","\u2022"),Q("\u2500","-"),Q("\u256E","+"),Q("\u251C","+"),Q("\u256F","+"),Q("\u2570","+"),Q("\u256D","+"),$_=Q("\u25CF","\u2022"),R_=Q("\u25C6","*"),v_=Q("\u25B2","!"),k_=Q("\u25A0","x"),Di=e=>{switch(e){case "initial":case "active":return styleText("cyan",C_);case "cancel":return styleText("red",zm);case "error":return styleText("yellow",Xm);case "submit":return styleText("green",Kl)}},N_=e=>{switch(e){case "initial":case "active":return styleText("cyan",z);case "cancel":return styleText("red",z);case "error":return styleText("yellow",z);case "submit":return styleText("green",z)}},P_=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,O_=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,L_=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,Bl=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,Ni=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Pi=/\t{1,1000}/y,ql=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,Oi=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,I_=/\p{M}+/gu,D_={limit:1/0,ellipsis:""},Jm=(e,t={},n={})=>{let r=t.limit??1/0,s=t.ellipsis??"",i=t?.ellipsisWidth??(s?Jm(s,D_,n).width:0),o=n.ansiWidth??0,a=n.controlWidth??0,l=n.tabWidth??8,c=n.ambiguousWidth??1,p=n.emojiWidth??2,u=n.fullWidthWidth??2,f=n.regularWidth??1,h=n.wideWidth??2,m=0,d=0,g=e.length,y=0,E=false,A=g,C=Math.max(0,r-i),$=0,R=0,T=0,x=0;e:for(;;){if(R>$||d>=g&&d>m){let O=e.slice($,R)||e.slice(m,d);y=0;for(let w of O.replaceAll(I_,"")){let D=w.codePointAt(0)||0;if(O_(D)?x=u:L_(D)?x=h:c!==f&&P_(D)?x=c:x=f,T+x>C&&(A=Math.min(A,Math.max($,m)+y)),T+x>r){E=true;break e}y+=w.length,T+=x;}$=R=0;}if(d>=g)break;if(Oi.lastIndex=d,Oi.test(e)){if(y=Oi.lastIndex-d,x=y*f,T+x>C&&(A=Math.min(A,d+Math.floor((C-T)/f))),T+x>r){E=true;break}T+=x,$=m,R=d,d=m=Oi.lastIndex;continue}if(Bl.lastIndex=d,Bl.test(e)){if(T+o>C&&(A=Math.min(A,d)),T+o>r){E=true;break}T+=o,$=m,R=d,d=m=Bl.lastIndex;continue}if(Ni.lastIndex=d,Ni.test(e)){if(y=Ni.lastIndex-d,x=y*a,T+x>C&&(A=Math.min(A,d+Math.floor((C-T)/a))),T+x>r){E=true;break}T+=x,$=m,R=d,d=m=Ni.lastIndex;continue}if(Pi.lastIndex=d,Pi.test(e)){if(y=Pi.lastIndex-d,x=y*l,T+x>C&&(A=Math.min(A,d+Math.floor((C-T)/l))),T+x>r){E=true;break}T+=x,$=m,R=d,d=m=Pi.lastIndex;continue}if(ql.lastIndex=d,ql.test(e)){if(T+p>C&&(A=Math.min(A,d)),T+p>r){E=true;break}T+=p,$=m,R=d,d=m=ql.lastIndex;continue}d+=1;}return {width:E?C:T,index:E?A:g,truncated:E,ellipsed:E&&r>=i}},j_={limit:1/0,ellipsis:"",ellipsisWidth:0},Fr=(e,t={})=>Jm(e,j_,t).width,ji="\x1B",Ym="\x9B",F_=39,zl="\x07",Qm="[",M_="]",Zm="m",Xl=`${M_}8;;`,Wm=new RegExp(`(?:\\${Qm}(?<code>\\d+)m|\\${Xl}(?<uri>.*)${zl})`,"y"),U_=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},Vm=e=>`${ji}${Qm}${e}${Zm}`,Km=e=>`${ji}${Xl}${e}${zl}`,B_=e=>e.map(t=>Fr(t)),Hl=(e,t,n)=>{let r=t[Symbol.iterator](),s=false,i=false,o=e.at(-1),a=o===void 0?0:Fr(o),l=r.next(),c=r.next(),p=0;for(;!l.done;){let u=l.value,f=Fr(u);a+f<=n?e[e.length-1]+=u:(e.push(u),a=0),(u===ji||u===Ym)&&(s=true,i=t.startsWith(Xl,p+1)),s?i?u===zl&&(s=false,i=false):u===Zm&&(s=false):(a+=f,a===n&&!c.done&&(e.push(""),a=0)),l=c,c=r.next(),p+=u.length;}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop());},q_=e=>{let t=e.split(" "),n=t.length;for(;n>0&&!(Fr(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(" ")+t.slice(n).join("")},H_=(e,t,n={})=>{if(n.trim!==false&&e.trim()==="")return "";let r="",s,i,o=e.split(" "),a=B_(o),l=[""];for(let[m,d]of o.entries()){n.trim!==false&&(l[l.length-1]=(l.at(-1)??"").trimStart());let g=Fr(l.at(-1)??"");if(m!==0&&(g>=t&&(n.wordWrap===false||n.trim===false)&&(l.push(""),g=0),(g>0||n.trim===false)&&(l[l.length-1]+=" ",g++)),n.hard&&a[m]>t){let y=t-g,E=1+Math.floor((a[m]-y-1)/t);Math.floor((a[m]-1)/t)<E&&l.push(""),Hl(l,d,t);continue}if(g+a[m]>t&&g>0&&a[m]>0){if(n.wordWrap===false&&g<t){Hl(l,d,t);continue}l.push("");}if(g+a[m]>t&&n.wordWrap===false){Hl(l,d,t);continue}l[l.length-1]+=d;}n.trim!==false&&(l=l.map(m=>q_(m)));let c=l.join(`
158
+ `),p=c[Symbol.iterator](),u=p.next(),f=p.next(),h=0;for(;!u.done;){let m=u.value,d=f.value;if(r+=m,m===ji||m===Ym){Wm.lastIndex=h+1;let y=Wm.exec(c)?.groups;if(y?.code!==void 0){let E=Number.parseFloat(y.code);s=E===F_?void 0:E;}else y?.uri!==void 0&&(i=y.uri.length===0?void 0:y.uri);}let g=s?U_(s):void 0;d===`
159
+ `?(i&&(r+=Km("")),s&&g&&(r+=Vm(g))):m===`
160
+ `&&(s&&g&&(r+=Vm(s)),i&&(r+=Km(i))),h+=m.length,u=f,f=p.next();}return r};G_=(e,t,n,r,s)=>{let i=t,o=0;for(let a=n;a<r;a++){let l=e[a];if(i=i-l.length,o++,i<=s)break}return {lineCount:i,removals:o}},W_=({cursor:e,options:t,style:n,output:r=process.stdout,maxItems:s=Number.POSITIVE_INFINITY,columnPadding:i=0,rowPadding:o=4})=>{let a=vi(r)-i,l=Ml(r),c=styleText("dim","..."),p=Math.max(l-o,0),u=Math.max(Math.min(s,p),5),f=0;e>=u-3&&(f=Math.max(Math.min(e-u+3,t.length-u),0));let h=u<t.length&&f>0,m=u<t.length&&f+u<t.length,d=Math.min(f+u,t.length),g=[],y=0;h&&y++,m&&y++;let E=f+(h?1:0),A=d-(m?1:0);for(let $=E;$<A;$++){let R=Vl(n(t[$],$===e),a,{hard:true,trim:false}).split(`
161
+ `);g.push(R),y+=R.length;}if(y>p){let $=0,R=0,T=y,x=e-E,O=(w,D)=>G_(g,T,w,D,p);h?({lineCount:T,removals:$}=O(0,x),T>p&&({lineCount:T,removals:R}=O(x+1,g.length))):({lineCount:T,removals:R}=O(x+1,g.length),T>p&&({lineCount:T,removals:$}=O(0,x))),$>0&&(h=true,g.splice(0,$)),R>0&&(m=true,g.splice(g.length-R,R));}let C=[];h&&C.push(c);for(let $ of g)for(let R of $)C.push(R);return m&&C.push(c),C},Mr=e=>{let t=e.active??"Yes",n=e.inactive??"No";return new Ti({active:t,inactive:n,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??true,render(){let r=e.withGuide??Oe.withGuide,s=`${r?`${styleText("gray",z)}
162
+ `:""}${Di(this.state)} ${e.message}
163
+ `,i=this.value?t:n;switch(this.state){case "submit":{let o=r?`${styleText("gray",z)} `:"";return `${s}${o}${styleText("dim",i)}`}case "cancel":{let o=r?`${styleText("gray",z)} `:"";return `${s}${o}${styleText(["strikethrough","dim"],i)}${r?`
164
+ ${styleText("gray",z)}`:""}`}default:{let o=r?`${styleText("cyan",z)} `:"",a=r?styleText("cyan",_n):"";return `${s}${o}${this.value?`${styleText("green",Wl)} ${t}`:`${styleText("dim",Ii)} ${styleText("dim",t)}`}${e.vertical?r?`
165
+ ${styleText("cyan",z)} `:`
166
+ `:` ${styleText("dim","/")} `}${this.value?`${styleText("dim",Ii)} ${styleText("dim",n)}`:`${styleText("green",Wl)} ${n}`}
160
167
  ${a}
161
- `}}}}).prompt()},X={message:(e=[],{symbol:t=styleText("gray",K),secondarySymbol:n=styleText("gray",K),output:r=process.stdout,spacing:s=1,withGuide:i}={})=>{let o=[],a=i??Ne.withGuide,l=a?n:"",c=a?`${t} `:"",p=a?`${n} `:"";for(let f=0;f<s;f++)o.push(l);let u=Array.isArray(e)?e:e.split(`
162
- `);if(u.length>0){let[f,...h]=u;f.length>0?o.push(`${c}${f}`):o.push(a?t:"");for(let d of h)d.length>0?o.push(`${p}${d}`):o.push(a?n:"");}r.write(`${o.join(`
168
+ `}}}}).prompt()},Y={message:(e=[],{symbol:t=styleText("gray",z),secondarySymbol:n=styleText("gray",z),output:r=process.stdout,spacing:s=1,withGuide:i}={})=>{let o=[],a=i??Oe.withGuide,l=a?n:"",c=a?`${t} `:"",p=a?`${n} `:"";for(let f=0;f<s;f++)o.push(l);let u=Array.isArray(e)?e:e.split(`
169
+ `);if(u.length>0){let[f,...h]=u;f.length>0?o.push(`${c}${f}`):o.push(a?t:"");for(let m of h)m.length>0?o.push(`${p}${m}`):o.push(a?n:"");}r.write(`${o.join(`
163
170
  `)}
164
- `);},info:(e,t)=>{X.message(e,{...t,symbol:styleText("blue",qE)});},success:(e,t)=>{X.message(e,{...t,symbol:styleText("green",HE)});},step:(e,t)=>{X.message(e,{...t,symbol:styleText("green",kl)});},warn:(e,t)=>{X.message(e,{...t,symbol:styleText("yellow",GE)});},warning:(e,t)=>{X.warn(e,t);},error:(e,t)=>{X.message(e,{...t,symbol:styleText("red",WE)});}},Cr=e=>new si({validate:e.validate,mask:e.mask??BE,signal:e.signal,input:e.input,output:e.output,render(){let t=e.withGuide??Ne.withGuide,n=`${t?`${styleText("gray",K)}
165
- `:""}${hi(this.state)} ${e.message}
166
- `,r=this.userInputWithCursor,s=this.masked;switch(this.state){case "error":{let i=t?`${styleText("yellow",K)} `:"",o=t?`${styleText("yellow",mn)} `:"",a=s??"";return e.clearOnError&&this.clear(),`${n.trim()}
171
+ `);},info:(e,t)=>{Y.message(e,{...t,symbol:styleText("blue",$_)});},success:(e,t)=>{Y.message(e,{...t,symbol:styleText("green",R_)});},step:(e,t)=>{Y.message(e,{...t,symbol:styleText("green",Kl)});},warn:(e,t)=>{Y.message(e,{...t,symbol:styleText("yellow",v_)});},warning:(e,t)=>{Y.warn(e,t);},error:(e,t)=>{Y.message(e,{...t,symbol:styleText("red",k_)});}},Ur=e=>new Ci({validate:e.validate,mask:e.mask??A_,signal:e.signal,input:e.input,output:e.output,render(){let t=e.withGuide??Oe.withGuide,n=`${t?`${styleText("gray",z)}
172
+ `:""}${Di(this.state)} ${e.message}
173
+ `,r=this.userInputWithCursor,s=this.masked;switch(this.state){case "error":{let i=t?`${styleText("yellow",z)} `:"",o=t?`${styleText("yellow",_n)} `:"",a=s??"";return e.clearOnError&&this.clear(),`${n.trim()}
167
174
  ${i}${a}
168
175
  ${o}${styleText("yellow",this.error)}
169
- `}case "submit":{let i=t?`${styleText("gray",K)} `:"",o=s?styleText("dim",s):"";return `${n}${i}${o}`}case "cancel":{let i=t?`${styleText("gray",K)} `:"",o=s?styleText(["strikethrough","dim"],s):"";return `${n}${i}${o}${s&&t?`
170
- ${styleText("gray",K)}`:""}`}default:{let i=t?`${styleText("cyan",K)} `:"",o=t?styleText("cyan",mn):"";return `${n}${i}${r}
176
+ `}case "submit":{let i=t?`${styleText("gray",z)} `:"",o=s?styleText("dim",s):"";return `${n}${i}${o}`}case "cancel":{let i=t?`${styleText("gray",z)} `:"",o=s?styleText(["strikethrough","dim"],s):"";return `${n}${i}${o}${s&&t?`
177
+ ${styleText("gray",z)}`:""}`}default:{let i=t?`${styleText("cyan",z)} `:"",o=t?styleText("cyan",_n):"";return `${n}${i}${r}
171
178
  ${o}
172
- `}}}}).prompt(),a_=e=>styleText("magenta",e),Ll=({indicator:e="dots",onCancel:t,output:n=process.stdout,cancelMessage:r,errorMessage:s,frames:i=$l?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:o=$l?80:120,signal:a,...l}={})=>{let c=UE(),p,u,f=false,h=false,d="",m,g=performance.now(),y=li(n),E=l?.styleFrame??a_,A=S=>{let _=S>1?s??Ne.messages.error:r??Ne.messages.cancel;h=S===1,f&&(j(_,S),h&&typeof t=="function"&&t());},C=()=>A(2),v=()=>A(1),$=()=>{process.on("uncaughtExceptionMonitor",C),process.on("unhandledRejection",C),process.on("SIGINT",v),process.on("SIGTERM",v),process.on("exit",A),a&&a.addEventListener("abort",v);},T=()=>{process.removeListener("uncaughtExceptionMonitor",C),process.removeListener("unhandledRejection",C),process.removeListener("SIGINT",v),process.removeListener("SIGTERM",v),process.removeListener("exit",A),a&&a.removeEventListener("abort",v);},x=()=>{if(m===void 0)return;c&&n.write(`
173
- `);let S=Rl(m,y,{hard:true,trim:false}).split(`
174
- `);S.length>1&&n.write(_r.cursor.up(S.length-1)),n.write(_r.cursor.to(0)),n.write(_r.erase.down());},O=S=>S.replace(/\.+$/,""),w=S=>{let _=(performance.now()-S)/1e3,Z=Math.floor(_/60),B=Math.floor(_%60);return Z>0?`[${Z}m ${B}s]`:`[${B}s]`},I=l.withGuide??Ne.withGuide,P=(S="")=>{f=true,p=Em({output:n}),d=O(S),g=performance.now(),I&&n.write(`${styleText("gray",K)}
175
- `);let _=0,Z=0;$(),u=setInterval(()=>{if(c&&d===m)return;x(),m=d;let B=E(i[_]),D;if(c)D=`${B} ${d}...`;else if(e==="timer")D=`${B} ${d} ${w(g)}`;else {let ce=".".repeat(Math.floor(Z)).slice(0,3);D=`${B} ${d}${ce}`;}let oe=Rl(D,y,{hard:true,trim:false});n.write(oe),_=_+1<i.length?_+1:0,Z=Z<4?Z+.125:0;},o);},j=(S="",_=0,Z=false)=>{if(!f)return;f=false,clearInterval(u),x();let B=_===0?styleText("green",kl):_===1?styleText("red",Cm):styleText("red",Am);d=S??d,Z||(e==="timer"?n.write(`${B} ${d} ${w(g)}
176
- `):n.write(`${B} ${d}
177
- `)),T(),p();};return {start:P,stop:(S="")=>j(S,0),message:(S="")=>{d=O(S??d);},cancel:(S="")=>j(S,1),error:(S="")=>j(S,2),clear:()=>j("",0,true),get isCancelled(){return h}}},{light:Y("\u2500","-"),heavy:Y("\u2501","="),block:Y("\u2588","#")},mi=(e,t)=>e.includes(`
179
+ `}}}}).prompt(),V_=e=>styleText("magenta",e),Jl=({indicator:e="dots",onCancel:t,output:n=process.stdout,cancelMessage:r,errorMessage:s,frames:i=Gl?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:o=Gl?80:120,signal:a,...l}={})=>{let c=T_(),p,u,f=false,h=false,m="",d,g=performance.now(),y=vi(n),E=l?.styleFrame??V_,A=S=>{let _=S>1?s??Oe.messages.error:r??Oe.messages.cancel;h=S===1,f&&(U(_,S),h&&typeof t=="function"&&t());},C=()=>A(2),$=()=>A(1),R=()=>{process.on("uncaughtExceptionMonitor",C),process.on("unhandledRejection",C),process.on("SIGINT",$),process.on("SIGTERM",$),process.on("exit",A),a&&a.addEventListener("abort",$);},T=()=>{process.removeListener("uncaughtExceptionMonitor",C),process.removeListener("unhandledRejection",C),process.removeListener("SIGINT",$),process.removeListener("SIGTERM",$),process.removeListener("exit",A),a&&a.removeEventListener("abort",$);},x=()=>{if(d===void 0)return;c&&n.write(`
180
+ `);let S=Vl(d,y,{hard:true,trim:false}).split(`
181
+ `);S.length>1&&n.write(jr.cursor.up(S.length-1)),n.write(jr.cursor.to(0)),n.write(jr.erase.down());},O=S=>S.replace(/\.+$/,""),w=S=>{let _=(performance.now()-S)/1e3,L=Math.floor(_/60),j=Math.floor(_%60);return L>0?`[${L}m ${j}s]`:`[${j}s]`},D=l.withGuide??Oe.withGuide,q=(S="")=>{f=true,p=Gm({output:n}),m=O(S),g=performance.now(),D&&n.write(`${styleText("gray",z)}
182
+ `);let _=0,L=0;R(),u=setInterval(()=>{if(c&&m===d)return;x(),d=m;let j=E(i[_]),I;if(c)I=`${j} ${m}...`;else if(e==="timer")I=`${j} ${m} ${w(g)}`;else {let ue=".".repeat(Math.floor(L)).slice(0,3);I=`${j} ${m}${ue}`;}let te=Vl(I,y,{hard:true,trim:false});n.write(te),_=_+1<i.length?_+1:0,L=L<4?L+.125:0;},o);},U=(S="",_=0,L=false)=>{if(!f)return;f=false,clearInterval(u),x();let j=_===0?styleText("green",Kl):_===1?styleText("red",zm):styleText("red",Xm);m=S??m,L||(e==="timer"?n.write(`${j} ${m} ${w(g)}
183
+ `):n.write(`${j} ${m}
184
+ `)),T(),p();};return {start:q,stop:(S="")=>U(S,0),message:(S="")=>{m=O(S??m);},cancel:(S="")=>U(S,1),error:(S="")=>U(S,2),clear:()=>U("",0,true),get isCancelled(){return h}}},{light:Q("\u2500","-"),heavy:Q("\u2501","="),block:Q("\u2588","#")},Li=(e,t)=>e.includes(`
178
185
  `)?e.split(`
179
186
  `).map(n=>t(n)).join(`
180
- `):t(e),Ar=e=>{let t=(n,r)=>{let s=n.label??String(n.value);switch(r){case "disabled":return `${styleText("gray",di)} ${mi(s,i=>styleText("gray",i))}${n.hint?` ${styleText("dim",`(${n.hint??"disabled"})`)}`:""}`;case "selected":return `${mi(s,i=>styleText("dim",i))}`;case "active":return `${styleText("green",vl)} ${s}${n.hint?` ${styleText("dim",`(${n.hint})`)}`:""}`;case "cancelled":return `${mi(s,i=>styleText(["strikethrough","dim"],i))}`;default:return `${styleText("dim",di)} ${mi(s,i=>styleText("dim",i))}`}};return new ii({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let n=e.withGuide??Ne.withGuide,r=`${hi(this.state)} `,s=`${VE(this.state)} `,i=ci(e.output,e.message,s,r),o=`${n?`${styleText("gray",K)}
187
+ `):t(e),Br=e=>{let t=(n,r)=>{let s=n.label??String(n.value);switch(r){case "disabled":return `${styleText("gray",Ii)} ${Li(s,i=>styleText("gray",i))}${n.hint?` ${styleText("dim",`(${n.hint??"disabled"})`)}`:""}`;case "selected":return `${Li(s,i=>styleText("dim",i))}`;case "active":return `${styleText("green",Wl)} ${s}${n.hint?` ${styleText("dim",`(${n.hint})`)}`:""}`;case "cancelled":return `${Li(s,i=>styleText(["strikethrough","dim"],i))}`;default:return `${styleText("dim",Ii)} ${Li(s,i=>styleText("dim",i))}`}};return new Ai({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let n=e.withGuide??Oe.withGuide,r=`${Di(this.state)} `,s=`${N_(this.state)} `,i=ki(e.output,e.message,s,r),o=`${n?`${styleText("gray",z)}
181
188
  `:""}${i}
182
- `;switch(this.state){case "submit":{let a=n?`${styleText("gray",K)} `:"",l=ci(e.output,t(this.options[this.cursor],"selected"),a);return `${o}${l}`}case "cancel":{let a=n?`${styleText("gray",K)} `:"",l=ci(e.output,t(this.options[this.cursor],"cancelled"),a);return `${o}${l}${n?`
183
- ${styleText("gray",K)}`:""}`}default:{let a=n?`${styleText("cyan",K)} `:"",l=n?styleText("cyan",mn):"",c=o.split(`
184
- `).length,p=n?2:1;return `${o}${a}${o_({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:a.length,rowPadding:c+p,style:(u,f)=>t(u,u.disabled?"disabled":f?"active":"inactive")}).join(`
189
+ `;switch(this.state){case "submit":{let a=n?`${styleText("gray",z)} `:"",l=ki(e.output,t(this.options[this.cursor],"selected"),a);return `${o}${l}`}case "cancel":{let a=n?`${styleText("gray",z)} `:"",l=ki(e.output,t(this.options[this.cursor],"cancelled"),a);return `${o}${l}${n?`
190
+ ${styleText("gray",z)}`:""}`}default:{let a=n?`${styleText("cyan",z)} `:"",l=n?styleText("cyan",_n):"",c=o.split(`
191
+ `).length,p=n?2:1;return `${o}${a}${W_({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:a.length,rowPadding:c+p,style:(u,f)=>t(u,u.disabled?"disabled":f?"active":"inactive")}).join(`
185
192
  ${a}`)}
186
193
  ${l}
187
- `}}}}).prompt()},`${styleText("gray",K)} `,$r=e=>new oi({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,n=`${`${t?`${styleText("gray",K)}
188
- `:""}${hi(this.state)} `}${e.message}
189
- `,r=e.placeholder?styleText("inverse",e.placeholder[0])+styleText("dim",e.placeholder.slice(1)):styleText(["inverse","hidden"],"_"),s=this.userInput?this.userInputWithCursor:r,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",mn):"";return `${n.trim()}
194
+ `}}}}).prompt()},`${styleText("gray",z)} `,qr=e=>new $i({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??Oe.withGuide,n=`${`${t?`${styleText("gray",z)}
195
+ `:""}${Di(this.state)} `}${e.message}
196
+ `,r=e.placeholder?styleText("inverse",e.placeholder[0])+styleText("dim",e.placeholder.slice(1)):styleText(["inverse","hidden"],"_"),s=this.userInput?this.userInputWithCursor:r,i=this.value??"";switch(this.state){case "error":{let o=this.error?` ${styleText("yellow",this.error)}`:"",a=t?`${styleText("yellow",z)} `:"",l=t?styleText("yellow",_n):"";return `${n.trim()}
190
197
  ${a}${s}
191
198
  ${l}${o}
192
- `}case "submit":{let o=i?` ${styleText("dim",i)}`:"",a=t?styleText("gray",K):"";return `${n}${a}${o}`}case "cancel":{let o=i?` ${styleText(["strikethrough","dim"],i)}`:"",a=t?styleText("gray",K):"";return `${n}${a}${o}${i.trim()?`
193
- ${a}`:""}`}default:{let o=t?`${styleText("cyan",K)} `:"",a=t?styleText("cyan",mn):"";return `${n}${o}${s}
199
+ `}case "submit":{let o=i?` ${styleText("dim",i)}`:"",a=t?styleText("gray",z):"";return `${n}${a}${o}`}case "cancel":{let o=i?` ${styleText(["strikethrough","dim"],i)}`:"",a=t?styleText("gray",z):"";return `${n}${a}${o}${i.trim()?`
200
+ ${a}`:""}`}default:{let o=t?`${styleText("cyan",z)} `:"",a=t?styleText("cyan",_n):"";return `${n}${o}${s}
194
201
  ${a}
195
- `}}}}).prompt();});async function u_(){return Wt||(Wt=await import('@sentry/node')),Wt}function Om(e){if(e)return false;let t=process.env.LITE_TELEMETRY;if(t==="0"||t==="false")return false;let n=process.env.DO_NOT_TRACK;return !(n==="1"||n==="true"||process.env.CI||process.env.LOCAL)}function p_(){let e=process.versions;return e.bun?"bun":e.deno?"deno":"node"}function f_(){if(process.env.CODESPACES)return "codespaces";if(process.env.REMOTE_CONTAINERS)return "devcontainer";try{return statSync("/.dockerenv"),"docker"}catch{return}}function m_(e){let t=e/1e6;return t<1?"<1MB":t<10?"1-10MB":t<100?"10-100MB":t<1e3?"100MB-1GB":">1GB"}function d_(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 n=new URL(t).hostname;return n==="localhost"||n==="127.0.0.1"||n==="::1"?"local":"remote"}catch{return "remote"}}}function h_(){try{let e=Ie__default.resolve(process.cwd(),ue.config_dir,"config.toml"),t;try{t=readFileSync(e,"utf-8");}catch{return {}}let n;try{n=At(t);}catch{return {}}let r=n.db?.driver,s=r==="sqlite"||r==="sqlite-postgres"||r==="pglite"||r==="postgres"?r:"sqlite-postgres",i=n.db?.url??ue.default_db_url,o=d_(s,i),a;if(o==="file"&&i.startsWith("file:"))try{let l=i.startsWith("file://")?i.slice(7):i.slice(5),c=Ie__default.resolve(process.cwd(),l);a=statSync(c).size;}catch{}return {driver:s,location:o,sizeBytes:a}}catch{return {}}}async function Im(e){if(dn)return;dn=true;let t=await u_(),{version:n}=await Yr();t.init({dsn:c_,release:`@supabase/lite@${n}`,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",p_()),t.setTag("node",process.version),t.setTag("platform",process.platform),t.setTag("arch",process.arch),t.setTag("ci",!!process.env.CI);let r=f_();r&&t.setTag("container",r);try{let{determineAgent:i}=await import('@vercel/detect-agent'),o=await i();o.isAgent&&t.setTag("agent",o.agent.name);}catch{}let s=h_();s.driver&&t.setTag("db.driver",s.driver),s.location&&t.setTag("db.location",s.location),typeof s.sizeBytes=="number"&&t.setTag("db.size",m_(s.sizeBytes));for(let[i,o]of Object.entries(e.args))t.setTag(`arg.${i}`,!!o);t.startSession(),Lm=true,Gt=t.startInactiveSpan({name:`cli:${e.command}`,op:"cli.command",forceTransaction:true});}async function hn(e,t){if(!dn)return;let n=Wt;try{if(e&&(n.setTag("status","failed"),t instanceof Error&&n.setTag("error_class",t.constructor.name)),Gt&&(Gt.setStatus({code:e?2:1,message:e?"internal_error":"ok"}),Gt.end(),Gt=void 0),Lm){let r=n.getCurrentScope().getSession();r&&e&&(r.status="crashed"),n.endSession();}}finally{await n.flush(2e3).catch(()=>{});}}function vr(e,t){if(!dn)return Promise.resolve(t());let n=Wt,r=()=>n.startSpan({name:e,op:"cli.step"},t);return Gt?n.withActiveSpan(Gt,r):r()}function Ol(e,t){dn&&Wt.setTag(e,t);}function Dm(e,t){if(!dn)return;let n=Wt;try{n.captureException(e,{tags:{translation_gap:!0,"db.variant":t.variant,error_class:e instanceof Error?e.constructor.name:"unknown"},contexts:{translation_gap:{variant:t.variant,failing_sql:t.failingSql?t.failingSql.slice(0,4e3):void 0}}});}catch{}}var c_,Wt,dn,Lm,Gt,Rr=b(()=>{An();$t();Ee();c_="https://9562525a4ea320539ea7e94859533a17@o398706.ingest.us.sentry.io/4511381939290112";dn=false,Lm=false;});function gn(e){return e instanceof yi}function Fm(){if(jm)return;jm=true;let e=process.exit.bind(process),t=false;process.exit=(n=>{let r=typeof n=="number"?n:Number(process.exitCode??0);throw t||(t=true,hn(r!==0).finally(()=>e(r))),new yi(r)});}var yi,jm,Il=b(()=>{Rr();yi=class extends Error{code;constructor(t){super(`process.exit(${t})`),this.name="ProcessExit",this.code=t;}};jm=false;});function Mm(e,t){let n=t?.renderHeader??(a=>String(a)),r=Object.keys(e[0]).filter(a=>!t?.omitKeys?.includes(a)).map(a=>{let l=n(a),c=Math.max(l.length,...e.map(p=>String(p[a]).length));return {key:a,header:l,length:c}}),s=" ".repeat(t?.paddingHorizontal??1),i=`
196
- `.repeat(t?.paddingVertical??1),o=t?.renderCell??((a,l)=>l===null?Um.default.dim("null"):String(l));return `${i}${s}| ${r.map(a=>a.header.padEnd(a.length)).join(" | ")} |
202
+ `}}}}).prompt();});async function X_(){return Jt||(Jt=await import('@sentry/node')),Jt}function rd(e){if(e)return false;let t=process.env.LITE_TELEMETRY;if(t==="0"||t==="false")return false;let n=process.env.DO_NOT_TRACK;return !(n==="1"||n==="true"||process.env.CI||process.env.LOCAL)}function J_(){let e=process.versions;return e.bun?"bun":e.deno?"deno":"node"}function Y_(){if(process.env.CODESPACES)return "codespaces";if(process.env.REMOTE_CONTAINERS)return "devcontainer";try{return statSync("/.dockerenv"),"docker"}catch{return}}function Q_(e){let t=e/1e6;return t<1?"<1MB":t<10?"1-10MB":t<100?"10-100MB":t<1e3?"100MB-1GB":">1GB"}function Z_(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 n=new URL(t).hostname;return n==="localhost"||n==="127.0.0.1"||n==="::1"?"local":"remote"}catch{return "remote"}}}function ex(){try{let e=Fe__default.resolve(process.cwd(),pe.config_dir,"config.toml"),t;try{t=readFileSync(e,"utf-8");}catch{return {}}let n;try{n=Ot(t);}catch{return {}}let r=n.db?.driver,s=r==="sqlite"||r==="sqlite-postgres"||r==="pglite"||r==="postgres"?r:"sqlite-postgres",i=n.db?.url??pe.default_db_url,o=Z_(s,i),a;if(o==="file"&&i.startsWith("file:"))try{let l=i.startsWith("file://")?i.slice(7):i.slice(5),c=Fe__default.resolve(process.cwd(),l);a=statSync(c).size;}catch{}return {driver:s,location:o,sizeBytes:a}}catch{return {}}}async function sd(e){if(xn)return;xn=true;let t=await X_(),{version:n}=await ps();t.init({dsn:z_,release:`@supabase/lite@${n}`,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",J_()),t.setTag("node",process.version),t.setTag("platform",process.platform),t.setTag("arch",process.arch),t.setTag("ci",!!process.env.CI);let r=Y_();r&&t.setTag("container",r);try{let{determineAgent:i}=await import('@vercel/detect-agent'),o=await i();o.isAgent&&t.setTag("agent",o.agent.name);}catch{}let s=ex();s.driver&&t.setTag("db.driver",s.driver),s.location&&t.setTag("db.location",s.location),typeof s.sizeBytes=="number"&&t.setTag("db.size",Q_(s.sizeBytes));for(let[i,o]of Object.entries(e.args))t.setTag(`arg.${i}`,!!o);t.startSession(),nd=true,Xt=t.startInactiveSpan({name:`cli:${e.command}`,op:"cli.command",forceTransaction:true});}async function Tn(e,t){if(!xn)return;let n=Jt;try{if(e&&(n.setTag("status","failed"),t instanceof Error&&n.setTag("error_class",t.constructor.name)),Xt&&(Xt.setStatus({code:e?2:1,message:e?"internal_error":"ok"}),Xt.end(),Xt=void 0),nd){let r=n.getCurrentScope().getSession();r&&e&&(r.status="crashed"),n.endSession();}}finally{await n.flush(2e3).catch(()=>{});}}function Hr(e,t){if(!xn)return Promise.resolve(t());let n=Jt,r=()=>n.startSpan({name:e,op:"cli.step"},t);return Xt?n.withActiveSpan(Xt,r):r()}function Yl(e,t){xn&&Jt.setTag(e,t);}function id(e,t){if(!xn)return;let n=Jt;try{n.captureException(e,{tags:{translation_gap:!0,"db.variant":t.variant,error_class:e instanceof Error?e.constructor.name:"unknown"},contexts:{translation_gap:{variant:t.variant,failing_sql:t.failingSql?t.failingSql.slice(0,4e3):void 0}}});}catch{}}var z_,Jt,xn,nd,Xt,Gr=b(()=>{In();Lt();Te();z_="https://9562525a4ea320539ea7e94859533a17@o398706.ingest.us.sentry.io/4511381939290112";xn=false,nd=false;});function Cn(e){return e instanceof Fi}function ad(){if(od)return;od=true;let e=process.exit.bind(process),t=false;process.exit=(n=>{let r=typeof n=="number"?n:Number(process.exitCode??0);throw t||(t=true,Tn(r!==0).finally(()=>e(r))),new Fi(r)});}var Fi,od,Ql=b(()=>{Gr();Fi=class extends Error{code;constructor(t){super(`process.exit(${t})`),this.name="ProcessExit",this.code=t;}};od=false;});function cd(e,t){let n=t?.renderHeader??(a=>String(a)),r=Object.keys(e[0]).filter(a=>!t?.omitKeys?.includes(a)).map(a=>{let l=n(a),c=Math.max(l.length,...e.map(p=>String(p[a]).length));return {key:a,header:l,length:c}}),s=" ".repeat(t?.paddingHorizontal??1),i=`
203
+ `.repeat(t?.paddingVertical??1),o=t?.renderCell??((a,l)=>l===null?ld.default.dim("null"):String(l));return `${i}${s}| ${r.map(a=>a.header.padEnd(a.length)).join(" | ")} |
197
204
  ${s}| ${r.map(a=>"\u2500".repeat(a.length)).join(" | ")} |
198
205
  ${e.map(a=>`${s}| ${Object.entries(a).filter(([l])=>!t?.omitKeys?.includes(l)).map(([l,c])=>o(l,c).padEnd(r.find(p=>p.key===l)?.length??0)).join(" | ")} |`).join(`
199
- `)}${i}`}async function J(e){try{await e();}catch(t){if(gn(t))throw t;(process.env.LOCAL||process.env.DEBUG)&&console.error(t),X.error(String(t)),process.exit(1);}process.exit(0);}var Um,Le=b(()=>{Um=V(z());Qe();Il();});function b_(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(n=>!Number.isNaN(n)):e;case 1002:case 1009:case 1015:return typeof e=="string"?Bm(e,g_):e;case 1005:case 1007:case 1016:return typeof e=="string"?Bm(e,y_):e;default:return e}}function Dl(e){let t=async(n,r)=>{let s=await e.driver.query(n,r?[...r]:[]);return {rows:s.rows.map(o=>Object.fromEntries(s.fields.map(a=>[a.name,b_(o[a.name],a.dataTypeID)])))}};return {query:t,connect:async()=>({query:t,release:()=>{}}),end:async()=>{}}}var Bm,g_,y_,qm=b(()=>{Bm=(e,t=n=>n)=>{if(!e||e==="{}")return [];let n=e.slice(1,-1);if(n==="")return [];let r=[],s="",i=false,o=0;for(let a=0;a<n.length;a++){let l=n[a];l==='"'&&n[a-1]!=="\\"?(i=!i,s+=l):l==="{"&&!i?(o++,s+=l):l==="}"&&!i?(o--,s+=l):l===","&&!i&&o===0?(r.push(t(s)),s=""):s+=l;}return s!==""&&r.push(t(s)),r},g_=e=>e==="NULL"?null:e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/\\(.)/g,"$1"):e,y_=e=>e==="NULL"?null:Number.parseInt(e,10);});async function Gm(){try{let[{extract:e},{plan:t},{segmentActions:n}]=await Promise.all([import('@supabase/pg-delta/extract'),import('@supabase/pg-delta/plan'),import('@supabase/pg-delta/apply')]);return {extract:e,plan:t,segmentActions:n}}catch(e){throw new Error("Postgres schema diffing requires pg-delta to be available.",{cause:e})}}function Wm(e){let t=[...e.assumedRoles??[]],n=[{match:{all:[{kind:"acl"},{idField:{field:"grantee",glob:"postgres"}}]},action:"exclude"},{match:{all:[{verb:["link","unlink"]},{edgeTo:{edgeKind:"owner"}}]},action:"exclude"}];return t.length>0&&n.push({match:{all:[{kind:"role"},{name:t}]},action:"exclude"}),e.only?n.push({match:{not:{any:Hm(e.only)}},action:"exclude"}):e.exclude?.length&&n.push({match:{any:Hm(e.exclude)},action:"exclude"}),{id:"supabase-lite",filter:n,assumedRoles:["postgres",...t]}}function Hm(e){let t=[...e];return [{all:[{kind:"schema"},{name:t}]},{schema:t},{target:{schema:t}}]}function Vm(e,t){return e.segmentActions(t.actions).map(n=>({transactional:n.transactional,statements:t.actions.slice(n.start,n.end).map(r=>r.sql)}))}function Km(e){return e.preamble.filter(t=>t.name!=="search_path").map(t=>`SET LOCAL ${t.name} = ${w_(t.value)}`)}function w_(e){return `'${e.replace(/'/g,"''")}'`}function zm(e){let t=[];for(let n of e.actions)n.dataLoss==="destructive"&&t.push(S_(n));return t}function S_(e){for(let t of e.destroys)if(t.kind==="table")return {table:jl(t.schema,t.name),reason:"drop table"};for(let t of e.destroys)if(t.kind==="column")return {table:jl(t.schema,t.table),reason:`drop column ${t.name}`};for(let t of e.destroys)if(t.kind==="sequence")return {table:jl(t.schema,t.name),reason:"drop sequence"};return {table:"unknown",reason:e.sql}}function jl(e,t){return e==="public"?t:`${e}.${t}`}var Xm=b(()=>{});function x_(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`(?<![\\w$])"?${n}"?\\.`);return e.some(s=>r.test(s))}function Ym(e,t){let n=new Set;for(let r of t)for(let s of r.matchAll(__))n.add(s[1]);return e.facts().filter(r=>r.id.kind==="schema").map(r=>r.id.name).filter(r=>!E_.has(r)&&!n.has(r)&&x_(t,r)).map(r=>`CREATE SCHEMA IF NOT EXISTS "${r}";`)}var E_,__,Jm=b(()=>{E_=new Set(["public","supabase_migrations"]),__=/\bCREATE\s+SCHEMA\b(?:\s+IF\s+NOT\s+EXISTS)?\s+"?([\w$]+)"?/gi;});function C_(e,t){let n=Ys(e),r=new Set([...St(e),...St(t)]);return new Set(pn.filter(s=>r.has(s)&&!n.has(s)))}function Qm(e){let t=e.trimEnd();return t.endsWith(";")?t:`${t};`}async function Zm(e,t,n=""){let r=await Gm(),{PgliteConnection:s}=await qe("@supabase/lite/pglite","pglite","@electric-sql/pglite"),i=new s,o=new s;try{let a=C_(e,t),l=St(t);await i.exec(wt(a)),await o.exec(wt(l)),i.config.baseSchema&&await i.exec(i.config.baseSchema),o.config.baseSchema&&await o.exec(o.config.baseSchema),n.trim()&&(await i.exec(n),await o.exec(n)),e.trim()&&await i.exec(e),t.trim()&&await o.exec(t);let{factBase:c}=await r.extract(Dl(i)),{factBase:p}=await r.extract(Dl(o)),u=r.plan(c,p,{policy:Wm({assumedRoles:sm(t)})});if(u.actions.length===0)return [];if(u.safetyReport.destructiveActions>0)throw new DataLossError(zm(u));let f=Vm(r,u),h=Ym(p,f.flatMap(m=>m.statements)),d=Km(u).map(Qm);return f.map((m,g)=>[...d,...g===0?h:[],...m.statements.map(Qm)].join(`
206
+ `)}${i}`}async function Z(e){try{await e();}catch(t){if(Cn(t))throw t;(process.env.LOCAL||process.env.DEBUG)&&console.error(t),Y.error(String(t)),process.exit(1);}process.exit(0);}var ld,De=b(()=>{ld=K(X());rt();Ql();});function rx(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(n=>!Number.isNaN(n)):e;case 1002:case 1009:case 1015:return typeof e=="string"?ud(e,tx):e;case 1005:case 1007:case 1016:return typeof e=="string"?ud(e,nx):e;default:return e}}function Zl(e){let t=async(n,r)=>{let s=await e.driver.query(n,r?[...r]:[]);return {rows:s.rows.map(o=>Object.fromEntries(s.fields.map(a=>[a.name,rx(o[a.name],a.dataTypeID)])))}};return {query:t,connect:async()=>({query:t,release:()=>{}}),end:async()=>{}}}var ud,tx,nx,pd=b(()=>{ud=(e,t=n=>n)=>{if(!e||e==="{}")return [];let n=e.slice(1,-1);if(n==="")return [];let r=[],s="",i=false,o=0;for(let a=0;a<n.length;a++){let l=n[a];l==='"'&&n[a-1]!=="\\"?(i=!i,s+=l):l==="{"&&!i?(o++,s+=l):l==="}"&&!i?(o--,s+=l):l===","&&!i&&o===0?(r.push(t(s)),s=""):s+=l;}return s!==""&&r.push(t(s)),r},tx=e=>e==="NULL"?null:e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/\\(.)/g,"$1"):e,nx=e=>e==="NULL"?null:Number.parseInt(e,10);});async function md(){try{let[{extract:e},{plan:t},{segmentActions:n}]=await Promise.all([import('@supabase/pg-delta/extract'),import('@supabase/pg-delta/plan'),import('@supabase/pg-delta/apply')]);return {extract:e,plan:t,segmentActions:n}}catch(e){throw new Error("Postgres schema diffing requires pg-delta to be available.",{cause:e})}}function dd(e){let t=[...e.assumedRoles??[]],n=[{match:{all:[{kind:"acl"},{idField:{field:"grantee",glob:"postgres"}}]},action:"exclude"},{match:{all:[{verb:["link","unlink"]},{edgeTo:{edgeKind:"owner"}}]},action:"exclude"}];return t.length>0&&n.push({match:{all:[{kind:"role"},{name:t}]},action:"exclude"}),e.only?n.push({match:{not:{any:fd(e.only)}},action:"exclude"}):e.exclude?.length&&n.push({match:{any:fd(e.exclude)},action:"exclude"}),{id:"supabase-lite",filter:n,assumedRoles:["postgres",...t]}}function fd(e){let t=[...e];return [{all:[{kind:"schema"},{name:t}]},{schema:t},{target:{schema:t}}]}function hd(e,t){return e.segmentActions(t.actions).map(n=>({transactional:n.transactional,statements:t.actions.slice(n.start,n.end).map(r=>r.sql)}))}function gd(e){return e.preamble.filter(t=>t.name!=="search_path").map(t=>`SET LOCAL ${t.name} = ${sx(t.value)}`)}function sx(e){return `'${e.replace(/'/g,"''")}'`}function yd(e){let t=[];for(let n of e.actions)n.dataLoss==="destructive"&&t.push(ix(n));return t}function ix(e){for(let t of e.destroys)if(t.kind==="table")return {table:ec(t.schema,t.name),reason:"drop table"};for(let t of e.destroys)if(t.kind==="column")return {table:ec(t.schema,t.table),reason:`drop column ${t.name}`};for(let t of e.destroys)if(t.kind==="sequence")return {table:ec(t.schema,t.name),reason:"drop sequence"};return {table:"unknown",reason:e.sql}}function ec(e,t){return e==="public"?t:`${e}.${t}`}var bd=b(()=>{});function lx(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`(?<![\\w$])"?${n}"?\\.`);return e.some(s=>r.test(s))}function wd(e,t){let n=new Set;for(let r of t)for(let s of r.matchAll(ax))n.add(s[1]);return e.facts().filter(r=>r.id.kind==="schema").map(r=>r.id.name).filter(r=>!ox.has(r)&&!n.has(r)&&lx(t,r)).map(r=>`CREATE SCHEMA IF NOT EXISTS "${r}";`)}var ox,ax,Sd=b(()=>{ox=new Set(["public","supabase_migrations"]),ax=/\bCREATE\s+SCHEMA\b(?:\s+IF\s+NOT\s+EXISTS)?\s+"?([\w$]+)"?/gi;});function ux(e,t){let n=yi(e),r=new Set([...$t(e),...$t(t)]);return new Set(Sn.filter(s=>r.has(s)&&!n.has(s)))}function Ed(e){let t=e.trimEnd();return t.endsWith(";")?t:`${t};`}async function _d(e,t,n=""){let r=await md(),{PgliteConnection:s}=await We("@supabase/lite/pglite","pglite","@electric-sql/pglite"),i=new s,o=new s;try{let a=ux(e,t),l=$t(t);await i.exec(At(a)),await o.exec(At(l)),i.config.baseSchema&&await i.exec(i.config.baseSchema),o.config.baseSchema&&await o.exec(o.config.baseSchema),n.trim()&&(await i.exec(n),await o.exec(n)),e.trim()&&await i.exec(e),t.trim()&&await o.exec(t);let{factBase:c}=await r.extract(Zl(i)),{factBase:p}=await r.extract(Zl(o)),u=r.plan(c,p,{policy:dd({assumedRoles:$m(t)})});if(u.actions.length===0)return [];if(u.safetyReport.destructiveActions>0)throw new DataLossError(yd(u));let f=hd(r,u),h=wd(p,f.flatMap(d=>d.statements)),m=gd(u).map(Ed);return f.map((d,g)=>[...m,...g===0?h:[],...d.statements.map(Ed)].join(`
200
207
 
201
- `))}finally{await i.close().catch(()=>{}),await o.close().catch(()=>{});}}var ed=b(()=>{tn();qm();Xm();Jm();Sr();});async function bi(e){let{parse:t}=await import('pgsql-parser');return t(e)}var td=b(()=>{});var wi,nd=b(()=>{an();Dt();wi=class{constructor(t){this.ast=t;this.result=[...this.walk(this.ast,[],{trackPaths:["returningList"]})];}result=[];*walk(t=this.ast,n=[],r={}){if(!t||typeof t!="object")return;let{trackPaths:s=[]}=r;if(Array.isArray(t)){for(let o=0;o<t.length;o++)yield*this.walk(t[o],n,r);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:n},yield*this.walk(t[o],[...n,o],r);}else for(let[o,a]of Object.entries(t))if(a&&typeof a=="object"){let l=s.includes(o)?[...n,o]:n;yield*this.walk(a,l,r);}}containsUnsupportedNode(){for(let{node:t}of this.result){let n=on(t),r=Ms.get(n);if(r&&r.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(n=>n.String?.sval||n.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:n})=>"A_Star"in n);if(t.length===0)return false;for(let{path:n}of t)if(!n.includes("SelectStmt")&&!n.includes("returningList"))return true;return false}getRelationDefinitions(){return this.result.filter(({node:n})=>"CreateStmt"in n).map(({node:n})=>n.CreateStmt).map(n=>({relation:{relname:n.relation?.relname??"",inh:n.relation?.inh,relpersistence:n.relation?.relpersistence},columns:n.tableElts?.map(r=>{let s=r.ColumnDef?.typeName?.names?.map(o=>"String"in o?o.String.sval:""),i=s?.some(o=>o.toLowerCase().includes("pg_catalog"));return {name:r.ColumnDef?.colname??"",is_local:r.ColumnDef?.is_local,pg_catalog:i,type:s?.filter(o=>!o.toLowerCase().includes("pg_catalog"))[0]??"",types:s,constraints:r.ColumnDef?.constraints}})}))}getRelationColumnTypes(){return {has_non_pg_catalog_types:this.getRelationDefinitions().some(t=>t.columns?.some(n=>!n.pg_catalog)),types:Array.from(new Set(this.getRelationDefinitions().flatMap(t=>t.columns?.map(n=>n.type))))}}};});var A_,$_,v_,R_,yn,Si,rd=b(()=>{an();A_=["DECLARE","IF","ELSIF","ELSE","LOOP","WHILE","FOR","FOREACH","EXCEPTION","RAISE","PERFORM","EXECUTE","SELECT"],$_=/^NEW\.(\w+)\s*(?::=|=)\s*(.+)$/is,v_=/^RETURN\s+(NEW|OLD)$/i,R_=/^(INSERT|UPDATE|DELETE)\b/i,yn=class extends jt{constructor(n,r,s){super(s??`Unsupported PL/pgSQL: ${n}`);this.hint=n;this.body=r;}},Si=class{parse(t){let n=this.extractBlock(t),r=this.splitStatements(n),s=[],i=null;for(let o of r){let a=o.trim();if(!a)continue;this.rejectUnsupported(a);let l=a.match(v_);if(l){i=l[1].toUpperCase(),s.push({type:"return",value:i});continue}let c=a.match($_);if(c){s.push({type:"assignment",column:c[1],expression:c[2].trim()});continue}if(R_.test(a)){s.push({type:"dml",sql:a});continue}throw new yn(`"${a.substring(0,80)}" is not translatable to SQLite`,n)}if(!i)throw new jt("Trigger function body must end with RETURN NEW or RETURN OLD");return {statements:s,returnValue:i}}extractBlock(t){let n=t.trim(),r=n.toUpperCase();if(/^\s*DECLARE\b/i.test(n))throw new yn('"DECLARE" is not translatable to SQLite',t);let s=r.indexOf("BEGIN"),i=r.lastIndexOf("END");if(s===-1||i===-1||i<=s)throw new yn("Expected BEGIN ... END block in trigger function body",t);return n.slice(s+5,i).trim()}splitStatements(t){let n=[],r="",s=0,i=false,o="";for(let l=0;l<t.length;l++){let c=t[l];if(i){r+=c,c===o&&(l+1<t.length&&t[l+1]===o?r+=t[++l]:i=false);continue}if(c==="'"||c==='"'){i=true,o=c,r+=c;continue}if(c==="("){s++,r+=c;continue}if(c===")"){s--,r+=c;continue}if(c===";"&&s===0){n.push(r.trim()),r="";continue}r+=c;}let a=r.trim();return a&&n.push(a),n}rejectUnsupported(t){let n=t.match(/^(\w+)/)?.[1]?.toUpperCase();if(n&&A_.includes(n))throw new yn(`"${n}" is not translatable to SQLite`,t)}};});var Ei,_i=b(()=>{Ei=class extends Error{constructor(n){super(`Migration would cause data loss:
202
- ${n.map(r=>` - ${r.table}: ${r.reason}`).join(`
203
- `)}`);this.warnings=n;this.name="DataLossError";}};});function k_(e,t){if(e.includes(sd)||t.includes(sd))return true;let n=fo(e),r=fo(t);return !n||!r?os(e)!==os(t):[...n].sort().join("\0")!==[...r].sort().join("\0")}var sd,xi,id=b(()=>{kt();sd="/* modified */";xi=class{makeIndexKey(t){return `${t.table}:${t.name}:${t.unique}:${t.columns.join(",")}`}makeForeignKeyKey(t){let n=(t.on_update??"NO ACTION").toUpperCase(),r=(t.on_delete??"NO ACTION").toUpperCase();return `${t.table}:${t.column}:${t.ref_table}:${t.ref_column}:${n}:${r}`}diff(t,n){let r=[],s=[],i=[],o=[],a=new Set(t.tables.map(m=>m.name)),l=new Set(n.tables.map(m=>m.name));for(let m of n.tables)a.has(m.name)||r.push({type:"added",name:m.name,sql:m.sql});for(let m of t.tables)l.has(m.name)||r.push({type:"removed",name:m.name});for(let m of t.tables){let g=n.tables.find(y=>y.name===m.name);g&&k_(m.sql,g.sql)&&r.push({type:"modified",name:m.name,sql:g.sql});}let c=t.tables.filter(m=>l.has(m.name));for(let m of c){let g=t.columns.filter(C=>C.table===m.name),y=n.columns.filter(C=>C.table===m.name),E=new Map(g.map(C=>[C.name,C])),A=new Map(y.map(C=>[C.name,C]));for(let[C,v]of A)E.has(C)||s.push({type:"added",table:m.name,name:C,column:v});for(let[C]of E)A.has(C)||s.push({type:"removed",table:m.name,name:C});for(let[C,v]of E){let $=A.get(C);if(!$)continue;let T={};po(v.type)!==po($.type)&&(T.type={from:v.type,to:$.type}),!(v.is_primary_key&&$.is_primary_key)&&v.nullable!==$.nullable&&(T.nullable={from:v.nullable,to:$.nullable}),mo(v.default_value)!==mo($.default_value)&&(T.default_value={from:v.default_value,to:$.default_value}),Object.keys(T).length>0&&s.push({type:"modified",table:m.name,name:C,changes:T});}}let p=new Map(t.indexes.map(m=>[this.makeIndexKey(m),m])),u=new Map(n.indexes.map(m=>[this.makeIndexKey(m),m]));for(let[m,g]of u)p.has(m)||i.push({type:"added",...g});for(let[m,g]of p)u.has(m)||i.push({type:"removed",...g});let f=new Map(t.foreign_keys.map(m=>[this.makeForeignKeyKey(m),m])),h=new Map(n.foreign_keys.map(m=>[this.makeForeignKeyKey(m),m]));for(let[m,g]of h)f.has(m)||o.push({type:"added",...g});for(let[m,g]of f)h.has(m)||o.push({type:"removed",...g});let d=r.length>0||s.length>0||i.length>0||o.length>0;return {tables:r,columns:s,indexes:i,foreign_keys:o,has_changes:d}}};});var P_,Ti,od=b(()=>{_i();Pn();P_=["CURRENT_TIMESTAMP","CURRENT_TIME","CURRENT_DATE"],Ti=class{plan(t,n,r,s){if(!t.has_changes)return {steps:[],warnings:[],unsafe:false};let i=[],o=[];i.push({sql:"PRAGMA foreign_keys=OFF;",description:"Disable foreign key checks",type:"disable_foreign_keys"}),i.push({sql:"BEGIN;",description:"Begin transaction",type:"begin_transaction"});for(let u of t.tables.filter(f=>f.type==="added")){i.push({sql:`${u.sql};`,description:`CREATE TABLE ${U(u.name)}`,type:"create_table"});let f=r.indexes.filter(h=>h.table===u.name);for(let h of f){let d=h.unique?"UNIQUE ":"",m=h.columns.map(g=>U(g)).join(", ");i.push({sql:`CREATE ${d}INDEX ${U(h.name)} ON ${U(u.name)} (${m});`,description:`Create index ${U(h.name)} on ${U(u.name)}`,type:"add_index"});}}let a=new Set(n.tables.map(u=>u.name)),l=new Set(r.tables.map(u=>u.name)),c=new Set(t.tables.filter(u=>u.type==="modified").map(u=>u.name)),p=[...a].filter(u=>l.has(u));for(let u of p){if(!(c.has(u)||t.columns.some(m=>m.table===u)||t.indexes.some(m=>m.table===u)||t.foreign_keys.some(m=>m.table===u)))continue;let{canAlter:h,addedCols:d}=this.canSimpleAlter(u,t,r);if(h){for(let y of d)i.push({sql:`ALTER TABLE ${U(u)} ADD COLUMN ${this.columnDef(y)};`,description:`Add column ${U(y.name)} to ${U(u)}`,type:"add_column"});let m=t.indexes.filter(y=>y.table===u&&y.type==="added"),g=t.indexes.filter(y=>y.table===u&&y.type==="removed");for(let y of g)i.push({sql:`DROP INDEX IF EXISTS ${U(y.name)};`,description:`Drop index ${U(y.name)}`,type:"drop_index"});for(let y of m){let E=y.unique?"UNIQUE ":"",A=y.columns.map(C=>U(C)).join(", ");i.push({sql:`CREATE ${E}INDEX ${U(y.name)} ON ${U(u)} (${A});`,description:`Create index ${U(y.name)} on ${U(u)}`,type:"add_index"});}}else {let m=this.rebuildTable(u,n,r,t);i.push(...m.steps),o.push(...m.warnings);}}for(let u of t.tables.filter(f=>f.type==="removed"))i.push({sql:`DROP TABLE ${U(u.name)};`,description:`Drop table ${U(u.name)}`,type:"drop_table"}),o.push({table:u.name,reason:"table will be dropped"});return i.push({sql:"COMMIT;",description:"Commit transaction",type:"commit_transaction"}),i.push({sql:"PRAGMA foreign_keys=ON;",description:"Re-enable foreign key checks",type:"enable_foreign_keys"}),{steps:i,warnings:o,unsafe:o.length>0}}rebuildTable(t,n,r,s){let i=[],o=[],a=r.tables.find(y=>y.name===t);if(!a)return {steps:i,warnings:o};let l=`_${t}_migrate_new`,c=a.sql.replace(new RegExp(`(CREATE\\s+TABLE\\s+)(?:"${t}"|${t})`,"i"),`$1${U(l)}`);i.push({sql:`${c};`,description:`Create temporary table ${U(l)}`,type:"create_table"});let p=n.columns.filter(y=>y.table===t).map(y=>y.name),u=r.columns.filter(y=>y.table===t).map(y=>y.name),f=p.filter(y=>u.includes(y));if(f.length>0){let y=f.map(E=>U(E)).join(", ");i.push({sql:`INSERT INTO ${U(l)} (${y})
204
- SELECT ${y}
205
- FROM ${U(t)};`,description:`Copy data from ${U(t)} to ${U(l)}`,type:"copy_data"});}i.push({sql:`DROP TABLE ${U(t)};`,description:`Drop old table ${U(t)}`,type:"drop_table"}),i.push({sql:`ALTER TABLE ${U(l)} RENAME TO ${U(t)};`,description:`Rename ${U(l)} to ${U(t)}`,type:"rename_table"});let h=r.indexes.filter(y=>y.table===t);for(let y of h){let E=y.unique?"UNIQUE ":"",A=y.columns.map(C=>U(C)).join(", ");i.push({sql:`CREATE ${E}INDEX ${U(y.name)} ON ${U(t)} (${A});`,description:`Recreate index ${U(y.name)} on ${U(t)}`,type:"add_index"});}let d=r.triggers?.filter(y=>y.table===t)??[];for(let y of d)i.push({sql:`${y.sql};`,description:`Recreate trigger ${U(y.name)} on ${U(t)}`,type:"create_trigger"});let m=s.columns.filter(y=>y.table===t&&y.type==="removed");for(let y of m)o.push({table:t,reason:`column "${y.name}" will be dropped`});let g=s.columns.filter(y=>y.table===t&&y.type==="modified");for(let y of g)y.changes?.type&&o.push({table:t,reason:`column "${y.name}" type changes from ${y.changes.type.from} to ${y.changes.type.to}`}),y.changes?.nullable&&!y.changes.nullable.to&&o.push({table:t,reason:`column "${y.name}" becomes NOT NULL`});return {steps:i,warnings:o}}canSimpleAlter(t,n,r){let s=n.columns.filter(u=>u.table===t),i=s.filter(u=>u.type==="added"),o=s.filter(u=>u.type==="removed"),a=s.filter(u=>u.type==="modified"),l=n.foreign_keys.some(u=>u.table===t);if(o.length>0||a.length>0||l)return {canAlter:false,addedCols:i};let c=r.tables.find(u=>u.name===t);return c&&/\bCHECK\s*\(/i.test(c.sql)?{canAlter:false,addedCols:i}:{canAlter:i.every(u=>{let f=u.column;return this.hasNonConstantDefault(f.default_value)?false:f.nullable||f.default_value!=null})&&i.length>0,addedCols:i}}hasNonConstantDefault(t){if(t==null)return false;let n=t.trim().toUpperCase();return P_.includes(n)}columnDef(t){let n=t.column,r=`${U(n.name)} ${n.type||"TEXT"}`;return n.nullable||(r+=" NOT NULL"),n.default_value!=null&&(r+=` DEFAULT ${n.default_value}`),r}};});function j_(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"&&D_.has(t.objtype)}function ad(e){return e?.String?.sval}var D_,Fl,Ci,ld=b(()=>{an();Vs();Dt();Dt();nd();ct();rd();_i();id();od();Pn();qa();Ga();D_=new Set(["OBJECT_TABLE","OBJECT_VIEW","OBJECT_SEQUENCE","OBJECT_SCHEMA"]);Fl=new Set(["plpgsql","pgcrypto","uuid-ossp"]);Ci=class extends Deparser{enums;schemaHandling;warnings=[];helper;config;triggerFunctions=new Map;plpgsqlParser=new Si;introspection;functionResolution;serialColumns;constructor(t,{enums:n,schemaHandling:r,introspection:s,serialColumns:i,...o}={}){super(t,o),this.schemaHandling=r??"default",this.enums=n??new Map,this.helper=new wi(t),this.config=o,this.introspection=s,this.functionResolution=o?.functionResolution??"translate",this.serialColumns=i??new WeakSet;}visit(t,n){let r=on(t);if(r==="GrantStmt"&&j_(t))return "";let s=t.AlterObjectSchemaStmt;if(r==="AlterObjectSchemaStmt"&&s?.objectType==="OBJECT_EXTENSION"){let o=ad(s.object);if(o&&Fl.has(o))return "";throw new M({[r]:t},"ALTER EXTENSION is not supported in SQLite")}if(r==="AlterExtensionStmt"||r==="AlterExtensionContentsStmt")throw new M({[r]:t},"ALTER EXTENSION is not supported in SQLite");let i=Ms.get(r);if(i){if(i.react==="error")throw new M({[r]:t},`Unsupported node type: ${r}`);return i.react==="warn"&&this.warnings.push({type:r,node:t}),""}return super.visit(t,n)}CreateExtensionStmt(t,n){let r=t.extname??"";if(Fl.has(r))return "";throw new M({CreateExtensionStmt:t},`CREATE EXTENSION ${JSON.stringify(r)} is not supported in SQLite`)}deparse(t,n){if(t==null)return null;if(!n){let r=new SqlFormatter;n=new DeparserContext({formatter:r});}return typeof t=="number"||t instanceof Number?t.toString():this.visit(t,n)}RawStmt(t,n){if(!t.stmt||t.stmt.CommentStmt)return "";let r=this.deparse(t.stmt,n);return !r||r.length===0?"":t.stmt_len?r+";":r}RangeVar(t,n){this.ensureRelation(t);let r=this.effectiveSchema(t.schemaname),s=t.relname,i=this.quoteBareIfNeeded(s);r&&(this.schemaHandling==="prefix"?i=`${r}__${s}`:i=`"${r}.${s}"`);let o=t.alias?" "+this.Alias(t.alias,n):"";return i+o}getRelationName(t){this.ensureRelation(t);let n=this.effectiveSchema(t.schemaname),r=t.relname;return n?this.schemaHandling==="prefix"?`${n}__${r}`:`${n}.${r}`:r}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 n=this.config.forceDefaultSchema;n&&(!t||typeof t!="object"||n.length===0||t.schemaname||(t.schemaname=n));}CreateStmt(t,n){if(t.inhRelations&&t.inhRelations.length>0)throw new M({CreateStmt:t},"Inheritance is not supported in SQLite");if(t.ofTypename!==void 0)throw new M({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 M({CreateStmt:t},"Empty tables are not supported in SQLite. Define at least one column.");return t.accessMethod&&(t.accessMethod=void 0),super.CreateStmt(t,n)+" STRICT"}TableLikeClause(t,n){throw new M({TableLikeClause:t},"CREATE TABLE ... (LIKE ...) is not supported in SQLite. Define the table columns explicitly instead.")}DefElem(t,n){if(["oids","fillfactor",/^autovacuum_/i,"toast_tuple_target","parallel_workers","user_catalog_table"].some(i=>Uc(t.defname??"",i)))return "";let s=super.DefElem(t,n);throw new M({DefElem:t},`DefElem "${t.defname}" (${s}) not supported`)}TypeName(t,n){if(!t.names)return "";let r=t.names.map(i=>i.String?i.String.sval||i.String.str:"").filter(Boolean);if(r.length===0)return "";let s=r.length===2&&r[0]==="pg_catalog"?r[1]:r.join(".");return t.arrayBounds&&t.arrayBounds.length>0||ln(this.enums,s)?"TEXT":Af(s)}ColumnDef(t,n){let r=[],s=t.colname;s&&r.push(this.quoteIfNeeded(s));let i=false,o=false,a=null,l=null,c=null,p=false;if(t.typeName){let u=t.typeName.names?.map(d=>d.String?.sval||d.String?.str).filter(Boolean);c=u&&u.length>0?u.length===2&&u[0]==="pg_catalog"?u[1]:u.join("."):null,i=!!(c&&js(c))||this.serialColumns.has(t),p=!!(t.typeName.arrayBounds&&t.typeName.arrayBounds.length>0);let f=Array.isArray(t.typeName.typmods)?t.typeName.typmods:[],h=d=>f[d]?.A_Const?.ival?.ival??f[d]?.A_Const?.val?.ival?.ival;if(c&&Fs(c)&&f.length>0){let d=h(0);typeof d=="number"&&d>0&&(a={maxLen:d});}if(c&&Us(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);}r.push(this.TypeName(t.typeName,n));}if(t.constraints){let u=Array.isArray(t.constraints)?t.constraints:[],f=n.spawn("ColumnDef",{isColumnConstraint:true}),h=u.map(m=>this.visit(m,f));r.push(...h.filter(Boolean));let d=u.some(m=>m.Constraint?.contype==="CONSTR_CHECK");i&&o&&!d?r.push("AUTOINCREMENT"):i&&!o&&this.warnings.push({type:"ColumnDef",node:{ColumnDef:t},message:`Column "${s}" is serial/auto-increment but not the primary key; SQLite can't auto-increment a non-primary-key column, so it becomes a plain INTEGER (no auto-increment).`});}if(s&&c){let u={isArray:p};a&&(u.lengthConstraint=a.maxLen),l&&(u.numericPrecision=l);let f=ln(this.enums,c);f&&(u.enumValues=f);let m=Mt({schema:"public",table:"",column:s,pgTypeName:c,nullable:true,defaultValue:null,defaultFn:null,isPrimaryKey:o,isUnique:false,isSerial:i},u).checkConstraint();m&&r.push(`CHECK (${m})`);}return r.join(" ")}Constraint(t,n){let r=t.contype;if(r==="CONSTR_IDENTITY"||r==="CONSTR_ATTR_DEFERRABLE"||r==="CONSTR_ATTR_NOT_DEFERRABLE"||r==="CONSTR_ATTR_DEFERRED"||r==="CONSTR_ATTR_IMMEDIATE")return "";if(r==="CONSTR_NULL")return "NULL";if(r==="CONSTR_NOTNULL")return "NOT NULL";if(r==="CONSTR_DEFAULT"&&t.raw_expr){let s=this.unwrapConstCast(t.raw_expr),i=this.visit(s,n);return i.includes("(")&&!i.startsWith("(")?`DEFAULT (${i})`:`DEFAULT ${i}`}if(r==="CONSTR_CHECK"&&t.raw_expr){let s=[];t.conname&&s.push("CONSTRAINT",Ds(t.conname)),s.push("CHECK");let i=this.visit(t.raw_expr,n);return s.push(`(${i})`),s.join(" ")}if(r==="CONSTR_PRIMARY")return t.keys&&t.keys.length>0?`PRIMARY KEY (${ht(t.keys).map(i=>this.visit(i,n)).join(", ")})`:"PRIMARY KEY";if(r==="CONSTR_UNIQUE")return t.keys&&t.keys.length>0?`UNIQUE (${ht(t.keys).map(i=>this.visit(i,n)).join(", ")})`:"UNIQUE";if(r==="CONSTR_FOREIGN")return super.Constraint(t,n).replace(/FOREIGN\s+KEY\s+REFERENCES/gi,"REFERENCES");if(r==="CONSTR_GENERATED"&&t.raw_expr)return `GENERATED ALWAYS AS (${this.visit(t.raw_expr,n)}) STORED`;if(r==="CONSTR_EXCLUSION")throw new M({Constraint:t},"EXCLUSION constraints are not supported in SQLite");return ""}FuncCall(t,n){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],n)})`}let a=(t.args??[]).map(c=>this.visit(c,n));if(t.agg_star)return `${i}(*)`;if(t.agg_distinct)return `${i}(DISTINCT ${a.join(", ")})`;let l=Ha(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=Gs[i];if(c?.sqlite){let p=c.sqlite();return p.includes("(")?p:`${p}(${a.join(", ")})`}}}throw new M({FuncCall:t},`Function call "${i}" not supported`)}SQLValueFunction(t,n){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 M({SQLValueFunction:t},`SQLValueFunction "${t.op}" not supported`)}}ResTarget(t,n){if(t.indirection&&t.indirection.length>0)throw new M({ResTarget:t},"Indirections are not supported in SQLite");let r=[];return n.update&&t.name?(r.push(this.quoteIfNeeded(t.name)),r.push("="),t.val&&r.push(this.deparse(t.val,n))):n.insertColumns&&t.name?r.push(this.quoteIfNeeded(t.name)):(t.val&&r.push(this.deparse(t.val,n)),t.name&&r.push(this.Alias({aliasname:t.name},n))),r.join(" ")}A_Expr(t,n){if(t.kind==="AEXPR_OP_ANY"&&(t.name?.[0]?.String?.sval||t.name?.[0]?.String?.str)==="="&&t.lexpr&&t.rexpr&&"A_ArrayExpr"in t.rexpr){let s=ht(t.rexpr.A_ArrayExpr.elements),i=this.tryFoldConstArrayElements(s,n);if(i!==void 0)return `${this.visit(t.lexpr,n)} IN (${i.join(", ")})`}if(["AEXPR_OP_ALL","AEXPR_OP_ANY"].includes(t.kind))throw new M({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 M({A_Expr:t},"Schema-qualified OPERATOR() syntax is not supported in SQLite");let r=t.name[0]?.String?.sval||t.name[0]?.String?.str;if(r){if(!t.lexpr||!t.rexpr)throw new M({A_Expr:t},"A_Expr missing left or right expression");if(!Cf.includes(r.toUpperCase()))throw new M({A_Expr:t},`Operator "${r}" is not supported in SQLite`);if(r==="~~"||r==="~~*"){let s=this.visit(t.lexpr,n),i=this.visit(t.rexpr,n);return `${s} LIKE ${i}`}if(r==="!~~"||r==="!~~*"){let s=this.visit(t.lexpr,n),i=this.visit(t.rexpr,n);return `${s} NOT LIKE ${i}`}if(r==="~"||r==="~*"){let s=this.visit(t.lexpr,n),i=this.visit(t.rexpr,n);return `${s} GLOB ${i}`}}}return super.A_Expr(t,n)}IndexStmt(t,n){let r=["CREATE"];t.unique&&r.push("UNIQUE"),r.push("INDEX"),t.if_not_exists&&r.push("IF NOT EXISTS"),t.idxname&&r.push(Ds(t.idxname)),r.push("ON"),t.relation&&r.push(this.RangeVar(t.relation,n));let s=(t.indexParams??[]).map(i=>"IndexElem"in i?this.IndexElem(i.IndexElem,n):this.visit(i,n)).filter(Boolean);return r.push(`(${s.join(", ")})`),r.join(" ")}IndexElem(t,n){let r=[];return t.name?r.push(Ds(t.name)):t.expr&&r.push(`(${this.visit(t.expr,n)})`),t.ordering==="SORTBY_ASC"&&r.push("ASC"),t.ordering==="SORTBY_DESC"&&r.push("DESC"),t.nulls_ordering==="SORTBY_NULLS_FIRST"&&r.push("NULLS FIRST"),t.nulls_ordering==="SORTBY_NULLS_LAST"&&r.push("NULLS LAST"),r.join(" ")}constFoldCategory(t){if(!t?.names||t.arrayBounds&&t.arrayBounds.length>0)return null;let n=t.names.map(c=>c.String?.sval||c.String?.str).filter(Boolean);if(n.length===0)return null;let r=n.length===2&&n[0]==="pg_catalog"?n[1]:n.join("."),s=r.toLowerCase().trim();return ln(this.enums,r)?"text":new Set(["bool","boolean"]).has(s)?"boolean":new Set(["int2","smallint","int4","integer","int","int8","bigint","serial","serial4","bigserial","serial8","smallserial","serial2"]).has(s)?"integer":new Set(["float4","real","float8","double precision","numeric","decimal"]).has(s)?"real":new Set(["text","varchar","character varying","char","character","bpchar","name","uuid"]).has(s)?"text":null}isFoldableCast(t,n){if(t.isnull)return true;let r=this.constFoldCategory(n);return r?"sval"in t?r==="text":"ival"in t?r==="integer":"fval"in t?r==="real":"boolval"in t?r==="boolean":false:false}findUnderlyingConst(t){let n=t;for(;"TypeCast"in n;){let r=n.TypeCast;if(!r.arg)return null;n=r.arg;}return "A_Const"in n?n.A_Const:null}unwrapConstCast(t){let n=t;for(;"TypeCast"in n;){let r=n.TypeCast;if(r.typeName?.arrayBounds&&r.typeName.arrayBounds.length>0||!r.arg)break;if("A_Const"in r.arg){if(!this.isFoldableCast(r.arg.A_Const,r.typeName))break;n=r.arg;continue}if("TypeCast"in r.arg){let s=this.findUnderlyingConst(r.arg);if(!s||!this.isFoldableCast(s,r.typeName))break;n=r.arg;continue}break}return n}tryFoldConstArrayElements(t,n){let r=[];for(let s of t){let i=this.unwrapConstCast(s);if("A_Const"in i){r.push(this.visit(i,n));continue}if(this.findUnderlyingConst(s)===null)return;r.push(this.visit(i,n));}return r}TypeCast(t,n){if(!t.arg||!t.typeName)return super.TypeCast(t,n);if([...this.helper.walk(t)].filter(({node:o})=>"A_Star"in o).length>0)throw new M({TypeCast:t},"A.* in type casts are not supported in SQLite");if(t.typeName.arrayBounds&&t.typeName.arrayBounds.length>0){if("A_Const"in t.arg&&t.arg.A_Const.sval){let o=t.arg.A_Const.sval.sval;if(o.startsWith("{")&&o.endsWith("}")){let a=t.typeName.names?.map(u=>u.String?.sval).filter(Boolean)??[],l=a.length===2&&a[0]==="pg_catalog"?a[1]:a[0],p=["text","varchar","character varying","char","bpchar","name","uuid"].includes(l?.toLowerCase());try{let u=this.parsePgArrayLiteral(o,p);return `'${JSON.stringify(u).replace(/'/g,"''")}'`}catch{}}}return this.visit(t.arg,n)}let s=this.visit(t.arg,n),i=this.TypeName(t.typeName,n);return `CAST(${s} AS ${i})`}A_ArrayExpr(t,n){let r=ht(t.elements),s=this.tryExtractStaticArray(r);return s!==void 0?`'${JSON.stringify(s).replace(/'/g,"''")}'`:`json_array(${r.map(o=>this.visit(o,n)).join(", ")})`}tryExtractStaticArray(t){let n=[];for(let r of t)if("A_ArrayExpr"in r){let s=ht(r.A_ArrayExpr.elements),i=this.tryExtractStaticArray(s);if(i===void 0)return;n.push(i);}else if("A_Const"in r){let s=r.A_Const;if(s.isnull)n.push(null);else if(s.ival)n.push(s.ival.ival);else if(s.fval)n.push(parseFloat(s.fval.fval));else if(s.sval)n.push(s.sval.sval);else if("boolval"in s)n.push(s.boolval.boolval===true);else return}else return;return n}parsePgArrayLiteral(t,n){if(!t.startsWith("{")||!t.endsWith("}"))throw new Error("Not a PG array literal");let r=t.slice(1,-1);if(r.length===0)return [];let s=[],i=0;for(;i<r.length;)if(r[i]==="{"){let o=0,a=i;for(;a<r.length;){if(r[a]==="{")o++;else if(r[a]==="}"&&(o--,o===0))break;a++;}s.push(this.parsePgArrayLiteral(r.slice(i,a+1),n)),i=a+1,r[i]===","&&i++;}else if(r[i]==='"'){let o=i+1,a="";for(;o<r.length&&r[o]!=='"';)r[o]==="\\"&&o++,a+=r[o],o++;s.push(a),i=o+1,r[i]===","&&i++;}else {let o=i;for(;o<r.length&&r[o]!==","&&r[o]!=="}";)o++;if(o===i)throw new Error("Malformed PG array literal");let a=r.slice(i,o);if(a==="NULL")s.push(null);else if(n)s.push(a);else {let l=Number(a);s.push(isNaN(l)?a:l);}i=o,r[i]===","&&i++;}return s}BetweenExpr(t,n){return super.A_Expr(t,n)}AlterTableStmt(t,n){let r=t.cmds??[],s=["AT_EnableRowSecurity","AT_ForceRowSecurity","AT_ChangeOwner"],i=r.filter(p=>"AlterTableCmd"in p&&!s.includes(p.AlterTableCmd.subtype));if(i.length===0)return "";if(!["OBJECT_TABLE","OBJECT_INDEX","OBJECT_VIEW"].includes(t.objtype))throw new M({AlterTableStmt:t},`AlterTableStmt with objtype ${t.objtype} is not supported`);let o=["AT_AddColumn","AT_DropColumn"],a=["AT_AlterColumnType","AT_SetNotNull","AT_DropNotNull","AT_ColumnDefault","AT_AddConstraint","AT_DropConstraint"],l=[],c=[];for(let p of i){let u=p.AlterTableCmd.subtype;if(o.includes(u)){let f={...t,cmds:[p]};l.push(super.AlterTableStmt(f,n));}else if(a.includes(u))c.push(p.AlterTableCmd);else throw new M({AlterTableStmt:t},`AlterTableCmd with subtype ${u} is not supported in SQLite`)}if(c.length>0){let p=this.getRelationName(t.relation);l.push(this.generateRebuildSql(p,c));}return l.join(`;
206
- `)}AlterTableCmd(t,n){if(!["AT_AddColumn","AT_DropColumn"].includes(t.subtype))throw new M({AlterTableCmd:t},`AlterTableCmd with subtype ${t.subtype} is not supported`);if(t.subtype==="AT_AddColumn"&&t.def&&"ColumnDef"in t.def){let s=this.ColumnDef(t.def.ColumnDef,n),i=n.objtype==="OBJECT_TYPE"?"ADD ATTRIBUTE":"ADD COLUMN",o=t.missing_ok?" IF NOT EXISTS":"";return `${i}${o} ${s}`}return t.subtype==="AT_DropColumn"&&t.behavior?super.AlterTableCmd({...t,behavior:void 0},n):super.AlterTableCmd(t,n)}DefineStmt(t,n){if(t.kind==="OBJECT_AGGREGATE")throw new Error("AGGREGATE definitions are not supported in SQLite");return super.DefineStmt(t,n)}InsertStmt(t,n){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},n);if(s.some(i=>i.some(o=>o===true)))throw new M({InsertStmt:t},"Insert with partial DEFAULT values is not supported")}return super.InsertStmt(t,n)}SelectStmt(t,n){if(this.helper.hasUnsafeStar())throw new M({SelectStmt:t},"Row-wise comparison using .* is not supported in SQLite. Expand to explicit per-column comparisons instead.");if(t.intoClause)throw new M({SelectStmt:t},"SELECT ... INTO clause is not supported in SQLite");if(t.distinctClause){let s=ht(t.distinctClause);if(s.length>0&&Object.keys(s[0]).length>0)throw new M({SelectStmt:t},"DISTINCT ON clause is not supported in SQLite. Use window functions instead.")}if(t.limitOffset&&!t.limitCount)throw new M({SelectStmt:t},"OFFSET without LIMIT is not supported in SQLite");let r=super.SelectStmt(t,n);if(/^SELECT\s+FROM/.test(r))throw new M({SelectStmt:t},"SELECT without a target list is not supported in SQLite");return r}JoinExpr(t,n){return t.alias&&this.Alias(t.alias,n),super.JoinExpr(t,n)}A_Const(t,n){if(t.bsval!==void 0)throw new M({A_Const:t},"Bit string literals are not supported in SQLite");let r=super.A_Const(t,n);return typeof r=="string"&&r.startsWith("E'")?r.substring(2,r.length-1):r}SortBy(t,n){if(t.sortby_dir==="SORTBY_USING"){let r=ht(t.useOp),s=r[0]?.String?.sval;if(r.length>1||!["<",">"].includes(s??""))throw new M({SortBy:t},"Only `USING <` or `USING >` are supported.");t.sortby_dir=s==="<"?"SORTBY_DESC":"SORTBY_ASC",t.useOp=void 0;}return super.SortBy(t,n)}RangeSubselect(t,n){if(t.lateral)throw new M({RangeSubselect:t},"LATERAL subqueries are not supported in SQLite");return super.RangeSubselect(t,n)}SubLink(t,n){if(["ANY_SUBLINK","ALL_SUBLINK"].includes(t.subLinkType))throw new M({SubLink:t},"ANY/ALL/SOME subqueries are not supported. Use NOT EXISTS or IN instead");if(t.subLinkType==="ARRAY_SUBLINK")throw new M({SubLink:t},"ARRAY subqueries are not supported in SQLite");return super.SubLink(t,n)}LockingClause(t,n){return ""}UpdateStmt(t,n){if(n.parentNodeTypes.includes("SelectStmt"))throw new M({UpdateStmt:t},"UPDATE ... FROM (SELECT ...) is not supported in SQLite");return super.UpdateStmt(t,n)}Alias(t,n){if(t.colnames&&t.colnames.length>0)throw new M({Alias:t},"Aliasing with column names is not supported in SQLite");return `AS "${t.aliasname}"`}CreateFunctionStmt(t,n){let r=t.options??[],s=t.returnType?.names?.map(c=>c.String?.sval).filter(Boolean).join("."),i=r.find(c=>c.DefElem?.defname==="language")?.DefElem?.arg?.String?.sval;if(s!=="trigger"||i!=="plpgsql")throw new M({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=r.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,n){let r=t.trigname,s=this.RangeVar(t.relation,n),i=t.funcname?.map(u=>u.String?.sval).filter(Boolean).pop();if(!i)throw new Error(`Trigger "${r}" has no function reference`);let o=this.triggerFunctions.get(i);if(!o)throw new M({CreateTrigStmt:t},`Trigger "${r}" references unknown function "${i}"`);let a=t.timing===2?"BEFORE":t.timing===64?"INSTEAD OF":"AFTER",l=[];if(t.events&4&&l.push("INSERT"),t.events&8&&l.push("DELETE"),t.events&16)if(t.columns?.length){let u=t.columns.map(f=>f.String?.sval).filter(Boolean);l.push(`UPDATE OF ${u.join(", ")}`);}else l.push("UPDATE");let c=l.join(" OR "),p=this.buildTriggerBody(o,s,n);return [`CREATE TRIGGER ${r}`,`${a} ${c} ON ${s}`,"FOR EACH ROW","BEGIN",...p.map(u=>` ${u};`),"END"].join(`
207
- `)}buildTriggerBody(t,n,r){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,n,r)),i.length=0),o.type==="dml"&&s.push(this.translateDml(o.sql,r));}return i.length>0&&s.push(this.buildAssignmentUpdate(i,n,r)),s}buildAssignmentUpdate(t,n,r){let s=t.map(i=>{let o=this.translateExpression(i.expression,r);return `${i.column} = ${o}`});return `UPDATE ${n} SET ${s.join(", ")} WHERE rowid = NEW.rowid`}translateExpression(t,n){try{let r=`SELECT ${t}`,s=t.trim().toLowerCase();return s==="now()"||s==="current_timestamp"?"datetime('now')":t}catch{return t}}flattenTriggerTableRef(t,n){let r=this.effectiveSchema(t);return r?this.schemaHandling==="prefix"?`${r}__${n}`:`"${r}.${n}"`:this.quoteBareIfNeeded(n)}translateDml(t,n){let r=/^(\s*)(insert\s+into|update|delete\s+from)\s+(?:"([^"]+)"|(\w+))\s*\.\s*(?:"([^"]+)"|(\w+))/i;return t=t.replace(r,(s,i,o,a,l,c,p)=>`${i}${o} ${this.flattenTriggerTableRef(a??l,c??p)}`),t.replace(/\bnow\(\)/gi,"datetime('now')").replace(/\bcurrent_timestamp\b/gi,"datetime('now')").replace(/\bgen_random_uuid\(\)/gi,this.uuidExpression()).replace(/\buuid_generate_v4\(\)/gi,this.uuidExpression())}uuidExpression(){return "lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))"}NullTest(t,n){if(t.arg?.ColumnRef?.fields?.length>1)throw new M({NullTest:t},"row-level NULL tests are not supported in SQLite");return super.NullTest(t,n)}RenameStmt(t,n){if(!t.renameType)throw new Error("RenameStmt requires renameType");if(t.renameType==="OBJECT_POLICY")return "";let r=["OBJECT_TABLE","OBJECT_VIEW","OBJECT_COLUMN"];if(t.renameType==="OBJECT_COLUMN"&&(t.relationType==="OBJECT_FOREIGN_TABLE"||t.relationType==="OBJECT_VIEW"))throw new M({RenameStmt:t},`RenameStmt with relationType ${t.relationType} is not supported`);if(!r.includes(t.renameType))throw new M({RenameStmt:t},`RenameStmt with renameType ${t.renameType} is not supported in SQLite`);return super.RenameStmt(t,n)}DropStmt(t,n){let r=t.removeType;if(r==="OBJECT_EXTENSION"){let o=t.objects?.map(ad)??[];if(o.length>0&&o.every(a=>a&&Fl.has(a)))return "";throw new M({DropStmt:t},"DROP EXTENSION is not supported in SQLite")}if(["OBJECT_TABLE","OBJECT_VIEW","OBJECT_INDEX","OBJECT_TRIGGER"].includes(r))return this.foldDropObjectSchemas(t),super.DropStmt(t,n);if(["OBJECT_POLICY"].includes(r))return "";throw new M({DropStmt:t},`DROP with removeType ${r} is not supported in SQLite`)}foldDropObjectSchemas(t){let n=t.removeType==="OBJECT_TRIGGER"?3:2;for(let r of t.objects??[]){let s=r?.List?.items;if(!Array.isArray(s)||s.length!==n)continue;let i=s[0]?.String?.sval,o=s[1]?.String?.sval;if(typeof i!="string"||typeof o!="string")continue;let a=this.effectiveSchema(i),l=a===void 0?o:this.schemaHandling==="prefix"?`${a}__${o}`:`${a}.${o}`;s.splice(0,2,{String:{sval:l}});}}generateRebuildSql(t,n){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 r=this.buildDesiredSchema(this.introspection,t,n),s=new xi,i=new Ti,o=s.diff(this.introspection,r);return o.has_changes?i.plan(o,this.introspection,r).steps.filter(l=>!["disable_foreign_keys","begin_transaction","commit_transaction","enable_foreign_keys"].includes(l.type)).map(l=>l.sql).join(`
208
- `):""}buildDesiredSchema(t,n,r){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 r){let o=s.columns.findIndex(a=>a.table===n&&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===n);a!==-1&&(s.tables[a]={...s.tables[a],sql:s.tables[a].sql+" /* modified */"});break}}}return this.rebuildTableSql(s,n),s}rebuildTableSql(t,n){let r=t.tables.findIndex(u=>u.name===n);if(r===-1)return;let s=t.columns.filter(u=>u.table===n),i=t.foreign_keys.filter(u=>u.table===n),o=t.check_constraints.filter(u=>u.table===n),a=s.map(u=>{let f=`${U(u.name)} ${u.type||"TEXT"}`;return u.is_primary_key&&(f+=" PRIMARY KEY"),u.nullable||(f+=" NOT NULL"),u.default_value!=null&&(f+=` DEFAULT ${u.default_value}`),f}),l=i.map(u=>`FOREIGN KEY (${U(u.column)}) REFERENCES ${U(u.ref_table)}(${U(u.ref_column)}) ON UPDATE ${u.on_update} ON DELETE ${u.on_delete}`),c=o.map(u=>`CHECK (${u.expression})`),p=[...a,...l,...c];t.tables[r]={...t.tables[r],sql:`CREATE TABLE ${U(n)} (${p.join(", ")}) STRICT`};}extractTypeName(t){let n=t.def?.ColumnDef;return n?.typeName?.TypeName?(n.typeName.TypeName.names??[]).map(s=>s.String?.sval).filter(Boolean).pop()??null:null}extractDefaultValue(t){if(!t.def)return null;let n=this.unwrapConstCast(t.def);if("A_Const"in n){let r=n.A_Const;return r.isnull?null:r.ival?String(r.ival.ival??0):r.fval?r.fval.fval:r.sval?`'${String(r.sval.sval).replace(/'/g,"''")}'`:"boolval"in r?r.boolval.boolval?"1":"0":null}return "Integer"in n?String(n.Integer.ival):"Float"in n?n.Float.fval:"String"in n?`'${n.String.sval}'`:null}};});function cd(e){return `${e?.schemaname??"public"}.${e?.relname??""}`}function F_(e){let t=e?.Constraint;if(!t||t.contype!=="CONSTR_DEFAULT")return false;let n=t.raw_expr?.FuncCall?.funcname;if(!Array.isArray(n))return false;let r=n.map(s=>s.String?.sval??s.String?.str).filter(Boolean);return r[r.length-1]?.toLowerCase()==="nextval"}function U_(e){return (Array.isArray(e.constraints)?e.constraints:[]).some(n=>n.Constraint?.contype==="CONSTR_IDENTITY")}function ud(e,t){let n=Array.isArray(e.constraints)?e.constraints:[],r=n.filter(s=>!F_(s));r.length!==n.length?(e.constraints=r,t.add(e)):U_(e)&&t.add(e);}function M_(e,t){let n=t?.Constraint;if(!n)return false;let r=n.contype;if(r!=="CONSTR_PRIMARY"&&r!=="CONSTR_UNIQUE"&&r!=="CONSTR_FOREIGN")return false;let s=e.tableElts??[];return r==="CONSTR_PRIMARY"&&pd(e,n)||r==="CONSTR_FOREIGN"&&fd(e,n)||(s.push(t),e.tableElts=s),true}function pd(e,t){let n=(t.keys??[]).map(i=>i.String?.sval??i.String?.str).filter(Boolean);if(n.length!==1)return false;let r=(e.tableElts??[]).find(i=>"ColumnDef"in i&&i.ColumnDef.colname===n[0]);if(!r)return false;let s=Array.isArray(r.ColumnDef.constraints)?r.ColumnDef.constraints:[];return r.ColumnDef.constraints=[...s.filter(i=>i.Constraint?.contype!=="CONSTR_NOTNULL"),{Constraint:{contype:"CONSTR_PRIMARY"}}],true}function fd(e,t){let n=(t.fk_attrs??[]).map(i=>i.String?.sval??i.String?.str).filter(Boolean);if(n.length!==1)return false;let r=(e.tableElts??[]).find(i=>"ColumnDef"in i&&i.ColumnDef.colname===n[0]);if(!r)return false;let s=Array.isArray(r.ColumnDef.constraints)?r.ColumnDef.constraints:[];return r.ColumnDef.constraints=[...s,{Constraint:t}],true}function B_(e){let t=e.tableElts??[],n=t.filter(r=>{let s=r?.Constraint;return !s||s.contype!=="CONSTR_PRIMARY"?true:!pd(e,s)});n.length!==t.length&&(e.tableElts=n);}function q_(e){let t=e.tableElts??[],n=t.filter(r=>{let s=r?.Constraint;return !s||s.contype!=="CONSTR_FOREIGN"?true:!fd(e,s)});n.length!==t.length&&(e.tableElts=n);}function md(e){let t=new WeakSet,n=new Map;for(let r of e.stmts??[]){let s=r.stmt;if(!s||!("CreateStmt"in s))continue;let i=s.CreateStmt;n.set(cd(i.relation),i);for(let o of i.tableElts??[])"ColumnDef"in o&&ud(o.ColumnDef,t);B_(i),q_(i);}for(let r of e.stmts??[]){let s=r.stmt;if(!s||!("AlterTableStmt"in s))continue;let i=s.AlterTableStmt,o=n.get(cd(i.relation)),a=i.cmds??[],l=[];for(let c of a){let p=c.AlterTableCmd;p?.subtype==="AT_AddColumn"&&p.def&&"ColumnDef"in p.def&&ud(p.def.ColumnDef,t),!(o&&p?.subtype==="AT_AddConstraint"&&p.def&&M_(o,p.def))&&l.push(c);}i.cmds=l;}return t}var dd=b(()=>{});async function kr(e,t={}){let n=await bi(e);return {ast:n,...H_(n,t)}}function H_(e,t={}){let n=md(e),r=za(e),s=Ja(e,r),i=Xa(e),o=Qa(e),a=Za(e),l=new Ci(e,{...t,enums:r,serialColumns:n}),{policies:c,tables:p}=Ya(e,{defaultSchema:t.defaultSchema,validateMutations:t.strict});if(t.strict)for(let u of c){if(!s.get(`${u.data.schema??"public"}.${u.data.table}`))throw new Error(`Policy "${u.data.name}" references unknown table "${u.data.table}"`);if(!p.has(u.data.table))throw new Error(`RLS is not enabled on table "${u.data.table}"`)}return {ddl:l.deparseQuery(),enums:r,rls:{tables:p,policies:c},schema:s,vars:i,tableConstraints:o,comments:a}}var Ai=b(()=>{td();ld();dd();$a();Vs();va();});async function hd(e){if(e.trim())try{await bi(e);}catch(t){let n=t instanceof Error?t.message:String(t);throw new Ml(`Declarative schema (schemas/*.sql) is not valid SQL: ${n}`,{cause:t})}}async function Ul(e,t,n,r){if(t.trim())try{let s=t;if(n==="postgres"){let i=await e.translateDdl(t);s=typeof i=="string"?i:i.ddl??"";}for(let i of Rt(s))if(i.trim())try{await e.exec(i);}catch(o){if(!r)throw o}}catch(s){if(!r)throw s}}async function gd(e,t){if(!t.trim())return;let n=_e(e.connection);if(n==="pg")return;let r=n==="sqlite"?"sqlite":"postgres",s=await createConnection({url:":memory:",ddlDialect:r,translation:e.connection.config.translation});try{let i=e.connection.config.baseSchema;i&&await Ul(s,i,r,!0);for(let o of await De(e))await Ul(s,o.sql,r,!0);await Ul(s,t,r,!1);}finally{await s.close().catch(()=>{});}}var Ml,yd=b(()=>{Ai();kt();dt();mt();Ml=class extends Error{constructor(t,n){super(t,n),this.name="SchemaParseError";}};});var Sd={};fe(Sd,{checkPendingDeclarativeSchema:()=>wd,db:()=>Y_});function z_(){console.log(Q.default.yellow("Declarative diff includes potentially destructive changes.")),console.log(Q.default.dim("Review the schema manually and author an explicit migration for drops or other data-loss changes."));}async function wd(e,t){let n=await re(e);if(!n)return {hint:false,reason:"no-schemas"};try{let s=await e.connection.createMigrator(n).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(r){return {hint:false,reason:"diff-failed",error:r instanceof Error?r.message:String(r)}}}async function bd(e){let t=await st(e),n=await re(t);if(!n&&!t.connection.config.baseSchema){console.log(Q.default.dim("No schema files found."));return}let s=await t.connection.createMigrator(n).diff();if(typeof s.diff!="string"&&!s.diff.has_changes){console.log(Q.default.dim("Schema in sync."));return}un(s);}async function X_(e,t){if(t?.trim())return t;if(!process.stdin.isTTY){let s=await Hr();if(s.trim())return s}let n=await re(e);if(n?.trim())return n;let r=await Zn(e);if(r?.trim())return r;throw new Error("No SQL provided and no declarative schemas or migrations found to deparse.")}var Q,K_,Y_,Ed=b(()=>{Q=V(z());Le();cl();Ue();wr();dt();ed();Ee();Ye();Tt();vt();kt();Js();Ue();mt();yd();Rr();K_="Local Development:";Y_=e=>{let t=e.command("db").description("Database operations").helpGroup(K_);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 n=>{console.log(),await J(async()=>{if(await ee(n.config),!n.file){await bd(n.config);return}let r=await st(n.config),s=await re(r);if(!s.trim()){console.log(Q.default.dim("No declarative schemas found \u2014 nothing to diff."));return}await hd(s);let i=_e(r.connection);if(i==="sqlite"){console.log(Q.default.yellow('`lite db diff -f` is not supported on the bare "sqlite" driver yet.')),console.log(Q.default.dim('Declarative schema diffs require the "sqlite-postgres" driver. Set db.driver = "sqlite-postgres" in supabase/config.toml.'));return}let o;{let u=await Zn(r);try{o=await Zm(u,s,r.connection.config.baseSchema??"");}catch(f){throw f instanceof DataLossError?(z_(),new Error("Declarative diff includes potentially destructive changes.")):f}if(o=o.filter(f=>f.trim()),o.length===0){console.log(Q.default.green("Schema in sync \u2014 no migration written."));return}}let a=o.join(`
208
+ `))}finally{await i.close().catch(()=>{}),await o.close().catch(()=>{});}}var xd=b(()=>{an();pd();bd();Sd();Ir();});async function Mi(e){let{parse:t}=await import('pgsql-parser');return t(e)}var Td=b(()=>{});var Ui,Cd=b(()=>{hn();Bt();Ui=class{constructor(t){this.ast=t;this.result=[...this.walk(this.ast,[],{trackPaths:["returningList"]})];}result=[];*walk(t=this.ast,n=[],r={}){if(!t||typeof t!="object")return;let{trackPaths:s=[]}=r;if(Array.isArray(t)){for(let o=0;o<t.length;o++)yield*this.walk(t[o],n,r);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:n},yield*this.walk(t[o],[...n,o],r);}else for(let[o,a]of Object.entries(t))if(a&&typeof a=="object"){let l=s.includes(o)?[...n,o]:n;yield*this.walk(a,l,r);}}containsUnsupportedNode(){for(let{node:t}of this.result){let n=dn(t),r=li.get(n);if(r&&r.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(n=>n.String?.sval||n.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:n})=>"A_Star"in n);if(t.length===0)return false;for(let{path:n}of t)if(!n.includes("SelectStmt")&&!n.includes("returningList"))return true;return false}getRelationDefinitions(){return this.result.filter(({node:n})=>"CreateStmt"in n).map(({node:n})=>n.CreateStmt).map(n=>({relation:{relname:n.relation?.relname??"",inh:n.relation?.inh,relpersistence:n.relation?.relpersistence},columns:n.tableElts?.map(r=>{let s=r.ColumnDef?.typeName?.names?.map(o=>"String"in o?o.String.sval:""),i=s?.some(o=>o.toLowerCase().includes("pg_catalog"));return {name:r.ColumnDef?.colname??"",is_local:r.ColumnDef?.is_local,pg_catalog:i,type:s?.filter(o=>!o.toLowerCase().includes("pg_catalog"))[0]??"",types:s,constraints:r.ColumnDef?.constraints}})}))}getRelationColumnTypes(){return {has_non_pg_catalog_types:this.getRelationDefinitions().some(t=>t.columns?.some(n=>!n.pg_catalog)),types:Array.from(new Set(this.getRelationDefinitions().flatMap(t=>t.columns?.map(n=>n.type))))}}};});var px,fx,mx,dx,An,Bi,Ad=b(()=>{hn();px=["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,dx=/^(INSERT|UPDATE|DELETE)\b/i,An=class extends qt{constructor(n,r,s){super(s??`Unsupported PL/pgSQL: ${n}`);this.hint=n;this.body=r;}},Bi=class{parse(t){let n=this.extractBlock(t),r=this.splitStatements(n),s=[],i=null;for(let o of r){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(dx.test(a)){s.push({type:"dml",sql:a});continue}throw new An(`"${a.substring(0,80)}" is not translatable to SQLite`,n)}if(!i)throw new qt("Trigger function body must end with RETURN NEW or RETURN OLD");return {statements:s,returnValue:i}}extractBlock(t){let n=t.trim(),r=n.toUpperCase();if(/^\s*DECLARE\b/i.test(n))throw new An('"DECLARE" is not translatable to SQLite',t);let s=r.indexOf("BEGIN"),i=r.lastIndexOf("END");if(s===-1||i===-1||i<=s)throw new An("Expected BEGIN ... END block in trigger function body",t);return n.slice(s+5,i).trim()}splitStatements(t){let n=[],r="",s=0,i=false,o="";for(let l=0;l<t.length;l++){let c=t[l];if(i){r+=c,c===o&&(l+1<t.length&&t[l+1]===o?r+=t[++l]:i=false);continue}if(c==="'"||c==='"'){i=true,o=c,r+=c;continue}if(c==="("){s++,r+=c;continue}if(c===")"){s--,r+=c;continue}if(c===";"&&s===0){n.push(r.trim()),r="";continue}r+=c;}let a=r.trim();return a&&n.push(a),n}rejectUnsupported(t){let n=t.match(/^(\w+)/)?.[1]?.toUpperCase();if(n&&px.includes(n))throw new An(`"${n}" is not translatable to SQLite`,t)}};});function wx(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"&&bx.has(t.objtype)}function $d(e){return e?.String?.sval}function Sx(e){return e?.FuncCall?.funcname?.map(t=>t.String?.sval??t.String?.str).filter(Boolean).at(-1)?.toLowerCase()}var bx,tc,qi,Rd=b(()=>{hn();hi();Bt();Bt();Cd();gt();Ad();Ys();xa();Ta();Bn();cl();pl();bx=new Set(["OBJECT_TABLE","OBJECT_VIEW","OBJECT_SEQUENCE","OBJECT_SCHEMA"]);tc=new Set(["plpgsql","pgcrypto","uuid-ossp"]);qi=class extends Deparser{enums;schemaHandling;warnings=[];helper;config;triggerFunctions=new Map;plpgsqlParser=new Bi;introspection;functionResolution;serialColumns;storagePathTokensConstraints=new WeakSet;constructor(t,{enums:n,schemaHandling:r,introspection:s,serialColumns:i,...o}={}){super(t,o),this.schemaHandling=r??"default",this.enums=n??new Map,this.helper=new Ui(t),this.config=o,this.introspection=s,this.functionResolution=o?.functionResolution??"translate",this.serialColumns=i??new WeakSet;}visit(t,n){let r=dn(t);if(r==="GrantStmt"&&wx(t))return "";let s=t.AlterObjectSchemaStmt;if(r==="AlterObjectSchemaStmt"&&s?.objectType==="OBJECT_EXTENSION"){let o=$d(s.object);if(o&&tc.has(o))return "";throw new F({[r]:t},"ALTER EXTENSION is not supported in SQLite")}if(r==="AlterExtensionStmt"||r==="AlterExtensionContentsStmt")throw new F({[r]:t},"ALTER EXTENSION is not supported in SQLite");if(r==="AlterEnumStmt"){let o=t.AlterEnumStmt??t,a=J(o.typeName??[]),l=a.length?`${a.map(p=>dr(p)).join(".")} `:"",c=o.oldVal!==void 0?"RENAME VALUE":"ADD VALUE";throw new F({[r]:t},`ALTER TYPE ${l}${c} is not supported on sqlite-postgres yet. Recreate the type with all values, or track this change in a manual migration.`)}let i=li.get(r);if(i){if(i.react==="error")throw new F({[r]:t},`Unsupported node type: ${r}`);return i.react==="warn"&&this.warnings.push({type:r,node:t}),""}return super.visit(t,n)}CreateExtensionStmt(t,n){let r=t.extname??"";if(tc.has(r))return "";throw new F({CreateExtensionStmt:t},`CREATE EXTENSION ${JSON.stringify(r)} is not supported in SQLite`)}deparse(t,n){if(t==null)return null;if(!n){let r=new SqlFormatter;n=new DeparserContext({formatter:r});}return typeof t=="number"||t instanceof Number?t.toString():this.visit(t,n)}RawStmt(t,n){if(!t.stmt||t.stmt.CommentStmt)return "";let r=this.deparse(t.stmt,n);return !r||r.length===0?"":t.stmt_len?r+";":r}RangeVar(t,n){this.ensureRelation(t);let r=this.effectiveSchema(t.schemaname),s=t.relname,i=this.quoteBareIfNeeded(s);r&&(this.schemaHandling==="prefix"?i=`${r}__${s}`:i=`"${r}.${s}"`);let o=t.alias?" "+this.Alias(t.alias,n):"";return i+o}getRelationName(t){this.ensureRelation(t);let n=this.effectiveSchema(t.schemaname),r=t.relname;return n?this.schemaHandling==="prefix"?`${n}__${r}`:`${n}.${r}`:r}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 n=this.config.forceDefaultSchema;n&&(!t||typeof t!="object"||n.length===0||t.schemaname||(t.schemaname=n));}CreateStmt(t,n){if(t.inhRelations&&t.inhRelations.length>0)throw new F({CreateStmt:t},"Inheritance is not supported in SQLite");if(t.ofTypename!==void 0)throw new F({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 F({CreateStmt:t},"Empty tables are not supported in SQLite. Define at least one column.");if(t.accessMethod&&(t.accessMethod=void 0),t.relation?.schemaname==="storage"&&t.relation.relname==="objects")for(let s of t.tableElts??[]){let i=s.ColumnDef;if(i?.colname==="path_tokens")for(let o of i.constraints??[]){let a=o.Constraint;a?.contype==="CONSTR_GENERATED"&&Sx(a.raw_expr)==="string_to_array"&&this.storagePathTokensConstraints.add(a);}}return super.CreateStmt(t,n)+" STRICT"}TableLikeClause(t,n){throw new F({TableLikeClause:t},"CREATE TABLE ... (LIKE ...) is not supported in SQLite. Define the table columns explicitly instead.")}DefElem(t,n){if(["oids","fillfactor",/^autovacuum_/i,"toast_tuple_target","parallel_workers","user_catalog_table"].some(i=>nu(t.defname??"",i)))return "";let s=super.DefElem(t,n);throw new F({DefElem:t},`DefElem "${t.defname}" (${s}) not supported`)}TypeName(t,n){if(!t.names)return "";let r=t.names.map(i=>i.String?i.String.sval||i.String.str:"").filter(Boolean);if(r.length===0)return "";let s=r.length===2&&r[0]==="pg_catalog"?r[1]:r.join(".");return t.arrayBounds&&t.arrayBounds.length>0||Be(this.enums,s)?"TEXT":tm(s)}ColumnDef(t,n){let r=[],s=t.colname;s&&r.push(this.quoteIfNeeded(s));let i=false,o=false,a=null,l=null,c=null,p=false;if(t.typeName){let u=t.typeName.names?.map(m=>m.String?.sval||m.String?.str).filter(Boolean);c=u&&u.length>0?u.length===2&&u[0]==="pg_catalog"?u[1]:u.join("."):null,i=!!(c&&ii(c))||this.serialColumns.has(t),p=!!(t.typeName.arrayBounds&&t.typeName.arrayBounds.length>0);let f=Array.isArray(t.typeName.typmods)?t.typeName.typmods:[],h=m=>f[m]?.A_Const?.ival?.ival??f[m]?.A_Const?.val?.ival?.ival;if(c&&oi(c)&&f.length>0){let m=h(0);typeof m=="number"&&m>0&&(a={maxLen:m});}if(c&&ai(c)&&f.length>=2){let m=h(0),d=h(1);typeof m=="number"&&typeof d=="number"&&m>0&&d>=0&&(l={precision:m,scale:d});}if(t.constraints){let m=Array.isArray(t.constraints)?t.constraints:[];o=m.some(d=>d.Constraint?.contype==="CONSTR_PRIMARY"),m.some(d=>d.Constraint?.contype==="CONSTR_IDENTITY")&&(i=true);}r.push(this.TypeName(t.typeName,n));}if(t.constraints){let u=Array.isArray(t.constraints)?t.constraints:[],f=n.spawn("ColumnDef",{isColumnConstraint:true}),h=u.map(d=>this.visit(d,f));r.push(...h.filter(Boolean));let m=u.some(d=>d.Constraint?.contype==="CONSTR_CHECK");i&&o&&!m?r.push("AUTOINCREMENT"):i&&!o&&this.warnings.push({type:"ColumnDef",node:{ColumnDef:t},message:`Column "${s}" is serial/auto-increment but not the primary key; SQLite can't auto-increment a non-primary-key column, so it becomes a plain INTEGER (no auto-increment).`});}if(s&&c){let u={isArray:p};a&&(u.lengthConstraint=a.maxLen),l&&(u.numericPrecision=l);let f=Be(this.enums,c);f&&(u.enumValues=f);let d=Ie({schema:"public",table:"",column:s,pgTypeName:c,nullable:true,defaultValue:null,defaultFn:null,isPrimaryKey:o,isUnique:false,isSerial:i},u).checkConstraint();d&&r.push(`CHECK (${d})`);}return r.join(" ")}Constraint(t,n){let r=t.contype;if(r==="CONSTR_IDENTITY"||r==="CONSTR_ATTR_DEFERRABLE"||r==="CONSTR_ATTR_NOT_DEFERRABLE"||r==="CONSTR_ATTR_DEFERRED"||r==="CONSTR_ATTR_IMMEDIATE")return "";if(r==="CONSTR_NULL")return "NULL";if(r==="CONSTR_NOTNULL")return "NOT NULL";if(r==="CONSTR_DEFAULT"&&t.raw_expr){let s=this.unwrapConstCast(t.raw_expr),i=this.visit(s,n);return i.includes("(")&&!i.startsWith("(")?`DEFAULT (${i})`:`DEFAULT ${i}`}if(r==="CONSTR_CHECK"&&t.raw_expr){let s=[];t.conname&&s.push("CONSTRAINT",dr(t.conname)),s.push("CHECK");let i=this.visit(t.raw_expr,n);return s.push(`(${i})`),s.join(" ")}if(r==="CONSTR_PRIMARY")return t.keys&&t.keys.length>0?`PRIMARY KEY (${Et(t.keys).map(i=>this.visit(i,n)).join(", ")})`:"PRIMARY KEY";if(r==="CONSTR_UNIQUE")return t.keys&&t.keys.length>0?`UNIQUE (${Et(t.keys).map(i=>this.visit(i,n)).join(", ")})`:"UNIQUE";if(r==="CONSTR_FOREIGN")return super.Constraint(t,n).replace(/FOREIGN\s+KEY\s+REFERENCES/gi,"REFERENCES");if(r==="CONSTR_GENERATED"&&t.raw_expr)return this.storagePathTokensConstraints.has(t)?"":`GENERATED ALWAYS AS (${this.visit(t.raw_expr,n)}) STORED`;if(r==="CONSTR_EXCLUSION")throw new F({Constraint:t},"EXCLUSION constraints are not supported in SQLite");return ""}FuncCall(t,n){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],n)})`}let a=(t.args??[]).map(c=>this.visit(c,n));if(t.agg_star)return `${i}(*)`;if(t.agg_distinct)return `${i}(DISTINCT ${a.join(", ")})`;let l=ul(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=mi[i];if(c?.sqlite){let p=c.sqlite();return p.includes("(")?p:`${p}(${a.join(", ")})`}}}throw new F({FuncCall:t},`Function call "${i}" not supported`)}SQLValueFunction(t,n){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 F({SQLValueFunction:t},`SQLValueFunction "${t.op}" not supported`)}}ResTarget(t,n){if(t.indirection&&t.indirection.length>0)throw new F({ResTarget:t},"Indirections are not supported in SQLite");let r=[];return n.update&&t.name?(r.push(this.quoteIfNeeded(t.name)),r.push("="),t.val&&r.push(this.deparse(t.val,n))):n.insertColumns&&t.name?r.push(this.quoteIfNeeded(t.name)):(t.val&&r.push(this.deparse(t.val,n)),t.name&&r.push(this.Alias({aliasname:t.name},n))),r.join(" ")}A_Expr(t,n){if(t.kind==="AEXPR_OP_ANY"&&(t.name?.[0]?.String?.sval||t.name?.[0]?.String?.str)==="="&&t.lexpr&&t.rexpr&&"A_ArrayExpr"in t.rexpr){let s=Et(t.rexpr.A_ArrayExpr.elements),i=this.tryFoldConstArrayElements(s,n);if(i!==void 0)return `${this.visit(t.lexpr,n)} IN (${i.join(", ")})`}if(["AEXPR_OP_ALL","AEXPR_OP_ANY"].includes(t.kind))throw new F({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 F({A_Expr:t},"Schema-qualified OPERATOR() syntax is not supported in SQLite");let r=t.name[0]?.String?.sval||t.name[0]?.String?.str;if(r){if(!t.lexpr||!t.rexpr)throw new F({A_Expr:t},"A_Expr missing left or right expression");if(!em.includes(r.toUpperCase()))throw new F({A_Expr:t},`Operator "${r}" is not supported in SQLite`);if(r==="~~"||r==="~~*"){let s=this.visit(t.lexpr,n),i=this.visit(t.rexpr,n);return `${s} LIKE ${i}`}if(r==="!~~"||r==="!~~*"){let s=this.visit(t.lexpr,n),i=this.visit(t.rexpr,n);return `${s} NOT LIKE ${i}`}if(r==="~"||r==="~*"){let s=this.visit(t.lexpr,n),i=this.visit(t.rexpr,n);return `${s} GLOB ${i}`}}}return super.A_Expr(t,n)}IndexStmt(t,n){let r=["CREATE"];t.unique&&r.push("UNIQUE"),r.push("INDEX"),t.if_not_exists&&r.push("IF NOT EXISTS"),t.idxname&&r.push(dr(t.idxname)),r.push("ON"),t.relation&&r.push(this.RangeVar(t.relation,n));let s=(t.indexParams??[]).map(i=>"IndexElem"in i?this.IndexElem(i.IndexElem,n):this.visit(i,n)).filter(Boolean);return r.push(`(${s.join(", ")})`),r.join(" ")}IndexElem(t,n){let r=[];return t.name?r.push(dr(t.name)):t.expr&&r.push(`(${this.visit(t.expr,n)})`),t.ordering==="SORTBY_ASC"&&r.push("ASC"),t.ordering==="SORTBY_DESC"&&r.push("DESC"),t.nulls_ordering==="SORTBY_NULLS_FIRST"&&r.push("NULLS FIRST"),t.nulls_ordering==="SORTBY_NULLS_LAST"&&r.push("NULLS LAST"),r.join(" ")}constFoldCategory(t){if(!t?.names||t.arrayBounds&&t.arrayBounds.length>0)return null;let n=t.names.map(c=>c.String?.sval||c.String?.str).filter(Boolean);if(n.length===0)return null;let r=n.length===2&&n[0]==="pg_catalog"?n[1]:n.join("."),s=r.toLowerCase().trim();return Be(this.enums,r)?"text":new Set(["bool","boolean"]).has(s)?"boolean":new Set(["int2","smallint","int4","integer","int","int8","bigint","serial","serial4","bigserial","serial8","smallserial","serial2"]).has(s)?"integer":new Set(["float4","real","float8","double precision","numeric","decimal"]).has(s)?"real":new Set(["text","varchar","character varying","char","character","bpchar","name","uuid"]).has(s)?"text":null}isFoldableCast(t,n){if(t.isnull)return true;let r=this.constFoldCategory(n);return r?"sval"in t?r==="text":"ival"in t?r==="integer":"fval"in t?r==="real":"boolval"in t?r==="boolean":false:false}findUnderlyingConst(t){let n=t;for(;"TypeCast"in n;){let r=n.TypeCast;if(!r.arg)return null;n=r.arg;}return "A_Const"in n?n.A_Const:null}unwrapConstCast(t){let n=t;for(;"TypeCast"in n;){let r=n.TypeCast;if(r.typeName?.arrayBounds&&r.typeName.arrayBounds.length>0||!r.arg)break;if("A_Const"in r.arg){if(!this.isFoldableCast(r.arg.A_Const,r.typeName))break;n=r.arg;continue}if("TypeCast"in r.arg){let s=this.findUnderlyingConst(r.arg);if(!s||!this.isFoldableCast(s,r.typeName))break;n=r.arg;continue}break}return n}tryFoldConstArrayElements(t,n){let r=[];for(let s of t){let i=this.unwrapConstCast(s);if("A_Const"in i){r.push(this.visit(i,n));continue}if(this.findUnderlyingConst(s)===null)return;r.push(this.visit(i,n));}return r}TypeCast(t,n){if(!t.arg||!t.typeName)return super.TypeCast(t,n);if([...this.helper.walk(t)].filter(({node:o})=>"A_Star"in o).length>0)throw new F({TypeCast:t},"A.* in type casts are not supported in SQLite");if(t.typeName.arrayBounds&&t.typeName.arrayBounds.length>0){if("A_Const"in t.arg&&t.arg.A_Const.sval){let o=t.arg.A_Const.sval.sval;if(o.startsWith("{")&&o.endsWith("}")){let a=t.typeName.names?.map(u=>u.String?.sval).filter(Boolean)??[],l=a.length===2&&a[0]==="pg_catalog"?a[1]:a[0],p=["text","varchar","character varying","char","bpchar","name","uuid"].includes(l?.toLowerCase());try{let u=this.parsePgArrayLiteral(o,p);return `'${JSON.stringify(u).replace(/'/g,"''")}'`}catch{}}}return this.visit(t.arg,n)}let s=this.visit(t.arg,n),i=this.TypeName(t.typeName,n);return `CAST(${s} AS ${i})`}A_ArrayExpr(t,n){let r=Et(t.elements),s=this.tryExtractStaticArray(r);return s!==void 0?`'${JSON.stringify(s).replace(/'/g,"''")}'`:`json_array(${r.map(o=>this.visit(o,n)).join(", ")})`}tryExtractStaticArray(t){let n=[];for(let r of t)if("A_ArrayExpr"in r){let s=Et(r.A_ArrayExpr.elements),i=this.tryExtractStaticArray(s);if(i===void 0)return;n.push(i);}else if("A_Const"in r){let s=r.A_Const;if(s.isnull)n.push(null);else if(s.ival)n.push(s.ival.ival);else if(s.fval)n.push(parseFloat(s.fval.fval));else if(s.sval)n.push(s.sval.sval);else if("boolval"in s)n.push(s.boolval.boolval===true);else return}else return;return n}parsePgArrayLiteral(t,n){if(!t.startsWith("{")||!t.endsWith("}"))throw new Error("Not a PG array literal");let r=t.slice(1,-1);if(r.length===0)return [];let s=[],i=0;for(;i<r.length;)if(r[i]==="{"){let o=0,a=i;for(;a<r.length;){if(r[a]==="{")o++;else if(r[a]==="}"&&(o--,o===0))break;a++;}s.push(this.parsePgArrayLiteral(r.slice(i,a+1),n)),i=a+1,r[i]===","&&i++;}else if(r[i]==='"'){let o=i+1,a="";for(;o<r.length&&r[o]!=='"';)r[o]==="\\"&&o++,a+=r[o],o++;s.push(a),i=o+1,r[i]===","&&i++;}else {let o=i;for(;o<r.length&&r[o]!==","&&r[o]!=="}";)o++;if(o===i)throw new Error("Malformed PG array literal");let a=r.slice(i,o);if(a==="NULL")s.push(null);else if(n)s.push(a);else {let l=Number(a);s.push(isNaN(l)?a:l);}i=o,r[i]===","&&i++;}return s}BetweenExpr(t,n){return super.A_Expr(t,n)}AlterTableStmt(t,n){let r=t.cmds??[],s=["AT_EnableRowSecurity","AT_DisableRowSecurity","AT_ForceRowSecurity","AT_NoForceRowSecurity","AT_ChangeOwner"],i=r.filter(p=>"AlterTableCmd"in p&&!s.includes(p.AlterTableCmd.subtype));if(i.length===0)return "";if(!["OBJECT_TABLE","OBJECT_INDEX","OBJECT_VIEW"].includes(t.objtype))throw new F({AlterTableStmt:t},`AlterTableStmt with objtype ${t.objtype} is not supported`);let o=["AT_AddColumn","AT_DropColumn"],a=["AT_AlterColumnType","AT_SetNotNull","AT_DropNotNull","AT_ColumnDefault","AT_AddConstraint","AT_DropConstraint"],l=[],c=[];for(let p of i){let u=p.AlterTableCmd.subtype;if(o.includes(u)){let f={...t,cmds:[p]};l.push(super.AlterTableStmt(f,n));}else if(a.includes(u))c.push(p.AlterTableCmd);else throw new F({AlterTableStmt:t},`AlterTableCmd with subtype ${u} is not supported in SQLite`)}if(c.length>0){let p=this.getRelationName(t.relation);l.push(this.generateRebuildSql(p,c));}return l.join(`;
209
+ `)}AlterTableCmd(t,n){if(!["AT_AddColumn","AT_DropColumn"].includes(t.subtype))throw new F({AlterTableCmd:t},`AlterTableCmd with subtype ${t.subtype} is not supported`);if(t.subtype==="AT_AddColumn"&&t.def&&"ColumnDef"in t.def){let s=this.ColumnDef(t.def.ColumnDef,n),i=n.objtype==="OBJECT_TYPE"?"ADD ATTRIBUTE":"ADD COLUMN",o=t.missing_ok?" IF NOT EXISTS":"";return `${i}${o} ${s}`}return t.subtype==="AT_DropColumn"&&t.behavior?super.AlterTableCmd({...t,behavior:void 0},n):super.AlterTableCmd(t,n)}DefineStmt(t,n){if(t.kind==="OBJECT_AGGREGATE")throw new Error("AGGREGATE definitions are not supported in SQLite");return super.DefineStmt(t,n)}InsertStmt(t,n){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},n);if(s.some(i=>i.some(o=>o===true)))throw new F({InsertStmt:t},"Insert with partial DEFAULT values is not supported")}return super.InsertStmt(t,n)}SelectStmt(t,n){if(this.helper.hasUnsafeStar())throw new F({SelectStmt:t},"Row-wise comparison using .* is not supported in SQLite. Expand to explicit per-column comparisons instead.");if(t.intoClause)throw new F({SelectStmt:t},"SELECT ... INTO clause is not supported in SQLite");if(t.distinctClause){let s=Et(t.distinctClause);if(s.length>0&&Object.keys(s[0]).length>0)throw new F({SelectStmt:t},"DISTINCT ON clause is not supported in SQLite. Use window functions instead.")}if(t.limitOffset&&!t.limitCount)throw new F({SelectStmt:t},"OFFSET without LIMIT is not supported in SQLite");let r=super.SelectStmt(t,n);if(/^SELECT\s+FROM/.test(r))throw new F({SelectStmt:t},"SELECT without a target list is not supported in SQLite");return r}JoinExpr(t,n){return t.alias&&this.Alias(t.alias,n),super.JoinExpr(t,n)}A_Const(t,n){if(t.bsval!==void 0)throw new F({A_Const:t},"Bit string literals are not supported in SQLite");let r=super.A_Const(t,n);return typeof r=="string"&&r.startsWith("E'")?r.substring(2,r.length-1):r}SortBy(t,n){if(t.sortby_dir==="SORTBY_USING"){let r=Et(t.useOp),s=r[0]?.String?.sval;if(r.length>1||!["<",">"].includes(s??""))throw new F({SortBy:t},"Only `USING <` or `USING >` are supported.");t.sortby_dir=s==="<"?"SORTBY_DESC":"SORTBY_ASC",t.useOp=void 0;}return super.SortBy(t,n)}RangeSubselect(t,n){if(t.lateral)throw new F({RangeSubselect:t},"LATERAL subqueries are not supported in SQLite");return super.RangeSubselect(t,n)}SubLink(t,n){if(["ANY_SUBLINK","ALL_SUBLINK"].includes(t.subLinkType))throw new F({SubLink:t},"ANY/ALL/SOME subqueries are not supported. Use NOT EXISTS or IN instead");if(t.subLinkType==="ARRAY_SUBLINK")throw new F({SubLink:t},"ARRAY subqueries are not supported in SQLite");return super.SubLink(t,n)}LockingClause(t,n){return ""}UpdateStmt(t,n){if(n.parentNodeTypes.includes("SelectStmt"))throw new F({UpdateStmt:t},"UPDATE ... FROM (SELECT ...) is not supported in SQLite");return super.UpdateStmt(t,n)}Alias(t,n){if(t.colnames&&t.colnames.length>0)throw new F({Alias:t},"Aliasing with column names is not supported in SQLite");return `AS "${t.aliasname}"`}CreateFunctionStmt(t,n){let r=t.options??[],s=t.funcname?.map(p=>p.String?.sval).filter(Boolean).join(".");if(s&&new Set(["storage.foldername","storage.filename","storage.extension","storage.operation","storage.allow_only_operation","storage.allow_any_operation"]).has(s))return "";let i=t.returnType?.names?.map(p=>p.String?.sval).filter(Boolean).join("."),o=r.find(p=>p.DefElem?.defname==="language")?.DefElem?.arg?.String?.sval;if(i!=="trigger"||o!=="plpgsql")throw new F({CreateFunctionStmt:t},"Only trigger functions with LANGUAGE plpgsql are supported");let a=t.funcname?.map(p=>p.String?.sval).filter(Boolean).pop();if(!a)throw new Error("Function has no name");let l=r.find(p=>p.DefElem?.defname==="as")?.DefElem?.arg?.List?.items?.[0]?.String?.sval;if(!l)throw new Error("Function has no body");let c=this.plpgsqlParser.parse(l);return this.triggerFunctions.set(a,c),""}CreateTrigStmt(t,n){let r=t.trigname,s=this.RangeVar(t.relation,n),i=t.funcname?.map(u=>u.String?.sval).filter(Boolean).pop();if(!i)throw new Error(`Trigger "${r}" has no function reference`);let o=this.triggerFunctions.get(i);if(!o)throw new F({CreateTrigStmt:t},`Trigger "${r}" references unknown function "${i}"`);let a=t.timing===2?"BEFORE":t.timing===64?"INSTEAD OF":"AFTER",l=[];if(t.events&4&&l.push("INSERT"),t.events&8&&l.push("DELETE"),t.events&16)if(t.columns?.length){let u=t.columns.map(f=>f.String?.sval).filter(Boolean);l.push(`UPDATE OF ${u.join(", ")}`);}else l.push("UPDATE");let c=l.join(" OR "),p=this.buildTriggerBody(o,s,n);return [`CREATE TRIGGER ${r}`,`${a} ${c} ON ${s}`,"FOR EACH ROW","BEGIN",...p.map(u=>` ${u};`),"END"].join(`
210
+ `)}buildTriggerBody(t,n,r){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,n,r)),i.length=0),o.type==="dml"&&s.push(this.translateDml(o.sql,r));}return i.length>0&&s.push(this.buildAssignmentUpdate(i,n,r)),s}buildAssignmentUpdate(t,n,r){let s=t.map(i=>{let o=this.translateExpression(i.expression,r);return `${i.column} = ${o}`});return `UPDATE ${n} SET ${s.join(", ")} WHERE rowid = NEW.rowid`}translateExpression(t,n){try{let r=`SELECT ${t}`,s=t.trim().toLowerCase();return s==="now()"||s==="current_timestamp"?"datetime('now')":t}catch{return t}}flattenTriggerTableRef(t,n){let r=this.effectiveSchema(t);return r?this.schemaHandling==="prefix"?`${r}__${n}`:`"${r}.${n}"`:this.quoteBareIfNeeded(n)}translateDml(t,n){let r=/^(\s*)(insert\s+into|update|delete\s+from)\s+(?:"([^"]+)"|(\w+))\s*\.\s*(?:"([^"]+)"|(\w+))/i;return t=t.replace(r,(s,i,o,a,l,c,p)=>`${i}${o} ${this.flattenTriggerTableRef(a??l,c??p)}`),t.replace(/\bnow\(\)/gi,"datetime('now')").replace(/\bcurrent_timestamp\b/gi,"datetime('now')").replace(/\bgen_random_uuid\(\)/gi,this.uuidExpression()).replace(/\buuid_generate_v4\(\)/gi,this.uuidExpression())}uuidExpression(){return "lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))"}NullTest(t,n){if(t.arg?.ColumnRef?.fields?.length>1)throw new F({NullTest:t},"row-level NULL tests are not supported in SQLite");return super.NullTest(t,n)}RenameStmt(t,n){if(!t.renameType)throw new Error("RenameStmt requires renameType");if(t.renameType==="OBJECT_POLICY")return "";let r=["OBJECT_TABLE","OBJECT_VIEW","OBJECT_COLUMN"];if(t.renameType==="OBJECT_COLUMN"&&(t.relationType==="OBJECT_FOREIGN_TABLE"||t.relationType==="OBJECT_VIEW"))throw new F({RenameStmt:t},`RenameStmt with relationType ${t.relationType} is not supported`);if(!r.includes(t.renameType))throw new F({RenameStmt:t},`RenameStmt with renameType ${t.renameType} is not supported in SQLite`);return super.RenameStmt(t,n)}DropStmt(t,n){let r=t.removeType;if(r==="OBJECT_EXTENSION"){let o=t.objects?.map($d)??[];if(o.length>0&&o.every(a=>a&&tc.has(a)))return "";throw new F({DropStmt:t},"DROP EXTENSION is not supported in SQLite")}if(["OBJECT_TABLE","OBJECT_VIEW","OBJECT_INDEX","OBJECT_TRIGGER"].includes(r))return this.foldDropObjectSchemas(t),super.DropStmt(t,n);if(["OBJECT_POLICY"].includes(r))return "";throw new F({DropStmt:t},`DROP with removeType ${r} is not supported in SQLite`)}foldDropObjectSchemas(t){let n=t.removeType==="OBJECT_TRIGGER"?3:2;for(let r of t.objects??[]){let s=r?.List?.items;if(!Array.isArray(s)||s.length!==n)continue;let i=s[0]?.String?.sval,o=s[1]?.String?.sval;if(typeof i!="string"||typeof o!="string")continue;let a=this.effectiveSchema(i),l=a===void 0?o:this.schemaHandling==="prefix"?`${a}__${o}`:`${a}.${o}`;s.splice(0,2,{String:{sval:l}});}}generateRebuildSql(t,n){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 r=this.buildDesiredSchema(this.introspection,t,n),s=new Qn,i=new Zn,o=s.diff(this.introspection,r);return o.has_changes?i.plan(o,this.introspection,r).steps.filter(l=>!["disable_foreign_keys","begin_transaction","commit_transaction","enable_foreign_keys"].includes(l.type)).map(l=>l.sql).join(`
211
+ `):""}buildDesiredSchema(t,n,r){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 r){let o=s.columns.findIndex(a=>a.table===n&&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===n);a!==-1&&(s.tables[a]={...s.tables[a],sql:s.tables[a].sql+" /* modified */"});break}}}return this.rebuildTableSql(s,n),s}rebuildTableSql(t,n){let r=t.tables.findIndex(u=>u.name===n);if(r===-1)return;let s=t.columns.filter(u=>u.table===n),i=t.foreign_keys.filter(u=>u.table===n),o=t.check_constraints.filter(u=>u.table===n),a=s.map(u=>{let f=`${B(u.name)} ${u.type||"TEXT"}`;return u.is_primary_key&&(f+=" PRIMARY KEY"),u.nullable||(f+=" NOT NULL"),u.default_value!=null&&(f+=` DEFAULT ${u.default_value}`),f}),l=i.map(u=>`FOREIGN KEY (${B(u.column)}) REFERENCES ${B(u.ref_table)}(${B(u.ref_column)}) ON UPDATE ${u.on_update} ON DELETE ${u.on_delete}`),c=o.map(u=>`CHECK (${u.expression})`),p=[...a,...l,...c];t.tables[r]={...t.tables[r],sql:`CREATE TABLE ${B(n)} (${p.join(", ")}) STRICT`};}extractTypeName(t){let n=t.def?.ColumnDef,r=n?.typeName?.TypeName??n?.typeName;return r?(r.names??[]).map(i=>i.String?.sval).filter(Boolean).pop()??null:null}extractDefaultValue(t){if(!t.def)return null;let n=this.unwrapConstCast(t.def);if("A_Const"in n){let r=n.A_Const;return r.isnull?null:r.ival?String(r.ival.ival??0):r.fval?r.fval.fval:r.sval?`'${String(r.sval.sval).replace(/'/g,"''")}'`:"boolval"in r?r.boolval.boolval?"1":"0":null}return "Integer"in n?String(n.Integer.ival):"Float"in n?n.Float.fval:"String"in n?`'${n.String.sval}'`:null}};});function vd(e){return `${e?.schemaname??"public"}.${e?.relname??""}`}function Ex(e){let t=e?.Constraint;if(!t||t.contype!=="CONSTR_DEFAULT")return false;let n=t.raw_expr?.FuncCall?.funcname;if(!Array.isArray(n))return false;let r=n.map(s=>s.String?.sval??s.String?.str).filter(Boolean);return r[r.length-1]?.toLowerCase()==="nextval"}function _x(e){return (Array.isArray(e.constraints)?e.constraints:[]).some(n=>n.Constraint?.contype==="CONSTR_IDENTITY")}function kd(e,t){let n=Array.isArray(e.constraints)?e.constraints:[],r=n.filter(s=>!Ex(s));r.length!==n.length?(e.constraints=r,t.add(e)):_x(e)&&t.add(e);}function xx(e,t){let n=t?.Constraint;if(!n)return false;let r=n.contype;if(r!=="CONSTR_PRIMARY"&&r!=="CONSTR_UNIQUE"&&r!=="CONSTR_FOREIGN")return false;let s=e.tableElts??[];return r==="CONSTR_PRIMARY"&&Nd(e,n)||r==="CONSTR_FOREIGN"&&Pd(e,n)||(s.push(t),e.tableElts=s),true}function Nd(e,t){let n=(t.keys??[]).map(i=>i.String?.sval??i.String?.str).filter(Boolean);if(n.length!==1)return false;let r=(e.tableElts??[]).find(i=>"ColumnDef"in i&&i.ColumnDef.colname===n[0]);if(!r)return false;let s=Array.isArray(r.ColumnDef.constraints)?r.ColumnDef.constraints:[];return r.ColumnDef.constraints=[...s.filter(i=>i.Constraint?.contype!=="CONSTR_NOTNULL"),{Constraint:{contype:"CONSTR_PRIMARY"}}],true}function Pd(e,t){let n=(t.fk_attrs??[]).map(i=>i.String?.sval??i.String?.str).filter(Boolean);if(n.length!==1)return false;let r=(e.tableElts??[]).find(i=>"ColumnDef"in i&&i.ColumnDef.colname===n[0]);if(!r)return false;let s=Array.isArray(r.ColumnDef.constraints)?r.ColumnDef.constraints:[];return r.ColumnDef.constraints=[...s,{Constraint:t}],true}function Tx(e){let t=e.tableElts??[],n=t.filter(r=>{let s=r?.Constraint;return !s||s.contype!=="CONSTR_PRIMARY"?true:!Nd(e,s)});n.length!==t.length&&(e.tableElts=n);}function Cx(e){let t=e.tableElts??[],n=t.filter(r=>{let s=r?.Constraint;return !s||s.contype!=="CONSTR_FOREIGN"?true:!Pd(e,s)});n.length!==t.length&&(e.tableElts=n);}function Od(e){let t=new WeakSet,n=new Map;for(let r of e.stmts??[]){let s=r.stmt;if(!s||!("CreateStmt"in s))continue;let i=s.CreateStmt;n.set(vd(i.relation),i);for(let o of i.tableElts??[])"ColumnDef"in o&&kd(o.ColumnDef,t);Tx(i),Cx(i);}for(let r of e.stmts??[]){let s=r.stmt;if(!s||!("AlterTableStmt"in s))continue;let i=s.AlterTableStmt,o=n.get(vd(i.relation)),a=i.cmds??[],l=[];for(let c of a){let p=c.AlterTableCmd;p?.subtype==="AT_AddColumn"&&p.def&&"ColumnDef"in p.def&&kd(p.def.ColumnDef,t),!(o&&p?.subtype==="AT_AddConstraint"&&p.def&&xx(o,p.def))&&l.push(c);}i.cmds=l;}return t}var Ld=b(()=>{});async function Wr(e,t={}){let n=await Mi(e);return {ast:n,...Ax(n,t)}}function Ax(e,t={}){let n=Od(e),r=hl(e),s=kr(e,r,n),i=gl(e),o=bl(e),a=wl(e),l=new qi(e,{...t,enums:r,serialColumns:n}),{policies:c,tables:p}=yl(e,{defaultSchema:t.defaultSchema,validateMutations:t.strict});if(t.strict){for(let u of c)if(!s.get(`${u.data.schema??"public"}.${u.data.table}`))throw new Error(`Policy "${u.data.name}" references unknown table "${u.data.table}"`)}return {ddl:l.deparseQuery(),enums:r,rls:{tables:p,policies:c},schema:s,vars:i,tableConstraints:o,comments:a}}var Hi=b(()=>{Td();Rd();Ld();za();hi();Xa();});async function Id(e){if(e.trim())try{await Mi(e);}catch(t){let n=t instanceof Error?t.message:String(t);throw new rc(`Declarative schema (schemas/*.sql) is not valid SQL: ${n}`,{cause:t})}}async function nc(e,t,n,r){if(t.trim())try{let s=t;if(n==="postgres"){let i=await e.translateDdl(t);s=typeof i=="string"?i:i.ddl??"";}for(let i of et(s))if(i.trim())try{await e.exec(i);}catch(o){if(!r)throw o}}catch(s){if(!r)throw s}}async function Dd(e,t){if(!t.trim())return;let n=Ce(e.connection);if(n==="pg")return;let r=n==="sqlite"?"sqlite":"postgres",s=await createConnection({url:":memory:",ddlDialect:r,translation:e.connection.config.translation});try{let i=e.connection.config.baseSchema;i&&await nc(s,i,r,!0);for(let o of await nt(e))await nc(s,o.sql,r,!0);await nc(s,t,r,!1);}finally{await s.close().catch(()=>{});}}var rc,jd=b(()=>{Hi();ht();Kt();St();rc=class extends Error{constructor(t,n){super(t,n),this.name="SchemaParseError";}};});var Ud={};me(Ud,{checkPendingDeclarativeSchema:()=>Md,db:()=>Ox});function Nx(){console.log(ee.default.yellow("Declarative diff includes potentially destructive changes.")),console.log(ee.default.dim("Review the schema manually and author an explicit migration for drops or other data-loss changes."));}async function Md(e,t){let n=await be(e);if(!n)return {hint:false,reason:"no-schemas"};try{let s=await e.connection.createMigrator(n).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(r){return {hint:false,reason:"diff-failed",error:r instanceof Error?r.message:String(r)}}}async function Fd(e){let t=await ut(e),n=await be(t);if(!n&&!t.connection.config.baseSchema){console.log(ee.default.dim("No schema files found."));return}let s=await t.connection.createMigrator(n).diff();if(typeof s.diff!="string"&&!s.diff.has_changes){console.log(ee.default.dim("Schema in sync."));return}wn(s);}async function Px(e,t){if(t?.trim())return t;if(!process.stdin.isTTY){let s=await ss();if(s.trim())return s}let n=await be(e);if(n?.trim())return n;let r=await Lr(e);if(r?.trim())return r;throw new Error("No SQL provided and no declarative schemas or migrations found to deparse.")}var ee,kx,Ox,Bd=b(()=>{ee=K(X());De();Al();tt();or();Kt();xd();Te();Ze();Nt();It();ht();bi();tt();St();jd();Gr();kx="Local Development:";Ox=e=>{let t=e.command("db").description("Database operations").helpGroup(kx);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 n=>{console.log(),await Z(async()=>{if(await ne(n.config),!n.file){await Fd(n.config);return}let r=await ut(n.config),s=await be(r);if(!s.trim()){console.log(ee.default.dim("No declarative schemas found \u2014 nothing to diff."));return}await Id(s);let i=Ce(r.connection);if(i==="sqlite"){console.log(ee.default.yellow('`lite db diff -f` is not supported on the bare "sqlite" driver yet.')),console.log(ee.default.dim('Declarative schema diffs require the "sqlite-postgres" driver. Set db.driver = "sqlite-postgres" in supabase/config.toml.'));return}let o;{let u=await Lr(r);try{o=await _d(u,s,r.connection.config.baseSchema??"");}catch(f){throw f instanceof DataLossError?(Nx(),new Error("Declarative diff includes potentially destructive changes.")):f}if(o=o.filter(f=>f.trim()),o.length===0){console.log(ee.default.green("Schema in sync \u2014 no migration written."));return}}let a=o.join(`
209
212
 
210
- `);try{await gd(r,a);}catch(u){Dm(u,{variant:i,failingSql:a});let f=u instanceof Error?u.message:String(u);throw new Error(`Generated migration does not run on the "${i}" backend and was not written: ${f}. This likely indicates a gap in supalite's Postgres\u2192SQLite translation; it has been reported.`)}let l=Ie__default.join(process.cwd(),"supabase",It(r));Ce(l);let c=new Date,p=o.length>1;for(let[u,f]of o.entries()){let h=Ca(new Date(c.getTime()+u*1e3)),d=p?`${n.file}_${u+1}`:n.file,m=Ie__default.join(l,Aa(d,h));await de__default.writeFile(m,f+`
211
- `,{flag:"wx"}),console.log(Q.default.green(" \u279C"),"Wrote migration",Q.default.cyan(Ie__default.relative(process.cwd(),m)));}o.length>1&&console.log(Q.default.dim(`Split into ${o.length} files: pg-delta requires a COMMIT between them.`));});}),t.command("reset").description(me("Drop user objects, clear history, replay migrations + seed")).option("--config <config>","Path to the config file").option("--no-seed","Skip running seed.sql after replay").option("--hard","Delete and recreate the local DB file/dir instead of dropping objects via SQL",false).action(async n=>{console.log(),await J(async()=>{if(await ee(n.config),n.hard){let l=await Zr(n.config);if(l){await de__default.rm(l,{recursive:!0,force:!0});for(let c of ["-wal","-shm","-journal"])await de__default.rm(`${l}${c}`,{force:!0});console.log(Q.default.dim(` \u279C removed ${Ie__default.relative(process.cwd(),l)}`));}else console.log(Q.default.dim("--hard: no local database file to delete; resetting via SQL."));}let r=await st(n.config),s=r.connection.dialect==="postgres",i=[];if(s){let{rows:l}=await r.connection.exec(`SELECT nspname AS name FROM pg_namespace
212
- WHERE nspname NOT LIKE 'pg\\_%' AND nspname <> 'information_schema'`);for(let c of l)i.push(`DROP SCHEMA IF EXISTS "${c.name.replace(/"/g,'""')}" CASCADE`);i.push("CREATE SCHEMA IF NOT EXISTS public AUTHORIZATION pg_database_owner"),i.push(`COMMENT ON SCHEMA "public" IS 'standard public schema'`),i.push('GRANT USAGE ON SCHEMA "public" TO PUBLIC');}else {let c=(await r.connection.introspect()).tables.filter(u=>u.type==="table"),p=(u,f)=>`"${u?`${u}.${f}`:f}"`;for(let u of c)i.push(`DROP TABLE IF EXISTS ${p(u.schema,u.name)}`);i.push("DROP TABLE IF EXISTS migrations"),i.push("DROP TABLE IF EXISTS seed_files"),i.push('DROP TABLE IF EXISTS "supabase_migrations.schema_migrations"'),i.push('DROP TABLE IF EXISTS "supabase_migrations.seed_files"');}for(let l of i)try{await r.connection.exec(l);}catch{}await r.connection.clearSchemaCache(),await Bf(),await Qf();let o=await Ht(r,{persistWithDeclarative:!0});for(let l of o.applied)console.log(Q.default.green(" \u2713"),"Applied",Q.default.cyan(l.filename));let a=await wd(r,o.applied.length);a.hint?(console.log(),console.log(Q.default.yellow("Declarative schemas detected with pending changes.")),console.log(Q.default.dim("The reset database reflects the migrations only \u2014 schema changes that were never diffed, including RLS policies, are gone.")),console.log(Q.default.dim("Run `lite db diff -f <name>` to capture them as a migration, then re-run `lite db reset`."))):a.reason==="diff-failed"&&(console.error(),console.error(Q.default.yellow("Declarative schemas detected but could not be checked.")),a.error&&console.error(Q.default.dim(a.error)),console.error(Q.default.dim("The reset database and its RLS metadata reflect the migrations only \u2014 anything `supabase/schemas/*.sql` declares, policies included, may be missing.")),console.error(Q.default.dim("Fix the schema files, then `lite db diff -f <name>` and re-run `lite db reset`."))),n.seed!==!1&&await yr(r).catch(l=>console.error(Q.default.yellow("Seed warning: "+String(l)))),console.log(Q.default.green("Database reset."));});}),t.command("translate").description("Translate Postgres SQL to this project's backend dialect").argument("[sql]","SQL to translate; reads stdin if omitted").option("--config <config>","Path to the config file").option("--deparse",me("Emit the JSON deparse payload (RLS policies + session vars) instead of DDL, for edge/serverless runtimes")).option("-o, --out <file>","Write output to a file instead of stdout").action(async(n,r)=>{await J(async()=>{await ee(r.config);let s=await st(r.config);try{if(r.deparse){let l=await X_(s,n),p=[s.connection.config.baseSchema??"",l].filter(d=>d.trim()).join(`
213
+ `);try{await Dd(r,a);}catch(u){id(u,{variant:i,failingSql:a});let f=u instanceof Error?u.message:String(u);throw new Error(`Generated migration does not run on the "${i}" backend and was not written: ${f}. This likely indicates a gap in supalite's Postgres\u2192SQLite translation; it has been reported.`)}let l=Fe__default.join(process.cwd(),"supabase",Vt(r));ve(l);let c=new Date,p=o.length>1;for(let[u,f]of o.entries()){let h=xl(new Date(c.getTime()+u*1e3)),m=p?`${n.file}_${u+1}`:n.file,d=Fe__default.join(l,Tl(m,h));await he__default.writeFile(d,f+`
214
+ `,{flag:"wx"}),console.log(ee.default.green(" \u279C"),"Wrote migration",ee.default.cyan(Fe__default.relative(process.cwd(),d)));}o.length>1&&console.log(ee.default.dim(`Split into ${o.length} files: pg-delta requires a COMMIT between them.`));});}),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").option("--hard","Delete and recreate the local DB file/dir instead of dropping objects via SQL",false).action(async n=>{console.log(),await Z(async()=>{if(await ne(n.config),n.hard){let l=await ds(n.config);if(l){await he__default.rm(l,{recursive:!0,force:!0});for(let c of ["-wal","-shm","-journal"])await he__default.rm(`${l}${c}`,{force:!0});console.log(ee.default.dim(` \u279C removed ${Fe__default.relative(process.cwd(),l)}`));}else console.log(ee.default.dim("--hard: no local database file to delete; resetting via SQL."));}let r=await ut(n.config),s=r.connection.dialect==="postgres",i=[];if(s){let{rows:l}=await r.connection.exec(`SELECT nspname AS name FROM pg_namespace
215
+ WHERE nspname NOT LIKE 'pg\\_%' AND nspname <> 'information_schema'`);for(let c of l)i.push(`DROP SCHEMA IF EXISTS "${c.name.replace(/"/g,'""')}" CASCADE`);i.push("CREATE SCHEMA IF NOT EXISTS public AUTHORIZATION pg_database_owner"),i.push(`COMMENT ON SCHEMA "public" IS 'standard public schema'`),i.push('GRANT USAGE ON SCHEMA "public" TO PUBLIC');}else {let c=(await r.connection.introspect()).tables.filter(u=>u.type==="table"),p=(u,f)=>`"${u?`${u}.${f}`:f}"`;for(let u of c)i.push(`DROP TABLE IF EXISTS ${p(u.schema,u.name)}`);i.push("DROP TABLE IF EXISTS migrations"),i.push("DROP TABLE IF EXISTS seed_files"),i.push('DROP TABLE IF EXISTS "supabase_migrations.schema_migrations"'),i.push('DROP TABLE IF EXISTS "supabase_migrations.seed_files"');}for(let l of i)try{await r.connection.exec(l);}catch{}await r.connection.clearSchemaCache(),await ym(),await of();let o=await zt(r);if(!await un(r))throw new Error("Applied migration metadata could not be rebuilt after reset.");for(let l of o.applied)console.log(ee.default.green(" \u2713"),"Applied",ee.default.cyan(l.filename));let a=await Md(r,o.applied.length);a.hint?(console.log(),console.log(ee.default.yellow("Declarative schemas detected with pending changes.")),console.log(ee.default.dim("The reset database reflects the migrations only \u2014 schema changes that were never diffed, including RLS policies, are gone.")),console.log(ee.default.dim("Run `lite db diff -f <name>` to capture them as a migration, then re-run `lite db reset`."))):a.reason==="diff-failed"&&(console.error(),console.error(ee.default.yellow("Declarative schemas detected but could not be checked.")),a.error&&console.error(ee.default.dim(a.error)),console.error(ee.default.dim("The reset database and its RLS metadata reflect the migrations only \u2014 anything `supabase/schemas/*.sql` declares, policies included, may be missing.")),console.error(ee.default.dim("Fix the schema files, then `lite db diff -f <name>` and re-run `lite db reset`."))),n.seed!==!1&&await Pr(r).catch(l=>console.error(ee.default.yellow("Seed warning: "+String(l)))),console.log(ee.default.green("Database reset."));});}),t.command("translate").description("Translate Postgres SQL to this project's backend dialect").argument("[sql]","SQL to translate; reads stdin if omitted").option("--config <config>","Path to the config file").option("--deparse",de("Emit the JSON deparse payload (RLS policies + session vars) instead of DDL, for edge/serverless runtimes")).option("-o, --out <file>","Write output to a file instead of stdout").action(async(n,r)=>{await Z(async()=>{await ne(r.config);let s=await ut(r.config);try{if(r.deparse){let l=await Px(s,n),p=[s.connection.config.baseSchema??"",l].filter(m=>m.trim()).join(`
213
216
 
214
- `),u=await s.connection.translateDdl(p),f=SqliteConnection.serializeDeparseInfo(u),h=JSON.stringify(f,null,2);r.out?(await de__default.writeFile(r.out,h+`
215
- `,"utf8"),console.error(Q.default.green(" \u279C"),`Wrote ${f.rls.policies.length} policies to`,Q.default.cyan(Ie__default.relative(process.cwd(),Ie__default.resolve(r.out))))):console.log(h);return}let i=n??await Hr(),o=await s.connection.translateDdl(i),a=typeof o=="string"?o:o.ddl??"";console.log(a);}finally{await s.connection.close();}});}),t.command("query").description("Execute a SQL statement against the local or remote project").argument("[statement]","The statement to execute; reads stdin if omitted").option("--remote","Execute the statement on the remote project",false).option("--config <config>","Path to the config file").action(async(n,r)=>{await J(async()=>{r.remote||await ee(r.config);let s=await st(r.remote?!0:r.config);try{if(n){Me(`Executing: ${Q.default.cyan(n)}`);let o=await s.connection.exec(n);console.log(o);return}let i=await Hr();for(let o of Rt(i)){if(!o.trim())continue;let a=await s.connection.exec(o);console.log(a);}}finally{await s.connection.close();}});}),t.command("schema").description(me("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 n=>{console.log(),await J(async()=>{if(await ee(n.config),n.diff){await bd(n.config);return}let s=await(await st(n.config)).connection.introspect();if(n.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(`;
217
+ `),u=await s.connection.translateDdl(p),f=SqliteConnection.serializeDeparseInfo(u),h=JSON.stringify(f,null,2);r.out?(await he__default.writeFile(r.out,h+`
218
+ `,"utf8"),console.error(ee.default.green(" \u279C"),`Wrote ${f.rls.policies.length} policies to`,ee.default.cyan(Fe__default.relative(process.cwd(),Fe__default.resolve(r.out))))):console.log(h);return}let i=n??await ss(),o=await s.connection.translateDdl(i),a=typeof o=="string"?o:o.ddl??"";console.log(a);}finally{await s.connection.close();}});}),t.command("query").description("Execute a SQL statement against the local or remote project").argument("[statement]","The statement to execute; reads stdin if omitted").option("--remote","Execute the statement on the remote project",false).option("--config <config>","Path to the config file").action(async(n,r)=>{await Z(async()=>{r.remote||await ne(r.config);let s=await ut(r.remote?!0:r.config);try{if(n){He(`Executing: ${ee.default.cyan(n)}`);let o=await s.connection.exec(n);console.log(o);return}let i=await ss();for(let o of et(i)){if(!o.trim())continue;let a=await s.connection.exec(o);console.log(a);}}finally{await s.connection.close();}});}),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 n=>{console.log(),await Z(async()=>{if(await ne(n.config),n.diff){await Fd(n.config);return}let s=await(await ut(n.config)).connection.introspect();if(n.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(`;
216
219
 
217
- `)+(i.length?";":""));return}Gf(s);});});};});var _d={};fe(_d,{migration:()=>Z_});var we,Q_,Z_,xd=b(()=>{we=V(z());dt();Js();mt();Te();Ee();Q_="Local Development:",Z_=e=>{let t=e.command("migration").description("Manage database migrations").helpGroup(Q_);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(n,r)=>{await ee(r.config);let i=await(await W({withSupabaseClient:false})).project.local.createApp(r.config),o=await xf(i,n);console.log(we.default.green(" \u279C"),"Created",we.default.cyan(Ie__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 n=>{await ee(n.config);let s=await(await W({withSupabaseClient:false})).project.local.createApp(n.config);if(n.dryRun){await nn(s.connection);let i=new Set(await Gn(s.connection)),a=(await De(s)).filter(l=>!i.has(l.version));a.length===0&&(console.log(we.default.green("No pending migrations.")),process.exit(0)),console.log(we.default.dim("Pending:"));for(let l of a)console.log(" "+we.default.cyan(l.filename));process.exit(0);}try{let i=await Ht(s);if(i.applied.length===0)console.log(we.default.green("Local database is up to date."));else for(let o of i.applied)console.log(we.default.green(" \u2713"),"Applied",we.default.cyan(o.filename));}catch(i){console.error(we.default.red("Migration failed: "+String(i.message??i))),process.exit(1);}process.exit(0);}),t.command("list").description("List applied and pending migrations").option("--config <config>","Path to the config file").action(async n=>{await ee(n.config);let s=await(await W({withSupabaseClient:false})).project.local.createApp(n.config);await nn(s.connection);let i=new Set(await Gn(s.connection)),o=await De(s);console.log(we.default.dim(`Migrations in ${It(s)}:`)),o.length===0&&console.log(we.default.dim(" (none)"));for(let c of o){let p=i.has(c.version)?we.default.green("[applied]"):we.default.yellow("[pending]");console.log(` ${p} ${we.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(we.default.dim("Recorded versions without matching file:"));for(let c of l)console.log(` ${we.default.red("[orphan]")} ${c}`);}process.exit(0);});};});function tx(e){let t=(e??process.env.SUPABASE_ENDPOINT??ex).replace(/\/+$/,""),n=new URL(t),r=n.host;return {apiUrl:`${n.protocol}//${r.startsWith("api.")?r:`api.${r}`}`,projectDomain:r==="supabase.com"?"supabase.co":r}}function Td(e){if(Array.isArray(e)){let t=e.find(r=>r.name==="anon")?.api_key??"",n=e.find(r=>r.name==="service_role")?.api_key??"";return {anon:t,service_role:n}}return e}var ex,vi,Cd=b(()=>{ex="https://supabase.com";vi=class{constructor(t,n){this.token=t;if(!t)throw new Error("Supabase access token required");let r=tx(n?.endpoint);this.apiUrl=r.apiUrl,this.projectDomain=r.projectDomain;}apiUrl;projectDomain;async request(t,n,r){let s=await fetch(`${this.apiUrl}${n}`,{method:t,headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json",Accept:"application/json"},body:r===void 0?void 0:JSON.stringify(r)});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Supabase API ${t} ${n} 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,n){return this.request("PATCH",`/v1/projects/${t}/config/auth`,n)}createSigningKey(t,n){return this.request("POST",`/v1/projects/${t}/config/auth/signing-keys`,n)}runSql(t,n){return this.request("POST",`/v1/projects/${t}/database/query`,{query:n})}async waitForActive(t,n={}){let r=n.timeoutMs??6e5,s=n.intervalMs??5e3,i=Date.now();for(;;){let o=await this.getProject(t);if(n.onTick?.(o.status),o.status==="ACTIVE_HEALTHY")return o;if(Date.now()-i>r)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 rx(e){if(e==null||typeof e!="string")return true;try{return JSON.parse(e),!0}catch{return false}}function sx(e){return e==null?true:typeof e!="string"?false:nx.test(e)}function ix(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 Ad(e){if(!e)return;let t=e.match(/varchar\s*\(\s*(\d+)\s*\)/i);return t?Number(t[1]):void 0}function $d(e){return e?/jsonb?/i.test(e):false}function vd(e){return e?/\buuid\b/i.test(e):false}function Rd(e){return e?/timestamp(tz)?|timestamp with|timestamp without/i.test(e):false}async function kd(e){let t=await e.connection.introspect(),n=[],r=e.connection.dialect;for(let s of t.tables){let i=s.name,o=s.schema,a=r==="sqlite"&&o&&o!=="main"?`"${o}.${i}"`:o?`"${o}"."${i}"`:`"${i}"`,l=t.columns.filter(h=>h.table===i&&(h.schema??o)===o),c=0,p=[];try{let h=await e.connection.exec(`SELECT COUNT(*) as c FROM ${a}`);c=Number(h?.rows?.[0]?.c??0);}catch{n.push({table:i,schema:o,rowCount:0,issues:p});continue}if(c===0){n.push({table:i,schema:o,rowCount:c,issues:p});continue}let u=l.filter(h=>$d(h.type)||vd(h.type)||Rd(h.type)||Ad(h.type)!==void 0);if(u.length===0){n.push({table:i,schema:o,rowCount:c,issues:p});continue}let f=u.map(h=>`"${h.name}"`).join(", ");try{let d=(await e.connection.exec(`SELECT ${f} FROM ${a}`))?.rows??[];for(let m of d)for(let g of u){let y=m[g.name];if($d(g.type)&&!rx(y)){p.push({table:i,column:g.name,kind:"invalid_json",message:`row contains non-parseable JSON in ${i}.${g.name}`});continue}if(vd(g.type)&&y!=null&&!sx(y)){p.push({table:i,column:g.name,kind:"invalid_uuid",message:`row contains invalid UUID in ${i}.${g.name}`});continue}if(Rd(g.type)&&!ix(y)){p.push({table:i,column:g.name,kind:"invalid_timestamp",message:`row contains unparseable timestamp in ${i}.${g.name}`});continue}let E=Ad(g.type);E!==void 0&&typeof y=="string"&&y.length>E&&p.push({table:i,column:g.name,kind:"varchar_overflow",message:`value exceeds varchar(${E}) in ${i}.${g.name}`});}}catch{}n.push({table:i,schema:o,rowCount:c,issues:p});}return n}var nx,Nd=b(()=>{nx=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;});function _t(e){let t=[],n="",r=0,s=false,i=false,o=false,a=false,l=null;for(;r<e.length;){let p=e[r],u=e[r+1];if(o){n+=p,p===`
218
- `&&(o=false),r++;continue}if(a){if(n+=p,p==="*"&&u==="/"){n+=u,r+=2,a=false;continue}r++;continue}if(l){if(n+=p,p==="$"&&e.startsWith(l,r)){n+=e.slice(r+1,r+l.length),r+=l.length,l=null;continue}r++;continue}if(s){if(n+=p,p==="'"&&u==="'"){n+=u,r+=2;continue}p==="'"&&(s=false),r++;continue}if(i){if(n+=p,p==='"'&&u==='"'){n+=u,r+=2;continue}p==='"'&&(i=false),r++;continue}if(p==="-"&&u==="-"){o=true,n+=p,r++;continue}if(p==="/"&&u==="*"){a=true,n+=p,r++;continue}if(p==="'"){s=true,n+=p,r++;continue}if(p==='"'){i=true,n+=p,r++;continue}if(p==="$"){let f=e.slice(r).match(/^\$[A-Za-z0-9_]*\$/);if(f){l=f[0],n+=f[0],r+=f[0].length;continue}}if(p===";"){let f=n.trim();f&&t.push(f),n="",r++;continue}n+=p,r++;}let c=n.trim();return c&&t.push(c),t}var Ri=b(()=>{});async function ki(e,t){let r=e.connection.dialect==="sqlite"?`"auth.${t}"`:`auth."${t}"`;try{let s=await e.connection.exec(`SELECT COUNT(*) as c FROM ${r}`);return Number(s?.rows?.[0]?.c??0)}catch{return 0}}async function Pd(e){let t=[],n=[],r=false;try{await e.connection.exec("SELECT 1"),r=!0;}catch(l){t.push(`Database not reachable: ${String(l)}`);}let s=await re(e),i=_t(s);i.length===0&&t.push("No schema statements found in supabase/schemas/*.sql");let o=[];if(r)try{o=await kd(e);}catch(l){n.push(`Data validation skipped: ${String(l)}`);}for(let l of o)for(let c of l.issues)n.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 r&&(a.users=await ki(e,"users"),a.sessions=await ki(e,"sessions"),a.refresh_tokens=await ki(e,"refresh_tokens"),a.identities=await ki(e,"identities")),a.jwt_secret_set||n.push("auth.jwt_secret is not configured \u2014 tokens will not survive upgrade"),e.config.storage?.enabled&&n.push("Storage is enabled but migration is not yet supported"),e.config.realtime?.enabled&&n.push("Realtime config migration is not yet supported"),{ok:t.length===0,errors:t,warnings:n,dbReachable:r,schemaStatementCount:i.length,schemaBytes:s.length,tables:o,auth:a}}var Ld=b(()=>{Ue();Nd();Ri();});var Bl,Od=b(()=>{Bl=`-- supabase/auth core schema (Postgres)
220
+ `)+(i.length?";":""));return}Sm(s);});});};});var qd={};me(qd,{migration:()=>Dx});var _e,Ix,Dx,Hd=b(()=>{_e=K(X());Kt();bi();St();Re();Te();or();Ix="Local Development:",Dx=e=>{let t=e.command("migration").description("Manage database migrations").helpGroup(Ix);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(n,r)=>{await ne(r.config);let i=await(await V({withSupabaseClient:false})).project.local.createApp(r.config),o=await xm(i,n);console.log(_e.default.green(" \u279C"),"Created",_e.default.cyan(Fe__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 n=>{await ne(n.config);let s=await(await V({withSupabaseClient:false})).project.local.createApp(n.config);if(n.dryRun){await ln(s.connection);let i=new Set(await tr(s.connection)),a=(await nt(s)).filter(l=>!i.has(l.version));a.length===0&&(console.log(_e.default.green("No pending migrations.")),process.exit(0)),console.log(_e.default.dim("Pending:"));for(let l of a)console.log(" "+_e.default.cyan(l.filename));process.exit(0);}try{let i=await zt(s);if(!await un(s))throw new Error("Applied migration metadata could not be rebuilt. Run `lite db reset`.");if(i.applied.length===0)console.log(_e.default.green("Local database is up to date."));else for(let o of i.applied)console.log(_e.default.green(" \u2713"),"Applied",_e.default.cyan(o.filename));}catch(i){console.error(_e.default.red("Migration failed: "+String(i.message??i))),process.exit(1);}process.exit(0);}),t.command("list").description("List applied and pending migrations").option("--config <config>","Path to the config file").action(async n=>{await ne(n.config);let s=await(await V({withSupabaseClient:false})).project.local.createApp(n.config);await ln(s.connection);let i=new Set(await tr(s.connection)),o=await nt(s);console.log(_e.default.dim(`Migrations in ${Vt(s)}:`)),o.length===0&&console.log(_e.default.dim(" (none)"));for(let c of o){let p=i.has(c.version)?_e.default.green("[applied]"):_e.default.yellow("[pending]");console.log(` ${p} ${_e.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(_e.default.dim("Recorded versions without matching file:"));for(let c of l)console.log(` ${_e.default.red("[orphan]")} ${c}`);}process.exit(0);});};});function Fx(e){let t=(e??process.env.SUPABASE_ENDPOINT??jx).replace(/\/+$/,""),n=new URL(t),r=n.host;return {apiUrl:`${n.protocol}//${r.startsWith("api.")?r:`api.${r}`}`,projectDomain:r==="supabase.com"?"supabase.co":r}}function Gd(e){if(Array.isArray(e)){let t=e.find(r=>r.name==="anon")?.api_key??"",n=e.find(r=>r.name==="service_role")?.api_key??"";return {anon:t,service_role:n}}return e}var jx,Wi,Wd=b(()=>{jx="https://supabase.com";Wi=class{constructor(t,n){this.token=t;if(!t)throw new Error("Supabase access token required");let r=Fx(n?.endpoint);this.apiUrl=r.apiUrl,this.projectDomain=r.projectDomain;}apiUrl;projectDomain;async request(t,n,r){let s=await fetch(`${this.apiUrl}${n}`,{method:t,headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json",Accept:"application/json"},body:r===void 0?void 0:JSON.stringify(r)});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Supabase API ${t} ${n} 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,n){return this.request("PATCH",`/v1/projects/${t}/config/auth`,n)}createSigningKey(t,n){return this.request("POST",`/v1/projects/${t}/config/auth/signing-keys`,n)}runSql(t,n){return this.request("POST",`/v1/projects/${t}/database/query`,{query:n})}async waitForActive(t,n={}){let r=n.timeoutMs??6e5,s=n.intervalMs??5e3,i=Date.now();for(;;){let o=await this.getProject(t);if(n.onTick?.(o.status),o.status==="ACTIVE_HEALTHY")return o;if(Date.now()-i>r)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 Ux(e){if(e==null||typeof e!="string")return true;try{return JSON.parse(e),!0}catch{return false}}function Bx(e){return e==null?true:typeof e!="string"?false:Mx.test(e)}function qx(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 Vd(e){if(!e)return;let t=e.match(/varchar\s*\(\s*(\d+)\s*\)/i);return t?Number(t[1]):void 0}function Kd(e){return e?/jsonb?/i.test(e):false}function zd(e){return e?/\buuid\b/i.test(e):false}function Xd(e){return e?/timestamp(tz)?|timestamp with|timestamp without/i.test(e):false}async function Jd(e){let t=await e.connection.introspect(),n=[],r=e.connection.dialect;for(let s of t.tables){let i=s.name,o=s.schema,a=r==="sqlite"&&o&&o!=="main"?`"${o}.${i}"`:o?`"${o}"."${i}"`:`"${i}"`,l=t.columns.filter(h=>h.table===i&&(h.schema??o)===o),c=0,p=[];try{let h=await e.connection.exec(`SELECT COUNT(*) as c FROM ${a}`);c=Number(h?.rows?.[0]?.c??0);}catch{n.push({table:i,schema:o,rowCount:0,issues:p});continue}if(c===0){n.push({table:i,schema:o,rowCount:c,issues:p});continue}let u=l.filter(h=>Kd(h.type)||zd(h.type)||Xd(h.type)||Vd(h.type)!==void 0);if(u.length===0){n.push({table:i,schema:o,rowCount:c,issues:p});continue}let f=u.map(h=>`"${h.name}"`).join(", ");try{let m=(await e.connection.exec(`SELECT ${f} FROM ${a}`))?.rows??[];for(let d of m)for(let g of u){let y=d[g.name];if(Kd(g.type)&&!Ux(y)){p.push({table:i,column:g.name,kind:"invalid_json",message:`row contains non-parseable JSON in ${i}.${g.name}`});continue}if(zd(g.type)&&y!=null&&!Bx(y)){p.push({table:i,column:g.name,kind:"invalid_uuid",message:`row contains invalid UUID in ${i}.${g.name}`});continue}if(Xd(g.type)&&!qx(y)){p.push({table:i,column:g.name,kind:"invalid_timestamp",message:`row contains unparseable timestamp in ${i}.${g.name}`});continue}let E=Vd(g.type);E!==void 0&&typeof y=="string"&&y.length>E&&p.push({table:i,column:g.name,kind:"varchar_overflow",message:`value exceeds varchar(${E}) in ${i}.${g.name}`});}}catch{}n.push({table:i,schema:o,rowCount:c,issues:p});}return n}var Mx,Yd=b(()=>{Mx=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;});function vt(e){let t=[],n="",r=0,s=false,i=false,o=false,a=false,l=null;for(;r<e.length;){let p=e[r],u=e[r+1];if(o){n+=p,p===`
221
+ `&&(o=false),r++;continue}if(a){if(n+=p,p==="*"&&u==="/"){n+=u,r+=2,a=false;continue}r++;continue}if(l){if(n+=p,p==="$"&&e.startsWith(l,r)){n+=e.slice(r+1,r+l.length),r+=l.length,l=null;continue}r++;continue}if(s){if(n+=p,p==="'"&&u==="'"){n+=u,r+=2;continue}p==="'"&&(s=false),r++;continue}if(i){if(n+=p,p==='"'&&u==='"'){n+=u,r+=2;continue}p==='"'&&(i=false),r++;continue}if(p==="-"&&u==="-"){o=true,n+=p,r++;continue}if(p==="/"&&u==="*"){a=true,n+=p,r++;continue}if(p==="'"){s=true,n+=p,r++;continue}if(p==='"'){i=true,n+=p,r++;continue}if(p==="$"){let f=e.slice(r).match(/^\$[A-Za-z0-9_]*\$/);if(f){l=f[0],n+=f[0],r+=f[0].length;continue}}if(p===";"){let f=n.trim();f&&t.push(f),n="",r++;continue}n+=p,r++;}let c=n.trim();return c&&t.push(c),t}var Vi=b(()=>{});async function Ki(e,t){let r=e.connection.dialect==="sqlite"?`"auth.${t}"`:`auth."${t}"`;try{let s=await e.connection.exec(`SELECT COUNT(*) as c FROM ${r}`);return Number(s?.rows?.[0]?.c??0)}catch{return 0}}async function Qd(e){let t=[],n=[],r=false;try{await e.connection.exec("SELECT 1"),r=!0;}catch(l){t.push(`Database not reachable: ${String(l)}`);}let s=await be(e),i=vt(s);i.length===0&&t.push("No schema statements found in supabase/schemas/*.sql");let o=[];if(r)try{o=await Jd(e);}catch(l){n.push(`Data validation skipped: ${String(l)}`);}for(let l of o)for(let c of l.issues)n.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 r&&(a.users=await Ki(e,"users"),a.sessions=await Ki(e,"sessions"),a.refresh_tokens=await Ki(e,"refresh_tokens"),a.identities=await Ki(e,"identities")),a.jwt_secret_set||n.push("auth.jwt_secret is not configured \u2014 tokens will not survive upgrade"),e.config.storage?.enabled&&n.push("Storage is enabled but migration is not yet supported"),e.config.realtime?.enabled&&n.push("Realtime config migration is not yet supported"),{ok:t.length===0,errors:t,warnings:n,dbReachable:r,schemaStatementCount:i.length,schemaBytes:s.length,tables:o,auth:a}}var Zd=b(()=>{tt();Yd();Vi();});var sc,eh=b(()=>{sc=`-- supabase/auth core schema (Postgres)
219
222
  -- Scope: Core Authentication + User Management
220
223
  -- Source: GoTrue migrations + runtime analysis
221
224
 
@@ -423,7 +426,7 @@ CREATE TABLE IF NOT EXISTS auth.audit_log_entries (
423
426
  created_at timestamptz DEFAULT now(),
424
427
  ip_address varchar(64) DEFAULT ''
425
428
  );
426
- `;});function Id(e=true){return e?Oc(Bl):Bl}var Dd=b(()=>{kt();Od();});function fx(e,t,n,r){if(e==null)return "NULL";if(r.includes(t))return e===true||e===1||e==="1"||e==="true"?"true":"false";if(n.includes(t)){let s=typeof e=="string"?e:JSON.stringify(e);return `${jd(s)}::jsonb`}return typeof e=="number"?Number.isFinite(e)?String(e):"NULL":typeof e=="boolean"?e?"true":"false":jd(String(e))}function jd(e){return `'${e.replace(/'/g,"''")}'`}async function Ni(e,t={}){let n=t.target??"supabase",r={users:[],sessions:[],identities:[],refresh_tokens:[]},s=e.connection.dialect,i=px[n];for(let o of lx){let a=s==="sqlite"?`"auth.${o}"`:`auth."${o}"`,l=[];try{l=(await e.connection.exec(`SELECT * FROM ${a}`))?.rows??[];}catch{continue}if(l.length===0)continue;let c=new Set(i[o]),p=cx[o],u=ux[o];for(let f of l){let h={...f};if(n==="supabase"&&o==="users"){let y=h.confirmed_at;y!=null&&h.email_confirmed_at==null&&(h.email_confirmed_at=y);}let d=Object.keys(h).filter(y=>!c.has(y)),m=d.map(y=>fx(h[y],y,p,u)),g=`INSERT INTO auth.${o} (${d.map(y=>`"${y}"`).join(", ")}) VALUES (${m.join(", ")}) ON CONFLICT DO NOTHING`;r[o].push(g);}}return r}var ax,lx,cx,ux,px,ql=b(()=>{ax=["users","sessions","identities","refresh_tokens"],lx=ax,cx={users:["raw_app_meta_data","raw_user_meta_data"],sessions:[],identities:["identity_data"],refresh_tokens:[]},ux={users:["is_sso_user","is_anonymous"],sessions:[],identities:[],refresh_tokens:["revoked"]},px={supabase:{users:["confirmed_at"],sessions:[],identities:["email"],refresh_tokens:["id"]},local:{users:["confirmed_at"],sessions:[],identities:["email"],refresh_tokens:[]}};});function Pi(e){return !e||e==="main"||e==="public"?"public":e}function Nr(e,t){return `${Pi(e)}.${t}`}function dx(e,t){let n=new Map(e.map(a=>[Nr(a.schema,a.name),a])),r=new Map,s=new Map;for(let a of n.keys())r.set(a,new Set),s.set(a,new Set);for(let a of t){let l=Nr(a.schema,a.table),c=Nr(a.ref_schema??a.schema,a.ref_table);!r.has(l)||!r.has(c)||(r.get(l).add(c),s.get(c).add(l));}let i=[...r.entries()].filter(([,a])=>a.size===0).map(([a])=>a),o=[];for(let a=0;a<i.length;a++){let l=i[a];o.push(l);for(let c of s.get(l)??[]){let p=r.get(c);p&&(p.delete(l),p.size===0&&i.push(c));}}if(o.length<e.length){console.warn("Warning: cycle detected in user table foreign keys; using best-effort data export order.");let a=new Set(o);for(let l of e){let c=Nr(l.schema,l.name);a.has(c)||o.push(c);}}return o.map(a=>n.get(a)).filter(Boolean)}function Ud(e,t){if(e==null)return "NULL";let n=(t??"").toLowerCase();if(Array.isArray(e)&&n.endsWith("[]")){let r=t?.slice(0,-2);return `ARRAY[${e.map(s=>Ud(s,r)).join(", ")}]::${t}`}if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return Number.isFinite(e)?String(e):"NULL";if(n.includes("bool")&&(e===0||e===1||e==="0"||e==="1"))return e===1||e==="1"?"true":"false";if(n.includes("json")){let r=typeof e=="string"?e:JSON.stringify(e),s=n.includes("jsonb")?"::jsonb":"::json";return `${wn(r)}${s}`}return e instanceof Date?wn(e.toISOString()):typeof e=="object"?`${wn(JSON.stringify(e))}::jsonb`:wn(String(e))}function wn(e){return `'${e.replace(/'/g,"''")}'`}function Hl(e){return `"${e.replace(/"/g,'""')}"`}function hx(e){let t=e.default_value??e.default;if(typeof t=="string"&&t.trim().toLowerCase().startsWith("nextval("))return true;let n=typeof e.type=="string"?e.type.toLowerCase():"",r=typeof e.pg_type=="string"?e.pg_type.toLowerCase():"";return Fd.has(n)||Fd.has(r)}function gx(e,t,n){let r=`${Hl(e)}.${Hl(t)}`;return `SELECT setval(pg_get_serial_sequence(${wn(r)}, ${wn(n)}), COALESCE((SELECT MAX(${Hl(n)}) FROM ${r}), 1));`}async function yx(e){let t=e.connection.config?.translation?.deparse?.schema;if(t instanceof Map&&t.size>0)return t;let n=await re(e);return n.trim()?(await kr(n)).schema:new Map}async function Li(e){let t=await e.connection.introspect(),n=e.connection.dialect,r=await yx(e),s=dx(t.tables.filter(o=>!mx.has(Pi(o.schema))),t.foreign_keys),i=[];for(let o of s){let a=Pi(o.schema),l=n==="sqlite"?a==="public"?`"${o.name}"`:`"${a}.${o.name}"`:`"${a}"."${o.name}"`,p=t.columns.filter(E=>E.table===o.name&&Pi(E.schema)===a).filter(E=>!E.generated&&!E.is_generated),u=[];try{u=(await e.connection.exec(`SELECT * FROM ${l}`))?.rows??[];}catch{continue}if(u.length===0)continue;let f=r.get(Nr(a,o.name)),h=typeof e.connection.deserializeRow=="function"?e.connection.deserializeRow.bind(e.connection):E=>E;u=u.map(E=>{let A=f?f.deserializeRow(E):E;return h(A)});let d=p.map(E=>E.name),m=new Map(p.map(E=>[E.name,E.pg_type??E.type])),g=[];for(let E of u){let A=d.map(C=>Ud(E[C],m.get(C)));g.push(`INSERT INTO "${a}"."${o.name}" (${d.map(C=>`"${C}"`).join(", ")}) VALUES (${A.join(", ")}) ON CONFLICT DO NOTHING`);}let y=p.filter(hx).map(E=>gx(a,o.name,E.name));i.push({schema:a,table:o.name,inserts:g,sequenceResets:y});}return i}var mx,Fd,Gl=b(()=>{Ai();Ue();mx=new Set(["auth","storage","realtime","supabase_functions","graphql","graphql_public","extensions","pgsodium","pgsodium_masks","vault","information_schema","pg_catalog","pg_toast"]),Fd=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]);});async function Md(e){let{PGlite:t}=await qe("@supabase/lite/pglite","pglite","@electric-sql/pglite"),n=new t,r=[],s=0,i=0,o=0,a=0;try{for(let d of ["anon","authenticated","service_role","supabase_auth_admin"])await n.exec(`CREATE ROLE ${d}`);let l=_t(Xs);for(let d=0;d<l.length;d++)try{await n.exec(l[d]);}catch(m){return r.push({phase:"schema",label:`auth helpers ${d+1}/${l.length}`,statement:l[d],error:String(m)}),{ok:!1,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:r}}if(e.config.auth?.enabled!==!1){let d=_t(Id());s=d.length;for(let m=0;m<d.length;m++)try{await n.exec(d[m]);}catch(g){return r.push({phase:"schema",label:`auth base schema ${m+1}/${d.length}`,statement:d[m],error:String(g)}),{ok:!1,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:r}}}let c=await re(e),p=_t(c);i=p.length;for(let d=0;d<p.length;d++)try{await n.exec(p[d]);}catch(m){return r.push({phase:"schema",label:`schema ${d+1}/${p.length}`,statement:p[d],error:String(m)}),{ok:!1,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:r}}let u=await Ni(e,{target:"local"}),f=["users","sessions","identities","refresh_tokens"];for(let d of f){let m=u[d];for(let g=0;g<m.length;g++){o++;try{await n.exec(m[g]);}catch(y){r.push({phase:"auth",label:`auth.${d} row ${g+1}/${m.length}`,statement:m[g],error:String(y)});}}}let h=await Li(e);for(let d of h){for(let m=0;m<d.inserts.length;m++){a++;try{await n.exec(d.inserts[m]);}catch(g){r.push({phase:"data",label:`${d.schema}.${d.table} row ${m+1}/${d.inserts.length}`,statement:d.inserts[m],error:String(g)});}}for(let m=0;m<d.sequenceResets.length;m++)try{await n.exec(d.sequenceResets[m]);}catch(g){r.push({phase:"data",label:`${d.schema}.${d.table} sequence reset ${m+1}/${d.sequenceResets.length}`,statement:d.sequenceResets[m],error:String(g)});}}}finally{await n.close().catch(()=>{});}return {ok:r.length===0,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:r}}var Bd=b(()=>{tn();Ue();Dd();Sr();Ri();ql();Gl();});function qd(e){if(console.log(L.default.bold("Readiness Report")),console.log(` db reachable: ${e.dbReachable?L.default.green("yes"):L.default.red("no")} schema statements: ${L.default.cyan(e.schemaStatementCount)} schema bytes: ${L.default.cyan(e.schemaBytes)}`),console.log(` auth \u2014 users: ${L.default.cyan(e.auth.users)} sessions: ${L.default.cyan(e.auth.sessions)} identities: ${L.default.cyan(e.auth.identities)} refresh_tokens: ${L.default.cyan(e.auth.refresh_tokens)} jwt_secret: ${e.auth.jwt_secret_set?L.default.green("set"):L.default.yellow("unset")}`),e.tables.length>0){console.log(L.default.dim(" tables:"));for(let t of e.tables){let n=t.issues.length>0?L.default.yellow(` (${t.issues.length} issues)`):"",r=t.schema?`${t.schema}.`:"";console.log(` ${r}${t.table}: ${L.default.cyan(t.rowCount)} rows${n}`);}}if(e.errors.length>0){console.log(L.default.red("Errors:"));for(let t of e.errors)console.log(` ${L.default.red("\u2717")} ${t}`);}if(e.warnings.length>0){console.log(L.default.yellow("Warnings:"));for(let t of e.warnings)console.log(` ${L.default.yellow("!")} ${t}`);}console.log(),console.log(e.ok?L.default.green("Ready to upgrade."):L.default.red("Not ready."));}function Hd(e){if(console.log(),console.log(L.default.bold("Rehearsal (in-memory pglite)")),console.log(` auth schema: ${L.default.cyan(e.baseSchemaStatements)} stmts user schema: ${L.default.cyan(e.schemaStatements)} stmts auth: ${L.default.cyan(e.authInserts)} inserts data: ${L.default.cyan(e.dataInserts)} inserts`),e.failures.length>0){console.log(L.default.red(` ${e.failures.length} failure(s):`));for(let t of e.failures)console.log(L.default.red(` \u2717 [${t.phase}] ${t.label}`)),console.log(L.default.dim(` ${t.statement}`)),console.log(L.default.dim(` ${t.error}`));}console.log(e.ok?L.default.green(" rehearsal passed"):L.default.red(" rehearsal failed"));}function Gd(e){console.log(),console.log(L.default.bold("SQLite Shim Audit")),console.log(` fields: ${L.default.cyan(e.summary.total)} passed: ${L.default.green(String(e.summary.passed))} warned: ${L.default.yellow(String(e.summary.warned))} failed: ${L.default.red(String(e.summary.failed))}`),e.results.length===0&&console.log(L.default.dim(" no shim-backed fields found"));for(let t of e.results.filter(n=>n.status!=="pass")){let n=t.status==="fail"?L.default.red:L.default.yellow;if(console.log(` ${n(t.status)} ${t.field} (${t.pg_type}) rows: ${L.default.cyan(t.rows_checked)} affected: ${L.default.cyan(t.affected_rows??0)}`),t.message&&console.log(` ${t.message}`),t.samples?.length)for(let r of t.samples)console.log(L.default.dim(` sample ${JSON.stringify(r.id)} raw=${JSON.stringify(r.raw_value)}`));t.action&&console.log(L.default.dim(` action: ${t.action}`));}console.log(e.summary.upgrade_safe?L.default.green(" shim audit passed"):L.default.red(" shim audit failed"));}function Wl(e){if(console.log(),console.log(L.default.bold(L.default.green("Upgrade complete."))),console.log(),console.log(` ${L.default.bold("Project URL:")} ${L.default.cyan(e.projectUrl)}`),console.log(` ${L.default.bold("API URL:")} ${L.default.cyan(e.apiUrl)}`),e.studioUrl&&console.log(` ${L.default.bold("Studio URL:")} ${L.default.cyan(e.studioUrl)}`),console.log(` ${L.default.bold("Ref:")} ${L.default.cyan(e.projectRef)}`),console.log(),console.log(` ${L.default.bold("anon key:")} ${e.anonKey}`),console.log(` ${L.default.bold("service_role key:")} ${e.serviceRoleKey}`),console.log(` ${L.default.bold("db password:")} ${e.dbPassword}`),console.log(),console.log(` migrated auth \u2014 users: ${L.default.cyan(e.auth.users)} sessions: ${L.default.cyan(e.auth.sessions)} identities: ${L.default.cyan(e.auth.identities)} refresh_tokens: ${L.default.cyan(e.auth.refresh_tokens)}`),console.log(` jwt secret: ${e.jwtMigrated?L.default.green("migrated"):L.default.yellow("not migrated \u2014 users must re-authenticate")}`),e.warnings.length>0){console.log(),console.log(L.default.yellow("Warnings:"));for(let t of e.warnings)console.log(` ${L.default.yellow("!")} ${t}`);}console.log(),console.log(L.default.bold("Update your supabase-js client:")),console.log(` url: ${L.default.cyan(e.apiUrl)}`),console.log(` anonKey: ${L.default.cyan(e.anonKey)}`),console.log();}var L,Wd=b(()=>{L=V(z());});function Vd(e){return {kty:"oct",alg:"HS256",k:Buffer$1.from(e,"utf8").toString("base64url")}}var Kd=b(()=>{Do();});async function zd(e){let t=e.trim();if(!t)return "";let{PGlite:n}=await qe("@supabase/lite/pglite","pglite","@electric-sql/pglite"),r=new n;try{return await r.exec(wt(St(t))),await r.exec(Xs),await wx(r,t)}finally{await r.close().catch(()=>{});}}async function wx(e,t){return t?(await e.exec(t),await Sx(e)):""}async function Sx(e){let t=await e.query(`
429
+ `;});function th(e=true){return e?Yc(sc):sc}var nh=b(()=>{ht();eh();});function Xx(e,t,n,r){if(e==null)return "NULL";if(r.includes(t))return e===true||e===1||e==="1"||e==="true"?"true":"false";if(n.includes(t)){let s=typeof e=="string"?e:JSON.stringify(e);return `${rh(s)}::jsonb`}return typeof e=="number"?Number.isFinite(e)?String(e):"NULL":typeof e=="boolean"?e?"true":"false":rh(String(e))}function rh(e){return `'${e.replace(/'/g,"''")}'`}async function zi(e,t={}){let n=t.target??"supabase",r={users:[],sessions:[],identities:[],refresh_tokens:[]},s=e.connection.dialect,i=zx[n];for(let o of Wx){let a=s==="sqlite"?`"auth.${o}"`:`auth."${o}"`,l=[];try{l=(await e.connection.exec(`SELECT * FROM ${a}`))?.rows??[];}catch{continue}if(l.length===0)continue;let c=new Set(i[o]),p=Vx[o],u=Kx[o];for(let f of l){let h={...f};if(n==="supabase"&&o==="users"){let y=h.confirmed_at;y!=null&&h.email_confirmed_at==null&&(h.email_confirmed_at=y);}let m=Object.keys(h).filter(y=>!c.has(y)),d=m.map(y=>Xx(h[y],y,p,u)),g=`INSERT INTO auth.${o} (${m.map(y=>`"${y}"`).join(", ")}) VALUES (${d.join(", ")}) ON CONFLICT DO NOTHING`;r[o].push(g);}}return r}var Gx,Wx,Vx,Kx,zx,ic=b(()=>{Gx=["users","sessions","identities","refresh_tokens"],Wx=Gx,Vx={users:["raw_app_meta_data","raw_user_meta_data"],sessions:[],identities:["identity_data"],refresh_tokens:[]},Kx={users:["is_sso_user","is_anonymous"],sessions:[],identities:[],refresh_tokens:["revoked"]},zx={supabase:{users:["confirmed_at"],sessions:[],identities:["email"],refresh_tokens:["id"]},local:{users:["confirmed_at"],sessions:[],identities:["email"],refresh_tokens:[]}};});function Xi(e){return !e||e==="main"||e==="public"?"public":e}function Vr(e,t){return `${Xi(e)}.${t}`}function Yx(e,t){let n=new Map(e.map(a=>[Vr(a.schema,a.name),a])),r=new Map,s=new Map;for(let a of n.keys())r.set(a,new Set),s.set(a,new Set);for(let a of t){let l=Vr(a.schema,a.table),c=Vr(a.ref_schema??a.schema,a.ref_table);!r.has(l)||!r.has(c)||(r.get(l).add(c),s.get(c).add(l));}let i=[...r.entries()].filter(([,a])=>a.size===0).map(([a])=>a),o=[];for(let a=0;a<i.length;a++){let l=i[a];o.push(l);for(let c of s.get(l)??[]){let p=r.get(c);p&&(p.delete(l),p.size===0&&i.push(c));}}if(o.length<e.length){console.warn("Warning: cycle detected in user table foreign keys; using best-effort data export order.");let a=new Set(o);for(let l of e){let c=Vr(l.schema,l.name);a.has(c)||o.push(c);}}return o.map(a=>n.get(a)).filter(Boolean)}function ih(e,t){if(e==null)return "NULL";let n=(t??"").toLowerCase();if(Array.isArray(e)&&n.endsWith("[]")){let r=t?.slice(0,-2);return `ARRAY[${e.map(s=>ih(s,r)).join(", ")}]::${t}`}if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return Number.isFinite(e)?String(e):"NULL";if(n.includes("bool")&&(e===0||e===1||e==="0"||e==="1"))return e===1||e==="1"?"true":"false";if(n.includes("json")){let r=typeof e=="string"?e:JSON.stringify(e),s=n.includes("jsonb")?"::jsonb":"::json";return `${Rn(r)}${s}`}return e instanceof Date?Rn(e.toISOString()):typeof e=="object"?`${Rn(JSON.stringify(e))}::jsonb`:Rn(String(e))}function Rn(e){return `'${e.replace(/'/g,"''")}'`}function oc(e){return `"${e.replace(/"/g,'""')}"`}function Qx(e){let t=e.default_value??e.default;if(typeof t=="string"&&t.trim().toLowerCase().startsWith("nextval("))return true;let n=typeof e.type=="string"?e.type.toLowerCase():"",r=typeof e.pg_type=="string"?e.pg_type.toLowerCase():"";return sh.has(n)||sh.has(r)}function Zx(e,t,n){let r=`${oc(e)}.${oc(t)}`;return `SELECT setval(pg_get_serial_sequence(${Rn(r)}, ${Rn(n)}), COALESCE((SELECT MAX(${oc(n)}) FROM ${r}), 1));`}async function eT(e){let t=e.connection.config?.translation?.deparse?.schema;if(t instanceof Map&&t.size>0)return t;let n=await be(e);return n.trim()?(await Wr(n)).schema:new Map}async function Ji(e){let t=await e.connection.introspect(),n=e.connection.dialect,r=await eT(e),s=Yx(t.tables.filter(o=>!Jx.has(Xi(o.schema))),t.foreign_keys),i=[];for(let o of s){let a=Xi(o.schema),l=n==="sqlite"?a==="public"?`"${o.name}"`:`"${a}.${o.name}"`:`"${a}"."${o.name}"`,p=t.columns.filter(E=>E.table===o.name&&Xi(E.schema)===a).filter(E=>!E.generated&&!E.is_generated),u=[];try{u=(await e.connection.exec(`SELECT * FROM ${l}`))?.rows??[];}catch{continue}if(u.length===0)continue;let f=r.get(Vr(a,o.name)),h=typeof e.connection.deserializeRow=="function"?e.connection.deserializeRow.bind(e.connection):E=>E;u=u.map(E=>{let A=f?f.deserializeRow(E):E;return h(A)});let m=p.map(E=>E.name),d=new Map(p.map(E=>[E.name,E.pg_type??E.type])),g=[];for(let E of u){let A=m.map(C=>ih(E[C],d.get(C)));g.push(`INSERT INTO "${a}"."${o.name}" (${m.map(C=>`"${C}"`).join(", ")}) VALUES (${A.join(", ")}) ON CONFLICT DO NOTHING`);}let y=p.filter(Qx).map(E=>Zx(a,o.name,E.name));i.push({schema:a,table:o.name,inserts:g,sequenceResets:y});}return i}var Jx,sh,ac=b(()=>{Hi();tt();Jx=new Set(["auth","storage","realtime","supabase_functions","graphql","graphql_public","extensions","pgsodium","pgsodium_masks","vault","information_schema","pg_catalog","pg_toast"]),sh=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]);});async function oh(e){let{PGlite:t}=await We("@supabase/lite/pglite","pglite","@electric-sql/pglite"),n=new t,r=[],s=0,i=0,o=0,a=0;try{for(let m of ["anon","authenticated","service_role","supabase_auth_admin"])await n.exec(`CREATE ROLE ${m}`);let l=vt(gi);for(let m=0;m<l.length;m++)try{await n.exec(l[m]);}catch(d){return r.push({phase:"schema",label:`auth helpers ${m+1}/${l.length}`,statement:l[m],error:String(d)}),{ok:!1,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:r}}if(e.config.auth?.enabled!==!1){let m=vt(th());s=m.length;for(let d=0;d<m.length;d++)try{await n.exec(m[d]);}catch(g){return r.push({phase:"schema",label:`auth base schema ${d+1}/${m.length}`,statement:m[d],error:String(g)}),{ok:!1,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:r}}}let c=await be(e),p=vt(c);i=p.length;for(let m=0;m<p.length;m++)try{await n.exec(p[m]);}catch(d){return r.push({phase:"schema",label:`schema ${m+1}/${p.length}`,statement:p[m],error:String(d)}),{ok:!1,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:r}}let u=await zi(e,{target:"local"}),f=["users","sessions","identities","refresh_tokens"];for(let m of f){let d=u[m];for(let g=0;g<d.length;g++){o++;try{await n.exec(d[g]);}catch(y){r.push({phase:"auth",label:`auth.${m} row ${g+1}/${d.length}`,statement:d[g],error:String(y)});}}}let h=await Ji(e);for(let m of h){for(let d=0;d<m.inserts.length;d++){a++;try{await n.exec(m.inserts[d]);}catch(g){r.push({phase:"data",label:`${m.schema}.${m.table} row ${d+1}/${m.inserts.length}`,statement:m.inserts[d],error:String(g)});}}for(let d=0;d<m.sequenceResets.length;d++)try{await n.exec(m.sequenceResets[d]);}catch(g){r.push({phase:"data",label:`${m.schema}.${m.table} sequence reset ${d+1}/${m.sequenceResets.length}`,statement:m.sequenceResets[d],error:String(g)});}}}finally{await n.close().catch(()=>{});}return {ok:r.length===0,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:r}}var ah=b(()=>{an();tt();nh();Ir();Vi();ic();ac();});function lh(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 n=t.issues.length>0?P.default.yellow(` (${t.issues.length} issues)`):"",r=t.schema?`${t.schema}.`:"";console.log(` ${r}${t.table}: ${P.default.cyan(t.rowCount)} rows${n}`);}}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 ch(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 uh(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(n=>n.status!=="pass")){let n=t.status==="fail"?P.default.red:P.default.yellow;if(console.log(` ${n(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 r of t.samples)console.log(P.default.dim(` sample ${JSON.stringify(r.id)} raw=${JSON.stringify(r.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 lc(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,ph=b(()=>{P=K(X());});function fh(e){return {kty:"oct",alg:"HS256",k:Buffer$1.from(e,"utf8").toString("base64url")}}var mh=b(()=>{ea();});async function dh(e){let t=e.trim();if(!t)return "";let{PGlite:n}=await We("@supabase/lite/pglite","pglite","@electric-sql/pglite"),r=new n;try{return await r.exec(At($t(t))),await r.exec(gi),await nT(r,t)}finally{await r.close().catch(()=>{});}}async function nT(e,t){return t?(await e.exec(t),await rT(e)):""}async function rT(e){let t=await e.query(`
427
430
  SELECT table_schema, table_name, column_name, is_nullable, data_type,
428
431
  udt_name, udt_schema, character_maximum_length,
429
432
  numeric_precision, numeric_scale, column_default, ordinal_position
@@ -440,28 +443,28 @@ CREATE TABLE IF NOT EXISTS auth.audit_log_entries (
440
443
  WHERE tc.constraint_type = 'PRIMARY KEY'
441
444
  AND tc.table_schema NOT IN ('pg_catalog', 'information_schema', 'pg_toast')
442
445
  ORDER BY kcu.ordinal_position
443
- `),r=new Map;for(let o of n.rows){let a=`${o.table_schema}.${o.table_name}`,l=r.get(a)??[];l.push(o.column_name),r.set(a,l);}let s=new Map;for(let o of t.rows){let a=`${o.table_schema}.${o.table_name}`,l=s.get(a)??[];l.push(o),s.set(a,l);}let i=[];for(let[o,a]of s){let l=a[0].table_schema,c=a[0].table_name,p=r.get(o)??[],u=a.map(f=>Ex(f,p));i.push(`CREATE TABLE ${Vl(l)}.${Vl(c)} (
446
+ `),r=new Map;for(let o of n.rows){let a=`${o.table_schema}.${o.table_name}`,l=r.get(a)??[];l.push(o.column_name),r.set(a,l);}let s=new Map;for(let o of t.rows){let a=`${o.table_schema}.${o.table_name}`,l=s.get(a)??[];l.push(o),s.set(a,l);}let i=[];for(let[o,a]of s){let l=a[0].table_schema,c=a[0].table_name,p=r.get(o)??[],u=a.map(f=>sT(f,p));i.push(`CREATE TABLE ${cc(l)}.${cc(c)} (
444
447
  ${u.join(`,
445
448
  `)}
446
449
  );`);}return i.join(`
447
450
 
448
- `)}function Vl(e){return /^[a-z_][a-z0-9_]*$/.test(e)?e:`"${e.replace(/"/g,'""')}"`}function Ex(e,t){let n=[Vl(e.column_name)];return n.push(_x(e)),e.is_nullable==="NO"&&!t.includes(e.column_name)&&n.push("NOT NULL"),e.column_default!==null&&n.push(`DEFAULT ${e.column_default}`),t.length===1&&t[0]===e.column_name&&n.push("PRIMARY KEY"),n.join(" ")}function _x(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 Xd=b(()=>{tn();Sr();});function Yd(e){return !e||e==="main"?"public":e}function Vt(e){return `"${e.replace(/"/g,'""')}"`}function Tx(e,t){return Vt(e==="public"?t:`${e}.${t}`)}function Kl(e){return `${e.schema}.${e.table}.${e.column}`}function Cx(e){let t=e.filter(s=>s.status==="pass").length,n=e.filter(s=>s.status==="warn").length,r=e.filter(s=>s.status==="fail").length;return {total:e.length,passed:t,warned:n,failed:r,upgrade_safe:r===0}}async function Ax(e){let t=e.connection.config?.translation?.deparse?.schema;if(t instanceof Map&&t.size>0)return t;let n=await Zn(e),r=await re(e);if(n.trim()){let i=[await zd(n),r].filter(o=>o.trim().length>0).join(`
449
- `);return i.trim()?(await kr(i)).schema:new Map}return r.trim()?(await kr(r)).schema:new Map}async function $x(e){let t=await Ax(e),n=[];for(let r of t.values())for(let s of r.all())s.isShimBacked&&n.push({schema:Yd(s.context.schema),table:s.context.table,column:s.context.column,field:s});return n}function vx(e,t){return e==="fail"||t==="fail"?"fail":e==="warn"||t==="warn"?"warn":"pass"}async function Rx(e,t,n){return (await e.connection.introspect()).primary_keys.find(i=>Yd(i.schema)===t&&i.table===n)?.columns??[]}async function kx(e,t){if(e.connection.dialect!=="sqlite")return {field:Kl(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 r=Tx(t.schema,t.table),s=await Rx(e,t.schema,t.table),i=s.length>0?s:["rowid"],a=[...s.length>0?s.map(m=>`${Vt(m)} AS ${Vt(`id_${m}`)}`):[`rowid AS ${Vt("id_rowid")}`],`${Vt(t.column)} AS ${Vt("__lite_value")}`].join(", "),l;try{l=await e.connection.exec(`SELECT ${a} FROM ${r}`);}catch(m){return {field:Kl(t),pg_type:zl(t.field),status:"fail",rows_checked:0,affected_rows:0,message:`Declared shim field could not be scanned in SQLite: ${String(m)}`,action:"Apply the declared schema to the local Supalite database, then rerun the dry-run audit before upgrading."}}let c=l?.rows??[],p="pass",u=0,f=null,h,d=[];for(let m of c){let g=t.field.validateStorage(m.__lite_value);if(p=vx(p,g.status),g.status!=="pass"&&(u++,f??=g.message,h??=g.action,d.length<xx)){let y={};for(let E of i)y[E]=m[`id_${E}`];d.push({id:y,raw_value:m.__lite_value});}}return {field:Kl(t),pg_type:zl(t.field),status:p,rows_checked:c.length,...u>0?{affected_rows:u}:{},message:f,...d.length>0?{samples:d}:{},...h?{action:h}:{}}}function zl(e){if(e instanceof yt)return `${e.elementField?zl(e.elementField):e.context.pgTypeName}[]`;if(e instanceof Ut&&e.numericPrecision){let{precision:t,scale:n}=e.numericPrecision;return `${e.context.pgTypeName}(${t},${n})`}return e instanceof le&&e.lengthConstraint!==void 0?`${e.context.pgTypeName}(${e.lengthConstraint})`:e.context.pgTypeName}async function Xl(e){let t=await $x(e),n=[];for(let r of t)n.push(await kx(e,r));return {summary:Cx(n),results:n}}var xx,Jd=b(()=>{Ue();dt();Xd();Ai();Hs();qs();Fe();xx=3;});function Qd(e){let t=e.auth??{},n={};return typeof t.site_url=="string"&&(n.site_url=t.site_url),Array.isArray(t.additional_redirect_urls)&&(n.uri_allow_list=t.additional_redirect_urls.join(",")),typeof t.jwt_expiry=="number"&&(n.jwt_exp=t.jwt_expiry),typeof t.enable_signup=="boolean"&&(n.disable_signup=!t.enable_signup),typeof t.enable_anonymous_sign_ins=="boolean"&&(n.external_anonymous_users_enabled=t.enable_anonymous_sign_ins),typeof t.minimum_password_length=="number"&&(n.min_password_length=t.minimum_password_length),typeof t.email?.enable_confirmations=="boolean"&&(n.mailer_autoconfirm=!t.email.enable_confirmations),n}var Zd=b(()=>{});function Nx(e){if(e.length===0)return "";if(e.length===1)return e[0];let t=e[0].match(eh);if(!t)return e.map(i=>i.trim().endsWith(";")?i:`${i};`).join(" ");let n=t[1],r=t[3]??"",s=[t[2]];for(let i=1;i<e.length;i++){let o=e[i].match(eh);if(!o||o[1]!==n||(o[3]??"")!==r)return e.map(a=>a.trim().endsWith(";")?a:`${a};`).join(" ");s.push(o[2]);}return `${n}${s.join(", ")}${r}`}async function th(e,t,n={}){let r=n.sizes??[50,10,1],s=[],i=0,o=t.length,a=async(l,c)=>{if(l.length===0)return;let p=r[c]??1;if(l.length===1||p===1){for(let u of l){try{await e.runSql(u);}catch(f){s.push({statement:u,error:String(f)});}i++,n.onProgress?.(i,o);}return}for(let u=0;u<l.length;u+=p){let f=l.slice(u,u+p),h=Nx(f);try{await e.runSql(h),i+=f.length,n.onProgress?.(i,o);}catch{await a(f,c+1);}}};return await a(t,0),s}var eh,nh=b(()=>{eh=/^(INSERT INTO [^(]+\([^)]+\)\s*VALUES\s*)(\(.*\))(\s*ON CONFLICT[\s\S]*)?$/i;});async function Px(e,t,n,r){r.onSql?.(t,n);try{await e.runSql(t);}catch(s){throw new Error(`Failed SQL (${n}): ${String(s)}
450
- ${t}`,{cause:s})}}async function Sn(e,t,n,r,s={}){if(n.length===0)return;r.onBatchStart?.(t,n.length);let i=await th(e,n,{sizes:s.sizes??r.batchSizes,onProgress:(o,a)=>r.onBatchProgress?.(t,o,a)});if(i.length>0)throw r.onBatchFailure?.(t,i),new Error(`${t} had ${i.length} failures`);r.onBatchEnd?.(t,n.length,s.unit??"rows");}async function Yl(e,t,n){let r=await re(e),s=_t(r);n.onSchemaStart?.(s.length);for(let c=0;c<s.length;c++)n.onSchemaProgress?.(c+1,s.length),await Px(t,s[c],`schema ${c+1}/${s.length}`,n);n.onSchemaEnd?.(s.length);let i=await Ni(e,{target:n.authTarget??"supabase"}),o={users:i.users.length,sessions:n.migrateSessions?i.sessions.length:0,identities:i.identities.length,refresh_tokens:n.migrateSessions?i.refresh_tokens.length:0};await Sn(t,"Migrating auth.users",i.users,n),await Sn(t,"Migrating auth.identities",i.identities,n),n.migrateSessions?(await Sn(t,"Migrating auth.sessions",i.sessions,n),await Sn(t,"Migrating auth.refresh_tokens",i.refresh_tokens,n)):(i.sessions.length>0||i.refresh_tokens.length>0)&&n.onSkip?.(`Skipped ${i.sessions.length} sessions and ${i.refresh_tokens.length} refresh tokens (existing tokens will be invalidated).`);let a=await Li(e),l=a.filter(c=>c.inserts.length>0);l.length===0&&n.onSkip?.("No user data rows to migrate.");for(let c of l)await Sn(t,`Migrating ${c.schema}.${c.table}`,c.inserts,n);for(let c of l)await Sn(t,`Resetting ${c.schema}.${c.table} sequences`,c.sequenceResets,n,{sizes:[1],unit:"statements"});if(n.syncAuthConfig!==false&&t.updateAuthConfig){let c=Qd(e.config);Object.keys(c).length>0&&(n.onAuthConfigStart?.(),await t.updateAuthConfig(c),n.onAuthConfigEnd?.());}return {schemaStatements:s.length,auth:o,dataTables:a}}var rh=b(()=>{Ue();Zd();ql();Gl();nh();Ri();});function Or(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}function sh(e,t=new Map){if(!e||typeof e!="object")return t;for(let[n,r]of Object.entries(e))typeof r=="string"?t.set(Or(n),r):r&&typeof r=="object"&&sh(r,t);return t}function Pr(e,t,n){for(let r of t){let s=e.get(Or(r));if(s)return s}throw new Error(`Supabase status JSON is missing ${n}`)}function jx(e){let t=JSON.parse(e),n=sh(t);return {apiUrl:Pr(n,["API_URL","api_url","API URL","Project URL"],"API URL"),studioUrl:n.get(Or("Studio URL"))??n.get(Or("STUDIO_URL"))??n.get(Or("studio_url")),dbUrl:Pr(n,["DB_URL","db_url","DB URL"],"DB URL"),anonKey:Pr(n,["ANON_KEY","anon_key","anon key","Publishable"],"anon key"),serviceRoleKey:Pr(n,["SERVICE_ROLE_KEY","service_role_key","service role key","Secret"],"service role key"),jwtSecret:Pr(n,["JWT_SECRET","jwt_secret","JWT secret"],"JWT secret")}}function ih(e){try{return decodeURIComponent(new URL(e).password)}catch{return ""}}function oh(e=process.cwd()){return e}async function Fx(){return await new Promise((e,t)=>{let n=Lx.createServer();n.once("error",t),n.listen(0,"127.0.0.1",()=>{let r=n.address();n.close(()=>{typeof r=="object"&&r?e(r.port):t(new Error("Could not allocate a free local port"));});});})}async function Ux(){let e=new Set,t=async()=>{for(;;){let n=await Fx();if(!e.has(n))return e.add(n),n}};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 Lr(e,t={}){let n=process.env.LITE_SUPABASE_CLI?.split(/\s+/).filter(Boolean)??Ix,{spawn:r}=await import('node:child_process').catch(()=>{throw new Error("Local Supabase upgrade requires a Node-compatible runtime")}),[s,...i]=n;return await new Promise((o,a)=>{let l=r(s,[...i,...e],{cwd:t.cwd,env:{...process.env,SUPABASE_TELEMETRY_DISABLED:"1",DO_NOT_TRACK:"1"}}),c=[],p=[],u=setTimeout(()=>l.kill(),t.timeoutMs??12e4);l.stdout?.on("data",f=>c.push(Buffer.from(f))),l.stderr?.on("data",f=>p.push(Buffer.from(f))),l.on("error",f=>{clearTimeout(u),a(f);}),l.on("close",f=>{clearTimeout(u);let h=Buffer.concat(c).toString("utf8"),d=Buffer.concat(p).toString("utf8");if(f!==0){a(new Error([`supabase ${e.join(" ")} failed with exit code ${f}`,h,d].filter(Boolean).join(`
451
- `)));return}o({stdout:h,stderr:d});});})}function ie(e,t,n,r){let s=new RegExp(`(\\[${t.replace(".","\\.")}\\][\\s\\S]*?)(?=\\n\\[|$)`),i=e.match(s);if(!i)return `${e.trimEnd()}
451
+ `)}function cc(e){return /^[a-z_][a-z0-9_]*$/.test(e)?e:`"${e.replace(/"/g,'""')}"`}function sT(e,t){let n=[cc(e.column_name)];return n.push(iT(e)),e.is_nullable==="NO"&&!t.includes(e.column_name)&&n.push("NOT NULL"),e.column_default!==null&&n.push(`DEFAULT ${e.column_default}`),t.length===1&&t[0]===e.column_name&&n.push("PRIMARY KEY"),n.join(" ")}function iT(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 hh=b(()=>{an();Ir();});function gh(e){return !e||e==="main"?"public":e}function Yt(e){return `"${e.replace(/"/g,'""')}"`}function aT(e,t){return Yt(e==="public"?t:`${e}.${t}`)}function uc(e){return `${e.schema}.${e.table}.${e.column}`}function lT(e){let t=e.filter(s=>s.status==="pass").length,n=e.filter(s=>s.status==="warn").length,r=e.filter(s=>s.status==="fail").length;return {total:e.length,passed:t,warned:n,failed:r,upgrade_safe:r===0}}async function cT(e){let t=e.connection.config?.translation?.deparse?.schema;if(t instanceof Map&&t.size>0)return t;let n=await Lr(e),r=await be(e);if(n.trim()){let i=[await dh(n),r].filter(o=>o.trim().length>0).join(`
452
+ `);return i.trim()?(await Wr(i)).schema:new Map}return r.trim()?(await Wr(r)).schema:new Map}async function uT(e){let t=await cT(e),n=[];for(let r of t.values())for(let s of r.all())s.isShimBacked&&n.push({schema:gh(s.context.schema),table:s.context.table,column:s.context.column,field:s});return n}function pT(e,t){return e==="fail"||t==="fail"?"fail":e==="warn"||t==="warn"?"warn":"pass"}async function fT(e,t,n){return (await e.connection.introspect()).primary_keys.find(i=>gh(i.schema)===t&&i.table===n)?.columns??[]}async function mT(e,t){if(e.connection.dialect!=="sqlite")return {field:uc(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 r=aT(t.schema,t.table),s=await fT(e,t.schema,t.table),i=s.length>0?s:["rowid"],a=[...s.length>0?s.map(d=>`${Yt(d)} AS ${Yt(`id_${d}`)}`):[`rowid AS ${Yt("id_rowid")}`],`${Yt(t.column)} AS ${Yt("__lite_value")}`].join(", "),l;try{l=await e.connection.exec(`SELECT ${a} FROM ${r}`);}catch(d){return {field:uc(t),pg_type:pc(t.field),status:"fail",rows_checked:0,affected_rows:0,message:`Declared shim field could not be scanned in SQLite: ${String(d)}`,action:"Apply the declared schema to the local Supalite database, then rerun the dry-run audit before upgrading."}}let c=l?.rows??[],p="pass",u=0,f=null,h,m=[];for(let d of c){let g=t.field.validateStorage(d.__lite_value);if(p=pT(p,g.status),g.status!=="pass"&&(u++,f??=g.message,h??=g.action,m.length<oT)){let y={};for(let E of i)y[E]=d[`id_${E}`];m.push({id:y,raw_value:d.__lite_value});}}return {field:uc(t),pg_type:pc(t.field),status:p,rows_checked:c.length,...u>0?{affected_rows:u}:{},message:f,...m.length>0?{samples:m}:{},...h?{action:h}:{}}}function pc(e){if(e instanceof Ct)return `${e.elementField?pc(e.elementField):e.context.pgTypeName}[]`;if(e instanceof Gt&&e.numericPrecision){let{precision:t,scale:n}=e.numericPrecision;return `${e.context.pgTypeName}(${t},${n})`}return e instanceof ce&&e.lengthConstraint!==void 0?`${e.context.pgTypeName}(${e.lengthConstraint})`:e.context.pgTypeName}async function fc(e){let t=await uT(e),n=[];for(let r of t)n.push(await mT(e,r));return {summary:lT(n),results:n}}var oT,yh=b(()=>{tt();Kt();hh();Hi();fi();pi();Ue();oT=3;});function bh(e){let t=e.auth??{},n={};return typeof t.site_url=="string"&&(n.site_url=t.site_url),Array.isArray(t.additional_redirect_urls)&&(n.uri_allow_list=t.additional_redirect_urls.join(",")),typeof t.jwt_expiry=="number"&&(n.jwt_exp=t.jwt_expiry),typeof t.enable_signup=="boolean"&&(n.disable_signup=!t.enable_signup),typeof t.enable_anonymous_sign_ins=="boolean"&&(n.external_anonymous_users_enabled=t.enable_anonymous_sign_ins),typeof t.minimum_password_length=="number"&&(n.min_password_length=t.minimum_password_length),typeof t.email?.enable_confirmations=="boolean"&&(n.mailer_autoconfirm=!t.email.enable_confirmations),n}var wh=b(()=>{});function dT(e){if(e.length===0)return "";if(e.length===1)return e[0];let t=e[0].match(Sh);if(!t)return e.map(i=>i.trim().endsWith(";")?i:`${i};`).join(" ");let n=t[1],r=t[3]??"",s=[t[2]];for(let i=1;i<e.length;i++){let o=e[i].match(Sh);if(!o||o[1]!==n||(o[3]??"")!==r)return e.map(a=>a.trim().endsWith(";")?a:`${a};`).join(" ");s.push(o[2]);}return `${n}${s.join(", ")}${r}`}async function Eh(e,t,n={}){let r=n.sizes??[50,10,1],s=[],i=0,o=t.length,a=async(l,c)=>{if(l.length===0)return;let p=r[c]??1;if(l.length===1||p===1){for(let u of l){try{await e.runSql(u);}catch(f){s.push({statement:u,error:String(f)});}i++,n.onProgress?.(i,o);}return}for(let u=0;u<l.length;u+=p){let f=l.slice(u,u+p),h=dT(f);try{await e.runSql(h),i+=f.length,n.onProgress?.(i,o);}catch{await a(f,c+1);}}};return await a(t,0),s}var Sh,_h=b(()=>{Sh=/^(INSERT INTO [^(]+\([^)]+\)\s*VALUES\s*)(\(.*\))(\s*ON CONFLICT[\s\S]*)?$/i;});async function hT(e,t,n,r){r.onSql?.(t,n);try{await e.runSql(t);}catch(s){throw new Error(`Failed SQL (${n}): ${String(s)}
453
+ ${t}`,{cause:s})}}async function vn(e,t,n,r,s={}){if(n.length===0)return;r.onBatchStart?.(t,n.length);let i=await Eh(e,n,{sizes:s.sizes??r.batchSizes,onProgress:(o,a)=>r.onBatchProgress?.(t,o,a)});if(i.length>0)throw r.onBatchFailure?.(t,i),new Error(`${t} had ${i.length} failures`);r.onBatchEnd?.(t,n.length,s.unit??"rows");}async function mc(e,t,n){let r=await be(e),s=vt(r);n.onSchemaStart?.(s.length);for(let c=0;c<s.length;c++)n.onSchemaProgress?.(c+1,s.length),await hT(t,s[c],`schema ${c+1}/${s.length}`,n);n.onSchemaEnd?.(s.length);let i=await zi(e,{target:n.authTarget??"supabase"}),o={users:i.users.length,sessions:n.migrateSessions?i.sessions.length:0,identities:i.identities.length,refresh_tokens:n.migrateSessions?i.refresh_tokens.length:0};await vn(t,"Migrating auth.users",i.users,n),await vn(t,"Migrating auth.identities",i.identities,n),n.migrateSessions?(await vn(t,"Migrating auth.sessions",i.sessions,n),await vn(t,"Migrating auth.refresh_tokens",i.refresh_tokens,n)):(i.sessions.length>0||i.refresh_tokens.length>0)&&n.onSkip?.(`Skipped ${i.sessions.length} sessions and ${i.refresh_tokens.length} refresh tokens (existing tokens will be invalidated).`);let a=await Ji(e),l=a.filter(c=>c.inserts.length>0);l.length===0&&n.onSkip?.("No user data rows to migrate.");for(let c of l)await vn(t,`Migrating ${c.schema}.${c.table}`,c.inserts,n);for(let c of l)await vn(t,`Resetting ${c.schema}.${c.table} sequences`,c.sequenceResets,n,{sizes:[1],unit:"statements"});if(n.syncAuthConfig!==false&&t.updateAuthConfig){let c=bh(e.config);Object.keys(c).length>0&&(n.onAuthConfigStart?.(),await t.updateAuthConfig(c),n.onAuthConfigEnd?.());}return {schemaStatements:s.length,auth:o,dataTables:a}}var xh=b(()=>{tt();wh();ic();ac();_h();Vi();});function Xr(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}function Th(e,t=new Map){if(!e||typeof e!="object")return t;for(let[n,r]of Object.entries(e))typeof r=="string"?t.set(Xr(n),r):r&&typeof r=="object"&&Th(r,t);return t}function Kr(e,t,n){for(let r of t){let s=e.get(Xr(r));if(s)return s}throw new Error(`Supabase status JSON is missing ${n}`)}function ST(e){let t=JSON.parse(e),n=Th(t);return {apiUrl:Kr(n,["API_URL","api_url","API URL","Project URL"],"API URL"),studioUrl:n.get(Xr("Studio URL"))??n.get(Xr("STUDIO_URL"))??n.get(Xr("studio_url")),dbUrl:Kr(n,["DB_URL","db_url","DB URL"],"DB URL"),anonKey:Kr(n,["ANON_KEY","anon_key","anon key","Publishable"],"anon key"),serviceRoleKey:Kr(n,["SERVICE_ROLE_KEY","service_role_key","service role key","Secret"],"service role key"),jwtSecret:Kr(n,["JWT_SECRET","jwt_secret","JWT secret"],"JWT secret")}}function Ch(e){try{return decodeURIComponent(new URL(e).password)}catch{return ""}}function Ah(e=process.cwd()){return e}async function ET(){return await new Promise((e,t)=>{let n=gT.createServer();n.once("error",t),n.listen(0,"127.0.0.1",()=>{let r=n.address();n.close(()=>{typeof r=="object"&&r?e(r.port):t(new Error("Could not allocate a free local port"));});});})}async function _T(){let e=new Set,t=async()=>{for(;;){let n=await ET();if(!e.has(n))return e.add(n),n}};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 zr(e,t={}){let n=process.env.LITE_SUPABASE_CLI?.split(/\s+/).filter(Boolean)??bT,{spawn:r}=await import('node:child_process').catch(()=>{throw new Error("Local Supabase upgrade requires a Node-compatible runtime")}),[s,...i]=n;return await new Promise((o,a)=>{let l=r(s,[...i,...e],{cwd:t.cwd,env:{...process.env,SUPABASE_TELEMETRY_DISABLED:"1",DO_NOT_TRACK:"1"}}),c=[],p=[],u=setTimeout(()=>l.kill(),t.timeoutMs??12e4);l.stdout?.on("data",f=>c.push(Buffer.from(f))),l.stderr?.on("data",f=>p.push(Buffer.from(f))),l.on("error",f=>{clearTimeout(u),a(f);}),l.on("close",f=>{clearTimeout(u);let h=Buffer.concat(c).toString("utf8"),m=Buffer.concat(p).toString("utf8");if(f!==0){a(new Error([`supabase ${e.join(" ")} failed with exit code ${f}`,h,m].filter(Boolean).join(`
454
+ `)));return}o({stdout:h,stderr:m});});})}function ae(e,t,n,r){let s=new RegExp(`(\\[${t.replace(".","\\.")}\\][\\s\\S]*?)(?=\\n\\[|$)`),i=e.match(s);if(!i)return `${e.trimEnd()}
452
455
 
453
456
  [${t}]
454
457
  ${n} = ${r}
455
458
  `;let o=i[1],a=new RegExp(`(^${n}\\s*=\\s*).*$`,"m"),l=a.test(o)?o.replace(a,`$1${r}`):`${o.trimEnd()}
456
459
  ${n} = ${r}
457
- `;return e.replace(o,l)}function Mx(e,t,n){let r=new RegExp(`(\\[${t.replace(".","\\.")}\\][\\s\\S]*?)(?=\\n\\[|$)`),s=e.match(r);if(!s)return e;let i=s[1],o=n.map(l=>l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),a=new RegExp(`^\\s*(${o})\\s*=.*(?:\\n|$)`,"gm");return e.replace(i,i.replace(a,""))}function Bx(e){return Mx(e,"db",["driver","url"])}function qx(e){let t=e.match(/(\[db\][\s\S]*?)(?=\n\[|$)/)?.[1];return t?/^\s*driver\s*=\s*["'](sqlite|sqlite-postgres|pglite|postgres)["']/m.test(t)?true:/^\s*url\s*=/m.test(t):false}async function Jl(e){return await de__default.access(e).then(()=>true).catch(()=>false)}async function ah(e){let t=Ie__default.join(e,"supabase","config.toml");if(!await Jl(t))return null;let n=await de__default.readFile(t,"utf-8");if(!qx(n))return null;let r=`${t}.bak`;return await Jl(r)||await de__default.writeFile(r,n,"utf-8"),r}async function Hx(e){let t=Ie__default.join(e,"supabase","config.toml");await Jl(t)||(await de__default.mkdir(e,{recursive:true}),await Lr(["init","--workdir",e,"--yes"],{timeoutMs:6e4}));}async function Gx(e,t,n){let r=Ie__default.join(e,"supabase","config.toml"),s=Bx(await de__default.readFile(r,"utf-8"));s=s.replace(/^project_id\s*=.*$/m,`project_id = "${t}"`),s=ie(s,"api","port",String(n.api)),s=ie(s,"db","port",String(n.db)),s=ie(s,"db","shadow_port",String(n.shadow)),s=ie(s,"db","major_version","15"),s=ie(s,"db.seed","enabled","false"),s=ie(s,"studio","enabled","true"),s=ie(s,"studio","port",String(n.studio)),s=ie(s,"inbucket","enabled","false"),s=ie(s,"inbucket","port",String(n.inbucket)),s=ie(s,"realtime","enabled","false"),s=ie(s,"storage","enabled","false"),s=ie(s,"edge_runtime","enabled","false"),s=ie(s,"edge_runtime","inspector_port",String(n.edgeInspector)),s=ie(s,"analytics","enabled","false"),s=ie(s,"analytics","port",String(n.analytics)),s=ie(s,"db.pooler","enabled","false"),s=ie(s,"db.pooler","port",String(n.pooler)),await de__default.writeFile(r,s,"utf-8");}function lh(e){return JSON.stringify(e)}function Wx(e){return `[${e.map(lh).join(", ")}]`}async function Vx(e,t){if(!t)return;let n=Ie__default.join(e,"supabase","config.toml"),r=await de__default.readFile(n,"utf-8"),s=t.auth??{},i=s.email??{},o=t.api??{};typeof o.max_rows=="number"&&(r=ie(r,"api","max_rows",String(o.max_rows))),typeof s.site_url=="string"&&(r=ie(r,"auth","site_url",lh(s.site_url))),Array.isArray(s.additional_redirect_urls)&&(r=ie(r,"auth","additional_redirect_urls",Wx(s.additional_redirect_urls))),typeof s.jwt_expiry=="number"&&(r=ie(r,"auth","jwt_expiry",String(s.jwt_expiry))),typeof s.enable_signup=="boolean"&&(r=ie(r,"auth","enable_signup",String(s.enable_signup))),typeof s.enable_anonymous_sign_ins=="boolean"&&(r=ie(r,"auth","enable_anonymous_sign_ins",String(s.enable_anonymous_sign_ins))),typeof s.minimum_password_length=="number"&&(r=ie(r,"auth","minimum_password_length",String(s.minimum_password_length))),typeof i.enable_confirmations=="boolean"&&(r=ie(r,"auth.email","enable_confirmations",String(i.enable_confirmations))),await de__default.writeFile(n,r,"utf-8");}var Ix,Dx,Oi,ch=b(()=>{tn();Ix=["bunx","supabase@2.98.1"],Dx=["mailpit","realtime","storage-api","imgproxy","edge-runtime","logflare","vector","supavisor"];Oi=class e{constructor(t,n,r,s){this.workdir=t;this.projectId=n;this.status=r;this.cleanupOnStop=s;}stopped=false;static async start(t={}){let n=t.workdir??await de__default.mkdtemp(Ie__default.join(Ny.tmpdir(),"lite-local-supa-")),r=t.projectId??`lite-local-${Date.now().toString(36)}`,s=t.cleanupOnStop??!t.workdir,i=await Ux();try{await Hx(n),await Gx(n,r,i),await Vx(n,t.sourceConfig),await Lr(["start","--workdir",n,"--yes","--exclude",Dx.join(",")],{timeoutMs:5*6e4});let{stdout:o}=await Lr(["status","--workdir",n,"-o","json"],{timeoutMs:6e4});return new e(n,r,jx(o),s)}catch(o){throw await Lr(["stop","--workdir",n,"--no-backup"],{timeoutMs:12e4}).catch(()=>{}),s&&await de__default.rm(n,{recursive:true,force:true}).catch(()=>{}),o}}async runSql(t){let{createPostgresConnection:n}=await qe("@supabase/lite/postgres","postgres","postgres"),r=n({url:this.status.dbUrl});try{await r.exec(t);}finally{await r.close();}}async stop(){this.stopped||(this.stopped=true,await Lr(["stop","--workdir",this.workdir,"--no-backup"],{timeoutMs:12e4}).catch(()=>{}),this.cleanupOnStop&&await de__default.rm(this.workdir,{recursive:true,force:true}));}};});async function Ii(){let e=await $r({message:"Email",placeholder:"Enter your email",validate:t=>{try{jc(t,{domains:["supabase.io"],panic:!0});return}catch(n){return n}}});return be(e)&&process.exit(1),e}async function Di(e=false){let t=await Cr({message:"Password",validate:n=>{try{Fc(n,{panic:!0});return}catch(r){return r}}});if(be(t)&&process.exit(1),e){let n=await Cr({message:"Confirm Password",validate:r=>{try{if(r!==t)throw new Error("Passwords do not match");return}catch(s){return s}}});be(n)&&process.exit(1);}return t}async function ji(){let e=await $r({message:"Project Name",placeholder:"Enter your project name",validate:t=>t?.trim()?void 0:"Project name is required"});return be(e)&&process.exit(1),e.trim()}async function Fi(e){let t=await Tr({message:e,initialValue:true});return be(t)&&process.exit(1),t}var En=b(()=>{Qe();Pn();});var dh={};fe(dh,{isNonInteractive:()=>Ql,resolveSessionMigration:()=>mh,resolveTarget:()=>fh,upgrade:()=>tT});async function zx(e,t){let n=await e.listOrganizations();if(n.length===0)throw new Error("No Supabase organizations found for this token");if(t){let s=n.find(i=>i.id===t||i.slug===t);if(!s)throw new Error(`Organization not found: ${t}`);return s}if(n.length===1)return n[0];let r=await Ar({message:"Select organization",options:n.map(s=>({value:s.id,label:`${s.name} (${s.slug})`}))});return be(r)&&process.exit(1),n.find(s=>s.id===r)}async function Yx(e,t,n){if(n)return n;let r=Xx;try{let o=(await e.listRegions(t)).regions??[];o.length>0&&(r=o.map(a=>({key:a.key,label:a.display_name??a.name??a.key})));}catch{}let s=await Ar({message:"Select region",options:r.map(i=>({value:i.key,label:i.label}))});return be(s)&&process.exit(1),s}async function Jx(e){if(e)return e;let t=await $r({message:"Project name",placeholder:"my-project",validate:n=>n&&n.trim().length>0?void 0:"Name is required"});return be(t)&&process.exit(1),t}function Qx(){return Kx.randomBytes(24).toString("base64url")}function fh(e){let t=e??"hosted";if(t==="hosted"||t==="local")return t;throw new Error(`Unknown upgrade target '${t}'. Use 'hosted' or 'local'.`)}function Ql(){return process.env.CI==="true"||process.env.LITE_NON_INTERACTIVE==="1"||!process.stdin.isTTY}async function Zx(e){if(typeof e=="boolean")return e;if(Ql())return false;let t=await Tr({message:"Migrate existing sessions (transfers JWT secret, sessions, refresh tokens)?",initialValue:false});return be(t)&&process.exit(1),t}async function eT(e){if(e)return e;let t=process.env.SUPABASE_ACCESS_TOKEN;if(t)return t;X.info("Create a personal access token at https://supabase.com/dashboard/account/tokens");let n=await Cr({message:"Supabase access token",validate:r=>r&&r.trim().length>0?void 0:"Token is required"});return be(n)&&process.exit(1),n}async function mh(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=Un(e.jwtSecret);if(t.strong||e.allowWeakJwtSecret)return {migrateSessions:true,jwtSecret:e.jwtSecret,weakReasons:t.reasons};if(Ql())throw new Error(["Cannot migrate sessions because auth.jwt_secret looks weak:",...t.reasons.map(r=>`- ${r}`),"Use --allow-weak-jwt-secret to preserve existing sessions anyway, or --no-migrate-sessions to require users to sign in again."].join(`
458
- `));X.warning(["auth.jwt_secret looks weak and will become a trusted Supabase signing key:",...t.reasons.map(r=>`- ${r}`)].join(`
459
- `));let n=await Tr({message:"Preserve existing sessions anyway by importing this JWT secret?",initialValue:false});return be(n)&&process.exit(1),n?{migrateSessions:true,jwtSecret:e.jwtSecret,weakReasons:t.reasons}:{migrateSessions:false,weakReasons:t.reasons}}var Se,Xx,tT,hh=b(()=>{Se=V(z());Qe();Le();Te();Cd();Ld();Bd();Wd();Kd();Jd();rh();ch();En();Rr();Ee();Xx=[{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)"}];tT=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 n=t.dryRun&&t.json,r=console.log;n||console.log(),await J(async()=>{await ee(t.config);let s=fh(t.target);if(Ol("upgrade.target",s),Ol("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.");n&&(console.log=()=>{});let i;try{i=await(await W({withSupabaseClient:!1})).project.local.createApp(t.config);}finally{n&&(console.log=r);}if(n){let w=await Xl(i);r(JSON.stringify(w,null,2)),w.summary.upgrade_safe||process.exit(1);return}console.log(Se.default.dim("Running readiness checks..."));let o=await vr("readiness",()=>Pd(i));if(qd(o),!o.ok)throw new Error("Readiness checks failed. See errors above.");let a=async()=>{console.log(Se.default.dim(`
460
- Rehearsing upgrade against in-memory pglite...`));let w=await vr("rehearsal",()=>Md(i));return Hd(w),w.ok};if(t.dryRun){let w=await Xl(i);Gd(w),w.summary.upgrade_safe||process.exit(1),await a()||process.exit(1);return}if(!t.force&&!await Fi("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=Ie__default.resolve(t.localDir??oh()),I=await ah(w),P=null;if(I){let D=Ie__default.relative(process.cwd(),I)||I;P=`Your project's supabase/config.toml was rewritten in place for the local Supabase CLI. The original was backed up to ${D}. To resume supalite dev (bun run dev), restore it: cp ${D} supabase/config.toml (or git checkout supabase/config.toml). Pass --local-dir <separate-dir> next time to keep the local stack isolated.`;}let j=Ll(),S,_;try{j.start(`Starting local Supabase in ${w}`),S=await Oi.start({workdir:w,cleanupOnStop:!1,sourceConfig:i.config}),j.stop(`Local Supabase is running at ${S.status.apiUrl}`),_=await vr("apply",()=>Yl(i,S,{migrateSessions:!1,authTarget:"supabase",syncAuthConfig:!1,onSql:(D,oe)=>{t.verbose&&console.log(Se.default.dim(`-- ${oe}
461
- ${D}`));},onSchemaStart:D=>j.start(`Applying schema (0/${D})`),onSchemaProgress:(D,oe)=>j.message(`Applying schema (${D}/${oe})`),onSchemaEnd:D=>j.stop(`Schema applied (${D} statements)`),onBatchStart:(D,oe)=>j.start(`${D} (0/${oe})`),onBatchProgress:(D,oe,ce)=>j.message(`${D} (${oe}/${ce})`),onBatchEnd:(D,oe,ce)=>j.stop(`${D} (${oe} ${ce})`),onBatchFailure:(D,oe)=>{j.stop(Se.default.red(`${D}: ${oe.length} failed`));for(let ce of oe)console.log(Se.default.red(` \u2717 ${ce.error}`)),t.verbose&&console.log(Se.default.dim(` ${ce.statement}`));},onSkip:D=>console.log(Se.default.dim(D))}));}catch(D){throw P&&console.log(Se.default.yellow(`
462
- ${P}`)),D}let Z=["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."];P&&Z.unshift(P),i.config.storage?.enabled&&Z.push("Storage migration is not yet supported."),i.config.realtime?.enabled&&Z.push("Realtime config migration is not yet supported.");let B=ih(S.status.dbUrl);if(t.dumpCredentials){let D=JSON.stringify({target:"local",workdir:S.workdir,projectUrl:S.status.apiUrl,apiUrl:S.status.apiUrl,studioUrl:S.status.studioUrl,dbUrl:S.status.dbUrl,anonKey:S.status.anonKey,serviceRoleKey:S.status.serviceRoleKey,dbPassword:B},null,2);await de__default.writeFile(t.dumpCredentials,D,"utf-8"),console.log(Se.default.dim(`Credentials written to ${t.dumpCredentials}`));}Wl({projectRef:S.projectId,projectUrl:S.status.apiUrl,apiUrl:S.status.apiUrl,studioUrl:S.status.studioUrl,anonKey:S.status.anonKey,serviceRoleKey:S.status.serviceRoleKey,dbPassword:B,auth:_.auth,jwtMigrated:!1,warnings:[`Local Supabase workdir: ${S.workdir}`,...Z]});return}let c=await eT(t.supabaseToken),p=new vi(c);try{await p.listOrganizations();}catch(w){throw new Error(`Supabase access token rejected: ${String(w)}`)}let u=await zx(p,t.orgId),f=await Yx(p,u.slug,t.region),h=await Jx(t.projectName),d=await Zx(t.migrateSessions),m=await mh({requested:d,jwtSecret:i.config.auth?.jwt_secret,allowWeakJwtSecret:t.allowWeakJwtSecret}),g=m.migrateSessions,y=Qx(),E=Ll();E.start("Creating Supabase project");let A=await p.createProject({organization_id:u.id,name:h,db_pass:y,region:f}),C=A.ref??A.id;if(E.stop(`Project created: ${C}`),E.start("Waiting for project to become active"),await p.waitForActive(C,{onTick:w=>E.message(`Project status: ${w}`)}),E.stop("Project is active"),g){E.start("Importing JWT signing key");try{await p.createSigningKey(C,{algorithm:"HS256",status:"in_use",private_jwk:Vd(m.jwtSecret)});}catch(w){throw E.stop(Se.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(" "))}E.stop("JWT signing key imported");}let $=(await vr("apply",()=>Yl(i,{runSql:w=>p.runSql(C,w),updateAuthConfig:w=>p.updateAuthConfig(C,w)},{migrateSessions:g,authTarget:"supabase",onSql:(w,I)=>{t.verbose&&console.log(Se.default.dim(`-- ${I}
463
- ${w}`));},onSchemaStart:w=>E.start(`Applying schema (0/${w})`),onSchemaProgress:(w,I)=>E.message(`Applying schema (${w}/${I})`),onSchemaEnd:w=>E.stop(`Schema applied (${w} statements)`),onBatchStart:(w,I)=>{E.start(`${w} (0/${I})`);},onBatchProgress:(w,I,P)=>E.message(`${w} (${I}/${P})`),onBatchEnd:(w,I,P)=>E.stop(`${w} (${I} ${P})`),onBatchFailure:(w,I)=>{E.stop(Se.default.red(`${w}: ${I.length} failed`));for(let P of I)console.log(Se.default.red(` \u2717 ${P.error}`)),t.verbose&&console.log(Se.default.dim(` ${P.statement}`));},onAuthConfigStart:()=>E.start("Syncing auth config"),onAuthConfigEnd:()=>E.stop("Auth config synced"),onSkip:w=>console.log(Se.default.dim(w))}))).auth,T=Td(await p.getApiKeys(C)),x=`https://${C}.${p.projectDomain}`,O=[];if(g?m.weakReasons.length>0?O.push(`A weak JWT secret was imported to preserve sessions: ${m.weakReasons.join("; ")}.`):O.push("Sessions preserved by importing auth.jwt_secret as a Supabase signing key."):O.push("Sessions and JWT secret not migrated. Existing tokens are invalid \u2014 users must re-authenticate."),i.config.storage?.enabled&&O.push("Storage migration is not yet supported."),i.config.realtime?.enabled&&O.push("Realtime config migration is not yet supported."),t.dumpCredentials){let w=JSON.stringify({ref:C,projectUrl:x,anonKey:T.anon,serviceRoleKey:T.service_role,dbPassword:y},null,2);await de__default.writeFile(t.dumpCredentials,w,"utf-8"),console.log(Se.default.dim(`Credentials written to ${t.dumpCredentials}`));}Wl({projectRef:C,projectUrl:x,apiUrl:x,anonKey:T.anon,serviceRoleKey:T.service_role,dbPassword:y,auth:$,jwtMigrated:!!(g&&m.jwtSecret),warnings:O});});});});var gh={};fe(gh,{login:()=>nT});var Zl,nT,yh=b(()=>{Zl=V(z());Qe();En();Le();Te();nT=e=>{e.command("login").description("Login").option("--json","Output in JSON format").helpGroup("Local Development:").action(async t=>{await J(async()=>{let n=await W();X.message(Zl.default.dim("Enter your credentials to login to the cloud"));let r=await Ii(),s=await Di(),{data:i,error:o}=await n.client.auth.signInWithPassword({email:r,password:s});o&&(X.error(o.message),process.exit(1)),t.json?console.log(JSON.stringify(i,null,2)):X.success(`Authenticated as: ${Zl.default.cyan(i.user.email)}`);});});};});var wh={};fe(wh,{logout:()=>rT});var bh,rT,Sh=b(()=>{bh=V(z());Te();Qe();Le();rT=e=>{e.command("logout").description("Logout").helpGroup("Local Development:").action(async()=>{console.log(),await J(async()=>{let t=await W(),{error:n}=await t.client.auth.signOut();n&&(X.error(n.message),process.exit(1)),console.log(bh.default.green("Logged out successfully"));});});};});var Eh={};fe(Eh,{signup:()=>sT});var ec,sT,_h=b(()=>{ec=V(z());Qe();En();Le();Te();Ye();sT=e=>{e.command("signup").description(me("Register a supalite cloud account")).option("--json","Output in JSON format").helpGroup("Local Development:").action(async t=>{X.message(ec.default.dim("Enter your credentials to sign up to the cloud")),await J(async()=>{let n=await W(),r=await Ii(),s=await Di(!0),{data:i,error:o}=await n.client.auth.signUp({email:r,password:s});o&&(X.error(o.message),process.exit(1)),t.json?console.log(JSON.stringify(i,null,2)):X.success(`Signed up as: ${ec.default.cyan(i.user.email)}`);});});};});var xh={};fe(xh,{whoami:()=>iT});var tc,iT,Th=b(()=>{tc=V(z());Te();Qe();Le();Ye();iT=e=>{e.command("whoami").description(me("Show the current authenticated user")).option("--json","Output in JSON format").helpGroup("Local Development:").action(async t=>{console.log(),await J(async()=>{let n=await W(),{data:r,error:s}=await n.client.auth.getUser();t.json?console.log(JSON.stringify(r,null,2)):r&&"user"in r&&r.user&&"email"in r.user?(console.log(`Authenticated as: ${tc.default.cyan(r.user.email)}`),process.exit(0)):(console.log(tc.default.yellow("Not authenticated")),process.exit(1)),s&&(X.error(s.message),process.exit(1));});});};});var Ah={};fe(Ah,{link:()=>oT});var Ch,oT,$h=b(()=>{Le();Te();Ee();Qe();Ch=V(z()),oT=e=>e.command("link").description("Link to a Supalite project").option("--project-ref <project-ref>","The reference of the project to link to").option("--json","Output in JSON format").helpGroup("Local Development:").action(async t=>{console.log(),await J(async()=>{await ee();let n=await W();n.project.local.ref()&&X.warning("Project is already linked.");let r=t.projectRef;if(!r){let i=await n.project.remote.list();r=await Ar({message:"Select a project:",options:i.map(o=>({value:o.id,hint:`name: ${o.name}, created: ${o.created_at}`}))}),be(r)&&process.exit(1);}if(!r)throw new Error("No project ref found");console.log("Linking project",r);let s=await n.project.remote.get(r);n.project.local.setRef(s.id),console.log(`Finished linking project ${Ch.default.cyan(s.id)}.`);});});});var vh={};fe(vh,{unlink:()=>aT});var aT,Rh=b(()=>{Le();Te();Ee();aT=e=>e.command("unlink").description("Unlink from a Supalite project").option("--json","Output in JSON format").helpGroup("Local Development:").action(async()=>{console.log(),await J(async()=>{await ee(),(await W()).project.local.unlink(),console.log("Finished unlinking project.");});});});var Nh={};fe(Nh,{status:()=>lT});var kh,lT,Ph=b(()=>{Te();Le();Ee();kh=V(z());Ye();lT=e=>e.command("status").description(me("Show information about the linked project")).helpGroup("Local Development:").action(async()=>{console.log(),await J(async()=>{await ee();let t=await W(),n=await t.project.remote.get();console.log(n),console.log(`Project URL: ${kh.default.cyan(t.project.remote.url(n.id))}`);});});});var Oh={};fe(Oh,{projects:()=>cT});var nc,cT,uT,pT,Ih=b(()=>{En();Qe();nc=V(z());Le();Te();Le();cT=e=>{e.command("projects").description("Manage Supalite cloud projects").helpGroup("Management APIs:").addCommand(pT).addCommand(uT);},uT=new Command$1().name("list").description("List projects").helpGroup("Projects:").action(async()=>{await J(async()=>{let t=await(await W()).project.remote.list();(!Array.isArray(t)||t.length===0)&&(X.info("No projects found"),process.exit(0)),console.log(Mm(t,{omitKeys:["config","user_id"],renderHeader:n=>String(n).split("_").map(r=>r.toUpperCase()).join(" ")}));});}),pT=new Command$1().name("create").description("Create a project").option("--name <name>","The name of the project").helpGroup("Projects:").action(async e=>{await J(async()=>{let t=await W(),n=e.name??await ji(),r=await t.project.remote.create({name:n});X.success(`Project ${nc.default.cyan(r.name)} created: ${nc.default.cyan(r.id)}`);});});});var Dh={};fe(Dh,{cloud:()=>hT});var Oe,dT,hT,jh=b(()=>{Oe=V(z());Le();Te();En();Ue();_i();Kt();Ee();Ye();dT="Management APIs:",hT=e=>{let t=e.command("cloud").description(me("Supalite cloud operations")).helpGroup(dT);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).option("--create","Create a new project if none present",false).option("--name <name>","Name of the project (paired with --create)").action(async n=>{let r=qi().filter(s=>s!=="cloud");r.length>0&&(console.error(Oe.default.red(`Cannot deploy: experimental features enabled (${r.join(", ")}). Cloud does not support them yet.`)),process.exit(1)),await J(async()=>{await ee(n.config);let s=await W(),i=await s.project.local.createApp(n.config),o=!1;await gr(i,{force:!0});let a=await s.project.remote.get().catch(async()=>{if(n.create||await Fi("No project found. Create a new project?")){o=!0;let m=n.name||await ji();return await s.project.remote.create({name:m}).then(g=>s.project.local.link(g))}throw new Error("No project found")}),l=await s.project.remote.createApp(a.id),c=await re(i),p=l.connection.createMigrator(c),u=await p.diff();console.log(),un(u);let f=l.getInfoJson(),h=i.getInfoJson();if(isEqual(f,h))console.log(Oe.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(Oe.default.green("Project config updated"));}let d=s.project.remote.url(a.id);if(u.plan.steps.length>0)try{if(await measureTime(async()=>{await p.migratePlan(u.plan,{force:n.force??!1});},m=>{console.log(Oe.default.green(`Pushed changes to project in ${m.toFixed(2)}ms.`));}),o)try{let m=await yr(l,{recoveryHint:"Fix `supabase/seed.sql` and rerun `lite cloud deploy` against the new project."});m>0&&console.log(Oe.default.green(`Seeded remote project (${m} statements).`));}catch(m){console.warn(Oe.default.yellow(String(m.message??m)));}console.log(`Project URL: ${Oe.default.cyan(d)}
464
- `);}catch(m){m instanceof Ei&&(console.warn(Oe.default.yellow("Migration would cause data loss. Rerun with --force to proceed.")),process.exit(1)),console.error(Oe.default.red("Migration error: "+String(m))),process.exit(1);}else console.log(Oe.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 n=>{console.log(),await J(async()=>{await ee(n.config);let r=await W(),s=await r.project.local.createApp(n.config);if(await gr(s,{force:!0}),!r.project.local.ref())throw new Error("No project linked");let i=await r.project.remote.get();if(!i)throw new Error("Project not found");let o=await r.project.remote.createApp(i.id),a=await re(s),l=await o.connection.createMigrator(a).diff();if(l.plan.steps.length>0)if(n.sql){let c=sl(l,{colorize:!0});console.log(Oe.default.cyan(c));}else un(l);else console.log(Oe.default.green("No changes to migrate."));});});};});Mi();var Mh=V(z());Kt();var Fh={init:()=>Promise.resolve().then(()=>(Cc(),Tc)).then(e=>e.init),"generate-keys":()=>Promise.resolve().then(()=>($c(),Ac)).then(e=>e.generateKeys),start:()=>Promise.resolve().then(()=>(em(),Zf)).then(e=>e.start),dev:()=>Promise.resolve().then(()=>(om(),im)).then(e=>e.dev),repl:()=>Promise.resolve().then(()=>(lm(),am)).then(e=>e.repl),debug:()=>Promise.resolve().then(()=>(um(),cm)).then(e=>e.debug),db:()=>Promise.resolve().then(()=>(Ed(),Sd)).then(e=>e.db),migration:()=>Promise.resolve().then(()=>(xd(),_d)).then(e=>e.migration),upgrade:()=>Promise.resolve().then(()=>(hh(),dh)).then(e=>e.upgrade)},gT={login:()=>Promise.resolve().then(()=>(yh(),gh)).then(e=>e.login),logout:()=>Promise.resolve().then(()=>(Sh(),wh)).then(e=>e.logout),signup:()=>Promise.resolve().then(()=>(_h(),Eh)).then(e=>e.signup),whoami:()=>Promise.resolve().then(()=>(Th(),xh)).then(e=>e.whoami),link:()=>Promise.resolve().then(()=>($h(),Ah)).then(e=>e.link),unlink:()=>Promise.resolve().then(()=>(Rh(),vh)).then(e=>e.unlink),status:()=>Promise.resolve().then(()=>(Ph(),Nh)).then(e=>e.status),projects:()=>Promise.resolve().then(()=>(Ih(),Oh)).then(e=>e.projects),cloud:()=>Promise.resolve().then(()=>(jh(),Dh)).then(e=>e.cloud)};function yT(){return lc("cloud")?{...Fh,...gT}:Fh}async function Uh(){let e=yT(),t=process.argv[2];return t&&Object.hasOwn(e,t)?[await e[t]()]:Promise.all(Object.values(e).map(n=>n()))}Ee();Rr();vt();Il();var rc=new Command;function wT(e){let t=[],n=e;for(;n&&n.name&&n.name()&&n.parent;)t.unshift(n.name()),n=n.parent;return t.join(" ")}async function ST(){Fm();let{version:e,name:t}=await Yr();rc.name("lite").description(`${Mh.default.yellowBright("\u26A1")} ${t} v${e}`).version(e).option("--no-telemetry","disable anonymous usage telemetry").option("--verbose","show diagnostic output").hook("preAction",async(n,r)=>{let s=n.opts?.()??{},i=typeof r.opts=="function"?r.opts():{};Sc(s.verbose===true),Om(s.telemetry===false)&&await Im({command:wT(r),args:i});});for(let n of await Uh())n(rc);await rc.parseAsync(),await hn(false);}process.on("unhandledRejection",e=>{if(!gn(e))throw e});process.on("uncaughtException",e=>{gn(e)||(console.error(e),hn(true,e).finally(()=>process.exit(1)));});ST().then(null).catch(async e=>{gn(e)||(console.error(e),await hn(true,e),process.exitCode=1);});
460
+ `;return e.replace(o,l)}function xT(e,t,n){let r=new RegExp(`(\\[${t.replace(".","\\.")}\\][\\s\\S]*?)(?=\\n\\[|$)`),s=e.match(r);if(!s)return e;let i=s[1],o=n.map(l=>l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),a=new RegExp(`^\\s*(${o})\\s*=.*(?:\\n|$)`,"gm");return e.replace(i,i.replace(a,""))}function TT(e){return xT(e,"db",["driver","url"])}function CT(e){let t=e.match(/(\[db\][\s\S]*?)(?=\n\[|$)/)?.[1];return t?/^\s*driver\s*=\s*["'](sqlite|sqlite-postgres|pglite|postgres)["']/m.test(t)?true:/^\s*url\s*=/m.test(t):false}async function dc(e){return await he__default.access(e).then(()=>true).catch(()=>false)}async function $h(e){let t=Fe__default.join(e,"supabase","config.toml");if(!await dc(t))return null;let n=await he__default.readFile(t,"utf-8");if(!CT(n))return null;let r=`${t}.bak`;return await dc(r)||await he__default.writeFile(r,n,"utf-8"),r}async function AT(e){let t=Fe__default.join(e,"supabase","config.toml");await dc(t)||(await he__default.mkdir(e,{recursive:true}),await zr(["init","--workdir",e,"--yes"],{timeoutMs:6e4}));}async function $T(e,t,n){let r=Fe__default.join(e,"supabase","config.toml"),s=TT(await he__default.readFile(r,"utf-8"));s=s.replace(/^project_id\s*=.*$/m,`project_id = "${t}"`),s=ae(s,"api","port",String(n.api)),s=ae(s,"db","port",String(n.db)),s=ae(s,"db","shadow_port",String(n.shadow)),s=ae(s,"db","major_version","15"),s=ae(s,"db.seed","enabled","false"),s=ae(s,"studio","enabled","true"),s=ae(s,"studio","port",String(n.studio)),s=ae(s,"inbucket","enabled","false"),s=ae(s,"inbucket","port",String(n.inbucket)),s=ae(s,"realtime","enabled","false"),s=ae(s,"storage","enabled","false"),s=ae(s,"edge_runtime","enabled","false"),s=ae(s,"edge_runtime","inspector_port",String(n.edgeInspector)),s=ae(s,"analytics","enabled","false"),s=ae(s,"analytics","port",String(n.analytics)),s=ae(s,"db.pooler","enabled","false"),s=ae(s,"db.pooler","port",String(n.pooler)),await he__default.writeFile(r,s,"utf-8");}function Rh(e){return JSON.stringify(e)}function RT(e){return `[${e.map(Rh).join(", ")}]`}async function vT(e,t){if(!t)return;let n=Fe__default.join(e,"supabase","config.toml"),r=await he__default.readFile(n,"utf-8"),s=t.auth??{},i=s.email??{},o=t.api??{};typeof o.max_rows=="number"&&(r=ae(r,"api","max_rows",String(o.max_rows))),typeof s.site_url=="string"&&(r=ae(r,"auth","site_url",Rh(s.site_url))),Array.isArray(s.additional_redirect_urls)&&(r=ae(r,"auth","additional_redirect_urls",RT(s.additional_redirect_urls))),typeof s.jwt_expiry=="number"&&(r=ae(r,"auth","jwt_expiry",String(s.jwt_expiry))),typeof s.enable_signup=="boolean"&&(r=ae(r,"auth","enable_signup",String(s.enable_signup))),typeof s.enable_anonymous_sign_ins=="boolean"&&(r=ae(r,"auth","enable_anonymous_sign_ins",String(s.enable_anonymous_sign_ins))),typeof s.minimum_password_length=="number"&&(r=ae(r,"auth","minimum_password_length",String(s.minimum_password_length))),typeof i.enable_confirmations=="boolean"&&(r=ae(r,"auth.email","enable_confirmations",String(i.enable_confirmations))),await he__default.writeFile(n,r,"utf-8");}var bT,wT,Yi,vh=b(()=>{an();bT=["bunx","supabase@2.98.1"],wT=["mailpit","realtime","storage-api","imgproxy","edge-runtime","logflare","vector","supavisor"];Yi=class e{constructor(t,n,r,s){this.workdir=t;this.projectId=n;this.status=r;this.cleanupOnStop=s;}stopped=false;static async start(t={}){let n=t.workdir??await he__default.mkdtemp(Fe__default.join(Qy.tmpdir(),"lite-local-supa-")),r=t.projectId??`lite-local-${Date.now().toString(36)}`,s=t.cleanupOnStop??!t.workdir,i=await _T();try{await AT(n),await $T(n,r,i),await vT(n,t.sourceConfig),await zr(["start","--workdir",n,"--yes","--exclude",wT.join(",")],{timeoutMs:5*6e4});let{stdout:o}=await zr(["status","--workdir",n,"-o","json"],{timeoutMs:6e4});return new e(n,r,ST(o),s)}catch(o){throw await zr(["stop","--workdir",n,"--no-backup"],{timeoutMs:12e4}).catch(()=>{}),s&&await he__default.rm(n,{recursive:true,force:true}).catch(()=>{}),o}}async runSql(t){let{createPostgresConnection:n}=await We("@supabase/lite/postgres","postgres","postgres"),r=n({url:this.status.dbUrl});try{await r.exec(t);}finally{await r.close();}}async stop(){this.stopped||(this.stopped=true,await zr(["stop","--workdir",this.workdir,"--no-backup"],{timeoutMs:12e4}).catch(()=>{}),this.cleanupOnStop&&await he__default.rm(this.workdir,{recursive:true,force:true}));}};});async function Qi(){let e=await qr({message:"Email",placeholder:"Enter your email",validate:t=>{try{eu(t,{domains:["supabase.io"],panic:!0});return}catch(n){return n}}});return Ee(e)&&process.exit(1),e}async function Zi(e=false){let t=await Ur({message:"Password",validate:n=>{try{tu(n,{panic:!0});return}catch(r){return r}}});if(Ee(t)&&process.exit(1),e){let n=await Ur({message:"Confirm Password",validate:r=>{try{if(r!==t)throw new Error("Passwords do not match");return}catch(s){return s}}});Ee(n)&&process.exit(1);}return t}async function eo(){let e=await qr({message:"Project Name",placeholder:"Enter your project name",validate:t=>t?.trim()?void 0:"Project name is required"});return Ee(e)&&process.exit(1),e.trim()}async function to(e){let t=await Mr({message:e,initialValue:true});return Ee(t)&&process.exit(1),t}var kn=b(()=>{rt();Bn();});var Lh={};me(Lh,{isNonInteractive:()=>hc,resolveSessionMigration:()=>Oh,resolveTarget:()=>Ph,upgrade:()=>FT});async function NT(e,t){let n=await e.listOrganizations();if(n.length===0)throw new Error("No Supabase organizations found for this token");if(t){let s=n.find(i=>i.id===t||i.slug===t);if(!s)throw new Error(`Organization not found: ${t}`);return s}if(n.length===1)return n[0];let r=await Br({message:"Select organization",options:n.map(s=>({value:s.id,label:`${s.name} (${s.slug})`}))});return Ee(r)&&process.exit(1),n.find(s=>s.id===r)}async function OT(e,t,n){if(n)return n;let r=PT;try{let o=(await e.listRegions(t)).regions??[];o.length>0&&(r=o.map(a=>({key:a.key,label:a.display_name??a.name??a.key})));}catch{}let s=await Br({message:"Select region",options:r.map(i=>({value:i.key,label:i.label}))});return Ee(s)&&process.exit(1),s}async function LT(e){if(e)return e;let t=await qr({message:"Project name",placeholder:"my-project",validate:n=>n&&n.trim().length>0?void 0:"Name is required"});return Ee(t)&&process.exit(1),t}function IT(){return kT.randomBytes(24).toString("base64url")}function Ph(e){let t=e??"hosted";if(t==="hosted"||t==="local")return t;throw new Error(`Unknown upgrade target '${t}'. Use 'hosted' or 'local'.`)}function hc(){return process.env.CI==="true"||process.env.LITE_NON_INTERACTIVE==="1"||!process.stdin.isTTY}async function DT(e){if(typeof e=="boolean")return e;if(hc())return false;let t=await Mr({message:"Migrate existing sessions (transfers JWT secret, sessions, refresh tokens)?",initialValue:false});return Ee(t)&&process.exit(1),t}async function jT(e){if(e)return e;let t=process.env.SUPABASE_ACCESS_TOKEN;if(t)return t;Y.info("Create a personal access token at https://supabase.com/dashboard/account/tokens");let n=await Ur({message:"Supabase access token",validate:r=>r&&r.trim().length>0?void 0:"Token is required"});return Ee(n)&&process.exit(1),n}async function Oh(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=zn(e.jwtSecret);if(t.strong||e.allowWeakJwtSecret)return {migrateSessions:true,jwtSecret:e.jwtSecret,weakReasons:t.reasons};if(hc())throw new Error(["Cannot migrate sessions because auth.jwt_secret looks weak:",...t.reasons.map(r=>`- ${r}`),"Use --allow-weak-jwt-secret to preserve existing sessions anyway, or --no-migrate-sessions to require users to sign in again."].join(`
461
+ `));Y.warning(["auth.jwt_secret looks weak and will become a trusted Supabase signing key:",...t.reasons.map(r=>`- ${r}`)].join(`
462
+ `));let n=await Mr({message:"Preserve existing sessions anyway by importing this JWT secret?",initialValue:false});return Ee(n)&&process.exit(1),n?{migrateSessions:true,jwtSecret:e.jwtSecret,weakReasons:t.reasons}:{migrateSessions:false,weakReasons:t.reasons}}var xe,PT,FT,Ih=b(()=>{xe=K(X());rt();De();Re();Wd();Zd();ah();ph();mh();yh();xh();vh();kn();Gr();Te();PT=[{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)"}];FT=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 n=t.dryRun&&t.json,r=console.log;n||console.log(),await Z(async()=>{await ne(t.config);let s=Ph(t.target);if(Yl("upgrade.target",s),Yl("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.");n&&(console.log=()=>{});let i;try{i=await(await V({withSupabaseClient:!1})).project.local.createApp(t.config);}finally{n&&(console.log=r);}if(n){let w=await fc(i);r(JSON.stringify(w,null,2)),w.summary.upgrade_safe||process.exit(1);return}console.log(xe.default.dim("Running readiness checks..."));let o=await Hr("readiness",()=>Qd(i));if(lh(o),!o.ok)throw new Error("Readiness checks failed. See errors above.");let a=async()=>{console.log(xe.default.dim(`
463
+ Rehearsing upgrade against in-memory pglite...`));let w=await Hr("rehearsal",()=>oh(i));return ch(w),w.ok};if(t.dryRun){let w=await fc(i);uh(w),w.summary.upgrade_safe||process.exit(1),await a()||process.exit(1);return}if(!t.force&&!await to("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=Fe__default.resolve(t.localDir??Ah()),D=await $h(w),q=null;if(D){let I=Fe__default.relative(process.cwd(),D)||D;q=`Your project's supabase/config.toml was rewritten in place for the local Supabase CLI. The original was backed up to ${I}. To resume supalite dev (bun run dev), restore it: cp ${I} supabase/config.toml (or git checkout supabase/config.toml). Pass --local-dir <separate-dir> next time to keep the local stack isolated.`;}let U=Jl(),S,_;try{U.start(`Starting local Supabase in ${w}`),S=await Yi.start({workdir:w,cleanupOnStop:!1,sourceConfig:i.config}),U.stop(`Local Supabase is running at ${S.status.apiUrl}`),_=await Hr("apply",()=>mc(i,S,{migrateSessions:!1,authTarget:"supabase",syncAuthConfig:!1,onSql:(I,te)=>{t.verbose&&console.log(xe.default.dim(`-- ${te}
464
+ ${I}`));},onSchemaStart:I=>U.start(`Applying schema (0/${I})`),onSchemaProgress:(I,te)=>U.message(`Applying schema (${I}/${te})`),onSchemaEnd:I=>U.stop(`Schema applied (${I} statements)`),onBatchStart:(I,te)=>U.start(`${I} (0/${te})`),onBatchProgress:(I,te,ue)=>U.message(`${I} (${te}/${ue})`),onBatchEnd:(I,te,ue)=>U.stop(`${I} (${te} ${ue})`),onBatchFailure:(I,te)=>{U.stop(xe.default.red(`${I}: ${te.length} failed`));for(let ue of te)console.log(xe.default.red(` \u2717 ${ue.error}`)),t.verbose&&console.log(xe.default.dim(` ${ue.statement}`));},onSkip:I=>console.log(xe.default.dim(I))}));}catch(I){throw q&&console.log(xe.default.yellow(`
465
+ ${q}`)),I}let L=["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."];q&&L.unshift(q),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.");let j=Ch(S.status.dbUrl);if(t.dumpCredentials){let I=JSON.stringify({target:"local",workdir:S.workdir,projectUrl:S.status.apiUrl,apiUrl:S.status.apiUrl,studioUrl:S.status.studioUrl,dbUrl:S.status.dbUrl,anonKey:S.status.anonKey,serviceRoleKey:S.status.serviceRoleKey,dbPassword:j},null,2);await he__default.writeFile(t.dumpCredentials,I,"utf-8"),console.log(xe.default.dim(`Credentials written to ${t.dumpCredentials}`));}lc({projectRef:S.projectId,projectUrl:S.status.apiUrl,apiUrl:S.status.apiUrl,studioUrl:S.status.studioUrl,anonKey:S.status.anonKey,serviceRoleKey:S.status.serviceRoleKey,dbPassword:j,auth:_.auth,jwtMigrated:!1,warnings:[`Local Supabase workdir: ${S.workdir}`,...L]});return}let c=await jT(t.supabaseToken),p=new Wi(c);try{await p.listOrganizations();}catch(w){throw new Error(`Supabase access token rejected: ${String(w)}`)}let u=await NT(p,t.orgId),f=await OT(p,u.slug,t.region),h=await LT(t.projectName),m=await DT(t.migrateSessions),d=await Oh({requested:m,jwtSecret:i.config.auth?.jwt_secret,allowWeakJwtSecret:t.allowWeakJwtSecret}),g=d.migrateSessions,y=IT(),E=Jl();E.start("Creating Supabase project");let A=await p.createProject({organization_id:u.id,name:h,db_pass:y,region:f}),C=A.ref??A.id;if(E.stop(`Project created: ${C}`),E.start("Waiting for project to become active"),await p.waitForActive(C,{onTick:w=>E.message(`Project status: ${w}`)}),E.stop("Project is active"),g){E.start("Importing JWT signing key");try{await p.createSigningKey(C,{algorithm:"HS256",status:"in_use",private_jwk:fh(d.jwtSecret)});}catch(w){throw E.stop(xe.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(" "))}E.stop("JWT signing key imported");}let R=(await Hr("apply",()=>mc(i,{runSql:w=>p.runSql(C,w),updateAuthConfig:w=>p.updateAuthConfig(C,w)},{migrateSessions:g,authTarget:"supabase",onSql:(w,D)=>{t.verbose&&console.log(xe.default.dim(`-- ${D}
466
+ ${w}`));},onSchemaStart:w=>E.start(`Applying schema (0/${w})`),onSchemaProgress:(w,D)=>E.message(`Applying schema (${w}/${D})`),onSchemaEnd:w=>E.stop(`Schema applied (${w} statements)`),onBatchStart:(w,D)=>{E.start(`${w} (0/${D})`);},onBatchProgress:(w,D,q)=>E.message(`${w} (${D}/${q})`),onBatchEnd:(w,D,q)=>E.stop(`${w} (${D} ${q})`),onBatchFailure:(w,D)=>{E.stop(xe.default.red(`${w}: ${D.length} failed`));for(let q of D)console.log(xe.default.red(` \u2717 ${q.error}`)),t.verbose&&console.log(xe.default.dim(` ${q.statement}`));},onAuthConfigStart:()=>E.start("Syncing auth config"),onAuthConfigEnd:()=>E.stop("Auth config synced"),onSkip:w=>console.log(xe.default.dim(w))}))).auth,T=Gd(await p.getApiKeys(C)),x=`https://${C}.${p.projectDomain}`,O=[];if(g?d.weakReasons.length>0?O.push(`A weak JWT secret was imported to preserve sessions: ${d.weakReasons.join("; ")}.`):O.push("Sessions preserved by importing auth.jwt_secret as a Supabase signing key."):O.push("Sessions and JWT secret not migrated. Existing tokens are invalid \u2014 users must re-authenticate."),i.config.storage?.enabled&&O.push("Storage migration is not yet supported."),i.config.realtime?.enabled&&O.push("Realtime config migration is not yet supported."),t.dumpCredentials){let w=JSON.stringify({ref:C,projectUrl:x,anonKey:T.anon,serviceRoleKey:T.service_role,dbPassword:y},null,2);await he__default.writeFile(t.dumpCredentials,w,"utf-8"),console.log(xe.default.dim(`Credentials written to ${t.dumpCredentials}`));}lc({projectRef:C,projectUrl:x,apiUrl:x,anonKey:T.anon,serviceRoleKey:T.service_role,dbPassword:y,auth:R,jwtMigrated:!!(g&&d.jwtSecret),warnings:O});});});});var Dh={};me(Dh,{login:()=>MT});var gc,MT,jh=b(()=>{gc=K(X());rt();kn();De();Re();MT=e=>{e.command("login").description("Login").option("--json","Output in JSON format").helpGroup("Local Development:").action(async t=>{await Z(async()=>{let n=await V();Y.message(gc.default.dim("Enter your credentials to login to the cloud"));let r=await Qi(),s=await Zi(),{data:i,error:o}=await n.client.auth.signInWithPassword({email:r,password:s});o&&(Y.error(o.message),process.exit(1)),t.json?console.log(JSON.stringify(i,null,2)):Y.success(`Authenticated as: ${gc.default.cyan(i.user.email)}`);});});};});var Mh={};me(Mh,{logout:()=>UT});var Fh,UT,Uh=b(()=>{Fh=K(X());Re();rt();De();UT=e=>{e.command("logout").description("Logout").helpGroup("Local Development:").action(async()=>{console.log(),await Z(async()=>{let t=await V(),{error:n}=await t.client.auth.signOut();n&&(Y.error(n.message),process.exit(1)),console.log(Fh.default.green("Logged out successfully"));});});};});var Bh={};me(Bh,{signup:()=>BT});var yc,BT,qh=b(()=>{yc=K(X());rt();kn();De();Re();Ze();BT=e=>{e.command("signup").description(de("Register a supalite cloud account")).option("--json","Output in JSON format").helpGroup("Local Development:").action(async t=>{Y.message(yc.default.dim("Enter your credentials to sign up to the cloud")),await Z(async()=>{let n=await V(),r=await Qi(),s=await Zi(!0),{data:i,error:o}=await n.client.auth.signUp({email:r,password:s});o&&(Y.error(o.message),process.exit(1)),t.json?console.log(JSON.stringify(i,null,2)):Y.success(`Signed up as: ${yc.default.cyan(i.user.email)}`);});});};});var Hh={};me(Hh,{whoami:()=>qT});var bc,qT,Gh=b(()=>{bc=K(X());Re();rt();De();Ze();qT=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 n=await V(),{data:r,error:s}=await n.client.auth.getUser();t.json?console.log(JSON.stringify(r,null,2)):r&&"user"in r&&r.user&&"email"in r.user?(console.log(`Authenticated as: ${bc.default.cyan(r.user.email)}`),process.exit(0)):(console.log(bc.default.yellow("Not authenticated")),process.exit(1)),s&&(Y.error(s.message),process.exit(1));});});};});var Vh={};me(Vh,{link:()=>HT});var Wh,HT,Kh=b(()=>{De();Re();Te();rt();Wh=K(X()),HT=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 ne();let n=await V();n.project.local.ref()&&Y.warning("Project is already linked.");let r=t.projectRef;if(!r){let i=await n.project.remote.list();r=await Br({message:"Select a project:",options:i.map(o=>({value:o.id,hint:`name: ${o.name}, created: ${o.created_at}`}))}),Ee(r)&&process.exit(1);}if(!r)throw new Error("No project ref found");console.log("Linking project",r);let s=await n.project.remote.get(r);n.project.local.setRef(s.id),console.log(`Finished linking project ${Wh.default.cyan(s.id)}.`);});});});var zh={};me(zh,{unlink:()=>GT});var GT,Xh=b(()=>{De();Re();Te();GT=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 ne(),(await V()).project.local.unlink(),console.log("Finished unlinking project.");});});});var Yh={};me(Yh,{status:()=>WT});var Jh,WT,Qh=b(()=>{Re();De();Te();Jh=K(X());Ze();WT=e=>e.command("status").description(de("Show information about the linked project")).helpGroup("Local Development:").action(async()=>{console.log(),await Z(async()=>{await ne();let t=await V(),n=await t.project.remote.get();console.log(n),console.log(`Project URL: ${Jh.default.cyan(t.project.remote.url(n.id))}`);});});});var eg={};me(eg,{projects:()=>VT});var wc,VT,KT,zT,tg=b(()=>{kn();rt();wc=K(X());De();Re();De();VT=e=>{e.command("projects").description("Manage Supalite cloud projects").helpGroup("Management APIs:").addCommand(zT).addCommand(KT);},KT=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)&&(Y.info("No projects found"),process.exit(0)),console.log(cd(t,{omitKeys:["config","user_id"],renderHeader:n=>String(n).split("_").map(r=>r.toUpperCase()).join(" ")}));});}),zT=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(),n=e.name??await eo(),r=await t.project.remote.create({name:n});Y.success(`Project ${wc.default.cyan(r.name)} created: ${wc.default.cyan(r.id)}`);});});});var ng={};me(ng,{cloud:()=>QT});var je,YT,QT,rg=b(()=>{je=K(X());De();Re();kn();tt();Ys();Qt();Te();Ze();YT="Management APIs:",QT=e=>{let t=e.command("cloud").description(de("Supalite cloud operations")).helpGroup(YT);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).option("--create","Create a new project if none present",false).option("--name <name>","Name of the project (paired with --create)").action(async n=>{let r=io().filter(s=>s!=="cloud");r.length>0&&(console.error(je.default.red(`Cannot deploy: experimental features enabled (${r.join(", ")}). Cloud does not support them yet.`)),process.exit(1)),await Z(async()=>{await ne(n.config);let s=await V(),i=await s.project.local.createApp(n.config),o=!1;await bn(i,{force:!0});let a=await s.project.remote.get().catch(async()=>{if(n.create||await to("No project found. Create a new project?")){o=!0;let d=n.name||await eo();return await s.project.remote.create({name:d}).then(g=>s.project.local.link(g))}throw new Error("No project found")}),l=await s.project.remote.createApp(a.id),c=await be(i),p=l.connection.createMigrator(c),u=await p.diff();console.log(),wn(u);let f=l.getInfoJson(),h=i.getInfoJson();if(isEqual(f,h))console.log(je.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(je.default.green("Project config updated"));}let m=s.project.remote.url(a.id);if(u.plan.steps.length>0)try{if(await measureTime(async()=>{await p.migratePlan(u.plan,{force:n.force??!1});},d=>{console.log(je.default.green(`Pushed changes to project in ${d.toFixed(2)}ms.`));}),o)try{let d=await Pr(l,{recoveryHint:"Fix `supabase/seed.sql` and rerun `lite cloud deploy` against the new project."});d>0&&console.log(je.default.green(`Seeded remote project (${d} statements).`));}catch(d){console.warn(je.default.yellow(String(d.message??d)));}console.log(`Project URL: ${je.default.cyan(m)}
467
+ `);}catch(d){d instanceof Js&&(console.warn(je.default.yellow("Migration would cause data loss. Rerun with --force to proceed.")),process.exit(1)),console.error(je.default.red("Migration error: "+String(d))),process.exit(1);}else console.log(je.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 n=>{console.log(),await Z(async()=>{await ne(n.config);let r=await V(),s=await r.project.local.createApp(n.config);if(await bn(s,{force:!0}),!r.project.local.ref())throw new Error("No project linked");let i=await r.project.remote.get();if(!i)throw new Error("Project not found");let o=await r.project.remote.createApp(i.id),a=await be(s),l=await o.connection.createMigrator(a).diff();if(l.plan.steps.length>0)if(n.sql){let c=_l(l,{colorize:!0});console.log(je.default.cyan(c));}else wn(l);else console.log(je.default.green("No changes to migrate."));});});};});ro();var og=K(X());Qt();var sg={init:()=>Promise.resolve().then(()=>(qc(),Bc)).then(e=>e.init),"generate-keys":()=>Promise.resolve().then(()=>(Gc(),Hc)).then(e=>e.generateKeys),start:()=>Promise.resolve().then(()=>(lf(),af)).then(e=>e.start),dev:()=>Promise.resolve().then(()=>(vm(),Rm)).then(e=>e.dev),repl:()=>Promise.resolve().then(()=>(Nm(),km)).then(e=>e.repl),debug:()=>Promise.resolve().then(()=>(Om(),Pm)).then(e=>e.debug),db:()=>Promise.resolve().then(()=>(Bd(),Ud)).then(e=>e.db),migration:()=>Promise.resolve().then(()=>(Hd(),qd)).then(e=>e.migration),upgrade:()=>Promise.resolve().then(()=>(Ih(),Lh)).then(e=>e.upgrade)},ZT={login:()=>Promise.resolve().then(()=>(jh(),Dh)).then(e=>e.login),logout:()=>Promise.resolve().then(()=>(Uh(),Mh)).then(e=>e.logout),signup:()=>Promise.resolve().then(()=>(qh(),Bh)).then(e=>e.signup),whoami:()=>Promise.resolve().then(()=>(Gh(),Hh)).then(e=>e.whoami),link:()=>Promise.resolve().then(()=>(Kh(),Vh)).then(e=>e.link),unlink:()=>Promise.resolve().then(()=>(Xh(),zh)).then(e=>e.unlink),status:()=>Promise.resolve().then(()=>(Qh(),Yh)).then(e=>e.status),projects:()=>Promise.resolve().then(()=>(tg(),eg)).then(e=>e.projects),cloud:()=>Promise.resolve().then(()=>(rg(),ng)).then(e=>e.cloud)};function eC(){return Cc("cloud")?{...sg,...ZT}:sg}async function ig(){let e=eC(),t=process.argv[2];return t&&Object.hasOwn(e,t)?[await e[t]()]:Promise.all(Object.values(e).map(n=>n()))}Te();Gr();It();Ql();var Sc=new Command;function nC(e){let t=[],n=e;for(;n&&n.name&&n.name()&&n.parent;)t.unshift(n.name()),n=n.parent;return t.join(" ")}async function rC(){ad();let{version:e,name:t}=await ps();Sc.name("lite").description(`${og.default.yellowBright("\u26A1")} ${t} v${e}`).version(e).option("--no-telemetry","disable anonymous usage telemetry").option("--verbose","show diagnostic output").hook("preAction",async(n,r)=>{let s=n.opts?.()??{},i=typeof r.opts=="function"?r.opts():{};jc(s.verbose===true),rd(s.telemetry===false)&&await sd({command:nC(r),args:i});});for(let n of await ig())n(Sc);await Sc.parseAsync(),await Tn(false);}process.on("unhandledRejection",e=>{if(!Cn(e))throw e});process.on("uncaughtException",e=>{Cn(e)||(console.error(e),Tn(true,e).finally(()=>process.exit(1)));});rC().then(null).catch(async e=>{Cn(e)||(console.error(e),await Tn(true,e),process.exitCode=1);});
465
468
  /*! Bundled license information:
466
469
 
467
470
  smol-toml/dist/error.js: