@supabase/lite 0.6.1 → 0.6.2-next.1
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/LIMITATIONS.md +1 -1
- package/README.md +15 -6
- package/STATUS.md +5 -3
- package/dist/cli/index.js +105 -105
- package/dist/cli/lib.js +35 -35
- package/dist/db/postgres/pglite/PgliteConnection.js +23 -23
- package/dist/index.d.ts +1 -0
- package/dist/index.js +36 -36
- package/package.json +1 -1
package/dist/cli/lib.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import'pgsql-deparser';import*as
|
|
1
|
+
import'pgsql-deparser';import*as it from'node:path';import it__default from'node:path';import Pi from'node:os';import he 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 M from'node:fs/promises';import M__default from'node:fs/promises';import {createHash}from'node:crypto';import {parse}from'dotenv';import'node:url';import*as Ct from'fs';import Ct__default from'fs';import jr,{posix,sep,basename,dirname,resolve,normalize,relative}from'path';import {fileURLToPath}from'url';import {createRequire}from'module';import rl 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 rt from'node:path';import rt__default from'node
|
|
|
9
9
|
};
|
|
10
10
|
} catch {}
|
|
11
11
|
|
|
12
|
-
var Si=Object.create;var Me=Object.defineProperty;var xi=Object.getOwnPropertyDescriptor;var Ei=Object.getOwnPropertyNames;var Ti=Object.getPrototypeOf,Ai=Object.prototype.hasOwnProperty;var L=(e,t)=>()=>(e&&(t=e(e=0)),t);var dt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),_i=(e,t)=>{for(var n in t)Me(e,n,{get:t[n],enumerable:true});},Ci=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ei(t))!Ai.call(e,i)&&i!==n&&Me(e,i,{get:()=>t[i],enumerable:!(r=xi(t,i))||r.enumerable});return e};var Nt=(e,t,n)=>(n=e!=null?Si(Ti(e)):{},Ci(Me(n,"default",{value:e,enumerable:true}),e));var kt=dt((ql,qe)=>{var ge=process||{},Un=ge.argv||[],de=ge.env||{},ki=!(de.NO_COLOR||Un.includes("--no-color"))&&(!!de.FORCE_COLOR||Un.includes("--color")||ge.platform==="win32"||(ge.stdout||{}).isTTY&&de.TERM!=="dumb"||!!de.CI),Pi=(e,t,n=e)=>r=>{let i=""+r,s=i.indexOf(t,e.length);return ~s?e+Li(i,t,n,s)+t:e+i+t},Li=(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)},Bn=(e=ki)=>{let t=e?Pi:()=>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")}};qe.exports=Bn();qe.exports.createColors=Bn;});var Dt=dt((Vu,gr)=>{var pr="[^\\\\/]",po="(?=.)",mr="[^/]",sn="(?:\\/|$)",hr="(?:^|\\/)",on=`\\.{1,2}${sn}`,mo="(?!\\.)",ho=`(?!${hr}${on})`,go=`(?!\\.{0,1}${sn})`,yo=`(?!${on})`,bo="[^.\\/]",wo=`${mr}*?`,So="/",dr={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:po,QMARK:mr,END_ANCHOR:sn,DOTS_SLASH:on,NO_DOT:mo,NO_DOTS:ho,NO_DOT_SLASH:go,NO_DOTS_SLASH:yo,QMARK_NO_DOT:bo,STAR:wo,START_ANCHOR:hr,SEP:So},xo={...dr,SLASH_LITERAL:"[\\\\/]",QMARK:pr,STAR:`${pr}*?`,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:"\\"},Eo={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"};gr.exports={MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:Eo,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?xo:dr}};});var Ut=dt(X=>{var{REGEX_BACKSLASH:To,REGEX_REMOVE_BACKSLASH:Ao,REGEX_SPECIAL_CHARS:_o,REGEX_SPECIAL_CHARS_GLOBAL:Co}=Dt();X.isObject=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);X.hasRegexChars=e=>_o.test(e);X.isRegexChar=e=>e.length===1&&X.hasRegexChars(e);X.escapeRegex=e=>e.replace(Co,"\\$1");X.toPosixSlashes=e=>e.replace(To,"/");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(Ao,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 Ar=dt((Wu,Tr)=>{var yr=Ut(),{CHAR_ASTERISK:an,CHAR_AT:Ro,CHAR_BACKWARD_SLASH:Bt,CHAR_COMMA:$o,CHAR_DOT:ln,CHAR_EXCLAMATION_MARK:cn,CHAR_FORWARD_SLASH:Er,CHAR_LEFT_CURLY_BRACE:un,CHAR_LEFT_PARENTHESES:fn,CHAR_LEFT_SQUARE_BRACKET:No,CHAR_PLUS:vo,CHAR_QUESTION_MARK:br,CHAR_RIGHT_CURLY_BRACE:ko,CHAR_RIGHT_PARENTHESES:wr,CHAR_RIGHT_SQUARE_BRACKET:Po}=Dt(),Sr=e=>e===Er||e===Bt,xr=e=>{e.isPrefix!==true&&(e.depth=e.isGlobstar?1/0:1);},Lo=(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,y=false,b=false,E=false,T=false,N=false,S=false,H=false,J=false,q=false,B=0,W,A,C={value:"",depth:0,isGlob:false},m=()=>c>=r,G=()=>l.charCodeAt(c+1),x=()=>(W=A,l.charCodeAt(++c));for(;c<r;){A=x();let P;if(A===Bt){S=C.backslashes=true,A=x(),A===un&&(N=true);continue}if(N===true||A===un){for(B++;m()!==true&&(A=x());){if(A===Bt){S=C.backslashes=true,x();continue}if(A===un){B++;continue}if(N!==true&&A===ln&&(A=x())===ln){if(d=C.isBrace=true,b=C.isGlob=true,q=true,i===true)continue;break}if(N!==true&&A===$o){if(d=C.isBrace=true,b=C.isGlob=true,q=true,i===true)continue;break}if(A===ko&&(B--,B===0)){N=false,d=C.isBrace=true,q=true;break}}if(i===true)continue;break}if(A===Er){if(s.push(c),o.push(C),C={value:"",depth:0,isGlob:false},q===true)continue;if(W===ln&&c===u+1){u+=2;continue}h=c+1;continue}if(n.noext!==true&&(A===vo||A===Ro||A===an||A===br||A===cn)===true&&G()===fn){if(b=C.isGlob=true,E=C.isExtglob=true,q=true,A===cn&&c===u&&(J=true),i===true){for(;m()!==true&&(A=x());){if(A===Bt){S=C.backslashes=true,A=x();continue}if(A===wr){b=C.isGlob=true,q=true;break}}continue}break}if(A===an){if(W===an&&(T=C.isGlobstar=true),b=C.isGlob=true,q=true,i===true)continue;break}if(A===br){if(b=C.isGlob=true,q=true,i===true)continue;break}if(A===No){for(;m()!==true&&(P=x());){if(P===Bt){S=C.backslashes=true,x();continue}if(P===Po){y=C.isBracket=true,b=C.isGlob=true,q=true;break}}if(i===true)continue;break}if(n.nonegate!==true&&A===cn&&c===u){H=C.negated=true,u++;continue}if(n.noparen!==true&&A===fn){if(b=C.isGlob=true,i===true){for(;m()!==true&&(A=x());){if(A===fn){S=C.backslashes=true,A=x();continue}if(A===wr){q=true;break}}continue}break}if(b===true){if(q=true,i===true)continue;break}}n.noext===true&&(E=false,b=false);let k=l,p="",f="";u>0&&(p=l.slice(0,u),l=l.slice(u),h-=u),k&&b===true&&h>0?(k=l.slice(0,h),f=l.slice(h)):b===true?(k="",f=l):k=l,k&&k!==""&&k!=="/"&&k!==l&&Sr(k.charCodeAt(k.length-1))&&(k=k.slice(0,-1)),n.unescape===true&&(f&&(f=yr.removeBackslashes(f)),k&&S===true&&(k=yr.removeBackslashes(k)));let Y={prefix:p,input:e,start:u,base:k,glob:f,isBrace:d,isBracket:y,isGlob:b,isExtglob:E,isGlobstar:T,negated:H,negatedExtglob:J};if(n.tokens===true&&(Y.maxDepth=0,Sr(A)||o.push(C),Y.tokens=o),n.parts===true||n.tokens===true){let P;for(let F=0;F<s.length;F++){let st=P?P+1:u,Q=s[F],ut=e.slice(st,Q);n.tokens&&(F===0&&u!==0?(o[F].isPrefix=true,o[F].value=p):o[F].value=ut,xr(o[F]),Y.maxDepth+=o[F].depth),(F!==0||ut!=="")&&a.push(ut),P=Q;}if(P&&P+1<e.length){let F=e.slice(P+1);a.push(F),n.tokens&&(o[o.length-1].value=F,xr(o[o.length-1]),Y.maxDepth+=o[o.length-1].depth);}Y.slashes=s,Y.parts=a;}return Y};Tr.exports=Lo;});var Rr=dt((zu,Cr)=>{var ve=Dt(),it=Ut(),{MAX_LENGTH:ke,POSIX_REGEX_SOURCE:Oo,REGEX_NON_SPECIAL_CHARS:Fo,REGEX_SPECIAL_CHARS_BACKREF:Io,REPLACEMENTS:_r}=ve,jo=(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},At=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`,pn=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a string");e=_r[e]||e;let n={...t},r=typeof n.maxLength=="number"?Math.min(ke,n.maxLength):ke,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=ve.globChars(n.windows),c=ve.extglobChars(l),{DOT_LITERAL:u,PLUS_LITERAL:h,SLASH_LITERAL:d,ONE_CHAR:y,DOTS_SLASH:b,NO_DOT:E,NO_DOT_SLASH:T,NO_DOTS_SLASH:N,QMARK:S,QMARK_NO_DOT:H,STAR:J,START_ANCHOR:q}=l,B=w=>`(${a}(?:(?!${q}${w.dot?b:u}).)*?)`,W=n.dot?"":E,A=n.dot?S:H,C=n.bash===true?B(n):J;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=[],x=[],k=[],p=s,f,Y=()=>m.index===i-1,P=m.peek=(w=1)=>e[m.index+w],F=m.advance=()=>e[++m.index]||"",st=()=>e.slice(m.index+1),Q=(w="",O=0)=>{m.consumed+=w,m.index+=O;},ut=w=>{m.output+=w.output!=null?w.output:w.value,Q(w.value);},bi=()=>{let w=1;for(;P()==="!"&&(P(2)!=="("||P(3)==="?");)F(),m.start++,w++;return w%2===0?false:(m.negated=true,m.start++,true)},le=w=>{m[w]++,k.push(w);},ht=w=>{m[w]--,k.pop();},$=w=>{if(p.type==="globstar"){let O=m.braces>0&&(w.type==="comma"||w.type==="brace"),g=w.extglob===true||G.length&&(w.type==="pipe"||w.type==="paren");w.type!=="slash"&&w.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&&w.type!=="paren"&&(G[G.length-1].inner+=w.value),(w.value||w.output)&&ut(w),p&&p.type==="text"&&w.type==="text"){p.output=(p.output||p.value)+w.value,p.value+=w.value;return}w.prev=p,o.push(w),p=w;},ce=(w,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;le("parens"),$({type:w,value:O,output:m.output?"":y}),$({type:"paren",extglob:true,value:F(),output:R}),G.push(g);},wi=w=>{let O=w.close+(n.capture?")":""),g;if(w.type==="negate"){let R=C;if(w.inner&&w.inner.length>1&&w.inner.includes("/")&&(R=B(n)),(R!==C||Y()||/^\)+$/.test(st()))&&(O=w.close=`)$))${R}`),w.inner.includes("*")&&(g=st())&&/^\.[^\\/.]+$/.test(g)){let I=pn(g,{...t,fastpaths:false}).output;O=w.close=`)${I})${R})`;}w.prev.type==="bos"&&(m.negatedExtglob=true);}$({type:"paren",extglob:true,value:f,output:O}),ht("parens");};if(n.fastpaths!==false&&!/(^[*!]|[/()[\]{}"])/.test(e)){let w=false,O=e.replace(Io,(g,R,I,z,M,Be)=>z==="\\"?(w=true,g):z==="?"?R?R+z+(M?S.repeat(M.length):""):Be===0?A+(M?S.repeat(M.length):""):S.repeat(I.length):z==="."?u.repeat(I.length):z==="*"?R?R+z+(M?C:""):C:R?g:`\\${g}`);return w===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(;!Y();){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=Oo[z];if(M){p.value=I+M,m.backtrack=true,F(),!s.output&&o.indexOf(p)===1&&(s.output=y);continue}}}(f==="["&&P()!==":"||f==="-"&&P()==="]")&&(f=`\\${f}`),f==="]"&&(p.value==="["||p.value==="[^")&&(f=`\\${f}`),n.posix===true&&f==="!"&&p.value==="["&&(f="^"),p.value+=f,ut({value:f});continue}if(m.quotes===1&&f!=='"'){f=it.escapeRegex(f),p.value+=f,ut({value:f});continue}if(f==='"'){m.quotes=m.quotes===1?0:1,n.keepQuotes===true&&$({type:"text",value:f});continue}if(f==="("){le("parens"),$({type:"paren",value:f});continue}if(f===")"){if(m.parens===0&&n.strictBrackets===true)throw new SyntaxError(At("opening","("));let g=G[G.length-1];if(g&&m.parens===g.parens+1){wi(G.pop());continue}$({type:"paren",value:f,output:m.parens?")":"\\)"}),ht("parens");continue}if(f==="["){if(n.nobracket===true||!st().includes("]")){if(n.nobracket!==true&&n.strictBrackets===true)throw new SyntaxError(At("closing","]"));f=`\\${f}`;}else le("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(At("opening","["));$({type:"text",value:f,output:`\\${f}`});continue}ht("brackets");let g=p.value.slice(1);if(p.posix!==true&&g[0]==="^"&&!g.includes("/")&&(f=`/${f}`),p.value+=f,ut({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){le("braces");let g={type:"brace",value:f,output:"(",outputIndex:m.output.length,tokensIndex:m.tokens.length};x.push(g),$(g);continue}if(f==="}"){let g=x[x.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=jo(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}),ht("braces"),x.pop();continue}if(f==="|"){G.length>0&&G[G.length-1].conditions++,$({type:"text",value:f});continue}if(f===","){let g=f,R=x[x.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=x[x.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)!=="?"){ce("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:H});continue}$({type:"qmark",value:f,output:S});continue}if(f==="!"){if(n.noextglob!==true&&P()==="("&&(P(2)!=="?"||!/[!=<:]/.test(P(3)))){ce("negate",f);continue}if(n.nonegate!==true&&m.index===0){bi();continue}}if(f==="+"){if(n.noextglob!==true&&P()==="("&&P(2)!=="?"){ce("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=Fo.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,Q(f);continue}let w=st();if(n.noextglob!==true&&/^\([^?]/.test(w)){ce("star",f);continue}if(p.type==="star"){if(n.noglobstar===true){Q(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||w[0]&&w[0]!=="/")){$({type:"star",value:f,output:""});continue}let M=m.braces>0&&(g.type==="comma"||g.type==="brace"),Be=G.length&&(g.type==="pipe"||g.type==="paren");if(!I&&g.type!=="paren"&&!M&&!Be){$({type:"star",value:f,output:""});continue}for(;w.slice(0,3)==="/**";){let ue=e[m.index+4];if(ue&&ue!=="/")break;w=w.slice(3),Q("/**",3);}if(g.type==="bos"&&Y()){p.type="globstar",p.value+=f,p.output=B(n),m.output=p.output,m.globstar=true,Q(f);continue}if(g.type==="slash"&&g.prev.type!=="bos"&&!z&&Y()){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,Q(f);continue}if(g.type==="slash"&&g.prev.type!=="bos"&&w[0]==="/"){let ue=w[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}${ue})`,p.value+=f,m.output+=g.output+p.output,m.globstar=true,Q(f+F()),$({type:"slash",value:"/",output:""});continue}if(g.type==="bos"&&w[0]==="/"){p.type="globstar",p.value+=f,p.output=`(?:^|${d}|${B(n)}${d})`,m.output=p.output,m.globstar=true,Q(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,Q(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+=T,p.output+=T):n.dot===true?(m.output+=N,p.output+=N):(m.output+=W,p.output+=W),P()!=="*"&&(m.output+=y,p.output+=y)),$(O);}for(;m.brackets>0;){if(n.strictBrackets===true)throw new SyntaxError(At("closing","]"));m.output=it.escapeLast(m.output,"["),ht("brackets");}for(;m.parens>0;){if(n.strictBrackets===true)throw new SyntaxError(At("closing",")"));m.output=it.escapeLast(m.output,"("),ht("parens");}for(;m.braces>0;){if(n.strictBrackets===true)throw new SyntaxError(At("closing","}"));m.output=it.escapeLast(m.output,"{"),ht("braces");}if(n.strictSlashes!==true&&(p.type==="star"||p.type==="bracket")&&$({type:"maybe_slash",value:"",output:`${d}?`}),m.backtrack===true){m.output="";for(let w of m.tokens)m.output+=w.output!=null?w.output:w.value,w.suffix&&(m.output+=w.suffix);}return m};pn.fastpaths=(e,t)=>{let n={...t},r=typeof n.maxLength=="number"?Math.min(ke,n.maxLength):ke,i=e.length;if(i>r)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${r}`);e=_r[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:y}=ve.globChars(n.windows),b=n.dot?u:c,E=n.dot?h:c,T=n.capture?"":"?:",N={negated:false,prefix:""},S=n.bash===true?".*?":d;n.capture&&(S=`(${S})`);let H=W=>W.noglobstar===true?S:`(${T}(?:(?!${y}${W.dot?l:s}).)*?)`,J=W=>{switch(W){case "*":return `${b}${a}${S}`;case ".*":return `${s}${a}${S}`;case "*.*":return `${b}${S}${s}${a}${S}`;case "*/*":return `${b}${S}${o}${a}${E}${S}`;case "**":return b+H(n);case "**/*":return `(?:${b}${H(n)}${o})?${E}${a}${S}`;case "**/*.*":return `(?:${b}${H(n)}${o})?${E}${S}${s}${a}${S}`;case "**/.*":return `(?:${b}${H(n)}${o})?${s}${a}${S}`;default:{let A=/^(.*?)\.(\w+)$/.exec(W);if(!A)return;let C=J(A[1]);return C?C+s+A[2]:void 0}}},q=it.removePrefix(e,N),B=J(q);return B&&n.strictSlashes!==true&&(B+=`${o}?`),B};Cr.exports=pn;});var vr=dt((Ku,Nr)=>{var Do=Ar(),mn=Rr(),$r=Ut(),Uo=Dt(),Bo=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 y of u){let b=y(d);if(b)return b}return false}}let r=Bo(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:y,output:b}=D.test(u,o,t,{glob:e,posix:s}),E={glob:e,state:a,regex:o,posix:s,input:u,output:b,match:y,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?$r.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($r.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)):mn(e,{...t,fastpaths:false});D.scan=(e,t)=>Do(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=mn.fastpaths(e,t)),i.output||(i=mn(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=Uo;Nr.exports=D;});var Or=dt((Xu,Lr)=>{var kr=vr(),Mo=Ut();function Pr(e,t,n=false){return t&&(t.windows===null||t.windows===void 0)&&(t={...t,windows:Mo.isWindows()}),kr(e,t,n)}Object.assign(Pr,kr);Lr.exports=Pr;});function Vt(e){if("String"in e)return e.String.sval}function wt(e){return e.map(Vt).filter(t=>t!=null)}function Vr(e){return Object.keys(e)[0]}function Gr(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 Fe=L(()=>{});function Wr(e){let t=e.toLowerCase();return ["serial","serial4","bigserial","serial8","smallserial","serial2"].includes(t)}function zr(e){let t=e.toLowerCase();return ["varchar","character varying","char","character","bpchar"].includes(t)}function Kr(e){let t=e.toLowerCase();return ["numeric","decimal"].includes(t)}var gn,Ie,ya,yn=L(()=>{Fe();gn=class extends Error{},Ie=class extends gn{constructor(n,r){super(r??`Unsupported node type: ${Vr(n)}`);this.node=n;}};ya={CreateEnumStmt:{react:"ignore"},CreateDomainStmt:{react:"warn"},CreateSeqStmt:{react:"ignore"},AlterSeqStmt:{react:"ignore"},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(ya));});var Z,je,Xr=L(()=>{Fe();yn();Z=class extends Ie{constructor(t,n){super(t,`Unsupported expression: ${n}`);}},je=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 Z({[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 Z({[n]:t},`deparseValue: ${n}`)}A_Expr(t){if(t.kind==="AEXPR_OP"){let n=t.name?.[0],r=n?Vt(n):void 0;if(!r)throw new Z({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 Z({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]?Vt(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 Z({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 Z({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 Z({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 y="ResTarget"in d?d.ResTarget:void 0;if(y?.val){let b=this.deparseValue(y.val);Array.isArray(b)?s.push(...b.map(String)):b!=null&&b!==""&&s.push(String(b));}}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 Z({FuncCall:t},`FuncCall: ${wt(t.funcname??[]).join(".")}`)}ColumnRef(t){let n=wt(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 Z({A_Const:t},"A_Const: unknown variant")}TypeCast(t){if(!t.arg)throw new Z({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=wt(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]?Vt(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 De,Jr=L(()=>{De=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 Gt,bn=L(()=>{Gt=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 V,ct=L(()=>{bn();V=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 Gt(this.context.table,this.context.column,t,n)}quoteIfNeeded(t){return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)?t:`"${t}"`}};});var St,Ue=L(()=>{ct();St=class extends V{get sqliteType(){return "INTEGER"}};});var Wt,wn=L(()=>{Ue();Wt=class extends St{constructor(t){super({...t,isSerial:true});}};});function ba(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 zt,Sn=L(()=>{ct();zt=class extends V{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(!ba(t,this.numericPrecision))return this.validationFail(`Does not fit numeric(${n}, ${r}).`,"Patch rows within numeric precision.")}return this.validationPass()}};});var j,et=L(()=>{ct();j=class extends V{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 Kt,xn=L(()=>{ct();Kt=class extends V{get sqliteType(){return "BLOB"}};});var Xt,En=L(()=>{ct();Xt=class extends V{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}checkConstraint(){return `${this.context.column} IN (0, 1)`}serialize(t){if(this.isNullish(t))return t;if(t===true||t===1)return 1;if(t===false||t===0)return 0;throw this.checkError("boolean_range",t)}deserialize(t){if(this.isNullish(t)||t===true||t===false)return t;if(typeof t=="number"&&Number.isFinite(t)){if(t===1)return true;if(t===0)return false}return t===1n?true:t===0n?false:t==="1"||t==="true"?true:t==="0"||t==="false"?false:t}validateStorage(t){return this.isNullish(t)?this.validationPass():t===1||t===0?this.validationPass():this.validationFail("Expected 0 or 1.","Patch rows with boolean values.")}};});function Yr(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var Jt,Tn=L(()=>{ct();Jt=class extends V{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=Yr(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."):Yr(t).ok?this.validationPass():this.validationFail("Invalid JSON text.","Patch rows with valid JSON.")}};});function wa(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 Yt,An=L(()=>{et();Yt=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"||!wa(t)?this.validationFail("Invalid date.","Patch rows with YYYY-MM-DD dates."):this.validationPass()}};});function Sa(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 Qt,_n=L(()=>{et();Qt=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"||!Sa(t)?this.validationFail("Invalid time.","Patch rows with HH:MM[:SS] times."):this.validationPass()}};});function xa(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),y=l===null||c!==null&&l<=15&&c<=59;return h&&d&&y}var Zt,Cn=L(()=>{et();Zt=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"||!xa(t)?this.validationFail("Invalid timestamp.","Patch rows with ISO timestamps."):this.validationPass()}};});var te,Rn=L(()=>{et();te=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 ee,$n=L(()=>{et();ee=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 Qr(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var $t,Nn=L(()=>{ct();$t=class extends V{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=Qr(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=Qr(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 Zr(e){return Ta.test(e.toLowerCase())}var Ea,Ta,ne,vn=L(()=>{et();Ea="????????-????-????-????-????????????",Ta=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;ne=class extends j{get isShimBacked(){return true}checkConstraint(){let t=this.quoteIfNeeded(this.context.column);return `${t} IS NULL OR ${t} GLOB '${Ea}'`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string")throw this.checkError("uuid_format",t);let n=t.toLowerCase();if(!Zr(n))throw this.checkError("uuid_format",t);return n}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!Zr(t)?this.validationFail("Invalid UUID.","Patch rows with valid UUIDs."):this.validationPass()}};});function Aa(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 _a(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 Ca(e){if(!e.includes(":"))return false;try{return new URL(`http://[${e}]/`),!0}catch{return false}}function ti(e){let t=Aa(e);return t?_a(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=32:Ca(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=128:false:false}var re,kn=L(()=>{et();re=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(!ti(n))throw this.checkError("inet_format",t);return n}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!ti(t.trim())?this.validationFail("Invalid inet address.","Patch rows with valid inet strings."):this.validationPass()}};});var ie,Pn=L(()=>{et();ie=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 se(e,t){if(t?.isArray){let r=se(e,{...t,isArray:false});return new $t(e,r)}if(t?.enumValues)return new ee(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=se(i);return new $t(e,s)}return $a.has(n)?new Wt(e):Ra.has(n)?new St(e):Pa.has(n)?new Xt(e):La.has(n)?new Jt(e):ja.has(n)?new Yt(e):Da.has(n)?new Qt(e):Ua.has(n)?new Zt(e):Ba.has(n)?new te(e):ka.has(n)?new Kt(e):Na.has(n)?new zt(e,t?.numericPrecision):Oa.has(n)?new ne(e):Fa.has(n)?new j(e,63):Ia.has(n)?new re(e):va.has(n)?new j(e,t?.lengthConstraint):new ie(e)}var Ra,$a,Na,va,ka,Pa,La,Oa,Fa,Ia,ja,Da,Ua,Ba,ei=L(()=>{Ue();wn();Sn();et();xn();En();Tn();An();_n();Cn();Rn();$n();Nn();vn();kn();Pn();Ra=new Set(["int2","smallint","int4","integer","int","int8","bigint"]),$a=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]),Na=new Set(["float4","real","float8","double precision","numeric","decimal"]),va=new Set(["text","varchar","character varying","char","character","bpchar"]),ka=new Set(["bytea"]),Pa=new Set(["bool","boolean"]),La=new Set(["json","jsonb"]),Oa=new Set(["uuid"]),Fa=new Set(["name"]),Ia=new Set(["inet"]),ja=new Set(["date"]),Da=new Set(["time","timetz","time without time zone","time with time zone"]),Ua=new Set(["timestamp","timestamptz","timestamp without time zone","timestamp with time zone"]),Ba=new Set(["interval"]);});var ni=L(()=>{});var oe,ri=L(()=>{oe=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 ii=L(()=>{ct();bn();Ue();wn();Sn();et();xn();En();Tn();An();_n();Cn();Rn();$n();Nn();vn();kn();Pn();ei();ni();ri();});var si={};_i(si,{_resetWarnedMissingToClauseForTests:()=>Ma,collectComments:()=>za,collectEnums:()=>Ha,collectPolicies:()=>Va,collectSchema:()=>Ga,collectTableConstraints:()=>Wa,collectVariables:()=>qa});function Ma(){Ln.clear();}function Ha(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=wt(r.typeName??[]).join(".");if(!i||!r.vals)continue;let s=wt(r.vals);t.set(i.toLowerCase(),s);}return t}function qa(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=Gr(r.args?.[0]??{});t.set(i,{value:s,local:r.is_local});}return t}function Va(e){let t=new je,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 T of s.roles??[])if("RoleSpec"in T){let N=T.RoleSpec;N.roletype==="ROLESPEC_PUBLIC"?N.location===-1&&(d=true):N.roletype==="ROLESPEC_CSTRING"&&N.rolename&&h.push(N.rolename);}let y=s.qual?t.deparse(s.qual):void 0,b=s.with_check?t.deparse(s.with_check):void 0;if(d){let T=a?`${a}.${o}`:o,N=s.policy_name??"",S=`${T}::${N}`;if(!Ln.has(S)){Ln.add(S);let H=JSON.stringify(y)+JSON.stringify(b);/\{\{auth\.(uid|jwt|role)/i.test(H)||console.warn(`[supalite] policy "${N}" on "${T}" has no TO clause \u2014 applies to all roles (PUBLIC). For clarity, prefer an explicit \`TO <role>\` clause (e.g. \`TO authenticated\`).`);}}let E=new De({name:s.policy_name??"",table:o,schema:a,command:c,permissive:u,roles:h,using:y,withCheck:b});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 Ga(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 oe(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(x=>x.String?.sval||x.String?.str).filter(Boolean),d=h&&(h.length===2&&h[0]==="pg_catalog"?h[1]:h[0]);if(!d)continue;let y=!!c.typeName?.arrayBounds?.length,b=Array.isArray(c.typeName?.typmods)?c.typeName.typmods:[],E=x=>b[x]?.A_Const?.ival?.ival??b[x]?.A_Const?.val?.ival?.ival,T={isArray:y};if(zr(d)&&b.length>0){let x=E(0);typeof x=="number"&&x>0&&(T.lengthConstraint=x);}if(Kr(d)&&b.length>=2){let x=E(0),k=E(1);typeof x=="number"&&typeof k=="number"&&x>0&&k>=0&&(T.numericPrecision={precision:x,scale:k});}let N=t.get(d.toLowerCase());N&&(T.enumValues=N);let S=Array.isArray(c.constraints)?c.constraints:[],H=S.some(x=>x.Constraint?.contype==="CONSTR_PRIMARY"),J=Wr(d)||S.some(x=>x.Constraint?.contype==="CONSTR_IDENTITY"),q=S.some(x=>x.Constraint?.contype==="CONSTR_NOTNULL"),B=S.find(x=>x.Constraint?.contype==="CONSTR_UNIQUE"),W=S.find(x=>x.Constraint?.contype==="CONSTR_GENERATED"),A=S.find(x=>x.Constraint?.contype==="CONSTR_FOREIGN"),C=S.find(x=>x.Constraint?.contype==="CONSTR_CHECK"),m;if(A){let x=A.Constraint,k=x.pktable?.relname,p=x.pktable?.schemaname,f=x.pk_attrs?.[0]?.String?.sval;k&&f&&(m={refSchema:p,refTable:k,refColumn:f,constraintName:x.conname||void 0});}let G={schema:o,table:s,column:u,pgTypeName:d,nullable:!q&&!H,defaultValue:null,defaultFn:null,isPrimaryKey:H,isUnique:!!B,isSerial:J,isGenerated:!!W,fkRef:m,hasCheck:!!C,checkConstraintName:C?.Constraint?.conname||void 0,uniqueConstraintName:B?.Constraint?.conname||void 0};a.set(u,se(G,T));}n.set(`${o}.${s}`,a);}return n}function Wa(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(y=>y.String?.sval??y.String?.str).filter(Boolean),h=(l.pk_attrs??[]).map(y=>y.String?.sval??y.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 za(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 Ln,oi=L(()=>{Xr();Fe();Jr();ii();yn();Ln=new Set;});function tt(e,t){fe.existsSync(e)||(fe.mkdirSync(e,{recursive:true}),t?.());}function gt(e,t,n){fe.existsSync(e)||(fe.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(Ri.homedir(),".lite")}static projectDir(){return rt__default.join(process.cwd(),"supabase")}deleteAll(t=false){try{fe.rmSync(this.root,{recursive:!0});}catch(n){if(!t)throw n}this.ensureRoot();}delete(t,n=false){try{fe.unlinkSync(rt__default.join(this.root,t));}catch(r){if(!n)throw r}}write(t,n,r=false){try{this.ensureRoot(),fe.writeFileSync(rt__default.join(this.root,t),n);}catch(i){if(!r)throw i}}read(t,n=false){try{return fe.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 he=class{root;constructor(t){this.root=t??rt__default.join(Ri.homedir(),".lite","auth"),tt(this.root);}async getItem(t){try{return fe.readFileSync(rt__default.join(this.root,t+".json"),"utf8")}catch{return null}}async setItem(t,n){fe.writeFileSync(rt__default.join(this.root,t+".json"),n);}async removeItem(t){try{fe.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 he(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 Et=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 ft={config_dir:"supabase",default_db_url:"file:supabase/.temp/data.db",default_db_dir:"supabase/.temp/data"};var jt=Nt(kt());function Oi(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return [n.length,n.pop().length+1]}function Fi(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 Ai=Object.create;var Ve=Object.defineProperty;var _i=Object.getOwnPropertyDescriptor;var Ci=Object.getOwnPropertyNames;var Ri=Object.getPrototypeOf,vi=Object.prototype.hasOwnProperty;var L=(e,t)=>()=>(e&&(t=e(e=0)),t);var gt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),$i=(e,t)=>{for(var n in t)Ve(e,n,{get:t[n],enumerable:true});},Ni=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ci(t))!vi.call(e,i)&&i!==n&&Ve(e,i,{get:()=>t[i],enumerable:!(r=_i(t,i))||r.enumerable});return e};var kt=(e,t,n)=>(n=e!=null?Ai(Ri(e)):{},Ni(Ve(n,"default",{value:e,enumerable:true}),e));var Lt=gt((Zl,We)=>{var we=process||{},Vn=we.argv||[],be=we.env||{},Ii=!(be.NO_COLOR||Vn.includes("--no-color"))&&(!!be.FORCE_COLOR||Vn.includes("--color")||we.platform==="win32"||(we.stdout||{}).isTTY&&be.TERM!=="dumb"||!!be.CI),Di=(e,t,n=e)=>r=>{let i=""+r,s=i.indexOf(t,e.length);return ~s?e+ji(i,t,n,s)+t:e+i+t},ji=(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)},Gn=(e=Ii)=>{let t=e?Di:()=>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")}};We.exports=Gn();We.exports.createColors=Gn;});var Mt=gt((of,br)=>{var hr="[^\\\\/]",xo="(?=.)",dr="[^/]",ln="(?:\\/|$)",gr="(?:^|\\/)",cn=`\\.{1,2}${ln}`,Eo="(?!\\.)",To=`(?!${gr}${cn})`,Ao=`(?!\\.{0,1}${ln})`,_o=`(?!${cn})`,Co="[^.\\/]",Ro=`${dr}*?`,vo="/",yr={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:xo,QMARK:dr,END_ANCHOR:ln,DOTS_SLASH:cn,NO_DOT:Eo,NO_DOTS:To,NO_DOT_SLASH:Ao,NO_DOTS_SLASH:_o,QMARK_NO_DOT:Co,STAR:Ro,START_ANCHOR:gr,SEP:vo},$o={...yr,SLASH_LITERAL:"[\\\\/]",QMARK:hr,STAR:`${hr}*?`,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:"\\"},No={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"};br.exports={MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:No,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?$o:yr}};});var Ht=gt(J=>{var{REGEX_BACKSLASH:ko,REGEX_REMOVE_BACKSLASH:Po,REGEX_SPECIAL_CHARS:Lo,REGEX_SPECIAL_CHARS_GLOBAL:Oo}=Mt();J.isObject=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);J.hasRegexChars=e=>Lo.test(e);J.isRegexChar=e=>e.length===1&&J.hasRegexChars(e);J.escapeRegex=e=>e.replace(Oo,"\\$1");J.toPosixSlashes=e=>e.replace(ko,"/");J.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};J.removeBackslashes=e=>e.replace(Po,t=>t==="\\"?"":t);J.escapeLast=(e,t,n)=>{let r=e.lastIndexOf(t,n);return r===-1?e:e[r-1]==="\\"?J.escapeLast(e,t,r-1):`${e.slice(0,r)}\\${e.slice(r)}`};J.removePrefix=(e,t={})=>{let n=e;return n.startsWith("./")&&(n=n.slice(2),t.prefix="./"),n};J.wrapOutput=(e,t={},n={})=>{let r=n.contains?"":"^",i=n.contains?"":"$",s=`${r}(?:${e})${i}`;return t.negated===true&&(s=`(?:^(?!${s}).*$)`),s};J.basename=(e,{windows:t}={})=>{let n=e.split(t?/[\\/]/:"/"),r=n[n.length-1];return r===""?n[n.length-2]:r};});var Cr=gt((lf,_r)=>{var wr=Ht(),{CHAR_ASTERISK:un,CHAR_AT:Fo,CHAR_BACKWARD_SLASH:qt,CHAR_COMMA:Io,CHAR_DOT:fn,CHAR_EXCLAMATION_MARK:pn,CHAR_FORWARD_SLASH:Ar,CHAR_LEFT_CURLY_BRACE:mn,CHAR_LEFT_PARENTHESES:hn,CHAR_LEFT_SQUARE_BRACKET:Do,CHAR_PLUS:jo,CHAR_QUESTION_MARK:Sr,CHAR_RIGHT_CURLY_BRACE:Bo,CHAR_RIGHT_PARENTHESES:xr,CHAR_RIGHT_SQUARE_BRACKET:Uo}=Mt(),Er=e=>e===Ar||e===qt,Tr=e=>{e.isPrefix!==true&&(e.depth=e.isGlobstar?1/0:1);},Mo=(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,g=false,b=false,E=false,T=false,N=false,S=false,q=false,K=false,U=false,j=0,G,A,C={value:"",depth:0,isGlob:false},m=()=>c>=r,W=()=>l.charCodeAt(c+1),x=()=>(G=A,l.charCodeAt(++c));for(;c<r;){A=x();let P;if(A===qt){S=C.backslashes=true,A=x(),A===mn&&(N=true);continue}if(N===true||A===mn){for(j++;m()!==true&&(A=x());){if(A===qt){S=C.backslashes=true,x();continue}if(A===mn){j++;continue}if(N!==true&&A===fn&&(A=x())===fn){if(d=C.isBrace=true,b=C.isGlob=true,U=true,i===true)continue;break}if(N!==true&&A===Io){if(d=C.isBrace=true,b=C.isGlob=true,U=true,i===true)continue;break}if(A===Bo&&(j--,j===0)){N=false,d=C.isBrace=true,U=true;break}}if(i===true)continue;break}if(A===Ar){if(s.push(c),o.push(C),C={value:"",depth:0,isGlob:false},U===true)continue;if(G===fn&&c===u+1){u+=2;continue}h=c+1;continue}if(n.noext!==true&&(A===jo||A===Fo||A===un||A===Sr||A===pn)===true&&W()===hn){if(b=C.isGlob=true,E=C.isExtglob=true,U=true,A===pn&&c===u&&(K=true),i===true){for(;m()!==true&&(A=x());){if(A===qt){S=C.backslashes=true,A=x();continue}if(A===xr){b=C.isGlob=true,U=true;break}}continue}break}if(A===un){if(G===un&&(T=C.isGlobstar=true),b=C.isGlob=true,U=true,i===true)continue;break}if(A===Sr){if(b=C.isGlob=true,U=true,i===true)continue;break}if(A===Do){for(;m()!==true&&(P=x());){if(P===qt){S=C.backslashes=true,x();continue}if(P===Uo){g=C.isBracket=true,b=C.isGlob=true,U=true;break}}if(i===true)continue;break}if(n.nonegate!==true&&A===pn&&c===u){q=C.negated=true,u++;continue}if(n.noparen!==true&&A===hn){if(b=C.isGlob=true,i===true){for(;m()!==true&&(A=x());){if(A===hn){S=C.backslashes=true,A=x();continue}if(A===xr){U=true;break}}continue}break}if(b===true){if(U=true,i===true)continue;break}}n.noext===true&&(E=false,b=false);let k=l,p="",f="";u>0&&(p=l.slice(0,u),l=l.slice(u),h-=u),k&&b===true&&h>0?(k=l.slice(0,h),f=l.slice(h)):b===true?(k="",f=l):k=l,k&&k!==""&&k!=="/"&&k!==l&&Er(k.charCodeAt(k.length-1))&&(k=k.slice(0,-1)),n.unescape===true&&(f&&(f=wr.removeBackslashes(f)),k&&S===true&&(k=wr.removeBackslashes(k)));let Y={prefix:p,input:e,start:u,base:k,glob:f,isBrace:d,isBracket:g,isGlob:b,isExtglob:E,isGlobstar:T,negated:q,negatedExtglob:K};if(n.tokens===true&&(Y.maxDepth=0,Er(A)||o.push(C),Y.tokens=o),n.parts===true||n.tokens===true){let P;for(let F=0;F<s.length;F++){let ot=P?P+1:u,Q=s[F],ft=e.slice(ot,Q);n.tokens&&(F===0&&u!==0?(o[F].isPrefix=true,o[F].value=p):o[F].value=ft,Tr(o[F]),Y.maxDepth+=o[F].depth),(F!==0||ft!=="")&&a.push(ft),P=Q;}if(P&&P+1<e.length){let F=e.slice(P+1);a.push(F),n.tokens&&(o[o.length-1].value=F,Tr(o[o.length-1]),Y.maxDepth+=o[o.length-1].depth);}Y.slashes=s,Y.parts=a;}return Y};_r.exports=Mo;});var $r=gt((cf,vr)=>{var Oe=Mt(),st=Ht(),{MAX_LENGTH:Fe,POSIX_REGEX_SOURCE:Ho,REGEX_NON_SPECIAL_CHARS:qo,REGEX_SPECIAL_CHARS_BACKREF:Vo,REPLACEMENTS:Rr}=Oe,Go=(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=>st.escapeRegex(i)).join("..")}return n},_t=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`,dn=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a string");e=Rr[e]||e;let n={...t},r=typeof n.maxLength=="number"?Math.min(Fe,n.maxLength):Fe,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=Oe.globChars(n.windows),c=Oe.extglobChars(l),{DOT_LITERAL:u,PLUS_LITERAL:h,SLASH_LITERAL:d,ONE_CHAR:g,DOTS_SLASH:b,NO_DOT:E,NO_DOT_SLASH:T,NO_DOTS_SLASH:N,QMARK:S,QMARK_NO_DOT:q,STAR:K,START_ANCHOR:U}=l,j=w=>`(${a}(?:(?!${U}${w.dot?b:u}).)*?)`,G=n.dot?"":E,A=n.dot?S:q,C=n.bash===true?j(n):K;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=st.removePrefix(e,m),i=e.length;let W=[],x=[],k=[],p=s,f,Y=()=>m.index===i-1,P=m.peek=(w=1)=>e[m.index+w],F=m.advance=()=>e[++m.index]||"",ot=()=>e.slice(m.index+1),Q=(w="",O=0)=>{m.consumed+=w,m.index+=O;},ft=w=>{m.output+=w.output!=null?w.output:w.value,Q(w.value);},Ei=()=>{let w=1;for(;P()==="!"&&(P(2)!=="("||P(3)==="?");)F(),m.start++,w++;return w%2===0?false:(m.negated=true,m.start++,true)},fe=w=>{m[w]++,k.push(w);},dt=w=>{m[w]--,k.pop();},v=w=>{if(p.type==="globstar"){let O=m.braces>0&&(w.type==="comma"||w.type==="brace"),y=w.extglob===true||W.length&&(w.type==="pipe"||w.type==="paren");w.type!=="slash"&&w.type!=="paren"&&!O&&!y&&(m.output=m.output.slice(0,-p.output.length),p.type="star",p.value="*",p.output=C,m.output+=p.output);}if(W.length&&w.type!=="paren"&&(W[W.length-1].inner+=w.value),(w.value||w.output)&&ft(w),p&&p.type==="text"&&w.type==="text"){p.output=(p.output||p.value)+w.value,p.value+=w.value;return}w.prev=p,o.push(w),p=w;},pe=(w,O)=>{let y={...c[O],conditions:1,inner:""};y.prev=p,y.parens=m.parens,y.output=m.output;let R=(n.capture?"(":"")+y.open;fe("parens"),v({type:w,value:O,output:m.output?"":g}),v({type:"paren",extglob:true,value:F(),output:R}),W.push(y);},Ti=w=>{let O=w.close+(n.capture?")":""),y;if(w.type==="negate"){let R=C;if(w.inner&&w.inner.length>1&&w.inner.includes("/")&&(R=j(n)),(R!==C||Y()||/^\)+$/.test(ot()))&&(O=w.close=`)$))${R}`),w.inner.includes("*")&&(y=ot())&&/^\.[^\\/.]+$/.test(y)){let I=dn(y,{...t,fastpaths:false}).output;O=w.close=`)${I})${R})`;}w.prev.type==="bos"&&(m.negatedExtglob=true);}v({type:"paren",extglob:true,value:f,output:O}),dt("parens");};if(n.fastpaths!==false&&!/(^[*!]|[/()[\]{}"])/.test(e)){let w=false,O=e.replace(Vo,(y,R,I,z,H,qe)=>z==="\\"?(w=true,y):z==="?"?R?R+z+(H?S.repeat(H.length):""):qe===0?A+(H?S.repeat(H.length):""):S.repeat(I.length):z==="."?u.repeat(I.length):z==="*"?R?R+z+(H?C:""):C:R?y:`\\${y}`);return w===true&&(n.unescape===true?O=O.replace(/\\/g,""):O=O.replace(/\\+/g,y=>y.length%2===0?"\\\\":y?"\\":"")),O===e&&n.contains===true?(m.output=e,m):(m.output=st.wrapOutput(O,m,t),m)}for(;!Y();){if(f=F(),f==="\0")continue;if(f==="\\"){let y=P();if(y==="/"&&n.bash!==true||y==="."||y===";")continue;if(!y){f+="\\",v({type:"text",value:f});continue}let R=/^\\+/.exec(ot()),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 y=p.value.slice(1);if(y.includes("[")&&(p.posix=true,y.includes(":"))){let R=p.value.lastIndexOf("["),I=p.value.slice(0,R),z=p.value.slice(R+2),H=Ho[z];if(H){p.value=I+H,m.backtrack=true,F(),!s.output&&o.indexOf(p)===1&&(s.output=g);continue}}}(f==="["&&P()!==":"||f==="-"&&P()==="]")&&(f=`\\${f}`),f==="]"&&(p.value==="["||p.value==="[^")&&(f=`\\${f}`),n.posix===true&&f==="!"&&p.value==="["&&(f="^"),p.value+=f,ft({value:f});continue}if(m.quotes===1&&f!=='"'){f=st.escapeRegex(f),p.value+=f,ft({value:f});continue}if(f==='"'){m.quotes=m.quotes===1?0:1,n.keepQuotes===true&&v({type:"text",value:f});continue}if(f==="("){fe("parens"),v({type:"paren",value:f});continue}if(f===")"){if(m.parens===0&&n.strictBrackets===true)throw new SyntaxError(_t("opening","("));let y=W[W.length-1];if(y&&m.parens===y.parens+1){Ti(W.pop());continue}v({type:"paren",value:f,output:m.parens?")":"\\)"}),dt("parens");continue}if(f==="["){if(n.nobracket===true||!ot().includes("]")){if(n.nobracket!==true&&n.strictBrackets===true)throw new SyntaxError(_t("closing","]"));f=`\\${f}`;}else fe("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(_t("opening","["));v({type:"text",value:f,output:`\\${f}`});continue}dt("brackets");let y=p.value.slice(1);if(p.posix!==true&&y[0]==="^"&&!y.includes("/")&&(f=`/${f}`),p.value+=f,ft({value:f}),n.literalBrackets===false||st.hasRegexChars(y))continue;let R=st.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){fe("braces");let y={type:"brace",value:f,output:"(",outputIndex:m.output.length,tokensIndex:m.tokens.length};x.push(y),v(y);continue}if(f==="}"){let y=x[x.length-1];if(n.nobrace===true||!y){v({type:"text",value:f,output:f});continue}let R=")";if(y.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=Go(z,n),m.backtrack=true;}if(y.comma!==true&&y.dots!==true){let I=m.output.slice(0,y.outputIndex),z=m.tokens.slice(y.tokensIndex);y.value=y.output="\\{",f=R="\\}",m.output=I;for(let H of z)m.output+=H.output||H.value;}v({type:"brace",value:f,output:R}),dt("braces"),x.pop();continue}if(f==="|"){W.length>0&&W[W.length-1].conditions++,v({type:"text",value:f});continue}if(f===","){let y=f,R=x[x.length-1];R&&k[k.length-1]==="braces"&&(R.comma=true,y="|"),v({type:"comma",value:f,output:y});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 y=x[x.length-1];p.type="dots",p.output+=f,p.value+=f,y.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)!=="?"){pe("qmark",f);continue}if(p&&p.type==="paren"){let R=P(),I=f;(p.value==="("&&!/[!=<:]/.test(R)||R==="<"&&!/<([!=]|\w+>)/.test(ot()))&&(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:q});continue}v({type:"qmark",value:f,output:S});continue}if(f==="!"){if(n.noextglob!==true&&P()==="("&&(P(2)!=="?"||!/[!=<:]/.test(P(3)))){pe("negate",f);continue}if(n.nonegate!==true&&m.index===0){Ei();continue}}if(f==="+"){if(n.noextglob!==true&&P()==="("&&P(2)!=="?"){pe("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 y=qo.exec(ot());y&&(f+=y[0],m.index+=y[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,Q(f);continue}let w=ot();if(n.noextglob!==true&&/^\([^?]/.test(w)){pe("star",f);continue}if(p.type==="star"){if(n.noglobstar===true){Q(f);continue}let y=p.prev,R=y.prev,I=y.type==="slash"||y.type==="bos",z=R&&(R.type==="star"||R.type==="globstar");if(n.bash===true&&(!I||w[0]&&w[0]!=="/")){v({type:"star",value:f,output:""});continue}let H=m.braces>0&&(y.type==="comma"||y.type==="brace"),qe=W.length&&(y.type==="pipe"||y.type==="paren");if(!I&&y.type!=="paren"&&!H&&!qe){v({type:"star",value:f,output:""});continue}for(;w.slice(0,3)==="/**";){let me=e[m.index+4];if(me&&me!=="/")break;w=w.slice(3),Q("/**",3);}if(y.type==="bos"&&Y()){p.type="globstar",p.value+=f,p.output=j(n),m.output=p.output,m.globstar=true,Q(f);continue}if(y.type==="slash"&&y.prev.type!=="bos"&&!z&&Y()){m.output=m.output.slice(0,-(y.output+p.output).length),y.output=`(?:${y.output}`,p.type="globstar",p.output=j(n)+(n.strictSlashes?")":"|$)"),p.value+=f,m.globstar=true,m.output+=y.output+p.output,Q(f);continue}if(y.type==="slash"&&y.prev.type!=="bos"&&w[0]==="/"){let me=w[1]!==void 0?"|$":"";m.output=m.output.slice(0,-(y.output+p.output).length),y.output=`(?:${y.output}`,p.type="globstar",p.output=`${j(n)}${d}|${d}${me})`,p.value+=f,m.output+=y.output+p.output,m.globstar=true,Q(f+F()),v({type:"slash",value:"/",output:""});continue}if(y.type==="bos"&&w[0]==="/"){p.type="globstar",p.value+=f,p.output=`(?:^|${d}|${j(n)}${d})`,m.output=p.output,m.globstar=true,Q(f+F()),v({type:"slash",value:"/",output:""});continue}m.output=m.output.slice(0,-p.output.length),p.type="globstar",p.output=j(n),p.value+=f,m.output+=p.output,m.globstar=true,Q(f);continue}let O={type:"star",value:f,output:C};if(n.bash===true){O.output=".*?",(p.type==="bos"||p.type==="slash")&&(O.output=G+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+=T,p.output+=T):n.dot===true?(m.output+=N,p.output+=N):(m.output+=G,p.output+=G),P()!=="*"&&(m.output+=g,p.output+=g)),v(O);}for(;m.brackets>0;){if(n.strictBrackets===true)throw new SyntaxError(_t("closing","]"));m.output=st.escapeLast(m.output,"["),dt("brackets");}for(;m.parens>0;){if(n.strictBrackets===true)throw new SyntaxError(_t("closing",")"));m.output=st.escapeLast(m.output,"("),dt("parens");}for(;m.braces>0;){if(n.strictBrackets===true)throw new SyntaxError(_t("closing","}"));m.output=st.escapeLast(m.output,"{"),dt("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 w of m.tokens)m.output+=w.output!=null?w.output:w.value,w.suffix&&(m.output+=w.suffix);}return m};dn.fastpaths=(e,t)=>{let n={...t},r=typeof n.maxLength=="number"?Math.min(Fe,n.maxLength):Fe,i=e.length;if(i>r)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${r}`);e=Rr[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:g}=Oe.globChars(n.windows),b=n.dot?u:c,E=n.dot?h:c,T=n.capture?"":"?:",N={negated:false,prefix:""},S=n.bash===true?".*?":d;n.capture&&(S=`(${S})`);let q=G=>G.noglobstar===true?S:`(${T}(?:(?!${g}${G.dot?l:s}).)*?)`,K=G=>{switch(G){case "*":return `${b}${a}${S}`;case ".*":return `${s}${a}${S}`;case "*.*":return `${b}${S}${s}${a}${S}`;case "*/*":return `${b}${S}${o}${a}${E}${S}`;case "**":return b+q(n);case "**/*":return `(?:${b}${q(n)}${o})?${E}${a}${S}`;case "**/*.*":return `(?:${b}${q(n)}${o})?${E}${S}${s}${a}${S}`;case "**/.*":return `(?:${b}${q(n)}${o})?${s}${a}${S}`;default:{let A=/^(.*?)\.(\w+)$/.exec(G);if(!A)return;let C=K(A[1]);return C?C+s+A[2]:void 0}}},U=st.removePrefix(e,N),j=K(U);return j&&n.strictSlashes!==true&&(j+=`${o}?`),j};vr.exports=dn;});var Pr=gt((uf,kr)=>{var Wo=Cr(),gn=$r(),Nr=Ht(),zo=Mt(),Ko=e=>e&&typeof e=="object"&&!Array.isArray(e),B=(e,t,n=false)=>{if(Array.isArray(e)){let u=e.map(d=>B(d,t,n));return d=>{for(let g of u){let b=g(d);if(b)return b}return false}}let r=Ko(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?B.compileRe(e,t):B.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=B(i.ignore,u,n);}let c=(u,h=false)=>{let{isMatch:d,match:g,output:b}=B.test(u,o,t,{glob:e,posix:s}),E={glob:e,state:a,regex:o,posix:s,input:u,output:b,match:g,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};B.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?Nr.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=B.matchBase(e,t,n,i):a=t.exec(l)),{isMatch:!!a,match:a,output:l}};B.matchBase=(e,t,n)=>(t instanceof RegExp?t:B.makeRe(t,n)).test(Nr.basename(e));B.isMatch=(e,t,n)=>B(t,n)(e);B.parse=(e,t)=>Array.isArray(e)?e.map(n=>B.parse(n,t)):gn(e,{...t,fastpaths:false});B.scan=(e,t)=>Wo(e,t);B.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=B.toRegex(a,t);return r===true&&(l.state=e),l};B.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=gn.fastpaths(e,t)),i.output||(i=gn(e,t)),B.compileRe(i,t,n,r)};B.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 /$^/}};B.constants=zo;kr.exports=B;});var Ir=gt((ff,Fr)=>{var Lr=Pr(),Xo=Ht();function Or(e,t,n=false){return t&&(t.windows===null||t.windows===void 0)&&(t={...t,windows:Xo.isWindows()}),Lr(e,t,n)}Object.assign(Or,Lr);Fr.exports=Or;});function zt(e){if("String"in e)return e.String.sval}function mt(e){return e.map(zt).filter(t=>t!=null)}function Wr(e){return Object.keys(e)[0]}function zr(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 Be=L(()=>{});function Kr(e){let t=e.toLowerCase();return ["serial","serial4","bigserial","serial8","smallserial","serial2"].includes(t)}function Xr(e){let t=e.toLowerCase();return ["varchar","character varying","char","character","bpchar"].includes(t)}function Jr(e){let t=e.toLowerCase();return ["numeric","decimal"].includes(t)}var wn,Ue,_a,Sn=L(()=>{Be();wn=class extends Error{},Ue=class extends wn{constructor(n,r){super(r??`Unsupported node type: ${Wr(n)}`);this.node=n;}};_a={CreateEnumStmt:{react:"ignore"},CreateDomainStmt:{react:"warn"},CreateSeqStmt:{react:"ignore"},AlterSeqStmt:{react:"ignore"},CreateSchemaStmt:{react:"warn"},CreatePolicyStmt:{react:"ignore"},AlterPolicyStmt:{react:"ignore"},PartitionElem:{react:"error"},PartitionCmd:{react:"error"},VariableSetStmt:{react:"ignore"},CompositeTypeStmt:{react:"error"},AlterEnumStmt:{react:"error"},AlterObjectSchemaStmt:{react:"error"},AlterOwnerStmt:{react:"error"},AlterTypeStmt:{react:"error"},AlterFunctionStmt:{react:"error"},AlterDefaultPrivilegesStmt:{react:"error"},GrantStmt:{react:"error"},GrantRoleStmt:{react:"error"},CopyStmt:{react:"error"},CreateCastStmt:{react:"error"},AlterOpFamilyStmt:{react:"error"},AlterOperatorStmt:{react:"error"},TruncateStmt:{react:"error"},A_Indirection:{react:"error"},XmlExpr:{react:"error"},XmlSerialize:{react:"error"},RangeTableSample:{react:"error"},GroupingSet:{react:"error"}},new Map(Object.entries(_a));});var Z,Me,Yr=L(()=>{Be();Sn();Z=class extends Ue{constructor(t,n){super(t,`Unsupported expression: ${n}`);}},Me=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 Z({[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 Z({[n]:t},`deparseValue: ${n}`)}A_Expr(t){if(t.kind==="AEXPR_OP"){let n=t.name?.[0],r=n?zt(n):void 0;if(!r)throw new Z({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 Z({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]?zt(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 Z({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 Z({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 Z({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 g="ResTarget"in d?d.ResTarget:void 0;if(g?.val){let b=this.deparseValue(g.val);Array.isArray(b)?s.push(...b.map(String)):b!=null&&b!==""&&s.push(String(b));}}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 Z({FuncCall:t},`FuncCall: ${mt(t.funcname??[]).join(".")}`)}ColumnRef(t){let n=mt(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 Z({A_Const:t},"A_Const: unknown variant")}TypeCast(t){if(!t.arg)throw new Z({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=mt(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]?zt(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 $t,Qr=L(()=>{$t=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 Kt,xn=L(()=>{Kt=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 V,ut=L(()=>{xn();V=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 Kt(this.context.table,this.context.column,t,n)}quoteIfNeeded(t){return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)?t:`"${t}"`}};});var St,He=L(()=>{ut();St=class extends V{get sqliteType(){return "INTEGER"}};});var Xt,En=L(()=>{He();Xt=class extends St{constructor(t){super({...t,isSerial:true});}};});function Ca(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 Jt,Tn=L(()=>{ut();Jt=class extends V{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(!Ca(t,this.numericPrecision))return this.validationFail(`Does not fit numeric(${n}, ${r}).`,"Patch rows within numeric precision.")}return this.validationPass()}};});var D,et=L(()=>{ut();D=class extends V{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 Yt,An=L(()=>{ut();Yt=class extends V{get sqliteType(){return "BLOB"}};});var Qt,_n=L(()=>{ut();Qt=class extends V{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}checkConstraint(){return `${this.context.column} IN (0, 1)`}serialize(t){if(this.isNullish(t))return t;if(t===true||t===1)return 1;if(t===false||t===0)return 0;throw this.checkError("boolean_range",t)}deserialize(t){if(this.isNullish(t)||t===true||t===false)return t;if(typeof t=="number"&&Number.isFinite(t)){if(t===1)return true;if(t===0)return false}return t===1n?true:t===0n?false:t==="1"||t==="true"?true:t==="0"||t==="false"?false:t}validateStorage(t){return this.isNullish(t)?this.validationPass():t===1||t===0?this.validationPass():this.validationFail("Expected 0 or 1.","Patch rows with boolean values.")}};});function Zr(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var Zt,Cn=L(()=>{ut();Zt=class extends V{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=Zr(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."):Zr(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 te,Rn=L(()=>{et();te=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 va(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 ee,vn=L(()=>{et();ee=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"||!va(t)?this.validationFail("Invalid time.","Patch rows with HH:MM[:SS] times."):this.validationPass()}};});function $a(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),g=l===null||c!==null&&l<=15&&c<=59;return h&&d&&g}var ne,$n=L(()=>{et();ne=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"||!$a(t)?this.validationFail("Invalid timestamp.","Patch rows with ISO timestamps."):this.validationPass()}};});var re,Nn=L(()=>{et();re=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 ie,kn=L(()=>{et();ie=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 ti(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var Nt,Pn=L(()=>{ut();Nt=class extends V{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=ti(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=ti(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 ei(e){return ka.test(e.toLowerCase())}var Na,ka,se,Ln=L(()=>{et();Na="????????-????-????-????-????????????",ka=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;se=class extends D{get isShimBacked(){return true}checkConstraint(){let t=this.quoteIfNeeded(this.context.column);return `${t} IS NULL OR ${t} GLOB '${Na}'`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string")throw this.checkError("uuid_format",t);let n=t.toLowerCase();if(!ei(n))throw this.checkError("uuid_format",t);return n}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!ei(t)?this.validationFail("Invalid UUID.","Patch rows with valid UUIDs."):this.validationPass()}};});function Pa(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 La(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 Oa(e){if(!e.includes(":"))return false;try{return new URL(`http://[${e}]/`),!0}catch{return false}}function ni(e){let t=Pa(e);return t?La(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=32:Oa(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=128:false:false}var oe,On=L(()=>{et();oe=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(!ni(n))throw this.checkError("inet_format",t);return n}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!ni(t.trim())?this.validationFail("Invalid inet address.","Patch rows with valid inet strings."):this.validationPass()}};});var ae,Fn=L(()=>{et();ae=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 le(e,t){if(t?.isArray){let r=le(e,{...t,isArray:false});return new Nt(e,r)}if(t?.enumValues)return new ie(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=le(i);return new Nt(e,s)}return Ia.has(n)?new Xt(e):Fa.has(n)?new St(e):Ua.has(n)?new Qt(e):Ma.has(n)?new Zt(e):Ga.has(n)?new te(e):Wa.has(n)?new ee(e):za.has(n)?new ne(e):Ka.has(n)?new re(e):Ba.has(n)?new Yt(e):Da.has(n)?new Jt(e,t?.numericPrecision):Ha.has(n)?new se(e):qa.has(n)?new D(e,63):Va.has(n)?new oe(e):ja.has(n)?new D(e,t?.lengthConstraint):new ae(e)}var Fa,Ia,Da,ja,Ba,Ua,Ma,Ha,qa,Va,Ga,Wa,za,Ka,ri=L(()=>{He();En();Tn();et();An();_n();Cn();Rn();vn();$n();Nn();kn();Pn();Ln();On();Fn();Fa=new Set(["int2","smallint","int4","integer","int","int8","bigint"]),Ia=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]),Da=new Set(["float4","real","float8","double precision","numeric","decimal"]),ja=new Set(["text","varchar","character varying","char","character","bpchar"]),Ba=new Set(["bytea"]),Ua=new Set(["bool","boolean"]),Ma=new Set(["json","jsonb"]),Ha=new Set(["uuid"]),qa=new Set(["name"]),Va=new Set(["inet"]),Ga=new Set(["date"]),Wa=new Set(["time","timetz","time without time zone","time with time zone"]),za=new Set(["timestamp","timestamptz","timestamp without time zone","timestamp with time zone"]),Ka=new Set(["interval"]);});var ii=L(()=>{});var ce,si=L(()=>{ce=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 oi=L(()=>{ut();xn();He();En();Tn();et();An();_n();Cn();Rn();vn();$n();Nn();kn();Pn();Ln();On();Fn();ri();ii();si();});var ci={};$i(ci,{_resetWarnedMissingToClauseForTests:()=>Xa,collectComments:()=>el,collectEnums:()=>Ja,collectPolicies:()=>Qa,collectSchema:()=>Za,collectTableConstraints:()=>tl,collectVariables:()=>Ya});function Xa(){jn.clear();}function Ja(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=mt(r.typeName??[]).join(".");if(!i||!r.vals)continue;let s=mt(r.vals);t.set(i.toLowerCase(),s);}return t}function Ya(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=zr(r.args?.[0]??{});t.set(i,{value:s,local:r.is_local});}return t}function ai(e){let t=[],n=false;for(let r of e??[])if("RoleSpec"in r){let i=r.RoleSpec;i.roletype==="ROLESPEC_PUBLIC"?i.location===-1&&(n=true):i.roletype==="ROLESPEC_CSTRING"&&i.rolename&&t.push(i.rolename);}return {roles:t,implicitPublic:n}}function li(e,t){return e&&e.length>0?e:t}function In(e,t,n){return e.findIndex(r=>r.data.name===t.name&&r.data.table===t.table&&li(r.data.schema,n)===li(t.schema,n))}function Dn(e,t){return new Error(`policy "${e}" for table "${t}" does not exist`)}function Qa(e,t={}){let n=t.defaultSchema||"public",r=t.validateMutations===true,i=new Me,s=new Set,o=[];for(let a of e.stmts??[])if(a.stmt){if("CreatePolicyStmt"in a.stmt){let l=a.stmt.CreatePolicyStmt,c=l.table?.relname??"",u=l.table?.schemaname,h={select:"SELECT",insert:"INSERT",update:"UPDATE",delete:"DELETE"},d=l.cmd_name?h[l.cmd_name]??"ALL":"ALL",g=l.permissive===true,{roles:b,implicitPublic:E}=ai(l.roles),T=l.qual?i.deparse(l.qual):void 0,N=l.with_check?i.deparse(l.with_check):void 0;if(E){let q=u?`${u}.${c}`:c,K=l.policy_name??"",U=`${q}::${K}`;if(!jn.has(U)){jn.add(U);let j=JSON.stringify(T)+JSON.stringify(N);/\{\{auth\.(uid|jwt|role)/i.test(j)||console.warn(`[supalite] policy "${K}" on "${q}" has no TO clause \u2014 applies to all roles (PUBLIC). For clarity, prefer an explicit \`TO <role>\` clause (e.g. \`TO authenticated\`).`);}}let S=new $t({name:l.policy_name??"",table:c,schema:u,command:d,permissive:g,roles:b,using:T,withCheck:N});o.push(S);}if("DropStmt"in a.stmt&&a.stmt.DropStmt.removeType==="OBJECT_POLICY"){let l=a.stmt.DropStmt,c=l.objects?.[0];if(c&&"List"in c){let u=mt(c.List.items??[]),h=u[u.length-1],d=u[u.length-2],g=u.length>=3?u[u.length-3]:void 0;if(h&&d){let b=In(o,{name:h,table:d,schema:g},n);if(b!==-1)o.splice(b,1);else if(r&&!l.missing_ok)throw Dn(h,d)}}}if("AlterPolicyStmt"in a.stmt){let l=a.stmt.AlterPolicyStmt,c=l.policy_name??"",u=l.table?.relname??"",h=l.table?.schemaname,d=In(o,{name:c,table:u,schema:h},n);if(d===-1){if(r)throw Dn(c,u);continue}let g=o[d].data,b=l.roles?ai(l.roles).roles:g.roles,E=l.qual?i.deparse(l.qual):g.using,T=l.with_check?i.deparse(l.with_check):g.withCheck;o[d]=new $t({...g,roles:b,using:E,withCheck:T});}if("RenameStmt"in a.stmt&&a.stmt.RenameStmt.renameType==="OBJECT_POLICY"){let l=a.stmt.RenameStmt,c=l.subname??"",u=l.relation?.relname??"",h=l.relation?.schemaname,d=In(o,{name:c,table:u,schema:h},n);if(d===-1){if(r)throw Dn(c,u);continue}l.newname&&(o[d]=new $t({...o[d].data,name:l.newname}));}if("AlterTableStmt"in a.stmt){let l=a.stmt.AlterTableStmt;if((l.cmds??[]).some(h=>"AlterTableCmd"in h&&(h.AlterTableCmd.subtype==="AT_EnableRowSecurity"||h.AlterTableCmd.subtype==="AT_ForceRowSecurity"))){let h=l.relation?.relname??"";s.add(h);}}}return {policies:o,tables:s}}function Za(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 ce(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(x=>x.String?.sval||x.String?.str).filter(Boolean),d=h&&(h.length===2&&h[0]==="pg_catalog"?h[1]:h[0]);if(!d)continue;let g=!!c.typeName?.arrayBounds?.length,b=Array.isArray(c.typeName?.typmods)?c.typeName.typmods:[],E=x=>b[x]?.A_Const?.ival?.ival??b[x]?.A_Const?.val?.ival?.ival,T={isArray:g};if(Xr(d)&&b.length>0){let x=E(0);typeof x=="number"&&x>0&&(T.lengthConstraint=x);}if(Jr(d)&&b.length>=2){let x=E(0),k=E(1);typeof x=="number"&&typeof k=="number"&&x>0&&k>=0&&(T.numericPrecision={precision:x,scale:k});}let N=t.get(d.toLowerCase());N&&(T.enumValues=N);let S=Array.isArray(c.constraints)?c.constraints:[],q=S.some(x=>x.Constraint?.contype==="CONSTR_PRIMARY"),K=Kr(d)||S.some(x=>x.Constraint?.contype==="CONSTR_IDENTITY"),U=S.some(x=>x.Constraint?.contype==="CONSTR_NOTNULL"),j=S.find(x=>x.Constraint?.contype==="CONSTR_UNIQUE"),G=S.find(x=>x.Constraint?.contype==="CONSTR_GENERATED"),A=S.find(x=>x.Constraint?.contype==="CONSTR_FOREIGN"),C=S.find(x=>x.Constraint?.contype==="CONSTR_CHECK"),m;if(A){let x=A.Constraint,k=x.pktable?.relname,p=x.pktable?.schemaname,f=x.pk_attrs?.[0]?.String?.sval;k&&f&&(m={refSchema:p,refTable:k,refColumn:f,constraintName:x.conname||void 0});}let W={schema:o,table:s,column:u,pgTypeName:d,nullable:!U&&!q,defaultValue:null,defaultFn:null,isPrimaryKey:q,isUnique:!!j,isSerial:K,isGenerated:!!G,fkRef:m,hasCheck:!!C,checkConstraintName:C?.Constraint?.conname||void 0,uniqueConstraintName:j?.Constraint?.conname||void 0};a.set(u,le(W,T));}n.set(`${o}.${s}`,a);}return n}function tl(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(g=>g.String?.sval??g.String?.str).filter(Boolean),h=(l.pk_attrs??[]).map(g=>g.String?.sval??g.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 el(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 jn,ui=L(()=>{Yr();Be();Qr();oi();Sn();jn=new Set;});process.stdin.isTTY?null:(async()=>{let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")})();function tt(e,t){he.existsSync(e)||(he.mkdirSync(e,{recursive:true}),t?.());}function yt(e,t,n){he.existsSync(e)||(he.writeFileSync(e,t),n?.());}var lt=class e{root;constructor(t,n){let r=n??e.projectDir();this.root=it__default.join(r,t??"");}ensureRoot(){tt(this.root);}static homeDir(){return it__default.join(Pi.homedir(),".lite")}static projectDir(){return it__default.join(process.cwd(),"supabase")}deleteAll(t=false){try{he.rmSync(this.root,{recursive:!0});}catch(n){if(!t)throw n}this.ensureRoot();}delete(t,n=false){try{he.unlinkSync(it__default.join(this.root,t));}catch(r){if(!n)throw r}}write(t,n,r=false){try{this.ensureRoot(),he.writeFileSync(it__default.join(this.root,t),n);}catch(i){if(!r)throw i}}read(t,n=false){try{return he.readFileSync(it__default.join(this.root,t),"utf8")}catch(r){if(!n)throw r}}relativePath(t){return t?it__default.relative(process.cwd(),it__default.join(this.root,t)):this.root}path(t){return t?it__default.join(this.root,t):this.root}};var Pt=process.env.SUPALITE_CLOUD_URL??(process.env.LOCAL?"http://localhost:2000":"https://www.lite.dev");var ye=class{root;constructor(t){this.root=t??it__default.join(Pi.homedir(),".lite","auth"),tt(this.root);}async getItem(t){try{return he.readFileSync(it__default.join(this.root,t+".json"),"utf8")}catch{return null}}async setItem(t,n){he.writeFileSync(it__default.join(this.root,t+".json"),n);}async removeItem(t){try{he.unlinkSync(it__default.join(this.root,t+".json"));}catch{return}}};var xt=class{constructor(t){this.config=t;this.tempFs=new lt(".temp",this.config.root),this.projectFs=new lt("supabase",this.config.root),this.schemaFs=new lt("schemas",this.config.root),this.authStorage=this.config.authStorage??new ye(it__default.join(lt.homeDir(),"auth")),this._client=this.config.withSupabaseClient!==false?this.config.client??createClient(this.config.host??Pt,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??Pt);return await fetch(r,{...n,headers:{...n?.headers,Authorization:`Bearer ${this.config.token}`}})}};var Et=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 rt={config_dir:"supabase",default_db_url:"file:supabase/.temp/data.db",default_db_dir:"supabase/.temp/data"};var Ut=kt(Lt());function Bi(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return [n.length,n.pop().length+1]}function Ui(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 _=class extends Error{line;column;codeblock;constructor(t,n){let[r,i]=
|
|
14
|
+
`));}return i}var _=class extends Error{line;column;codeblock;constructor(t,n){let[r,i]=Bi(n.toml,n.ptr),s=Ui(n.toml,r,i);super(`Invalid TOML document: ${t}
|
|
15
15
|
|
|
16
|
-
${s}`,n),this.line=r,this.column=i,this.codeblock=s;}};function
|
|
16
|
+
${s}`,n),this.line=r,this.column=i,this.codeblock=s;}};function Mi(e,t){let n=0;for(;e[t-++n]==="\\";);return --n&&n%2}function Se(e,t=0,n=e.length){let r=e.indexOf(`
|
|
17
17
|
`,t);return e[r-1]==="\r"&&r--,r<=n?r:-1}function Tt(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 _("control characters are not allowed in comments",{toml:e,ptr:t})}return e.length}function
|
|
19
|
+
`)return n+1;if(r<" "&&r!==" "||r==="\x7F")throw new _("control characters are not allowed in comments",{toml:e,ptr:t})}return e.length}function X(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:
|
|
21
|
+
`);)t++;return r||i!=="#"?t:X(e,Tt(e,t),n)}function Wn(e,t,n,r,i=false){if(!r)return t=Se(e,t),t<0?e.length:t;for(let s=t;s<e.length;s++){let o=e[s];if(o==="#")s=Se(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 _("cannot find end of structure",{toml:e,ptr:t})}function
|
|
24
|
-
`,f:"\f",r:"\r",e:"\x1B",'"':'"',"\\":"\\"};function
|
|
23
|
+
`))return s}}throw new _("cannot find end of structure",{toml:e,ptr:t})}function xe(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!=="'"&&Mi(e,t));return t>-1&&(t+=r.length,r.length>1&&(e[t]===n&&t++,e[t]===n&&t++)),t}var Hi=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,Ot=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(Hi);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 qi=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,Vi=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,Gi=/^[+-]?0[0-9_]/,Wi=/^[0-9a-f]{2,8}$/i,zn={b:"\b",t:" ",n:`
|
|
24
|
+
`,f:"\f",r:"\r",e:"\x1B",'"':'"',"\\":"\\"};function Ee(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 _("newlines are not allowed in strings",{toml:e,ptr:t-1})}else if(c<" "&&c!==" "||c==="\x7F")throw new _("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(!
|
|
28
|
-
`||c===" "||c===" "||c==="\r")){if(t=
|
|
29
|
-
`&&e[t]!=="\r")throw new _("invalid escape: only line-ending whitespace may be escaped",{toml:e,ptr:s});t=
|
|
30
|
-
`&&e[o]!=="\r")throw new _("unexpected character encountered",{toml:e,ptr:o});o+=+(e[o]===",");}return [l,o]}o=
|
|
31
|
-
`&&o!=="\r"){let a,l=i,c=false,[u,h]=
|
|
32
|
-
`&&s!=="\r"){let o=
|
|
33
|
-
`&&e[a]!=="\r")throw new _("each key-value declaration must be followed by an end-of-line",{toml:e,ptr:a});a=
|
|
27
|
+
`){if(!i)throw new _("newlines are not allowed in strings",{toml:e,ptr:t-1})}else if(c<" "&&c!==" "||c==="\x7F")throw new _("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(!Wi.test(u))throw new _("invalid unicode escape",{toml:e,ptr:s});try{a+=String.fromCodePoint(parseInt(u,16));}catch{throw new _("invalid unicode escape",{toml:e,ptr:s})}}else if(i&&(c===`
|
|
28
|
+
`||c===" "||c===" "||c==="\r")){if(t=X(e,t-1,true),e[t]!==`
|
|
29
|
+
`&&e[t]!=="\r")throw new _("invalid escape: only line-ending whitespace may be escaped",{toml:e,ptr:s});t=X(e,t);}else if(c in zn)a+=zn[c];else throw new _("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 Kn(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=qi.test(e);if(i||Vi.test(e)){if(Gi.test(e))throw new _("leading zeroes are not allowed",{toml:t,ptr:n});e=e.replace(/_/g,"");let o=+e;if(isNaN(o))throw new _("invalid number",{toml:t,ptr:n});if(i){if((i=!Number.isSafeInteger(o))&&!r)throw new _("integer value cannot be represented losslessly",{toml:t,ptr:n});(i||r===true)&&(o=BigInt(e));}return o}let s=new Ot(e);if(!s.isValid())throw new _("invalid value",{toml:t,ptr:n});return s}function zi(e,t,n){let r=e.slice(t,n),i=r.indexOf("#");return i>-1&&(Tt(e,i),r=r.slice(0,i)),[r.trimEnd(),i]}function Ft(e,t,n,r,i){if(r===0)throw new _("document contains excessively nested structures. aborting.",{toml:e,ptr:t});let s=e[t];if(s==="["||s==="{"){let[l,c]=s==="["?Jn(e,t,r,i):Xn(e,t,r,i);if(n){if(c=X(e,c),e[c]===",")c++;else if(e[c]!==n)throw new _("expected comma or end of structure",{toml:e,ptr:c})}return [l,c]}let o;if(s==='"'||s==="'"){o=xe(e,t);let l=Ee(e,t,o);if(n){if(o=X(e,o),e[o]&&e[o]!==","&&e[o]!==n&&e[o]!==`
|
|
30
|
+
`&&e[o]!=="\r")throw new _("unexpected character encountered",{toml:e,ptr:o});o+=+(e[o]===",");}return [l,o]}o=Wn(e,t,",",n);let a=zi(e,t,o-+(e[o-1]===","));if(!a[0])throw new _("incomplete key-value declaration: no value specified",{toml:e,ptr:t});return n&&a[1]>-1&&(o=X(e,t+a[1]),o+=+(e[o]===",")),[Kn(a[0],e,t,i),o]}var Ki=/^[a-zA-Z0-9-_]+[ \t]*$/;function Te(e,t,n="="){let r=t-1,i=[],s=e.indexOf(n,t);if(s<0)throw new _("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 _("multiline strings are not allowed in keys",{toml:e,ptr:t});let a=xe(e,t);if(a<0)throw new _("unfinished string encountered",{toml:e,ptr:t});r=e.indexOf(".",a);let l=e.slice(a,r<0||r>s?s:r),c=Se(l);if(c>-1)throw new _("newlines are not allowed in keys",{toml:e,ptr:t+r+c});if(l.trimStart())throw new _("found extra tokens after the string part",{toml:e,ptr:a});if(s<a&&(s=e.indexOf(n,a),s<0))throw new _("incomplete key-value: cannot find end of key",{toml:e,ptr:t});i.push(Ee(e,t,a));}else {r=e.indexOf(".",t);let a=e.slice(t,r<0||r>s?s:r);if(!Ki.test(a))throw new _("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,X(e,s+1,true,true)]}function Xn(e,t,n,r){let i={},s=new Set,o;for(t++;(o=e[t++])!=="}"&&o;){if(o===",")throw new _("expected value, found comma",{toml:e,ptr:t-1});if(o==="#")t=Tt(e,t);else if(o!==" "&&o!==" "&&o!==`
|
|
31
|
+
`&&o!=="\r"){let a,l=i,c=false,[u,h]=Te(e,t-1);for(let b=0;b<u.length;b++){if(b&&(l=c?l[a]:l[a]={}),a=u[b],(c=Object.hasOwn(l,a))&&(typeof l[a]!="object"||s.has(l[a])))throw new _("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 _("trying to redefine an already defined value",{toml:e,ptr:t});let[d,g]=Ft(e,h,"}",n-1,r);s.add(d),l[a]=d,t=g;}}if(!o)throw new _("unfinished table encountered",{toml:e,ptr:t});return [i,t]}function Jn(e,t,n,r){let i=[],s;for(t++;(s=e[t++])!=="]"&&s;){if(s===",")throw new _("expected value, found comma",{toml:e,ptr:t-1});if(s==="#")t=Tt(e,t);else if(s!==" "&&s!==" "&&s!==`
|
|
32
|
+
`&&s!=="\r"){let o=Ft(e,t-1,"]",n-1,r);i.push(o[0]),t=o[1];}}if(!s)throw new _("unfinished array encountered",{toml:e,ptr:t});return [i,t]}function Yn(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 It(e,{maxDepth:t=1e3,integersAsBigInt:n}={}){let r={},i={},s=r,o=i;for(let a=X(e,0);a<e.length;){if(e[a]==="["){let l=e[++a]==="[",c=Te(e,a+=+l,"]");if(l){if(e[c[1]-1]!=="]")throw new _("expected end of table declaration",{toml:e,ptr:c[1]-1});c[1]++;}let u=Yn(c[0],r,i,l?2:1);if(!u)throw new _("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=Te(e,a),c=Yn(l[0],s,o,0);if(!c)throw new _("trying to redefine an already defined table or value",{toml:e,ptr:a});let u=Ft(e,l[1],void 0,t,n);c[1][c[0]]=u[0],a=u[1];}if(a=X(e,a,true),e[a]&&e[a]!==`
|
|
33
|
+
`&&e[a]!=="\r")throw new _("each key-value declaration must be followed by an end-of-line",{toml:e,ptr:a});a=X(e,a);}return r}var Qn=/^[a-z0-9-_]+$/i;function Dt(e){let t=typeof e;if(t==="object"){if(Array.isArray(e))return "array";if(e instanceof Date)return "date"}return t}function Xi(e){for(let t=0;t<e.length;t++)if(Dt(e[t])!=="object")return false;return e.length!=0}function ze(e){return JSON.stringify(e).replace(/\x7f/g,"\\u007f")}function Ke(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 ze(e);if(t==="date"){if(isNaN(e.getTime()))throw new TypeError("cannot serialize invalid date");return e.toISOString()}if(t==="object")return Ji(e,n,r);if(t==="array")return Yi(e,n,r)}function Ji(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+=Qn.test(o)?o:ze(o),i+=" = ",i+=Ke(e[o],Dt(e[o]),t-1,n);}return i+" }"}function Yi(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+=Ke(e[i],Dt(e[i]),t-1,n);}return r+" ]"}function Qi(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+=Xe(0,e[s],t,n,r);return i}function Xe(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=Dt(t[c]);if(u==="symbol"||u==="function")throw new TypeError(`cannot serialize values of type '${u}'`);let h=Qn.test(c)?c:ze(c);if(u==="array"&&Xi(t[c]))o+=(o&&`
|
|
36
|
+
`)+Qi(t[c],n?`${n}.${h}`:h,r-1,i);else if(u==="object"){let d=n?`${n}.${h}`:h;o+=(o&&`
|
|
37
|
+
`)+Xe(d,t[c],d,r-1,i);}else s+=h,s+=" = ",s+=Ke(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 Je(e,{maxDepth:t=1e3,numbersAsFloat:n=false}={}){if(Dt(e)!=="object")throw new TypeError("stringify can only be called with an object");let r=Xe(0,e,"",t,n);return r[r.length-1]!==`
|
|
41
41
|
`?r+`
|
|
42
|
-
`:r}var
|
|
43
|
-
`;)n+=e[r],r++;continue}if(h==="/"&&d==="*"){for(n+="/*",r+=2;r<i&&!(e[r]==="*"&&e[r+1]==="/");)n+=e[r],r++;r<i&&(n+="*/",r+=2);continue}if(h==="'"){for(n+=h,r++;r<i;){if(e[r]==="'"&&e[r+1]==="'"){n+="''",r+=2;continue}if(n+=e[r],e[r]==="'"){r++;break}r++;}continue}if(h==='"'){for(n+=h,r++;r<i;){if(e[r]==='"'&&e[r+1]==='"'){n+='""',r+=2;continue}if(n+=e[r],e[r]==='"'){r++;break}r++;}continue}if(h==="$"){let
|
|
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 Ke(e){return typeof e=="number"?e:Number.parseInt(String(e),10)}var Te=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 y=Number.parseInt(d[1],10),b=d[2]?Number.parseInt(d[2],10):o.size-1;u=b-y+1,c=`bytes ${y}-${b}/${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:y,value:b}=await d.read();if(y)break;h.push(b);}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:Ke(t.size),size:Ke(t.size),mimetype:Qi(r),lastModified:t.mtime,eTag:n}}};function Qi(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 Zi=new Function("spec","return import(spec)");async function Xe(e,t,n){try{return await Zi(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 Jn(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=ns(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=fe.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,y]of Object.entries(h))r[d]===void 0&&(r[d]=y);}}function ns(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 rs=/^env\((\w+)\)$/;function Yn(e,t=process.env){return Je(e,t)}function Je(e,t){if(typeof e=="string"){let n=e.match(rs);return n?t[n[1]]??"":e}if(Array.isArray(e))return e.map(n=>Je(n,t));if(e&&typeof e=="object"){let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)return e;let r={};for(let[i,s]of Object.entries(e))r[i]=Je(s,t);return r}return e}var ss=["toml","json","ts","mts","js","mjs","cjs"],Ae=class extends Et{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(),ft.config_dir);if(!t)for(let r of ss){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(jt.default.dim(`Using config file: ${jt.default.cyan(`./${n}`)}`));let r=rt__default.dirname(rt__default.resolve(n));Jn(r);let i=n.split(".").pop(),s;switch(i){case "toml":s=Ot(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 Yn(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??ft.default_db_url,r=await createConnection({url:i,ddlDialect:"sqlite"});break;case "pglite":{i=n.db?.url??rt__default.join(process.cwd(),ft.default_db_dir);let{createPgliteConnection:s}=await Xe("@supabase/lite/pglite","pglite","@electric-sql/pglite");r=await s({url:i});break}case "postgres":{i=n.db?.url??"";let{createPostgresConnection:s}=await Xe("@supabase/lite/postgres","postgres","postgres");r=await s({url:i});break}default:i=n.db?.url??ft.default_db_url,r=await createConnection({url:i,ddlDialect:"postgres"});break}if(!r)throw new Error("Failed to create connection");return console.log(jt.default.green(" \u279C"),"Database located at",jt.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 Te({basePath:rt__default.join(process.cwd(),ft.config_dir,".temp/storage")})),await r.init()}};var _e=class extends Et{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 Ce=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 Ae(t),remote:new _e(t)},this}};async function ls(e={}){return await new Ce({host:vt,root:at.projectDir(),...e}).init()}var en=Nt(kt());var Ze=Nt(kt());var cs=["toml","json","ts","mts","js","mjs","cjs"];async function $e(e){let t=rt__default.relative(process.cwd(),ft.config_dir);if(!e)for(let n of cs){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 Zn(e){let t=await $e(e);if(!t)return {};switch(console.log(Ze.default.dim(`Using config file: ${Ze.default.cyan(`./${t}`)}`)),t.split(".").pop()){case "toml":return Ot(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 tr(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 us(e={}){let t=process.cwd();if(e.recreate){console.log(en.default.dim("Recreating database..."));try{let r=await $e();if(r&&!/\.(ts|mts|js|mjs|cjs)$/.test(r)){let s=(await Zn(r))?.db?.url,o=s?tr(s):void 0;o&&fe.existsSync(o)&&(fe.rmSync(o,{recursive:!0,force:!0}),console.log(en.default.dim(` \u279C removed ${rt__default.relative(t,o)}`)));}}catch{}try{fe.rmSync(rt__default.join(t,"supabase",".temp"),{recursive:!0,force:!0});}catch{}}if(tt(rt__default.join(t,"supabase")),!await $e()){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"?gt(s,JSON.stringify(r)):gt(s,ze(r));}tt(rt__default.join(t,"supabase",".temp")),tt(rt__default.join(t,"supabase","schemas"),()=>{gt(rt__default.join(t,"supabase","schemas","schema.sql"),e.template?fs:`-- This is a schema file for the database
|
|
45
|
-
`);}),
|
|
46
|
-
`);}var
|
|
42
|
+
`:r}var Zi={storage:"EXPERIMENTAL_STORAGE",cloud:"EXPERIMENTAL_CLOUD"},ts=["storage","cloud"];Object.fromEntries(ts.map(e=>[e,es(e)]));function es(e){let t=typeof process<"u"&&process.env||void 0;return t?t.NODE_ENV==="test"?true:t[Zi[e]]==="1":false}function Ae(e){let t=[],n="",r=0,i=e.length,s=false,o=false,a=0,l=/^create(\s+or\s+replace)?(\s+temp(orary)?)?$/i,c=h=>{tr(h).length>0&&t.push(h.trim());},u=()=>{s=false,o=false,a=0;};for(;r<i;){let h=e[r],d=e[r+1];if(h==="-"&&d==="-"){for(;r<i&&e[r]!==`
|
|
43
|
+
`;)n+=e[r],r++;continue}if(h==="/"&&d==="*"){for(n+="/*",r+=2;r<i&&!(e[r]==="*"&&e[r+1]==="/");)n+=e[r],r++;r<i&&(n+="*/",r+=2);continue}if(h==="'"){for(n+=h,r++;r<i;){if(e[r]==="'"&&e[r+1]==="'"){n+="''",r+=2;continue}if(n+=e[r],e[r]==="'"){r++;break}r++;}continue}if(h==='"'){for(n+=h,r++;r<i;){if(e[r]==='"'&&e[r+1]==='"'){n+='""',r+=2;continue}if(n+=e[r],e[r]==='"'){r++;break}r++;}continue}if(h==="$"){let g=e.indexOf("$",r+1);if(g!==-1){let b=e.slice(r,g+1);if(/^\$[A-Za-z_][A-Za-z0-9_]*\$$|^\$\$$/.test(b)){n+=b,r=g+1;let T=e.indexOf(b,r);T===-1?(n+=e.slice(r),r=i):(n+=e.slice(r,T+b.length),r=T+b.length);continue}}}if(/[A-Za-z_]/.test(h)){let g=r;for(;g<i&&/[A-Za-z0-9_]/.test(e[g]);)g++;let b=e.slice(r,g),E=b.toLowerCase();if(E==="trigger"&&l.test(tr(n))?s=true:s&&E==="begin"?(o=true,a++):s&&o&&E==="case"?a++:s&&o&&E==="end"&&a>0&&a--,n+=b,r=g,s&&o&&a===0){let T=r;for(;T<i&&/\s/.test(e[T]);)T++;e[T]===";"&&(r=T+1),c(n),n="",u();}continue}if(h===";"){if(s&&o&&a>0){n+=h,r++;continue}c(n),n="",u(),r++;continue}n+=h,r++;}return c(n),t}function tr(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 Ye(e){return typeof e=="number"?e:Number.parseInt(String(e),10)}var Ce=class{driver=M;basePath;constructor(t){this.basePath=it.resolve(t.basePath);}filePath(t,n){return it.join(this.basePath,t,n)}async ensureDir(t){await M.mkdir(it.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 g=Number.parseInt(d[1],10),b=d[2]?Number.parseInt(d[2],10):o.size-1;u=b-g+1,c=`bytes ${g}-${b}/${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:g,value:b}=await d.read();if(g)break;h.push(b);}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:Ye(t.size),size:Ye(t.size),mimetype:rs(r),lastModified:t.mtime,eTag:n}}};function rs(e){let t=it.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 is=new Function("spec","return import(spec)");async function Qe(e,t,n){try{return await is(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 Re(e,t={}){let n=it__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=as(it__default.resolve(e),n);for(let a of o)for(let l of s){let c=it__default.join(a,l),u;try{u=he.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,g]of Object.entries(h))r[d]===void 0&&(r[d]=g);}}function as(e,t){let n=[],r=e,i=it__default.parse(r).root;for(;n.push(r),!(r===t||r===i);){let s=it__default.dirname(r);if(s===r)break;r=s;}return n}var ls=/^env\((\w+)\)$/;function ve(e,t=process.env){return Ze(e,t)}function Ze(e,t){if(typeof e=="string"){let n=e.match(ls);return n?t[n[1]]??"":e}if(Array.isArray(e))return e.map(n=>Ze(n,t));if(e&&typeof e=="object"){let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)return e;let r={};for(let[i,s]of Object.entries(e))r[i]=Ze(s,t);return r}return e}var cs=process.env.LITE_VERBOSE==="1";function Bt(...e){cs&&console.error(...e);}var fs=["toml","json","ts","mts","js","mjs","cjs"],$e=class extends Et{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=it__default.relative(process.cwd(),rt.config_dir);if(!t)for(let r of fs){let i=it__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 {};Bt(Ut.default.dim(`Using config file: ${Ut.default.cyan(`./${n}`)}`));let r=it__default.dirname(it__default.resolve(n));Re(r);let i=n.split(".").pop(),s;switch(i){case "toml":s=It(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(it__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 ve(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??rt.default_db_url,r=await createConnection({url:i,ddlDialect:"sqlite"});break;case "pglite":{i=n.db?.url??it__default.join(process.cwd(),rt.default_db_dir);let{createPgliteConnection:s}=await Qe("@supabase/lite/pglite","pglite","@electric-sql/pglite");r=await s({url:i});break}case "postgres":{i=n.db?.url??"";let{createPostgresConnection:s}=await Qe("@supabase/lite/postgres","postgres","postgres");r=await s({url:i});break}default:i=n.db?.url??rt.default_db_url,r=await createConnection({url:i,ddlDialect:"postgres"});break}if(!r)throw new Error("Failed to create connection");return Bt(Ut.default.green(" \u279C"),"Database located at",Ut.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 Ce({basePath:it__default.join(process.cwd(),rt.config_dir,".temp/storage")})),await r.init()}};var Ne=class extends Et{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 ke=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 $e(t),remote:new Ne(t)},this}};async function hs(e={}){return await new ke({host:Pt,root:lt.projectDir(),...e}).init()}var sn=kt(Lt());var nn=kt(Lt());var ds=["toml","json","ts","mts","js","mjs","cjs"];async function Pe(e){let t=it__default.relative(process.cwd(),rt.config_dir);if(!e)for(let n of ds){let r=it__default.join(t,`config.${n}`);if(await M__default.access(r).then(()=>true).catch(()=>false)){e=r;break}}return e}async function gs(e){let t=await Pe(e);if(!t)return {};switch(Bt(nn.default.dim(`Using config file: ${nn.default.cyan(`./${t}`)}`)),t.split(".").pop()){case "toml":return It(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(it__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 ys(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 it__default.resolve(process.cwd(),t)}async function nr(e){let t=await Pe(e);t&&Re(it__default.dirname(it__default.resolve(t)));let n=ve(await gs(e));if("connection"in n)return;let r=n?.db?.driver;if(r==="postgres")return;let i=n?.db?.url??(r==="pglite"?rt.default_db_dir:rt.default_db_url);return ys(i)}async function bs(e={}){let t=process.cwd();if(e.recreate){console.log(sn.default.dim("Recreating database..."));try{let r=await nr();r&&he.existsSync(r)&&(he.rmSync(r,{recursive:!0,force:!0}),console.log(sn.default.dim(` \u279C removed ${it__default.relative(t,r)}`)));}catch{}try{he.rmSync(it__default.join(t,"supabase",".temp"),{recursive:!0,force:!0});}catch{}}if(tt(it__default.join(t,"supabase")),!await Pe()){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=it__default.relative(process.cwd(),it__default.join(t,"supabase",".temp","data")));let i=e.configFormat??"toml",s=it__default.join(t,"supabase",`config.${i}`);i==="json"?yt(s,JSON.stringify(r)):yt(s,Je(r));}tt(it__default.join(t,"supabase",".temp")),tt(it__default.join(t,"supabase","schemas"),()=>{yt(it__default.join(t,"supabase","schemas","schema.sql"),e.template?ws:`-- This is a schema file for the database
|
|
45
|
+
`);}),yt(it__default.join(t,"supabase","seed.sql"),e.template?Ss:`-- This is a seed file for the database
|
|
46
|
+
`);}var ws=`
|
|
47
47
|
create table todos (
|
|
48
48
|
id serial primary key,
|
|
49
49
|
title text not null,
|
|
@@ -56,7 +56,7 @@ create table todos (
|
|
|
56
56
|
create table test (
|
|
57
57
|
id serial primary key,
|
|
58
58
|
name text not null
|
|
59
|
-
)`,ps="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 er=createRequire(import.meta.url);function ws(e){let t=normalize(e);return t.length>1&&t[t.length-1]===sep&&(t=t.substring(0,t.length-1)),t}var Ss=/[\\/]/g;function ir(e,t){return e.replace(Ss,t)}var xs=/^[a-z]:[\\/]$/i;function Es(e){return e==="/"||xs.test(e)}function nn(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=ws(e)),e===".")return "";let o=e[e.length-1]!==i;return ir(o?e+i:e,i)}function sr(e,t){return t+e}function Ts(e,t){return function(n,r){return r.startsWith(e)?r.slice(e.length)+n:ir(relative(e,r),t.pathSeparator)+t.pathSeparator+n}}function As(e){return e}function _s(e,t,n){return t+e+n}function Cs(e,t){let{relativePaths:n,includeBasePath:r}=t;return n&&e?Ts(e,t):r?sr:As}function Rs(e){return function(t,n){n.push(t.substring(e.length)||".");}}function $s(e){return function(t,n,r){let i=t.substring(e.length)||".";r.every(s=>s(i,true))&&n.push(i);}}var Ns=(e,t)=>{t.push(e||".");},vs=(e,t,n)=>{let r=e||".";n.every(i=>i(r,true))&&t.push(r);},ks=()=>{};function Ps(e,t){let{includeDirs:n,filters:r,relativePaths:i}=t;return n?i?r&&r.length?$s(e):Rs(e):r&&r.length?vs:Ns:ks}var Ls=(e,t,n,r)=>{r.every(i=>i(e,false))&&n.files++;},Os=(e,t,n,r)=>{r.every(i=>i(e,false))&&t.push(e);},Fs=(e,t,n,r)=>{n.files++;},Is=(e,t)=>{t.push(e);},js=()=>{};function Ds(e){let{excludeFiles:t,filters:n,onlyCounts:r}=e;return t?js:n&&n.length?r?Ls:Os:r?Fs:Is}var Us=e=>e,Bs=()=>[""].slice(0,0);function Ms(e){return e.group?Bs:Us}var Hs=(e,t,n)=>{e.push({directory:t,files:n,dir:t});},qs=()=>{};function Vs(e){return e.group?Hs:qs}var Gs=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()&&or(e,a,t))return r.dequeue(null,t);n(c,a),r.dequeue(null,t);});});},Ws=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()&&or(e,o,t))return;n(a,o);}catch(o){if(!s)throw o}};function zs(e,t){return !e.resolveSymlinks||e.excludeSymlinks?null:t?Ws:Gs}function or(e,t,n){if(n.options.useRealPaths)return Ks(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 Ks(e,t){return t.visited.includes(e+t.options.pathSeparator)}var Xs=e=>e.counts,Js=e=>e.groups,Ys=e=>e.paths,Qs=e=>e.paths.slice(0,e.options.maxFiles),Zs=(e,t,n)=>(Ne(t,n,e.counts,e.options.suppressErrors),null),to=(e,t,n)=>(Ne(t,n,e.paths,e.options.suppressErrors),null),eo=(e,t,n)=>(Ne(t,n,e.paths.slice(0,e.options.maxFiles),e.options.suppressErrors),null),no=(e,t,n)=>(Ne(t,n,e.groups,e.options.suppressErrors),null);function Ne(e,t,n,r){t(e&&!r?e:null,n);}function ro(e,t){let{onlyCounts:n,group:r,maxFiles:i}=e;return n?t?Xs:Zs:r?t?Js:no:i?t?Qs:eo:t?Ys:to}var ar={withFileTypes:true},io=(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||".",ar,(o,a=[])=>{i(a,n,r),e.queue.dequeue(e.options.suppressErrors?null:o,e);});},so=(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||".",ar);}catch(a){if(!e.options.suppressErrors)throw a}i(o,n,r);};function oo(e){return e?so:io}var ao=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));}},lo=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}},co=class{aborted=false;abort(){this.aborted=true;}},lr=class{root;isSynchronous;state;joinPath;pushDirectory;pushFile;getArray;groupFiles;resolveSymlink;walkDirectory;callbackInvoker;constructor(e,t,n){this.isSynchronous=!n,this.callbackInvoker=ro(t,this.isSynchronous),this.root=nn(e,t),this.state={root:Es(this.root)?this.root:this.root.slice(0,-1),paths:[""].slice(0,0),groups:[],counts:new lo,options:t,queue:new ao((r,i)=>this.callbackInvoker(i,r,n)),symlinks:new Map,visited:[""].slice(0,0),controller:new co,fs:t.fs||_t},this.joinPath=Cs(this.root,t),this.pushDirectory=Ps(this.root,t),this.pushFile=Ds(t),this.getArray=Ms(t),this.groupFiles=Vs(t),this.resolveSymlink=zs(t,this.isSynchronous),this.walkDirectory=oo(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 y=this.getArray(this.state.paths);for(let b=0;b<e.length;++b){let E=e[b];if(E.isFile()||E.isSymbolicLink()&&!s&&!o){let T=this.joinPath(E.name,t);this.pushFile(T,y,this.state.counts,i);}else if(E.isDirectory()){let T=_s(E.name,t,this.state.options.pathSeparator);if(a&&a(E.name,T))continue;this.pushDirectory(T,r,i),this.walkDirectory(this.state,T,T,n-1,this.walk);}else if(this.resolveSymlink&&E.isSymbolicLink()){let T=sr(E.name,t);this.resolveSymlink(T,this.state,(N,S)=>{if(N.isDirectory()){if(S=nn(S,this.state.options),a&&a(E.name,u?S:T+h))return;this.walkDirectory(this.state,S,u?S:T+h,n-1,this.walk);}else {S=u?S:T;let H=basename(S),J=nn(dirname(S),this.state.options);S=this.joinPath(H,J),this.pushFile(S,y,this.state.counts,i);}});}}this.groupFiles(this.state.groups,t,y);}};function uo(e,t){return new Promise((n,r)=>{cr(e,t,(i,s)=>{if(i)return r(i);n(s);});})}function cr(e,t,n){new lr(e,t,n).start();}function fo(e,t){return new lr(e,t).start()}var nr=class{constructor(e,t){this.root=e,this.options=t;}withPromise(){return uo(this.root,this.options)}withCallback(e){cr(this.root,this.options,e);}sync(){return fo(this.root,this.options)}},ur=null;try{er.resolve("picomatch"),ur=er("picomatch");}catch{}var fr=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 nr(e||".",this.options)}withGlobFunction(e){return this.globFunction=e,this}crawlWithOptions(e,t){return this.options={...this.options,...t},new nr(e||".",this.options)}glob(...e){return this.globFunction?this.globWithOptions(e):this.globWithOptions(e,{dot:true})}globWithOptions(e,...t){let n=this.globFunction||ur;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 Rt=Nt(Or()),qo=Array.isArray,jr=process.platform==="win32",Vo=/^(\/?\.\.)+$/;function Go(e,t={}){let n=e.length,r=Array(n),i=Array(n),s=!t.noglobstar;for(let o=0;o<n;o++){let a=Dr(e[o]);r[o]=a;let l=a.length,c=Array(l);for(let u=0;u<l;u++)c[u]=(0, Rt.default)(a[u],t);i[o]=c;}return o=>{let a=o.split("/");if(a[0]===".."&&Vo.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),y=0;for(;y<d;){let b=c[y];if(b.includes("/"))return true;if(!u[y](a[y]))break;if(s&&b==="**")return true;y++;}if(y===h)return true}return false}}var Wo=/^[A-Z]:\/$/i,zo=jr?e=>Wo.test(e):e=>e==="/";function Fr(e,t,n){if(e===t||t.startsWith(`${e}/`)){if(n){let i=zo(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 Ko(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 Xo={parts:true};function Dr(e){var t;let n=Rt.default.scan(e,Xo);return !((t=n.parts)===null||t===void 0)&&t.length?n.parts:[e]}var Jo=/(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g,Yo=/(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g,Qo=e=>e.replace(Jo,"\\$&"),Zo=e=>e.replace(Yo,"\\$&"),ta=jr?Zo:Qo;function ea(e,t){let n=Rt.default.scan(e);return n.isGlob||n.negated}function Ct(...e){console.log(`[tinyglobby ${new Date().toLocaleTimeString("es")}]`,...e);}var na=/^(\/?\.\.)+/,ra=/\\(?=[()[\]{}!*+?@|])/g,Pe=/\\/g;function hn(e,t,n,r,i){let s=e;e.endsWith("/")&&(s=e.slice(0,-1)),!s.endsWith("*")&&t&&(s+="/**");let o=ta(n);Ir.isAbsolute(s.replace(ra,""))?s=posix.relative(o,s):s=posix.normalize(s);let a=na.exec(s),l=Dr(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 y=posix.join(n,a[0].slice(h*3));!y.startsWith(".")&&r.root.length>y.length&&(r.root=y,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 y=l[d];if(y==="**"&&!l[d+1]){u.pop();break}if(y!==r.commonPath[d]||ea(y)||d===l.length-1)break;u.push(y);}r.depthOffset=u.length,r.commonPath=u,r.root=u.length>0?posix.join(n,...u):n;}return s}function ia({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(hn(a,n,r,i,true));for(let a of e)a&&(a[0]!=="!"||a[1]==="("?s.push(hn(a,n,r,i,false)):(a[1]!=="!"||a[2]==="(")&&o.push(hn(a.slice(1),n,r,i,true)));return {match:s,ignore:o}}function sa(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];e[n]=t(r);}return e}function oa(e){return e?e instanceof URL?fileURLToPath(e).replace(Pe,"/"):Ir.resolve(e).replace(Pe,"/"):process.cwd().replace(Pe,"/")}function aa(e,t={}){let n=process.env.TINYGLOBBY_DEBUG?{...t,debug:true}:t,r=oa(n.cwd);if(n.debug&&Ct("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=ia({...n,patterns:e},r,i);n.debug&&Ct("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, Rt.default)(s.match,{...o,ignore:s.ignore}),l=(0, Rt.default)(s.ignore,o),c=Go(s.match,o),u=Fr(r,i.root,n.absolute),h=n.absolute?u:Fr(r,i.root,true),d={filters:[n.debug?(E,T)=>{let N=u(E,T),S=a(N);return S&&Ct(`matched ${N}`),S}:(E,T)=>a(u(E,T))],exclude:n.debug?(E,T)=>{let N=h(T,true),S=N!=="."&&!c(N)||l(N);return Ct(S?`skipped ${T}`:`crawling ${T}`),S}:(E,T)=>{let N=h(T,true);return N!=="."&&!c(N)||l(N)},fs:n.fs?{readdir:n.fs.readdir||_t__default.readdir,readdirSync:n.fs.readdirSync||_t__default.readdirSync,realpath:n.fs.realpath||_t__default.realpath,realpathSync:n.fs.realpathSync||_t__default.realpathSync,stat:n.fs.stat||_t__default.stat,statSync:n.fs.statSync||_t__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(Pe,"");let y=i.root;n.debug&&Ct("internal properties:",i);let b=r!==y&&!n.absolute&&Ko(r,i.root);return [new fr(d).crawl(y),b]}async function Mt(e,t){if(e&&t?.patterns)throw new Error("Cannot pass patterns as both an argument and an option");let n=qo(e)||typeof e=="string",r=n?t:e,i=n?e:e.patterns,[s,o]=aa(i,r);return o?sa(await s.withPromise(),o):s.withPromise()}var v=Nt(kt());function lt(e){return e.dialect==="postgres"?"pg":e.config?.ddlDialect==="sqlite"?"sqlite":"pg-flat"}function Le(e){return e==="sqlite"?{schema_migrations:"migrations",seed_files:"seed_files"}:e==="pg-flat"?{schema_migrations:'"supabase_migrations.schema_migrations"',seed_files:'"supabase_migrations.seed_files"'}:{schema_migrations:"supabase_migrations.schema_migrations",seed_files:"supabase_migrations.seed_files"}}function Ht(e){return `'${e.replace(/'/g,"''")}'`}function la(e){return `'${`{${e.map(r=>`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`).join(",")}}`.replace(/'/g,"''")}'`}function ca(e){return e==="sqlite"?[`CREATE TABLE IF NOT EXISTS migrations (
|
|
59
|
+
)`,Ss="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 rr=createRequire(import.meta.url);function Rs(e){let t=normalize(e);return t.length>1&&t[t.length-1]===sep&&(t=t.substring(0,t.length-1)),t}var vs=/[\\/]/g;function or(e,t){return e.replace(vs,t)}var $s=/^[a-z]:[\\/]$/i;function Ns(e){return e==="/"||$s.test(e)}function on(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=Rs(e)),e===".")return "";let o=e[e.length-1]!==i;return or(o?e+i:e,i)}function ar(e,t){return t+e}function ks(e,t){return function(n,r){return r.startsWith(e)?r.slice(e.length)+n:or(relative(e,r),t.pathSeparator)+t.pathSeparator+n}}function Ps(e){return e}function Ls(e,t,n){return t+e+n}function Os(e,t){let{relativePaths:n,includeBasePath:r}=t;return n&&e?ks(e,t):r?ar:Ps}function Fs(e){return function(t,n){n.push(t.substring(e.length)||".");}}function Is(e){return function(t,n,r){let i=t.substring(e.length)||".";r.every(s=>s(i,true))&&n.push(i);}}var Ds=(e,t)=>{t.push(e||".");},js=(e,t,n)=>{let r=e||".";n.every(i=>i(r,true))&&t.push(r);},Bs=()=>{};function Us(e,t){let{includeDirs:n,filters:r,relativePaths:i}=t;return n?i?r&&r.length?Is(e):Fs(e):r&&r.length?js:Ds:Bs}var Ms=(e,t,n,r)=>{r.every(i=>i(e,false))&&n.files++;},Hs=(e,t,n,r)=>{r.every(i=>i(e,false))&&t.push(e);},qs=(e,t,n,r)=>{n.files++;},Vs=(e,t)=>{t.push(e);},Gs=()=>{};function Ws(e){let{excludeFiles:t,filters:n,onlyCounts:r}=e;return t?Gs:n&&n.length?r?Ms:Hs:r?qs:Vs}var zs=e=>e,Ks=()=>[""].slice(0,0);function Xs(e){return e.group?Ks:zs}var Js=(e,t,n)=>{e.push({directory:t,files:n,dir:t});},Ys=()=>{};function Qs(e){return e.group?Js:Ys}var Zs=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()&&lr(e,a,t))return r.dequeue(null,t);n(c,a),r.dequeue(null,t);});});},to=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()&&lr(e,o,t))return;n(a,o);}catch(o){if(!s)throw o}};function eo(e,t){return !e.resolveSymlinks||e.excludeSymlinks?null:t?to:Zs}function lr(e,t,n){if(n.options.useRealPaths)return no(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 no(e,t){return t.visited.includes(e+t.options.pathSeparator)}var ro=e=>e.counts,io=e=>e.groups,so=e=>e.paths,oo=e=>e.paths.slice(0,e.options.maxFiles),ao=(e,t,n)=>(Le(t,n,e.counts,e.options.suppressErrors),null),lo=(e,t,n)=>(Le(t,n,e.paths,e.options.suppressErrors),null),co=(e,t,n)=>(Le(t,n,e.paths.slice(0,e.options.maxFiles),e.options.suppressErrors),null),uo=(e,t,n)=>(Le(t,n,e.groups,e.options.suppressErrors),null);function Le(e,t,n,r){t(e&&!r?e:null,n);}function fo(e,t){let{onlyCounts:n,group:r,maxFiles:i}=e;return n?t?ro:ao:r?t?io:uo:i?t?oo:co:t?so:lo}var cr={withFileTypes:true},po=(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||".",cr,(o,a=[])=>{i(a,n,r),e.queue.dequeue(e.options.suppressErrors?null:o,e);});},mo=(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||".",cr);}catch(a){if(!e.options.suppressErrors)throw a}i(o,n,r);};function ho(e){return e?mo:po}var go=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));}},yo=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}},bo=class{aborted=false;abort(){this.aborted=true;}},ur=class{root;isSynchronous;state;joinPath;pushDirectory;pushFile;getArray;groupFiles;resolveSymlink;walkDirectory;callbackInvoker;constructor(e,t,n){this.isSynchronous=!n,this.callbackInvoker=fo(t,this.isSynchronous),this.root=on(e,t),this.state={root:Ns(this.root)?this.root:this.root.slice(0,-1),paths:[""].slice(0,0),groups:[],counts:new yo,options:t,queue:new go((r,i)=>this.callbackInvoker(i,r,n)),symlinks:new Map,visited:[""].slice(0,0),controller:new bo,fs:t.fs||Ct},this.joinPath=Os(this.root,t),this.pushDirectory=Us(this.root,t),this.pushFile=Ws(t),this.getArray=Xs(t),this.groupFiles=Qs(t),this.resolveSymlink=eo(t,this.isSynchronous),this.walkDirectory=ho(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 g=this.getArray(this.state.paths);for(let b=0;b<e.length;++b){let E=e[b];if(E.isFile()||E.isSymbolicLink()&&!s&&!o){let T=this.joinPath(E.name,t);this.pushFile(T,g,this.state.counts,i);}else if(E.isDirectory()){let T=Ls(E.name,t,this.state.options.pathSeparator);if(a&&a(E.name,T))continue;this.pushDirectory(T,r,i),this.walkDirectory(this.state,T,T,n-1,this.walk);}else if(this.resolveSymlink&&E.isSymbolicLink()){let T=ar(E.name,t);this.resolveSymlink(T,this.state,(N,S)=>{if(N.isDirectory()){if(S=on(S,this.state.options),a&&a(E.name,u?S:T+h))return;this.walkDirectory(this.state,S,u?S:T+h,n-1,this.walk);}else {S=u?S:T;let q=basename(S),K=on(dirname(S),this.state.options);S=this.joinPath(q,K),this.pushFile(S,g,this.state.counts,i);}});}}this.groupFiles(this.state.groups,t,g);}};function wo(e,t){return new Promise((n,r)=>{fr(e,t,(i,s)=>{if(i)return r(i);n(s);});})}function fr(e,t,n){new ur(e,t,n).start();}function So(e,t){return new ur(e,t).start()}var ir=class{constructor(e,t){this.root=e,this.options=t;}withPromise(){return wo(this.root,this.options)}withCallback(e){fr(this.root,this.options,e);}sync(){return So(this.root,this.options)}},pr=null;try{rr.resolve("picomatch"),pr=rr("picomatch");}catch{}var mr=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 ir(e||".",this.options)}withGlobFunction(e){return this.globFunction=e,this}crawlWithOptions(e,t){return this.options={...this.options,...t},new ir(e||".",this.options)}glob(...e){return this.globFunction?this.globWithOptions(e):this.globWithOptions(e,{dot:true})}globWithOptions(e,...t){let n=this.globFunction||pr;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 vt=kt(Ir()),Yo=Array.isArray,Br=process.platform==="win32",Qo=/^(\/?\.\.)+$/;function Zo(e,t={}){let n=e.length,r=Array(n),i=Array(n),s=!t.noglobstar;for(let o=0;o<n;o++){let a=Ur(e[o]);r[o]=a;let l=a.length,c=Array(l);for(let u=0;u<l;u++)c[u]=(0, vt.default)(a[u],t);i[o]=c;}return o=>{let a=o.split("/");if(a[0]===".."&&Qo.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),g=0;for(;g<d;){let b=c[g];if(b.includes("/"))return true;if(!u[g](a[g]))break;if(s&&b==="**")return true;g++;}if(g===h)return true}return false}}var ta=/^[A-Z]:\/$/i,ea=Br?e=>ta.test(e):e=>e==="/";function Dr(e,t,n){if(e===t||t.startsWith(`${e}/`)){if(n){let i=ea(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 na(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 ra={parts:true};function Ur(e){var t;let n=vt.default.scan(e,ra);return !((t=n.parts)===null||t===void 0)&&t.length?n.parts:[e]}var ia=/(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g,sa=/(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g,oa=e=>e.replace(ia,"\\$&"),aa=e=>e.replace(sa,"\\$&"),la=Br?aa:oa;function ca(e,t){let n=vt.default.scan(e);return n.isGlob||n.negated}function Rt(...e){console.log(`[tinyglobby ${new Date().toLocaleTimeString("es")}]`,...e);}var ua=/^(\/?\.\.)+/,fa=/\\(?=[()[\]{}!*+?@|])/g,Ie=/\\/g;function yn(e,t,n,r,i){let s=e;e.endsWith("/")&&(s=e.slice(0,-1)),!s.endsWith("*")&&t&&(s+="/**");let o=la(n);jr.isAbsolute(s.replace(fa,""))?s=posix.relative(o,s):s=posix.normalize(s);let a=ua.exec(s),l=Ur(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 g=posix.join(n,a[0].slice(h*3));!g.startsWith(".")&&r.root.length>g.length&&(r.root=g,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 g=l[d];if(g==="**"&&!l[d+1]){u.pop();break}if(g!==r.commonPath[d]||ca(g)||d===l.length-1)break;u.push(g);}r.depthOffset=u.length,r.commonPath=u,r.root=u.length>0?posix.join(n,...u):n;}return s}function pa({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(yn(a,n,r,i,true));for(let a of e)a&&(a[0]!=="!"||a[1]==="("?s.push(yn(a,n,r,i,false)):(a[1]!=="!"||a[2]==="(")&&o.push(yn(a.slice(1),n,r,i,true)));return {match:s,ignore:o}}function ma(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];e[n]=t(r);}return e}function ha(e){return e?e instanceof URL?fileURLToPath(e).replace(Ie,"/"):jr.resolve(e).replace(Ie,"/"):process.cwd().replace(Ie,"/")}function da(e,t={}){let n=process.env.TINYGLOBBY_DEBUG?{...t,debug:true}:t,r=ha(n.cwd);if(n.debug&&Rt("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=pa({...n,patterns:e},r,i);n.debug&&Rt("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, vt.default)(s.match,{...o,ignore:s.ignore}),l=(0, vt.default)(s.ignore,o),c=Zo(s.match,o),u=Dr(r,i.root,n.absolute),h=n.absolute?u:Dr(r,i.root,true),d={filters:[n.debug?(E,T)=>{let N=u(E,T),S=a(N);return S&&Rt(`matched ${N}`),S}:(E,T)=>a(u(E,T))],exclude:n.debug?(E,T)=>{let N=h(T,true),S=N!=="."&&!c(N)||l(N);return Rt(S?`skipped ${T}`:`crawling ${T}`),S}:(E,T)=>{let N=h(T,true);return N!=="."&&!c(N)||l(N)},fs:n.fs?{readdir:n.fs.readdir||Ct__default.readdir,readdirSync:n.fs.readdirSync||Ct__default.readdirSync,realpath:n.fs.realpath||Ct__default.realpath,realpathSync:n.fs.realpathSync||Ct__default.realpathSync,stat:n.fs.stat||Ct__default.stat,statSync:n.fs.statSync||Ct__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(Ie,"");let g=i.root;n.debug&&Rt("internal properties:",i);let b=r!==g&&!n.absolute&&na(r,i.root);return [new mr(d).crawl(g),b]}async function Vt(e,t){if(e&&t?.patterns)throw new Error("Cannot pass patterns as both an argument and an option");let n=Yo(e)||typeof e=="string",r=n?t:e,i=n?e:e.patterns,[s,o]=da(i,r);return o?ma(await s.withPromise(),o):s.withPromise()}var $=kt(Lt());function ct(e){return e.dialect==="postgres"?"pg":e.config?.ddlDialect==="sqlite"?"sqlite":"pg-flat"}function De(e){return e==="sqlite"?{schema_migrations:"migrations",seed_files:"seed_files"}:e==="pg-flat"?{schema_migrations:'"supabase_migrations.schema_migrations"',seed_files:'"supabase_migrations.seed_files"'}:{schema_migrations:"supabase_migrations.schema_migrations",seed_files:"supabase_migrations.seed_files"}}function Gt(e){return `'${e.replace(/'/g,"''")}'`}function ga(e){return `'${`{${e.map(r=>`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`).join(",")}}`.replace(/'/g,"''")}'`}function ya(e){return e==="sqlite"?[`CREATE TABLE IF NOT EXISTS migrations (
|
|
60
60
|
version TEXT NOT NULL PRIMARY KEY,
|
|
61
61
|
statements TEXT,
|
|
62
62
|
name TEXT
|
|
@@ -70,21 +70,21 @@ create table test (
|
|
|
70
70
|
)`,`CREATE TABLE IF NOT EXISTS supabase_migrations.seed_files (
|
|
71
71
|
path text NOT NULL PRIMARY KEY,
|
|
72
72
|
hash text NOT NULL
|
|
73
|
-
)`]}function
|
|
74
|
-
`)+";",i=await
|
|
75
|
-
${c}`)}return o.reduce((l,c)=>l+c.statements.length,0)}async function
|
|
73
|
+
)`]}function Mr(e,t){let{schema_migrations:n}=De(e),r=t.name===null?"NULL":Gt(t.name),i=e==="pg"?ga(t.statements):Gt(JSON.stringify(t.statements));return `INSERT INTO ${n} (version, statements, name) VALUES (${Gt(t.version)}, ${i}, ${r})`}function ba(e){let{schema_migrations:t}=De(e);return `SELECT version FROM ${t} ORDER BY version ASC`}function wa(e){let{seed_files:t}=De(e);return t?`SELECT path, hash FROM ${t}`:null}function Hr(e,t){let{seed_files:n}=De(e);return n?`INSERT INTO ${n} (path, hash) VALUES (${Gt(t.path)}, ${Gt(t.hash)}) ON CONFLICT (path) DO UPDATE SET hash = EXCLUDED.hash`:null}async function Sa(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 xa(e){return e.split(/;\s*(?:\n|$)/).map(t=>t.trim()).filter(t=>t.length>0)}async function je(e){let t=ct(e),r=ya(t).map(s=>s.trim()).join(`;
|
|
74
|
+
`)+";",i=await Sa(e,r);for(let s of xa(i))await e.exec(s);}async function qr(e){let t=ct(e);return ((await e.exec(ba(t)))?.rows??[]).map(r=>r.version)}async function Vr(e){let t=ct(e),n=wa(t);return n?((await e.exec(n))?.rows??[]).map(i=>({path:i.path,hash:i.hash})):[]}var Ta=/^(\d{14})(?:_([^.]+))?\.sql$/;function Gr(e){return ct(e.connection)==="sqlite"?"./sqlite-migrations/*.sql":"./migrations/*.sql"}function Aa(e){return it__default.posix.dirname(Gr(e))}async function Wt(e){let t=it__default.join(process.cwd(),"supabase"),n=await Vt([Gr(e)],{cwd:t,absolute:true}),r=[];for(let i of n){let s=it__default.basename(i),o=Ta.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 mi="supabase/.temp/.translation-cache.json",hi=2;async function il(e,t){let n=await e.connection.introspect(),r=Bn(n);await di(e,{...t,dbHasTables:n.tables.length>0,dbFingerprint:r}),await ll(e);let i=await e.connection.introspect();yi(i,e);}async function sl(e){return Vt(e.config.db?.seed?.sql_paths??["./seed.sql"],{cwd:it__default.join(process.cwd(),"supabase"),absolute:true})}async function ol(e){let t=await sl(e);return Promise.all(t.map(async n=>{let r=await M__default.readFile(n,"utf-8"),i=createHash("sha256").update(r).digest("hex");return {path:it__default.relative(process.cwd(),n),hash:i,statements:splitSqlStatements(r)}}))}async function al(e,t){if(e.config.db?.seed?.enabled===false)return 0;let r=(await ol(e)).filter(l=>l.statements.length>0);if(r.length===0)return 0;await je(e.connection);let i=ct(e.connection),s=new Map((await Vr(e.connection)).map(l=>[l.path,l.hash])),o=r.filter(l=>s.get(l.path)!==l.hash);if(o.length===0)return 0;console.log($.default.dim("Seeding database..."));let a=[];for(let l of o){a.push(...l.statements);let c=Hr(i,{path:l.path,hash:l.hash});c&&a.push(c);}try{await e.connection.transaction(a);}catch(l){let c="Fix `supabase/seed.sql`, then re-run `lite dev` to reapply the schema and reseed.";throw new Error(`Seed failed and was rolled back: ${String(l.message??l)}
|
|
75
|
+
${c}`)}return o.reduce((l,c)=>l+c.statements.length,0)}async function ll(e){await al(e);}async function cl(e){let t=await Vt(e.config?.db?.migrations?.schema_paths??["./schemas/*.sql"],{cwd:it__default.join(process.cwd(),"supabase"),absolute:true}),n=await Promise.all(t.map(async r=>await M__default.readFile(r,"utf-8"))).then(r=>r.map(i=>i.split(`
|
|
76
76
|
`).filter(s=>s.trim().length>0&&!s.trim().startsWith("--")).join(`
|
|
77
77
|
`)).join(`
|
|
78
|
-
`));return n||""}async function
|
|
78
|
+
`));return n||""}async function di(e,t){let n=await cl(e);if(!(!n&&(await Wt(e)).length>0)&&!(!n&&!e.connection.config.baseSchema)){if(t?.dbHasTables&&await fl(e,n,t.dbFingerprint)){console.log($.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=Bn(o);if(i.plan.steps.length===0){await pi(e,n,s,a);return}await r.migratePlan(i.plan,{force:t?.force??!1}),dl(i);let l=await e.connection.introspect();return await pi(e,n,s,Bn(l)),console.log(""),gl(i),i}catch(r){if(String(r).includes("likely empty"))console.log($.default.dim("Nothing to migrate."));else {console.error("Migration error: "+String(r));try{await e.connection.exec("rollback");}catch{}}}}}function ul(e){return e.connection.config?.baseSchema??""}function gi(e,t){let n=createHash("sha256");return n.update(JSON.stringify([ul(e),t??""])),n.digest("hex")}function Bn(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 fl(e,t,n){let r=e.connection;if(typeof r.updateDeparseInfo!="function")return false;let i=it__default.join(process.cwd(),mi),s;try{s=await M__default.readFile(i,"utf-8");}catch{return false}let o;try{o=JSON.parse(s);}catch{return false}if(o.v!==hi||o.hash!==gi(e,t)||!n||o.dbFingerprint!==n||!o.ast||typeof o.ast!="object")return false;try{let a=await Promise.resolve().then(()=>(ui(),ci)),l=o.ast,c=a.collectEnums(l),u=a.collectSchema(l,c),h=a.collectVariables(l),d=a.collectTableConstraints(l),g=a.collectComments(l),b=r.config?.translation?.schemas?.defaultSchema,{policies:E,tables:T}=a.collectPolicies(l,{defaultSchema:b});return r.updateDeparseInfo({enums:c,rls:{tables:T,policies:E},schema:u,vars:h,tableConstraints:d,comments:g}),!0}catch{return false}}async function pi(e,t,n,r){if(!n||typeof n!="object")return;let i={v:hi,hash:gi(e,t),dbFingerprint:r,ast:n},s=it__default.join(process.cwd(),mi);try{await M__default.mkdir(it__default.dirname(s),{recursive:!0}),await M__default.writeFile(s,JSON.stringify(i),"utf-8");}catch{}}function yi(e,t){console.log();let n=(i,s)=>{let o=l=>{let c=$.default.dim;return typeof l=="number"&&(l>=0&&(c=l>0?$.default.green:$.default.dim),l<0&&(c=$.default.red)),typeof l=="boolean"?l?$.default.green("\u2713"):$.default.red("\u2717"):c(String(l))},a=Object.entries(s).map(([l,c])=>`${l}: ${o(c)}`).join($.default.dim(" / "));console.log(`${$.default.dim("[")} ${i} ${$.default.dim("]")} ${a}`);};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($.default.green("AUTH"),{enabled:!!t.config.auth?.enabled,tables:ensureVar.Set(r.tables).size,policies:ensureVar.Array(r.policies).length});}function pl(e,t){setTimeout(()=>{console.log($.default.dim("Watching for changes...")),rl.watch("./supabase/schemas").on("change",async r=>{console.log(),console.log($.default.dim(`Schema changed: ${r}`)),await di(e,t);let i=await e.connection.introspect();yi(i,e);});},200);}function ml(e,t){let n=r=>r;return e.plan.steps.flatMap(r=>[r.description?n(`-- ${r.description}`):"",r.sql+`
|
|
79
79
|
`]).filter(r=>r.trim().length>0).join(`
|
|
80
|
-
`)}function
|
|
80
|
+
`)}function hl(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 dl(e,t){let n="./supabase/.temp/migrations";tt(n);let r=hl(),i=ml(e);yt(it__default.join(n,r),i),console.log($.default.dim(`Migration written to ${$.default.cyan(it__default.join(n,r))}`));}function gl({diff:e}){if(typeof e=="string"){console.log($.default.cyan(e));return}if(!e.has_changes)return;console.log($.default.bgWhite($.default.black(" Schema Diff "))),console.log();let t={added:{color:$.default.green,symbol:"+"},removed:{color:$.default.red,symbol:"-"},modified:{color:$.default.yellow,symbol:"~"}};if(e.tables.length>0){console.log($.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($.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($.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($.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();}}var Hn=["anon","authenticated","service_role"];function yl(e){return e==="service_role"?"NOLOGIN BYPASSRLS":"NOLOGIN"}function qn(e){return e.size===0?"":`DO $$ BEGIN${[...e].map(n=>`
|
|
81
81
|
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '${n}') THEN
|
|
82
|
-
CREATE ROLE ${n} ${
|
|
82
|
+
CREATE ROLE ${n} ${yl(n)};
|
|
83
83
|
END IF;`).join("")}
|
|
84
84
|
END $$;
|
|
85
|
-
`}
|
|
86
|
-
`;)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=
|
|
87
|
-
`);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
|
|
85
|
+
`}qn(new Set(Hn));function wi(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 bl(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 wl(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 Sl(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 Si(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]!==`
|
|
86
|
+
`;)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=wl(e,n);continue}if(r==="$"){let s=Sl(e,n);if(s!==void 0){n=s;continue}}if(r==='"'){let{token:s,end:o}=bl(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 xl(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 El(e){let t=new Set,n=Si(e);for(let r=0;r<n.length;r++){if(nt(n[r])!=="create")continue;let i=xl(n,r);for(let s of Hn)wi(i,s)&&t.add(s);}return t}function Mn(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 Hn)wi(e[i],o)&&n.add(o);}}function Tl(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 bi(e,t){return e.some(n=>nt(n)===t)}function Al(e){let t=new Set,n=Tl(Si(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"&&(bi(r,"grant")||bi(r,"policy")||nt(r[a-1])==="owner")&&Mn(r,a+1,t),l==="from"&&i==="revoke"&&Mn(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)&&Mn(r,1,t);}return t}function xi(e){let t=El(e);return new Set([...Al(e)].filter(n=>!t.has(n)))}async function _l(e){await Rl(e),await je(e.connection);let t=new Set(await qr(e.connection)),n=await Wt(e),r=ct(e.connection),i=[],s=[];for(let o of n){if(t.has(o.version)){s.push(o);continue}let a=Ae(o.sql),l;if(r==="pg-flat"){let u=await e.connection.translateDdl(o.sql),h=typeof u=="string"?u:u.ddl??"";l=Ae(h);}else l=a;let c=Mr(r,{version:o.version,name:o.name,statements:a});if(r==="pg"){let u=qn(xi(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 Cl(e,n),{applied:i,skipped:s}}async function Cl(e,t){let n=t.map(o=>o.sql).join(`
|
|
87
|
+
`);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 Rl(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 Ae(r))try{await n.exec(i);}catch{}}/*! Bundled license information:
|
|
88
88
|
|
|
89
89
|
smol-toml/dist/error.js:
|
|
90
90
|
smol-toml/dist/util.js:
|
|
@@ -122,4 +122,4 @@ smol-toml/dist/index.js:
|
|
|
122
122
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
123
123
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
124
124
|
*)
|
|
125
|
-
*/export{
|
|
125
|
+
*/export{_l as applyPendingMigrations,hs as createApi,bs as ensureInitialStructure,il as ensureSchema,Wt as listMigrationFiles,Aa as migrationsDir,pl as watchSchema};
|