@supabase/lite 0.2.1-next.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -2
- package/STATUS.md +7 -6
- package/dist/cli/index.js +144 -117
- package/dist/cli/lib.js +38 -32
- package/dist/db/postgres/{BasePostgresConnection-B7zHDAib.d.ts → BasePostgresConnection-Clykq58D.d.ts} +1 -1
- package/dist/db/postgres/PostgresConnection.d.ts +1 -1
- package/dist/db/postgres/PostgresConnection.js +21 -25
- package/dist/db/postgres/pglite/PgliteConnection.d.ts +1 -1
- package/dist/db/postgres/pglite/PgliteConnection.js +25 -27
- package/dist/index.js +33 -33
- package/package.json +3 -7
package/dist/cli/lib.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import'pgsql-deparser';import*as
|
|
1
|
+
import'pgsql-deparser';import*as rt from'node:path';import rt__default from'node:path';import Ai from'node:os';import ce from'node:fs';import {createClient}from'@supabase/supabase-js';import {ensureVar,App,cloud,splitSqlStatements}from'@supabase/lite';import {createConnection}from'@supabase/lite/sqlite';import*as U from'node:fs/promises';import U__default from'node:fs/promises';import {createHash}from'node:crypto';import {parse}from'dotenv';import'node:url';import*as At from'fs';import At__default from'fs';import Pr,{posix,sep,basename,dirname,resolve,normalize,relative}from'path';import {fileURLToPath}from'url';import {createRequire}from'module';import Ma from'chokidar';try {
|
|
2
2
|
/**
|
|
3
3
|
* Adding this to avoid warnings from node:sqlite being experimental
|
|
4
4
|
*/
|
|
@@ -9,41 +9,41 @@ import'pgsql-deparser';import*as nt from'node:path';import nt__default from'node
|
|
|
9
9
|
};
|
|
10
10
|
} catch {}
|
|
11
11
|
|
|
12
|
-
var ci=Object.create;var De=Object.defineProperty;var ui=Object.getOwnPropertyDescriptor;var fi=Object.getOwnPropertyNames;var pi=Object.getPrototypeOf,mi=Object.prototype.hasOwnProperty;var L=(e,t)=>()=>(e&&(t=e(e=0)),t);var pt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),hi=(e,t)=>{for(var n in t)De(e,n,{get:t[n],enumerable:true});},di=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of fi(t))!mi.call(e,i)&&i!==n&&De(e,i,{get:()=>t[i],enumerable:!(r=ui(t,i))||r.enumerable});return e};var Rt=(e,t,n)=>(n=e!=null?ci(pi(e)):{},di(De(n,"default",{value:e,enumerable:true}),e));var $t=pt((Al,Me)=>{var me=process||{},Pn=me.argv||[],pe=me.env||{},xi=!(pe.NO_COLOR||Pn.includes("--no-color"))&&(!!pe.FORCE_COLOR||Pn.includes("--color")||me.platform==="win32"||(me.stdout||{}).isTTY&&pe.TERM!=="dumb"||!!pe.CI),Si=(e,t,n=e)=>r=>{let i=""+r,s=i.indexOf(t,e.length);return ~s?e+Ei(i,t,n,s)+t:e+i+t},Ei=(e,t,n,r)=>{let i="",s=0;do i+=e.substring(s,r)+n,s=r+t.length,r=e.indexOf(t,s);while(~r);return i+e.substring(s)},Ln=(e=xi)=>{let t=e?Si:()=>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")}};Me.exports=Ln();Me.exports.createColors=Ln;});var It=pt((Tu,lr)=>{var ir="[^\\\\/]",no="(?=.)",sr="[^/]",tn="(?:\\/|$)",or="(?:^|\\/)",en=`\\.{1,2}${tn}`,ro="(?!\\.)",io=`(?!${or}${en})`,so=`(?!\\.{0,1}${tn})`,oo=`(?!${en})`,ao="[^.\\/]",lo=`${sr}*?`,co="/",ar={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:no,QMARK:sr,END_ANCHOR:tn,DOTS_SLASH:en,NO_DOT:ro,NO_DOTS:io,NO_DOT_SLASH:so,NO_DOTS_SLASH:oo,QMARK_NO_DOT:ao,STAR:lo,START_ANCHOR:or,SEP:co},uo={...ar,SLASH_LITERAL:"[\\\\/]",QMARK:ir,STAR:`${ir}*?`,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:"\\"},fo={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"};lr.exports={MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:fo,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?uo:ar}};});var Dt=pt(X=>{var{REGEX_BACKSLASH:po,REGEX_REMOVE_BACKSLASH:mo,REGEX_SPECIAL_CHARS:ho,REGEX_SPECIAL_CHARS_GLOBAL:go}=It();X.isObject=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);X.hasRegexChars=e=>ho.test(e);X.isRegexChar=e=>e.length===1&&X.hasRegexChars(e);X.escapeRegex=e=>e.replace(go,"\\$1");X.toPosixSlashes=e=>e.replace(po,"/");X.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};X.removeBackslashes=e=>e.replace(mo,t=>t==="\\"?"":t);X.escapeLast=(e,t,n)=>{let r=e.lastIndexOf(t,n);return r===-1?e:e[r-1]==="\\"?X.escapeLast(e,t,r-1):`${e.slice(0,r)}\\${e.slice(r)}`};X.removePrefix=(e,t={})=>{let n=e;return n.startsWith("./")&&(n=n.slice(2),t.prefix="./"),n};X.wrapOutput=(e,t={},n={})=>{let r=n.contains?"":"^",i=n.contains?"":"$",s=`${r}(?:${e})${i}`;return t.negated===true&&(s=`(?:^(?!${s}).*$)`),s};X.basename=(e,{windows:t}={})=>{let n=e.split(t?/[\\/]/:"/"),r=n[n.length-1];return r===""?n[n.length-2]:r};});var gr=pt((Cu,dr)=>{var cr=Dt(),{CHAR_ASTERISK:nn,CHAR_AT:yo,CHAR_BACKWARD_SLASH:jt,CHAR_COMMA:bo,CHAR_DOT:rn,CHAR_EXCLAMATION_MARK:sn,CHAR_FORWARD_SLASH:hr,CHAR_LEFT_CURLY_BRACE:on,CHAR_LEFT_PARENTHESES:an,CHAR_LEFT_SQUARE_BRACKET:wo,CHAR_PLUS:xo,CHAR_QUESTION_MARK:ur,CHAR_RIGHT_CURLY_BRACE:So,CHAR_RIGHT_PARENTHESES:fr,CHAR_RIGHT_SQUARE_BRACKET:Eo}=It(),pr=e=>e===hr||e===jt,mr=e=>{e.isPrefix!==true&&(e.depth=e.isGlobstar?1/0:1);},Ao=(e,t)=>{let n=t||{},r=e.length-1,i=n.parts===true||n.scanToEnd===true,s=[],o=[],a=[],l=e,c=-1,u=0,h=0,d=false,b=false,w=false,E=false,_=false,$=false,x=false,G=false,Z=false,B=false,U=0,W,A,C={value:"",depth:0,isGlob:false},m=()=>c>=r,V=()=>l.charCodeAt(c+1),S=()=>(W=A,l.charCodeAt(++c));for(;c<r;){A=S();let P;if(A===jt){x=C.backslashes=true,A=S(),A===on&&($=true);continue}if($===true||A===on){for(U++;m()!==true&&(A=S());){if(A===jt){x=C.backslashes=true,S();continue}if(A===on){U++;continue}if($!==true&&A===rn&&(A=S())===rn){if(d=C.isBrace=true,w=C.isGlob=true,B=true,i===true)continue;break}if($!==true&&A===bo){if(d=C.isBrace=true,w=C.isGlob=true,B=true,i===true)continue;break}if(A===So&&(U--,U===0)){$=false,d=C.isBrace=true,B=true;break}}if(i===true)continue;break}if(A===hr){if(s.push(c),o.push(C),C={value:"",depth:0,isGlob:false},B===true)continue;if(W===rn&&c===u+1){u+=2;continue}h=c+1;continue}if(n.noext!==true&&(A===xo||A===yo||A===nn||A===ur||A===sn)===true&&V()===an){if(w=C.isGlob=true,E=C.isExtglob=true,B=true,A===sn&&c===u&&(Z=true),i===true){for(;m()!==true&&(A=S());){if(A===jt){x=C.backslashes=true,A=S();continue}if(A===fr){w=C.isGlob=true,B=true;break}}continue}break}if(A===nn){if(W===nn&&(_=C.isGlobstar=true),w=C.isGlob=true,B=true,i===true)continue;break}if(A===ur){if(w=C.isGlob=true,B=true,i===true)continue;break}if(A===wo){for(;m()!==true&&(P=S());){if(P===jt){x=C.backslashes=true,S();continue}if(P===Eo){b=C.isBracket=true,w=C.isGlob=true,B=true;break}}if(i===true)continue;break}if(n.nonegate!==true&&A===sn&&c===u){G=C.negated=true,u++;continue}if(n.noparen!==true&&A===an){if(w=C.isGlob=true,i===true){for(;m()!==true&&(A=S());){if(A===an){x=C.backslashes=true,A=S();continue}if(A===fr){B=true;break}}continue}break}if(w===true){if(B=true,i===true)continue;break}}n.noext===true&&(E=false,w=false);let k=l,p="",f="";u>0&&(p=l.slice(0,u),l=l.slice(u),h-=u),k&&w===true&&h>0?(k=l.slice(0,h),f=l.slice(h)):w===true?(k="",f=l):k=l,k&&k!==""&&k!=="/"&&k!==l&&pr(k.charCodeAt(k.length-1))&&(k=k.slice(0,-1)),n.unescape===true&&(f&&(f=cr.removeBackslashes(f)),k&&x===true&&(k=cr.removeBackslashes(k)));let J={prefix:p,input:e,start:u,base:k,glob:f,isBrace:d,isBracket:b,isGlob:w,isExtglob:E,isGlobstar:_,negated:G,negatedExtglob:Z};if(n.tokens===true&&(J.maxDepth=0,pr(A)||o.push(C),J.tokens=o),n.parts===true||n.tokens===true){let P;for(let F=0;F<s.length;F++){let it=P?P+1:u,Y=s[F],lt=e.slice(it,Y);n.tokens&&(F===0&&u!==0?(o[F].isPrefix=true,o[F].value=p):o[F].value=lt,mr(o[F]),J.maxDepth+=o[F].depth),(F!==0||lt!=="")&&a.push(lt),P=Y;}if(P&&P+1<e.length){let F=e.slice(P+1);a.push(F),n.tokens&&(o[o.length-1].value=F,mr(o[o.length-1]),J.maxDepth+=o[o.length-1].depth);}J.slashes=s,J.parts=a;}return J};dr.exports=Ao;});var wr=pt((Ru,br)=>{var Re=It(),rt=Dt(),{MAX_LENGTH:ve,POSIX_REGEX_SOURCE:To,REGEX_NON_SPECIAL_CHARS:_o,REGEX_SPECIAL_CHARS_BACKREF:Co,REPLACEMENTS:yr}=Re,Ro=(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(i=>rt.escapeRegex(i)).join("..")}return n},Et=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`,ln=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a string");e=yr[e]||e;let n={...t},r=typeof n.maxLength=="number"?Math.min(ve,n.maxLength):ve,i=e.length;if(i>r)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${r}`);let s={type:"bos",value:"",output:n.prepend||""},o=[s],a=n.capture?"":"?:",l=Re.globChars(n.windows),c=Re.extglobChars(l),{DOT_LITERAL:u,PLUS_LITERAL:h,SLASH_LITERAL:d,ONE_CHAR:b,DOTS_SLASH:w,NO_DOT:E,NO_DOT_SLASH:_,NO_DOTS_SLASH:$,QMARK:x,QMARK_NO_DOT:G,STAR:Z,START_ANCHOR:B}=l,U=y=>`(${a}(?:(?!${B}${y.dot?w:u}).)*?)`,W=n.dot?"":E,A=n.dot?x:G,C=n.bash===true?U(n):Z;n.capture&&(C=`(${C})`),typeof n.noext=="boolean"&&(n.noextglob=n.noext);let m={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=rt.removePrefix(e,m),i=e.length;let V=[],S=[],k=[],p=s,f,J=()=>m.index===i-1,P=m.peek=(y=1)=>e[m.index+y],F=m.advance=()=>e[++m.index]||"",it=()=>e.slice(m.index+1),Y=(y="",O=0)=>{m.consumed+=y,m.index+=O;},lt=y=>{m.output+=y.output!=null?y.output:y.value,Y(y.value);},ai=()=>{let y=1;for(;P()==="!"&&(P(2)!=="("||P(3)==="?");)F(),m.start++,y++;return y%2===0?false:(m.negated=true,m.start++,true)},se=y=>{m[y]++,k.push(y);},ft=y=>{m[y]--,k.pop();},v=y=>{if(p.type==="globstar"){let O=m.braces>0&&(y.type==="comma"||y.type==="brace"),g=y.extglob===true||V.length&&(y.type==="pipe"||y.type==="paren");y.type!=="slash"&&y.type!=="paren"&&!O&&!g&&(m.output=m.output.slice(0,-p.output.length),p.type="star",p.value="*",p.output=C,m.output+=p.output);}if(V.length&&y.type!=="paren"&&(V[V.length-1].inner+=y.value),(y.value||y.output)&<(y),p&&p.type==="text"&&y.type==="text"){p.output=(p.output||p.value)+y.value,p.value+=y.value;return}y.prev=p,o.push(y),p=y;},oe=(y,O)=>{let g={...c[O],conditions:1,inner:""};g.prev=p,g.parens=m.parens,g.output=m.output;let R=(n.capture?"(":"")+g.open;se("parens"),v({type:y,value:O,output:m.output?"":b}),v({type:"paren",extglob:true,value:F(),output:R}),V.push(g);},li=y=>{let O=y.close+(n.capture?")":""),g;if(y.type==="negate"){let R=C;if(y.inner&&y.inner.length>1&&y.inner.includes("/")&&(R=U(n)),(R!==C||J()||/^\)+$/.test(it()))&&(O=y.close=`)$))${R}`),y.inner.includes("*")&&(g=it())&&/^\.[^\\/.]+$/.test(g)){let I=ln(g,{...t,fastpaths:false}).output;O=y.close=`)${I})${R})`;}y.prev.type==="bos"&&(m.negatedExtglob=true);}v({type:"paren",extglob:true,value:f,output:O}),ft("parens");};if(n.fastpaths!==false&&!/(^[*!]|[/()[\]{}"])/.test(e)){let y=false,O=e.replace(Co,(g,R,I,z,H,Ie)=>z==="\\"?(y=true,g):z==="?"?R?R+z+(H?x.repeat(H.length):""):Ie===0?A+(H?x.repeat(H.length):""):x.repeat(I.length):z==="."?u.repeat(I.length):z==="*"?R?R+z+(H?C:""):C:R?g:`\\${g}`);return y===true&&(n.unescape===true?O=O.replace(/\\/g,""):O=O.replace(/\\+/g,g=>g.length%2===0?"\\\\":g?"\\":"")),O===e&&n.contains===true?(m.output=e,m):(m.output=rt.wrapOutput(O,m,t),m)}for(;!J();){if(f=F(),f==="\0")continue;if(f==="\\"){let g=P();if(g==="/"&&n.bash!==true||g==="."||g===";")continue;if(!g){f+="\\",v({type:"text",value:f});continue}let R=/^\\+/.exec(it()),I=0;if(R&&R[0].length>2&&(I=R[0].length,m.index+=I,I%2!==0&&(f+="\\")),n.unescape===true?f=F():f+=F(),m.brackets===0){v({type:"text",value:f});continue}}if(m.brackets>0&&(f!=="]"||p.value==="["||p.value==="[^")){if(n.posix!==false&&f===":"){let g=p.value.slice(1);if(g.includes("[")&&(p.posix=true,g.includes(":"))){let R=p.value.lastIndexOf("["),I=p.value.slice(0,R),z=p.value.slice(R+2),H=To[z];if(H){p.value=I+H,m.backtrack=true,F(),!s.output&&o.indexOf(p)===1&&(s.output=b);continue}}}(f==="["&&P()!==":"||f==="-"&&P()==="]")&&(f=`\\${f}`),f==="]"&&(p.value==="["||p.value==="[^")&&(f=`\\${f}`),n.posix===true&&f==="!"&&p.value==="["&&(f="^"),p.value+=f,lt({value:f});continue}if(m.quotes===1&&f!=='"'){f=rt.escapeRegex(f),p.value+=f,lt({value:f});continue}if(f==='"'){m.quotes=m.quotes===1?0:1,n.keepQuotes===true&&v({type:"text",value:f});continue}if(f==="("){se("parens"),v({type:"paren",value:f});continue}if(f===")"){if(m.parens===0&&n.strictBrackets===true)throw new SyntaxError(Et("opening","("));let g=V[V.length-1];if(g&&m.parens===g.parens+1){li(V.pop());continue}v({type:"paren",value:f,output:m.parens?")":"\\)"}),ft("parens");continue}if(f==="["){if(n.nobracket===true||!it().includes("]")){if(n.nobracket!==true&&n.strictBrackets===true)throw new SyntaxError(Et("closing","]"));f=`\\${f}`;}else se("brackets");v({type:"bracket",value:f});continue}if(f==="]"){if(n.nobracket===true||p&&p.type==="bracket"&&p.value.length===1){v({type:"text",value:f,output:`\\${f}`});continue}if(m.brackets===0){if(n.strictBrackets===true)throw new SyntaxError(Et("opening","["));v({type:"text",value:f,output:`\\${f}`});continue}ft("brackets");let g=p.value.slice(1);if(p.posix!==true&&g[0]==="^"&&!g.includes("/")&&(f=`/${f}`),p.value+=f,lt({value:f}),n.literalBrackets===false||rt.hasRegexChars(g))continue;let R=rt.escapeRegex(p.value);if(m.output=m.output.slice(0,-p.value.length),n.literalBrackets===true){m.output+=R,p.value=R;continue}p.value=`(${a}${R}|${p.value})`,m.output+=p.value;continue}if(f==="{"&&n.nobrace!==true){se("braces");let g={type:"brace",value:f,output:"(",outputIndex:m.output.length,tokensIndex:m.tokens.length};S.push(g),v(g);continue}if(f==="}"){let g=S[S.length-1];if(n.nobrace===true||!g){v({type:"text",value:f,output:f});continue}let R=")";if(g.dots===true){let I=o.slice(),z=[];for(let H=I.length-1;H>=0&&(o.pop(),I[H].type!=="brace");H--)I[H].type!=="dots"&&z.unshift(I[H].value);R=Ro(z,n),m.backtrack=true;}if(g.comma!==true&&g.dots!==true){let I=m.output.slice(0,g.outputIndex),z=m.tokens.slice(g.tokensIndex);g.value=g.output="\\{",f=R="\\}",m.output=I;for(let H of z)m.output+=H.output||H.value;}v({type:"brace",value:f,output:R}),ft("braces"),S.pop();continue}if(f==="|"){V.length>0&&V[V.length-1].conditions++,v({type:"text",value:f});continue}if(f===","){let g=f,R=S[S.length-1];R&&k[k.length-1]==="braces"&&(R.comma=true,g="|"),v({type:"comma",value:f,output:g});continue}if(f==="/"){if(p.type==="dot"&&m.index===m.start+1){m.start=m.index+1,m.consumed="",m.output="",o.pop(),p=s;continue}v({type:"slash",value:f,output:d});continue}if(f==="."){if(m.braces>0&&p.type==="dot"){p.value==="."&&(p.output=u);let g=S[S.length-1];p.type="dots",p.output+=f,p.value+=f,g.dots=true;continue}if(m.braces+m.parens===0&&p.type!=="bos"&&p.type!=="slash"){v({type:"text",value:f,output:u});continue}v({type:"dot",value:f,output:u});continue}if(f==="?"){if(!(p&&p.value==="(")&&n.noextglob!==true&&P()==="("&&P(2)!=="?"){oe("qmark",f);continue}if(p&&p.type==="paren"){let R=P(),I=f;(p.value==="("&&!/[!=<:]/.test(R)||R==="<"&&!/<([!=]|\w+>)/.test(it()))&&(I=`\\${f}`),v({type:"text",value:f,output:I});continue}if(n.dot!==true&&(p.type==="slash"||p.type==="bos")){v({type:"qmark",value:f,output:G});continue}v({type:"qmark",value:f,output:x});continue}if(f==="!"){if(n.noextglob!==true&&P()==="("&&(P(2)!=="?"||!/[!=<:]/.test(P(3)))){oe("negate",f);continue}if(n.nonegate!==true&&m.index===0){ai();continue}}if(f==="+"){if(n.noextglob!==true&&P()==="("&&P(2)!=="?"){oe("plus",f);continue}if(p&&p.value==="("||n.regex===false){v({type:"plus",value:f,output:h});continue}if(p&&(p.type==="bracket"||p.type==="paren"||p.type==="brace")||m.parens>0){v({type:"plus",value:f});continue}v({type:"plus",value:h});continue}if(f==="@"){if(n.noextglob!==true&&P()==="("&&P(2)!=="?"){v({type:"at",extglob:true,value:f,output:""});continue}v({type:"text",value:f});continue}if(f!=="*"){(f==="$"||f==="^")&&(f=`\\${f}`);let g=_o.exec(it());g&&(f+=g[0],m.index+=g[0].length),v({type:"text",value:f});continue}if(p&&(p.type==="globstar"||p.star===true)){p.type="star",p.star=true,p.value+=f,p.output=C,m.backtrack=true,m.globstar=true,Y(f);continue}let y=it();if(n.noextglob!==true&&/^\([^?]/.test(y)){oe("star",f);continue}if(p.type==="star"){if(n.noglobstar===true){Y(f);continue}let g=p.prev,R=g.prev,I=g.type==="slash"||g.type==="bos",z=R&&(R.type==="star"||R.type==="globstar");if(n.bash===true&&(!I||y[0]&&y[0]!=="/")){v({type:"star",value:f,output:""});continue}let H=m.braces>0&&(g.type==="comma"||g.type==="brace"),Ie=V.length&&(g.type==="pipe"||g.type==="paren");if(!I&&g.type!=="paren"&&!H&&!Ie){v({type:"star",value:f,output:""});continue}for(;y.slice(0,3)==="/**";){let ae=e[m.index+4];if(ae&&ae!=="/")break;y=y.slice(3),Y("/**",3);}if(g.type==="bos"&&J()){p.type="globstar",p.value+=f,p.output=U(n),m.output=p.output,m.globstar=true,Y(f);continue}if(g.type==="slash"&&g.prev.type!=="bos"&&!z&&J()){m.output=m.output.slice(0,-(g.output+p.output).length),g.output=`(?:${g.output}`,p.type="globstar",p.output=U(n)+(n.strictSlashes?")":"|$)"),p.value+=f,m.globstar=true,m.output+=g.output+p.output,Y(f);continue}if(g.type==="slash"&&g.prev.type!=="bos"&&y[0]==="/"){let ae=y[1]!==void 0?"|$":"";m.output=m.output.slice(0,-(g.output+p.output).length),g.output=`(?:${g.output}`,p.type="globstar",p.output=`${U(n)}${d}|${d}${ae})`,p.value+=f,m.output+=g.output+p.output,m.globstar=true,Y(f+F()),v({type:"slash",value:"/",output:""});continue}if(g.type==="bos"&&y[0]==="/"){p.type="globstar",p.value+=f,p.output=`(?:^|${d}|${U(n)}${d})`,m.output=p.output,m.globstar=true,Y(f+F()),v({type:"slash",value:"/",output:""});continue}m.output=m.output.slice(0,-p.output.length),p.type="globstar",p.output=U(n),p.value+=f,m.output+=p.output,m.globstar=true,Y(f);continue}let O={type:"star",value:f,output:C};if(n.bash===true){O.output=".*?",(p.type==="bos"||p.type==="slash")&&(O.output=W+O.output),v(O);continue}if(p&&(p.type==="bracket"||p.type==="paren")&&n.regex===true){O.output=f,v(O);continue}(m.index===m.start||p.type==="slash"||p.type==="dot")&&(p.type==="dot"?(m.output+=_,p.output+=_):n.dot===true?(m.output+=$,p.output+=$):(m.output+=W,p.output+=W),P()!=="*"&&(m.output+=b,p.output+=b)),v(O);}for(;m.brackets>0;){if(n.strictBrackets===true)throw new SyntaxError(Et("closing","]"));m.output=rt.escapeLast(m.output,"["),ft("brackets");}for(;m.parens>0;){if(n.strictBrackets===true)throw new SyntaxError(Et("closing",")"));m.output=rt.escapeLast(m.output,"("),ft("parens");}for(;m.braces>0;){if(n.strictBrackets===true)throw new SyntaxError(Et("closing","}"));m.output=rt.escapeLast(m.output,"{"),ft("braces");}if(n.strictSlashes!==true&&(p.type==="star"||p.type==="bracket")&&v({type:"maybe_slash",value:"",output:`${d}?`}),m.backtrack===true){m.output="";for(let y of m.tokens)m.output+=y.output!=null?y.output:y.value,y.suffix&&(m.output+=y.suffix);}return m};ln.fastpaths=(e,t)=>{let n={...t},r=typeof n.maxLength=="number"?Math.min(ve,n.maxLength):ve,i=e.length;if(i>r)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${r}`);e=yr[e]||e;let{DOT_LITERAL:s,SLASH_LITERAL:o,ONE_CHAR:a,DOTS_SLASH:l,NO_DOT:c,NO_DOTS:u,NO_DOTS_SLASH:h,STAR:d,START_ANCHOR:b}=Re.globChars(n.windows),w=n.dot?u:c,E=n.dot?h:c,_=n.capture?"":"?:",$={negated:false,prefix:""},x=n.bash===true?".*?":d;n.capture&&(x=`(${x})`);let G=W=>W.noglobstar===true?x:`(${_}(?:(?!${b}${W.dot?l:s}).)*?)`,Z=W=>{switch(W){case "*":return `${w}${a}${x}`;case ".*":return `${s}${a}${x}`;case "*.*":return `${w}${x}${s}${a}${x}`;case "*/*":return `${w}${x}${o}${a}${E}${x}`;case "**":return w+G(n);case "**/*":return `(?:${w}${G(n)}${o})?${E}${a}${x}`;case "**/*.*":return `(?:${w}${G(n)}${o})?${E}${x}${s}${a}${x}`;case "**/.*":return `(?:${w}${G(n)}${o})?${s}${a}${x}`;default:{let A=/^(.*?)\.(\w+)$/.exec(W);if(!A)return;let C=Z(A[1]);return C?C+s+A[2]:void 0}}},B=rt.removePrefix(e,$),U=Z(B);return U&&n.strictSlashes!==true&&(U+=`${o}?`),U};br.exports=ln;});var Er=pt((vu,Sr)=>{var vo=gr(),cn=wr(),xr=Dt(),$o=It(),No=e=>e&&typeof e=="object"&&!Array.isArray(e),j=(e,t,n=false)=>{if(Array.isArray(e)){let u=e.map(d=>j(d,t,n));return d=>{for(let b of u){let w=b(d);if(w)return w}return false}}let r=No(e)&&e.tokens&&e.input;if(e===""||typeof e!="string"&&!r)throw new TypeError("Expected pattern to be a non-empty string");let i=t||{},s=i.windows,o=r?j.compileRe(e,t):j.makeRe(e,t,false,true),a=o.state;delete o.state;let l=()=>false;if(i.ignore){let u={...t,ignore:null,onMatch:null,onResult:null};l=j(i.ignore,u,n);}let c=(u,h=false)=>{let{isMatch:d,match:b,output:w}=j.test(u,o,t,{glob:e,posix:s}),E={glob:e,state:a,regex:o,posix:s,input:u,output:w,match:b,isMatch:d};return typeof i.onResult=="function"&&i.onResult(E),d===false?(E.isMatch=false,h?E:false):l(u)?(typeof i.onIgnore=="function"&&i.onIgnore(E),E.isMatch=false,h?E:false):(typeof i.onMatch=="function"&&i.onMatch(E),h?E:true)};return n&&(c.state=a),c};j.test=(e,t,n,{glob:r,posix:i}={})=>{if(typeof e!="string")throw new TypeError("Expected input to be a string");if(e==="")return {isMatch:false,output:""};let s=n||{},o=s.format||(i?xr.toPosixSlashes:null),a=e===r,l=a&&o?o(e):e;return a===false&&(l=o?o(e):e,a=l===r),(a===false||s.capture===true)&&(s.matchBase===true||s.basename===true?a=j.matchBase(e,t,n,i):a=t.exec(l)),{isMatch:!!a,match:a,output:l}};j.matchBase=(e,t,n)=>(t instanceof RegExp?t:j.makeRe(t,n)).test(xr.basename(e));j.isMatch=(e,t,n)=>j(t,n)(e);j.parse=(e,t)=>Array.isArray(e)?e.map(n=>j.parse(n,t)):cn(e,{...t,fastpaths:false});j.scan=(e,t)=>vo(e,t);j.compileRe=(e,t,n=false,r=false)=>{if(n===true)return e.output;let i=t||{},s=i.contains?"":"^",o=i.contains?"":"$",a=`${s}(?:${e.output})${o}`;e&&e.negated===true&&(a=`^(?!${a}).*$`);let l=j.toRegex(a,t);return r===true&&(l.state=e),l};j.makeRe=(e,t={},n=false,r=false)=>{if(!e||typeof e!="string")throw new TypeError("Expected a non-empty string");let i={negated:false,fastpaths:true};return t.fastpaths!==false&&(e[0]==="."||e[0]==="*")&&(i.output=cn.fastpaths(e,t)),i.output||(i=cn(e,t)),j.compileRe(i,t,n,r)};j.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 /$^/}};j.constants=$o;Sr.exports=j;});var Cr=pt(($u,_r)=>{var Ar=Er(),ko=Dt();function Tr(e,t,n=false){return t&&(t.windows===null||t.windows===void 0)&&(t={...t,windows:ko.isWindows()}),Ar(e,t,n)}Object.assign(Tr,Ar);_r.exports=Tr;});function Ht(e){if("String"in e)return e.String.sval}function gt(e){return e.map(Ht).filter(t=>t!=null)}function Pr(e){return Object.keys(e)[0]}function Lr(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 Ne=L(()=>{});function Or(e){let t=e.toLowerCase();return ["serial","serial4","bigserial","serial8","smallserial","serial2"].includes(t)}function Fr(e){let t=e.toLowerCase();return ["varchar","character varying","char","character","bpchar"].includes(t)}function Ir(e){let t=e.toLowerCase();return ["numeric","decimal"].includes(t)}var pn,ke,ea,mn=L(()=>{Ne();pn=class extends Error{},ke=class extends pn{constructor(n,r){super(r??`Unsupported node type: ${Pr(n)}`);this.node=n;}};ea={CreateEnumStmt:{react:"ignore"},CreateDomainStmt:{react:"warn"},CreateSeqStmt:{react:"error"},AlterSeqStmt:{react:"error"},CreateSchemaStmt:{react:"warn"},CreatePolicyStmt:{react:"ignore"},PartitionElem:{react:"error"},PartitionCmd:{react:"error"},VariableSetStmt:{react:"ignore"},CompositeTypeStmt:{react:"error"},AlterEnumStmt:{react:"error"},AlterObjectSchemaStmt:{react:"error"},AlterOwnerStmt:{react:"error"},AlterTypeStmt:{react:"error"},AlterFunctionStmt:{react:"error"},AlterDefaultPrivilegesStmt:{react:"error"},GrantStmt:{react:"error"},GrantRoleStmt:{react:"error"},CopyStmt:{react:"error"},CreateCastStmt:{react:"error"},AlterOpFamilyStmt:{react:"error"},AlterOperatorStmt:{react:"error"},TruncateStmt:{react:"error"},A_Indirection:{react:"error"},XmlExpr:{react:"error"},XmlSerialize:{react:"error"},RangeTableSample:{react:"error"},GroupingSet:{react:"error"}},new Map(Object.entries(ea));});var Q,Pe,Dr=L(()=>{Ne();mn();Q=class extends ke{constructor(t,n){super(t,`Unsupported expression: ${n}`);}},Pe=class{deparse(t){if("A_Const"in t){let i=t.A_Const;if(i.boolval!==void 0)return i.boolval.boolval?{}:{$always:false}}let n=Object.keys(t)[0],r=this[n];if(!r)throw new Q({[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 Q({[n]:t},`deparseValue: ${n}`)}A_Expr(t){if(t.kind==="AEXPR_OP"){let n=t.name?.[0],r=n?Ht(n):void 0;if(!r)throw new Q({A_Expr:t},"A_Expr missing operator");let i=this.isJwtAccessor(t);if(i)return {[i]:{}};let s=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 Q({A_Expr:t},`Unsupported operator: ${r}`);let l=t.rexpr!=null&&"ColumnRef"in t.rexpr;if(typeof s=="string"&&s.startsWith("{{")&&l)return {[o]:{[a]:s}};let c=l&&typeof o=="string"?{$ref:o}:o;return {[s]:{[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.name?.[0]?Ht(t.name[0]):"~~")==="!~~"?"$notLike":"$like";return {[n]:{[s]: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(i=>this.deparseValue(i)):[];return {[n]:{$in:r}}}throw new Q({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 Q({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],i="ResTarget"in r?r.ResTarget:void 0;if(i?.val){let s=this.deparseValue(i.val);return s}}}throw new Q({SubLink:t},`SubLink type: ${t.subLinkType}`)}SelectStmt(t){let{from:n,schema:r,join:i}=this.deparseFromClause(t.fromClause??[]),s=[];for(let d of t.targetList??[]){let b="ResTarget"in d?d.ResTarget:void 0;if(b?.val){let w=this.deparseValue(b.val);Array.isArray(w)?s.push(...w.map(String)):w!=null&&w!==""&&s.push(String(w));}}let o=t.whereClause?this.deparse(t.whereClause):void 0,a=this.deparseSortClause(t.sortClause),l=this.deparseLimit(t.limitCount),c=this.deparseLimit(t.limitOffset),u=this.deparseGroupClause(t.groupClause),h={type:"query",from:n,select:s};return r&&(h.schema=r),Object.keys(i).length>0&&(h.join=i),o&&(h.where=o),a.length>0&&(h.order=a),l!==void 0&&(h.limit=l),c!==void 0&&(h.offset=c),u.length>0&&(h.group=u),h}FuncCall(t){let n=this.isAuthFunc(t.funcname??[]);if(n)return n;throw new Q({FuncCall:t},`FuncCall: ${gt(t.funcname??[]).join(".")}`)}ColumnRef(t){let n=gt(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 Q({A_Const:t},"A_Const: unknown variant")}TypeCast(t){if(!t.arg)throw new Q({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 i=r.RangeVar;return {from:i.relname??"",schema:i.schemaname,join:n}}if("JoinExpr"in r){let{from:i,schema:s}=this.walkJoinExpr(r.JoinExpr,n);return {from:i,schema:s,join:n}}return {from:"",join:n}}walkJoinExpr(t,n){let r={from:""};if(t.larg)if("RangeVar"in t.larg){let i=t.larg.RangeVar;r={from:i.relname??"",schema:i.schemaname};}else "JoinExpr"in t.larg&&(r=this.walkJoinExpr(t.larg.JoinExpr,n));if(t.rarg&&"RangeVar"in t.rarg){let i=t.rarg.RangeVar,s=i.relname??"",o=i.alias?.aliasname??s,a=t.jointype==="JOIN_LEFT"?"left":"inner",l={from:s,type:a};t.quals&&(l.on=this.deparse(t.quals));let c=o;if(c in n){let u=2;for(;`${c}_${u}`in n;)u++;c=`${c}_${u}`;}n[c]=l;}return r}deparseSortClause(t){if(!t)return [];let n=[];for(let r of t){if(!("SortBy"in r))continue;let i=r.SortBy;if(!i.node)continue;let s=String(this.deparseValue(i.node)),o=i.sortby_dir==="SORTBY_DESC"?"desc":"asc",a={column:s,direction:o};i.sortby_nulls==="SORTBY_NULLS_FIRST"?a.nullsFirst=true:i.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=gt(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]?Ht(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 i=this.isJwtAccessor(t.lexpr.A_Expr);if(i)return `${i.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 Le,jr=L(()=>{Le=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 Bt,hn=L(()=>{Bt=class extends Error{constructor(n,r,i,s){super(`check constraint "${i}" violated for ${n}.${r}`);this.table=n;this.column=r;this.constraint=i;this.value=s;this.name="CheckConstraintError";}};});var q,at=L(()=>{hn();q=class{context;constructor(t){this.context=t;}get isShimBacked(){return false}checkConstraint(){return null}serialize(t){return t}deserialize(t){return t}validateStorage(t){return {status:"pass",message:null}}validationFail(t,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=[],i=this.context.column;r.push(this.quoteIfNeeded(i)),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 s=this.checkConstraint();return s&&r.push(`CHECK (${s})`),r.join(" ")}checkError(t,n){return new Bt(this.context.table,this.context.column,t,n)}quoteIfNeeded(t){return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)?t:`"${t}"`}};});var yt,Oe=L(()=>{at();yt=class extends q{get sqliteType(){return "INTEGER"}};});var qt,dn=L(()=>{Oe();qt=class extends yt{constructor(t){super({...t,isSerial:true});}};});function na(e,t){let{precision:n,scale:r}=t,i=10**r,s=10**(n-r);return Math.abs(Math.round(e*i)-e*i)<1e-4&&Math.abs(e)<s}var Vt,gn=L(()=>{at();Vt=class extends q{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,i=10**n,s=10**(t-n);return `ABS(ROUND(${r} * ${i}) - ${r} * ${i}) < 0.0001 AND ABS(${r}) < ${s}`}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(!na(t,this.numericPrecision))return this.validationFail(`Does not fit numeric(${n}, ${r}).`,"Patch rows within numeric precision.")}return this.validationPass()}};});var D,et=L(()=>{at();D=class extends q{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 Gt,yn=L(()=>{at();Gt=class extends q{get sqliteType(){return "BLOB"}};});var Wt,bn=L(()=>{at();Wt=class extends q{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}checkConstraint(){return `${this.context.column} IN (0, 1)`}serialize(t){if(this.isNullish(t))return t;if(t===true||t===1)return 1;if(t===false||t===0)return 0;throw this.checkError("boolean_range",t)}deserialize(t){return this.isNullish(t)?t:t===1?true:t===0?false:t}validateStorage(t){return this.isNullish(t)?this.validationPass():t===1||t===0?this.validationPass():this.validationFail("Expected 0 or 1.","Patch rows with boolean values.")}};});function Mr(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var zt,wn=L(()=>{at();zt=class extends q{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=Mr(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."):Mr(t).ok?this.validationPass():this.validationFail("Invalid JSON text.","Patch rows with valid JSON.")}};});function ra(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 Kt,xn=L(()=>{et();Kt=class extends D{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"||!ra(t)?this.validationFail("Invalid date.","Patch rows with YYYY-MM-DD dates."):this.validationPass()}};});function ia(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]),i=t[3]===void 0?0:Number(t[3]),s=t[5]===void 0?null:Number(t[5]),o=t[6]===void 0?null:Number(t[6]),a=s===null||o!==null&&s<=15&&o<=59;return n<=24&&r<=59&&i<=59&&(n!==24||r===0&&i===0)&&a}var Xt,Sn=L(()=>{et();Xt=class extends D{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"||!ia(t)?this.validationFail("Invalid time.","Patch rows with HH:MM[:SS] times."):this.validationPass()}};});function sa(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]),i=Number(t[3]),s=Number(t[4]),o=Number(t[5]),a=t[6]===void 0?0:Number(t[6]),l=t[8]===void 0?null:Number(t[8]),c=t[9]===void 0?null:Number(t[9]),u=new Date(Date.UTC(n,r-1,i)),h=u.getUTCFullYear()===n&&u.getUTCMonth()===r-1&&u.getUTCDate()===i,d=s<=24&&o<=59&&a<=59&&(s!==24||o===0&&a===0),b=l===null||c!==null&&l<=15&&c<=59;return h&&d&&b}var Jt,En=L(()=>{et();Jt=class extends D{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"||!sa(t)?this.validationFail("Invalid timestamp.","Patch rows with ISO timestamps."):this.validationPass()}};});var Yt,An=L(()=>{et();Yt=class extends D{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 Qt,Tn=L(()=>{et();Qt=class extends D{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 Ur(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var Ct,_n=L(()=>{at();Ct=class extends q{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=Ur(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=Ur(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 i=this.elementField.validateStorage(r);if(i.status==="fail")return this.validationFail(`Invalid ${this.elementField.context.pgTypeName} array element.`,i.action??"Patch rows with valid array elements.")}return this.validationPass()}};});function Hr(e){return aa.test(e.toLowerCase())}var oa,aa,Zt,Cn=L(()=>{et();oa="????????-????-????-????-????????????",aa=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;Zt=class extends D{get isShimBacked(){return true}checkConstraint(){let t=this.quoteIfNeeded(this.context.column);return `${t} IS NULL OR ${t} GLOB '${oa}'`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string")throw this.checkError("uuid_format",t);let n=t.toLowerCase();if(!Hr(n))throw this.checkError("uuid_format",t);return n}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!Hr(t)?this.validationFail("Invalid UUID.","Patch rows with valid UUIDs."):this.validationPass()}};});function la(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 ca(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 ua(e){if(!e.includes(":"))return false;try{return new URL(`http://[${e}]/`),!0}catch{return false}}function Br(e){let t=la(e);return t?ca(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=32:ua(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=128:false:false}var te,Rn=L(()=>{et();te=class extends D{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(!Br(n))throw this.checkError("inet_format",t);return n}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!Br(t.trim())?this.validationFail("Invalid inet address.","Patch rows with valid inet strings."):this.validationPass()}};});var ee,vn=L(()=>{et();ee=class extends D{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 ne(e,t){if(t?.isArray){let r=ne(e,{...t,isArray:false});return new Ct(e,r)}if(t?.enumValues)return new Qt(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),i={...e,pgTypeName:r},s=ne(i);return new Ct(e,s)}return pa.has(n)?new qt(e):fa.has(n)?new yt(e):ga.has(n)?new Wt(e):ya.has(n)?new zt(e):Sa.has(n)?new Kt(e):Ea.has(n)?new Xt(e):Aa.has(n)?new Jt(e):Ta.has(n)?new Yt(e):da.has(n)?new Gt(e):ma.has(n)?new Vt(e,t?.numericPrecision):ba.has(n)?new Zt(e):wa.has(n)?new D(e,63):xa.has(n)?new te(e):ha.has(n)?new D(e,t?.lengthConstraint):new ee(e)}var fa,pa,ma,ha,da,ga,ya,ba,wa,xa,Sa,Ea,Aa,Ta,qr=L(()=>{Oe();dn();gn();et();yn();bn();wn();xn();Sn();En();An();Tn();_n();Cn();Rn();vn();fa=new Set(["int2","smallint","int4","integer","int","int8","bigint"]),pa=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]),ma=new Set(["float4","real","float8","double precision","numeric","decimal"]),ha=new Set(["text","varchar","character varying","char","character","bpchar"]),da=new Set(["bytea"]),ga=new Set(["bool","boolean"]),ya=new Set(["json","jsonb"]),ba=new Set(["uuid"]),wa=new Set(["name"]),xa=new Set(["inet"]),Sa=new Set(["date"]),Ea=new Set(["time","timetz","time without time zone","time with time zone"]),Aa=new Set(["timestamp","timestamptz","timestamp without time zone","timestamp with time zone"]),Ta=new Set(["interval"]);});var Vr=L(()=>{});var re,Gr=L(()=>{re=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,i]of Object.entries(t)){let s=this.fields.get(r);n[r]=s?s.serialize(i):i;}return n}deserializeRow(t){let n={};for(let[r,i]of Object.entries(t)){let s=this.fields.get(r);n[r]=s?s.deserialize(i):i;}return n}applyDefaults(t){let n={...t};for(let[r,i]of this.fields)!(r in n)&&i.context.defaultFn&&(n[r]=i.context.defaultFn());return n}};});var Wr=L(()=>{at();hn();Oe();dn();gn();et();yn();bn();wn();xn();Sn();En();An();Tn();_n();Cn();Rn();vn();qr();Vr();Gr();});var zr={};hi(zr,{_resetWarnedMissingToClauseForTests:()=>_a,collectComments:()=>ka,collectEnums:()=>Ca,collectPolicies:()=>va,collectSchema:()=>$a,collectTableConstraints:()=>Na,collectVariables:()=>Ra});function _a(){$n.clear();}function Ca(e){let t=new Map;for(let n of e.stmts??[]){if(!n.stmt||!("CreateEnumStmt"in n.stmt))continue;let r=n.stmt.CreateEnumStmt,i=gt(r.typeName??[]).join(".");if(!i||!r.vals)continue;let s=gt(r.vals);t.set(i.toLowerCase(),s);}return t}function Ra(e){let t=new Map;for(let n of e.stmts??[]){if(!n.stmt||!("VariableSetStmt"in n.stmt))continue;let r=n.stmt.VariableSetStmt,i=r.name,s=Lr(r.args?.[0]??{});t.set(i,{value:s,local:r.is_local});}return t}function va(e){let t=new Pe,n=new Set,r=[];for(let i of e.stmts??[])if(i.stmt){if("CreatePolicyStmt"in i.stmt){let s=i.stmt.CreatePolicyStmt,o=s.table?.relname??"",a=s.table?.schemaname,l={select:"SELECT",insert:"INSERT",update:"UPDATE",delete:"DELETE"},c=s.cmd_name?l[s.cmd_name]??"ALL":"ALL",u=s.permissive===true,h=[],d=false;for(let _ of s.roles??[])if("RoleSpec"in _){let $=_.RoleSpec;$.roletype==="ROLESPEC_PUBLIC"?$.location===-1&&(d=true):$.roletype==="ROLESPEC_CSTRING"&&$.rolename&&h.push($.rolename);}if(d){let _=a?`${a}.${o}`:o,$=s.policy_name??"",x=`${_}::${$}`;$n.has(x)||($n.add(x),console.warn(`[supalite] policy "${$}" on "${_}" has no TO clause \u2014 applies to all roles (PUBLIC). For clarity, prefer an explicit \`TO <role>\` clause (e.g. \`TO authenticated\`).`));}let b=s.qual?t.deparse(s.qual):void 0,w=s.with_check?t.deparse(s.with_check):void 0,E=new Le({name:s.policy_name??"",table:o,schema:a,command:c,permissive:u,roles:h,using:b,withCheck:w});r.push(E);}if("AlterTableStmt"in i.stmt){let s=i.stmt.AlterTableStmt;if((s.cmds??[]).some(l=>"AlterTableCmd"in l&&(l.AlterTableCmd.subtype==="AT_EnableRowSecurity"||l.AlterTableCmd.subtype==="AT_ForceRowSecurity"))){let l=s.relation?.relname??"";n.add(l);}}}return {policies:r,tables:n}}function $a(e,t){let n=new Map;for(let r of e.stmts??[]){if(!r.stmt||!("CreateStmt"in r.stmt))continue;let i=r.stmt.CreateStmt,s=i.relation?.relname??"",o=i.relation?.schemaname??"public";if(!s)continue;let a=new re(s,o);for(let l of i.tableElts??[]){if(!("ColumnDef"in l))continue;let c=l.ColumnDef,u=c.colname;if(!u)continue;let h=c.typeName?.names?.map(S=>S.String?.sval||S.String?.str).filter(Boolean),d=h&&(h.length===2&&h[0]==="pg_catalog"?h[1]:h[0]);if(!d)continue;let b=!!c.typeName?.arrayBounds?.length,w=Array.isArray(c.typeName?.typmods)?c.typeName.typmods:[],E=S=>w[S]?.A_Const?.ival?.ival??w[S]?.A_Const?.val?.ival?.ival,_={isArray:b};if(Fr(d)&&w.length>0){let S=E(0);typeof S=="number"&&S>0&&(_.lengthConstraint=S);}if(Ir(d)&&w.length>=2){let S=E(0),k=E(1);typeof S=="number"&&typeof k=="number"&&S>0&&k>=0&&(_.numericPrecision={precision:S,scale:k});}let $=t.get(d.toLowerCase());$&&(_.enumValues=$);let x=Array.isArray(c.constraints)?c.constraints:[],G=x.some(S=>S.Constraint?.contype==="CONSTR_PRIMARY"),Z=Or(d)||x.some(S=>S.Constraint?.contype==="CONSTR_IDENTITY"),B=x.some(S=>S.Constraint?.contype==="CONSTR_NOTNULL"),U=x.find(S=>S.Constraint?.contype==="CONSTR_UNIQUE"),W=x.find(S=>S.Constraint?.contype==="CONSTR_GENERATED"),A=x.find(S=>S.Constraint?.contype==="CONSTR_FOREIGN"),C=x.find(S=>S.Constraint?.contype==="CONSTR_CHECK"),m;if(A){let S=A.Constraint,k=S.pktable?.relname,p=S.pktable?.schemaname,f=S.pk_attrs?.[0]?.String?.sval;k&&f&&(m={refSchema:p,refTable:k,refColumn:f,constraintName:S.conname||void 0});}let V={schema:o,table:s,column:u,pgTypeName:d,nullable:!B&&!G,defaultValue:null,defaultFn:null,isPrimaryKey:G,isUnique:!!U,isSerial:Z,isGenerated:!!W,fkRef:m,hasCheck:!!C,checkConstraintName:C?.Constraint?.conname||void 0,uniqueConstraintName:U?.Constraint?.conname||void 0};a.set(u,ne(V,_));}n.set(`${o}.${s}`,a);}return n}function Na(e){let t=[];for(let n of e.stmts??[]){if(!n.stmt||!("CreateStmt"in n.stmt))continue;let r=n.stmt.CreateStmt,i=r.relation?.relname??"",s=r.relation?.schemaname??"public";if(i)for(let o of r.tableElts??[]){if("ColumnDef"in o)continue;let a=o;if(!a.Constraint)continue;let l=a.Constraint,c=l.contype;if(c==="CONSTR_UNIQUE"){let u=(l.keys??[]).map(h=>h.String?.sval??h.String?.str).filter(Boolean);if(u.length===0)continue;t.push({schema:s,table:i,kind:"unique",name:l.conname||void 0,columns:u});}else if(c==="CONSTR_CHECK")t.push({schema:s,table:i,kind:"check",name:l.conname||void 0,columns:[]});else if(c==="CONSTR_FOREIGN"){let u=(l.fk_attrs??[]).map(b=>b.String?.sval??b.String?.str).filter(Boolean),h=(l.pk_attrs??[]).map(b=>b.String?.sval??b.String?.str).filter(Boolean),d=l.pktable?.relname;if(!d)continue;t.push({schema:s,table:i,kind:"foreign_key",name:l.conname||void 0,columns:u,refSchema:l.pktable?.schemaname,refTable:d,refColumns:h});}}}return t}function ka(e){let t=[];for(let n of e.stmts??[]){if(!n.stmt||!("CommentStmt"in n.stmt))continue;let r=n.stmt.CommentStmt,i=r.comment??"";if(!i)continue;let s=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(s==="OBJECT_TABLE"||s==="OBJECT_VIEW"){let[a,l]=o.length>=2?o:["public",o[0]];t.push({schema:a,table:l,text:i});}else if(s==="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:i});}}}return t}var $n,Kr=L(()=>{Dr();Ne();jr();Wr();mn();$n=new Set;});function tt(e,t){le.existsSync(e)||(le.mkdirSync(e,{recursive:true}),t?.());}function mt(e,t,n){le.existsSync(e)||(le.writeFileSync(e,t),n?.());}var ot=class e{root;constructor(t,n){let r=n??e.projectDir();this.root=nt__default.join(r,t??"");}ensureRoot(){tt(this.root);}static homeDir(){return nt__default.join(gi.homedir(),".lite")}static projectDir(){return nt__default.join(process.cwd(),"supabase")}deleteAll(t=false){try{le.rmSync(this.root,{recursive:!0});}catch(n){if(!t)throw n}this.ensureRoot();}delete(t,n=false){try{le.unlinkSync(nt__default.join(this.root,t));}catch(r){if(!n)throw r}}write(t,n,r=false){try{this.ensureRoot(),le.writeFileSync(nt__default.join(this.root,t),n);}catch(i){if(!r)throw i}}read(t,n=false){try{return le.readFileSync(nt__default.join(this.root,t),"utf8")}catch(r){if(!n)throw r}}relativePath(t){return t?nt__default.relative(process.cwd(),nt__default.join(this.root,t)):this.root}path(t){return t?nt__default.join(this.root,t):this.root}};var vt=process.env.SUPALITE_CLOUD_URL??(process.env.LOCAL?"http://localhost:2000":"https://www.lite.dev");var fe=class{root;constructor(t){this.root=t??nt__default.join(gi.homedir(),".lite","auth"),tt(this.root);}async getItem(t){try{return le.readFileSync(nt__default.join(this.root,t+".json"),"utf8")}catch{return null}}async setItem(t,n){le.writeFileSync(nt__default.join(this.root,t+".json"),n);}async removeItem(t){try{le.unlinkSync(nt__default.join(this.root,t+".json"));}catch{return}}};var wt=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 fe(nt__default.join(ot.homeDir(),"auth")),this._client=this.config.withSupabaseClient!==false?this.config.client??createClient(this.config.host??vt,process.env.SUPALITE_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??vt);return await fetch(r,{...n,headers:{...n?.headers,Authorization:`Bearer ${this.config.token}`}})}};var xt=class extends wt{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.host),i=r.hostname==="localhost"?"supalite.local":r.hostname,s=i.split(".").filter(a=>a!=="www"),o=s.length>=2?s.slice(-2).join("."):i;return `${r.protocol}//${n}.${o}${r.port?`:${r.port}`:""}`}};var ct={config_dir:"supabase",default_db_url:"file:supabase/.temp/data.db",default_db_dir:"supabase/.temp/data"};var Ft=Rt($t());function Ai(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return [n.length,n.pop().length+1]}function Ti(e,t,n){let r=e.split(/\r\n|\n|\r/g),i="",s=(Math.log10(t+1)|0)+1;for(let o=t-1;o<=t+1;o++){let a=r[o-1];a&&(i+=o.toString().padEnd(s," "),i+=": ",i+=a,i+=`
|
|
12
|
+
var yi=Object.create;var De=Object.defineProperty;var bi=Object.getOwnPropertyDescriptor;var wi=Object.getOwnPropertyNames;var xi=Object.getPrototypeOf,Si=Object.prototype.hasOwnProperty;var L=(e,t)=>()=>(e&&(t=e(e=0)),t);var mt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ei=(e,t)=>{for(var n in t)De(e,n,{get:t[n],enumerable:true});},Ti=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of wi(t))!Si.call(e,i)&&i!==n&&De(e,i,{get:()=>t[i],enumerable:!(r=bi(t,i))||r.enumerable});return e};var $t=(e,t,n)=>(n=e!=null?yi(xi(e)):{},Ti(De(n,"default",{value:e,enumerable:true}),e));var Nt=mt((Ul,Be)=>{var he=process||{},In=he.argv||[],me=he.env||{},$i=!(me.NO_COLOR||In.includes("--no-color"))&&(!!me.FORCE_COLOR||In.includes("--color")||he.platform==="win32"||(he.stdout||{}).isTTY&&me.TERM!=="dumb"||!!me.CI),vi=(e,t,n=e)=>r=>{let i=""+r,s=i.indexOf(t,e.length);return ~s?e+Ni(i,t,n,s)+t:e+i+t},Ni=(e,t,n,r)=>{let i="",s=0;do i+=e.substring(s,r)+n,s=r+t.length,r=e.indexOf(t,s);while(~r);return i+e.substring(s)},jn=(e=$i)=>{let t=e?vi:()=>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")}};Be.exports=jn();Be.exports.createColors=jn;});var jt=mt((Bu,pr)=>{var lr="[^\\\\/]",uo="(?=.)",cr="[^/]",en="(?:\\/|$)",ur="(?:^|\\/)",nn=`\\.{1,2}${en}`,fo="(?!\\.)",po=`(?!${ur}${nn})`,mo=`(?!\\.{0,1}${en})`,ho=`(?!${nn})`,go="[^.\\/]",yo=`${cr}*?`,bo="/",fr={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:uo,QMARK:cr,END_ANCHOR:en,DOTS_SLASH:nn,NO_DOT:fo,NO_DOTS:po,NO_DOT_SLASH:mo,NO_DOTS_SLASH:ho,QMARK_NO_DOT:go,STAR:yo,START_ANCHOR:ur,SEP:bo},wo={...fr,SLASH_LITERAL:"[\\\\/]",QMARK:lr,STAR:`${lr}*?`,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:"\\"},xo={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"};pr.exports={MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:xo,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?wo:fr}};});var Dt=mt(X=>{var{REGEX_BACKSLASH:So,REGEX_REMOVE_BACKSLASH:Eo,REGEX_SPECIAL_CHARS:To,REGEX_SPECIAL_CHARS_GLOBAL:Ao}=jt();X.isObject=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);X.hasRegexChars=e=>To.test(e);X.isRegexChar=e=>e.length===1&&X.hasRegexChars(e);X.escapeRegex=e=>e.replace(Ao,"\\$1");X.toPosixSlashes=e=>e.replace(So,"/");X.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};X.removeBackslashes=e=>e.replace(Eo,t=>t==="\\"?"":t);X.escapeLast=(e,t,n)=>{let r=e.lastIndexOf(t,n);return r===-1?e:e[r-1]==="\\"?X.escapeLast(e,t,r-1):`${e.slice(0,r)}\\${e.slice(r)}`};X.removePrefix=(e,t={})=>{let n=e;return n.startsWith("./")&&(n=n.slice(2),t.prefix="./"),n};X.wrapOutput=(e,t={},n={})=>{let r=n.contains?"":"^",i=n.contains?"":"$",s=`${r}(?:${e})${i}`;return t.negated===true&&(s=`(?:^(?!${s}).*$)`),s};X.basename=(e,{windows:t}={})=>{let n=e.split(t?/[\\/]/:"/"),r=n[n.length-1];return r===""?n[n.length-2]:r};});var xr=mt((Hu,wr)=>{var mr=Dt(),{CHAR_ASTERISK:rn,CHAR_AT:_o,CHAR_BACKWARD_SLASH:Ut,CHAR_COMMA:Co,CHAR_DOT:sn,CHAR_EXCLAMATION_MARK:on,CHAR_FORWARD_SLASH:br,CHAR_LEFT_CURLY_BRACE:an,CHAR_LEFT_PARENTHESES:ln,CHAR_LEFT_SQUARE_BRACKET:Ro,CHAR_PLUS:$o,CHAR_QUESTION_MARK:hr,CHAR_RIGHT_CURLY_BRACE:vo,CHAR_RIGHT_PARENTHESES:dr,CHAR_RIGHT_SQUARE_BRACKET:No}=jt(),gr=e=>e===br||e===Ut,yr=e=>{e.isPrefix!==true&&(e.depth=e.isGlobstar?1/0:1);},ko=(e,t)=>{let n=t||{},r=e.length-1,i=n.parts===true||n.scanToEnd===true,s=[],o=[],a=[],l=e,c=-1,u=0,h=0,d=false,b=false,w=false,E=false,_=false,v=false,x=false,V=false,Z=false,H=false,B=0,W,T,C={value:"",depth:0,isGlob:false},m=()=>c>=r,G=()=>l.charCodeAt(c+1),S=()=>(W=T,l.charCodeAt(++c));for(;c<r;){T=S();let P;if(T===Ut){x=C.backslashes=true,T=S(),T===an&&(v=true);continue}if(v===true||T===an){for(B++;m()!==true&&(T=S());){if(T===Ut){x=C.backslashes=true,S();continue}if(T===an){B++;continue}if(v!==true&&T===sn&&(T=S())===sn){if(d=C.isBrace=true,w=C.isGlob=true,H=true,i===true)continue;break}if(v!==true&&T===Co){if(d=C.isBrace=true,w=C.isGlob=true,H=true,i===true)continue;break}if(T===vo&&(B--,B===0)){v=false,d=C.isBrace=true,H=true;break}}if(i===true)continue;break}if(T===br){if(s.push(c),o.push(C),C={value:"",depth:0,isGlob:false},H===true)continue;if(W===sn&&c===u+1){u+=2;continue}h=c+1;continue}if(n.noext!==true&&(T===$o||T===_o||T===rn||T===hr||T===on)===true&&G()===ln){if(w=C.isGlob=true,E=C.isExtglob=true,H=true,T===on&&c===u&&(Z=true),i===true){for(;m()!==true&&(T=S());){if(T===Ut){x=C.backslashes=true,T=S();continue}if(T===dr){w=C.isGlob=true,H=true;break}}continue}break}if(T===rn){if(W===rn&&(_=C.isGlobstar=true),w=C.isGlob=true,H=true,i===true)continue;break}if(T===hr){if(w=C.isGlob=true,H=true,i===true)continue;break}if(T===Ro){for(;m()!==true&&(P=S());){if(P===Ut){x=C.backslashes=true,S();continue}if(P===No){b=C.isBracket=true,w=C.isGlob=true,H=true;break}}if(i===true)continue;break}if(n.nonegate!==true&&T===on&&c===u){V=C.negated=true,u++;continue}if(n.noparen!==true&&T===ln){if(w=C.isGlob=true,i===true){for(;m()!==true&&(T=S());){if(T===ln){x=C.backslashes=true,T=S();continue}if(T===dr){H=true;break}}continue}break}if(w===true){if(H=true,i===true)continue;break}}n.noext===true&&(E=false,w=false);let k=l,p="",f="";u>0&&(p=l.slice(0,u),l=l.slice(u),h-=u),k&&w===true&&h>0?(k=l.slice(0,h),f=l.slice(h)):w===true?(k="",f=l):k=l,k&&k!==""&&k!=="/"&&k!==l&&gr(k.charCodeAt(k.length-1))&&(k=k.slice(0,-1)),n.unescape===true&&(f&&(f=mr.removeBackslashes(f)),k&&x===true&&(k=mr.removeBackslashes(k)));let J={prefix:p,input:e,start:u,base:k,glob:f,isBrace:d,isBracket:b,isGlob:w,isExtglob:E,isGlobstar:_,negated:V,negatedExtglob:Z};if(n.tokens===true&&(J.maxDepth=0,gr(T)||o.push(C),J.tokens=o),n.parts===true||n.tokens===true){let P;for(let F=0;F<s.length;F++){let st=P?P+1:u,Y=s[F],ct=e.slice(st,Y);n.tokens&&(F===0&&u!==0?(o[F].isPrefix=true,o[F].value=p):o[F].value=ct,yr(o[F]),J.maxDepth+=o[F].depth),(F!==0||ct!=="")&&a.push(ct),P=Y;}if(P&&P+1<e.length){let F=e.slice(P+1);a.push(F),n.tokens&&(o[o.length-1].value=F,yr(o[o.length-1]),J.maxDepth+=o[o.length-1].depth);}J.slashes=s,J.parts=a;}return J};wr.exports=ko;});var Tr=mt((qu,Er)=>{var $e=jt(),it=Dt(),{MAX_LENGTH:ve,POSIX_REGEX_SOURCE:Po,REGEX_NON_SPECIAL_CHARS:Lo,REGEX_SPECIAL_CHARS_BACKREF:Oo,REPLACEMENTS:Sr}=$e,Fo=(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(i=>it.escapeRegex(i)).join("..")}return n},Tt=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`,cn=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a string");e=Sr[e]||e;let n={...t},r=typeof n.maxLength=="number"?Math.min(ve,n.maxLength):ve,i=e.length;if(i>r)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${r}`);let s={type:"bos",value:"",output:n.prepend||""},o=[s],a=n.capture?"":"?:",l=$e.globChars(n.windows),c=$e.extglobChars(l),{DOT_LITERAL:u,PLUS_LITERAL:h,SLASH_LITERAL:d,ONE_CHAR:b,DOTS_SLASH:w,NO_DOT:E,NO_DOT_SLASH:_,NO_DOTS_SLASH:v,QMARK:x,QMARK_NO_DOT:V,STAR:Z,START_ANCHOR:H}=l,B=y=>`(${a}(?:(?!${H}${y.dot?w:u}).)*?)`,W=n.dot?"":E,T=n.dot?x:V,C=n.bash===true?B(n):Z;n.capture&&(C=`(${C})`),typeof n.noext=="boolean"&&(n.noextglob=n.noext);let m={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=it.removePrefix(e,m),i=e.length;let G=[],S=[],k=[],p=s,f,J=()=>m.index===i-1,P=m.peek=(y=1)=>e[m.index+y],F=m.advance=()=>e[++m.index]||"",st=()=>e.slice(m.index+1),Y=(y="",O=0)=>{m.consumed+=y,m.index+=O;},ct=y=>{m.output+=y.output!=null?y.output:y.value,Y(y.value);},di=()=>{let y=1;for(;P()==="!"&&(P(2)!=="("||P(3)==="?");)F(),m.start++,y++;return y%2===0?false:(m.negated=true,m.start++,true)},oe=y=>{m[y]++,k.push(y);},pt=y=>{m[y]--,k.pop();},$=y=>{if(p.type==="globstar"){let O=m.braces>0&&(y.type==="comma"||y.type==="brace"),g=y.extglob===true||G.length&&(y.type==="pipe"||y.type==="paren");y.type!=="slash"&&y.type!=="paren"&&!O&&!g&&(m.output=m.output.slice(0,-p.output.length),p.type="star",p.value="*",p.output=C,m.output+=p.output);}if(G.length&&y.type!=="paren"&&(G[G.length-1].inner+=y.value),(y.value||y.output)&&ct(y),p&&p.type==="text"&&y.type==="text"){p.output=(p.output||p.value)+y.value,p.value+=y.value;return}y.prev=p,o.push(y),p=y;},ae=(y,O)=>{let g={...c[O],conditions:1,inner:""};g.prev=p,g.parens=m.parens,g.output=m.output;let R=(n.capture?"(":"")+g.open;oe("parens"),$({type:y,value:O,output:m.output?"":b}),$({type:"paren",extglob:true,value:F(),output:R}),G.push(g);},gi=y=>{let O=y.close+(n.capture?")":""),g;if(y.type==="negate"){let R=C;if(y.inner&&y.inner.length>1&&y.inner.includes("/")&&(R=B(n)),(R!==C||J()||/^\)+$/.test(st()))&&(O=y.close=`)$))${R}`),y.inner.includes("*")&&(g=st())&&/^\.[^\\/.]+$/.test(g)){let I=cn(g,{...t,fastpaths:false}).output;O=y.close=`)${I})${R})`;}y.prev.type==="bos"&&(m.negatedExtglob=true);}$({type:"paren",extglob:true,value:f,output:O}),pt("parens");};if(n.fastpaths!==false&&!/(^[*!]|[/()[\]{}"])/.test(e)){let y=false,O=e.replace(Oo,(g,R,I,z,M,je)=>z==="\\"?(y=true,g):z==="?"?R?R+z+(M?x.repeat(M.length):""):je===0?T+(M?x.repeat(M.length):""):x.repeat(I.length):z==="."?u.repeat(I.length):z==="*"?R?R+z+(M?C:""):C:R?g:`\\${g}`);return y===true&&(n.unescape===true?O=O.replace(/\\/g,""):O=O.replace(/\\+/g,g=>g.length%2===0?"\\\\":g?"\\":"")),O===e&&n.contains===true?(m.output=e,m):(m.output=it.wrapOutput(O,m,t),m)}for(;!J();){if(f=F(),f==="\0")continue;if(f==="\\"){let g=P();if(g==="/"&&n.bash!==true||g==="."||g===";")continue;if(!g){f+="\\",$({type:"text",value:f});continue}let R=/^\\+/.exec(st()),I=0;if(R&&R[0].length>2&&(I=R[0].length,m.index+=I,I%2!==0&&(f+="\\")),n.unescape===true?f=F():f+=F(),m.brackets===0){$({type:"text",value:f});continue}}if(m.brackets>0&&(f!=="]"||p.value==="["||p.value==="[^")){if(n.posix!==false&&f===":"){let g=p.value.slice(1);if(g.includes("[")&&(p.posix=true,g.includes(":"))){let R=p.value.lastIndexOf("["),I=p.value.slice(0,R),z=p.value.slice(R+2),M=Po[z];if(M){p.value=I+M,m.backtrack=true,F(),!s.output&&o.indexOf(p)===1&&(s.output=b);continue}}}(f==="["&&P()!==":"||f==="-"&&P()==="]")&&(f=`\\${f}`),f==="]"&&(p.value==="["||p.value==="[^")&&(f=`\\${f}`),n.posix===true&&f==="!"&&p.value==="["&&(f="^"),p.value+=f,ct({value:f});continue}if(m.quotes===1&&f!=='"'){f=it.escapeRegex(f),p.value+=f,ct({value:f});continue}if(f==='"'){m.quotes=m.quotes===1?0:1,n.keepQuotes===true&&$({type:"text",value:f});continue}if(f==="("){oe("parens"),$({type:"paren",value:f});continue}if(f===")"){if(m.parens===0&&n.strictBrackets===true)throw new SyntaxError(Tt("opening","("));let g=G[G.length-1];if(g&&m.parens===g.parens+1){gi(G.pop());continue}$({type:"paren",value:f,output:m.parens?")":"\\)"}),pt("parens");continue}if(f==="["){if(n.nobracket===true||!st().includes("]")){if(n.nobracket!==true&&n.strictBrackets===true)throw new SyntaxError(Tt("closing","]"));f=`\\${f}`;}else oe("brackets");$({type:"bracket",value:f});continue}if(f==="]"){if(n.nobracket===true||p&&p.type==="bracket"&&p.value.length===1){$({type:"text",value:f,output:`\\${f}`});continue}if(m.brackets===0){if(n.strictBrackets===true)throw new SyntaxError(Tt("opening","["));$({type:"text",value:f,output:`\\${f}`});continue}pt("brackets");let g=p.value.slice(1);if(p.posix!==true&&g[0]==="^"&&!g.includes("/")&&(f=`/${f}`),p.value+=f,ct({value:f}),n.literalBrackets===false||it.hasRegexChars(g))continue;let R=it.escapeRegex(p.value);if(m.output=m.output.slice(0,-p.value.length),n.literalBrackets===true){m.output+=R,p.value=R;continue}p.value=`(${a}${R}|${p.value})`,m.output+=p.value;continue}if(f==="{"&&n.nobrace!==true){oe("braces");let g={type:"brace",value:f,output:"(",outputIndex:m.output.length,tokensIndex:m.tokens.length};S.push(g),$(g);continue}if(f==="}"){let g=S[S.length-1];if(n.nobrace===true||!g){$({type:"text",value:f,output:f});continue}let R=")";if(g.dots===true){let I=o.slice(),z=[];for(let M=I.length-1;M>=0&&(o.pop(),I[M].type!=="brace");M--)I[M].type!=="dots"&&z.unshift(I[M].value);R=Fo(z,n),m.backtrack=true;}if(g.comma!==true&&g.dots!==true){let I=m.output.slice(0,g.outputIndex),z=m.tokens.slice(g.tokensIndex);g.value=g.output="\\{",f=R="\\}",m.output=I;for(let M of z)m.output+=M.output||M.value;}$({type:"brace",value:f,output:R}),pt("braces"),S.pop();continue}if(f==="|"){G.length>0&&G[G.length-1].conditions++,$({type:"text",value:f});continue}if(f===","){let g=f,R=S[S.length-1];R&&k[k.length-1]==="braces"&&(R.comma=true,g="|"),$({type:"comma",value:f,output:g});continue}if(f==="/"){if(p.type==="dot"&&m.index===m.start+1){m.start=m.index+1,m.consumed="",m.output="",o.pop(),p=s;continue}$({type:"slash",value:f,output:d});continue}if(f==="."){if(m.braces>0&&p.type==="dot"){p.value==="."&&(p.output=u);let g=S[S.length-1];p.type="dots",p.output+=f,p.value+=f,g.dots=true;continue}if(m.braces+m.parens===0&&p.type!=="bos"&&p.type!=="slash"){$({type:"text",value:f,output:u});continue}$({type:"dot",value:f,output:u});continue}if(f==="?"){if(!(p&&p.value==="(")&&n.noextglob!==true&&P()==="("&&P(2)!=="?"){ae("qmark",f);continue}if(p&&p.type==="paren"){let R=P(),I=f;(p.value==="("&&!/[!=<:]/.test(R)||R==="<"&&!/<([!=]|\w+>)/.test(st()))&&(I=`\\${f}`),$({type:"text",value:f,output:I});continue}if(n.dot!==true&&(p.type==="slash"||p.type==="bos")){$({type:"qmark",value:f,output:V});continue}$({type:"qmark",value:f,output:x});continue}if(f==="!"){if(n.noextglob!==true&&P()==="("&&(P(2)!=="?"||!/[!=<:]/.test(P(3)))){ae("negate",f);continue}if(n.nonegate!==true&&m.index===0){di();continue}}if(f==="+"){if(n.noextglob!==true&&P()==="("&&P(2)!=="?"){ae("plus",f);continue}if(p&&p.value==="("||n.regex===false){$({type:"plus",value:f,output:h});continue}if(p&&(p.type==="bracket"||p.type==="paren"||p.type==="brace")||m.parens>0){$({type:"plus",value:f});continue}$({type:"plus",value:h});continue}if(f==="@"){if(n.noextglob!==true&&P()==="("&&P(2)!=="?"){$({type:"at",extglob:true,value:f,output:""});continue}$({type:"text",value:f});continue}if(f!=="*"){(f==="$"||f==="^")&&(f=`\\${f}`);let g=Lo.exec(st());g&&(f+=g[0],m.index+=g[0].length),$({type:"text",value:f});continue}if(p&&(p.type==="globstar"||p.star===true)){p.type="star",p.star=true,p.value+=f,p.output=C,m.backtrack=true,m.globstar=true,Y(f);continue}let y=st();if(n.noextglob!==true&&/^\([^?]/.test(y)){ae("star",f);continue}if(p.type==="star"){if(n.noglobstar===true){Y(f);continue}let g=p.prev,R=g.prev,I=g.type==="slash"||g.type==="bos",z=R&&(R.type==="star"||R.type==="globstar");if(n.bash===true&&(!I||y[0]&&y[0]!=="/")){$({type:"star",value:f,output:""});continue}let M=m.braces>0&&(g.type==="comma"||g.type==="brace"),je=G.length&&(g.type==="pipe"||g.type==="paren");if(!I&&g.type!=="paren"&&!M&&!je){$({type:"star",value:f,output:""});continue}for(;y.slice(0,3)==="/**";){let le=e[m.index+4];if(le&&le!=="/")break;y=y.slice(3),Y("/**",3);}if(g.type==="bos"&&J()){p.type="globstar",p.value+=f,p.output=B(n),m.output=p.output,m.globstar=true,Y(f);continue}if(g.type==="slash"&&g.prev.type!=="bos"&&!z&&J()){m.output=m.output.slice(0,-(g.output+p.output).length),g.output=`(?:${g.output}`,p.type="globstar",p.output=B(n)+(n.strictSlashes?")":"|$)"),p.value+=f,m.globstar=true,m.output+=g.output+p.output,Y(f);continue}if(g.type==="slash"&&g.prev.type!=="bos"&&y[0]==="/"){let le=y[1]!==void 0?"|$":"";m.output=m.output.slice(0,-(g.output+p.output).length),g.output=`(?:${g.output}`,p.type="globstar",p.output=`${B(n)}${d}|${d}${le})`,p.value+=f,m.output+=g.output+p.output,m.globstar=true,Y(f+F()),$({type:"slash",value:"/",output:""});continue}if(g.type==="bos"&&y[0]==="/"){p.type="globstar",p.value+=f,p.output=`(?:^|${d}|${B(n)}${d})`,m.output=p.output,m.globstar=true,Y(f+F()),$({type:"slash",value:"/",output:""});continue}m.output=m.output.slice(0,-p.output.length),p.type="globstar",p.output=B(n),p.value+=f,m.output+=p.output,m.globstar=true,Y(f);continue}let O={type:"star",value:f,output:C};if(n.bash===true){O.output=".*?",(p.type==="bos"||p.type==="slash")&&(O.output=W+O.output),$(O);continue}if(p&&(p.type==="bracket"||p.type==="paren")&&n.regex===true){O.output=f,$(O);continue}(m.index===m.start||p.type==="slash"||p.type==="dot")&&(p.type==="dot"?(m.output+=_,p.output+=_):n.dot===true?(m.output+=v,p.output+=v):(m.output+=W,p.output+=W),P()!=="*"&&(m.output+=b,p.output+=b)),$(O);}for(;m.brackets>0;){if(n.strictBrackets===true)throw new SyntaxError(Tt("closing","]"));m.output=it.escapeLast(m.output,"["),pt("brackets");}for(;m.parens>0;){if(n.strictBrackets===true)throw new SyntaxError(Tt("closing",")"));m.output=it.escapeLast(m.output,"("),pt("parens");}for(;m.braces>0;){if(n.strictBrackets===true)throw new SyntaxError(Tt("closing","}"));m.output=it.escapeLast(m.output,"{"),pt("braces");}if(n.strictSlashes!==true&&(p.type==="star"||p.type==="bracket")&&$({type:"maybe_slash",value:"",output:`${d}?`}),m.backtrack===true){m.output="";for(let y of m.tokens)m.output+=y.output!=null?y.output:y.value,y.suffix&&(m.output+=y.suffix);}return m};cn.fastpaths=(e,t)=>{let n={...t},r=typeof n.maxLength=="number"?Math.min(ve,n.maxLength):ve,i=e.length;if(i>r)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${r}`);e=Sr[e]||e;let{DOT_LITERAL:s,SLASH_LITERAL:o,ONE_CHAR:a,DOTS_SLASH:l,NO_DOT:c,NO_DOTS:u,NO_DOTS_SLASH:h,STAR:d,START_ANCHOR:b}=$e.globChars(n.windows),w=n.dot?u:c,E=n.dot?h:c,_=n.capture?"":"?:",v={negated:false,prefix:""},x=n.bash===true?".*?":d;n.capture&&(x=`(${x})`);let V=W=>W.noglobstar===true?x:`(${_}(?:(?!${b}${W.dot?l:s}).)*?)`,Z=W=>{switch(W){case "*":return `${w}${a}${x}`;case ".*":return `${s}${a}${x}`;case "*.*":return `${w}${x}${s}${a}${x}`;case "*/*":return `${w}${x}${o}${a}${E}${x}`;case "**":return w+V(n);case "**/*":return `(?:${w}${V(n)}${o})?${E}${a}${x}`;case "**/*.*":return `(?:${w}${V(n)}${o})?${E}${x}${s}${a}${x}`;case "**/.*":return `(?:${w}${V(n)}${o})?${s}${a}${x}`;default:{let T=/^(.*?)\.(\w+)$/.exec(W);if(!T)return;let C=Z(T[1]);return C?C+s+T[2]:void 0}}},H=it.removePrefix(e,v),B=Z(H);return B&&n.strictSlashes!==true&&(B+=`${o}?`),B};Er.exports=cn;});var Cr=mt((Gu,_r)=>{var Io=xr(),un=Tr(),Ar=Dt(),jo=jt(),Do=e=>e&&typeof e=="object"&&!Array.isArray(e),D=(e,t,n=false)=>{if(Array.isArray(e)){let u=e.map(d=>D(d,t,n));return d=>{for(let b of u){let w=b(d);if(w)return w}return false}}let r=Do(e)&&e.tokens&&e.input;if(e===""||typeof e!="string"&&!r)throw new TypeError("Expected pattern to be a non-empty string");let i=t||{},s=i.windows,o=r?D.compileRe(e,t):D.makeRe(e,t,false,true),a=o.state;delete o.state;let l=()=>false;if(i.ignore){let u={...t,ignore:null,onMatch:null,onResult:null};l=D(i.ignore,u,n);}let c=(u,h=false)=>{let{isMatch:d,match:b,output:w}=D.test(u,o,t,{glob:e,posix:s}),E={glob:e,state:a,regex:o,posix:s,input:u,output:w,match:b,isMatch:d};return typeof i.onResult=="function"&&i.onResult(E),d===false?(E.isMatch=false,h?E:false):l(u)?(typeof i.onIgnore=="function"&&i.onIgnore(E),E.isMatch=false,h?E:false):(typeof i.onMatch=="function"&&i.onMatch(E),h?E:true)};return n&&(c.state=a),c};D.test=(e,t,n,{glob:r,posix:i}={})=>{if(typeof e!="string")throw new TypeError("Expected input to be a string");if(e==="")return {isMatch:false,output:""};let s=n||{},o=s.format||(i?Ar.toPosixSlashes:null),a=e===r,l=a&&o?o(e):e;return a===false&&(l=o?o(e):e,a=l===r),(a===false||s.capture===true)&&(s.matchBase===true||s.basename===true?a=D.matchBase(e,t,n,i):a=t.exec(l)),{isMatch:!!a,match:a,output:l}};D.matchBase=(e,t,n)=>(t instanceof RegExp?t:D.makeRe(t,n)).test(Ar.basename(e));D.isMatch=(e,t,n)=>D(t,n)(e);D.parse=(e,t)=>Array.isArray(e)?e.map(n=>D.parse(n,t)):un(e,{...t,fastpaths:false});D.scan=(e,t)=>Io(e,t);D.compileRe=(e,t,n=false,r=false)=>{if(n===true)return e.output;let i=t||{},s=i.contains?"":"^",o=i.contains?"":"$",a=`${s}(?:${e.output})${o}`;e&&e.negated===true&&(a=`^(?!${a}).*$`);let l=D.toRegex(a,t);return r===true&&(l.state=e),l};D.makeRe=(e,t={},n=false,r=false)=>{if(!e||typeof e!="string")throw new TypeError("Expected a non-empty string");let i={negated:false,fastpaths:true};return t.fastpaths!==false&&(e[0]==="."||e[0]==="*")&&(i.output=un.fastpaths(e,t)),i.output||(i=un(e,t)),D.compileRe(i,t,n,r)};D.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 /$^/}};D.constants=jo;_r.exports=D;});var Nr=mt((Vu,vr)=>{var Rr=Cr(),Uo=Dt();function $r(e,t,n=false){return t&&(t.windows===null||t.windows===void 0)&&(t={...t,windows:Uo.isWindows()}),Rr(e,t,n)}Object.assign($r,Rr);vr.exports=$r;});function Ht(e){if("String"in e)return e.String.sval}function yt(e){return e.map(Ht).filter(t=>t!=null)}function Ir(e){return Object.keys(e)[0]}function jr(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 ke=L(()=>{});function Dr(e){let t=e.toLowerCase();return ["serial","serial4","bigserial","serial8","smallserial","serial2"].includes(t)}function Ur(e){let t=e.toLowerCase();return ["varchar","character varying","char","character","bpchar"].includes(t)}function Br(e){let t=e.toLowerCase();return ["numeric","decimal"].includes(t)}var mn,Pe,ca,hn=L(()=>{ke();mn=class extends Error{},Pe=class extends mn{constructor(n,r){super(r??`Unsupported node type: ${Ir(n)}`);this.node=n;}};ca={CreateEnumStmt:{react:"ignore"},CreateDomainStmt:{react:"warn"},CreateSeqStmt:{react:"error"},AlterSeqStmt:{react:"error"},CreateSchemaStmt:{react:"warn"},CreatePolicyStmt:{react:"ignore"},PartitionElem:{react:"error"},PartitionCmd:{react:"error"},VariableSetStmt:{react:"ignore"},CompositeTypeStmt:{react:"error"},AlterEnumStmt:{react:"error"},AlterObjectSchemaStmt:{react:"error"},AlterOwnerStmt:{react:"error"},AlterTypeStmt:{react:"error"},AlterFunctionStmt:{react:"error"},AlterDefaultPrivilegesStmt:{react:"error"},GrantStmt:{react:"error"},GrantRoleStmt:{react:"error"},CopyStmt:{react:"error"},CreateCastStmt:{react:"error"},AlterOpFamilyStmt:{react:"error"},AlterOperatorStmt:{react:"error"},TruncateStmt:{react:"error"},A_Indirection:{react:"error"},XmlExpr:{react:"error"},XmlSerialize:{react:"error"},RangeTableSample:{react:"error"},GroupingSet:{react:"error"}},new Map(Object.entries(ca));});var Q,Le,Mr=L(()=>{ke();hn();Q=class extends Pe{constructor(t,n){super(t,`Unsupported expression: ${n}`);}},Le=class{deparse(t){if("A_Const"in t){let i=t.A_Const;if(i.boolval!==void 0)return i.boolval.boolval?{}:{$always:false}}let n=Object.keys(t)[0],r=this[n];if(!r)throw new Q({[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 Q({[n]:t},`deparseValue: ${n}`)}A_Expr(t){if(t.kind==="AEXPR_OP"){let n=t.name?.[0],r=n?Ht(n):void 0;if(!r)throw new Q({A_Expr:t},"A_Expr missing operator");let i=this.isJwtAccessor(t);if(i)return {[i]:{}};let s=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 Q({A_Expr:t},`Unsupported operator: ${r}`);let l=t.rexpr!=null&&"ColumnRef"in t.rexpr;if(typeof s=="string"&&s.startsWith("{{")&&l)return {[o]:{[a]:s}};let c=l&&typeof o=="string"?{$ref:o}:o;return {[s]:{[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.name?.[0]?Ht(t.name[0]):"~~")==="!~~"?"$notLike":"$like";return {[n]:{[s]: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(i=>this.deparseValue(i)):[];return {[n]:{$in:r}}}throw new Q({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 Q({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],i="ResTarget"in r?r.ResTarget:void 0;if(i?.val){let s=this.deparseValue(i.val);return s}}}throw new Q({SubLink:t},`SubLink type: ${t.subLinkType}`)}SelectStmt(t){let{from:n,schema:r,join:i}=this.deparseFromClause(t.fromClause??[]),s=[];for(let d of t.targetList??[]){let b="ResTarget"in d?d.ResTarget:void 0;if(b?.val){let w=this.deparseValue(b.val);Array.isArray(w)?s.push(...w.map(String)):w!=null&&w!==""&&s.push(String(w));}}let o=t.whereClause?this.deparse(t.whereClause):void 0,a=this.deparseSortClause(t.sortClause),l=this.deparseLimit(t.limitCount),c=this.deparseLimit(t.limitOffset),u=this.deparseGroupClause(t.groupClause),h={type:"query",from:n,select:s};return r&&(h.schema=r),Object.keys(i).length>0&&(h.join=i),o&&(h.where=o),a.length>0&&(h.order=a),l!==void 0&&(h.limit=l),c!==void 0&&(h.offset=c),u.length>0&&(h.group=u),h}FuncCall(t){let n=this.isAuthFunc(t.funcname??[]);if(n)return n;throw new Q({FuncCall:t},`FuncCall: ${yt(t.funcname??[]).join(".")}`)}ColumnRef(t){let n=yt(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 Q({A_Const:t},"A_Const: unknown variant")}TypeCast(t){if(!t.arg)throw new Q({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 i=r.RangeVar;return {from:i.relname??"",schema:i.schemaname,join:n}}if("JoinExpr"in r){let{from:i,schema:s}=this.walkJoinExpr(r.JoinExpr,n);return {from:i,schema:s,join:n}}return {from:"",join:n}}walkJoinExpr(t,n){let r={from:""};if(t.larg)if("RangeVar"in t.larg){let i=t.larg.RangeVar;r={from:i.relname??"",schema:i.schemaname};}else "JoinExpr"in t.larg&&(r=this.walkJoinExpr(t.larg.JoinExpr,n));if(t.rarg&&"RangeVar"in t.rarg){let i=t.rarg.RangeVar,s=i.relname??"",o=i.alias?.aliasname??s,a=t.jointype==="JOIN_LEFT"?"left":"inner",l={from:s,type:a};t.quals&&(l.on=this.deparse(t.quals));let c=o;if(c in n){let u=2;for(;`${c}_${u}`in n;)u++;c=`${c}_${u}`;}n[c]=l;}return r}deparseSortClause(t){if(!t)return [];let n=[];for(let r of t){if(!("SortBy"in r))continue;let i=r.SortBy;if(!i.node)continue;let s=String(this.deparseValue(i.node)),o=i.sortby_dir==="SORTBY_DESC"?"desc":"asc",a={column:s,direction:o};i.sortby_nulls==="SORTBY_NULLS_FIRST"?a.nullsFirst=true:i.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=yt(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]?Ht(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 i=this.isJwtAccessor(t.lexpr.A_Expr);if(i)return `${i.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 Oe,Hr=L(()=>{Oe=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 qt,dn=L(()=>{qt=class extends Error{constructor(n,r,i,s){super(`check constraint "${i}" violated for ${n}.${r}`);this.table=n;this.column=r;this.constraint=i;this.value=s;this.name="CheckConstraintError";}};});var q,lt=L(()=>{dn();q=class{context;constructor(t){this.context=t;}get isShimBacked(){return false}checkConstraint(){return null}serialize(t){return t}deserialize(t){return t}validateStorage(t){return {status:"pass",message:null}}validationFail(t,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=[],i=this.context.column;r.push(this.quoteIfNeeded(i)),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 s=this.checkConstraint();return s&&r.push(`CHECK (${s})`),r.join(" ")}checkError(t,n){return new qt(this.context.table,this.context.column,t,n)}quoteIfNeeded(t){return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)?t:`"${t}"`}};});var bt,Fe=L(()=>{lt();bt=class extends q{get sqliteType(){return "INTEGER"}};});var Gt,gn=L(()=>{Fe();Gt=class extends bt{constructor(t){super({...t,isSerial:true});}};});function ua(e,t){let{precision:n,scale:r}=t,i=10**r,s=10**(n-r);return Math.abs(Math.round(e*i)-e*i)<1e-4&&Math.abs(e)<s}var Vt,yn=L(()=>{lt();Vt=class extends q{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,i=10**n,s=10**(t-n);return `ABS(ROUND(${r} * ${i}) - ${r} * ${i}) < 0.0001 AND ABS(${r}) < ${s}`}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(!ua(t,this.numericPrecision))return this.validationFail(`Does not fit numeric(${n}, ${r}).`,"Patch rows within numeric precision.")}return this.validationPass()}};});var j,et=L(()=>{lt();j=class extends q{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 Wt,bn=L(()=>{lt();Wt=class extends q{get sqliteType(){return "BLOB"}};});var zt,wn=L(()=>{lt();zt=class extends q{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}checkConstraint(){return `${this.context.column} IN (0, 1)`}serialize(t){if(this.isNullish(t))return t;if(t===true||t===1)return 1;if(t===false||t===0)return 0;throw this.checkError("boolean_range",t)}deserialize(t){return this.isNullish(t)?t:t===1?true:t===0?false:t}validateStorage(t){return this.isNullish(t)?this.validationPass():t===1||t===0?this.validationPass():this.validationFail("Expected 0 or 1.","Patch rows with boolean values.")}};});function qr(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var Kt,xn=L(()=>{lt();Kt=class extends q{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=qr(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."):qr(t).ok?this.validationPass():this.validationFail("Invalid JSON text.","Patch rows with valid JSON.")}};});function fa(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 Xt,Sn=L(()=>{et();Xt=class extends j{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"||!fa(t)?this.validationFail("Invalid date.","Patch rows with YYYY-MM-DD dates."):this.validationPass()}};});function pa(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]),i=t[3]===void 0?0:Number(t[3]),s=t[5]===void 0?null:Number(t[5]),o=t[6]===void 0?null:Number(t[6]),a=s===null||o!==null&&s<=15&&o<=59;return n<=24&&r<=59&&i<=59&&(n!==24||r===0&&i===0)&&a}var Jt,En=L(()=>{et();Jt=class extends j{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"||!pa(t)?this.validationFail("Invalid time.","Patch rows with HH:MM[:SS] times."):this.validationPass()}};});function ma(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]),i=Number(t[3]),s=Number(t[4]),o=Number(t[5]),a=t[6]===void 0?0:Number(t[6]),l=t[8]===void 0?null:Number(t[8]),c=t[9]===void 0?null:Number(t[9]),u=new Date(Date.UTC(n,r-1,i)),h=u.getUTCFullYear()===n&&u.getUTCMonth()===r-1&&u.getUTCDate()===i,d=s<=24&&o<=59&&a<=59&&(s!==24||o===0&&a===0),b=l===null||c!==null&&l<=15&&c<=59;return h&&d&&b}var Yt,Tn=L(()=>{et();Yt=class extends j{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"||!ma(t)?this.validationFail("Invalid timestamp.","Patch rows with ISO timestamps."):this.validationPass()}};});var Qt,An=L(()=>{et();Qt=class extends j{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 Zt,_n=L(()=>{et();Zt=class extends j{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 Gr(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var Rt,Cn=L(()=>{lt();Rt=class extends q{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=Gr(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=Gr(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 i=this.elementField.validateStorage(r);if(i.status==="fail")return this.validationFail(`Invalid ${this.elementField.context.pgTypeName} array element.`,i.action??"Patch rows with valid array elements.")}return this.validationPass()}};});function Vr(e){return da.test(e.toLowerCase())}var ha,da,te,Rn=L(()=>{et();ha="????????-????-????-????-????????????",da=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;te=class extends j{get isShimBacked(){return true}checkConstraint(){let t=this.quoteIfNeeded(this.context.column);return `${t} IS NULL OR ${t} GLOB '${ha}'`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string")throw this.checkError("uuid_format",t);let n=t.toLowerCase();if(!Vr(n))throw this.checkError("uuid_format",t);return n}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!Vr(t)?this.validationFail("Invalid UUID.","Patch rows with valid UUIDs."):this.validationPass()}};});function ga(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 ya(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 ba(e){if(!e.includes(":"))return false;try{return new URL(`http://[${e}]/`),!0}catch{return false}}function Wr(e){let t=ga(e);return t?ya(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=32:ba(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=128:false:false}var ee,$n=L(()=>{et();ee=class extends j{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(!Wr(n))throw this.checkError("inet_format",t);return n}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!Wr(t.trim())?this.validationFail("Invalid inet address.","Patch rows with valid inet strings."):this.validationPass()}};});var ne,vn=L(()=>{et();ne=class extends j{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 re(e,t){if(t?.isArray){let r=re(e,{...t,isArray:false});return new Rt(e,r)}if(t?.enumValues)return new Zt(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),i={...e,pgTypeName:r},s=re(i);return new Rt(e,s)}return xa.has(n)?new Gt(e):wa.has(n)?new bt(e):Aa.has(n)?new zt(e):_a.has(n)?new Kt(e):va.has(n)?new Xt(e):Na.has(n)?new Jt(e):ka.has(n)?new Yt(e):Pa.has(n)?new Qt(e):Ta.has(n)?new Wt(e):Sa.has(n)?new Vt(e,t?.numericPrecision):Ca.has(n)?new te(e):Ra.has(n)?new j(e,63):$a.has(n)?new ee(e):Ea.has(n)?new j(e,t?.lengthConstraint):new ne(e)}var wa,xa,Sa,Ea,Ta,Aa,_a,Ca,Ra,$a,va,Na,ka,Pa,zr=L(()=>{Fe();gn();yn();et();bn();wn();xn();Sn();En();Tn();An();_n();Cn();Rn();$n();vn();wa=new Set(["int2","smallint","int4","integer","int","int8","bigint"]),xa=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]),Sa=new Set(["float4","real","float8","double precision","numeric","decimal"]),Ea=new Set(["text","varchar","character varying","char","character","bpchar"]),Ta=new Set(["bytea"]),Aa=new Set(["bool","boolean"]),_a=new Set(["json","jsonb"]),Ca=new Set(["uuid"]),Ra=new Set(["name"]),$a=new Set(["inet"]),va=new Set(["date"]),Na=new Set(["time","timetz","time without time zone","time with time zone"]),ka=new Set(["timestamp","timestamptz","timestamp without time zone","timestamp with time zone"]),Pa=new Set(["interval"]);});var Kr=L(()=>{});var ie,Xr=L(()=>{ie=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,i]of Object.entries(t)){let s=this.fields.get(r);n[r]=s?s.serialize(i):i;}return n}deserializeRow(t){let n={};for(let[r,i]of Object.entries(t)){let s=this.fields.get(r);n[r]=s?s.deserialize(i):i;}return n}applyDefaults(t){let n={...t};for(let[r,i]of this.fields)!(r in n)&&i.context.defaultFn&&(n[r]=i.context.defaultFn());return n}};});var Jr=L(()=>{lt();dn();Fe();gn();yn();et();bn();wn();xn();Sn();En();Tn();An();_n();Cn();Rn();$n();vn();zr();Kr();Xr();});var Yr={};Ei(Yr,{_resetWarnedMissingToClauseForTests:()=>La,collectComments:()=>Ua,collectEnums:()=>Oa,collectPolicies:()=>Ia,collectSchema:()=>ja,collectTableConstraints:()=>Da,collectVariables:()=>Fa});function La(){Nn.clear();}function Oa(e){let t=new Map;for(let n of e.stmts??[]){if(!n.stmt||!("CreateEnumStmt"in n.stmt))continue;let r=n.stmt.CreateEnumStmt,i=yt(r.typeName??[]).join(".");if(!i||!r.vals)continue;let s=yt(r.vals);t.set(i.toLowerCase(),s);}return t}function Fa(e){let t=new Map;for(let n of e.stmts??[]){if(!n.stmt||!("VariableSetStmt"in n.stmt))continue;let r=n.stmt.VariableSetStmt,i=r.name,s=jr(r.args?.[0]??{});t.set(i,{value:s,local:r.is_local});}return t}function Ia(e){let t=new Le,n=new Set,r=[];for(let i of e.stmts??[])if(i.stmt){if("CreatePolicyStmt"in i.stmt){let s=i.stmt.CreatePolicyStmt,o=s.table?.relname??"",a=s.table?.schemaname,l={select:"SELECT",insert:"INSERT",update:"UPDATE",delete:"DELETE"},c=s.cmd_name?l[s.cmd_name]??"ALL":"ALL",u=s.permissive===true,h=[],d=false;for(let _ of s.roles??[])if("RoleSpec"in _){let v=_.RoleSpec;v.roletype==="ROLESPEC_PUBLIC"?v.location===-1&&(d=true):v.roletype==="ROLESPEC_CSTRING"&&v.rolename&&h.push(v.rolename);}if(d){let _=a?`${a}.${o}`:o,v=s.policy_name??"",x=`${_}::${v}`;Nn.has(x)||(Nn.add(x),console.warn(`[supalite] policy "${v}" on "${_}" has no TO clause \u2014 applies to all roles (PUBLIC). For clarity, prefer an explicit \`TO <role>\` clause (e.g. \`TO authenticated\`).`));}let b=s.qual?t.deparse(s.qual):void 0,w=s.with_check?t.deparse(s.with_check):void 0,E=new Oe({name:s.policy_name??"",table:o,schema:a,command:c,permissive:u,roles:h,using:b,withCheck:w});r.push(E);}if("AlterTableStmt"in i.stmt){let s=i.stmt.AlterTableStmt;if((s.cmds??[]).some(l=>"AlterTableCmd"in l&&(l.AlterTableCmd.subtype==="AT_EnableRowSecurity"||l.AlterTableCmd.subtype==="AT_ForceRowSecurity"))){let l=s.relation?.relname??"";n.add(l);}}}return {policies:r,tables:n}}function ja(e,t){let n=new Map;for(let r of e.stmts??[]){if(!r.stmt||!("CreateStmt"in r.stmt))continue;let i=r.stmt.CreateStmt,s=i.relation?.relname??"",o=i.relation?.schemaname??"public";if(!s)continue;let a=new ie(s,o);for(let l of i.tableElts??[]){if(!("ColumnDef"in l))continue;let c=l.ColumnDef,u=c.colname;if(!u)continue;let h=c.typeName?.names?.map(S=>S.String?.sval||S.String?.str).filter(Boolean),d=h&&(h.length===2&&h[0]==="pg_catalog"?h[1]:h[0]);if(!d)continue;let b=!!c.typeName?.arrayBounds?.length,w=Array.isArray(c.typeName?.typmods)?c.typeName.typmods:[],E=S=>w[S]?.A_Const?.ival?.ival??w[S]?.A_Const?.val?.ival?.ival,_={isArray:b};if(Ur(d)&&w.length>0){let S=E(0);typeof S=="number"&&S>0&&(_.lengthConstraint=S);}if(Br(d)&&w.length>=2){let S=E(0),k=E(1);typeof S=="number"&&typeof k=="number"&&S>0&&k>=0&&(_.numericPrecision={precision:S,scale:k});}let v=t.get(d.toLowerCase());v&&(_.enumValues=v);let x=Array.isArray(c.constraints)?c.constraints:[],V=x.some(S=>S.Constraint?.contype==="CONSTR_PRIMARY"),Z=Dr(d)||x.some(S=>S.Constraint?.contype==="CONSTR_IDENTITY"),H=x.some(S=>S.Constraint?.contype==="CONSTR_NOTNULL"),B=x.find(S=>S.Constraint?.contype==="CONSTR_UNIQUE"),W=x.find(S=>S.Constraint?.contype==="CONSTR_GENERATED"),T=x.find(S=>S.Constraint?.contype==="CONSTR_FOREIGN"),C=x.find(S=>S.Constraint?.contype==="CONSTR_CHECK"),m;if(T){let S=T.Constraint,k=S.pktable?.relname,p=S.pktable?.schemaname,f=S.pk_attrs?.[0]?.String?.sval;k&&f&&(m={refSchema:p,refTable:k,refColumn:f,constraintName:S.conname||void 0});}let G={schema:o,table:s,column:u,pgTypeName:d,nullable:!H&&!V,defaultValue:null,defaultFn:null,isPrimaryKey:V,isUnique:!!B,isSerial:Z,isGenerated:!!W,fkRef:m,hasCheck:!!C,checkConstraintName:C?.Constraint?.conname||void 0,uniqueConstraintName:B?.Constraint?.conname||void 0};a.set(u,re(G,_));}n.set(`${o}.${s}`,a);}return n}function Da(e){let t=[];for(let n of e.stmts??[]){if(!n.stmt||!("CreateStmt"in n.stmt))continue;let r=n.stmt.CreateStmt,i=r.relation?.relname??"",s=r.relation?.schemaname??"public";if(i)for(let o of r.tableElts??[]){if("ColumnDef"in o)continue;let a=o;if(!a.Constraint)continue;let l=a.Constraint,c=l.contype;if(c==="CONSTR_UNIQUE"){let u=(l.keys??[]).map(h=>h.String?.sval??h.String?.str).filter(Boolean);if(u.length===0)continue;t.push({schema:s,table:i,kind:"unique",name:l.conname||void 0,columns:u});}else if(c==="CONSTR_CHECK")t.push({schema:s,table:i,kind:"check",name:l.conname||void 0,columns:[]});else if(c==="CONSTR_FOREIGN"){let u=(l.fk_attrs??[]).map(b=>b.String?.sval??b.String?.str).filter(Boolean),h=(l.pk_attrs??[]).map(b=>b.String?.sval??b.String?.str).filter(Boolean),d=l.pktable?.relname;if(!d)continue;t.push({schema:s,table:i,kind:"foreign_key",name:l.conname||void 0,columns:u,refSchema:l.pktable?.schemaname,refTable:d,refColumns:h});}}}return t}function Ua(e){let t=[];for(let n of e.stmts??[]){if(!n.stmt||!("CommentStmt"in n.stmt))continue;let r=n.stmt.CommentStmt,i=r.comment??"";if(!i)continue;let s=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(s==="OBJECT_TABLE"||s==="OBJECT_VIEW"){let[a,l]=o.length>=2?o:["public",o[0]];t.push({schema:a,table:l,text:i});}else if(s==="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:i});}}}return t}var Nn,Qr=L(()=>{Mr();ke();Hr();Jr();hn();Nn=new Set;});function tt(e,t){ce.existsSync(e)||(ce.mkdirSync(e,{recursive:true}),t?.());}function ht(e,t,n){ce.existsSync(e)||(ce.writeFileSync(e,t),n?.());}var at=class e{root;constructor(t,n){let r=n??e.projectDir();this.root=rt__default.join(r,t??"");}ensureRoot(){tt(this.root);}static homeDir(){return rt__default.join(Ai.homedir(),".lite")}static projectDir(){return rt__default.join(process.cwd(),"supabase")}deleteAll(t=false){try{ce.rmSync(this.root,{recursive:!0});}catch(n){if(!t)throw n}this.ensureRoot();}delete(t,n=false){try{ce.unlinkSync(rt__default.join(this.root,t));}catch(r){if(!n)throw r}}write(t,n,r=false){try{this.ensureRoot(),ce.writeFileSync(rt__default.join(this.root,t),n);}catch(i){if(!r)throw i}}read(t,n=false){try{return ce.readFileSync(rt__default.join(this.root,t),"utf8")}catch(r){if(!n)throw r}}relativePath(t){return t?rt__default.relative(process.cwd(),rt__default.join(this.root,t)):this.root}path(t){return t?rt__default.join(this.root,t):this.root}};var vt=process.env.SUPALITE_CLOUD_URL??(process.env.LOCAL?"http://localhost:2000":"https://www.lite.dev");var pe=class{root;constructor(t){this.root=t??rt__default.join(Ai.homedir(),".lite","auth"),tt(this.root);}async getItem(t){try{return ce.readFileSync(rt__default.join(this.root,t+".json"),"utf8")}catch{return null}}async setItem(t,n){ce.writeFileSync(rt__default.join(this.root,t+".json"),n);}async removeItem(t){try{ce.unlinkSync(rt__default.join(this.root,t+".json"));}catch{return}}};var xt=class{constructor(t){this.config=t;this.tempFs=new at(".temp",this.config.root),this.projectFs=new at("supabase",this.config.root),this.schemaFs=new at("schemas",this.config.root),this.authStorage=this.config.authStorage??new pe(rt__default.join(at.homeDir(),"auth")),this._client=this.config.withSupabaseClient!==false?this.config.client??createClient(this.config.host??vt,process.env.SUPALITE_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??vt);return await fetch(r,{...n,headers:{...n?.headers,Authorization:`Bearer ${this.config.token}`}})}};var St=class extends xt{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.host),i=r.hostname==="localhost"?"supalite.local":r.hostname,s=i.split(".").filter(a=>a!=="www"),o=s.length>=2?s.slice(-2).join("."):i;return `${r.protocol}//${n}.${o}${r.port?`:${r.port}`:""}`}};var ut={config_dir:"supabase",default_db_url:"file:supabase/.temp/data.db",default_db_dir:"supabase/.temp/data"};var It=$t(Nt());function ki(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return [n.length,n.pop().length+1]}function Pi(e,t,n){let r=e.split(/\r\n|\n|\r/g),i="",s=(Math.log10(t+1)|0)+1;for(let o=t-1;o<=t+1;o++){let a=r[o-1];a&&(i+=o.toString().padEnd(s," "),i+=": ",i+=a,i+=`
|
|
13
13
|
`,o===t&&(i+=" ".repeat(s+n+2),i+=`^
|
|
14
|
-
`));}return i}var
|
|
14
|
+
`));}return i}var A=class extends Error{line;column;codeblock;constructor(t,n){let[r,i]=ki(n.toml,n.ptr),s=Pi(n.toml,r,i);super(`Invalid TOML document: ${t}
|
|
15
15
|
|
|
16
|
-
${s}`,n),this.line=r,this.column=i,this.codeblock=s;}};function
|
|
17
|
-
`,t);return e[r-1]==="\r"&&r--,r<=n?r:-1}function
|
|
16
|
+
${s}`,n),this.line=r,this.column=i,this.codeblock=s;}};function Li(e,t){let n=0;for(;e[t-++n]==="\\";);return --n&&n%2}function de(e,t=0,n=e.length){let r=e.indexOf(`
|
|
17
|
+
`,t);return e[r-1]==="\r"&&r--,r<=n?r:-1}function Et(e,t){for(let n=t;n<e.length;n++){let r=e[n];if(r===`
|
|
18
18
|
`)return n;if(r==="\r"&&e[n+1]===`
|
|
19
|
-
`)return n+1;if(r<" "&&r!==" "||r==="\x7F")throw new
|
|
19
|
+
`)return n+1;if(r<" "&&r!==" "||r==="\x7F")throw new A("control characters are not allowed in comments",{toml:e,ptr:t})}return e.length}function K(e,t,n,r){let i;for(;(i=e[t])===" "||i===" "||!n&&(i===`
|
|
20
20
|
`||i==="\r"&&e[t+1]===`
|
|
21
|
-
`);)t++;return r||i!=="#"?t:K(e,
|
|
21
|
+
`);)t++;return r||i!=="#"?t:K(e,Et(e,t),n)}function Dn(e,t,n,r,i=false){if(!r)return t=de(e,t),t<0?e.length:t;for(let s=t;s<e.length;s++){let o=e[s];if(o==="#")s=de(e,s);else {if(o===n)return s+1;if(o===r||i&&(o===`
|
|
22
22
|
`||o==="\r"&&e[s+1]===`
|
|
23
|
-
`))return s}}throw new
|
|
24
|
-
`,f:"\f",r:"\r",e:"\x1B",'"':'"',"\\":"\\"};function
|
|
23
|
+
`))return s}}throw new A("cannot find end of structure",{toml:e,ptr:t})}function ge(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!=="'"&&Li(e,t));return t>-1&&(t+=r.length,r.length>1&&(e[t]===n&&t++,e[t]===n&&t++)),t}var Oi=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,kt=class e extends Date{#e=false;#n=false;#t=null;constructor(t){let n=true,r=true,i="Z";if(typeof t=="string"){let s=t.match(Oi);s?(s[1]||(n=false,t=`0000-01-01T${t}`),r=!!s[2],r&&t[10]===" "&&(t=t.replace(" ","T")),s[2]&&+s[2]>23?t="":(i=s[3]||null,t=t.toUpperCase(),!i&&r&&(t+="Z"))):t="";}super(t),isNaN(this.getTime())||(this.#e=n,this.#n=r,this.#t=i);}isDateTime(){return this.#e&&this.#n}isLocal(){return !this.#e||!this.#n||!this.#t}isDate(){return this.#e&&!this.#n}isTime(){return this.#n&&!this.#e}isValid(){return this.#e||this.#n}toISOString(){let t=super.toISOString();if(this.isDate())return t.slice(0,10);if(this.isTime())return t.slice(11,23);if(this.#t===null)return t.slice(0,-1);if(this.#t==="Z")return t;let n=+this.#t.slice(1,3)*60+ +this.#t.slice(4,6);return n=this.#t[0]==="-"?n:-n,new Date(this.getTime()-n*6e4).toISOString().slice(0,-1)+this.#t}static wrapAsOffsetDateTime(t,n="Z"){let r=new e(t);return r.#t=n,r}static wrapAsLocalDateTime(t){let n=new e(t);return n.#t=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#n=false,n.#t=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#e=false,n.#t=null,n}};var Fi=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,Ii=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,ji=/^[+-]?0[0-9_]/,Di=/^[0-9a-f]{2,8}$/i,Un={b:"\b",t:" ",n:`
|
|
24
|
+
`,f:"\f",r:"\r",e:"\x1B",'"':'"',"\\":"\\"};function ye(e,t=0,n=e.length){let r=e[t]==="'",i=e[t++]===e[t]&&e[t]===e[t+1];i&&(n-=2,e[t+=2]==="\r"&&t++,e[t]===`
|
|
25
25
|
`&&t++);let s=0,o,a="",l=t;for(;t<n-1;){let c=e[t++];if(c===`
|
|
26
26
|
`||c==="\r"&&e[t]===`
|
|
27
|
-
`){if(!i)throw new
|
|
27
|
+
`){if(!i)throw new A("newlines are not allowed in strings",{toml:e,ptr:t-1})}else if(c<" "&&c!==" "||c==="\x7F")throw new A("control characters are not allowed in strings",{toml:e,ptr:t-1});if(o){if(o=false,c==="x"||c==="u"||c==="U"){let u=e.slice(t,t+=c==="x"?2:c==="u"?4:8);if(!Di.test(u))throw new A("invalid unicode escape",{toml:e,ptr:s});try{a+=String.fromCodePoint(parseInt(u,16));}catch{throw new A("invalid unicode escape",{toml:e,ptr:s})}}else if(i&&(c===`
|
|
28
28
|
`||c===" "||c===" "||c==="\r")){if(t=K(e,t-1,true),e[t]!==`
|
|
29
|
-
`&&e[t]!=="\r")throw new
|
|
30
|
-
`&&e[o]!=="\r")throw new
|
|
31
|
-
`&&o!=="\r"){let a,l=i,c=false,[u,h]=
|
|
32
|
-
`&&s!=="\r"){let o=
|
|
33
|
-
`&&e[a]!=="\r")throw new
|
|
29
|
+
`&&e[t]!=="\r")throw new A("invalid escape: only line-ending whitespace may be escaped",{toml:e,ptr:s});t=K(e,t);}else if(c in Un)a+=Un[c];else throw new A("unrecognized escape sequence",{toml:e,ptr:s});l=t;}else !r&&c==="\\"&&(s=t-1,o=true,a+=e.slice(l,s));}return a+e.slice(l,n-1)}function Bn(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 i=Fi.test(e);if(i||Ii.test(e)){if(ji.test(e))throw new A("leading zeroes are not allowed",{toml:t,ptr:n});e=e.replace(/_/g,"");let o=+e;if(isNaN(o))throw new A("invalid number",{toml:t,ptr:n});if(i){if((i=!Number.isSafeInteger(o))&&!r)throw new A("integer value cannot be represented losslessly",{toml:t,ptr:n});(i||r===true)&&(o=BigInt(e));}return o}let s=new kt(e);if(!s.isValid())throw new A("invalid value",{toml:t,ptr:n});return s}function Ui(e,t,n){let r=e.slice(t,n),i=r.indexOf("#");return i>-1&&(Et(e,i),r=r.slice(0,i)),[r.trimEnd(),i]}function Pt(e,t,n,r,i){if(r===0)throw new A("document contains excessively nested structures. aborting.",{toml:e,ptr:t});let s=e[t];if(s==="["||s==="{"){let[l,c]=s==="["?Hn(e,t,r,i):Mn(e,t,r,i);if(n){if(c=K(e,c),e[c]===",")c++;else if(e[c]!==n)throw new A("expected comma or end of structure",{toml:e,ptr:c})}return [l,c]}let o;if(s==='"'||s==="'"){o=ge(e,t);let l=ye(e,t,o);if(n){if(o=K(e,o),e[o]&&e[o]!==","&&e[o]!==n&&e[o]!==`
|
|
30
|
+
`&&e[o]!=="\r")throw new A("unexpected character encountered",{toml:e,ptr:o});o+=+(e[o]===",");}return [l,o]}o=Dn(e,t,",",n);let a=Ui(e,t,o-+(e[o-1]===","));if(!a[0])throw new A("incomplete key-value declaration: no value specified",{toml:e,ptr:t});return n&&a[1]>-1&&(o=K(e,t+a[1]),o+=+(e[o]===",")),[Bn(a[0],e,t,i),o]}var Bi=/^[a-zA-Z0-9-_]+[ \t]*$/;function be(e,t,n="="){let r=t-1,i=[],s=e.indexOf(n,t);if(s<0)throw new A("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 A("multiline strings are not allowed in keys",{toml:e,ptr:t});let a=ge(e,t);if(a<0)throw new A("unfinished string encountered",{toml:e,ptr:t});r=e.indexOf(".",a);let l=e.slice(a,r<0||r>s?s:r),c=de(l);if(c>-1)throw new A("newlines are not allowed in keys",{toml:e,ptr:t+r+c});if(l.trimStart())throw new A("found extra tokens after the string part",{toml:e,ptr:a});if(s<a&&(s=e.indexOf(n,a),s<0))throw new A("incomplete key-value: cannot find end of key",{toml:e,ptr:t});i.push(ye(e,t,a));}else {r=e.indexOf(".",t);let a=e.slice(t,r<0||r>s?s:r);if(!Bi.test(a))throw new A("only letter, numbers, dashes and underscores are allowed in keys",{toml:e,ptr:t});i.push(a.trimEnd());}}while(r+1&&r<s);return [i,K(e,s+1,true,true)]}function Mn(e,t,n,r){let i={},s=new Set,o;for(t++;(o=e[t++])!=="}"&&o;){if(o===",")throw new A("expected value, found comma",{toml:e,ptr:t-1});if(o==="#")t=Et(e,t);else if(o!==" "&&o!==" "&&o!==`
|
|
31
|
+
`&&o!=="\r"){let a,l=i,c=false,[u,h]=be(e,t-1);for(let w=0;w<u.length;w++){if(w&&(l=c?l[a]:l[a]={}),a=u[w],(c=Object.hasOwn(l,a))&&(typeof l[a]!="object"||s.has(l[a])))throw new A("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 A("trying to redefine an already defined value",{toml:e,ptr:t});let[d,b]=Pt(e,h,"}",n-1,r);s.add(d),l[a]=d,t=b;}}if(!o)throw new A("unfinished table encountered",{toml:e,ptr:t});return [i,t]}function Hn(e,t,n,r){let i=[],s;for(t++;(s=e[t++])!=="]"&&s;){if(s===",")throw new A("expected value, found comma",{toml:e,ptr:t-1});if(s==="#")t=Et(e,t);else if(s!==" "&&s!==" "&&s!==`
|
|
32
|
+
`&&s!=="\r"){let o=Pt(e,t-1,"]",n-1,r);i.push(o[0]),t=o[1];}}if(!s)throw new A("unfinished array encountered",{toml:e,ptr:t});return [i,t]}function qn(e,t,n,r){let i=t,s=n,o,a=false,l;for(let c=0;c<e.length;c++){if(c){if(i=a?i[o]:i[o]={},s=(l=s[o]).c,r===0&&(l.t===1||l.t===2))return null;if(l.t===2){let u=i.length-1;i=i[u],s=s[u].c;}}if(o=e[c],(a=Object.hasOwn(i,o))&&s[o]?.t===0&&s[o]?.d)return null;a||(o==="__proto__"&&(Object.defineProperty(i,o,{enumerable:true,configurable:true,writable:true}),Object.defineProperty(s,o,{enumerable:true,configurable:true,writable:true})),s[o]={t:c<e.length-1&&r===2?3:r,d:false,i:0,c:{}});}if(l=s[o],l.t!==r&&!(r===1&&l.t===3)||(r===2&&(l.d||(l.d=true,i[o]=[]),i[o].push(i={}),l.c[l.i++]=l={t:1,d:false,i:0,c:{}}),l.d))return null;if(l.d=true,r===1)i=a?i[o]:i[o]={};else if(r===0&&a)return null;return [o,i,l.c]}function Lt(e,{maxDepth:t=1e3,integersAsBigInt:n}={}){let r={},i={},s=r,o=i;for(let a=K(e,0);a<e.length;){if(e[a]==="["){let l=e[++a]==="[",c=be(e,a+=+l,"]");if(l){if(e[c[1]-1]!=="]")throw new A("expected end of table declaration",{toml:e,ptr:c[1]-1});c[1]++;}let u=qn(c[0],r,i,l?2:1);if(!u)throw new A("trying to redefine an already defined table or value",{toml:e,ptr:a});o=u[2],s=u[1],a=c[1];}else {let l=be(e,a),c=qn(l[0],s,o,0);if(!c)throw new A("trying to redefine an already defined table or value",{toml:e,ptr:a});let u=Pt(e,l[1],void 0,t,n);c[1][c[0]]=u[0],a=u[1];}if(a=K(e,a,true),e[a]&&e[a]!==`
|
|
33
|
+
`&&e[a]!=="\r")throw new A("each key-value declaration must be followed by an end-of-line",{toml:e,ptr:a});a=K(e,a);}return r}var Gn=/^[a-z0-9-_]+$/i;function Ot(e){let t=typeof e;if(t==="object"){if(Array.isArray(e))return "array";if(e instanceof Date)return "date"}return t}function Mi(e){for(let t=0;t<e.length;t++)if(Ot(e[t])!=="object")return false;return e.length!=0}function Me(e){return JSON.stringify(e).replace(/\x7f/g,"\\u007f")}function He(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 Me(e);if(t==="date"){if(isNaN(e.getTime()))throw new TypeError("cannot serialize invalid date");return e.toISOString()}if(t==="object")return Hi(e,n,r);if(t==="array")return qi(e,n,r)}function Hi(e,t,n){let r=Object.keys(e);if(r.length===0)return "{}";let i="{ ";for(let s=0;s<r.length;s++){let o=r[s];s&&(i+=", "),i+=Gn.test(o)?o:Me(o),i+=" = ",i+=He(e[o],Ot(e[o]),t-1,n);}return i+" }"}function qi(e,t,n){if(e.length===0)return "[]";let r="[ ";for(let i=0;i<e.length;i++){if(i&&(r+=", "),e[i]===null||e[i]===void 0)throw new TypeError("arrays cannot contain null or undefined values");r+=He(e[i],Ot(e[i]),t-1,n);}return r+" ]"}function Gi(e,t,n,r){if(n===0)throw new Error("Could not stringify the object: maximum object depth exceeded");let i="";for(let s=0;s<e.length;s++)i+=`${i&&`
|
|
34
34
|
`}[[${t}]]
|
|
35
|
-
`,i+=
|
|
36
|
-
`)+
|
|
37
|
-
`)+
|
|
35
|
+
`,i+=qe(0,e[s],t,n,r);return i}function qe(e,t,n,r,i){if(r===0)throw new Error("Could not stringify the object: maximum object depth exceeded");let s="",o="",a=Object.keys(t);for(let l=0;l<a.length;l++){let c=a[l];if(t[c]!==null&&t[c]!==void 0){let u=Ot(t[c]);if(u==="symbol"||u==="function")throw new TypeError(`cannot serialize values of type '${u}'`);let h=Gn.test(c)?c:Me(c);if(u==="array"&&Mi(t[c]))o+=(o&&`
|
|
36
|
+
`)+Gi(t[c],n?`${n}.${h}`:h,r-1,i);else if(u==="object"){let d=n?`${n}.${h}`:h;o+=(o&&`
|
|
37
|
+
`)+qe(d,t[c],d,r-1,i);}else s+=h,s+=" = ",s+=He(t[c],u,r,i),s+=`
|
|
38
38
|
`;}}return e&&(s||!o)&&(s=s?`[${e}]
|
|
39
39
|
${s}`:`[${e}]`),s&&o?`${s}
|
|
40
|
-
${o}`:s||o}function
|
|
40
|
+
${o}`:s||o}function Ge(e,{maxDepth:t=1e3,numbersAsFloat:n=false}={}){if(Ot(e)!=="object")throw new TypeError("stringify can only be called with an object");let r=qe(0,e,"",t,n);return r[r.length-1]!==`
|
|
41
41
|
`?r+`
|
|
42
|
-
`:r}var
|
|
43
|
-
`;)n+=e[r],r++;continue}if(o==="/"&&a==="*"){for(n+="/*",r+=2;r<i&&!(e[r]==="*"&&e[r+1]==="/");)n+=e[r],r++;r<i&&(n+="*/",r+=2);continue}if(o==="'"){for(n+=o,r++;r<i;){if(e[r]==="'"&&e[r+1]==="'"){n+="''",r+=2;continue}if(n+=e[r],e[r]==="'"){r++;break}r++;}continue}if(o==='"'){for(n+=o,r++;r<i;){if(e[r]==='"'&&e[r+1]==='"'){n+='""',r+=2;continue}if(n+=e[r],e[r]==='"'){r++;break}r++;}continue}if(o==="$"){let l=e.indexOf("$",r+1);if(l!==-1){let c=e.slice(r,l+1);if(/^\$[A-Za-z_][A-Za-z0-9_]*\$$|^\$\$$/.test(c)){n+=c,r=l+1;let h=e.indexOf(c,r);h===-1?(n+=e.slice(r),r=i):(n+=e.slice(r,h+c.length),r=h+c.length);continue}}}if(o===";"){s(n),n="",r++;continue}n+=o,r++;}return s(n),t}function
|
|
44
|
-
`;)n++;continue}if(i==="/"&&s==="*"){for(n+=2;n<r&&!(e[n]==="*"&&e[n+1]==="/");)n++;n+=2;continue}t+=i,n++;}return t.trim()}function Ve(e){return typeof e=="number"?e:Number.parseInt(String(e),10)}var xe=class{driver=M;basePath;constructor(t){this.basePath=nt.resolve(t.basePath);}filePath(t,n){return nt.join(this.basePath,t,n)}async ensureDir(t){await M.mkdir(nt.dirname(t),{recursive:true});}async getObject(t,n,r,i){let s=this.filePath(t,n),o=await M.stat(s),a=`"${createHash("md5").update(`${s}:${o.mtimeMs}`).digest("hex")}"`;if(i?.ifNoneMatch===a)return {httpStatusCode:304,metadata:this.buildMetadata(o,a,n)};if(i?.ifModifiedSince){let d=new Date(i.ifModifiedSince);if(o.mtime<=d)return {httpStatusCode:304,metadata:this.buildMetadata(o,a,n)}}let l,c,u=o.size,h=200;if(i?.range){let d=i.range.match(/^bytes=(\d+)-(\d*)$/);if(d){let b=Number.parseInt(d[1],10),w=d[2]?Number.parseInt(d[2],10):o.size-1;u=w-b+1,c=`bytes ${b}-${w}/${o.size}`,h=206,l=(await M.open(s,"r")).readableWebStream();}else l=(await M.open(s,"r")).readableWebStream();}else l=(await M.open(s,"r")).readableWebStream();return {httpStatusCode:h,metadata:{...this.buildMetadata(o,a,n),contentLength:u,contentRange:c},body:l}}async uploadObject(t,n,r,i,s,o){let a=this.filePath(t,n);await this.ensureDir(a);let l;if(i instanceof Uint8Array||Buffer.isBuffer(i))l=i;else {let h=[],d=i.getReader();for(;;){let{done:b,value:w}=await d.read();if(b)break;h.push(w);}l=Buffer.concat(h);}await M.writeFile(a,l);let c=await M.stat(a),u=`"${createHash("md5").update(l).digest("hex")}"`;return {cacheControl:o,contentLength:c.size,size:c.size,mimetype:s,lastModified:c.mtime,eTag:u}}async deleteObject(t,n,r){let i=this.filePath(t,n);await M.unlink(i).catch(s=>{if(s.code!=="ENOENT")throw s});}async deleteObjects(t,n){for(let r of n)await this.deleteObject(t,r,void 0);}async copyObject(t,n,r,i,s){let o=this.filePath(t,n),a=this.filePath(t,i);await this.ensureDir(a),await M.copyFile(o,a);let l=await M.stat(a),c=await M.readFile(a);return {httpStatusCode:200,eTag:`"${createHash("md5").update(c).digest("hex")}"`,lastModified:l.mtime}}async headObject(t,n,r){let i=this.filePath(t,n),s=await M.stat(i),o=`"${createHash("md5").update(`${i}:${s.mtimeMs}`).digest("hex")}"`;return this.buildMetadata(s,o,n)}async privateAssetUrl(t,n,r){return `file://${this.filePath(t,n)}`}buildMetadata(t,n,r){return {cacheControl:"no-cache",contentLength:Ve(t.size),size:Ve(t.size),mimetype:Bi(r),lastModified:t.mtime,eTag:n}}};function Bi(e){let t=nt.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 qi=new Function("spec","return import(spec)");async function Ge(e,t,n){try{return await qi(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}}function Bn(e,t={}){let n=nt__default.resolve(t.cwd??process.cwd()),r=t.env??process.env,i=process.env.SUPABASE_ENV||"development",s=[`.env.${i}.local`,i==="test"?null:".env.local",`.env.${i}`,".env"].filter(a=>a!==null),o=Wi(nt__default.resolve(e),n);for(let a of o)for(let l of s){let c=nt__default.join(a,l),u;try{u=le.readFileSync(c,"utf-8");}catch{continue}let h;try{h=parse(u);}catch(d){throw new Error(`Failed to parse ${c}: ${d.message}`)}for(let[d,b]of Object.entries(h))r[d]===void 0&&(r[d]=b);}}function Wi(e,t){let n=[],r=e,i=nt__default.parse(r).root;for(;n.push(r),!(r===t||r===i);){let s=nt__default.dirname(r);if(s===r)break;r=s;}return n}var zi=/^env\((\w+)\)$/;function qn(e,t=process.env){return We(e,t)}function We(e,t){if(typeof e=="string"){let n=e.match(zi);return n?t[n[1]]??"":e}if(Array.isArray(e))return e.map(n=>We(n,t));if(e&&typeof e=="object"){let n={};for(let[r,i]of Object.entries(e))n[r]=We(i,t);return n}return e}var Xi=["toml","json","ts","mts","js","mjs","cjs"],Se=class extends xt{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=nt__default.relative(process.cwd(),ct.config_dir);if(!t)for(let r of Xi){let i=nt__default.join(n,`config.${r}`);if(await M__default.access(i).then(()=>true).catch(()=>false)){t=i;break}}return t}async readConfig(t){let n=await this.getConfigPath(t);if(!n)return {};console.log(Ft.default.dim(`Using config file: ${Ft.default.cyan(`./${n}`)}`));let r=nt__default.dirname(nt__default.resolve(n));Bn(r);let i=n.split(".").pop(),s;switch(i){case "toml":s=Pt(await M__default.readFile(n,"utf-8"));break;case "json":s=JSON.parse(await M__default.readFile(n,"utf-8"));break;case "ts":case "mts":case "js":case "mjs":case "cjs":try{s=(await import(nt__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 qn(s)}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,i;switch(n.db?.driver){case "sqlite":i=n.db?.url??ct.default_db_url,r=await createConnection({url:i,ddlDialect:"sqlite"});break;case "pglite":{i=n.db?.url??nt__default.join(process.cwd(),ct.default_db_dir);let{createPgliteConnection:s}=await Ge("@supabase/lite/pglite","pglite","@electric-sql/pglite");r=await s({url:i});break}case "postgres":{i=n.db?.url??"";let{createPostgresConnection:s}=await Ge("@supabase/lite/postgres","postgres","postgres");r=await s({url:i});break}default:i=n.db?.url??ct.default_db_url,r=await createConnection({url:i,ddlDialect:"postgres"});break}if(!r)throw new Error("Failed to create connection");return console.log(Ft.default.green(" \u279C"),"Database located at",Ft.default.cyan(i??"in-memory")),{...n,connection:r}}async createApp(t){let n=await this.getConfig(t),r=new App(n);return r.config.storage?.enabled&&process.env.EXPERIMENTAL_STORAGE==="1"&&!r._storageAdapter&&(r._storageAdapter=new xe({basePath:nt__default.join(process.cwd(),ct.config_dir,".temp/storage")})),await r.init()}};var Ee=class extends xt{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(!n||!n.data)throw new Error("Failed to list projects");return n.data}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={}){let n=await this.fetch("/v1/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)throw new Error(`Failed to create project: ${n.status} ${n.statusText}`);let r=await n.json();if(!r.data||!r.data.id)throw new Error("Failed to create project");return r.data}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 i=await this.getConfig(t);return await new App({...i.config,connection:cloud({projectRef:t,token:n.session.access_token,host:this.config.host})}).init()}};var Ae=class extends wt{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 Se(t),remote:new Ee(t)},this}};async function Qi(e={}){return await new Ae({host:vt,root:ot.projectDir(),...e}).init()}var Ye=Rt($t());var Xe=Rt($t());var Zi=["toml","json","ts","mts","js","mjs","cjs"];async function _e(e){let t=nt__default.relative(process.cwd(),ct.config_dir);if(!e)for(let n of Zi){let r=nt__default.join(t,`config.${n}`);if(await M__default.access(r).then(()=>true).catch(()=>false)){e=r;break}}return e}async function Gn(e){let t=await _e(e);if(!t)return {};switch(console.log(Xe.default.dim(`Using config file: ${Xe.default.cyan(`./${t}`)}`)),t.split(".").pop()){case "toml":return Pt(await M__default.readFile(t,"utf-8"));case "json":return JSON.parse(await M__default.readFile(t,"utf-8"));case "ts":case "mts":case "js":case "mjs":case "cjs":try{return (await import(nt__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 Wn(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 nt__default.resolve(process.cwd(),t)}async function ts(e={}){let t=process.cwd();if(e.recreate){console.log(Ye.default.dim("Recreating database..."));try{let r=await _e();if(r&&!/\.(ts|mts|js|mjs|cjs)$/.test(r)){let s=(await Gn(r))?.db?.url,o=s?Wn(s):void 0;o&&le.existsSync(o)&&(le.rmSync(o,{recursive:!0,force:!0}),console.log(Ye.default.dim(` \u279C removed ${nt__default.relative(t,o)}`)));}}catch{}try{le.rmSync(nt__default.join(t,"supabase",".temp"),{recursive:!0,force:!0});}catch{}}if(tt(nt__default.join(t,"supabase")),!await _e()){let r={db:{driver:"sqlite-postgres",url:"file:./supabase/.temp/data.db"},auth:{enabled:true}};e.driver==="pglite"&&(r.db.driver="pglite",r.db.url=nt__default.relative(process.cwd(),nt__default.join(t,"supabase",".temp","data")));let i=e.configFormat??"toml",s=nt__default.join(t,"supabase",`config.${i}`);i==="json"?mt(s,JSON.stringify(r)):mt(s,qe(r));}tt(nt__default.join(t,"supabase",".temp")),tt(nt__default.join(t,"supabase","schemas"),()=>{mt(nt__default.join(t,"supabase","schemas","schema.sql"),e.template?es:`-- This is a schema file for the database
|
|
45
|
-
`);}),
|
|
46
|
-
`);}var
|
|
42
|
+
`:r}var Vi={storage:"EXPERIMENTAL_STORAGE",cloud:"EXPERIMENTAL_CLOUD"},Wi=["storage","cloud"];Object.fromEntries(Wi.map(e=>[e,zi(e)]));function zi(e){let t=typeof process<"u"&&process.env||void 0;return t?t.NODE_ENV==="test"?true:t[Vi[e]]==="1":false}function we(e){let t=[],n="",r=0,i=e.length,s=o=>{Xi(o).length>0&&t.push(o.trim());};for(;r<i;){let o=e[r],a=e[r+1];if(o==="-"&&a==="-"){for(;r<i&&e[r]!==`
|
|
43
|
+
`;)n+=e[r],r++;continue}if(o==="/"&&a==="*"){for(n+="/*",r+=2;r<i&&!(e[r]==="*"&&e[r+1]==="/");)n+=e[r],r++;r<i&&(n+="*/",r+=2);continue}if(o==="'"){for(n+=o,r++;r<i;){if(e[r]==="'"&&e[r+1]==="'"){n+="''",r+=2;continue}if(n+=e[r],e[r]==="'"){r++;break}r++;}continue}if(o==='"'){for(n+=o,r++;r<i;){if(e[r]==='"'&&e[r+1]==='"'){n+='""',r+=2;continue}if(n+=e[r],e[r]==='"'){r++;break}r++;}continue}if(o==="$"){let l=e.indexOf("$",r+1);if(l!==-1){let c=e.slice(r,l+1);if(/^\$[A-Za-z_][A-Za-z0-9_]*\$$|^\$\$$/.test(c)){n+=c,r=l+1;let h=e.indexOf(c,r);h===-1?(n+=e.slice(r),r=i):(n+=e.slice(r,h+c.length),r=h+c.length);continue}}}if(o===";"){s(n),n="",r++;continue}n+=o,r++;}return s(n),t}function Xi(e){let t="",n=0,r=e.length;for(;n<r;){let i=e[n],s=e[n+1];if(i==="-"&&s==="-"){for(;n<r&&e[n]!==`
|
|
44
|
+
`;)n++;continue}if(i==="/"&&s==="*"){for(n+=2;n<r&&!(e[n]==="*"&&e[n+1]==="/");)n++;n+=2;continue}t+=i,n++;}return t.trim()}function Ve(e){return typeof e=="number"?e:Number.parseInt(String(e),10)}var Se=class{driver=U;basePath;constructor(t){this.basePath=rt.resolve(t.basePath);}filePath(t,n){return rt.join(this.basePath,t,n)}async ensureDir(t){await U.mkdir(rt.dirname(t),{recursive:true});}async getObject(t,n,r,i){let s=this.filePath(t,n),o=await U.stat(s),a=`"${createHash("md5").update(`${s}:${o.mtimeMs}`).digest("hex")}"`;if(i?.ifNoneMatch===a)return {httpStatusCode:304,metadata:this.buildMetadata(o,a,n)};if(i?.ifModifiedSince){let d=new Date(i.ifModifiedSince);if(o.mtime<=d)return {httpStatusCode:304,metadata:this.buildMetadata(o,a,n)}}let l,c,u=o.size,h=200;if(i?.range){let d=i.range.match(/^bytes=(\d+)-(\d*)$/);if(d){let b=Number.parseInt(d[1],10),w=d[2]?Number.parseInt(d[2],10):o.size-1;u=w-b+1,c=`bytes ${b}-${w}/${o.size}`,h=206,l=(await U.open(s,"r")).readableWebStream();}else l=(await U.open(s,"r")).readableWebStream();}else l=(await U.open(s,"r")).readableWebStream();return {httpStatusCode:h,metadata:{...this.buildMetadata(o,a,n),contentLength:u,contentRange:c},body:l}}async uploadObject(t,n,r,i,s,o){let a=this.filePath(t,n);await this.ensureDir(a);let l;if(i instanceof Uint8Array||Buffer.isBuffer(i))l=i;else {let h=[],d=i.getReader();for(;;){let{done:b,value:w}=await d.read();if(b)break;h.push(w);}l=Buffer.concat(h);}await U.writeFile(a,l);let c=await U.stat(a),u=`"${createHash("md5").update(l).digest("hex")}"`;return {cacheControl:o,contentLength:c.size,size:c.size,mimetype:s,lastModified:c.mtime,eTag:u}}async deleteObject(t,n,r){let i=this.filePath(t,n);await U.unlink(i).catch(s=>{if(s.code!=="ENOENT")throw s});}async deleteObjects(t,n){for(let r of n)await this.deleteObject(t,r,void 0);}async copyObject(t,n,r,i,s){let o=this.filePath(t,n),a=this.filePath(t,i);await this.ensureDir(a),await U.copyFile(o,a);let l=await U.stat(a),c=await U.readFile(a);return {httpStatusCode:200,eTag:`"${createHash("md5").update(c).digest("hex")}"`,lastModified:l.mtime}}async headObject(t,n,r){let i=this.filePath(t,n),s=await U.stat(i),o=`"${createHash("md5").update(`${i}:${s.mtimeMs}`).digest("hex")}"`;return this.buildMetadata(s,o,n)}async privateAssetUrl(t,n,r){return `file://${this.filePath(t,n)}`}buildMetadata(t,n,r){return {cacheControl:"no-cache",contentLength:Ve(t.size),size:Ve(t.size),mimetype:Ji(r),lastModified:t.mtime,eTag:n}}};function Ji(e){let t=rt.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 Yi=new Function("spec","return import(spec)");async function We(e,t,n){try{return await Yi(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}}function Wn(e,t={}){let n=rt__default.resolve(t.cwd??process.cwd()),r=t.env??process.env,i=process.env.SUPABASE_ENV||"development",s=[`.env.${i}.local`,i==="test"?null:".env.local",`.env.${i}`,".env"].filter(a=>a!==null),o=ts(rt__default.resolve(e),n);for(let a of o)for(let l of s){let c=rt__default.join(a,l),u;try{u=ce.readFileSync(c,"utf-8");}catch{continue}let h;try{h=parse(u);}catch(d){throw new Error(`Failed to parse ${c}: ${d.message}`)}for(let[d,b]of Object.entries(h))r[d]===void 0&&(r[d]=b);}}function ts(e,t){let n=[],r=e,i=rt__default.parse(r).root;for(;n.push(r),!(r===t||r===i);){let s=rt__default.dirname(r);if(s===r)break;r=s;}return n}var es=/^env\((\w+)\)$/;function zn(e,t=process.env){return ze(e,t)}function ze(e,t){if(typeof e=="string"){let n=e.match(es);return n?t[n[1]]??"":e}if(Array.isArray(e))return e.map(n=>ze(n,t));if(e&&typeof e=="object"){let n={};for(let[r,i]of Object.entries(e))n[r]=ze(i,t);return n}return e}var rs=["toml","json","ts","mts","js","mjs","cjs"],Ee=class extends St{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=rt__default.relative(process.cwd(),ut.config_dir);if(!t)for(let r of rs){let i=rt__default.join(n,`config.${r}`);if(await U__default.access(i).then(()=>true).catch(()=>false)){t=i;break}}return t}async readConfig(t){let n=await this.getConfigPath(t);if(!n)return {};console.log(It.default.dim(`Using config file: ${It.default.cyan(`./${n}`)}`));let r=rt__default.dirname(rt__default.resolve(n));Wn(r);let i=n.split(".").pop(),s;switch(i){case "toml":s=Lt(await U__default.readFile(n,"utf-8"));break;case "json":s=JSON.parse(await U__default.readFile(n,"utf-8"));break;case "ts":case "mts":case "js":case "mjs":case "cjs":try{s=(await import(rt__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 zn(s)}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,i;switch(n.db?.driver){case "sqlite":i=n.db?.url??ut.default_db_url,r=await createConnection({url:i,ddlDialect:"sqlite"});break;case "pglite":{i=n.db?.url??rt__default.join(process.cwd(),ut.default_db_dir);let{createPgliteConnection:s}=await We("@supabase/lite/pglite","pglite","@electric-sql/pglite");r=await s({url:i});break}case "postgres":{i=n.db?.url??"";let{createPostgresConnection:s}=await We("@supabase/lite/postgres","postgres","postgres");r=await s({url:i});break}default:i=n.db?.url??ut.default_db_url,r=await createConnection({url:i,ddlDialect:"postgres"});break}if(!r)throw new Error("Failed to create connection");return console.log(It.default.green(" \u279C"),"Database located at",It.default.cyan(i??"in-memory")),{...n,connection:r}}async createApp(t){let n=await this.getConfig(t),r=new App(n);return r.config.storage?.enabled&&process.env.EXPERIMENTAL_STORAGE==="1"&&!r._storageAdapter&&(r._storageAdapter=new Se({basePath:rt__default.join(process.cwd(),ut.config_dir,".temp/storage")})),await r.init()}};var Te=class extends St{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(!n||!n.data)throw new Error("Failed to list projects");return n.data}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={}){let n=await this.fetch("/v1/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)throw new Error(`Failed to create project: ${n.status} ${n.statusText}`);let r=await n.json();if(!r.data||!r.data.id)throw new Error("Failed to create project");return r.data}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 i=await this.getConfig(t);return await new App({...i.config,connection:cloud({projectRef:t,token:n.session.access_token,host:this.config.host})}).init()}};var Ae=class extends xt{project;get client(){if(!this._client)throw new Error("Supabase client not initialized");return this._client}async getSession(){return await this.client.auth.getSession()}async getAccessToken(){let{data:t,error: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 Ee(t),remote:new Te(t)},this}};async function os(e={}){return await new Ae({host:vt,root:at.projectDir(),...e}).init()}var Qe=$t(Nt());var Je=$t(Nt());var as=["toml","json","ts","mts","js","mjs","cjs"];async function Ce(e){let t=rt__default.relative(process.cwd(),ut.config_dir);if(!e)for(let n of as){let r=rt__default.join(t,`config.${n}`);if(await U__default.access(r).then(()=>true).catch(()=>false)){e=r;break}}return e}async function Xn(e){let t=await Ce(e);if(!t)return {};switch(console.log(Je.default.dim(`Using config file: ${Je.default.cyan(`./${t}`)}`)),t.split(".").pop()){case "toml":return Lt(await U__default.readFile(t,"utf-8"));case "json":return JSON.parse(await U__default.readFile(t,"utf-8"));case "ts":case "mts":case "js":case "mjs":case "cjs":try{return (await import(rt__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 Jn(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 rt__default.resolve(process.cwd(),t)}async function ls(e={}){let t=process.cwd();if(e.recreate){console.log(Qe.default.dim("Recreating database..."));try{let r=await Ce();if(r&&!/\.(ts|mts|js|mjs|cjs)$/.test(r)){let s=(await Xn(r))?.db?.url,o=s?Jn(s):void 0;o&&ce.existsSync(o)&&(ce.rmSync(o,{recursive:!0,force:!0}),console.log(Qe.default.dim(` \u279C removed ${rt__default.relative(t,o)}`)));}}catch{}try{ce.rmSync(rt__default.join(t,"supabase",".temp"),{recursive:!0,force:!0});}catch{}}if(tt(rt__default.join(t,"supabase")),!await Ce()){let r={api:{port:54321},db:{driver:"sqlite-postgres",url:"file:./supabase/.temp/data.db",migrations:{schema_paths:["./schemas/schema.sql"]},seed:{sql_paths:["./seed.sql"]}},auth:{enabled:true,jwt_secret:"dev-secret-change-me",jwt_expiry:3600,enable_signup:true,email:{enable_confirmations:false}}};e.driver==="pglite"&&(r.db.driver="pglite",r.db.url=rt__default.relative(process.cwd(),rt__default.join(t,"supabase",".temp","data")));let i=e.configFormat??"toml",s=rt__default.join(t,"supabase",`config.${i}`);i==="json"?ht(s,JSON.stringify(r)):ht(s,Ge(r));}tt(rt__default.join(t,"supabase",".temp")),tt(rt__default.join(t,"supabase","schemas"),()=>{ht(rt__default.join(t,"supabase","schemas","schema.sql"),e.template?cs:`-- This is a schema file for the database
|
|
45
|
+
`);}),ht(rt__default.join(t,"supabase","seed.sql"),e.template?us:`-- This is a seed file for the database
|
|
46
|
+
`);}var cs=`
|
|
47
47
|
create table todos (
|
|
48
48
|
id serial primary key,
|
|
49
49
|
title text not null,
|
|
@@ -56,13 +56,13 @@ create table todos (
|
|
|
56
56
|
create table test (
|
|
57
57
|
id serial primary key,
|
|
58
58
|
name text not null
|
|
59
|
-
)`,ns="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 zn=createRequire(import.meta.url);function cs(e){let t=normalize(e);return t.length>1&&t[t.length-1]===sep&&(t=t.substring(0,t.length-1)),t}var us=/[\\/]/g;function Jn(e,t){return e.replace(us,t)}var fs=/^[a-z]:[\\/]$/i;function ps(e){return e==="/"||fs.test(e)}function Qe(e,t){let{resolvePaths:n,normalizePath:r,pathSeparator:i}=t,s=process.platform==="win32"&&e.includes("/")||e.startsWith(".");if(n&&(e=resolve(e)),(r||s)&&(e=cs(e)),e===".")return "";let o=e[e.length-1]!==i;return Jn(o?e+i:e,i)}function Yn(e,t){return t+e}function ms(e,t){return function(n,r){return r.startsWith(e)?r.slice(e.length)+n:Jn(relative(e,r),t.pathSeparator)+t.pathSeparator+n}}function hs(e){return e}function ds(e,t,n){return t+e+n}function gs(e,t){let{relativePaths:n,includeBasePath:r}=t;return n&&e?ms(e,t):r?Yn:hs}function ys(e){return function(t,n){n.push(t.substring(e.length)||".");}}function bs(e){return function(t,n,r){let i=t.substring(e.length)||".";r.every(s=>s(i,true))&&n.push(i);}}var ws=(e,t)=>{t.push(e||".");},xs=(e,t,n)=>{let r=e||".";n.every(i=>i(r,true))&&t.push(r);},Ss=()=>{};function Es(e,t){let{includeDirs:n,filters:r,relativePaths:i}=t;return n?i?r&&r.length?bs(e):ys(e):r&&r.length?xs:ws:Ss}var As=(e,t,n,r)=>{r.every(i=>i(e,false))&&n.files++;},Ts=(e,t,n,r)=>{r.every(i=>i(e,false))&&t.push(e);},_s=(e,t,n,r)=>{n.files++;},Cs=(e,t)=>{t.push(e);},Rs=()=>{};function vs(e){let{excludeFiles:t,filters:n,onlyCounts:r}=e;return t?Rs:n&&n.length?r?As:Ts:r?_s:Cs}var $s=e=>e,Ns=()=>[""].slice(0,0);function ks(e){return e.group?Ns:$s}var Ps=(e,t,n)=>{e.push({directory:t,files:n,dir:t});},Ls=()=>{};function Os(e){return e.group?Ps:Ls}var Fs=function(e,t,n){let{queue:r,fs:i,options:{suppressErrors:s}}=t;r.enqueue(),i.realpath(e,(o,a)=>{if(o)return r.dequeue(s?null:o,t);i.stat(a,(l,c)=>{if(l)return r.dequeue(s?null:l,t);if(c.isDirectory()&&Qn(e,a,t))return r.dequeue(null,t);n(c,a),r.dequeue(null,t);});});},Is=function(e,t,n){let{queue:r,fs:i,options:{suppressErrors:s}}=t;r.enqueue();try{let o=i.realpathSync(e),a=i.statSync(o);if(a.isDirectory()&&Qn(e,o,t))return;n(a,o);}catch(o){if(!s)throw o}};function Ds(e,t){return !e.resolveSymlinks||e.excludeSymlinks?null:t?Is:Fs}function Qn(e,t,n){if(n.options.useRealPaths)return js(t,n);let r=dirname(e),i=1;for(;r!==n.root&&i<2;){let s=n.symlinks.get(r);!!s&&(s===t||s.startsWith(t)||t.startsWith(s))?i++:r=dirname(r);}return n.symlinks.set(e,t),i>1}function js(e,t){return t.visited.includes(e+t.options.pathSeparator)}var Ms=e=>e.counts,Us=e=>e.groups,Hs=e=>e.paths,Bs=e=>e.paths.slice(0,e.options.maxFiles),qs=(e,t,n)=>(Ce(t,n,e.counts,e.options.suppressErrors),null),Vs=(e,t,n)=>(Ce(t,n,e.paths,e.options.suppressErrors),null),Gs=(e,t,n)=>(Ce(t,n,e.paths.slice(0,e.options.maxFiles),e.options.suppressErrors),null),Ws=(e,t,n)=>(Ce(t,n,e.groups,e.options.suppressErrors),null);function Ce(e,t,n,r){t(e&&!r?e:null,n);}function zs(e,t){let{onlyCounts:n,group:r,maxFiles:i}=e;return n?t?Ms:qs:r?t?Us:Ws:i?t?Bs:Gs:t?Hs:Vs}var Zn={withFileTypes:true},Ks=(e,t,n,r,i)=>{if(e.queue.enqueue(),r<0)return e.queue.dequeue(null,e);let{fs:s}=e;e.visited.push(t),e.counts.directories++,s.readdir(t||".",Zn,(o,a=[])=>{i(a,n,r),e.queue.dequeue(e.options.suppressErrors?null:o,e);});},Xs=(e,t,n,r,i)=>{let{fs:s}=e;if(r<0)return;e.visited.push(t),e.counts.directories++;let o=[];try{o=s.readdirSync(t||".",Zn);}catch(a){if(!e.options.suppressErrors)throw a}i(o,n,r);};function Js(e){return e?Xs:Ks}var Ys=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));}},Qs=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}},Zs=class{aborted=false;abort(){this.aborted=true;}},tr=class{root;isSynchronous;state;joinPath;pushDirectory;pushFile;getArray;groupFiles;resolveSymlink;walkDirectory;callbackInvoker;constructor(e,t,n){this.isSynchronous=!n,this.callbackInvoker=zs(t,this.isSynchronous),this.root=Qe(e,t),this.state={root:ps(this.root)?this.root:this.root.slice(0,-1),paths:[""].slice(0,0),groups:[],counts:new Qs,options:t,queue:new Ys((r,i)=>this.callbackInvoker(i,r,n)),symlinks:new Map,visited:[""].slice(0,0),controller:new Zs,fs:t.fs||At},this.joinPath=gs(this.root,t),this.pushDirectory=Es(this.root,t),this.pushFile=vs(t),this.getArray=ks(t),this.groupFiles=Os(t),this.resolveSymlink=Ds(t,this.isSynchronous),this.walkDirectory=Js(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:i,resolveSymlinks:s,excludeSymlinks:o,exclude:a,maxFiles:l,signal:c,useRealPaths:u,pathSeparator:h},controller:d}=this.state;if(d.aborted||c&&c.aborted||l&&r.length>l)return;let b=this.getArray(this.state.paths);for(let w=0;w<e.length;++w){let E=e[w];if(E.isFile()||E.isSymbolicLink()&&!s&&!o){let _=this.joinPath(E.name,t);this.pushFile(_,b,this.state.counts,i);}else if(E.isDirectory()){let _=ds(E.name,t,this.state.options.pathSeparator);if(a&&a(E.name,_))continue;this.pushDirectory(_,r,i),this.walkDirectory(this.state,_,_,n-1,this.walk);}else if(this.resolveSymlink&&E.isSymbolicLink()){let _=Yn(E.name,t);this.resolveSymlink(_,this.state,($,x)=>{if($.isDirectory()){if(x=Qe(x,this.state.options),a&&a(E.name,u?x:_+h))return;this.walkDirectory(this.state,x,u?x:_+h,n-1,this.walk);}else {x=u?x:_;let G=basename(x),Z=Qe(dirname(x),this.state.options);x=this.joinPath(G,Z),this.pushFile(x,b,this.state.counts,i);}});}}this.groupFiles(this.state.groups,t,b);}};function to(e,t){return new Promise((n,r)=>{er(e,t,(i,s)=>{if(i)return r(i);n(s);});})}function er(e,t,n){new tr(e,t,n).start();}function eo(e,t){return new tr(e,t).start()}var Kn=class{constructor(e,t){this.root=e,this.options=t;}withPromise(){return to(this.root,this.options)}withCallback(e){er(this.root,this.options,e);}sync(){return eo(this.root,this.options)}},nr=null;try{zn.resolve("picomatch"),nr=zn("picomatch");}catch{}var rr=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 Kn(e||".",this.options)}withGlobFunction(e){return this.globFunction=e,this}crawlWithOptions(e,t){return this.options={...this.options,...t},new Kn(e||".",this.options)}glob(...e){return this.globFunction?this.globWithOptions(e):this.globWithOptions(e,{dot:true})}globWithOptions(e,...t){let n=this.globFunction||nr;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(i=>r(i)),this}};var _t=Rt(Cr()),Lo=Array.isArray,$r=process.platform==="win32",Oo=/^(\/?\.\.)+$/;function Fo(e,t={}){let n=e.length,r=Array(n),i=Array(n),s=!t.noglobstar;for(let o=0;o<n;o++){let a=Nr(e[o]);r[o]=a;let l=a.length,c=Array(l);for(let u=0;u<l;u++)c[u]=(0, _t.default)(a[u],t);i[o]=c;}return o=>{let a=o.split("/");if(a[0]===".."&&Oo.test(o))return true;for(let l=0;l<e.length;l++){let c=r[l],u=i[l],h=a.length,d=Math.min(h,c.length),b=0;for(;b<d;){let w=c[b];if(w.includes("/"))return true;if(!u[b](a[b]))break;if(s&&w==="**")return true;b++;}if(b===h)return true}return false}}var Io=/^[A-Z]:\/$/i,Do=$r?e=>Io.test(e):e=>e==="/";function Rr(e,t,n){if(e===t||t.startsWith(`${e}/`)){if(n){let i=Do(e)?e.length:e.length+1;return (s,o)=>s.slice(i,o?-1:void 0)||"."}let r=t.slice(e.length+1);return r?(i,s)=>{if(i===".")return r;let o=`${r}/${i}`;return s?o.slice(0,-1):o}:(i,s)=>s&&i!=="."?i.slice(0,-1):i}return n?r=>posix.relative(e,r)||".":r=>posix.relative(e,`${t}/${r}`)||"."}function jo(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.endsWith("/")&&r!==""?`${r}/`:r||"."}}var Mo={parts:true};function Nr(e){var t;let n=_t.default.scan(e,Mo);return !((t=n.parts)===null||t===void 0)&&t.length?n.parts:[e]}var Uo=/(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g,Ho=/(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g,Bo=e=>e.replace(Uo,"\\$&"),qo=e=>e.replace(Ho,"\\$&"),Vo=$r?qo:Bo;function Go(e,t){let n=_t.default.scan(e);return n.isGlob||n.negated}function Tt(...e){console.log(`[tinyglobby ${new Date().toLocaleTimeString("es")}]`,...e);}var Wo=/^(\/?\.\.)+/,zo=/\\(?=[()[\]{}!*+?@|])/g,$e=/\\/g;function un(e,t,n,r,i){let s=e;e.endsWith("/")&&(s=e.slice(0,-1)),!s.endsWith("*")&&t&&(s+="/**");let o=Vo(n);vr.isAbsolute(s.replace(zo,""))?s=posix.relative(o,s):s=posix.normalize(s);let a=Wo.exec(s),l=Nr(s);if(a?.[0]){let u=(a[0].length+1)/3,h=0,d=o.split("/");for(;h<u&&l[h+u]===d[d.length+h-u];)s=s.slice(0,(u-h-1)*3)+s.slice((u-h)*3+l[h+u].length+1)||".",h++;let b=posix.join(n,a[0].slice(h*3));!b.startsWith(".")&&r.root.length>b.length&&(r.root=b,r.depthOffset=-u+h);}if(!i&&r.depthOffset>=0){var c;(c=r.commonPath)!==null&&c!==void 0||(r.commonPath=l);let u=[],h=Math.min(r.commonPath.length,l.length);for(let d=0;d<h;d++){let b=l[d];if(b==="**"&&!l[d+1]){u.pop();break}if(b!==r.commonPath[d]||Go(b)||d===l.length-1)break;u.push(b);}r.depthOffset=u.length,r.commonPath=u,r.root=u.length>0?posix.join(n,...u):n;}return s}function Ko({patterns:e=["**/*"],ignore:t=[],expandDirectories:n=true},r,i){typeof e=="string"&&(e=[e]),typeof t=="string"&&(t=[t]);let s=[],o=[];for(let a of t)a&&(a[0]!=="!"||a[1]==="(")&&o.push(un(a,n,r,i,true));for(let a of e)a&&(a[0]!=="!"||a[1]==="("?s.push(un(a,n,r,i,false)):(a[1]!=="!"||a[2]==="(")&&o.push(un(a.slice(1),n,r,i,true)));return {match:s,ignore:o}}function Xo(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];e[n]=t(r);}return e}function Jo(e){return e?e instanceof URL?fileURLToPath(e).replace($e,"/"):vr.resolve(e).replace($e,"/"):process.cwd().replace($e,"/")}function Yo(e,t={}){let n=process.env.TINYGLOBBY_DEBUG?{...t,debug:true}:t,r=Jo(n.cwd);if(n.debug&&Tt("globbing with:",{patterns:e,options:n,cwd:r}),Array.isArray(e)&&e.length===0)return [{sync:()=>[],withPromise:async()=>[]},false];let i={root:r,commonPath:null,depthOffset:0},s=Ko({...n,patterns:e},r,i);n.debug&&Tt("internal processing patterns:",s);let o={dot:n.dot,nobrace:n.braceExpansion===false,nocase:n.caseSensitiveMatch===false,noextglob:n.extglob===false,noglobstar:n.globstar===false,posix:true},a=(0, _t.default)(s.match,{...o,ignore:s.ignore}),l=(0, _t.default)(s.ignore,o),c=Fo(s.match,o),u=Rr(r,i.root,n.absolute),h=n.absolute?u:Rr(r,i.root,true),d={filters:[n.debug?(E,_)=>{let $=u(E,_),x=a($);return x&&Tt(`matched ${$}`),x}:(E,_)=>a(u(E,_))],exclude:n.debug?(E,_)=>{let $=h(_,true),x=$!=="."&&!c($)||l($);return Tt(x?`skipped ${_}`:`crawling ${_}`),x}:(E,_)=>{let $=h(_,true);return $!=="."&&!c($)||l($)},fs:n.fs?{readdir:n.fs.readdir||At__default.readdir,readdirSync:n.fs.readdirSync||At__default.readdirSync,realpath:n.fs.realpath||At__default.realpath,realpathSync:n.fs.realpathSync||At__default.realpathSync,stat:n.fs.stat||At__default.stat,statSync:n.fs.statSync||At__default.statSync}:void 0,pathSeparator:"/",relativePaths:true,resolveSymlinks:true,signal:n.signal};n.deep!==void 0&&(d.maxDepth=Math.round(n.deep-i.depthOffset)),n.absolute&&(d.relativePaths=false,d.resolvePaths=true,d.includeBasePath=true),n.followSymbolicLinks===false&&(d.resolveSymlinks=false,d.excludeSymlinks=true),n.onlyDirectories?(d.excludeFiles=true,d.includeDirs=true):n.onlyFiles===false&&(d.includeDirs=true),i.root=i.root.replace($e,"");let b=i.root;n.debug&&Tt("internal properties:",i);let w=r!==b&&!n.absolute&&jo(r,i.root);return [new rr(d).crawl(b),w]}async function Mt(e,t){if(e&&t?.patterns)throw new Error("Cannot pass patterns as both an argument and an option");let n=Lo(e)||typeof e=="string",r=n?t:e,i=n?e:e.patterns,[s,o]=Yo(i,r);return o?Xo(await s.withPromise(),o):s.withPromise()}var N=Rt($t());var Zo=/^(\d{14})(?:_([^.]+))?\.sql$/;function kr(e){return e.config?.db?.driver==="sqlite"?"./sqlite-migrations/*.sql":"./migrations/*.sql"}function ta(e){return nt__default.posix.dirname(kr(e))}async function Ut(e){let t=nt__default.join(process.cwd(),"supabase"),n=await Mt([kr(e)],{cwd:t,absolute:true}),r=[];for(let i of n){let s=nt__default.basename(i),o=Zo.exec(s);if(!o)continue;let a=await M__default.readFile(i,"utf-8");r.push({version:o[1],name:o[2]??null,filename:s,path:i,sql:a});}return r.sort((i,s)=>i.version.localeCompare(s.version))}var Qr="supabase/.temp/.translation-cache.json",Zr=2;async function Oa(e,t){let n=await e.connection.introspect(),r=Nn(n);await ti(e,{...t,dbHasTables:n.tables.length>0,dbFingerprint:r}),n.tables.length===0&&await Da(e);let i=await e.connection.introspect();ni(i,e);}async function Fa(e){let t=await Mt(e.config.db?.seed?.sql_paths??["./seed.sql"],{cwd:nt__default.join(process.cwd(),"supabase"),absolute:true});return (await Promise.all(t.map(r=>M__default.readFile(r,"utf-8")))).flatMap(r=>splitSqlStatements(r))}async function Ia(e,t){let n=await Fa(e);if(n.length===0)return 0;console.log(N.default.dim("Seeding database..."));try{return await e.connection.transaction(n),n.length}catch(r){let i="Fix `supabase/seed.sql`, then run `bun run dev --recreate` to reset and reseed.";throw new Error(`Seed failed and was rolled back: ${String(r.message??r)}
|
|
60
|
-
${i}`)}}async function
|
|
59
|
+
)`,us="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 Yn=createRequire(import.meta.url);function ys(e){let t=normalize(e);return t.length>1&&t[t.length-1]===sep&&(t=t.substring(0,t.length-1)),t}var bs=/[\\/]/g;function tr(e,t){return e.replace(bs,t)}var ws=/^[a-z]:[\\/]$/i;function xs(e){return e==="/"||ws.test(e)}function Ze(e,t){let{resolvePaths:n,normalizePath:r,pathSeparator:i}=t,s=process.platform==="win32"&&e.includes("/")||e.startsWith(".");if(n&&(e=resolve(e)),(r||s)&&(e=ys(e)),e===".")return "";let o=e[e.length-1]!==i;return tr(o?e+i:e,i)}function er(e,t){return t+e}function Ss(e,t){return function(n,r){return r.startsWith(e)?r.slice(e.length)+n:tr(relative(e,r),t.pathSeparator)+t.pathSeparator+n}}function Es(e){return e}function Ts(e,t,n){return t+e+n}function As(e,t){let{relativePaths:n,includeBasePath:r}=t;return n&&e?Ss(e,t):r?er:Es}function _s(e){return function(t,n){n.push(t.substring(e.length)||".");}}function Cs(e){return function(t,n,r){let i=t.substring(e.length)||".";r.every(s=>s(i,true))&&n.push(i);}}var Rs=(e,t)=>{t.push(e||".");},$s=(e,t,n)=>{let r=e||".";n.every(i=>i(r,true))&&t.push(r);},vs=()=>{};function Ns(e,t){let{includeDirs:n,filters:r,relativePaths:i}=t;return n?i?r&&r.length?Cs(e):_s(e):r&&r.length?$s:Rs:vs}var ks=(e,t,n,r)=>{r.every(i=>i(e,false))&&n.files++;},Ps=(e,t,n,r)=>{r.every(i=>i(e,false))&&t.push(e);},Ls=(e,t,n,r)=>{n.files++;},Os=(e,t)=>{t.push(e);},Fs=()=>{};function Is(e){let{excludeFiles:t,filters:n,onlyCounts:r}=e;return t?Fs:n&&n.length?r?ks:Ps:r?Ls:Os}var js=e=>e,Ds=()=>[""].slice(0,0);function Us(e){return e.group?Ds:js}var Bs=(e,t,n)=>{e.push({directory:t,files:n,dir:t});},Ms=()=>{};function Hs(e){return e.group?Bs:Ms}var qs=function(e,t,n){let{queue:r,fs:i,options:{suppressErrors:s}}=t;r.enqueue(),i.realpath(e,(o,a)=>{if(o)return r.dequeue(s?null:o,t);i.stat(a,(l,c)=>{if(l)return r.dequeue(s?null:l,t);if(c.isDirectory()&&nr(e,a,t))return r.dequeue(null,t);n(c,a),r.dequeue(null,t);});});},Gs=function(e,t,n){let{queue:r,fs:i,options:{suppressErrors:s}}=t;r.enqueue();try{let o=i.realpathSync(e),a=i.statSync(o);if(a.isDirectory()&&nr(e,o,t))return;n(a,o);}catch(o){if(!s)throw o}};function Vs(e,t){return !e.resolveSymlinks||e.excludeSymlinks?null:t?Gs:qs}function nr(e,t,n){if(n.options.useRealPaths)return Ws(t,n);let r=dirname(e),i=1;for(;r!==n.root&&i<2;){let s=n.symlinks.get(r);!!s&&(s===t||s.startsWith(t)||t.startsWith(s))?i++:r=dirname(r);}return n.symlinks.set(e,t),i>1}function Ws(e,t){return t.visited.includes(e+t.options.pathSeparator)}var zs=e=>e.counts,Ks=e=>e.groups,Xs=e=>e.paths,Js=e=>e.paths.slice(0,e.options.maxFiles),Ys=(e,t,n)=>(Re(t,n,e.counts,e.options.suppressErrors),null),Qs=(e,t,n)=>(Re(t,n,e.paths,e.options.suppressErrors),null),Zs=(e,t,n)=>(Re(t,n,e.paths.slice(0,e.options.maxFiles),e.options.suppressErrors),null),to=(e,t,n)=>(Re(t,n,e.groups,e.options.suppressErrors),null);function Re(e,t,n,r){t(e&&!r?e:null,n);}function eo(e,t){let{onlyCounts:n,group:r,maxFiles:i}=e;return n?t?zs:Ys:r?t?Ks:to:i?t?Js:Zs:t?Xs:Qs}var rr={withFileTypes:true},no=(e,t,n,r,i)=>{if(e.queue.enqueue(),r<0)return e.queue.dequeue(null,e);let{fs:s}=e;e.visited.push(t),e.counts.directories++,s.readdir(t||".",rr,(o,a=[])=>{i(a,n,r),e.queue.dequeue(e.options.suppressErrors?null:o,e);});},ro=(e,t,n,r,i)=>{let{fs:s}=e;if(r<0)return;e.visited.push(t),e.counts.directories++;let o=[];try{o=s.readdirSync(t||".",rr);}catch(a){if(!e.options.suppressErrors)throw a}i(o,n,r);};function io(e){return e?ro:no}var so=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));}},oo=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}},ao=class{aborted=false;abort(){this.aborted=true;}},ir=class{root;isSynchronous;state;joinPath;pushDirectory;pushFile;getArray;groupFiles;resolveSymlink;walkDirectory;callbackInvoker;constructor(e,t,n){this.isSynchronous=!n,this.callbackInvoker=eo(t,this.isSynchronous),this.root=Ze(e,t),this.state={root:xs(this.root)?this.root:this.root.slice(0,-1),paths:[""].slice(0,0),groups:[],counts:new oo,options:t,queue:new so((r,i)=>this.callbackInvoker(i,r,n)),symlinks:new Map,visited:[""].slice(0,0),controller:new ao,fs:t.fs||At},this.joinPath=As(this.root,t),this.pushDirectory=Ns(this.root,t),this.pushFile=Is(t),this.getArray=Us(t),this.groupFiles=Hs(t),this.resolveSymlink=Vs(t,this.isSynchronous),this.walkDirectory=io(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:i,resolveSymlinks:s,excludeSymlinks:o,exclude:a,maxFiles:l,signal:c,useRealPaths:u,pathSeparator:h},controller:d}=this.state;if(d.aborted||c&&c.aborted||l&&r.length>l)return;let b=this.getArray(this.state.paths);for(let w=0;w<e.length;++w){let E=e[w];if(E.isFile()||E.isSymbolicLink()&&!s&&!o){let _=this.joinPath(E.name,t);this.pushFile(_,b,this.state.counts,i);}else if(E.isDirectory()){let _=Ts(E.name,t,this.state.options.pathSeparator);if(a&&a(E.name,_))continue;this.pushDirectory(_,r,i),this.walkDirectory(this.state,_,_,n-1,this.walk);}else if(this.resolveSymlink&&E.isSymbolicLink()){let _=er(E.name,t);this.resolveSymlink(_,this.state,(v,x)=>{if(v.isDirectory()){if(x=Ze(x,this.state.options),a&&a(E.name,u?x:_+h))return;this.walkDirectory(this.state,x,u?x:_+h,n-1,this.walk);}else {x=u?x:_;let V=basename(x),Z=Ze(dirname(x),this.state.options);x=this.joinPath(V,Z),this.pushFile(x,b,this.state.counts,i);}});}}this.groupFiles(this.state.groups,t,b);}};function lo(e,t){return new Promise((n,r)=>{sr(e,t,(i,s)=>{if(i)return r(i);n(s);});})}function sr(e,t,n){new ir(e,t,n).start();}function co(e,t){return new ir(e,t).start()}var Qn=class{constructor(e,t){this.root=e,this.options=t;}withPromise(){return lo(this.root,this.options)}withCallback(e){sr(this.root,this.options,e);}sync(){return co(this.root,this.options)}},or=null;try{Yn.resolve("picomatch"),or=Yn("picomatch");}catch{}var ar=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 Qn(e||".",this.options)}withGlobFunction(e){return this.globFunction=e,this}crawlWithOptions(e,t){return this.options={...this.options,...t},new Qn(e||".",this.options)}glob(...e){return this.globFunction?this.globWithOptions(e):this.globWithOptions(e,{dot:true})}globWithOptions(e,...t){let n=this.globFunction||or;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(i=>r(i)),this}};var Ct=$t(Nr()),Mo=Array.isArray,Lr=process.platform==="win32",Ho=/^(\/?\.\.)+$/;function qo(e,t={}){let n=e.length,r=Array(n),i=Array(n),s=!t.noglobstar;for(let o=0;o<n;o++){let a=Or(e[o]);r[o]=a;let l=a.length,c=Array(l);for(let u=0;u<l;u++)c[u]=(0, Ct.default)(a[u],t);i[o]=c;}return o=>{let a=o.split("/");if(a[0]===".."&&Ho.test(o))return true;for(let l=0;l<e.length;l++){let c=r[l],u=i[l],h=a.length,d=Math.min(h,c.length),b=0;for(;b<d;){let w=c[b];if(w.includes("/"))return true;if(!u[b](a[b]))break;if(s&&w==="**")return true;b++;}if(b===h)return true}return false}}var Go=/^[A-Z]:\/$/i,Vo=Lr?e=>Go.test(e):e=>e==="/";function kr(e,t,n){if(e===t||t.startsWith(`${e}/`)){if(n){let i=Vo(e)?e.length:e.length+1;return (s,o)=>s.slice(i,o?-1:void 0)||"."}let r=t.slice(e.length+1);return r?(i,s)=>{if(i===".")return r;let o=`${r}/${i}`;return s?o.slice(0,-1):o}:(i,s)=>s&&i!=="."?i.slice(0,-1):i}return n?r=>posix.relative(e,r)||".":r=>posix.relative(e,`${t}/${r}`)||"."}function Wo(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.endsWith("/")&&r!==""?`${r}/`:r||"."}}var zo={parts:true};function Or(e){var t;let n=Ct.default.scan(e,zo);return !((t=n.parts)===null||t===void 0)&&t.length?n.parts:[e]}var Ko=/(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g,Xo=/(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g,Jo=e=>e.replace(Ko,"\\$&"),Yo=e=>e.replace(Xo,"\\$&"),Qo=Lr?Yo:Jo;function Zo(e,t){let n=Ct.default.scan(e);return n.isGlob||n.negated}function _t(...e){console.log(`[tinyglobby ${new Date().toLocaleTimeString("es")}]`,...e);}var ta=/^(\/?\.\.)+/,ea=/\\(?=[()[\]{}!*+?@|])/g,Ne=/\\/g;function fn(e,t,n,r,i){let s=e;e.endsWith("/")&&(s=e.slice(0,-1)),!s.endsWith("*")&&t&&(s+="/**");let o=Qo(n);Pr.isAbsolute(s.replace(ea,""))?s=posix.relative(o,s):s=posix.normalize(s);let a=ta.exec(s),l=Or(s);if(a?.[0]){let u=(a[0].length+1)/3,h=0,d=o.split("/");for(;h<u&&l[h+u]===d[d.length+h-u];)s=s.slice(0,(u-h-1)*3)+s.slice((u-h)*3+l[h+u].length+1)||".",h++;let b=posix.join(n,a[0].slice(h*3));!b.startsWith(".")&&r.root.length>b.length&&(r.root=b,r.depthOffset=-u+h);}if(!i&&r.depthOffset>=0){var c;(c=r.commonPath)!==null&&c!==void 0||(r.commonPath=l);let u=[],h=Math.min(r.commonPath.length,l.length);for(let d=0;d<h;d++){let b=l[d];if(b==="**"&&!l[d+1]){u.pop();break}if(b!==r.commonPath[d]||Zo(b)||d===l.length-1)break;u.push(b);}r.depthOffset=u.length,r.commonPath=u,r.root=u.length>0?posix.join(n,...u):n;}return s}function na({patterns:e=["**/*"],ignore:t=[],expandDirectories:n=true},r,i){typeof e=="string"&&(e=[e]),typeof t=="string"&&(t=[t]);let s=[],o=[];for(let a of t)a&&(a[0]!=="!"||a[1]==="(")&&o.push(fn(a,n,r,i,true));for(let a of e)a&&(a[0]!=="!"||a[1]==="("?s.push(fn(a,n,r,i,false)):(a[1]!=="!"||a[2]==="(")&&o.push(fn(a.slice(1),n,r,i,true)));return {match:s,ignore:o}}function ra(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];e[n]=t(r);}return e}function ia(e){return e?e instanceof URL?fileURLToPath(e).replace(Ne,"/"):Pr.resolve(e).replace(Ne,"/"):process.cwd().replace(Ne,"/")}function sa(e,t={}){let n=process.env.TINYGLOBBY_DEBUG?{...t,debug:true}:t,r=ia(n.cwd);if(n.debug&&_t("globbing with:",{patterns:e,options:n,cwd:r}),Array.isArray(e)&&e.length===0)return [{sync:()=>[],withPromise:async()=>[]},false];let i={root:r,commonPath:null,depthOffset:0},s=na({...n,patterns:e},r,i);n.debug&&_t("internal processing patterns:",s);let o={dot:n.dot,nobrace:n.braceExpansion===false,nocase:n.caseSensitiveMatch===false,noextglob:n.extglob===false,noglobstar:n.globstar===false,posix:true},a=(0, Ct.default)(s.match,{...o,ignore:s.ignore}),l=(0, Ct.default)(s.ignore,o),c=qo(s.match,o),u=kr(r,i.root,n.absolute),h=n.absolute?u:kr(r,i.root,true),d={filters:[n.debug?(E,_)=>{let v=u(E,_),x=a(v);return x&&_t(`matched ${v}`),x}:(E,_)=>a(u(E,_))],exclude:n.debug?(E,_)=>{let v=h(_,true),x=v!=="."&&!c(v)||l(v);return _t(x?`skipped ${_}`:`crawling ${_}`),x}:(E,_)=>{let v=h(_,true);return v!=="."&&!c(v)||l(v)},fs:n.fs?{readdir:n.fs.readdir||At__default.readdir,readdirSync:n.fs.readdirSync||At__default.readdirSync,realpath:n.fs.realpath||At__default.realpath,realpathSync:n.fs.realpathSync||At__default.realpathSync,stat:n.fs.stat||At__default.stat,statSync:n.fs.statSync||At__default.statSync}:void 0,pathSeparator:"/",relativePaths:true,resolveSymlinks:true,signal:n.signal};n.deep!==void 0&&(d.maxDepth=Math.round(n.deep-i.depthOffset)),n.absolute&&(d.relativePaths=false,d.resolvePaths=true,d.includeBasePath=true),n.followSymbolicLinks===false&&(d.resolveSymlinks=false,d.excludeSymlinks=true),n.onlyDirectories?(d.excludeFiles=true,d.includeDirs=true):n.onlyFiles===false&&(d.includeDirs=true),i.root=i.root.replace(Ne,"");let b=i.root;n.debug&&_t("internal properties:",i);let w=r!==b&&!n.absolute&&Wo(r,i.root);return [new ar(d).crawl(b),w]}async function Bt(e,t){if(e&&t?.patterns)throw new Error("Cannot pass patterns as both an argument and an option");let n=Mo(e)||typeof e=="string",r=n?t:e,i=n?e:e.patterns,[s,o]=sa(i,r);return o?ra(await s.withPromise(),o):s.withPromise()}var N=$t(Nt());var aa=/^(\d{14})(?:_([^.]+))?\.sql$/;function Fr(e){return e.config?.db?.driver==="sqlite"?"./sqlite-migrations/*.sql":"./migrations/*.sql"}function la(e){return rt__default.posix.dirname(Fr(e))}async function Mt(e){let t=rt__default.join(process.cwd(),"supabase"),n=await Bt([Fr(e)],{cwd:t,absolute:true}),r=[];for(let i of n){let s=rt__default.basename(i),o=aa.exec(s);if(!o)continue;let a=await U__default.readFile(i,"utf-8");r.push({version:o[1],name:o[2]??null,filename:s,path:i,sql:a});}return r.sort((i,s)=>i.version.localeCompare(s.version))}var ni="supabase/.temp/.translation-cache.json",ri=2;async function Ha(e,t){let n=await e.connection.introspect(),r=kn(n);await ii(e,{...t,dbHasTables:n.tables.length>0,dbFingerprint:r}),n.tables.length===0&&await Va(e);let i=await e.connection.introspect();oi(i,e);}async function qa(e){let t=await Bt(e.config.db?.seed?.sql_paths??["./seed.sql"],{cwd:rt__default.join(process.cwd(),"supabase"),absolute:true});return (await Promise.all(t.map(r=>U__default.readFile(r,"utf-8")))).flatMap(r=>splitSqlStatements(r))}async function Ga(e,t){let n=await qa(e);if(n.length===0)return 0;console.log(N.default.dim("Seeding database..."));try{return await e.connection.transaction(n),n.length}catch(r){let i="Fix `supabase/seed.sql`, then run `bun run dev --recreate` to reset and reseed.";throw new Error(`Seed failed and was rolled back: ${String(r.message??r)}
|
|
60
|
+
${i}`)}}async function Va(e){await Ga(e);}async function Wa(e){let t=await Bt(e.config?.db?.migrations?.schema_paths??["./schemas/*.sql"],{cwd:rt__default.join(process.cwd(),"supabase"),absolute:true}),n=await Promise.all(t.map(async r=>await U__default.readFile(r,"utf-8"))).then(r=>r.map(i=>i.split(`
|
|
61
61
|
`).filter(s=>s.trim().length>0&&!s.trim().startsWith("--")).join(`
|
|
62
62
|
`)).join(`
|
|
63
|
-
`));return n||""}async function
|
|
63
|
+
`));return n||""}async function ii(e,t){let n=await Wa(e);if(!(!n&&(await Mt(e)).length>0)&&!(!n&&!e.connection.config.baseSchema)){if(t?.dbHasTables&&await Ka(e,n,t.dbFingerprint)){console.log(N.default.dim("Schema unchanged \u2014 skipping translation."));return}try{let r=e.connection.createMigrator(n),i=await r.diff(),s=r.translationResult?.ast,o=await e.connection.introspect(),a=kn(o);if(i.plan.steps.length===0){await ti(e,n,s,a);return}await r.migratePlan(i.plan,{force:t?.force??!1}),Qa(i);let l=await e.connection.introspect();return await ti(e,n,s,kn(l)),console.log(""),Za(i),i}catch(r){if(String(r).includes("likely empty"))console.log(N.default.dim("Nothing to migrate."));else {console.error("Migration error: "+String(r));try{await e.connection.exec("rollback");}catch{}}}}}function za(e){return e.connection.config?.baseSchema??""}function si(e,t){let n=createHash("sha256");return n.update(JSON.stringify([za(e),t??""])),n.digest("hex")}function kn(e){let t=(r,i)=>[...r].sort((s,o)=>i(s).localeCompare(i(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 Ka(e,t,n){let r=e.connection;if(typeof r.updateDeparseInfo!="function")return false;let i=rt__default.join(process.cwd(),ni),s;try{s=await U__default.readFile(i,"utf-8");}catch{return false}let o;try{o=JSON.parse(s);}catch{return false}if(o.v!==ri||o.hash!==si(e,t)||!n||o.dbFingerprint!==n||!o.ast||typeof o.ast!="object")return false;try{let a=await Promise.resolve().then(()=>(Qr(),Yr)),l=o.ast,c=a.collectEnums(l),u=a.collectSchema(l,c),h=a.collectVariables(l),d=a.collectTableConstraints(l),b=a.collectComments(l),{policies:w,tables:E}=a.collectPolicies(l);return r.updateDeparseInfo({enums:c,rls:{tables:E,policies:w},schema:u,vars:h,tableConstraints:d,comments:b}),!0}catch{return false}}async function ti(e,t,n,r){if(!n||typeof n!="object")return;let i={v:ri,hash:si(e,t),dbFingerprint:r,ast:n},s=rt__default.join(process.cwd(),ni);try{await U__default.mkdir(rt__default.dirname(s),{recursive:!0}),await U__default.writeFile(s,JSON.stringify(i),"utf-8");}catch{}}function oi(e,t){console.log();let n=(i,s)=>{let o=l=>{let c=N.default.dim;return typeof l=="number"&&(l>=0&&(c=l>0?N.default.green:N.default.dim),l<0&&(c=N.default.red)),typeof l=="boolean"?l?N.default.green("\u2713"):N.default.red("\u2717"):c(String(l))},a=Object.entries(s).map(([l,c])=>`${l}: ${o(c)}`).join(N.default.dim(" / "));console.log(`${N.default.dim("[")} ${i} ${N.default.dim("]")} ${a}`);};n(N.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(N.default.green("AUTH"),{enabled:!!t.config.auth?.enabled,tables:ensureVar.Set(r.tables).size,policies:ensureVar.Array(r.policies).length});}function Xa(e,t){setTimeout(()=>{console.log(N.default.dim("Watching for changes...")),Ma.watch("./supabase/schemas").on("change",async r=>{console.log(),console.log(N.default.dim(`Schema changed: ${r}`)),await ii(e,t);let i=await e.connection.introspect();oi(i,e);});},200);}function Ja(e,t){let n=r=>r;return e.plan.steps.flatMap(r=>[r.description?n(`-- ${r.description}`):"",r.sql+`
|
|
64
64
|
`]).filter(r=>r.trim().length>0).join(`
|
|
65
|
-
`)}function
|
|
65
|
+
`)}function Ya(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 Qa(e,t){let n="./supabase/.temp/migrations";tt(n);let r=Ya(),i=Ja(e);ht(rt__default.join(n,r),i),console.log(N.default.dim(`Migration written to ${N.default.cyan(rt__default.join(n,r))}`));}function Za({diff:e}){if(typeof e=="string"){console.log(N.default.cyan(e));return}if(!e.has_changes)return;console.log(N.default.bgWhite(N.default.black(" Schema Diff "))),console.log();let t={added:{color:N.default.green,symbol:"+"},removed:{color:N.default.red,symbol:"-"},modified:{color:N.default.yellow,symbol:"~"}};if(e.tables.length>0){console.log(N.default.dim("Tables:"));for(let n of e.tables){let{color:r,symbol:i}=t[n.type];console.log(r(`${i} ${n.name}`));}console.log();}if(e.columns.length>0){console.log(N.default.dim("Columns:"));for(let n of e.columns){let{color:r,symbol:i}=t[n.type],s="";n.changes&&(s=Object.entries(n.changes).map(([o,a])=>`${o}: ${a.from} \u2192 ${a.to}`).join(", ")),console.log(r(`${i} ${n.table}.${n.name}${s?` (${s})`:""}`));}console.log();}if(e.indexes.length>0){console.log(N.default.dim("Indexes:"));for(let n of e.indexes){let{color:r,symbol:i}=t[n.type];console.log(r(`${i} ${n.name} on ${n.table}`));}console.log();}if(e.foreign_keys.length>0){console.log(N.default.dim("Foreign Keys:"));for(let n of e.foreign_keys){let{color:r,symbol:i}=t[n.type];console.log(r(`${i} ${n.table}.${n.column} \u2192 ${n.ref_table}.${n.ref_column}`));}console.log();}}function Ie(e){return e.dialect==="postgres"?"pg":e.config?.ddlDialect==="sqlite"?"sqlite":"pg-flat"}function ai(e){return e==="sqlite"?{schema_migrations:"migrations",seed_files:null}:e==="pg-flat"?{schema_migrations:'"supabase_migrations.schema_migrations"',seed_files:'"supabase_migrations.seed_files"'}:{schema_migrations:"supabase_migrations.schema_migrations",seed_files:"supabase_migrations.seed_files"}}function Pn(e){return `'${e.replace(/'/g,"''")}'`}function tl(e){return `'${`{${e.map(r=>`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`).join(",")}}`.replace(/'/g,"''")}'`}function el(e){return e==="sqlite"?[`CREATE TABLE IF NOT EXISTS migrations (
|
|
66
66
|
version TEXT NOT NULL PRIMARY KEY,
|
|
67
67
|
statements TEXT,
|
|
68
68
|
name TEXT
|
|
@@ -73,9 +73,15 @@ ${i}`)}}async function Da(e){await Ia(e);}async function ja(e){let t=await Mt(e.
|
|
|
73
73
|
)`,`CREATE TABLE IF NOT EXISTS supabase_migrations.seed_files (
|
|
74
74
|
path text NOT NULL PRIMARY KEY,
|
|
75
75
|
hash text NOT NULL
|
|
76
|
-
)`]}function
|
|
77
|
-
`)+";",i=await
|
|
78
|
-
|
|
76
|
+
)`]}function li(e,t){let{schema_migrations:n}=ai(e),r=t.name===null?"NULL":Pn(t.name),i=e==="pg"?tl(t.statements):Pn(JSON.stringify(t.statements));return `INSERT INTO ${n} (version, statements, name) VALUES (${Pn(t.version)}, ${i}, ${r})`}function nl(e){let{schema_migrations:t}=ai(e);return `SELECT version FROM ${t} ORDER BY version ASC`}async function rl(e,t){if(e.dialect==="postgres"||e.config.ddlDialect==="sqlite")return t;let r=await e.translateDdl(t);return typeof r=="string"?r:r.ddl??t}function il(e){return e.split(/;\s*(?:\n|$)/).map(t=>t.trim()).filter(t=>t.length>0)}async function ci(e){let t=Ie(e),r=el(t).map(s=>s.trim()).join(`;
|
|
77
|
+
`)+";",i=await rl(e,r);for(let s of il(i))await e.exec(s);}async function ui(e){let t=Ie(e);return ((await e.exec(nl(t)))?.rows??[]).map(r=>r.version)}var On=["anon","authenticated","service_role"];function sl(e){return e==="service_role"?"NOLOGIN BYPASSRLS":"NOLOGIN"}function Fn(e){return e.size===0?"":`DO $$ BEGIN${[...e].map(n=>`
|
|
78
|
+
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '${n}') THEN
|
|
79
|
+
CREATE ROLE ${n} ${sl(n)};
|
|
80
|
+
END IF;`).join("")}
|
|
81
|
+
END $$;
|
|
82
|
+
`}Fn(new Set(On));function pi(e,t){return e?e.quoted?e.value===t:e.value.toLowerCase()===t:false}function nt(e){return e?.quoted?e.value:e?.value.toLowerCase()}function ol(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 al(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 ll(e,t){let n=/^\$[A-Za-z_][A-Za-z0-9_]*\$|^\$\$/.exec(e.slice(t))?.[0];if(!n)return;let r=t+n.length,i=e.indexOf(n,r);return i===-1?e.length:i+n.length}function mi(e){let t=[],n=0;for(;n<e.length;){let r=e[n],i=e[n+1];if(/\s/.test(r)){n++;continue}if(r==="-"&&i==="-"){for(n+=2;n<e.length&&e[n]!==`
|
|
83
|
+
`;)n++;continue}if(r==="/"&&i==="*"){for(n+=2;n<e.length&&!(e[n]==="*"&&e[n+1]==="/");)n++;n=n<e.length?n+2:n;continue}if(r==="'"){n=al(e,n);continue}if(r==="$"){let s=ll(e,n);if(s!==void 0){n=s;continue}}if(r==='"'){let{token:s,end:o}=ol(e,n);t.push(s),n=o;continue}if(r===","||r===";"){t.push({value:r,quoted:false}),n++;continue}if(/[A-Za-z_]/.test(r)){let s=n;for(n++;n<e.length&&/[A-Za-z0-9_$]/.test(e[n]);)n++;t.push({value:e.slice(s,n).toLowerCase(),quoted:false});continue}n++;}return t}function cl(e,t){let n=nt(e[t]),r=nt(e[t+1]);if((n==="create"||n==="alter")&&(r==="role"||r==="user"||r==="group"))return e[t+2]}function ul(e){let t=new Set,n=mi(e);for(let r=0;r<n.length;r++){if(nt(n[r])!=="create")continue;let i=cl(n,r);for(let s of On)pi(i,s)&&t.add(s);}return t}function Ln(e,t,n){let r=new Set([";","as","by","check","for","granted","in","on","option","using","where","with"]);for(let i=t;i<e.length;i++){let s=nt(e[i]);if(!s||r.has(s))return;for(let o of On)pi(e[i],o)&&n.add(o);}}function fl(e){let t=[],n=[];for(let r of e){if(nt(r)===";"){n.length>0&&t.push(n),n=[];continue}n.push(r);}return n.length>0&&t.push(n),t}function fi(e,t){return e.some(n=>nt(n)===t)}function pl(e){let t=new Set,n=fl(mi(e));for(let r of n){let i=nt(r[0]);for(let a=0;a<r.length;a++){let l=nt(r[a]);l==="to"&&(fi(r,"grant")||fi(r,"policy")||nt(r[a-1])==="owner")&&Ln(r,a+1,t),l==="from"&&i==="revoke"&&Ln(r,a+1,t);}let s=r.findIndex(a=>nt(a)==="to"),o=r.findIndex(a=>nt(a)==="on");i==="grant"&&s>1&&(o===-1||s<o)&&Ln(r,1,t);}return t}function hi(e){let t=ul(e);return new Set([...pl(e)].filter(n=>!t.has(n)))}async function ml(e){await dl(e),await ci(e.connection);let t=new Set(await ui(e.connection)),n=await Mt(e),r=Ie(e.connection),i=[],s=[];for(let o of n){if(t.has(o.version)){s.push(o);continue}let a=we(o.sql),l;if(r==="pg-flat"){let u=await e.connection.translateDdl(o.sql),h=typeof u=="string"?u:u.ddl??"";l=we(h);}else l=a;let c=li(r,{version:o.version,name:o.name,statements:a});if(r==="pg"){let u=Fn(hi(o.sql));u&&await e.connection.exec(u);}await e.connection.transaction([...l,c],{intent:"migration"}),i.push(o);}return n.length>0&&r!=="sqlite"&&await hl(e,n),{applied:i,skipped:s}}async function hl(e,t){let n=t.map(o=>o.sql).join(`
|
|
84
|
+
`);if(!n.trim())return;let r=e.connection;if(typeof r.translateDdl!="function"||typeof r.updateDeparseInfo!="function")return;let i=await r.translateDdl(n),s=r.config?.translation?.deparse??{};r.updateDeparseInfo({...s,...i});}async function dl(e){let t=e.connection.config?.baseSchema;if(!t||!t.trim())return;let n=e.connection,r=t;if(n.dialect==="sqlite"&&n.config.ddlDialect!=="sqlite"&&n.translateDdl){let i=await n.translateDdl(t);r=typeof i=="string"?i:i.ddl??t;}for(let i of we(r))try{await n.exec(i);}catch{}}/*! Bundled license information:
|
|
79
85
|
|
|
80
86
|
smol-toml/dist/error.js:
|
|
81
87
|
smol-toml/dist/util.js:
|
|
@@ -113,4 +119,4 @@ smol-toml/dist/index.js:
|
|
|
113
119
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
114
120
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
115
121
|
*)
|
|
116
|
-
*/export{
|
|
122
|
+
*/export{ml as applyPendingMigrations,os as createApi,ls as ensureInitialStructure,Ha as ensureSchema,Mt as listMigrationFiles,la as migrationsDir,Xa as watchSchema};
|