@supabase/lite 0.2.0 → 0.2.1-next.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/lib.js CHANGED
@@ -1,4 +1,4 @@
1
- import*as v from'node:path';import v__default,{resolve,join,relative,sep as sep$1}from'node:path';import In,{type}from'node:os';import Ne,{stat as stat$1,unwatchFile,watchFile,watch}from'node:fs';import {createClient}from'@supabase/supabase-js';import {ensureVar,App,splitSqlStatements}from'@supabase/lite';import {cloud,createConnection}from'@supabase/lite/sqlite';import*as G from'node:fs/promises';import G__default,{stat,realpath,lstat,readdir,open}from'node:fs/promises';import {createHash}from'node:crypto';import {parse}from'dotenv';import'node:url';import*as Dt from'fs';import Dt__default from'fs';import cr,{posix,sep,basename,dirname,resolve as resolve$1,normalize,relative as relative$1}from'path';import {fileURLToPath}from'url';import {createRequire}from'module';import {EventEmitter}from'node:events';import {Readable}from'node:stream';try {
1
+ import'pgsql-deparser';import*as nt from'node:path';import nt__default from'node:path';import gi from'node:os';import le 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 At from'fs';import At__default from'fs';import vr,{posix,sep,basename,dirname,resolve,normalize,relative}from'path';import {fileURLToPath}from'url';import {createRequire}from'module';import La from'chokidar';try {
2
2
  /**
3
3
  * Adding this to avoid warnings from node:sqlite being experimental
4
4
  */
@@ -9,70 +9,41 @@ import*as v from'node:path';import v__default,{resolve,join,relative,sep as sep$
9
9
  };
10
10
  } catch {}
11
11
 
12
- var bn=Object.create;var os=Object.defineProperty;var On=Object.getOwnPropertyDescriptor;var _n=Object.getOwnPropertyNames;var wn=Object.getPrototypeOf,dn=Object.prototype.hasOwnProperty;var P=(a,t)=>()=>(a&&(t=a(a=0)),t);var Ct=(a,t)=>()=>(t||a((t={exports:{}}).exports,t),t.exports),yn=(a,t)=>{for(var s in t)os(a,s,{get:t[s],enumerable:true});},Ln=(a,t,s,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of _n(t))!dn.call(a,i)&&i!==s&&os(a,i,{get:()=>t[i],enumerable:!(e=On(t,i))||e.enumerable});return a};var Ut=(a,t,s)=>(s=a!=null?bn(wn(a)):{},Ln(os(s,"default",{value:a,enumerable:true}),a));var Mt=Ct((Dp,ls)=>{var de=process||{},Ei=de.argv||[],we=de.env||{},$n=!(we.NO_COLOR||Ei.includes("--no-color"))&&(!!we.FORCE_COLOR||Ei.includes("--color")||de.platform==="win32"||(de.stdout||{}).isTTY&&we.TERM!=="dumb"||!!we.CI),jn=(a,t,s=a)=>e=>{let i=""+e,r=i.indexOf(t,a.length);return ~r?a+kn(i,t,s,r)+t:a+i+t},kn=(a,t,s,e)=>{let i="",r=0;do i+=a.substring(r,e)+s,r=e+t.length,e=a.indexOf(t,r);while(~e);return i+a.substring(r)},gi=(a=$n)=>{let t=a?jn:()=>String;return {isColorSupported:a,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")}};ls.exports=gi();ls.exports.createColors=gi;});var Jt=Ct(($f,Wi)=>{var xi="[^\\\\/]",go="(?=.)",qi="[^/]",Os="(?:\\/|$)",Vi="(?:^|\\/)",_s=`\\.{1,2}${Os}`,To="(?!\\.)",So=`(?!${Vi}${_s})`,Ao=`(?!\\.{0,1}${Os})`,Co=`(?!${_s})`,Ro="[^.\\/]",No=`${qi}*?`,bo="/",Gi={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:go,QMARK:qi,END_ANCHOR:Os,DOTS_SLASH:_s,NO_DOT:To,NO_DOTS:So,NO_DOT_SLASH:Ao,NO_DOTS_SLASH:Co,QMARK_NO_DOT:Ro,STAR:No,START_ANCHOR:Vi,SEP:bo},Oo={...Gi,SLASH_LITERAL:"[\\\\/]",QMARK:xi,STAR:`${xi}*?`,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:"\\"},_o={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"};Wi.exports={MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:_o,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(a){return {"!":{type:"negate",open:"(?:(?!(?:",close:`))${a.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(a){return a===true?Oo:Gi}};});var Yt=Ct(tt=>{var{REGEX_BACKSLASH:wo,REGEX_REMOVE_BACKSLASH:yo,REGEX_SPECIAL_CHARS:Lo,REGEX_SPECIAL_CHARS_GLOBAL:Io}=Jt();tt.isObject=a=>a!==null&&typeof a=="object"&&!Array.isArray(a);tt.hasRegexChars=a=>Lo.test(a);tt.isRegexChar=a=>a.length===1&&tt.hasRegexChars(a);tt.escapeRegex=a=>a.replace(Io,"\\$1");tt.toPosixSlashes=a=>a.replace(wo,"/");tt.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let a=navigator.platform.toLowerCase();return a==="win32"||a==="windows"}return typeof process<"u"&&process.platform?process.platform==="win32":false};tt.removeBackslashes=a=>a.replace(yo,t=>t==="\\"?"":t);tt.escapeLast=(a,t,s)=>{let e=a.lastIndexOf(t,s);return e===-1?a:a[e-1]==="\\"?tt.escapeLast(a,t,e-1):`${a.slice(0,e)}\\${a.slice(e)}`};tt.removePrefix=(a,t={})=>{let s=a;return s.startsWith("./")&&(s=s.slice(2),t.prefix="./"),s};tt.wrapOutput=(a,t={},s={})=>{let e=s.contains?"":"^",i=s.contains?"":"$",r=`${e}(?:${a})${i}`;return t.negated===true&&(r=`(?:^(?!${r}).*$)`),r};tt.basename=(a,{windows:t}={})=>{let s=a.split(t?/[\\/]/:"/"),e=s[s.length-1];return e===""?s[s.length-2]:e};});var Zi=Ct((kf,Qi)=>{var Hi=Yt(),{CHAR_ASTERISK:ws,CHAR_AT:vo,CHAR_BACKWARD_SLASH:Xt,CHAR_COMMA:Do,CHAR_DOT:ds,CHAR_EXCLAMATION_MARK:ys,CHAR_FORWARD_SLASH:zi,CHAR_LEFT_CURLY_BRACE:Ls,CHAR_LEFT_PARENTHESES:Is,CHAR_LEFT_SQUARE_BRACKET:Po,CHAR_PLUS:$o,CHAR_QUESTION_MARK:Ji,CHAR_RIGHT_CURLY_BRACE:jo,CHAR_RIGHT_PARENTHESES:Yi,CHAR_RIGHT_SQUARE_BRACKET:ko}=Jt(),Xi=a=>a===zi||a===Xt,Ki=a=>{a.isPrefix!==true&&(a.depth=a.isGlobstar?1/0:1);},Fo=(a,t)=>{let s=t||{},e=a.length-1,i=s.parts===true||s.scanToEnd===true,r=[],n=[],o=[],u=a,l=-1,p=0,f=0,h=false,E=false,g=false,R=false,b=false,d=false,O=false,J=false,et=false,Y=false,W=0,z,w,L={value:"",depth:0,isGlob:false},A=()=>l>=e,K=()=>u.charCodeAt(l+1),_=()=>(z=w,u.charCodeAt(++l));for(;l<e;){w=_();let k;if(w===Xt){O=L.backslashes=true,w=_(),w===Ls&&(d=true);continue}if(d===true||w===Ls){for(W++;A()!==true&&(w=_());){if(w===Xt){O=L.backslashes=true,_();continue}if(w===Ls){W++;continue}if(d!==true&&w===ds&&(w=_())===ds){if(h=L.isBrace=true,g=L.isGlob=true,Y=true,i===true)continue;break}if(d!==true&&w===Do){if(h=L.isBrace=true,g=L.isGlob=true,Y=true,i===true)continue;break}if(w===jo&&(W--,W===0)){d=false,h=L.isBrace=true,Y=true;break}}if(i===true)continue;break}if(w===zi){if(r.push(l),n.push(L),L={value:"",depth:0,isGlob:false},Y===true)continue;if(z===ds&&l===p+1){p+=2;continue}f=l+1;continue}if(s.noext!==true&&(w===$o||w===vo||w===ws||w===Ji||w===ys)===true&&K()===Is){if(g=L.isGlob=true,R=L.isExtglob=true,Y=true,w===ys&&l===p&&(et=true),i===true){for(;A()!==true&&(w=_());){if(w===Xt){O=L.backslashes=true,w=_();continue}if(w===Yi){g=L.isGlob=true,Y=true;break}}continue}break}if(w===ws){if(z===ws&&(b=L.isGlobstar=true),g=L.isGlob=true,Y=true,i===true)continue;break}if(w===Ji){if(g=L.isGlob=true,Y=true,i===true)continue;break}if(w===Po){for(;A()!==true&&(k=_());){if(k===Xt){O=L.backslashes=true,_();continue}if(k===ko){E=L.isBracket=true,g=L.isGlob=true,Y=true;break}}if(i===true)continue;break}if(s.nonegate!==true&&w===ys&&l===p){J=L.negated=true,p++;continue}if(s.noparen!==true&&w===Is){if(g=L.isGlob=true,i===true){for(;A()!==true&&(w=_());){if(w===Is){O=L.backslashes=true,w=_();continue}if(w===Yi){Y=true;break}}continue}break}if(g===true){if(Y=true,i===true)continue;break}}s.noext===true&&(R=false,g=false);let j=u,S="",T="";p>0&&(S=u.slice(0,p),u=u.slice(p),f-=p),j&&g===true&&f>0?(j=u.slice(0,f),T=u.slice(f)):g===true?(j="",T=u):j=u,j&&j!==""&&j!=="/"&&j!==u&&Xi(j.charCodeAt(j.length-1))&&(j=j.slice(0,-1)),s.unescape===true&&(T&&(T=Hi.removeBackslashes(T)),j&&O===true&&(j=Hi.removeBackslashes(j)));let it={prefix:S,input:a,start:p,base:j,glob:T,isBrace:h,isBracket:E,isGlob:g,isExtglob:R,isGlobstar:b,negated:J,negatedExtglob:et};if(s.tokens===true&&(it.maxDepth=0,Xi(w)||n.push(L),it.tokens=n),s.parts===true||s.tokens===true){let k;for(let B=0;B<r.length;B++){let ct=k?k+1:p,rt=r[B],Et=a.slice(ct,rt);s.tokens&&(B===0&&p!==0?(n[B].isPrefix=true,n[B].value=S):n[B].value=Et,Ki(n[B]),it.maxDepth+=n[B].depth),(B!==0||Et!=="")&&o.push(Et),k=rt;}if(k&&k+1<a.length){let B=a.slice(k+1);o.push(B),s.tokens&&(n[n.length-1].value=B,Ki(n[n.length-1]),it.maxDepth+=n[n.length-1].depth);}it.slashes=r,it.parts=o;}return it};Qi.exports=Fo;});var sr=Ct((Ff,er)=>{var xe=Jt(),pt=Yt(),{MAX_LENGTH:qe,POSIX_REGEX_SOURCE:Uo,REGEX_NON_SPECIAL_CHARS:Bo,REGEX_SPECIAL_CHARS_BACKREF:Mo,REPLACEMENTS:tr}=xe,xo=(a,t)=>{if(typeof t.expandRange=="function")return t.expandRange(...a,t);a.sort();let s=`[${a.join("-")}]`;try{new RegExp(s);}catch{return a.map(i=>pt.escapeRegex(i)).join("..")}return s},vt=(a,t)=>`Missing ${a}: "${t}" - use "\\\\${t}" to match literal characters`,vs=(a,t)=>{if(typeof a!="string")throw new TypeError("Expected a string");a=tr[a]||a;let s={...t},e=typeof s.maxLength=="number"?Math.min(qe,s.maxLength):qe,i=a.length;if(i>e)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${e}`);let r={type:"bos",value:"",output:s.prepend||""},n=[r],o=s.capture?"":"?:",u=xe.globChars(s.windows),l=xe.extglobChars(u),{DOT_LITERAL:p,PLUS_LITERAL:f,SLASH_LITERAL:h,ONE_CHAR:E,DOTS_SLASH:g,NO_DOT:R,NO_DOT_SLASH:b,NO_DOTS_SLASH:d,QMARK:O,QMARK_NO_DOT:J,STAR:et,START_ANCHOR:Y}=u,W=N=>`(${o}(?:(?!${Y}${N.dot?g:p}).)*?)`,z=s.dot?"":R,w=s.dot?O:J,L=s.bash===true?W(s):et;s.capture&&(L=`(${L})`),typeof s.noext=="boolean"&&(s.noextglob=s.noext);let A={input:a,index:-1,start:0,dot:s.dot===true,consumed:"",output:"",prefix:"",backtrack:false,negated:false,brackets:0,braces:0,parens:0,quotes:0,globstar:false,tokens:n};a=pt.removePrefix(a,A),i=a.length;let K=[],_=[],j=[],S=r,T,it=()=>A.index===i-1,k=A.peek=(N=1)=>a[A.index+N],B=A.advance=()=>a[++A.index]||"",ct=()=>a.slice(A.index+1),rt=(N="",F=0)=>{A.consumed+=N,A.index+=F;},Et=N=>{A.output+=N.output!=null?N.output:N.value,rt(N.value);},Rn=()=>{let N=1;for(;k()==="!"&&(k(2)!=="("||k(3)==="?");)B(),A.start++,N++;return N%2===0?false:(A.negated=true,A.start++,true)},Ae=N=>{A[N]++,j.push(N);},At=N=>{A[N]--,j.pop();},D=N=>{if(S.type==="globstar"){let F=A.braces>0&&(N.type==="comma"||N.type==="brace"),C=N.extglob===true||K.length&&(N.type==="pipe"||N.type==="paren");N.type!=="slash"&&N.type!=="paren"&&!F&&!C&&(A.output=A.output.slice(0,-S.output.length),S.type="star",S.value="*",S.output=L,A.output+=S.output);}if(K.length&&N.type!=="paren"&&(K[K.length-1].inner+=N.value),(N.value||N.output)&&Et(N),S&&S.type==="text"&&N.type==="text"){S.output=(S.output||S.value)+N.value,S.value+=N.value;return}N.prev=S,n.push(N),S=N;},Ce=(N,F)=>{let C={...l[F],conditions:1,inner:""};C.prev=S,C.parens=A.parens,C.output=A.output;let I=(s.capture?"(":"")+C.open;Ae("parens"),D({type:N,value:F,output:A.output?"":E}),D({type:"paren",extglob:true,value:B(),output:I}),K.push(C);},Nn=N=>{let F=N.close+(s.capture?")":""),C;if(N.type==="negate"){let I=L;if(N.inner&&N.inner.length>1&&N.inner.includes("/")&&(I=W(s)),(I!==L||it()||/^\)+$/.test(ct()))&&(F=N.close=`)$))${I}`),N.inner.includes("*")&&(C=ct())&&/^\.[^\\/.]+$/.test(C)){let M=vs(C,{...t,fastpaths:false}).output;F=N.close=`)${M})${I})`;}N.prev.type==="bos"&&(A.negatedExtglob=true);}D({type:"paren",extglob:true,value:T,output:F}),At("parens");};if(s.fastpaths!==false&&!/(^[*!]|[/()[\]{}"])/.test(a)){let N=false,F=a.replace(Mo,(C,I,M,Q,H,as)=>Q==="\\"?(N=true,C):Q==="?"?I?I+Q+(H?O.repeat(H.length):""):as===0?w+(H?O.repeat(H.length):""):O.repeat(M.length):Q==="."?p.repeat(M.length):Q==="*"?I?I+Q+(H?L:""):L:I?C:`\\${C}`);return N===true&&(s.unescape===true?F=F.replace(/\\/g,""):F=F.replace(/\\+/g,C=>C.length%2===0?"\\\\":C?"\\":"")),F===a&&s.contains===true?(A.output=a,A):(A.output=pt.wrapOutput(F,A,t),A)}for(;!it();){if(T=B(),T==="\0")continue;if(T==="\\"){let C=k();if(C==="/"&&s.bash!==true||C==="."||C===";")continue;if(!C){T+="\\",D({type:"text",value:T});continue}let I=/^\\+/.exec(ct()),M=0;if(I&&I[0].length>2&&(M=I[0].length,A.index+=M,M%2!==0&&(T+="\\")),s.unescape===true?T=B():T+=B(),A.brackets===0){D({type:"text",value:T});continue}}if(A.brackets>0&&(T!=="]"||S.value==="["||S.value==="[^")){if(s.posix!==false&&T===":"){let C=S.value.slice(1);if(C.includes("[")&&(S.posix=true,C.includes(":"))){let I=S.value.lastIndexOf("["),M=S.value.slice(0,I),Q=S.value.slice(I+2),H=Uo[Q];if(H){S.value=M+H,A.backtrack=true,B(),!r.output&&n.indexOf(S)===1&&(r.output=E);continue}}}(T==="["&&k()!==":"||T==="-"&&k()==="]")&&(T=`\\${T}`),T==="]"&&(S.value==="["||S.value==="[^")&&(T=`\\${T}`),s.posix===true&&T==="!"&&S.value==="["&&(T="^"),S.value+=T,Et({value:T});continue}if(A.quotes===1&&T!=='"'){T=pt.escapeRegex(T),S.value+=T,Et({value:T});continue}if(T==='"'){A.quotes=A.quotes===1?0:1,s.keepQuotes===true&&D({type:"text",value:T});continue}if(T==="("){Ae("parens"),D({type:"paren",value:T});continue}if(T===")"){if(A.parens===0&&s.strictBrackets===true)throw new SyntaxError(vt("opening","("));let C=K[K.length-1];if(C&&A.parens===C.parens+1){Nn(K.pop());continue}D({type:"paren",value:T,output:A.parens?")":"\\)"}),At("parens");continue}if(T==="["){if(s.nobracket===true||!ct().includes("]")){if(s.nobracket!==true&&s.strictBrackets===true)throw new SyntaxError(vt("closing","]"));T=`\\${T}`;}else Ae("brackets");D({type:"bracket",value:T});continue}if(T==="]"){if(s.nobracket===true||S&&S.type==="bracket"&&S.value.length===1){D({type:"text",value:T,output:`\\${T}`});continue}if(A.brackets===0){if(s.strictBrackets===true)throw new SyntaxError(vt("opening","["));D({type:"text",value:T,output:`\\${T}`});continue}At("brackets");let C=S.value.slice(1);if(S.posix!==true&&C[0]==="^"&&!C.includes("/")&&(T=`/${T}`),S.value+=T,Et({value:T}),s.literalBrackets===false||pt.hasRegexChars(C))continue;let I=pt.escapeRegex(S.value);if(A.output=A.output.slice(0,-S.value.length),s.literalBrackets===true){A.output+=I,S.value=I;continue}S.value=`(${o}${I}|${S.value})`,A.output+=S.value;continue}if(T==="{"&&s.nobrace!==true){Ae("braces");let C={type:"brace",value:T,output:"(",outputIndex:A.output.length,tokensIndex:A.tokens.length};_.push(C),D(C);continue}if(T==="}"){let C=_[_.length-1];if(s.nobrace===true||!C){D({type:"text",value:T,output:T});continue}let I=")";if(C.dots===true){let M=n.slice(),Q=[];for(let H=M.length-1;H>=0&&(n.pop(),M[H].type!=="brace");H--)M[H].type!=="dots"&&Q.unshift(M[H].value);I=xo(Q,s),A.backtrack=true;}if(C.comma!==true&&C.dots!==true){let M=A.output.slice(0,C.outputIndex),Q=A.tokens.slice(C.tokensIndex);C.value=C.output="\\{",T=I="\\}",A.output=M;for(let H of Q)A.output+=H.output||H.value;}D({type:"brace",value:T,output:I}),At("braces"),_.pop();continue}if(T==="|"){K.length>0&&K[K.length-1].conditions++,D({type:"text",value:T});continue}if(T===","){let C=T,I=_[_.length-1];I&&j[j.length-1]==="braces"&&(I.comma=true,C="|"),D({type:"comma",value:T,output:C});continue}if(T==="/"){if(S.type==="dot"&&A.index===A.start+1){A.start=A.index+1,A.consumed="",A.output="",n.pop(),S=r;continue}D({type:"slash",value:T,output:h});continue}if(T==="."){if(A.braces>0&&S.type==="dot"){S.value==="."&&(S.output=p);let C=_[_.length-1];S.type="dots",S.output+=T,S.value+=T,C.dots=true;continue}if(A.braces+A.parens===0&&S.type!=="bos"&&S.type!=="slash"){D({type:"text",value:T,output:p});continue}D({type:"dot",value:T,output:p});continue}if(T==="?"){if(!(S&&S.value==="(")&&s.noextglob!==true&&k()==="("&&k(2)!=="?"){Ce("qmark",T);continue}if(S&&S.type==="paren"){let I=k(),M=T;(S.value==="("&&!/[!=<:]/.test(I)||I==="<"&&!/<([!=]|\w+>)/.test(ct()))&&(M=`\\${T}`),D({type:"text",value:T,output:M});continue}if(s.dot!==true&&(S.type==="slash"||S.type==="bos")){D({type:"qmark",value:T,output:J});continue}D({type:"qmark",value:T,output:O});continue}if(T==="!"){if(s.noextglob!==true&&k()==="("&&(k(2)!=="?"||!/[!=<:]/.test(k(3)))){Ce("negate",T);continue}if(s.nonegate!==true&&A.index===0){Rn();continue}}if(T==="+"){if(s.noextglob!==true&&k()==="("&&k(2)!=="?"){Ce("plus",T);continue}if(S&&S.value==="("||s.regex===false){D({type:"plus",value:T,output:f});continue}if(S&&(S.type==="bracket"||S.type==="paren"||S.type==="brace")||A.parens>0){D({type:"plus",value:T});continue}D({type:"plus",value:f});continue}if(T==="@"){if(s.noextglob!==true&&k()==="("&&k(2)!=="?"){D({type:"at",extglob:true,value:T,output:""});continue}D({type:"text",value:T});continue}if(T!=="*"){(T==="$"||T==="^")&&(T=`\\${T}`);let C=Bo.exec(ct());C&&(T+=C[0],A.index+=C[0].length),D({type:"text",value:T});continue}if(S&&(S.type==="globstar"||S.star===true)){S.type="star",S.star=true,S.value+=T,S.output=L,A.backtrack=true,A.globstar=true,rt(T);continue}let N=ct();if(s.noextglob!==true&&/^\([^?]/.test(N)){Ce("star",T);continue}if(S.type==="star"){if(s.noglobstar===true){rt(T);continue}let C=S.prev,I=C.prev,M=C.type==="slash"||C.type==="bos",Q=I&&(I.type==="star"||I.type==="globstar");if(s.bash===true&&(!M||N[0]&&N[0]!=="/")){D({type:"star",value:T,output:""});continue}let H=A.braces>0&&(C.type==="comma"||C.type==="brace"),as=K.length&&(C.type==="pipe"||C.type==="paren");if(!M&&C.type!=="paren"&&!H&&!as){D({type:"star",value:T,output:""});continue}for(;N.slice(0,3)==="/**";){let Re=a[A.index+4];if(Re&&Re!=="/")break;N=N.slice(3),rt("/**",3);}if(C.type==="bos"&&it()){S.type="globstar",S.value+=T,S.output=W(s),A.output=S.output,A.globstar=true,rt(T);continue}if(C.type==="slash"&&C.prev.type!=="bos"&&!Q&&it()){A.output=A.output.slice(0,-(C.output+S.output).length),C.output=`(?:${C.output}`,S.type="globstar",S.output=W(s)+(s.strictSlashes?")":"|$)"),S.value+=T,A.globstar=true,A.output+=C.output+S.output,rt(T);continue}if(C.type==="slash"&&C.prev.type!=="bos"&&N[0]==="/"){let Re=N[1]!==void 0?"|$":"";A.output=A.output.slice(0,-(C.output+S.output).length),C.output=`(?:${C.output}`,S.type="globstar",S.output=`${W(s)}${h}|${h}${Re})`,S.value+=T,A.output+=C.output+S.output,A.globstar=true,rt(T+B()),D({type:"slash",value:"/",output:""});continue}if(C.type==="bos"&&N[0]==="/"){S.type="globstar",S.value+=T,S.output=`(?:^|${h}|${W(s)}${h})`,A.output=S.output,A.globstar=true,rt(T+B()),D({type:"slash",value:"/",output:""});continue}A.output=A.output.slice(0,-S.output.length),S.type="globstar",S.output=W(s),S.value+=T,A.output+=S.output,A.globstar=true,rt(T);continue}let F={type:"star",value:T,output:L};if(s.bash===true){F.output=".*?",(S.type==="bos"||S.type==="slash")&&(F.output=z+F.output),D(F);continue}if(S&&(S.type==="bracket"||S.type==="paren")&&s.regex===true){F.output=T,D(F);continue}(A.index===A.start||S.type==="slash"||S.type==="dot")&&(S.type==="dot"?(A.output+=b,S.output+=b):s.dot===true?(A.output+=d,S.output+=d):(A.output+=z,S.output+=z),k()!=="*"&&(A.output+=E,S.output+=E)),D(F);}for(;A.brackets>0;){if(s.strictBrackets===true)throw new SyntaxError(vt("closing","]"));A.output=pt.escapeLast(A.output,"["),At("brackets");}for(;A.parens>0;){if(s.strictBrackets===true)throw new SyntaxError(vt("closing",")"));A.output=pt.escapeLast(A.output,"("),At("parens");}for(;A.braces>0;){if(s.strictBrackets===true)throw new SyntaxError(vt("closing","}"));A.output=pt.escapeLast(A.output,"{"),At("braces");}if(s.strictSlashes!==true&&(S.type==="star"||S.type==="bracket")&&D({type:"maybe_slash",value:"",output:`${h}?`}),A.backtrack===true){A.output="";for(let N of A.tokens)A.output+=N.output!=null?N.output:N.value,N.suffix&&(A.output+=N.suffix);}return A};vs.fastpaths=(a,t)=>{let s={...t},e=typeof s.maxLength=="number"?Math.min(qe,s.maxLength):qe,i=a.length;if(i>e)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${e}`);a=tr[a]||a;let{DOT_LITERAL:r,SLASH_LITERAL:n,ONE_CHAR:o,DOTS_SLASH:u,NO_DOT:l,NO_DOTS:p,NO_DOTS_SLASH:f,STAR:h,START_ANCHOR:E}=xe.globChars(s.windows),g=s.dot?p:l,R=s.dot?f:l,b=s.capture?"":"?:",d={negated:false,prefix:""},O=s.bash===true?".*?":h;s.capture&&(O=`(${O})`);let J=z=>z.noglobstar===true?O:`(${b}(?:(?!${E}${z.dot?u:r}).)*?)`,et=z=>{switch(z){case "*":return `${g}${o}${O}`;case ".*":return `${r}${o}${O}`;case "*.*":return `${g}${O}${r}${o}${O}`;case "*/*":return `${g}${O}${n}${o}${R}${O}`;case "**":return g+J(s);case "**/*":return `(?:${g}${J(s)}${n})?${R}${o}${O}`;case "**/*.*":return `(?:${g}${J(s)}${n})?${R}${O}${r}${o}${O}`;case "**/.*":return `(?:${g}${J(s)}${n})?${r}${o}${O}`;default:{let w=/^(.*?)\.(\w+)$/.exec(z);if(!w)return;let L=et(w[1]);return L?L+r+w[2]:void 0}}},Y=pt.removePrefix(a,d),W=et(Y);return W&&s.strictSlashes!==true&&(W+=`${n}?`),W};er.exports=vs;});var nr=Ct((Uf,rr)=>{var qo=Zi(),Ds=sr(),ir=Yt(),Vo=Jt(),Go=a=>a&&typeof a=="object"&&!Array.isArray(a),V=(a,t,s=false)=>{if(Array.isArray(a)){let p=a.map(h=>V(h,t,s));return h=>{for(let E of p){let g=E(h);if(g)return g}return false}}let e=Go(a)&&a.tokens&&a.input;if(a===""||typeof a!="string"&&!e)throw new TypeError("Expected pattern to be a non-empty string");let i=t||{},r=i.windows,n=e?V.compileRe(a,t):V.makeRe(a,t,false,true),o=n.state;delete n.state;let u=()=>false;if(i.ignore){let p={...t,ignore:null,onMatch:null,onResult:null};u=V(i.ignore,p,s);}let l=(p,f=false)=>{let{isMatch:h,match:E,output:g}=V.test(p,n,t,{glob:a,posix:r}),R={glob:a,state:o,regex:n,posix:r,input:p,output:g,match:E,isMatch:h};return typeof i.onResult=="function"&&i.onResult(R),h===false?(R.isMatch=false,f?R:false):u(p)?(typeof i.onIgnore=="function"&&i.onIgnore(R),R.isMatch=false,f?R:false):(typeof i.onMatch=="function"&&i.onMatch(R),f?R:true)};return s&&(l.state=o),l};V.test=(a,t,s,{glob:e,posix:i}={})=>{if(typeof a!="string")throw new TypeError("Expected input to be a string");if(a==="")return {isMatch:false,output:""};let r=s||{},n=r.format||(i?ir.toPosixSlashes:null),o=a===e,u=o&&n?n(a):a;return o===false&&(u=n?n(a):a,o=u===e),(o===false||r.capture===true)&&(r.matchBase===true||r.basename===true?o=V.matchBase(a,t,s,i):o=t.exec(u)),{isMatch:!!o,match:o,output:u}};V.matchBase=(a,t,s)=>(t instanceof RegExp?t:V.makeRe(t,s)).test(ir.basename(a));V.isMatch=(a,t,s)=>V(t,s)(a);V.parse=(a,t)=>Array.isArray(a)?a.map(s=>V.parse(s,t)):Ds(a,{...t,fastpaths:false});V.scan=(a,t)=>qo(a,t);V.compileRe=(a,t,s=false,e=false)=>{if(s===true)return a.output;let i=t||{},r=i.contains?"":"^",n=i.contains?"":"$",o=`${r}(?:${a.output})${n}`;a&&a.negated===true&&(o=`^(?!${o}).*$`);let u=V.toRegex(o,t);return e===true&&(u.state=a),u};V.makeRe=(a,t={},s=false,e=false)=>{if(!a||typeof a!="string")throw new TypeError("Expected a non-empty string");let i={negated:false,fastpaths:true};return t.fastpaths!==false&&(a[0]==="."||a[0]==="*")&&(i.output=Ds.fastpaths(a,t)),i.output||(i=Ds(a,t)),V.compileRe(i,t,s,e)};V.toRegex=(a,t)=>{try{let s=t||{};return new RegExp(a,s.flags||(s.nocase?"i":""))}catch(s){if(t&&t.debug===true)throw s;return /$^/}};V.constants=Vo;rr.exports=V;});var lr=Ct((Bf,ur)=>{var ar=nr(),Wo=Yt();function or(a,t,s=false){return t&&(t.windows===null||t.windows===void 0)&&(t={...t,windows:Wo.isWindows()}),ar(a,t,s)}Object.assign(or,ar);ur.exports=or;});var St,Hs=P(()=>{St=class{newlineChar;tabChar;prettyMode;constructor(t=`
13
- `,s=" ",e=true){this.newlineChar=t,this.tabChar=s,this.prettyMode=e;}format(t,s=" "){return t.filter(e=>e!=null&&e!=="").join(s)}indent(t,s=1){if(!this.prettyMode)return t;let e=this.tabChar.repeat(s);return t.split(this.newlineChar).map(i=>i.trim()?e+i:i).join(this.newlineChar)}parens(t){return `(${t})`}newline(){return this.newlineChar}tab(){return this.tabChar}isPretty(){return this.prettyMode}};});var kt,kr=P(()=>{Hs();kt=class a{indentLevel;prettyMode;isStringLiteral;parentNodeTypes;formatter;select;from;group;sort;insertColumns;update;bool;isColumnConstraint;isDomainConstraint;alterColumnOptions;alterTableOptions;isEnumValue;objtype;subtype;constructor({indentLevel:t=0,prettyMode:s=true,isStringLiteral:e,parentNodeTypes:i=[],formatter:r,select:n,from:o,group:u,sort:l,insertColumns:p,update:f,bool:h,isColumnConstraint:E,isDomainConstraint:g,alterColumnOptions:R,alterTableOptions:b,isEnumValue:d,objtype:O,subtype:J,...et}={}){this.indentLevel=t,this.prettyMode=s,this.isStringLiteral=e,this.parentNodeTypes=i,this.formatter=r||new St(`
14
- `," ",s),this.select=n,this.from=o,this.group=u,this.sort=l,this.insertColumns=p,this.update=f,this.bool=h,this.isColumnConstraint=E,this.isDomainConstraint=g,this.alterColumnOptions=R,this.alterTableOptions=b,this.isEnumValue=d,this.objtype=O,this.subtype=J,Object.assign(this,et);}spawn(t,s={}){return new a({indentLevel:this.indentLevel,prettyMode:this.prettyMode,isStringLiteral:this.isStringLiteral,parentNodeTypes:[...this.parentNodeTypes,t],formatter:this.formatter,select:this.select,from:this.from,group:this.group,sort:this.sort,insertColumns:this.insertColumns,update:this.update,bool:this.bool,isColumnConstraint:this.isColumnConstraint,isDomainConstraint:this.isDomainConstraint,alterColumnOptions:this.alterColumnOptions,alterTableOptions:this.alterTableOptions,isEnumValue:this.isEnumValue,objtype:this.objtype,subtype:this.subtype,...s})}indent(t,s){if(!this.prettyMode)return t;let e=s!==void 0?s:this.indentLevel+1;return this.formatter.indent(t,e)}newline(){return this.formatter.newline()}parens(t){return this.formatter.parens(t)}format(t,s){return this.formatter.format(t,s)}isPretty(){return this.formatter.isPretty()}};});function Qe(a){let t=a.toLowerCase();return Fr.has(t)?"RESERVED_KEYWORD":Mr.has(t)?"TYPE_FUNC_NAME_KEYWORD":Br.has(t)?"COL_NAME_KEYWORD":Ur.has(t)?"UNRESERVED_KEYWORD":"NO_KEYWORD"}var te,Fr,Ur,Br,Mr,Js=P(()=>{te={UNRESERVED_KEYWORD:["abort","absent","absolute","access","action","add","admin","after","aggregate","also","alter","always","asensitive","assertion","assignment","at","atomic","attach","attribute","backward","before","begin","breadth","by","cache","call","called","cascade","cascaded","catalog","chain","characteristics","checkpoint","class","close","cluster","columns","comment","comments","commit","committed","compression","conditional","configuration","conflict","connection","constraints","content","continue","conversion","copy","cost","csv","cube","current","cursor","cycle","data","database","day","deallocate","declare","defaults","deferred","definer","delete","delimiter","delimiters","depends","depth","detach","dictionary","disable","discard","document","domain","double","drop","each","empty","enable","encoding","encrypted","enforced","enum","error","escape","event","exclude","excluding","exclusive","execute","explain","expression","extension","external","family","filter","finalize","first","following","force","format","forward","function","functions","generated","global","granted","groups","handler","header","hold","hour","identity","if","ignore","immediate","immutable","implicit","import","include","including","increment","indent","index","indexes","inherit","inherits","inline","input","insensitive","insert","instead","invoker","isolation","keep","key","keys","label","language","large","last","leakproof","level","listen","load","local","location","lock","locked","logged","lsn","mapping","match","matched","materialized","maxvalue","merge","method","minute","minvalue","mode","month","move","name","names","nested","new","next","nfc","nfd","nfkc","nfkd","no","normalized","nothing","notify","nowait","nulls","object","objects","of","off","oids","old","omit","operator","option","options","ordinality","others","over","overriding","owned","owner","parallel","parameter","parser","partial","partition","partitions","passing","password","path","period","plan","plans","policy","preceding","prepare","prepared","preserve","prior","privileges","procedural","procedure","procedures","program","publication","quote","quotes","range","read","reassign","recursive","ref","referencing","refresh","reindex","relative","release","rename","repeatable","replace","replica","reset","respect","restart","restrict","return","returns","revoke","role","rollback","rollup","routine","routines","rows","rule","savepoint","scalar","schema","schemas","scroll","search","second","security","sequence","sequences","serializable","server","session","set","sets","share","show","simple","skip","snapshot","source","split","sql","stable","standalone","start","statement","statistics","stdin","stdout","storage","stored","strict","string","strip","subscription","support","sysid","system","tables","tablespace","target","temp","template","temporary","text","ties","transaction","transform","trigger","truncate","trusted","type","types","uescape","unbounded","uncommitted","unconditional","unencrypted","unknown","unlisten","unlogged","until","update","vacuum","valid","validate","validator","value","varying","version","view","views","virtual","volatile","wait","whitespace","within","without","work","wrapper","write","xml","year","yes","zone"],RESERVED_KEYWORD:["all","analyse","analyze","and","any","array","as","asc","asymmetric","both","case","cast","check","collate","column","constraint","create","current_catalog","current_date","current_role","current_time","current_timestamp","current_user","default","deferrable","desc","distinct","do","else","end","except","false","fetch","for","foreign","from","grant","group","having","in","initially","intersect","into","lateral","leading","limit","localtime","localtimestamp","not","null","offset","on","only","or","order","placing","primary","references","returning","select","session_user","some","symmetric","system_user","table","then","to","trailing","true","union","unique","user","using","variadic","when","where","window","with"],TYPE_FUNC_NAME_KEYWORD:["authorization","binary","collation","concurrently","cross","current_schema","freeze","full","ilike","inner","is","isnull","join","left","like","natural","notnull","outer","overlaps","right","similar","tablesample","verbose"],COL_NAME_KEYWORD:["between","bigint","bit","boolean","char","character","coalesce","dec","decimal","exists","extract","float","greatest","grouping","inout","int","integer","interval","json","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_scalar","json_serialize","json_table","json_value","least","merge_action","national","nchar","none","normalize","nullif","numeric","out","overlay","position","precision","real","row","setof","smallint","substring","time","timestamp","treat","trim","values","varchar","xmlattributes","xmlconcat","xmlelement","xmlexists","xmlforest","xmlnamespaces","xmlparse","xmlpi","xmlroot","xmlserialize","xmltable"]},Fr=new Set(te.RESERVED_KEYWORD??[]),Ur=new Set(te.UNRESERVED_KEYWORD??[]),Br=new Set(te.COL_NAME_KEYWORD??[]),Mr=new Set(te.TYPE_FUNC_NAME_KEYWORD??[]);});var m,xr=P(()=>{Js();m=class a{static escape(t){return `'${t.replace(/'/g,"''")}'`}static escapeEString(t){return t.replace(/\\/g,"\\\\").replace(/'/g,"''")}static formatEString(t){return a.needsEscapePrefix(t)?`E'${a.escapeEString(t)}'`:a.escape(t)}static needsEscapePrefix(t){return !/^\\x[0-9a-fA-F]+$/i.test(t)&&t.includes("\\")}static quoteIdentifier(t){if(!t)return t;let s=true,e=t[0];e>="a"&&e<="z"||e==="_"||(s=false);for(let r=0;r<t.length;r++){let n=t[r];n>="a"&&n<="z"||n>="0"&&n<="9"||n==="_"||(s=false);}if(s){let r=Qe(t);r!=="NO_KEYWORD"&&r!=="UNRESERVED_KEYWORD"&&(s=false);}if(s)return t;let i='"';for(let r=0;r<t.length;r++){let n=t[r];n==='"'&&(i+='"'),i+=n;}return i+='"',i}static quoteIdentifierAfterDot(t){if(!t)return t;let s=true,e=t[0];e>="a"&&e<="z"||e==="_"||(s=false);for(let r=0;r<t.length;r++){let n=t[r];n>="a"&&n<="z"||n>="0"&&n<="9"||n==="_"||(s=false);}if(s)return t;let i='"';for(let r=0;r<t.length;r++){let n=t[r];n==='"'&&(i+='"'),i+=n;}return i+='"',i}static quoteDottedName(t){return !t||t.length===0?"":t.length===1?a.quoteIdentifier(t[0]):t.map((s,e)=>e===0?a.quoteIdentifier(s):a.quoteIdentifierAfterDot(s)).join(".")}static quoteQualifiedIdentifier(t,s){return t?`${a.quoteIdentifier(t)}.${a.quoteIdentifierAfterDot(s)}`:a.quoteIdentifier(s)}static quoteIdentifierTypeName(t){if(!t)return t;let s=true,e=t[0];e>="a"&&e<="z"||e==="_"||(s=false);for(let r=0;r<t.length;r++){let n=t[r];n>="a"&&n<="z"||n>="0"&&n<="9"||n==="_"||(s=false);}if(s&&Qe(t)==="RESERVED_KEYWORD"&&(s=false),s)return t;let i='"';for(let r=0;r<t.length;r++){let n=t[r];n==='"'&&(i+='"'),i+=n;}return i+='"',i}static quoteTypeDottedName(t){return !t||t.length===0?"":t.map(s=>a.quoteIdentifierTypeName(s)).join(".")}};});var Ys=P(()=>{xr();Js();});var c,qr=P(()=>{c=class{static unwrapList(t){return t==null?[]:t.List!==void 0?t.List.items||[]:Array.isArray(t)?t:[t]}static formatList(t,s=", ",e="",i){return !t||t.length===0?"":t.map(r=>`${e}${i(r)}`).join(s)}};});function pl(a){return a&&typeof a=="object"&&!Array.isArray(a)&&!("ParseResult"in a)&&!("RawStmt"in a)&&("stmts"in a||"version"in a)}var ul,ll,Ze,Vr=P(()=>{kr();Hs();Ys();qr();ul=["int2","int4","int8","float4","float8","numeric","varchar","char","bpchar","text","bool","date","time","timetz","timestamp","timestamptz","interval","bytea","uuid","json","jsonb","xml","money","bit","varbit","inet","cidr","macaddr","macaddr8"],ll=[["numeric",["decimal","dec"]],["int4",["int","integer"]],["float8",["float"]],["bpchar",["character"]],["varchar",["character varying"]]];Ze=class a{tree;options;constructor(t,s={}){this.options={functionDelimiter:"$$",functionDelimiterFallback:"$EOFCODE$",...s},pl(t)?this.tree=[{ParseResult:t}]:Array.isArray(t)?this.tree=t:this.tree=[t];}static deparse(t,s={}){return new a(t,s).deparseQuery()}deparseQuery(){let t=new St(this.options.newline,this.options.tab,this.options.pretty),s=new kt({formatter:t,prettyMode:this.options.pretty});return this.tree.map(e=>this.deparse(e,s)||"").filter(e=>e!=="").join(s.newline()+s.newline())}getFunctionDelimiter(t){let s=this.options.functionDelimiter||"$$";return t.includes(s)?this.options.functionDelimiterFallback||"$EOFCODE$":s}getObjectTypeKeyword(t){switch(t){case "OBJECT_TABLE":return "TABLE";case "OBJECT_VIEW":return "VIEW";case "OBJECT_INDEX":return "INDEX";case "OBJECT_SEQUENCE":return "SEQUENCE";case "OBJECT_FUNCTION":return "FUNCTION";case "OBJECT_PROCEDURE":return "PROCEDURE";case "OBJECT_SCHEMA":return "SCHEMA";case "OBJECT_DATABASE":return "DATABASE";case "OBJECT_DOMAIN":return "DOMAIN";case "OBJECT_AGGREGATE":return "AGGREGATE";case "OBJECT_CONVERSION":return "CONVERSION";case "OBJECT_LANGUAGE":return "LANGUAGE";case "OBJECT_OPERATOR":return "OPERATOR";case "OBJECT_OPFAMILY":return "OPERATOR FAMILY";case "OBJECT_OPCLASS":return "OPERATOR CLASS";case "OBJECT_TSDICTIONARY":return "TEXT SEARCH DICTIONARY";case "OBJECT_TSCONFIGURATION":return "TEXT SEARCH CONFIGURATION";case "OBJECT_EVENT_TRIGGER":return "EVENT TRIGGER";case "OBJECT_FDW":return "FOREIGN DATA WRAPPER";case "OBJECT_FOREIGN_SERVER":return "SERVER";case "OBJECT_TYPE":return "TYPE";case "OBJECT_COLLATION":return "COLLATION";case "OBJECT_PUBLICATION":return "PUBLICATION";case "OBJECT_ACCESS_METHOD":return "ACCESS METHOD";case "OBJECT_AMOP":return "OPERATOR CLASS";case "OBJECT_AMPROC":return "OPERATOR CLASS";case "OBJECT_ATTRIBUTE":return "ATTRIBUTE";case "OBJECT_CAST":return "CAST";case "OBJECT_COLUMN":return "COLUMN";case "OBJECT_DEFAULT":return "DEFAULT";case "OBJECT_DEFACL":return "DEFAULT PRIVILEGES";case "OBJECT_DOMCONSTRAINT":return "DOMAIN";case "OBJECT_EXTENSION":return "EXTENSION";case "OBJECT_FOREIGN_TABLE":return "FOREIGN TABLE";case "OBJECT_LARGEOBJECT":return "LARGE OBJECT";case "OBJECT_MATVIEW":return "MATERIALIZED VIEW";case "OBJECT_PARAMETER_ACL":return "PARAMETER";case "OBJECT_POLICY":return "POLICY";case "OBJECT_PUBLICATION_NAMESPACE":return "PUBLICATION";case "OBJECT_PUBLICATION_REL":return "PUBLICATION";case "OBJECT_ROLE":return "ROLE";case "OBJECT_ROUTINE":return "ROUTINE";case "OBJECT_RULE":return "RULE";case "OBJECT_STATISTIC_EXT":return "STATISTICS";case "OBJECT_SUBSCRIPTION":return "SUBSCRIPTION";case "OBJECT_TABCONSTRAINT":return "CONSTRAINT";case "OBJECT_TABLESPACE":return "TABLESPACE";case "OBJECT_TRANSFORM":return "TRANSFORM";case "OBJECT_TRIGGER":return "TRIGGER";case "OBJECT_TSPARSER":return "TEXT SEARCH PARSER";case "OBJECT_TSTEMPLATE":return "TEXT SEARCH TEMPLATE";case "OBJECT_USER_MAPPING":return "USER MAPPING";default:throw new Error(`Unsupported objectType: ${t}`)}}deparse(t,s){if(t==null)return null;if(!s){let e=new St(this.options.newline,this.options.tab,this.options.pretty);s=new kt({formatter:e,prettyMode:this.options.pretty});}if(typeof t=="number"||t instanceof Number)return t.toString();try{return this.visit(t,s)}catch(e){let i=Object.keys(t)[0];throw new Error(`Error deparsing ${i}: ${e.message}`)}}visit(t,s){if(!s){let n=new St(this.options.newline,this.options.tab,this.options.pretty);s=new kt({formatter:n,prettyMode:this.options.pretty});}let e=this.getNodeType(t);if(!e)return "";let i=this.getNodeData(t),r=e;if(typeof this[r]=="function")return this[r](i,s);throw new Error(`Deparser does not handle node type: ${e}`)}getNodeType(t){return Object.keys(t)[0]}getNodeData(t){let s=Object.keys(t);return s.length===1&&typeof t[s[0]]=="object"?t[s[0]]:t}ParseResult(t,s){return !t.stmts||t.stmts.length===0?"":t.stmts.filter(e=>e!=null).map(e=>this.RawStmt(e,s)).filter(e=>e!=="").join(s.newline()+s.newline())}RawStmt(t,s){if(!t.stmt)return "";let e=this.deparse(t.stmt,s);return t.stmt_len?e+";":e}SelectStmt(t,s){let e=[];if(t.withClause&&e.push(this.WithClause(t.withClause,s)),!t.op||t.op==="SETOP_NONE")t.valuesLists==null&&(!s.isPretty()||!t.targetList)&&e.push("SELECT");else {let r=this.SelectStmt(t.larg,s),n=this.SelectStmt(t.rarg,s),o=t.larg&&(t.larg.op&&t.larg.op!=="SETOP_NONE"||t.larg.sortClause||t.larg.limitCount||t.larg.limitOffset||t.larg.withClause),u=t.rarg&&(t.rarg.op&&t.rarg.op!=="SETOP_NONE"||t.rarg.sortClause||t.rarg.limitCount||t.rarg.limitOffset||t.rarg.withClause);switch(o?e.push(s.parens(r)):e.push(r),t.op){case "SETOP_UNION":e.push("UNION");break;case "SETOP_INTERSECT":e.push("INTERSECT");break;case "SETOP_EXCEPT":e.push("EXCEPT");break;default:throw new Error(`Bad SelectStmt op: ${t.op}`)}t.all&&e.push("ALL"),u?e.push(s.parens(n)):e.push(n);}let i="";if(t.distinctClause){let r=c.unwrapList(t.distinctClause);if(r.length>0&&Object.keys(r[0]).length>0){let n=r.map(o=>this.visit(o,s.spawn("SelectStmt",{select:true}))).join(", ");i=" DISTINCT ON "+s.parens(n);}else i=" DISTINCT";if(!s.isPretty())if(r.length>0&&Object.keys(r[0]).length>0){e.push("DISTINCT ON");let n=r.map(o=>this.visit(o,s.spawn("SelectStmt",{select:true}))).join(", ");e.push(s.parens(n));}else e.push("DISTINCT");}if(t.targetList){let r=c.unwrapList(t.targetList);if(s.isPretty())if(r.length===1){let n=r[0],o=this.visit(n,s.spawn("SelectStmt",{select:true}));this.isComplexSelectTarget(n)?(e.push("SELECT"+i),this.containsMultilineStringLiteral(o)?e.push(o):e.push(s.indent(o))):e.push("SELECT"+i+" "+o);}else {let o=r.map(u=>{let l=this.visit(u,s.spawn("SelectStmt",{select:true}));return this.containsMultilineStringLiteral(l)?l:s.indent(l)}).join(","+s.newline());e.push("SELECT"+i),e.push(o);}else {let n=r.map(o=>this.visit(o,s.spawn("SelectStmt",{select:true}))).join(", ");e.push(n);}}if(t.intoClause&&(e.push("INTO"),e.push(this.IntoClause(t.intoClause,s))),t.fromClause){let n=c.unwrapList(t.fromClause).map(o=>this.deparse(o,s.spawn("SelectStmt",{from:true}))).join(", ");e.push("FROM "+n.trim());}if(t.whereClause)if(s.isPretty()){e.push("WHERE");let o=this.visit(t.whereClause,s).split(s.newline()).map((u,l)=>l===0?s.indent(u):u);e.push(o.join(s.newline()));}else e.push("WHERE"),e.push(this.visit(t.whereClause,s));if(t.valuesLists)if(s.isPretty()){e.push("VALUES");let n=c.unwrapList(t.valuesLists).map(o=>{let u=c.unwrapList(o).map(l=>this.visit(l,s));return s.parens(u.join(", "))}).map(o=>this.containsMultilineStringLiteral(o)?o:s.indent(o));e.push(n.join(`,
15
- `));}else {e.push("VALUES");let r=c.unwrapList(t.valuesLists).map(n=>{let o=c.unwrapList(n).map(u=>this.visit(u,s));return s.parens(o.join(", "))});e.push(r.join(", "));}if(t.groupClause){let r=c.unwrapList(t.groupClause);if(s.isPretty()){let n=r.map(o=>{let u=this.visit(o,s.spawn("SelectStmt",{group:true,indentLevel:s.indentLevel+1}));return this.containsMultilineStringLiteral(u)?u:s.indent(u)}).join(","+s.newline());e.push("GROUP BY"),e.push(n);}else {e.push("GROUP BY");let n=r.map(o=>this.visit(o,s.spawn("SelectStmt",{group:true}))).join(", ");e.push(n);}}if(t.havingClause)if(s.isPretty()){e.push("HAVING");let r=this.visit(t.havingClause,s);this.containsMultilineStringLiteral(r)?e.push(r):e.push(s.indent(r));}else e.push("HAVING"),e.push(this.visit(t.havingClause,s));if(t.windowClause){e.push("WINDOW");let n=c.unwrapList(t.windowClause).map(o=>this.visit(o,s)).join(", ");e.push(n);}if(t.sortClause){let r=c.unwrapList(t.sortClause);if(s.isPretty()){let n=r.map(o=>{let u=this.visit(o,s.spawn("SelectStmt",{sort:true,indentLevel:s.indentLevel+1}));return this.containsMultilineStringLiteral(u)?u:s.indent(u)}).join(","+s.newline());e.push("ORDER BY"),e.push(n);}else {e.push("ORDER BY");let n=r.map(o=>this.visit(o,s.spawn("SelectStmt",{sort:true}))).join(", ");e.push(n);}}if(t.limitCount&&e.push("LIMIT "+this.visit(t.limitCount,s)),t.limitOffset&&e.push("OFFSET "+this.visit(t.limitOffset,s)),t.lockingClause){let n=c.unwrapList(t.lockingClause).map(o=>this.visit(o,s)).join(" ");e.push(n);}return s.isPretty()?e.filter(n=>n.trim()!=="").join(s.newline()):e.join(" ")}A_Expr(t,s){let e=t.kind,i=c.unwrapList(t.name),r=t.lexpr,n=t.rexpr;switch(e){case "AEXPR_OP":if(r&&n){let h=this.deparseOperatorName(i,s),E=this.visit(r,s),g=this.visit(n,s),R=false;if(r&&"A_Expr"in r&&r.A_Expr?.kind==="AEXPR_OP"){let d=this.deparseOperatorName(c.unwrapList(r.A_Expr.name),s);this.needsParentheses(d,h,"left")&&(R=true);}r&&this.isComplexExpression(r)&&(R=true),R&&(E=s.parens(E));let b=false;if(n&&"A_Expr"in n&&n.A_Expr?.kind==="AEXPR_OP"){let d=this.deparseOperatorName(c.unwrapList(n.A_Expr.name),s);this.needsParentheses(d,h,"right")&&(b=true);}return n&&this.isComplexExpression(n)&&(b=true),b&&(g=s.parens(g)),s.format([E,h,g])}else if(n){let h=this.deparseOperatorName(i,s),E=this.visit(n,s);return n&&"A_Expr"in n&&n.A_Expr?.kind==="AEXPR_OP"&&n.A_Expr?.lexpr&&(E=s.parens(E)),s.format([h,E])}break;case "AEXPR_OP_ANY":return s.format([this.visit(r,s),this.deparseOperatorName(i,s),"ANY",s.parens(this.visit(n,s))]);case "AEXPR_OP_ALL":return s.format([this.visit(r,s),this.deparseOperatorName(i,s),"ALL",s.parens(this.visit(n,s))]);case "AEXPR_DISTINCT":{let h=this.visit(r,s),E=this.visit(n,s);return r&&this.isComplexExpression(r)&&(h=s.parens(h)),n&&this.isComplexExpression(n)&&(E=s.parens(E)),s.format([h,"IS DISTINCT FROM",E])}case "AEXPR_NOT_DISTINCT":{let h=this.visit(r,s),E=this.visit(n,s);return r&&this.isComplexExpression(r)&&(h=s.parens(h)),n&&this.isComplexExpression(n)&&(E=s.parens(E)),s.format([h,"IS NOT DISTINCT FROM",E])}case "AEXPR_NULLIF":return s.format(["NULLIF",s.parens([this.visit(r,s),this.visit(n,s)].join(", "))]);case "AEXPR_IN":let o=this.deparseOperatorName(i,s);return o==="<>"||o==="!="?s.format([this.visit(r,s),"NOT IN",s.parens(this.visit(n,s))]):s.format([this.visit(r,s),"IN",s.parens(this.visit(n,s))]);case "AEXPR_LIKE":return this.deparseOperatorName(i,s)==="!~~"?s.format([this.visit(r,s),"NOT LIKE",this.visit(n,s)]):s.format([this.visit(r,s),"LIKE",this.visit(n,s)]);case "AEXPR_ILIKE":return this.deparseOperatorName(i,s)==="!~~*"?s.format([this.visit(r,s),"NOT ILIKE",this.visit(n,s)]):s.format([this.visit(r,s),"ILIKE",this.visit(n,s)]);case "AEXPR_SIMILAR":let p=this.deparseOperatorName(i,s),f;if(n&&"FuncCall"in n&&n.FuncCall?.funcname?.length===2&&n.FuncCall.funcname[0]?.String?.sval==="pg_catalog"&&n.FuncCall.funcname[1]?.String?.sval==="similar_to_escape"){let h=n.FuncCall.args||[];f=this.visit(h[0],s),h.length>1&&(f+=` ESCAPE ${this.visit(h[1],s)}`);}else f=this.visit(n,s);return p==="!~"?s.format([this.visit(r,s),"NOT SIMILAR TO",f]):s.format([this.visit(r,s),"SIMILAR TO",f]);case "AEXPR_BETWEEN":return s.format([this.visit(r,s),"BETWEEN",this.visitBetweenRange(n,s)]);case "AEXPR_NOT_BETWEEN":return s.format([this.visit(r,s),"NOT BETWEEN",this.visitBetweenRange(n,s)]);case "AEXPR_BETWEEN_SYM":return s.format([this.visit(r,s),"BETWEEN SYMMETRIC",this.visitBetweenRange(n,s)]);case "AEXPR_NOT_BETWEEN_SYM":return s.format([this.visit(r,s),"NOT BETWEEN SYMMETRIC",this.visitBetweenRange(n,s)])}throw new Error(`Unhandled A_Expr kind: ${e}`)}deparseOperatorName(t,s){if(!t||t.length===0)return "";let e=t.map(i=>i.String?i.String.sval||i.String.str:this.visit(i,s));return e.length>1?`OPERATOR(${e.join(".")})`:e.join(".")}getOperatorPrecedence(t){return {"||":1,OR:2,AND:3,NOT:4,IS:5,IN:5,BETWEEN:5,LIKE:5,ILIKE:5,SIMILAR:5,"<":6,"<=":6,">":6,">=":6,"=":6,"<>":6,"!=":6,"+":7,"-":7,"*":8,"/":8,"%":8,"^":9,"~":10,"&":10,"|":10,"#":10,"<<":10,">>":10}[t]||0}needsParentheses(t,s,e){let i=this.getOperatorPrecedence(t),r=this.getOperatorPrecedence(s);return i<r||i===r&&e==="right"&&(s==="-"||s==="/")}isComplexExpression(t){return !!(t.NullTest||t.BooleanTest||t.BoolExpr||t.CaseExpr||t.CoalesceExpr||t.SubLink||t.A_Expr)}isComplexSelectTarget(t){if(!t)return false;if(t.ResTarget?.val)return this.isComplexExpression(t.ResTarget.val);if(t.CaseExpr||t.SubLink||t.NullTest||t.BooleanTest||t.BoolExpr)return true;if(t.CoalesceExpr){let s=t.CoalesceExpr.args;if(s&&Array.isArray(s)&&s.length>1)return true}if(t.FuncCall){let s=t.FuncCall,e=s.args?Array.isArray(s.args)?s.args:[s.args]:[];if(s.over||s.agg_filter||s.agg_order||s.agg_distinct||e.length>1)return true;if(e.length===1)return this.isComplexSelectTarget(e[0])}if(t.A_Expr){let s=t.A_Expr;return !!(s.lexpr&&this.isComplexSelectTarget(s.lexpr)||s.rexpr&&this.isComplexSelectTarget(s.rexpr))}return t.TypeCast?this.isComplexSelectTarget(t.TypeCast.arg):t.A_ArrayExpr?true:t.A_Indirection?this.isComplexSelectTarget(t.A_Indirection.arg):(t.A_Const||t.ColumnRef||t.ParamRef||t.A_Star,false)}visitBetweenRange(t,s){return t&&"List"in t&&t.List?.items?t.List.items.map(i=>this.visit(i,s)).join(" AND "):this.visit(t,s)}InsertStmt(t,s){let e=[];if(t.withClause&&e.push(this.WithClause(t.withClause,s)),e.push("INSERT INTO"),e.push(this.RangeVar(t.relation,s)),t.cols){let i=c.unwrapList(t.cols),r=s.spawn("InsertStmt",{insertColumns:true}),n=i.map(o=>this.visit(o,r));if(s.isPretty()){let o=n.map(u=>s.indent(u));e.push(`(
16
- `+o.join(`,
17
- `)+`
18
- )`);}else e.push(s.parens(n.join(", ")));}if(t.selectStmt?e.push(this.visit(t.selectStmt,s)):(!t.cols||t.cols&&c.unwrapList(t.cols).length===0)&&e.push("DEFAULT VALUES"),t.onConflictClause){if(e.push("ON CONFLICT"),t.onConflictClause.infer){let i=t.onConflictClause.infer;if(i.conname)e.push("ON CONSTRAINT"),e.push(i.conname);else if(i.indexElems){let n=c.unwrapList(i.indexElems).map(o=>this.visit(o,s));e.push(s.parens(n.join(", ")));}i.whereClause&&(e.push("WHERE"),e.push(this.visit(i.whereClause,s)));}if(t.onConflictClause.action==="ONCONFLICT_UPDATE"){e.push("DO UPDATE SET");let i=c.unwrapList(t.onConflictClause.targetList);if(i&&i.length){let r=i[0];if(r.ResTarget?.val?.MultiAssignRef&&i.every(n=>n.ResTarget?.val?.MultiAssignRef)){let o=i.sort((u,l)=>u.ResTarget.val.MultiAssignRef.colno-l.ResTarget.val.MultiAssignRef.colno).map(u=>u.ResTarget.name);e.push(s.parens(o.join(", "))),e.push("="),e.push(this.visit(r.ResTarget.val.MultiAssignRef.source,s));}else {let n=s.spawn("UpdateStmt",{update:true}),o=i.map(u=>this.visit(u,n));if(s.isPretty()){let u=o.map(l=>s.indent(l));e.push(`
19
- `+u.join(`,
20
- `));}else e.push(o.join(", "));}}t.onConflictClause.whereClause&&(e.push("WHERE"),e.push(this.visit(t.onConflictClause.whereClause,s)));}else t.onConflictClause.action==="ONCONFLICT_NOTHING"&&e.push("DO NOTHING");}if(t.returningList){e.push("RETURNING");let r=c.unwrapList(t.returningList).map(n=>this.visit(n,s));e.push(r.join(", "));}return e.join(" ")}UpdateStmt(t,s){let e=[];t.withClause&&e.push(this.WithClause(t.withClause,s)),e.push("UPDATE"),t.relation&&e.push(this.RangeVar(t.relation,s)),e.push("SET");let i=c.unwrapList(t.targetList);if(i&&i.length){i[0];let n=new Set,o=[];for(let u=0;u<i.length;u++){if(n.has(u))continue;let l=i[u],p=l.ResTarget?.val?.MultiAssignRef;if(p){let f=[];for(let g=u;g<i.length;g++){let R=i[g],b=R.ResTarget?.val?.MultiAssignRef;b&&JSON.stringify(b.source)===JSON.stringify(p.source)&&(f.push(R),n.add(g));}let h=f.map(g=>g.ResTarget.name),E=`${s.parens(h.join(", "))} = ${this.visit(p.source,s)}`;o.push(E);}else o.push(this.visit(l,s.spawn("UpdateStmt",{update:true}))),n.add(u);}e.push(o.join(","));}if(t.fromClause){e.push("FROM");let n=c.unwrapList(t.fromClause).map(o=>this.visit(o,s));e.push(n.join(", "));}return t.whereClause&&(e.push("WHERE"),e.push(this.visit(t.whereClause,s))),t.returningList&&(e.push("RETURNING"),e.push(this.deparseReturningList(t.returningList,s))),e.join(" ")}DeleteStmt(t,s){try{let e=[];if(t.withClause)try{e.push(this.WithClause(t.withClause,s));}catch(i){throw console.warn(`Error processing withClause in DeleteStmt: ${i instanceof Error?i.message:String(i)}`),new Error(`Error deparsing DeleteStmt: ${i instanceof Error?i.message:String(i)}`)}if(e.push("DELETE"),e.push("FROM"),!t.relation)throw new Error("DeleteStmt requires a relation");if(e.push(this.RangeVar(t.relation,s)),t.usingClause){e.push("USING");let r=c.unwrapList(t.usingClause).filter(n=>n!=null&&this.getNodeType(n)!=="undefined").map(n=>{try{return this.visit(n,s)}catch(o){return console.warn(`Error processing usingClause item in DeleteStmt: ${o instanceof Error?o.message:String(o)}`),""}}).filter(n=>n&&n.trim());r.length>0&&e.push(r.join(", "));}if(t.whereClause){e.push("WHERE");try{e.push(this.visit(t.whereClause,s));}catch(i){throw console.warn(`Error processing whereClause in DeleteStmt: ${i instanceof Error?i.message:String(i)}`),new Error(`Error deparsing DeleteStmt: ${i instanceof Error?i.message:String(i)}`)}}if(t.returningList){e.push("RETURNING");try{e.push(this.deparseReturningList(t.returningList,s));}catch(i){throw console.warn(`Error processing returningList in DeleteStmt: ${i instanceof Error?i.message:String(i)}`),new Error(`Error deparsing DeleteStmt: ${i instanceof Error?i.message:String(i)}`)}}return e.join(" ")}catch(e){throw new Error(`Error deparsing DeleteStmt: ${e instanceof Error?e.message:String(e)}`)}}WithClause(t,s){let e=["WITH"];if(t.recursive&&e.push("RECURSIVE"),t.ctes&&t.ctes.length>0){let i=c.unwrapList(t.ctes);if(s.isPretty()){let r=i.map((n,o)=>{let u=this.visit(n,s),l=o===0?s.newline():","+s.newline();return this.containsMultilineStringLiteral(u)?l+u:l+s.indent(u)});e.push(r.join(""));}else {let r=i.map(n=>this.visit(n,s));e.push(r.join(", "));}}return e.join(" ")}ResTarget(t,s){let e=[];if(s.update&&t.name){if(e.push(m.quoteIdentifier(t.name)),t.indirection&&t.indirection.length>0){let i=c.unwrapList(t.indirection).map(r=>r.String?`.${m.quoteIdentifierAfterDot(r.String.sval||r.String.str)}`:this.visit(r,s));e.push(i.join(""));}e.push("="),t.val&&e.push(this.deparse(t.val,s));}else if(s.insertColumns&&t.name){if(e.push(m.quoteIdentifier(t.name)),t.indirection&&t.indirection.length>0){let i=c.unwrapList(t.indirection).map(r=>r.String?`.${m.quoteIdentifierAfterDot(r.String.sval||r.String.str)}`:this.visit(r,s));e.push(i.join(""));}}else t.val&&e.push(this.deparse(t.val,s)),t.name&&(e.push("AS"),e.push(m.quoteIdentifier(t.name)));return e.join(" ")}deparseReturningList(t,s){return c.unwrapList(t).filter(e=>e!=null&&this.getNodeType(e)!=="undefined").map(e=>{try{if(this.getNodeType(e)==="ResTarget"){let i=this.getNodeData(e),r=i.val?this.visit(i.val,s):"",n=i.name?` AS ${m.quoteIdentifier(i.name)}`:"";return r+n}else return this.visit(e,s)}catch(i){return console.warn(`Error processing returning item: ${i instanceof Error?i.message:String(i)}`),""}}).filter(e=>e&&e.trim()).join(", ")}BoolExpr(t,s){let e=t.boolop,i=c.unwrapList(t.args),r="%s";s.bool&&(r="(%s)");let n=s.spawn("BoolExpr",{bool:true});switch(e){case "AND_EXPR":if(s.isPretty()&&i.length>1){let o=i.map(u=>this.visit(u,n)).join(s.newline()+s.indent("AND "));return r.replace("%s",()=>o)}else {let o=i.map(u=>this.visit(u,n)).join(" AND ");return r.replace("%s",()=>o)}case "OR_EXPR":if(s.isPretty()&&i.length>1){let o=i.map(u=>this.visit(u,n)).join(s.newline()+s.indent("OR "));return r.replace("%s",()=>o)}else {let o=i.map(u=>this.visit(u,n)).join(" OR ");return r.replace("%s",()=>o)}case "NOT_EXPR":return `NOT (${this.visit(i[0],s)})`;default:throw new Error(`Unhandled BoolExpr boolop: ${e}`)}}FuncCall(t,s){let e=c.unwrapList(t.funcname),i=c.unwrapList(t.args),r=e.map(p=>p.String?.sval||p.String?.str||"").filter(p=>p),n=m.quoteDottedName(r);if(t.funcformat==="COERCE_SQL_SYNTAX"&&n==="pg_catalog.xmlexists"&&i.length>=2){let p=this.visit(i[0],s),f=this.visit(i[1],s);return `xmlexists (${p} PASSING ${f})`}if(t.funcformat==="COERCE_SQL_SYNTAX"&&n==="pg_catalog.extract"&&i.length>=2){let p=this.visit(i[0],s),f=this.visit(i[1],s);return p.startsWith("'")&&p.endsWith("'")&&(p=p.slice(1,-1).toUpperCase()),`EXTRACT(${p} FROM ${f})`}if(t.funcformat==="COERCE_SQL_SYNTAX"&&(n==="pg_catalog.rtrim"||n==="pg_catalog.ltrim"||n==="pg_catalog.btrim")&&i.length>=1){let p=this.visit(i[0],s),f="";if(i.length>=2&&(f=` ${this.visit(i[1],s)}`),n==="pg_catalog.rtrim")return `TRIM(TRAILING${f} FROM ${p})`;if(n==="pg_catalog.ltrim")return `TRIM(LEADING${f} FROM ${p})`;if(n==="pg_catalog.btrim")return `TRIM(BOTH${f} FROM ${p})`}if(t.funcformat==="COERCE_SQL_SYNTAX"&&n==="pg_catalog.pg_collation_for")return `COLLATION FOR (${i.map(f=>this.visit(f,s)).join(", ")})`;if(t.funcformat==="COERCE_SQL_SYNTAX"&&n==="pg_catalog.substring"){let p=this.visit(i[0],s);if(i.length===3){let f=this.visit(i[1],s),h=this.visit(i[2],s);return `SUBSTRING(${p} FROM ${f} FOR ${h})`}else if(i.length===2){let f=this.visit(i[1],s);return `SUBSTRING(${p} FROM ${f})`}}if(t.funcformat==="COERCE_SQL_SYNTAX"&&n==="pg_catalog.position"&&i.length===2){let p=this.visit(i[0],s);return `POSITION(${this.visit(i[1],s)} IN ${p})`}if(t.funcformat==="COERCE_SQL_SYNTAX"&&n==="pg_catalog.overlay"){if(i.length===4){let p=this.visit(i[0],s),f=this.visit(i[1],s),h=this.visit(i[2],s),E=this.visit(i[3],s);return `OVERLAY(${p} PLACING ${f} FROM ${h} FOR ${E})`}else if(i.length===3){let p=this.visit(i[0],s),f=this.visit(i[1],s),h=this.visit(i[2],s);return `OVERLAY(${p} PLACING ${f} FROM ${h})`}}if(t.funcformat==="COERCE_SQL_SYNTAX"&&n==="pg_catalog.is_normalized"){let p=this.visit(i[0],s);if(i.length===2){let h=this.visit(i[1],s).replace(/'/g,"");return `${p} IS ${h} NORMALIZED`}else return `${p} IS NORMALIZED`}if(t.funcformat==="COERCE_SQL_SYNTAX"&&n==="pg_catalog.normalize"){let p=this.visit(i[0],s);if(i.length===2){let h=this.visit(i[1],s).replace(/'/g,"");return `normalize(${p}, ${h})`}else return `normalize(${p})`}if(t.funcformat==="COERCE_SQL_SYNTAX"&&n==="pg_catalog.system_user"&&i.length===0)return "SYSTEM_USER";if(n==="pg_catalog.overlaps"&&i.length===4){let p=this.visit(i[0],s),f=this.visit(i[1],s),h=this.visit(i[2],s),E=this.visit(i[3],s);return `(${p}, ${f}) OVERLAPS (${h}, ${E})`}if(n==="pg_catalog.timezone"&&i.length===2){let p=this.visit(i[1],s),f=this.visit(i[0],s);if(i[1]&&"A_Expr"in i[1]&&i[1].A_Expr?.kind==="AEXPR_OP"){let h=this.deparseOperatorName(c.unwrapList(i[1].A_Expr.name),s);(h==="+"||h==="-"||h==="*"||h==="/")&&(p=s.parens(p));}return `${p} AT TIME ZONE ${f}`}let o=[];if(t.agg_star)t.agg_distinct?o.push("DISTINCT *"):o.push("*");else {let p=i.map(f=>this.visit(f,s));if(t.func_variadic&&p.length>0){let f=p.length-1;p[f]=`VARIADIC ${p[f]}`;}t.agg_distinct&&p.length>0?o.push("DISTINCT "+p.join(", ")):o.push(...p);}let u="";if(t.agg_order&&t.agg_order.length>0){let f=c.unwrapList(t.agg_order).map(h=>this.visit(h,s));t.agg_within_group?u=` WITHIN GROUP (ORDER BY ${f.join(", ")})`:u=` ORDER BY ${f.join(", ")}`;}let l;if(t.agg_within_group&&u?l=`${n}(${o.join(", ")})${u}`:l=`${n}(${o.join(", ")}${u})`,t.agg_filter&&(l+=` FILTER (WHERE ${this.visit(t.agg_filter,s)})`),t.over)if(t.over.name)l+=` OVER ${t.over.name}`;else {let p=[];if(t.over.partitionClause){let E=c.unwrapList(t.over.partitionClause).map(g=>this.visit(g,s));p.push(`PARTITION BY ${E.join(", ")}`);}if(t.over.orderClause){let E=c.unwrapList(t.over.orderClause).map(g=>this.visit(g,s));p.push(`ORDER BY ${E.join(", ")}`);}let f=this.formatWindowFrame(t.over,s.spawn("FuncCall"));if(f&&p.push(f),p.length>0)if(s.isPretty()&&p.length>1){let h=p.map(E=>s.indent(E));l+=` OVER (${s.newline()}${h.join(s.newline())}${s.newline()})`;}else l+=` OVER (${p.join(" ")})`;else l+=" OVER ()";}return l}FuncExpr(t,s){let e=`func_${t.funcid}`,i=t.args?c.unwrapList(t.args).map(r=>this.visit(r,s)).join(", "):"";return `${e}(${i})`}A_Const(t,s){let e=t;if(e.ival!==void 0)return typeof e.ival=="object"&&e.ival!==null?e.ival.ival!==void 0?e.ival.ival.toString():Object.keys(e.ival).length===0?"0":e.ival.toString():e.ival===null?"NULL":e.ival.toString();if(e.fval!==void 0)return typeof e.fval=="object"&&e.fval!==null?e.fval.fval!==void 0?e.fval.fval.toString():Object.keys(e.fval).length===0?"0.0":e.fval.toString():e.fval===null?"NULL":e.fval.toString();if(e.sval!==void 0)return typeof e.sval=="object"&&e.sval!==null?e.sval.sval!==void 0?m.formatEString(e.sval.sval):e.sval.String&&e.sval.String.sval!==void 0?m.formatEString(e.sval.String.sval):Object.keys(e.sval).length===0?"''":m.formatEString(e.sval.toString()):e.sval===null?"NULL":m.formatEString(e.sval);if(e.boolval!==void 0)return typeof e.boolval=="object"&&e.boolval!==null?e.boolval.boolval!==void 0?e.boolval.boolval?"true":"false":Object.keys(e.boolval).length===0?"false":e.boolval?"true":"false":e.boolval===null?"NULL":e.boolval?"true":"false";if(e.bsval!==void 0)if(typeof e.bsval=="object"&&e.bsval!==null)if(e.bsval.bsval!==void 0){let i=e.bsval.bsval;return i.startsWith("x")&&/^x[0-9A-Fa-f]+$/.test(i)?`x'${i.substring(1)}'`:i.startsWith("b")?`b'${i.substring(1)}'`:`b'${i}'`}else return Object.keys(e.bsval).length===0?"''":e.bsval.toString();else {if(e.bsval===null)return "NULL";{let i=e.bsval;return i.startsWith("x")&&/^x[0-9A-Fa-f]+$/.test(i)?`x'${i.substring(1)}'`:i.startsWith("b")?`b'${i.substring(1)}'`:`b'${i}'`}}if(e.val){if(e.val.Integer?.ival!==void 0)return e.val.Integer.ival.toString();if(e.val.Float?.fval!==void 0)return e.val.Float.fval.toString();if(e.val.String?.sval!==void 0)return m.escape(e.val.String.sval);if(e.val.Boolean?.boolval!==void 0)return e.val.Boolean.boolval?"true":"false";if(e.val.BitString?.bsval!==void 0)return e.val.BitString.bsval}return e.isnull===true?"NULL":typeof e=="object"&&e!==null?e.Boolean!==void 0?e.Boolean?"true":"false":e.Integer!==void 0?typeof e.Integer=="object"&&e.Integer.ival!==void 0?e.Integer.ival.toString():e.Integer.toString():e.Float!==void 0?typeof e.Float=="object"&&e.Float.fval!==void 0?e.Float.fval.toString():e.Float.toString():e.String!==void 0?typeof e.String=="object"&&e.String.sval!==void 0?m.escape(e.String.sval):m.escape(e.String):(Object.keys(e).length===0||console.warn("A_Const: Unhandled object structure:",JSON.stringify(e,null,2)),"NULL"):"NULL"}ColumnRef(t,s){return c.unwrapList(t.fields).map(i=>i.String?m.quoteIdentifier(i.String.sval||i.String.str):i.A_Star?"*":this.visit(i,s)).join(".")}TypeName(t,s){if(!t.names)return "";let e=[];t.setof&&e.push("SETOF");let i=t.names.map(l=>l.String?l.String.sval||l.String.str:"").filter(Boolean);if(i.length===0)return "";let r=null;t.typmods?i.some(p=>(typeof p=="string"?p:p.String?.sval||p.String?.str)==="interval")?r=this.formatIntervalTypeMods(t.typmods,s):r=this.formatTypeMods(t.typmods,s):t.typemod&&t.typemod!==-1&&(r=this.formatSingleTypeMod(t.typemod,i[0]));let n=(l,p)=>p!=null?l==="interval"?p.startsWith("(")?`${l}${p}`:`${l} ${p}`:`${l}(${p})`:l,o=l=>l.map(p=>p.Integer&&p.Integer.ival!==void 0&&p.Integer.ival!==-1?`[${p.Integer.ival}]`:"[]").join("");if(i.length===1){let l=i[0];if(l==="char")return s.parentNodeTypes.includes("TypeCast")&&r==="1"?e.push('"char"'):e.push(n('"char"',r)),e.join(" ");let p=n(m.quoteIdentifierTypeName(l),r);return t.arrayBounds&&t.arrayBounds.length>0&&(p+=o(t.arrayBounds)),e.push(p),e.join(" ")}if(i.length===2){let[l,p]=i;if(l==="pg_catalog"&&p==="char")return e.push(n("pg_catalog.char",r)),e.join(" ");if(l==="pg_catalog"){let f=`${l}.${p}`;p==="bpchar"&&r?f="char":p==="varchar"?f="varchar":p==="numeric"?f="numeric":p==="int4"?f="int":p==="float8"?f="double precision":p==="float4"?f="real":p==="int8"?f="bigint":p==="int2"?f="smallint":p==="bool"?f="boolean":p==="interval"?(s.parentNodeTypes.includes("TypeCast"),f="interval"):p==="timestamptz"?r?(f=`timestamp(${r}) with time zone`,r=null):f="timestamp with time zone":p==="timetz"?r?(f=`time(${r}) with time zone`,r=null):f="time with time zone":p==="timestamp"?r?(f=`timestamp(${r})`,r=null):f="timestamp":p==="time"&&(r?(f=`time(${r})`,r=null):f="time");let h=n(f,r);return t.arrayBounds&&t.arrayBounds.length>0&&(h+=o(t.arrayBounds)),e.push(h),e.join(" ")}}let u=n(m.quoteTypeDottedName(i),r);return t.arrayBounds&&t.arrayBounds.length>0&&(u+=o(t.arrayBounds)),e.push(u),e.join(" ")}Alias(t,s){let e=t.aliasname,i=[];if(t.colnames){let n=c.unwrapList(t.colnames).map(o=>{let u=this.deparse(o,s);return u.startsWith('"')&&u.endsWith('"')?u:this.quoteIfNeeded(u)});i.push("AS",this.quoteIfNeeded(e)+s.parens(n.join(", ")));}else i.push("AS",this.quoteIfNeeded(e));return i.join(" ")}RangeVar(t,s){let e=[];t&&(!("inh"in t)||t.inh===void 0)&&!s.parentNodeTypes.includes("CompositeTypeStmt")&&!s.parentNodeTypes.includes("AlterTypeStmt")&&s.objtype!=="OBJECT_TYPE"&&!s.parentNodeTypes.includes("CreateForeignTableStmt")&&e.push("ONLY");let i="";if(t.catalogname?(i=m.quoteIdentifier(t.catalogname),t.schemaname&&(i+="."+m.quoteIdentifierAfterDot(t.schemaname)),i+="."+m.quoteIdentifierAfterDot(t.relname)):t.schemaname?i=m.quoteQualifiedIdentifier(t.schemaname,t.relname):i=m.quoteIdentifier(t.relname),e.push(i),t.alias){let n=this.Alias(t.alias,s);e.push(n);}return e.join(" ")}formatIntervalTypeMods(t,s){if(!t||t.length===0)return null;let e=c.unwrapList(t),i={4:"year",2:"month",8:"day",1024:"hour",2048:"minute",4096:"second",6:"year to month",1032:"day to hour",3080:"day to minute",7176:"day to second",3072:"hour to minute",7168:"hour to second",6144:"minute to second"};if(e.length===1){let n=e[0];if(n&&typeof n=="object"){let o=n.A_Const;if(o&&o.ival!==void 0){let u=typeof o.ival=="object"?o.ival.ival:o.ival;if(u!==void 0)return i[u]?i[u]:`(${u})`}}}if(e.length===2){let n=e[0],o=e[1];if(n&&typeof n=="object"){let u=n.A_Const;if(u&&u.ival!==void 0){let l=typeof u.ival=="object"?u.ival.ival:u.ival;if(o&&typeof o=="object"){let p=o.A_Const;if(p&&p.ival!==void 0){let f=typeof p.ival=="object"?p.ival.ival!==void 0?p.ival.ival:0:p.ival;if(l===32767&&f>=0)return `(${f})`;if(i[l]&&f>=0)return `${i[l]}(${f})`}}}}}let r=e.map(n=>{if(n&&typeof n=="object"){let u=n.A_Const;if(u&&u.ival!==void 0){let l=typeof u.ival=="object"?u.ival.ival:u.ival;if(l!==void 0)return i[l]||l.toString()}}return this.visit(n,s)||""}).filter(Boolean);return r.length>0?r.join(" "):null}formatTypeMods(t,s){if(!t||t.length===0)return null;let i=c.unwrapList(t).filter(r=>{if(r&&typeof r=="object"){let n=r.A_Const;if(n&&n.ival&&(typeof n.ival=="object"?n.ival.ival:n.ival)===32767)return false}return true});return i.length===0?null:i.map(r=>this.deparse(r,s)).join(", ")}formatSingleTypeMod(t,s){switch(s){case "varchar":case "bpchar":case "char":if(t>4)return (t-64).toString();break;case "numeric":case "decimal":if(t>4){let e=t-4,i=e>>16&65535,r=e&65535;return r>0?`${i},${r}`:i.toString()}break;case "time":case "timetz":case "timestamp":case "timestamptz":case "interval":if(t>=0)return t.toString();break}return null}getPgCatalogTypeName(t,s){switch(t){case "bpchar":return s!=null?"char":"bpchar";case "varchar":return "varchar";case "numeric":return "numeric";case "bool":return "boolean";case "int2":return "smallint";case "int4":return "int";case "int8":return "bigint";case "real":return "float4";case "time":return "time";case "timestamp":return "timestamp";case "interval":return "interval";case "bit":return "bit";default:return t}}isPgCatalogType(t){let s=t.replace(/^pg_catalog\./,"");if(ul.includes(s))return true;for(let[e,i]of ll)if(i.includes(s))return true;return false}A_ArrayExpr(t,s){return `ARRAY[${c.unwrapList(t.elements).map(r=>this.visit(r,s)).join(", ")}]`}A_Indices(t,s){let e=[];return t.is_slice?(t.lidx&&e.push(this.visit(t.lidx,s)),e.push(":"),t.uidx&&e.push(this.visit(t.uidx,s))):t.uidx&&e.push(this.visit(t.uidx,s)),`[${e.join("")}]`}A_Indirection(t,s){let e=this.visit(t.arg,s),i=this.getNodeType(t.arg);(i==="TypeCast"||i==="SubLink"||i==="A_Expr"||i==="FuncCall"||i==="A_Indirection"||i==="ColumnRef"||i==="RowExpr")&&(e=`(${e})`);let r=[e],n=c.unwrapList(t.indirection);for(let o of n)if(o.String||o.A_Star){let u=o.A_Star?"*":m.quoteIdentifier(o.String.sval||o.String.str);r.push(`.${u}`);}else r.push(this.visit(o,s));return r.join("")}A_Star(t,s){return "*"}CaseExpr(t,s){let e=["CASE"];t.arg&&e.push(this.visit(t.arg,s));let i=c.unwrapList(t.args);if(s.isPretty()&&i.length>0){for(let r of i){let n=this.visit(r,s);this.containsMultilineStringLiteral(n)?e.push(s.newline()+n):e.push(s.newline()+s.indent(n));}if(t.defresult){let r=this.visit(t.defresult,s);this.containsMultilineStringLiteral(r)?e.push(s.newline()+"ELSE "+r):e.push(s.newline()+s.indent("ELSE "+r));}return e.push(s.newline()+"END"),e.join(" ")}else {for(let r of i)e.push(this.visit(r,s));return t.defresult&&(e.push("ELSE"),e.push(this.visit(t.defresult,s))),e.push("END"),e.join(" ")}}CoalesceExpr(t,s){return `COALESCE(${c.unwrapList(t.args).map(r=>this.visit(r,s)).join(", ")})`}TypeCast(t,s){let e=this.visit(t.arg,s),i=this.TypeName(t.typeName,s);if(i==="bpchar"||i==="pg_catalog.bpchar"){let r=t.typeName?.names;if(r&&r.length===2&&r[0]?.String?.sval==="pg_catalog"&&r[1]?.String?.sval==="bpchar")return `CAST(${e} AS ${i})`}if(this.isPgCatalogType(i)){let r=this.getNodeType(t.arg),n=r==="A_Const"||r==="ColumnRef",o=r==="FuncCall";if((n||o)&&!(n&&(e.includes("(")||e.startsWith("-")))){let l=i.replace("pg_catalog.","");return o?`${s.parens(e)}::${l}`:`${e}::${l}`}}return `CAST(${e} AS ${i})`}CollateClause(t,s){let e=[];if(t.arg){let i=this.visit(t.arg,s),r=this.getNodeType(t.arg);(r==="A_Expr"||r==="FuncCall"||r==="SubLink")&&(i=`(${i})`),e.push(i);}if(e.push("COLLATE"),t.collname){let i=c.unwrapList(t.collname);e.push(i.map(r=>this.visit(r,s)).join("."));}return e.join(" ")}BooleanTest(t,s){let e=[],i=s.spawn("BooleanTest",{bool:true});switch(e.push(this.visit(t.arg,i)),t.booltesttype){case "IS_TRUE":e.push("IS TRUE");break;case "IS_NOT_TRUE":e.push("IS NOT TRUE");break;case "IS_FALSE":e.push("IS FALSE");break;case "IS_NOT_FALSE":e.push("IS NOT FALSE");break;case "IS_UNKNOWN":e.push("IS UNKNOWN");break;case "IS_NOT_UNKNOWN":e.push("IS NOT UNKNOWN");break}return e.join(" ")}NullTest(t,s){let e=[];switch(e.push(this.visit(t.arg,s)),t.nulltesttype){case "IS_NULL":e.push("IS NULL");break;case "IS_NOT_NULL":e.push("IS NOT NULL");break}return e.join(" ")}quoteIfNeeded(t){return m.quoteIdentifier(t)}preserveOperatorDefElemCase(t){return {leftarg:"Leftarg",rightarg:"Rightarg",procedure:"Procedure",function:"Function",commutator:"Commutator",negator:"Negator",restrict:"Restrict",join:"Join",hashes:"Hashes",merges:"Merges"}[t.toLowerCase()]||t}String(t,s){if(s.isStringLiteral||s.isEnumValue)return m.formatEString(t.sval||"");let e=t.sval||"";return s.parentNodeTypes.includes("DefElem")||s.parentNodeTypes.includes("CreateOpClassItem")||s.parentNodeTypes.includes("ObjectWithArgs")&&/^[+\-*/<>=~!@#%^&|`?]+$/.test(e)?e:m.quoteIdentifier(e)}Integer(t,s){return t.ival?.toString()||"0"}Float(t,s){return t.fval||"0.0"}Boolean(t,s){return t.boolval?"true":"false"}BitString(t,s){return t.bsval.startsWith("x")?`x'${t.bsval.substring(1)}'`:t.bsval.startsWith("b")?`b'${t.bsval.substring(1)}'`:`b'${t.bsval}'`}Null(t,s){return "NULL"}List(t,s){return !t.items||t.items.length===0?"":t.items.map(e=>this.visit(e,s)).join(", ")}CreateStmt(t,s){let e=["CREATE"];if(t.relation&&t.relation.relpersistence==="t"?e.push("TEMPORARY"):t.relation&&t.relation.relpersistence==="u"&&e.push("UNLOGGED"),t.if_not_exists?e.push("TABLE IF NOT EXISTS"):e.push("TABLE"),e.push(this.RangeVar(t.relation,s)),t.ofTypename){if(e.push("OF"),e.push(this.TypeName(t.ofTypename,s)),t.tableElts){let r=c.unwrapList(t.tableElts).map(n=>this.deparse(n,s));e.push(s.parens(r.join(", ")));}}else if(t.tableElts){let r=c.unwrapList(t.tableElts).map(n=>this.deparse(n,s.spawn("CreateStmt")));if(s.isPretty()){let n=r.map(o=>{let u=o.trim();return u.startsWith(`
21
- `)?s.indent(u.substring(1)):s.indent(u)}).join(","+s.newline());e.push("("+s.newline()+n+s.newline()+")");}else e.push(s.parens(r.join(", ")));}else t.partbound||e.push(s.parens(""));if(t.partbound&&t.inhRelations&&t.inhRelations.length>0){e.push("PARTITION OF");let r=c.unwrapList(t.inhRelations).map(n=>this.visit(n,s));if(e.push(r[0]),t.partbound.strategy==="l"&&t.partbound.listdatums){e.push("FOR VALUES IN");let n=c.unwrapList(t.partbound.listdatums).map(o=>this.visit(o,s)).join(", ");e.push(`(${n})`);}else if(t.partbound.strategy==="r"&&(t.partbound.lowerdatums||t.partbound.upperdatums)){if(e.push("FOR VALUES FROM"),t.partbound.lowerdatums){let n=c.unwrapList(t.partbound.lowerdatums).map(o=>this.visit(o,s)).join(", ");e.push(`(${n})`);}if(t.partbound.upperdatums){e.push("TO");let n=c.unwrapList(t.partbound.upperdatums).map(o=>this.visit(o,s)).join(", ");e.push(`(${n})`);}}else if(t.partbound.strategy==="h"&&t.partbound.modulus!==void 0){e.push("FOR VALUES WITH");let n=t.partbound.remainder!==void 0?t.partbound.remainder:0;e.push(`(MODULUS ${t.partbound.modulus}, REMAINDER ${n})`);}else t.partbound.is_default&&e.push("DEFAULT");}else if(t.inhRelations){e.push("INHERITS");let r=c.unwrapList(t.inhRelations).map(n=>this.visit(n,s));e.push(s.parens(r.join(", ")));}if(t.partspec){switch(e.push("PARTITION BY"),t.partspec.strategy){case "PARTITION_STRATEGY_HASH":e.push("HASH");break;case "PARTITION_STRATEGY_LIST":e.push("LIST");break;case "PARTITION_STRATEGY_RANGE":e.push("RANGE");break}if(t.partspec.partParams&&t.partspec.partParams.length>0){let i=c.unwrapList(t.partspec.partParams).map(r=>this.visit(r,s)).join(", ");e.push(`(${i})`);}}if(t.oncommit&&t.oncommit!=="ONCOMMIT_NOOP")switch(e.push("ON COMMIT"),t.oncommit){case "ONCOMMIT_PRESERVE_ROWS":e.push("PRESERVE ROWS");break;case "ONCOMMIT_DELETE_ROWS":e.push("DELETE ROWS");break;case "ONCOMMIT_DROP":e.push("DROP");break}if(t.options&&t.options.length>0){let i=s.spawn("CreateStmt"),r=t.options.map(n=>this.deparse(n,i));e.push("WITH",`(${r.join(", ")})`);}return t.accessMethod&&(e.push("USING"),e.push(this.quoteIfNeeded(t.accessMethod))),e.join(" ")}ColumnDef(t,s){let e=[];if(t.colname&&e.push(m.quoteIdentifier(t.colname)),t.typeName&&e.push(this.TypeName(t.typeName,s)),t.fdwoptions&&t.fdwoptions.length>0){e.push("OPTIONS");let i=s.spawn("ColumnDef"),r=c.unwrapList(t.fdwoptions).map(n=>this.visit(n,i));e.push(`(${r.join(", ")})`);}if(t.collClause&&e.push(this.CollateClause(t.collClause,s)),t.constraints){let r=c.unwrapList(t.constraints).map(n=>{let o=s.spawn("ColumnDef",{isColumnConstraint:true});return this.visit(n,o)});e.push(...r);}return t.raw_default&&(e.push("DEFAULT"),e.push(this.visit(t.raw_default,s))),t.generated&&(e.push("GENERATED ALWAYS AS"),e.push(`(${t.generated})`),e.push("STORED")),t.is_not_null&&e.push("NOT NULL"),e.join(" ")}Constraint(t,s){let e=[];switch(t.conname&&(t.contype==="CONSTR_CHECK"||t.contype==="CONSTR_UNIQUE"||t.contype==="CONSTR_PRIMARY"||t.contype==="CONSTR_FOREIGN")&&(e.push("CONSTRAINT"),e.push(m.quoteIdentifier(t.conname))),t.contype){case "CONSTR_NULL":e.push("NULL");break;case "CONSTR_NOTNULL":e.push("NOT NULL");break;case "CONSTR_DEFAULT":e.push("DEFAULT"),t.raw_expr&&e.push(this.visit(t.raw_expr,s));break;case "CONSTR_CHECK":if(s.isPretty()&&!s.isColumnConstraint?e.push(`
22
- `+s.indent("CHECK")):e.push("CHECK"),t.raw_expr)if(s.isPretty()){let i=this.visit(t.raw_expr,s);i.includes(`
23
- `)?e.push(`(
24
- `+s.indent(i)+`
25
- )`):e.push(`(${i})`);}else e.push(s.parens(this.visit(t.raw_expr,s)));t.skip_validation&&e.push("NOT VALID"),t.is_no_inherit&&!s.isDomainConstraint&&e.push("NO INHERIT");break;case "CONSTR_GENERATED":e.push("GENERATED"),t.generated_when==="a"?e.push("ALWAYS"):t.generated_when==="s"&&e.push("BY DEFAULT"),e.push("AS"),t.raw_expr&&e.push(s.parens(this.visit(t.raw_expr,s))),e.push("STORED");break;case "CONSTR_IDENTITY":if(e.push("GENERATED"),t.generated_when==="a"?e.push("ALWAYS"):(t.generated_when==="d"||t.generated_when==="s")&&e.push("BY DEFAULT"),e.push("AS IDENTITY"),t.options&&t.options.length>0){let i=c.unwrapList(t.options).map(r=>{if(r.DefElem){let n=r.DefElem;if(n.defname==="sequence_name")return n.arg&&n.arg.List?`SEQUENCE NAME ${c.unwrapList(n.arg).map(l=>this.visit(l,s)).join(".")}`:"SEQUENCE NAME";if(n.defname==="start")return `START WITH ${n.arg?this.visit(n.arg,s):""}`;if(n.defname==="increment")return `INCREMENT BY ${n.arg?this.visit(n.arg,s):""}`;if(n.defname==="minvalue")return n.arg?`MINVALUE ${this.visit(n.arg,s)}`:"NO MINVALUE";if(n.defname==="maxvalue")return n.arg?`MAXVALUE ${this.visit(n.arg,s)}`:"NO MAXVALUE";if(n.defname==="cache")return `CACHE ${n.arg?this.visit(n.arg,s):""}`;if(n.defname==="cycle")return (n.arg?this.visit(n.arg,s):"")==="true"?"CYCLE":"NO CYCLE";let o=n.arg?this.visit(n.arg,s):"";return `${n.defname.toUpperCase()} ${o}`}return this.visit(r,s)});if(s.isPretty()){let r=i.map(n=>s.indent(n));e.push(`(
26
- `+r.join(`
27
- `)+`
28
- )`);}else e.push(`(${i.join(" ")})`);}break;case "CONSTR_PRIMARY":if(e.push("PRIMARY KEY"),t.keys&&t.keys.length>0){let i=c.unwrapList(t.keys).map(r=>this.visit(r,s)).join(", ");e.push(`(${i})`);}t.indexname&&(e.push("USING INDEX"),e.push(t.indexname));break;case "CONSTR_UNIQUE":if(s.isPretty()&&!s.isColumnConstraint?e.push(`
29
- `+s.indent("UNIQUE")):e.push("UNIQUE"),t.nulls_not_distinct&&e.push("NULLS NOT DISTINCT"),t.keys&&t.keys.length>0){let i=c.unwrapList(t.keys).map(r=>this.visit(r,s)).join(", ");e.push(`(${i})`);}t.indexname&&(e.push("USING INDEX"),e.push(t.indexname));break;case "CONSTR_FOREIGN":if(s.isColumnConstraint)e.push("REFERENCES");else if(s.isPretty()){if(e.push(`
30
- `+s.indent("FOREIGN KEY")),t.fk_attrs&&t.fk_attrs.length>0){let i=c.unwrapList(t.fk_attrs).map(r=>this.visit(r,s)).join(", ");e.push(`(${i})`);}e.push(`
31
- `+s.indent("REFERENCES"));}else {if(e.push("FOREIGN KEY"),t.fk_attrs&&t.fk_attrs.length>0){let i=c.unwrapList(t.fk_attrs).map(r=>this.visit(r,s)).join(", ");e.push(`(${i})`);}e.push("REFERENCES");}if(t.pktable)if(s.isPretty()&&!s.isColumnConstraint){let i=e.length-1;i>=0&&e[i].includes("REFERENCES")?e[i]+=" "+this.RangeVar(t.pktable,s):e.push(this.RangeVar(t.pktable,s));}else e.push(this.RangeVar(t.pktable,s));if(t.pk_attrs&&t.pk_attrs.length>0){let i=c.unwrapList(t.pk_attrs).map(r=>this.visit(r,s)).join(", ");if(s.isPretty()&&!s.isColumnConstraint){let r=e.length-1;r>=0?e[r]+=` (${i})`:e.push(`(${i})`);}else e.push(`(${i})`);}if(t.fk_matchtype&&t.fk_matchtype!=="s"){let i="";switch(t.fk_matchtype){case "f":i="MATCH FULL";break;case "p":i="MATCH PARTIAL";break}s.isPretty()&&!s.isColumnConstraint?e.push(`
32
- `+s.indent(i)):e.push(i);}if(t.fk_upd_action&&t.fk_upd_action!=="a"){let i="ON UPDATE ";switch(t.fk_upd_action){case "r":i+="RESTRICT";break;case "c":i+="CASCADE";break;case "n":i+="SET NULL";break;case "d":i+="SET DEFAULT";break}s.isPretty()?e.push(`
33
- `+s.indent(i)):(e.push("ON UPDATE"),e.push(i.replace("ON UPDATE ","")));}if(t.fk_del_action&&t.fk_del_action!=="a"){let i="ON DELETE ";switch(t.fk_del_action){case "r":i+="RESTRICT";break;case "c":i+="CASCADE";break;case "n":i+="SET NULL";break;case "d":i+="SET DEFAULT";break}s.isPretty()?e.push(`
34
- `+s.indent(i)):(e.push("ON DELETE"),e.push(i.replace("ON DELETE ","")));}t.skip_validation&&!s.isDomainConstraint&&(s.isPretty()&&!s.isColumnConstraint?e.push(`
35
- `+s.indent("NOT VALID")):e.push("NOT VALID"));break;case "CONSTR_ATTR_DEFERRABLE":e.push("DEFERRABLE");break;case "CONSTR_ATTR_NOT_DEFERRABLE":e.push("NOT DEFERRABLE");break;case "CONSTR_ATTR_DEFERRED":e.push("INITIALLY DEFERRED");break;case "CONSTR_ATTR_IMMEDIATE":e.push("INITIALLY IMMEDIATE");break;case "CONSTR_EXCLUSION":if(e.push("EXCLUDE"),t.access_method&&(e.push("USING"),e.push(t.access_method)),t.exclusions&&t.exclusions.length>0){let i=c.unwrapList(t.exclusions).map(r=>{if(this.getNodeType(r)==="List"){let n=c.unwrapList(r);if(n.length>=2){let o=this.visit(n[0],s),u=n[1],l="";if(this.getNodeType(u)==="List"){let p=c.unwrapList(u);p.length>0&&p[0].String&&(l=p[0].String.sval);}else u.String?l=u.String.sval:l=this.visit(u,s);return `${o} WITH ${l}`}}return this.visit(r,s)});e.push(`(${i.join(", ")})`);}t.where_clause&&(e.push("WHERE"),e.push(s.parens(this.visit(t.where_clause,s))));break}if((t.contype==="CONSTR_PRIMARY"||t.contype==="CONSTR_UNIQUE"||t.contype==="CONSTR_FOREIGN")&&(t.deferrable?s.isPretty()&&t.contype==="CONSTR_FOREIGN"?(e.push(`
36
- `+s.indent("DEFERRABLE")),t.initdeferred===true?e.push(`
37
- `+s.indent("INITIALLY DEFERRED")):t.initdeferred===false&&e.push(`
38
- `+s.indent("INITIALLY IMMEDIATE"))):(e.push("DEFERRABLE"),t.initdeferred===true?e.push("INITIALLY DEFERRED"):t.initdeferred===false&&e.push("INITIALLY IMMEDIATE")):t.deferrable===false&&(s.isPretty()&&t.contype==="CONSTR_FOREIGN"?e.push(`
39
- `+s.indent("NOT DEFERRABLE")):e.push("NOT DEFERRABLE"))),s.isPretty()&&t.contype==="CONSTR_FOREIGN"){let i="";for(let r=0;r<e.length;r++)e[r].startsWith(`
40
- `)||r>0&&!e[r-1].startsWith(`
41
- `)&&(i+=" "),i+=e[r];return i}return e.join(" ")}SubLink(t,s){let e=s.parens(this.visit(t.subselect,s));switch(t.subLinkType){case "ANY_SUBLINK":if(t.testexpr&&t.operName){let i=this.visit(t.testexpr,s),r=this.deparseOperatorName(t.operName,s);return `${i} ${r} ANY ${e}`}else if(t.testexpr)return `${this.visit(t.testexpr,s)} IN ${e}`;return e;case "ALL_SUBLINK":if(t.testexpr&&t.operName){let i=this.visit(t.testexpr,s),r=this.deparseOperatorName(t.operName,s);return `${i} ${r} ALL ${e}`}return e;case "EXISTS_SUBLINK":return `EXISTS ${e}`;case "ARRAY_SUBLINK":return `ARRAY${e}`;default:return e}}CaseWhen(t,s){let e=["WHEN"];return t.expr&&e.push(this.visit(t.expr,s)),e.push("THEN"),t.result&&e.push(this.visit(t.result,s)),e.join(" ")}WindowDef(t,s){let e=[];t.name&&e.push(t.name);let i=[];if(t.partitionClause){let n=c.unwrapList(t.partitionClause).map(o=>this.visit(o,s));i.push(`PARTITION BY ${n.join(", ")}`);}if(t.orderClause){let n=c.unwrapList(t.orderClause).map(o=>this.visit(o,s));i.push(`ORDER BY ${n.join(", ")}`);}if(t.frameOptions&&t.frameOptions!==1058){let r=this.formatWindowFrame(t,s.spawn("WindowDef"));r&&i.push(r);}return i.length>0?(t.name&&e.push("AS"),e.push(`(${i.join(" ")})`)):t.name?(e.push("AS"),e.push("()")):e.length===0&&e.push("()"),e.join(" ")}formatWindowFrame(t,s){if(!t.frameOptions)return null;let e=t.frameOptions,r=e&-229377,n=[];if(e&1&&(e&2?n.push("RANGE"):e&4?n.push("ROWS"):e&8&&n.push("GROUPS")),n.length===0)return null;let o=[];if(r===789)o.push("CURRENT ROW"),o.push("AND UNBOUNDED FOLLOWING");else if(r===1077)o.push("UNBOUNDED PRECEDING"),o.push("AND CURRENT ROW");else if(r===18453)t.startOffset&&t.endOffset&&(o.push(`${this.visit(t.startOffset,s)} PRECEDING`),o.push(`AND ${this.visit(t.endOffset,s)} FOLLOWING`));else if(r===1557)o.push("CURRENT ROW"),o.push("AND CURRENT ROW");else if(r===16917)o.push("CURRENT ROW"),t.endOffset&&o.push(`AND ${this.visit(t.endOffset,s)} FOLLOWING`);else {if(r===1058)return null;t.startOffset?e&1024?o.push(`${this.visit(t.startOffset,s)} PRECEDING`):e&2048?o.push(`${this.visit(t.startOffset,s)} FOLLOWING`):o.push(`${this.visit(t.startOffset,s)} PRECEDING`):e&16?o.push("UNBOUNDED PRECEDING"):e&32&&o.push("CURRENT ROW"),t.endOffset?o.length>0&&(e&4096?o.push(`AND ${this.visit(t.endOffset,s)} PRECEDING`):e&8192?o.push(`AND ${this.visit(t.endOffset,s)} FOLLOWING`):o.push(`AND ${this.visit(t.endOffset,s)} FOLLOWING`)):e&128?o.length>0&&o.push("AND UNBOUNDED FOLLOWING"):(o.length>0&&o.push("AND CURRENT ROW"));}return o.length>0&&(n.push("BETWEEN"),n.push(o.join(" "))),e&32768?n.push("EXCLUDE CURRENT ROW"):e&65536?n.push("EXCLUDE GROUP"):e&131072&&n.push("EXCLUDE TIES"),n.join(" ")}SortBy(t,s){let e=[];if(t.node&&e.push(this.visit(t.node,s)),t.sortby_dir==="SORTBY_USING"&&t.useOp){e.push("USING");let i=c.unwrapList(t.useOp);e.push(i.map(r=>r.String&&r.String.sval?r.String.sval:this.visit(r,s)).join("."));}else t.sortby_dir==="SORTBY_ASC"?e.push("ASC"):t.sortby_dir==="SORTBY_DESC"&&e.push("DESC");return t.sortby_nulls==="SORTBY_NULLS_FIRST"?e.push("NULLS FIRST"):t.sortby_nulls==="SORTBY_NULLS_LAST"&&e.push("NULLS LAST"),e.join(" ")}GroupingSet(t,s){switch(t.kind){case "GROUPING_SET_EMPTY":return "()";case "GROUPING_SET_SIMPLE":return "";case "GROUPING_SET_ROLLUP":return `ROLLUP (${c.unwrapList(t.content).map(l=>this.visit(l,s)).join(", ")})`;case "GROUPING_SET_CUBE":return `CUBE (${c.unwrapList(t.content).map(l=>this.visit(l,s)).join(", ")})`;case "GROUPING_SET_SETS":return `GROUPING SETS (${c.unwrapList(t.content).map(l=>this.visit(l,s)).join(", ")})`;default:return ""}}CommonTableExpr(t,s){let e=[];if(t.ctename&&e.push(t.ctename),t.aliascolnames){let r=c.unwrapList(t.aliascolnames).map(n=>this.visit(n,s));e[e.length-1]+=s.parens(r.join(", "));}return e.push("AS"),t.ctematerialized==="CTEMaterializeNever"?e.push("NOT MATERIALIZED"):t.ctematerialized==="CTEMaterializeAlways"&&e.push("MATERIALIZED"),t.ctequery&&e.push(s.parens(this.visit(t.ctequery,s))),e.join(" ")}ParamRef(t,s){return `$${t.number}`}LockingClause(t,s){let e=[];switch(t.strength){case "LCS_FORUPDATE":e.push("FOR UPDATE");break;case "LCS_FORSHARE":e.push("FOR SHARE");break;case "LCS_FORKEYSHARE":e.push("FOR KEY SHARE");break;case "LCS_FORNOKEYUPDATE":e.push("FOR NO KEY UPDATE");break;default:throw new Error(`Unsupported locking strength: ${t.strength}`)}if(t.lockedRels&&t.lockedRels.length>0){e.push("OF");let i=c.unwrapList(t.lockedRels).map(r=>this.visit(r,s)).join(", ");e.push(i);}return t.waitPolicy==="LockWaitSkip"?e.push("SKIP LOCKED"):t.waitPolicy==="LockWaitError"&&e.push("NOWAIT"),e.join(" ")}MinMaxExpr(t,s){let i=c.unwrapList(t.args).map(r=>this.visit(r,s));return t.op==="IS_GREATEST"?`GREATEST(${i.join(", ")})`:`LEAST(${i.join(", ")})`}RowExpr(t,s){let i=c.unwrapList(t.args).map(r=>this.visit(r,s));return t.row_format==="COERCE_IMPLICIT_CAST"?`(${i.join(", ")})`:`ROW(${i.join(", ")})`}OpExpr(t,s){let e=c.unwrapList(t.args);if(e.length===2){let i=this.visit(e[0],s),r=this.visit(e[1],s),n=this.getOperatorName(t.opno);return `${i} ${n} ${r}`}else if(e.length===1){let i=this.visit(e[0],s);return `${this.getOperatorName(t.opno)} ${i}`}throw new Error(`Unsupported OpExpr with ${e.length} arguments`)}DistinctExpr(t,s){let e=c.unwrapList(t.args);if(e.length===2){let i=s.spawn("DistinctExpr",{isStringLiteral:true}),r=this.visit(e[0],i),n=this.visit(e[1],i);return `${r} IS DISTINCT FROM ${n}`}throw new Error(`DistinctExpr requires exactly 2 arguments, got ${e.length}`)}NullIfExpr(t,s){let e=c.unwrapList(t.args);if(e.length===2){let i=s.spawn("NullIfExpr",{isStringLiteral:true}),r=this.visit(e[0],i),n=this.visit(e[1],i);return `NULLIF(${r}, ${n})`}throw new Error(`NullIfExpr requires exactly 2 arguments, got ${e.length}`)}ScalarArrayOpExpr(t,s){let e=c.unwrapList(t.args);if(e.length===2){let i=this.visit(e[0],s),r=this.visit(e[1],s),n=t.useOr?"ANY":"ALL",o=this.getOperatorName(t.opno);return `${i} ${o} ${n}(${r})`}throw new Error(`ScalarArrayOpExpr requires exactly 2 arguments, got ${e.length}`)}Aggref(t,s){let e=this.getAggFunctionName(t.aggfnoid),i=e+"(",r=t.aggdistinct&&t.aggdistinct.length>0;if(t.args&&t.args.length>0){let o=c.unwrapList(t.args).map(u=>this.visit(u,s));r?i+="DISTINCT "+o.join(", "):i+=o.join(", ");}else e.toUpperCase()==="COUNT"&&(r?i+="DISTINCT *":i+="*");if(i+=")",t.aggorder&&t.aggorder.length>0){i+=" ORDER BY ";let o=c.unwrapList(t.aggorder).map(u=>this.visit(u,s));i+=o.join(", ");}return i}WindowFunc(t,s){let i=this.getWindowFunctionName(t.winfnoid)+"(";if(t.args&&t.args.length>0){let n=c.unwrapList(t.args).map(o=>this.visit(o,s));i+=n.join(", ");}return i+=") OVER (",t.winref&&typeof t.winref=="object"?i+=this.visit(t.winref,s):t.winref&&(i+="ORDER BY created_at ASC"),i+=")",i}FieldSelect(t,s){let e=[];return t.arg&&e.push(this.visit(t.arg,s)),t.fieldnum!==void 0&&e.push(`.field_${t.fieldnum}`),e.join("")}RelabelType(t,s){if(t.arg){let e=s.spawn("RelabelType",{isStringLiteral:true});return this.visit(t.arg,e)}return ""}CoerceViaIO(t,s){return t.arg?this.visit(t.arg,s):""}ArrayCoerceExpr(t,s){return t.arg?this.visit(t.arg,s):""}ConvertRowtypeExpr(t,s){if(t.arg){let e=s.spawn("ConvertRowtypeExpr",{isStringLiteral:true});return this.visit(t.arg,e)}return ""}NamedArgExpr(t,s){let e=[];return t.name&&(e.push(t.name),e.push("=>")),t.arg&&e.push(this.visit(t.arg,s)),e.join(" ")}ViewStmt(t,s){let e=[];if(e.push("CREATE"),t.replace&&e.push("OR REPLACE"),t.view&&t.view.relpersistence==="t"&&e.push("TEMPORARY"),e.push("VIEW"),t.view&&e.push(this.RangeVar(t.view,s)),t.aliases&&t.aliases.length>0){let i=c.unwrapList(t.aliases).map(r=>this.visit(r,s));e.push(s.parens(i.join(", ")));}if(t.options&&t.options.length>0){let i=s.spawn("ViewStmt"),r=c.unwrapList(t.options).map(n=>this.visit(n,i));e.push(`WITH (${r.join(", ")})`);}if(e.push("AS"),t.query&&e.push(this.visit(t.query,s)),t.withCheckOption)switch(t.withCheckOption){case "CASCADED_CHECK_OPTION":e.push("WITH CASCADED CHECK OPTION");break;case "LOCAL_CHECK_OPTION":e.push("WITH LOCAL CHECK OPTION");break}return e.join(" ")}IndexStmt(t,s){let e=[];if(e.push("CREATE"),t.unique&&e.push("UNIQUE"),e.push("INDEX"),t.concurrent&&e.push("CONCURRENTLY"),t.if_not_exists&&e.push("IF NOT EXISTS"),t.idxname&&e.push(m.quoteIdentifier(t.idxname)),e.push("ON"),t.relation&&e.push(this.RangeVar(t.relation,s)),t.accessMethod&&t.accessMethod!=="btree"&&(e.push("USING"),e.push(t.accessMethod)),t.indexParams&&t.indexParams.length>0){let i=c.unwrapList(t.indexParams).map(r=>this.visit(r,s));e.push(s.parens(i.join(", ")));}if(t.indexIncludingParams&&t.indexIncludingParams.length>0){let i=c.unwrapList(t.indexIncludingParams).map(r=>this.visit(r,s));e.push("INCLUDE"),e.push(s.parens(i.join(", ")));}if(t.whereClause&&(e.push("WHERE"),e.push(this.visit(t.whereClause,s))),t.options&&t.options.length>0){let i=s.spawn("IndexStmt"),r=c.unwrapList(t.options).map(n=>this.visit(n,i));e.push("WITH"),e.push(s.parens(r.join(", ")));}return t.nulls_not_distinct&&e.push("NULLS NOT DISTINCT"),t.tableSpace&&(e.push("TABLESPACE"),e.push(m.quoteIdentifier(t.tableSpace))),e.join(" ")}IndexElem(t,s){let e=[];if(t.name?e.push(m.quoteIdentifier(t.name)):t.expr&&e.push(s.parens(this.visit(t.expr,s))),t.collation&&t.collation.length>0){let i=c.unwrapList(t.collation).map(r=>this.visit(r,s));e.push("COLLATE"),e.push(i.join("."));}if(t.opclass&&t.opclass.length>0){let r=c.unwrapList(t.opclass).map(n=>this.visit(n,s)).join(".");if(t.opclassopts&&t.opclassopts.length>0){let n=c.unwrapList(t.opclassopts).map(o=>{if(o.DefElem&&o.DefElem.arg&&this.getNodeType(o.DefElem.arg)==="String"){let u=this.getNodeData(o.DefElem.arg);return `${o.DefElem.defname}='${u.sval}'`}return this.visit(o,s.spawn("IndexElem"))});r+=`(${n.join(", ")})`;}e.push(r);}if(t.ordering)switch(t.ordering){case "SORTBY_ASC":e.push("ASC");break;case "SORTBY_DESC":e.push("DESC");break}if(t.nulls_ordering)switch(t.nulls_ordering){case "SORTBY_NULLS_FIRST":e.push("NULLS FIRST");break;case "SORTBY_NULLS_LAST":e.push("NULLS LAST");break}return e.join(" ")}PartitionElem(t,s){let e=[];if(t.name?e.push(m.quoteIdentifier(t.name)):t.expr&&e.push(s.parens(this.visit(t.expr,s))),t.collation&&t.collation.length>0){let i=c.unwrapList(t.collation).map(r=>this.visit(r,s));e.push("COLLATE"),e.push(i.join("."));}if(t.opclass&&t.opclass.length>0){let i=c.unwrapList(t.opclass).map(r=>this.visit(r,s));e.push(i.join("."));}return e.join(" ")}PartitionCmd(t,s){let e=[];if(t.concurrent&&e.push("CONCURRENTLY"),t.name&&e.push(this.visit(t.name,s)),t.bound)if(t.bound.strategy==="l"&&t.bound.listdatums){e.push("FOR VALUES IN");let i=c.unwrapList(t.bound.listdatums).map(r=>this.visit(r,s)).join(", ");e.push(`(${i})`);}else if(t.bound.strategy==="r"&&(t.bound.lowerdatums||t.bound.upperdatums)){if(e.push("FOR VALUES FROM"),t.bound.lowerdatums){let i=c.unwrapList(t.bound.lowerdatums).map(r=>this.visit(r,s)).join(", ");e.push(`(${i})`);}if(t.bound.upperdatums){e.push("TO");let i=c.unwrapList(t.bound.upperdatums).map(r=>this.visit(r,s)).join(", ");e.push(`(${i})`);}}else t.bound.strategy==="h"&&t.bound.modulus!==void 0&&t.bound.remainder!==void 0?(e.push("FOR VALUES WITH"),e.push(`(modulus ${t.bound.modulus}, remainder ${t.bound.remainder})`)):t.bound.is_default&&e.push("DEFAULT");return e.join(" ")}getAggFunctionName(t){return {2100:"avg",2101:"count",2102:"max",2103:"min",2104:"sum",2105:"stddev",2106:"variance",2107:"array_agg",2108:"string_agg"}[t||0]||"unknown_agg"}getWindowFunctionName(t){return {3100:"row_number",3101:"rank",3102:"dense_rank",3103:"percent_rank",3104:"cume_dist",3105:"ntile",3106:"lag",3107:"lead",3108:"first_value",3109:"last_value"}[t||0]||"unknown_window_func"}getOperatorName(t){return {96:"=",518:"<>",97:"<",521:">",523:"<=",525:">=",551:"+",552:"-",553:"*",554:"/",555:"%",484:"-",1752:"~~",1753:"!~~",1754:"~~*",1755:"!~~*",15:"=",58:"<",59:"<=",61:">",62:">="}[t||0]||"="}JoinExpr(t,s){let e=[];t.larg&&e.push(this.visit(t.larg,s));let i="";switch(t.isNatural&&(i="NATURAL "),t.jointype){case "JOIN_INNER":t.isNatural?i+="JOIN":!t.quals&&(!t.usingClause||t.usingClause.length===0)?i+="CROSS JOIN":i+="JOIN";break;case "JOIN_LEFT":i+="LEFT JOIN";break;case "JOIN_FULL":i+="FULL JOIN";break;case "JOIN_RIGHT":i+="RIGHT JOIN";break;default:i+="JOIN";}if(t.rarg){let n=this.visit(t.rarg,s);t.rarg&&"JoinExpr"in t.rarg&&!t.rarg.JoinExpr.alias&&(n=`(${n})`),s.isPretty()?e.push(s.newline()+i+" "+n):e.push(i+" "+n);}else s.isPretty()?e.push(s.newline()+i):e.push(i);if(t.usingClause&&t.usingClause.length>0){let o=c.unwrapList(t.usingClause).map(u=>this.visit(u,s));s.isPretty()?e.push(` USING (${o.join(", ")})`):e.push(`USING (${o.join(", ")})`);}else if(t.quals){let n=this.visit(t.quals,s);s.isPretty()?n.includes("AND")||n.includes("OR")||n.length>50?this.containsMultilineStringLiteral(n)?e.push(` ON ${n}`):e.push(` ON${s.newline()}${s.indent(n)}`):e.push(` ON ${n}`):e.push(`ON ${n}`);}let r;if(s.isPretty()?r=e.join(""):r=e.join(" "),t.join_using_alias&&t.join_using_alias.aliasname){let n=t.join_using_alias.aliasname;if(t.join_using_alias.colnames&&t.join_using_alias.colnames.length>0){let u=c.unwrapList(t.join_using_alias.colnames).map(l=>this.visit(l,s)).join(", ");n+=`(${u})`;}r+=` AS ${n}`;}if(t.alias&&t.alias.aliasname){let n=t.alias.aliasname;if(t.alias.colnames&&t.alias.colnames.length>0){let u=c.unwrapList(t.alias.colnames).map(l=>this.visit(l,s)).join(", ");n+=`(${u})`;}r=`(${r}) ${n}`;}return r}FromExpr(t,s){let r=c.unwrapList(t.fromlist).map(n=>this.visit(n,s)).join(", ");return t.quals&&(r+=` WHERE ${this.visit(t.quals,s)}`),r}TransactionStmt(t,s){let e=[];switch(t.kind){case "TRANS_STMT_BEGIN":e.push("BEGIN");break;case "TRANS_STMT_START":e.push("START TRANSACTION");break;case "TRANS_STMT_COMMIT":e.push("COMMIT");break;case "TRANS_STMT_ROLLBACK":e.push("ROLLBACK");break;case "TRANS_STMT_SAVEPOINT":e.push("SAVEPOINT"),t.savepoint_name&&e.push(m.quoteIdentifier(t.savepoint_name));break;case "TRANS_STMT_RELEASE":e.push("RELEASE SAVEPOINT"),t.savepoint_name&&e.push(m.quoteIdentifier(t.savepoint_name));break;case "TRANS_STMT_ROLLBACK_TO":e.push("ROLLBACK TO"),t.savepoint_name&&e.push(m.quoteIdentifier(t.savepoint_name));break;case "TRANS_STMT_PREPARE":e.push("PREPARE TRANSACTION"),t.gid&&e.push(`'${t.gid}'`);break;case "TRANS_STMT_COMMIT_PREPARED":e.push("COMMIT PREPARED"),t.gid&&e.push(`'${t.gid}'`);break;case "TRANS_STMT_ROLLBACK_PREPARED":e.push("ROLLBACK PREPARED"),t.gid&&e.push(`'${t.gid}'`);break;default:throw new Error(`Unsupported TransactionStmt kind: ${t.kind}`)}if(t.options&&t.options.length>0){let i=c.unwrapList(t.options).map(r=>{if(r.DefElem){let n=r.DefElem;if(n.defname==="transaction_read_only"){let o=false;if(n.arg){let u=this.getNodeData(n.arg);if(u.ival!==void 0)o=(typeof u.ival=="object"?u.ival.ival:u.ival)===1;else if(u.sval!==void 0){let p=(typeof u.sval=="object"?u.sval.sval:u.sval).replace(/'/g,"");o=p.toLowerCase()==="on"||p.toLowerCase()==="true";}}return o?"READ ONLY":"READ WRITE"}else if(n.defname==="transaction_isolation"){if(n.arg&&n.arg.A_Const&&n.arg.A_Const.sval)return `ISOLATION LEVEL ${n.arg.A_Const.sval.sval.toUpperCase()}`}else if(n.defname==="transaction_deferrable"){let o=false;if(n.arg){let u=this.getNodeData(n.arg);if(u.ival!==void 0)o=(typeof u.ival=="object"?u.ival.ival:u.ival)===1;else if(u.sval!==void 0){let p=(typeof u.sval=="object"?u.sval.sval:u.sval).replace(/'/g,"");o=p.toLowerCase()==="on"||p.toLowerCase()==="true";}}return o?"DEFERRABLE":"NOT DEFERRABLE"}}return this.visit(r,s)}).filter(Boolean);i.length>0&&e.push(i.join(", "));}return e.join(" ")}VariableSetStmt(t,s){switch(t.kind){case "VAR_SET_VALUE":let e=t.is_local?"LOCAL ":"",i=t.args?c.unwrapList(t.args).map(l=>{let p=this.getNodeData(l);if(p.sval!==void 0){let f=typeof p.sval=="object"?p.sval.sval:p.sval;return f===""||f.includes(" ")||f.includes("-")||/[A-Z]/.test(f)||/^\d/.test(f)||f.includes(".")||f.includes("$")||f.toLowerCase()==="all"||/^[+-]\d/.test(f)?`'${f}'`:f}return this.visit(l,s)}).join(", "):"",r=m.quoteIdentifier(t.name);return !t.args||t.args.length===0?`SET ${e}${r}`:`SET ${e}${r} TO ${i}`;case "VAR_SET_DEFAULT":return `SET ${m.quoteIdentifier(t.name)} TO DEFAULT`;case "VAR_SET_CURRENT":return `SET ${m.quoteIdentifier(t.name)} FROM CURRENT`;case "VAR_SET_MULTI":if(t.name==="TRANSACTION"||t.name==="SESSION CHARACTERISTICS"){let l=[];if(t.args){let p=c.unwrapList(t.args);for(let f of p)if(f.DefElem){let h=f.DefElem;if(h.defname==="transaction_isolation"){let E=h.arg?this.visit(h.arg,s):"";l.push(`ISOLATION LEVEL ${E.replace(/'/g,"").toUpperCase()}`);}else if(h.defname==="transaction_read_only"){let E=false;if(h.arg){let g=this.getNodeData(h.arg);if(g.ival!==void 0)E=(typeof g.ival=="object"?g.ival.ival:g.ival)===1;else if(g.sval!==void 0){let b=(typeof g.sval=="object"?g.sval.sval:g.sval).replace(/'/g,"");E=b.toLowerCase()==="on"||b.toLowerCase()==="true";}}l.push(E?"READ ONLY":"READ WRITE");}else if(h.defname==="transaction_deferrable"){let E=false;if(h.arg){let g=this.getNodeData(h.arg);if(g.ival!==void 0)E=(typeof g.ival=="object"?g.ival.ival:g.ival)===1;else if(g.sval!==void 0){let b=(typeof g.sval=="object"?g.sval.sval:g.sval).replace(/'/g,"");E=b.toLowerCase()==="on"||b.toLowerCase()==="true";}}l.push(E?"DEFERRABLE":"NOT DEFERRABLE");}}}return t.name==="SESSION CHARACTERISTICS"?`SET SESSION CHARACTERISTICS AS TRANSACTION ${l.join(", ")}`:`SET TRANSACTION ${l.join(", ")}`}else return `SET ${t.args?c.unwrapList(t.args).map(p=>p.VariableSetStmt?this.VariableSetStmt(p.VariableSetStmt,s):this.visit(p,s)).join(", "):""}`;case "VAR_RESET":return `RESET ${m.quoteIdentifier(t.name)}`;case "VAR_RESET_ALL":return "RESET ALL";default:throw new Error(`Unsupported VariableSetStmt kind: ${t.kind}`)}}VariableShowStmt(t,s){return t.name==="ALL"?"SHOW ALL":`SHOW ${t.name}`}CreateSchemaStmt(t,s){let e=["CREATE SCHEMA"];if(t.if_not_exists&&e.push("IF NOT EXISTS"),t.schemaname&&e.push(m.quoteIdentifier(t.schemaname)),t.authrole&&(e.push("AUTHORIZATION"),e.push(this.RoleSpec(t.authrole,s))),t.schemaElts&&t.schemaElts.length>0){let i=c.unwrapList(t.schemaElts).map(r=>this.visit(r,s)).join(" ");e.push(i);}return e.join(" ")}RoleSpec(t,s){if(t.rolename)return this.quoteIfNeeded(t.rolename);switch(t.roletype){case "ROLESPEC_PUBLIC":return "PUBLIC";case "ROLESPEC_CURRENT_USER":return "CURRENT_USER";case "ROLESPEC_SESSION_USER":return "SESSION_USER";case "ROLESPEC_CURRENT_ROLE":return "CURRENT_ROLE";default:return "PUBLIC"}}roletype(t,s){return t.rolename?t.rolename:""}DropStmt(t,s){let e=["DROP"];if(t.removeType)switch(t.removeType){case "OBJECT_TABLE":e.push("TABLE");break;case "OBJECT_VIEW":e.push("VIEW");break;case "OBJECT_INDEX":e.push("INDEX");break;case "OBJECT_SEQUENCE":e.push("SEQUENCE");break;case "OBJECT_SCHEMA":e.push("SCHEMA");break;case "OBJECT_FUNCTION":e.push("FUNCTION");break;case "OBJECT_PROCEDURE":e.push("PROCEDURE");break;case "OBJECT_DATABASE":e.push("DATABASE");break;case "OBJECT_EXTENSION":e.push("EXTENSION");break;case "OBJECT_TYPE":e.push("TYPE");break;case "OBJECT_DOMAIN":e.push("DOMAIN");break;case "OBJECT_TRIGGER":e.push("TRIGGER");break;case "OBJECT_RULE":e.push("RULE");break;case "OBJECT_POLICY":e.push("POLICY");break;case "OBJECT_ROLE":e.push("ROLE");break;case "OBJECT_TABLESPACE":e.push("TABLESPACE");break;case "OBJECT_FOREIGN_SERVER":e.push("SERVER");break;case "OBJECT_FDW":e.push("FOREIGN DATA WRAPPER");break;case "OBJECT_PUBLICATION":e.push("PUBLICATION");break;case "OBJECT_SUBSCRIPTION":e.push("SUBSCRIPTION");break;case "OBJECT_CAST":e.push("CAST");break;case "OBJECT_TRANSFORM":e.push("TRANSFORM");break;case "OBJECT_ACCESS_METHOD":e.push("ACCESS METHOD");break;case "OBJECT_OPERATOR":e.push("OPERATOR");break;case "OBJECT_FOREIGN_TABLE":e.push("FOREIGN TABLE");break;case "OBJECT_MATVIEW":e.push("MATERIALIZED VIEW");break;case "OBJECT_OPCLASS":e.push("OPERATOR CLASS");break;case "OBJECT_OPFAMILY":e.push("OPERATOR FAMILY");break;case "OBJECT_COLLATION":e.push("COLLATION");break;case "OBJECT_CONVERSION":e.push("CONVERSION");break;case "OBJECT_LANGUAGE":e.push("LANGUAGE");break;case "OBJECT_LARGEOBJECT":e.push("LARGE OBJECT");break;case "OBJECT_AGGREGATE":e.push("AGGREGATE");break;case "OBJECT_STATISTIC_EXT":e.push("STATISTICS");break;case "OBJECT_EVENT_TRIGGER":e.push("EVENT TRIGGER");break;case "OBJECT_AMOP":e.push("OPERATOR CLASS");break;case "OBJECT_AMPROC":e.push("OPERATOR CLASS");break;case "OBJECT_ATTRIBUTE":e.push("ATTRIBUTE");break;case "OBJECT_DEFAULT":e.push("DEFAULT");break;case "OBJECT_DEFACL":e.push("DEFAULT PRIVILEGES");break;case "OBJECT_PARAMETER_ACL":e.push("PARAMETER");break;case "OBJECT_PUBLICATION_NAMESPACE":e.push("PUBLICATION");break;case "OBJECT_PUBLICATION_REL":e.push("PUBLICATION");break;case "OBJECT_ROUTINE":e.push("ROUTINE");break;case "OBJECT_TABCONSTRAINT":e.push("CONSTRAINT");break;case "OBJECT_TSCONFIGURATION":e.push("TEXT SEARCH CONFIGURATION");break;case "OBJECT_TSDICTIONARY":e.push("TEXT SEARCH DICTIONARY");break;case "OBJECT_TSPARSER":e.push("TEXT SEARCH PARSER");break;case "OBJECT_TSTEMPLATE":e.push("TEXT SEARCH TEMPLATE");break;case "OBJECT_USER_MAPPING":e.push("USER MAPPING");break;default:throw new Error(`Unsupported DROP object type: ${t.removeType}`)}if(t.concurrent&&e.push("CONCURRENTLY"),t.missing_ok&&e.push("IF EXISTS"),t.objects&&t.objects.length>0)if(t.removeType==="OBJECT_POLICY"){let i=t.objects[0];if(i&&i.List&&i.List.items){let r=i.List.items.map(n=>n.String&&n.String.sval?n.String.sval:this.visit(n,s));if(r.length===3){let[n,o,u]=r;e.push(`${u} ON ${n}.${o}`);}else if(r.length===2){let[n,o]=r;e.push(`${o} ON ${n}`);}else e.push(r.join(", "));}}else if(t.removeType==="OBJECT_CAST"){let i=t.objects.map(r=>{if(r&&r.List&&r.List.items){let o=r.List.items.map(u=>this.visit(u,s)).filter(u=>u&&u.trim());if(o.length===2){let[u,l]=o;return `(${u} AS ${l})`}return o.join(".")}return this.visit(r,s)}).filter(r=>r&&r.trim()).join(", ");i&&e.push(i);}else if(t.removeType==="OBJECT_TRIGGER"||t.removeType==="OBJECT_RULE"){let i=t.objects.map(r=>{if(r&&r.List&&r.List.items){let o=r.List.items.map(u=>u.String&&u.String.sval?m.quoteIdentifier(u.String.sval):this.visit(u,s)).filter(u=>u&&u.trim());if(o.length===2){let[u,l]=o;return `${l} ON ${u}`}else if(o.length===3){let[u,l,p]=o;return `${p} ON ${u}.${l}`}return o.join(".")}return this.visit(r,s)}).filter(r=>r&&r.trim()).join(", ");i&&e.push(i);}else if(t.removeType==="OBJECT_OPFAMILY"||t.removeType==="OBJECT_OPCLASS"){let i=t.objects.map(r=>{if(r&&r.List&&r.List.items){let o=r.List.items.map(u=>u.String&&u.String.sval?u.String.sval:this.visit(u,s)).filter(u=>u&&u.trim());if(o.length===2){let u=o[0],l=o[1];return `${m.quoteIdentifier(l)} USING ${u}`}else if(o.length===3){let u=o[0],l=o[1],p=o[2];return `${m.quoteQualifiedIdentifier(l,p)} USING ${u}`}return o.join(".")}return this.visit(r,s)}).filter(r=>r&&r.trim()).join(", ");i&&e.push(i);}else if(t.removeType==="OBJECT_TRANSFORM"){let i=t.objects.map(r=>{if(r&&r.List&&r.List.items){let o=r.List.items.map(u=>u.String&&u.String.sval?u.String.sval:this.visit(u,s)).filter(u=>u&&u.trim());if(o.length===2){let[u,l]=o;return `FOR ${u} LANGUAGE ${l}`}return o.join(".")}return this.visit(r,s)}).filter(r=>r&&r.trim()).join(", ");i&&e.push(i);}else {let i=t.objects.map(r=>{if(Array.isArray(r))return r.map(l=>this.visit(l,s)).filter(l=>l&&l.trim()).join(".");if(r&&r.List&&r.List.items)return r.List.items.map(l=>l.String&&l.String.sval?m.quoteIdentifier(l.String.sval):this.visit(l,s)).filter(l=>l&&l.trim()).join(".");let n=s.spawn("DropStmt",{objtype:t.removeType});return this.visit(r,n)}).filter(r=>r&&r.trim()).join(", ");i&&e.push(i);}return t.behavior==="DROP_CASCADE"&&e.push("CASCADE"),e.join(" ")}TruncateStmt(t,s){let e=["TRUNCATE"];if(t.relations&&t.relations.length>0){let i=t.relations.map(r=>this.visit(r,s)).join(", ");e.push(i);}return t.restart_seqs&&e.push("RESTART IDENTITY"),t.behavior==="DROP_CASCADE"&&e.push("CASCADE"),e.join(" ")}ReturnStmt(t,s){let e=["RETURN"];if(t.returnval){let i=this.visit(t.returnval,s);e.push(i);}return e.join(" ")}PLAssignStmt(t,s){let e=[];if(t.name){let i=m.quoteIdentifier(t.name);if(t.indirection&&t.indirection.length>0){let r=t.indirection.map(n=>this.visit(n,s)).join("");i+=r;}e.push(i);}if(e.push(":="),t.val){let i=t.val;if(i.targetList){e.push("SELECT");let r=this.targetList(i.targetList,s);e.push(r);}else {let r=this.visit(t.val,s);e.push(r);}}return e.join(" ")}CopyStmt(t,s){let e=["COPY"];if(t.relation){let i=this.RangeVar(t.relation,s);e.push(i);}else if(t.query){let i=this.visit(t.query,s);e.push(`(${i})`);}if(t.attlist&&t.attlist.length>0){let i=c.unwrapList(t.attlist).map(r=>this.visit(r,s)).join(", ");e.push(`(${i})`);}if(t.is_from?e.push("FROM"):e.push("TO"),t.is_program&&e.push("PROGRAM"),t.filename?e.push(`'${t.filename}'`):e.push("STDIN"),t.options&&t.options.length>0){e.push("WITH");let i=c.unwrapList(t.options).map(r=>this.visit(r,s.spawn("CopyStmt"))).join(", ");e.push(`(${i})`);}if(t.whereClause){e.push("WHERE");let i=this.visit(t.whereClause,s);e.push(i);}return e.join(" ")}AlterTableStmt(t,s){let e=["ALTER"];if(t.objtype)switch(t.objtype){case "OBJECT_TABLE":e.push("TABLE");break;case "OBJECT_INDEX":e.push("INDEX");break;case "OBJECT_SEQUENCE":e.push("SEQUENCE");break;case "OBJECT_VIEW":e.push("VIEW");break;case "OBJECT_MATVIEW":e.push("MATERIALIZED VIEW");break;case "OBJECT_FOREIGN_TABLE":e.push("FOREIGN TABLE");break;case "OBJECT_TYPE":e.push("TYPE");break;default:e.push("TABLE");}else e.push("TABLE");t.missing_ok&&e.push("IF EXISTS");let i=s.spawn("AlterTableStmt",{objtype:t.objtype});if(t.relation){let r=this.RangeVar(t.relation,i);e.push(r);}if(t.cmds&&t.cmds.length>0){let r=c.unwrapList(t.cmds);if(s.isPretty()){let n=r.map(o=>{let u=this.visit(o,i);return s.newline()+s.indent(u)}).join(",");e.push(n);}else {let n=r.map(o=>this.visit(o,i)).join(", ");e.push(n);}}return e.join(" ")}AlterTableCmd(t,s){let e=[];if(t.subtype)switch(t.subtype){case "AT_AddColumn":if(s.objtype==="OBJECT_TYPE"?e.push("ADD ATTRIBUTE"):e.push("ADD COLUMN"),t.missing_ok&&e.push("IF NOT EXISTS"),t.def){let i=this.getNodeData(t.def);if(s.isPretty()){let r=[],n=[];if(i.colname&&r.push(m.quoteIdentifier(i.colname)),i.typeName&&r.push(this.TypeName(i.typeName,s)),i.is_not_null&&n.push("NOT NULL"),i.collClause&&n.push(this.CollateClause(i.collClause,s)),i.constraints&&c.unwrapList(i.constraints).forEach(l=>{let p=s.spawn("ColumnDef",{isColumnConstraint:true}),f=this.visit(l,p);if(f.includes("REFERENCES")&&f.includes("ON DELETE")){let h=f.match(/^(.*REFERENCES[^)]*\([^)]*\))\s*(ON\s+DELETE\s+CASCADE.*)$/);h?(n.push(h[1]),n.push(h[2])):n.push(f);}else if(f==="UNIQUE"&&i.raw_default){let h="DEFAULT "+this.visit(i.raw_default,s);n.push("UNIQUE "+h);}else n.push(f);}),i.raw_default&&!i.constraints?.some(u=>this.visit(u,s.spawn("ColumnDef",{isColumnConstraint:true}))==="UNIQUE")){let u="DEFAULT "+this.visit(i.raw_default,s);n.push(u);}if(i.fdwoptions&&i.fdwoptions.length>0){n.push("OPTIONS");let u=s.spawn("ColumnDef"),l=c.unwrapList(i.fdwoptions).map(p=>this.visit(p,u));n.push(`(${l.join(", ")})`);}let o=r.join(" ");if(n.length>0){let u=n.map(l=>s.indent(l)).join(s.newline());o+=s.newline()+u;}e.push(o);}else {let r=[];if(i.colname&&r.push(m.quoteIdentifier(i.colname)),i.typeName&&r.push(this.TypeName(i.typeName,s)),i.collClause&&r.push(this.CollateClause(i.collClause,s)),i.fdwoptions&&i.fdwoptions.length>0){r.push("OPTIONS");let n=s.spawn("ColumnDef"),o=c.unwrapList(i.fdwoptions).map(u=>this.visit(u,n));r.push(`(${o.join(", ")})`);}if(i.constraints){let o=c.unwrapList(i.constraints).map(u=>{let l=s.spawn("ColumnDef",{isColumnConstraint:true});return this.visit(u,l)});r.push(...o);}i.raw_default&&(r.push("DEFAULT"),r.push(this.visit(i.raw_default,s))),i.is_not_null&&r.push("NOT NULL"),e.push(r.join(" "));}}t.behavior==="DROP_CASCADE"&&e.push("CASCADE");break;case "AT_DropColumn":t.missing_ok?s.objtype==="OBJECT_TYPE"?e.push("DROP ATTRIBUTE IF EXISTS"):e.push("DROP COLUMN IF EXISTS"):s.objtype==="OBJECT_TYPE"?e.push("DROP ATTRIBUTE"):e.push("DROP COLUMN"),t.name&&e.push(m.quoteIdentifier(t.name)),t.behavior==="DROP_CASCADE"?e.push("CASCADE"):t.behavior==="DROP_RESTRICT"&&e.push("RESTRICT");break;case "AT_AlterColumnType":if(s.objtype==="OBJECT_TYPE"?e.push("ALTER ATTRIBUTE"):e.push("ALTER COLUMN"),t.name&&e.push(m.quoteIdentifier(t.name)),e.push("TYPE"),t.def){let i=this.getNodeData(t.def);if(i&&i.typeName)e.push(this.TypeName(i.typeName,s)),i.raw_default&&(e.push("USING"),e.push(this.visit(i.raw_default,s)));else {let r=this.visit(t.def,s);e.push(r);}}t.behavior==="DROP_CASCADE"&&e.push("CASCADE");break;case "AT_SetTableSpace":e.push("SET TABLESPACE"),t.name&&e.push(m.quoteIdentifier(t.name));break;case "AT_AddConstraint":if(e.push("ADD"),t.def){let i=this.visit(t.def,s);e.push(i);}break;case "AT_DropConstraint":t.missing_ok?e.push("DROP CONSTRAINT IF EXISTS"):e.push("DROP CONSTRAINT"),t.name&&e.push(m.quoteIdentifier(t.name)),t.behavior==="DROP_CASCADE"?e.push("CASCADE"):t.behavior==="DROP_RESTRICT"&&e.push("RESTRICT");break;case "AT_SetRelOptions":if(e.push("SET"),t.def){let i=s.spawn("AlterTableCmd",{subtype:"AT_SetRelOptions"}),r=c.unwrapList(t.def).map(n=>this.visit(n,i)).join(", ");e.push(`(${r})`);}else e.push("()");break;case "AT_ResetRelOptions":if(e.push("RESET"),t.def){let i=s.spawn("AlterTableCmd",{subtype:"AT_ResetRelOptions"}),r=c.unwrapList(t.def).map(n=>this.visit(n,i)).join(", ");e.push(`(${r})`);}else e.push("()");break;case "AT_ColumnDefault":e.push("ALTER COLUMN"),t.name&&e.push(m.quoteIdentifier(t.name)),t.def?(e.push("SET DEFAULT"),e.push(this.visit(t.def,s))):e.push("DROP DEFAULT");break;case "AT_SetStorage":if(e.push("ALTER COLUMN"),t.name&&e.push(m.quoteIdentifier(t.name)),e.push("SET STORAGE"),t.def){let i=this.visit(t.def,s);e.push(i);}break;case "AT_ClusterOn":e.push("CLUSTER ON"),t.name&&e.push(m.quoteIdentifier(t.name));break;case "AT_DropCluster":e.push("SET WITHOUT CLUSTER");break;case "AT_ChangeOwner":e.push("OWNER TO"),t.newowner&&e.push(this.RoleSpec(t.newowner,s));break;case "AT_AddInherit":e.push("INHERIT"),t.def&&e.push(this.visit(t.def,s));break;case "AT_DropInherit":e.push("NO INHERIT"),t.def&&e.push(this.visit(t.def,s));break;case "AT_SetNotNull":e.push("ALTER COLUMN"),t.name&&e.push(m.quoteIdentifier(t.name)),e.push("SET NOT NULL");break;case "AT_DropNotNull":e.push("ALTER COLUMN"),t.name&&e.push(m.quoteIdentifier(t.name)),e.push("DROP NOT NULL");break;case "AT_SetStatistics":e.push("ALTER COLUMN"),t.name?e.push(m.quoteIdentifier(t.name)):t.num!==void 0&&t.num!==null&&e.push(t.num.toString()),e.push("SET STATISTICS"),t.def&&e.push(this.visit(t.def,s));break;case "AT_SetOptions":if(e.push("ALTER COLUMN"),t.name&&e.push(m.quoteIdentifier(t.name)),e.push("SET"),t.def){let i=s.spawn("AlterTableCmd",{subtype:"AT_SetOptions"}),r=c.unwrapList(t.def).map(n=>this.visit(n,i)).join(", ");e.push(`(${r})`);}else e.push("()");break;case "AT_ResetOptions":if(e.push("ALTER COLUMN"),t.name&&e.push(m.quoteIdentifier(t.name)),e.push("RESET"),t.def){let i=s.spawn("AlterTableCmd",{subtype:"AT_ResetOptions"}),r=c.unwrapList(t.def).map(n=>this.visit(n,i)).join(", ");e.push(`(${r})`);}else e.push("()");break;case "AT_SetCompression":e.push("ALTER COLUMN"),t.name&&e.push(m.quoteIdentifier(t.name)),e.push("SET COMPRESSION"),t.def&&e.push(this.visit(t.def,s));break;case "AT_ValidateConstraint":e.push("VALIDATE CONSTRAINT"),t.name&&e.push(m.quoteIdentifier(t.name));break;case "AT_EnableTrig":e.push("ENABLE TRIGGER"),t.name&&e.push(m.quoteIdentifier(t.name));break;case "AT_EnableAlwaysTrig":e.push("ENABLE ALWAYS TRIGGER"),t.name&&e.push(m.quoteIdentifier(t.name));break;case "AT_EnableReplicaTrig":e.push("ENABLE REPLICA TRIGGER"),t.name&&e.push(m.quoteIdentifier(t.name));break;case "AT_DisableTrig":e.push("DISABLE TRIGGER"),t.name&&e.push(m.quoteIdentifier(t.name));break;case "AT_EnableTrigAll":e.push("ENABLE TRIGGER ALL");break;case "AT_DisableTrigAll":e.push("DISABLE TRIGGER ALL");break;case "AT_EnableTrigUser":e.push("ENABLE TRIGGER USER");break;case "AT_DisableTrigUser":e.push("DISABLE TRIGGER USER");break;case "AT_EnableRule":e.push("ENABLE RULE"),t.name&&e.push(m.quoteIdentifier(t.name));break;case "AT_EnableAlwaysRule":e.push("ENABLE ALWAYS RULE"),t.name&&e.push(m.quoteIdentifier(t.name));break;case "AT_EnableReplicaRule":e.push("ENABLE REPLICA RULE"),t.name&&e.push(m.quoteIdentifier(t.name));break;case "AT_DisableRule":e.push("DISABLE RULE"),t.name&&e.push(m.quoteIdentifier(t.name));break;case "AT_SetAccessMethod":e.push("SET ACCESS METHOD"),t.name?e.push(m.quoteIdentifier(t.name)):e.push("DEFAULT");break;case "AT_EnableRowSecurity":e.push("ENABLE ROW LEVEL SECURITY");break;case "AT_DisableRowSecurity":e.push("DISABLE ROW LEVEL SECURITY");break;case "AT_ForceRowSecurity":e.push("FORCE ROW LEVEL SECURITY");break;case "AT_NoForceRowSecurity":e.push("NO FORCE ROW LEVEL SECURITY");break;case "AT_AttachPartition":e.push("ATTACH PARTITION"),t.def&&e.push(this.visit(t.def,s));break;case "AT_DetachPartition":e.push("DETACH PARTITION"),t.def&&e.push(this.visit(t.def,s));break;case "AT_DetachPartitionFinalize":e.push("DETACH PARTITION"),t.def&&e.push(this.visit(t.def,s)),e.push("FINALIZE");break;case "AT_SetLogged":e.push("SET LOGGED");break;case "AT_SetUnLogged":e.push("SET UNLOGGED");break;case "AT_AddColumnToView":if(e.push("ADD COLUMN"),t.def){let i=this.visit(t.def,s);e.push(i);}break;case "AT_CookedColumnDefault":e.push("ALTER COLUMN"),t.name&&e.push(m.quoteIdentifier(t.name)),t.def?(e.push("SET DEFAULT"),e.push(this.visit(t.def,s))):e.push("DROP DEFAULT");break;case "AT_SetExpression":e.push("ALTER COLUMN"),t.name&&e.push(m.quoteIdentifier(t.name)),e.push("SET EXPRESSION"),t.def&&e.push(this.visit(t.def,s));break;case "AT_DropExpression":e.push("ALTER COLUMN"),t.name&&e.push(m.quoteIdentifier(t.name)),e.push("DROP EXPRESSION");break;case "AT_CheckNotNull":e.push("ALTER COLUMN"),t.name&&e.push(m.quoteIdentifier(t.name)),e.push("SET NOT NULL");break;case "AT_AddIndex":e.push("ADD"),t.def&&e.push(this.visit(t.def,s));break;case "AT_ReAddIndex":e.push("ADD"),t.def&&e.push(this.visit(t.def,s));break;case "AT_ReAddConstraint":e.push("ADD"),t.def&&e.push(this.visit(t.def,s));break;case "AT_ReAddDomainConstraint":e.push("ADD"),t.def&&e.push(this.visit(t.def,s));break;case "AT_AlterConstraint":if(e.push("ALTER CONSTRAINT"),t.def&&this.getNodeType(t.def)==="Constraint"){let i=this.getNodeData(t.def);i.conname&&(e.push(m.quoteIdentifier(i.conname)),i.deferrable!==void 0&&e.push(i.deferrable?"DEFERRABLE":"NOT DEFERRABLE"),i.initdeferred!==void 0&&e.push(i.initdeferred?"INITIALLY DEFERRED":"INITIALLY IMMEDIATE"));}else t.name&&(e.push(m.quoteIdentifier(t.name)),t.def&&e.push(this.visit(t.def,s)));break;case "AT_AddIndexConstraint":e.push("ADD"),t.def&&e.push(this.visit(t.def,s));break;case "AT_ReAddComment":e.push("COMMENT"),t.def&&e.push(this.visit(t.def,s));break;case "AT_AlterColumnGenericOptions":if(e.push("ALTER COLUMN"),t.name&&e.push(m.quoteIdentifier(t.name)),e.push("OPTIONS"),t.def){let i=s.spawn("AlterTableCmd",{alterColumnOptions:true}),r=c.unwrapList(t.def).map(n=>this.visit(n,i)).join(", ");e.push(`(${r})`);}break;case "AT_DropOids":e.push("SET WITHOUT OIDS");break;case "AT_ReplaceRelOptions":if(e.push("REPLACE"),t.def&&Array.isArray(t.def)){let i=c.unwrapList(t.def).map(r=>this.visit(r,s)).join(", ");e.push(`(${i})`);}else e.push("()");break;case "AT_AddOf":e.push("OF"),t.def&&e.push(this.visit(t.def,s));break;case "AT_DropOf":e.push("NOT OF");break;case "AT_ReplicaIdentity":e.push("REPLICA IDENTITY"),t.def&&e.push(this.visit(t.def,s));break;case "AT_GenericOptions":if(e.push("OPTIONS"),t.def){let i=s.spawn("AlterTableCmd",{alterTableOptions:true}),r=c.unwrapList(t.def).map(n=>this.visit(n,i)).join(", ");e.push(`(${r})`);}break;case "AT_AddIdentity":e.push("ALTER COLUMN"),t.name&&e.push(m.quoteIdentifier(t.name)),e.push("ADD"),t.def&&e.push(this.visit(t.def,s));break;case "AT_SetIdentity":e.push("ALTER COLUMN"),t.name&&e.push(m.quoteIdentifier(t.name)),e.push("SET"),t.def&&e.push(this.visit(t.def,s));break;case "AT_DropIdentity":e.push("ALTER COLUMN"),t.name&&e.push(m.quoteIdentifier(t.name)),e.push("DROP IDENTITY"),t.behavior==="DROP_CASCADE"?e.push("CASCADE"):t.behavior==="DROP_RESTRICT"&&e.push("RESTRICT");break;case "AT_ReAddStatistics":e.push("ADD"),t.def&&e.push(this.visit(t.def,s));break;default:throw new Error(`Unsupported AlterTableCmd subtype: ${t.subtype}`)}return e.join(" ")}CreateFunctionStmt(t,s){let e=["CREATE"];if(t.replace&&e.push("OR REPLACE"),t.is_procedure?e.push("PROCEDURE"):e.push("FUNCTION"),t.funcname&&t.funcname.length>0){let r=t.funcname.map(o=>o.String?.sval||o.String?.str||"").filter(o=>o),n=m.quoteDottedName(r);if(t.parameters&&t.parameters.length>0){let o=t.parameters.filter(u=>this.getNodeData(u).mode!=="FUNC_PARAM_TABLE").map(u=>this.visit(u,s));if(o.length>0)if(s.isPretty()){let u=o.map(l=>s.indent(l)).join(","+s.newline());e.push(n+"("+s.newline()+u+s.newline()+")");}else e.push(n+"("+o.join(", ")+")");else e.push(n+"()");}else e.push(n+"()");}if(t.parameters&&t.parameters.some(r=>this.getNodeData(r).mode==="FUNC_PARAM_TABLE")){let r=t.parameters.filter(n=>this.getNodeData(n).mode==="FUNC_PARAM_TABLE").map(n=>this.visit(n,s));if(s.isPretty()){let n=r.map(o=>s.indent(o)).join(","+s.newline());e.push("RETURNS TABLE ("+s.newline()+n+s.newline()+")");}else e.push("RETURNS TABLE ("),e.push(r.join(", ")),e.push(")");}else t.returnType&&(e.push("RETURNS"),e.push(this.TypeName(t.returnType,s)));if(t.options&&t.options.length>0){let r=s.spawn("CreateFunctionStmt"),n=t.options.map(o=>this.visit(o,r));e.push(...n);}if(t.sql_body){let r=this.getNodeType(t.sql_body);if(r==="ReturnStmt")e.push(this.visit(t.sql_body,s));else {if(e.push("BEGIN ATOMIC"),r==="List"){let n=c.unwrapList(t.sql_body);if(!(n.length===0||n.length===1&&Object.keys(n[0]).length===0)){let o=n;n.length===1&&n[0].List&&(o=c.unwrapList(n[0]));let u=o.filter(l=>l&&Object.keys(l).length>0).map(l=>{let p=this.visit(l,s);return p.endsWith(";")?p:p+";"});u.length>0&&e.push(u.join(" "));}}else {let n=this.visit(t.sql_body,s);n&&!n.endsWith(";")?e.push(n+";"):e.push(n);}e.push("END");}}return e.join(" ")}FunctionParameter(t,s){let e=[];if(t.mode)switch(t.mode){case "FUNC_PARAM_IN":e.push("IN");break;case "FUNC_PARAM_OUT":e.push("OUT");break;case "FUNC_PARAM_INOUT":e.push("INOUT");break;case "FUNC_PARAM_VARIADIC":e.push("VARIADIC");break}return t.name&&e.push(m.quoteIdentifier(t.name)),t.argType&&e.push(this.TypeName(t.argType,s)),t.defexpr&&(e.push("DEFAULT"),e.push(this.visit(t.defexpr,s))),e.join(" ")}CreateEnumStmt(t,s){let e=["CREATE","TYPE"];if(t.typeName){let i=c.unwrapList(t.typeName).map(r=>this.visit(r,s)).join(".");e.push(i);}if(e.push("AS","ENUM"),t.vals&&t.vals.length>0){let i=s.spawn("CreateEnumStmt",{isEnumValue:true}),r=c.unwrapList(t.vals).map(n=>this.visit(n,i)).join(", ");e.push(`(${r})`);}else e.push("()");return e.join(" ")}CreateDomainStmt(t,s){let e=["CREATE","DOMAIN"];if(t.domainname){let i=c.unwrapList(t.domainname).map(r=>this.visit(r,s)).join(".");e.push(i);}if(t.typeName&&(e.push("AS"),e.push(this.TypeName(t.typeName,s))),t.collClause&&e.push(this.CollateClause(t.collClause,s)),t.constraints){let i=c.unwrapList(t.constraints).map(r=>this.visit(r,s)).join(" ");i&&e.push(i);}return e.join(" ")}CreateRoleStmt(t,s){let e=["CREATE"];if(t.stmt_type==="ROLESTMT_ROLE"?e.push("ROLE"):t.stmt_type==="ROLESTMT_USER"?e.push("USER"):t.stmt_type==="ROLESTMT_GROUP"?e.push("GROUP"):e.push("ROLE"),t.role){let i=m.quoteIdentifier(t.role);e.push(i);}if(t.options){let i=c.unwrapList(t.options).map(r=>this.visit(r,s.spawn("CreateRoleStmt"))).join(" ");i&&(e.push("WITH"),e.push(i));}return e.join(" ")}DefElem(t,s){if(!t.defname)return "";if(s.parentNodeTypes.includes("DefineStmt")&&["commutator","negator"].includes(t.defname.toLowerCase())&&t.arg&&this.getNodeType(t.arg)==="List"){let e=this.getNodeData(t.arg),i=c.unwrapList(e.items);if(i.length===1&&i[0].String)return `${this.preserveOperatorDefElemCase(t.defname)} = ${i[0].String.sval}`}if(s.parentNodeTypes.includes("IndexElem")){if(t.arg&&this.getNodeType(t.arg)==="String"){let e=this.getNodeData(t.arg);return `${t.defname}='${e.sval}'`}return `${t.defname}=${this.visit(t.arg,s.spawn("DefElem"))}`}if(s.parentNodeTypes.includes("DefineStmt")&&["hashes","merges"].includes(t.defname.toLowerCase())&&!t.arg)return t.defname!==t.defname.toLowerCase()&&t.defname!==t.defname.toUpperCase()?m.quoteIdentifier(t.defname):t.defname.charAt(0).toUpperCase()+t.defname.slice(1).toLowerCase();if(s.parentNodeTypes.includes("AlterFdwStmt")||s.parentNodeTypes.includes("CreateFdwStmt")||s.parentNodeTypes.includes("CreateForeignServerStmt")||s.parentNodeTypes.includes("AlterForeignServerStmt")||s.parentNodeTypes.includes("CreateUserMappingStmt")||s.parentNodeTypes.includes("AlterUserMappingStmt")||s.parentNodeTypes.includes("ColumnDef")||s.parentNodeTypes.includes("CreateForeignTableStmt")||s.parentNodeTypes.includes("ImportForeignSchemaStmt")||s.alterColumnOptions||s.alterTableOptions){if(["handler","validator"].includes(t.defname)){if(!t.arg)return `NO ${t.defname.toUpperCase()}`;let e=s.spawn("DefElem"),i=this.visit(t.arg,e);return `${t.defname.toUpperCase()} ${i}`}if(t.arg){let e=s.spawn("DefElem"),i=this.visit(t.arg,e);if(s.parentNodeTypes.includes("CreateFdwStmt")||s.parentNodeTypes.includes("AlterFdwStmt")){let o=typeof i=="string"&&!i.startsWith("'")?`'${i}'`:i,u=m.quoteIdentifier(t.defname);return t.defaction==="DEFELEM_ADD"?`ADD ${u} ${o}`:t.defaction==="DEFELEM_DROP"?`DROP ${u}`:t.defaction==="DEFELEM_SET"?`SET ${u} ${o}`:`${u} ${o}`}let r=typeof i=="string"&&!i.startsWith("'")?`'${i}'`:i;return t.defaction==="DEFELEM_ADD"?`ADD ${t.defname} ${r}`:t.defaction==="DEFELEM_DROP"?`DROP ${t.defname}`:t.defaction==="DEFELEM_SET"?`SET ${t.defname} ${r}`:`${m.quoteIdentifier(t.defname)} ${r}`}else if(t.defaction==="DEFELEM_DROP")return `DROP ${t.defname}`}if((s.parentNodeTypes.includes("CreateSeqStmt")||s.parentNodeTypes.includes("AlterSeqStmt"))&&(t.defname==="minvalue"||t.defname==="maxvalue")&&!t.arg)return `NO ${t.defname.toUpperCase()}`;if((s.parentNodeTypes.includes("CreateRoleStmt")||s.parentNodeTypes.includes("AlterRoleStmt"))&&t.defname==="password"){if(!t.arg)return "PASSWORD NULL";let e=s.spawn("DefElem"),i=this.visit(t.arg,e);return `PASSWORD ${typeof i=="string"&&!i.startsWith("'")?`'${i}'`:i}`}if(t.arg){let e=s.spawn("DefElem"),i=this.visit(t.arg,e);if(s.parentNodeTypes.includes("AlterOperatorStmt")){if(t.arg&&this.getNodeType(t.arg)==="TypeName"){let n=this.getNodeData(t.arg);if(n.names){let o=c.unwrapList(n.names);if(o.length===1&&o[0].String)return `${t.defname} = ${o[0].String.sval}`}}if(t.arg&&this.getNodeType(t.arg)==="List"){let n=this.getNodeData(t.arg),o=c.unwrapList(n.items);if(o.length===1&&o[0].String)return `${t.defname} = ${o[0].String.sval}`}}if(s.parentNodeTypes.includes("CreatedbStmt")||s.parentNodeTypes.includes("DropdbStmt")){let n=typeof i=="string"?m.escape(i):i;return `${t.defname} = ${n}`}if(s.parentNodeTypes.includes("CreateForeignServerStmt")||s.parentNodeTypes.includes("AlterForeignServerStmt")){let n=typeof i=="string"?m.escape(i):i;return `${m.quoteIdentifier(t.defname)} ${n}`}if(s.parentNodeTypes.includes("CreateRoleStmt")||s.parentNodeTypes.includes("AlterRoleStmt")){if(t.defname==="rolemembers"&&t.arg&&this.getNodeType(t.arg)==="List"){let n=this.getNodeData(t.arg),u=c.unwrapList(n.items).map(l=>this.visit(l,s));return s.parentNodeTypes.includes("CreateRoleStmt")?`ROLE ${u.join(", ")}`:`ADD USER ${u.join(", ")}`}if(t.defname==="addroleto"&&t.arg&&this.getNodeType(t.arg)==="List"){let n=this.getNodeData(t.arg);return `IN ROLE ${c.unwrapList(n.items).map(l=>this.visit(l,s)).join(", ")}`}if(t.defname==="validUntil")return `VALID UNTIL ${typeof i=="string"&&!i.startsWith("'")?`'${i}'`:i}`;if(t.defname==="adminmembers")return `ADMIN ${i}`;if(t.defname==="connectionlimit")return `CONNECTION LIMIT ${i}`;if(t.defname==="sysid")return `SYSID ${i}`;if(String(i)==="true")return t.defname==="isreplication"?"REPLICATION":t.defname==="canlogin"?"LOGIN":t.defname.toUpperCase();if(String(i)==="false")return t.defname==="canlogin"?"NOLOGIN":t.defname==="isreplication"?"NOREPLICATION":`NO${t.defname.toUpperCase()}`}if(s.parentNodeTypes.includes("CreateSeqStmt")||s.parentNodeTypes.includes("AlterSeqStmt")){if(t.defname==="owned_by")if(t.arg&&this.getNodeType(t.arg)==="List"){let n=this.getNodeData(t.arg);return `OWNED BY ${c.unwrapList(n.items).map(l=>{let p=this.getNodeData(l);if(this.getNodeType(l)==="String"){let f=p.sval;return m.quoteIdentifier(f)}return this.visit(l,s)}).join(".")}`}else return `OWNED BY ${i}`;if(t.defname==="cycle"){let n=String(i).toLowerCase();if(n==="true"||n==="1")return "CYCLE";if(n==="false"||n==="0")return "NO CYCLE"}return (t.defname==="minvalue"||t.defname==="maxvalue")&&!t.arg?`NO ${t.defname.toUpperCase()}`:`${t.defname.toUpperCase()} ${i}`}if(s.parentNodeTypes.includes("CreateTableSpaceStmt")||s.parentNodeTypes.includes("AlterTableSpaceOptionsStmt"))return `${t.defname.toUpperCase()} ${i}`;if(s.parentNodeTypes.includes("ExplainStmt"))return i?`${t.defname.toUpperCase()} ${i.toUpperCase()}`:t.defname.toUpperCase();if(s.parentNodeTypes.includes("DoStmt")){if(t.defname==="as"){let n=s.spawn("DefElem"),o=t.arg?this.visit(t.arg,n):"";if(Array.isArray(o)){let l=o.join(""),p=this.getFunctionDelimiter(l);return `${p}${l}${p}`}else {let u=this.getFunctionDelimiter(o);return `${u}${o}${u}`}}return ""}if(s.parentNodeTypes.includes("CreateFunctionStmt")||s.parentNodeTypes.includes("AlterFunctionStmt")){if(t.defname==="as")if(t.arg&&t.arg.List){let u=(t.arg.List.items||[]).map(l=>l.String?l.String.sval:this.visit(l,s));if(u.length===1){let l=u[0],p=this.getFunctionDelimiter(l);return `AS ${p}${l}${p}`}else return `AS ${u.map(l=>{let p=this.getFunctionDelimiter(l);return `${p}${l}${p}`}).join(", ")}`}else if(Array.isArray(i)){let n=i;if(n.length===1){let o=n[0],u=this.getFunctionDelimiter(o);return `AS ${u}${o}${u}`}else return `AS ${n.map(o=>{let u=this.getFunctionDelimiter(o);return `${u}${o}${u}`}).join(", ")}`}else {let n=this.getFunctionDelimiter(i);return `AS ${n}${i}${n}`}return t.defname==="language"?`LANGUAGE ${i}`:t.defname==="volatility"?i.toUpperCase():t.defname==="strict"?i==="true"?"STRICT":"CALLED ON NULL INPUT":t.defname==="security"?i==="true"?"SECURITY DEFINER":"SECURITY INVOKER":t.defname==="leakproof"?i==="true"?"LEAKPROOF":"NOT LEAKPROOF":t.defname==="cost"?`COST ${i}`:t.defname==="rows"?`ROWS ${i}`:t.defname==="window"?i==="true"?"WINDOW":"":t.defname==="set"?this.visit(t.arg,s):`${t.defname.toUpperCase()} ${i}`}if(s.parentNodeTypes.includes("CreateExtensionStmt")||s.parentNodeTypes.includes("AlterExtensionStmt")||s.parentNodeTypes.includes("CreateFdwStmt")||s.parentNodeTypes.includes("AlterFdwStmt")){if(s.parentNodeTypes.includes("AlterExtensionStmt")){if(t.defname==="new_version")return `UPDATE TO ${typeof i=="string"&&!i.startsWith("'")?`'${i}'`:i}`;if(t.defname==="schema")return `SET SCHEMA ${i}`}if(s.parentNodeTypes.includes("CreateFdwStmt")){if(["handler","validator"].includes(t.defname))return `${t.defname.toUpperCase()} ${i}`;let n=typeof i=="string"?m.escape(i):i;return `${t.defname} ${n}`}return t.defname==="cascade"?i==="true"?"CASCADE":"":`${t.defname.toUpperCase()} ${i}`}if(s.parentNodeTypes.includes("IndexStmt"))return `${t.defname}=${i}`;if(s.parentNodeTypes.includes("IndexElem")){if(t.arg&&this.getNodeType(t.arg)==="String"){let n=this.getNodeData(t.arg);return `${t.defname}='${n.sval}'`}return `${t.defname}=${i}`}if(s.parentNodeTypes.includes("CreateStmt")){if(t.arg&&this.getNodeType(t.arg)==="Integer"){let n=this.getNodeData(t.arg);return `${t.defname}=${n.ival}`}return `${t.defname}=${i}`}if(s.parentNodeTypes.includes("CreateEventTrigStmt")){if(t.arg&&this.getNodeType(t.arg)==="List"){let n=this.getNodeData(t.arg),u=c.unwrapList(n.items).map(l=>this.getNodeType(l)==="String"?`'${this.getNodeData(l).sval||""}'`:this.visit(l,s));return `${t.defname} IN (${u.join(", ")})`}return `${t.defname} = ${i}`}if((s.parentNodeTypes.includes("AlterTableCmd")||s.parentNodeTypes.includes("AlterTableStmt"))&&!s.parentNodeTypes.includes("ColumnDef")){let n=t.defnamespace?`${t.defnamespace}.${t.defname}`:t.defname;return t.arg&&this.getNodeType(t.arg)==="TypeName"?`${n} = ${i}`:`${n} = ${i}`}if(s.parentNodeTypes.includes("ViewStmt")){if(typeof i=="string"&&/^\d+$/.test(i))return `${t.defname}=${i}`;let n=typeof i=="string"?m.escape(i):i;return `${t.defname} = ${n}`}if(s.parentNodeTypes.includes("CopyStmt"))return t.defname==="format"&&t.arg&&this.getNodeType(t.arg)==="String"?`FORMAT ${this.getNodeData(t.arg).sval.toUpperCase()}`:t.arg?`${t.defname.toUpperCase()} ${i}`:t.defname.toUpperCase();if(s.parentNodeTypes.includes("DefineStmt")){let n=this.preserveOperatorDefElemCase(t.defname);if(["commutator","negator"].includes(t.defname.toLowerCase())){if(t.arg){if(t.arg&&this.getNodeType(t.arg)==="List"){let l=this.getNodeData(t.arg),p=c.unwrapList(l.items);if(p.length===1&&p[0].String)return `${n} = ${p[0].String.sval}`}let u=i.replace(/^"(.*)"$/,"$1");return `${n} = ${u}`}return n}if(["hashes","merges"].includes(t.defname.toLowerCase()))return t.defname!==t.defname.toLowerCase()&&t.defname!==t.defname.toUpperCase()?m.quoteIdentifier(t.defname):n.toUpperCase();let o=m.quoteIdentifier(t.defname);if(o!==t.defname){if(t.arg){if(this.getNodeType(t.arg)==="String"){let u=this.getNodeData(t.arg);return u.sval==="true"||u.sval==="false"?`${o} = ${u.sval}`:`${o} = '${u.sval}'`}return `${o} = ${i}`}return o}if(n!==t.defname)return t.arg?`${n} = ${i}`:n;if(t.arg&&this.getNodeType(t.arg)==="String"){let u=this.getNodeData(t.arg);return u.sval==="true"||u.sval==="false"?`${t.defname} = ${u.sval}`:`${t.defname} = '${u.sval}'`}if(t.arg&&this.getNodeType(t.arg)==="Boolean"){let u=this.getNodeData(t.arg);return `${t.defname} = ${u.boolval?"true":"false"}`}if(t.arg&&this.getNodeType(t.arg)==="Integer"){let u=this.getNodeData(t.arg);return `${t.defname} = ${u.ival}`}if(t.arg&&this.getNodeType(t.arg)==="TypeName"){let u=this.getNodeData(t.arg);if(u.names){let l=c.unwrapList(u.names);if(l.length===1&&l[0].String)return `${t.defname} = ${l[0].String.sval}`}return `${t.defname} = ${i}`}}let r=typeof i=="string"?m.escape(i):i;return `${t.defname} = ${r}`}return s.parentNodeTypes.includes("DefineStmt")&&!t.arg&&t.defname!==t.defname.toLowerCase()&&t.defname!==t.defname.toUpperCase()?m.quoteIdentifier(t.defname):t.defname.toUpperCase()}CreateTableSpaceStmt(t,s){let e=["CREATE","TABLESPACE"];if(t.tablespacename&&e.push(t.tablespacename),t.owner&&(e.push("OWNER"),e.push(this.RoleSpec(t.owner,s))),t.location&&(e.push("LOCATION"),e.push(`'${t.location}'`)),t.options&&t.options.length>0){e.push("WITH");let i=s.spawn("CreateTableSpaceStmt"),r=c.unwrapList(t.options).map(n=>this.visit(n,i)).join(", ");e.push(`(${r})`);}return e.join(" ")}DropTableSpaceStmt(t,s){let e=["DROP","TABLESPACE"];return t.missing_ok&&e.push("IF","EXISTS"),t.tablespacename&&e.push(t.tablespacename),e.join(" ")}AlterTableSpaceOptionsStmt(t,s){let e=["ALTER","TABLESPACE"];if(t.tablespacename&&e.push(t.tablespacename),t.isReset?e.push("RESET"):e.push("SET"),t.options&&t.options.length>0){let i=s.spawn("AlterTableSpaceOptionsStmt"),r=c.unwrapList(t.options).map(n=>this.visit(n,i)).join(", ");e.push(`(${r})`);}return e.join(" ")}CreateExtensionStmt(t,s){let e=["CREATE","EXTENSION"];if(t.if_not_exists&&e.push("IF","NOT","EXISTS"),t.extname&&e.push(this.quoteIfNeeded(t.extname)),t.options&&t.options.length>0){let i=s.spawn("CreateExtensionStmt"),r=c.unwrapList(t.options).map(n=>this.visit(n,i)).join(" ");e.push(r);}return e.join(" ")}AlterExtensionStmt(t,s){let e=["ALTER","EXTENSION"];if(t.extname&&e.push(this.quoteIfNeeded(t.extname)),t.options&&t.options.length>0){let i=s.spawn("AlterExtensionStmt"),r=c.unwrapList(t.options).map(n=>this.visit(n,i)).join(" ");e.push(r);}return e.join(" ")}AlterExtensionContentsStmt(t,s){let e=["ALTER","EXTENSION"];if(t.extname&&e.push(this.quoteIfNeeded(t.extname)),t.action===1?e.push("ADD"):t.action===-1&&e.push("DROP"),t.objtype)try{e.push(this.getObjectTypeKeyword(t.objtype));}catch{e.push(t.objtype.toString());}return t.object&&e.push(this.visit(t.object,s)),e.join(" ")}CreateFdwStmt(t,s){let e=["CREATE","FOREIGN","DATA","WRAPPER"];if(t.fdwname&&e.push(t.fdwname),t.func_options&&t.func_options.length>0){let i=s.spawn("CreateFdwStmt"),r=c.unwrapList(t.func_options).map(n=>this.visit(n,i)).join(" ");e.push(r);}if(t.options&&t.options.length>0){e.push("OPTIONS");let i=s.spawn("CreateFdwStmt"),r=c.unwrapList(t.options).map(n=>this.visit(n,i)).join(", ");e.push(`(${r})`);}return e.join(" ")}SetOperationStmt(t,s){let e=[];if(t.larg&&e.push(this.visit(t.larg,s)),t.op)switch(t.op){case "SETOP_UNION":e.push(t.all?"UNION ALL":"UNION");break;case "SETOP_INTERSECT":e.push(t.all?"INTERSECT ALL":"INTERSECT");break;case "SETOP_EXCEPT":e.push(t.all?"EXCEPT ALL":"EXCEPT");break;default:throw new Error(`Unsupported SetOperation: ${t.op}`)}return t.rarg&&e.push(this.visit(t.rarg,s)),e.join(" ")}ReplicaIdentityStmt(t,s){let e=[];if(t.identity_type)switch(t.identity_type){case "d":case "REPLICA_IDENTITY_DEFAULT":e.push("DEFAULT");break;case "f":case "REPLICA_IDENTITY_FULL":e.push("FULL");break;case "n":case "REPLICA_IDENTITY_NOTHING":e.push("NOTHING");break;case "i":case "REPLICA_IDENTITY_INDEX":e.push("USING","INDEX"),t.name&&e.push(m.quoteIdentifier(t.name));break;default:throw new Error(`Unsupported replica identity type: ${t.identity_type}`)}return e.join(" ")}AlterCollationStmt(t,s){let e=["ALTER","COLLATION"];if(t.collname&&t.collname.length>0){let i=c.unwrapList(t.collname).map(r=>this.visit(r,s)).join(".");e.push(i);}return e.push("REFRESH","VERSION"),e.join(" ")}AlterDomainStmt(t,s){let e=["ALTER","DOMAIN"];if(t.typeName&&t.typeName.length>0){let i=c.unwrapList(t.typeName).map(r=>this.visit(r,s)).join(".");e.push(i);}if(t.subtype)switch(t.subtype){case "AT_SetNotNull":e.push("SET","NOT","NULL");break;case "AT_DropNotNull":e.push("DROP","NOT","NULL");break;case "AT_SetDefault":e.push("SET","DEFAULT"),t.def&&e.push(this.visit(t.def,s));break;case "AT_DropDefault":e.push("DROP","DEFAULT");break;case "AT_AddConstraint":if(e.push("ADD"),t.def){let i=s.spawn("CreateDomainStmt",{isDomainConstraint:true});e.push(this.visit(t.def,i));}break;case "AT_DropConstraint":e.push("DROP","CONSTRAINT"),t.missing_ok&&e.push("IF","EXISTS"),t.name&&e.push(m.quoteIdentifier(t.name)),t.behavior==="DROP_CASCADE"&&e.push("CASCADE");break;case "AT_ValidateConstraint":e.push("VALIDATE","CONSTRAINT"),t.name&&e.push(m.quoteIdentifier(t.name));break;case "C":if(e.push("ADD"),t.def){let i=s.spawn("CreateDomainStmt",{isDomainConstraint:true});e.push(this.visit(t.def,i));}break;case "X":e.push("DROP","CONSTRAINT"),t.missing_ok&&e.push("IF","EXISTS"),t.name&&e.push(m.quoteIdentifier(t.name)),t.behavior==="DROP_CASCADE"&&e.push("CASCADE");break;case "V":e.push("VALIDATE","CONSTRAINT"),t.name&&e.push(m.quoteIdentifier(t.name));break;case "O":e.push("SET","NOT","NULL");break;case "N":e.push("DROP","NOT","NULL");break;case "T":t.def?(e.push("SET","DEFAULT"),e.push(this.visit(t.def,s))):e.push("DROP","DEFAULT");break;default:throw new Error(`Unsupported AlterDomainStmt subtype: ${t.subtype}`)}return e.join(" ")}PrepareStmt(t,s){let e=["PREPARE"];if(t.name&&e.push(t.name),t.argtypes&&t.argtypes.length>0){let i=c.unwrapList(t.argtypes).map(r=>this.visit(r,s)).join(", ");e.push(`(${i})`);}return e.push("AS"),t.query&&e.push(this.visit(t.query,s)),e.join(" ")}ExecuteStmt(t,s){let e=["EXECUTE"];if(t.name&&e.push(t.name),t.params&&t.params.length>0){let i=c.unwrapList(t.params).map(r=>this.visit(r,s)).join(", ");e.push(`(${i})`);}return e.join(" ")}DeallocateStmt(t,s){let e=["DEALLOCATE"];return t.isall?e.push("ALL"):t.name&&e.push(t.name),e.join(" ")}NotifyStmt(t,s){let e=["NOTIFY"];return t.conditionname&&e.push(t.conditionname),t.payload!==null&&t.payload!==void 0&&(e.push(","),e.push(`'${t.payload}'`)),e.join(" ")}ListenStmt(t,s){let e=["LISTEN"];return t.conditionname&&e.push(t.conditionname),e.join(" ")}UnlistenStmt(t,s){let e=["UNLISTEN"];return t.conditionname?e.push(t.conditionname):e.push("*"),e.join(" ")}CheckPointStmt(t,s){return "CHECKPOINT"}LoadStmt(t,s){if(!t.filename)throw new Error("LoadStmt requires filename");return `LOAD '${t.filename}'`}DiscardStmt(t,s){switch(t.target){case "DISCARD_ALL":return "DISCARD ALL";case "DISCARD_PLANS":return "DISCARD PLANS";case "DISCARD_SEQUENCES":return "DISCARD SEQUENCES";case "DISCARD_TEMP":return "DISCARD TEMP";default:throw new Error(`Unsupported DiscardStmt target: ${t.target}`)}}CommentStmt(t,s){let e=["COMMENT ON"];if(t.objtype)switch(t.objtype){case "OBJECT_TABLE":e.push("TABLE");break;case "OBJECT_COLUMN":e.push("COLUMN");break;case "OBJECT_INDEX":e.push("INDEX");break;case "OBJECT_FUNCTION":e.push("FUNCTION");break;case "OBJECT_VIEW":e.push("VIEW");break;case "OBJECT_SCHEMA":e.push("SCHEMA");break;case "OBJECT_DATABASE":e.push("DATABASE");break;case "OBJECT_MATVIEW":e.push("MATERIALIZED VIEW");break;case "OBJECT_TABCONSTRAINT":e.push("CONSTRAINT");break;case "OBJECT_TRIGGER":e.push("TRIGGER");break;case "OBJECT_FDW":e.push("FOREIGN DATA WRAPPER");break;case "OBJECT_EVENT_TRIGGER":e.push("EVENT TRIGGER");break;case "OBJECT_FOREIGN_SERVER":e.push("SERVER");break;case "OBJECT_FOREIGN_TABLE":e.push("FOREIGN TABLE");break;case "OBJECT_STATISTIC_EXT":e.push("STATISTICS");break;case "OBJECT_LARGEOBJECT":e.push("LARGE OBJECT");break;case "OBJECT_OPERATOR":e.push("OPERATOR");break;case "OBJECT_OPCLASS":e.push("OPERATOR CLASS");break;case "OBJECT_OPFAMILY":e.push("OPERATOR FAMILY");break;case "OBJECT_POLICY":e.push("POLICY");break;case "OBJECT_TSPARSER":e.push("TEXT SEARCH PARSER");break;case "OBJECT_TSDICTIONARY":e.push("TEXT SEARCH DICTIONARY");break;case "OBJECT_TSTEMPLATE":e.push("TEXT SEARCH TEMPLATE");break;case "OBJECT_TSCONFIGURATION":e.push("TEXT SEARCH CONFIGURATION");break;case "OBJECT_TRANSFORM":e.push("TRANSFORM");break;default:e.push(t.objtype.replace("OBJECT_",""));}if(t.object)if(t.object&&typeof t.object=="object"&&"List"in t.object){let i=t.object.List;if(i.items&&i.items.length>0){let r=c.unwrapList(i.items).map(n=>this.visit(n,s));if(t.objtype==="OBJECT_TABCONSTRAINT")if(r.length===3){let[n,o,u]=r;e.push(u),e.push("ON"),e.push(`${n}.${o}`);}else if(r.length===2){let[n,o]=r;e.push(o),e.push("ON"),e.push(n);}else e.push(r.join("."));else if(t.objtype==="OBJECT_TRIGGER")if(r.length===2){let[n,o]=r;e.push(o),e.push("ON"),e.push(n);}else e.push(r.join("."));else if(t.objtype==="OBJECT_RULE")if(r.length===2){let[n,o]=r;e.push(o),e.push("ON"),e.push(n);}else e.push(r.join("."));else if(t.objtype==="OBJECT_OPERATOR")if(t.object&&t.object.ObjectWithArgs){let n=t.object.ObjectWithArgs,o=n.objname&&n.objname[0]&&n.objname[0].String?n.objname[0].String.sval:"unknown";o.startsWith('"')&&o.endsWith('"')&&(o=o.slice(1,-1));let u=[];n.objargs&&n.objargs.forEach(l=>{if(!l||Object.keys(l).length===0)u.push("NONE");else if(l.TypeName){let p=this.visit(l,s);u.push(p);}else u.push("unknown");}),e.push(`${o} (${u.join(", ")})`);}else e.push(r.join("."));else if(t.objtype==="OBJECT_OPCLASS"||t.objtype==="OBJECT_OPFAMILY")if(r.length>=2){let n=r[r.length-1],o=r[r.length-2];e.push(`${n} USING ${o}`);}else e.push(r.join(" USING "));else if(t.objtype==="OBJECT_POLICY")if(r.length===2){let[n,o]=r;e.push(o),e.push("ON"),e.push(n);}else e.push(r.join("."));else if(t.objtype==="OBJECT_TRANSFORM")if(r.length===2){let[n,o]=r;e.push("FOR"),e.push(n),e.push("LANGUAGE"),e.push(o);}else e.push(r.join("."));else e.push(r.join("."));}}else if(t.objtype==="OBJECT_OPERATOR"&&t.object&&t.object.ObjectWithArgs){let i=t.object.ObjectWithArgs,r=i.objname&&i.objname[0]&&i.objname[0].String?i.objname[0].String.sval:"unknown";r.startsWith('"')&&r.endsWith('"')&&(r=r.slice(1,-1));let n=[];i.objargs&&i.objargs.forEach(o=>{if(!o||Object.keys(o).length===0)n.push("NONE");else if(o.TypeName){let u=this.visit(o,s);n.push(u);}else n.push("unknown");}),e.push(`${r}(${n.join(", ")})`);}else {let i=s.spawn("CommentStmt",{objtype:t.objtype});e.push(this.visit(t.object,i));}return e.push("IS"),t.comment===null||t.comment===void 0?e.push("NULL"):t.comment&&e.push(m.formatEString(t.comment)),e.join(" ")}LockStmt(t,s){let e=["LOCK","TABLE"];if(t.relations&&t.relations.length>0){let i=c.unwrapList(t.relations).map(r=>this.visit(r,s)).join(", ");e.push(i);}if(t.mode!==void 0){let i=["","ACCESS SHARE","ROW SHARE","ROW EXCLUSIVE","SHARE UPDATE EXCLUSIVE","SHARE","SHARE ROW EXCLUSIVE","EXCLUSIVE","ACCESS EXCLUSIVE"];t.mode>=1&&t.mode<i.length&&e.push("IN",i[t.mode],"MODE");}return t.nowait&&e.push("NOWAIT"),e.join(" ")}CreatePolicyStmt(t,s){let e=[],i=["CREATE","POLICY"];if(t.policy_name&&i.push(m.quoteIdentifier(t.policy_name)),e.push(i.join(" ")),t.table&&(s.isPretty()?e.push(s.newline()+s.indent(`ON ${this.RangeVar(t.table,s)}`)):(e.push("ON"),e.push(this.RangeVar(t.table,s)))),t.permissive===void 0?s.isPretty()?e.push(s.newline()+s.indent("AS RESTRICTIVE")):e.push("AS","RESTRICTIVE"):t.permissive===true&&(s.isPretty()?e.push(s.newline()+s.indent("AS PERMISSIVE")):e.push("AS","PERMISSIVE")),t.cmd_name&&(s.isPretty()?e.push(s.newline()+s.indent(`FOR ${t.cmd_name.toUpperCase()}`)):e.push("FOR",t.cmd_name.toUpperCase())),t.roles&&t.roles.length>0){let r=c.unwrapList(t.roles).map(n=>this.visit(n,s));s.isPretty()?e.push(s.newline()+s.indent(`TO ${r.join(", ")}`)):(e.push("TO"),e.push(r.join(", ")));}if(t.qual)if(s.isPretty()){let r=this.visit(t.qual,s);e.push(s.newline()+s.indent("USING (")),e.push(s.newline()+s.indent(s.indent(r))),e.push(s.newline()+s.indent(")"));}else e.push("USING"),e.push(`(${this.visit(t.qual,s)})`);if(t.with_check)if(s.isPretty()){let r=this.visit(t.with_check,s);e.push(s.newline()+s.indent("WITH CHECK (")),e.push(s.newline()+s.indent(s.indent(r))),e.push(s.newline()+s.indent(")"));}else e.push("WITH CHECK"),e.push(`(${this.visit(t.with_check,s)})`);return s.isPretty()?e.join(""):e.join(" ")}AlterPolicyStmt(t,s){let e=["ALTER","POLICY"];if(t.policy_name&&e.push(m.quoteIdentifier(t.policy_name)),t.table&&(e.push("ON"),e.push(this.RangeVar(t.table,s))),t.roles&&t.roles.length>0){e.push("TO");let i=c.unwrapList(t.roles).map(r=>this.visit(r,s));e.push(i.join(", "));}return t.qual&&(e.push("USING"),e.push(`(${this.visit(t.qual,s)})`)),t.with_check&&(e.push("WITH CHECK"),e.push(`(${this.visit(t.with_check,s)})`)),e.join(" ")}CreateUserMappingStmt(t,s){let e=["CREATE"];if(t.if_not_exists&&e.push("IF","NOT","EXISTS"),e.push("USER","MAPPING"),e.push("FOR"),t.user?e.push(this.RoleSpec(t.user,s)):e.push("CURRENT_USER"),e.push("SERVER"),t.servername&&e.push(m.quoteIdentifier(t.servername)),t.options&&t.options.length>0){e.push("OPTIONS");let i=s.spawn("CreateUserMappingStmt"),r=c.unwrapList(t.options).map(n=>this.visit(n,i));e.push(`(${r.join(", ")})`);}return e.join(" ")}CreateStatsStmt(t,s){let e=["CREATE"];if(t.if_not_exists&&e.push("IF","NOT","EXISTS"),e.push("STATISTICS"),t.defnames&&t.defnames.length>0){let i=c.unwrapList(t.defnames).map(r=>this.visit(r,s));e.push(i.join("."));}if(t.stat_types&&t.stat_types.length>0){let i=c.unwrapList(t.stat_types).map(r=>this.visit(r,s));e.push(`(${i.join(", ")})`);}if(e.push("ON"),t.exprs&&t.exprs.length>0){let i=c.unwrapList(t.exprs).map(r=>this.visit(r,s));e.push(i.join(", "));}if(t.relations&&t.relations.length>0){e.push("FROM");let i=c.unwrapList(t.relations).map(r=>this.visit(r,s));e.push(i.join(", "));}return e.join(" ")}StatsElem(t,s){return t.name?this.quoteIfNeeded(t.name):t.expr?`(${this.visit(t.expr,s)})`:""}CreatePublicationStmt(t,s){let e=["CREATE","PUBLICATION"];if(t.pubname&&e.push(m.quoteIdentifier(t.pubname)),t.pubobjects&&t.pubobjects.length>0){e.push("FOR","TABLE");let i=c.unwrapList(t.pubobjects).map(r=>this.visit(r,s));e.push(i.join(", "));}else t.for_all_tables&&e.push("FOR","ALL","TABLES");if(t.options&&t.options.length>0){e.push("WITH");let i=c.unwrapList(t.options).map(r=>this.visit(r,s));e.push(`(${i.join(", ")})`);}return e.join(" ")}CreateSubscriptionStmt(t,s){let e=["CREATE","SUBSCRIPTION"];if(t.subname&&e.push(m.quoteIdentifier(t.subname)),e.push("CONNECTION"),t.conninfo&&e.push(`'${t.conninfo}'`),e.push("PUBLICATION"),t.publication&&t.publication.length>0){let i=c.unwrapList(t.publication).map(r=>this.visit(r,s));e.push(i.join(", "));}if(t.options&&t.options.length>0){e.push("WITH");let i=c.unwrapList(t.options).map(r=>this.visit(r,s));e.push(`(${i.join(", ")})`);}return e.join(" ")}AlterPublicationStmt(t,s){let e=["ALTER","PUBLICATION"];if(t.pubname&&e.push(m.quoteIdentifier(t.pubname)),t.action)switch(t.action){case "AP_AddObjects":e.push("ADD");break;case "AP_DropObjects":e.push("DROP");break;case "AP_SetObjects":e.push("SET");break;default:throw new Error(`Unsupported AlterPublicationStmt action: ${t.action}`)}if(t.for_all_tables)e.push("FOR ALL TABLES");else if(t.pubobjects&&t.pubobjects.length>0){e.push("FOR TABLE");let i=c.unwrapList(t.pubobjects).map(r=>this.visit(r,s));e.push(i.join(", "));}if(t.options&&t.options.length>0){e.push("WITH");let i=c.unwrapList(t.options).map(r=>this.visit(r,s));e.push(`(${i.join(", ")})`);}return e.join(" ")}AlterSubscriptionStmt(t,s){let e=["ALTER","SUBSCRIPTION"];if(t.subname&&e.push(m.quoteIdentifier(t.subname)),t.kind)switch(t.kind){case "ALTER_SUBSCRIPTION_OPTIONS":e.push("SET");break;case "ALTER_SUBSCRIPTION_CONNECTION":e.push("CONNECTION"),t.conninfo&&e.push(`'${t.conninfo}'`);break;case "ALTER_SUBSCRIPTION_SET_PUBLICATION":if(e.push("SET PUBLICATION"),t.publication&&t.publication.length>0){let i=c.unwrapList(t.publication).map(r=>this.visit(r,s));e.push(i.join(", "));}break;case "ALTER_SUBSCRIPTION_REFRESH":e.push("REFRESH PUBLICATION");break;case "ALTER_SUBSCRIPTION_ENABLED":e.push("ENABLE");break;case "ALTER_SUBSCRIPTION_SKIP":e.push("SKIP");break;default:throw new Error(`Unsupported AlterSubscriptionStmt kind: ${t.kind}`)}if(t.options&&t.options.length>0){e.push("WITH");let i=c.unwrapList(t.options).map(r=>this.visit(r,s));e.push(`(${i.join(", ")})`);}return e.join(" ")}DropSubscriptionStmt(t,s){let e=["DROP","SUBSCRIPTION"];if(t.missing_ok&&e.push("IF EXISTS"),t.subname&&e.push(m.quoteIdentifier(t.subname)),t.behavior)switch(t.behavior){case "DROP_CASCADE":e.push("CASCADE");break;case "DROP_RESTRICT":e.push("RESTRICT");break}return e.join(" ")}DoStmt(t,s){let e=["DO"];if(t.args&&t.args.length>0){let i=s.spawn("DoStmt"),r=c.unwrapList(t.args),n=[];for(let o of r)if(this.getNodeType(o)==="DefElem"){let l=this.getNodeData(o);if(l.defname==="language"){let p=this.visit(l.arg,i);n.push(`LANGUAGE ${p}`);}else if(l.defname==="as")if(this.getNodeType(l.arg)==="String"){let f=this.getNodeData(l.arg),h=this.getFunctionDelimiter(f.sval);n.push(`${h}${f.sval}${h}`);}else n.push(this.visit(l.arg,i));}e.push(...n);}return e.join(" ")}generateUniqueDollarTag(t){let s=/\$[a-zA-Z0-9_]*\$/g,e=t.match(s)||[];if(e.length===0)return "$$";let i=new Set(e);if(i.has("$$")){let r=1,n=`$do${r}$`;for(;i.has(n);)r++,n=`$do${r}$`;return n}return "$$"}InlineCodeBlock(t,s){if(t.source_text){let i=this.getFunctionDelimiter(t.source_text);return `${i}${t.source_text}${i}`}let e=this.options.functionDelimiter||"$$";return `${e}${e}`}CallContext(t,s){return t.atomic!==void 0?t.atomic?"ATOMIC":"NOT ATOMIC":""}ConstraintsSetStmt(t,s){let e=["SET","CONSTRAINTS"];if(t.constraints&&t.constraints.length>0){let i=c.unwrapList(t.constraints).map(r=>this.visit(r,s));e.push(i.join(", "));}else e.push("ALL");return e.push(t.deferred?"DEFERRED":"IMMEDIATE"),e.join(" ")}AlterSystemStmt(t,s){let e=["ALTER","SYSTEM"];if(t.setstmt){let r=this.VariableSetStmt(t.setstmt,s).replace(/^SET\s+/,"");e.push("SET",r);}return e.join(" ")}VacuumRelation(t,s){let e=[];if(t.relation&&e.push(this.RangeVar(t.relation,s)),t.va_cols&&t.va_cols.length>0){e.push("(");let i=c.unwrapList(t.va_cols).map(r=>this.visit(r,s));e.push(i.join(", ")),e.push(")");}return e.join(" ")}DropOwnedStmt(t,s){let e=["DROP","OWNED","BY"];if(t.roles&&t.roles.length>0){let i=c.unwrapList(t.roles).map(r=>this.visit(r,s));e.push(i.join(", "));}if(t.behavior)switch(t.behavior){case "DROP_CASCADE":e.push("CASCADE");break;case "DROP_RESTRICT":e.push("RESTRICT");break}return e.join(" ")}ReassignOwnedStmt(t,s){let e=["REASSIGN","OWNED","BY"];if(t.roles&&t.roles.length>0){let i=c.unwrapList(t.roles).map(r=>this.visit(r,s));e.push(i.join(", "));}return e.push("TO"),t.newrole&&e.push(this.RoleSpec(t.newrole,s)),e.join(" ")}AlterTSDictionaryStmt(t,s){let e=["ALTER","TEXT","SEARCH","DICTIONARY"];if(t.dictname&&t.dictname.length>0){let i=c.unwrapList(t.dictname).map(r=>this.visit(r,s));e.push(i.join("."));}if(t.options&&t.options.length>0){e.push("(");let i=c.unwrapList(t.options).map(r=>this.visit(r,s));e.push(i.join(", ")),e.push(")");}return e.join(" ")}AlterTSConfigurationStmt(t,s){let e=["ALTER","TEXT","SEARCH","CONFIGURATION"];if(t.cfgname&&t.cfgname.length>0){let i=c.unwrapList(t.cfgname).map(r=>this.visit(r,s));e.push(i.join("."));}if(t.kind)switch(t.kind){case "ALTER_TSCONFIG_ADD_MAPPING":if(e.push("ADD","MAPPING","FOR"),t.tokentype&&t.tokentype.length>0){let i=c.unwrapList(t.tokentype).map(r=>this.visit(r,s));e.push(i.join(", "));}if(t.dicts&&t.dicts.length>0){e.push("WITH");let i=c.unwrapList(t.dicts).map(r=>r.List&&r.List.items?c.unwrapList(r.List.items).map(n=>this.visit(n,s)).join("."):this.visit(r,s));e.push(i.join(", "));}break;case "ALTER_TSCONFIG_ALTER_MAPPING_FOR_TOKEN":if(e.push("ALTER","MAPPING","FOR"),t.tokentype&&t.tokentype.length>0){let i=c.unwrapList(t.tokentype).map(r=>this.visit(r,s));e.push(i.join(", "));}if(t.dicts&&t.dicts.length>0){e.push("WITH");let i=c.unwrapList(t.dicts).map(r=>r.List&&r.List.items?c.unwrapList(r.List.items).map(n=>this.visit(n,s)).join("."):this.visit(r,s));e.push(i.join(", "));}break;case "ALTER_TSCONFIG_REPLACE_DICT":if(e.push("ALTER","MAPPING","REPLACE"),t.dicts&&t.dicts.length>=2){let i=c.unwrapList(t.dicts).map(r=>r.List&&r.List.items?c.unwrapList(r.List.items).map(n=>this.visit(n,s)).join("."):this.visit(r,s));e.push(i[0],"WITH",i.slice(1).join(", "));}break;case "ALTER_TSCONFIG_REPLACE_DICT_FOR_TOKEN":if(e.push("ALTER","MAPPING","FOR"),t.tokentype&&t.tokentype.length>0){let i=c.unwrapList(t.tokentype).map(r=>this.visit(r,s));e.push(i.join(", "));}if(t.dicts&&t.dicts.length>=2){e.push("REPLACE");let i=c.unwrapList(t.dicts).map(r=>r.List&&r.List.items?c.unwrapList(r.List.items).map(n=>this.visit(n,s)).join("."):this.visit(r,s));e.push(i[0],"WITH",i.slice(1).join(", "));}break;case "ALTER_TSCONFIG_DROP_MAPPING":if(e.push("DROP","MAPPING","FOR"),t.tokentype&&t.tokentype.length>0){let i=c.unwrapList(t.tokentype).map(r=>this.visit(r,s));e.push(i.join(", "));}break;default:throw new Error(`Unsupported AlterTSConfigurationStmt kind: ${t.kind}`)}return e.join(" ")}ClosePortalStmt(t,s){let e=["CLOSE"];return t.portalname?e.push(m.quoteIdentifier(t.portalname)):e.push("ALL"),e.join(" ")}FetchStmt(t,s){let e=[t.ismove?"MOVE":"FETCH"],i=t.howMany===9223372036854776e3;if(t.direction)switch(t.direction){case "FETCH_FORWARD":i?e.push("FORWARD","ALL"):t.howMany!==void 0&&t.howMany!==null?e.push("FORWARD",t.howMany.toString()):e.push("FORWARD");break;case "FETCH_BACKWARD":i?e.push("BACKWARD","ALL"):t.howMany!==void 0&&t.howMany!==null?e.push("BACKWARD",t.howMany.toString()):e.push("BACKWARD");break;case "FETCH_ABSOLUTE":t.howMany!==void 0&&t.howMany!==null&&e.push("ABSOLUTE",t.howMany.toString());break;case "FETCH_RELATIVE":t.howMany!==void 0&&t.howMany!==null?e.push("RELATIVE",t.howMany.toString()):e.push("RELATIVE","0");break;default:throw new Error(`Unsupported FetchStmt direction: ${t.direction}`)}else i&&e.push("ALL");return t.portalname&&e.push(m.quoteIdentifier(t.portalname)),e.join(" ")}AlterStatsStmt(t,s){let e=["ALTER","STATISTICS"];if(t.defnames&&t.defnames.length>0){let i=c.unwrapList(t.defnames).map(r=>this.visit(r,s));e.push(i.join("."));}return e.push("SET","STATISTICS"),t.stxstattarget&&e.push(this.visit(t.stxstattarget,s)),e.join(" ")}ObjectWithArgs(t,s){let e="";if(t.objname&&t.objname.length>0){let i=s.spawn("ObjectWithArgs");e=c.unwrapList(t.objname).map(n=>this.visit(n,i)).join(".");}if(t.objfuncargs&&t.objfuncargs.length>0){let i=c.unwrapList(t.objfuncargs).map(r=>this.visit(r,s));e+=`(${i.join(", ")})`;}else if(t.objargs&&t.objargs.length>0){let i=c.unwrapList(t.objargs).map(r=>!r||Object.keys(r).length===0?"NONE":this.visit(r,s));e+=`(${i.join(", ")})`;}else t.args_unspecified||((s.parentNodeTypes.includes("CommentStmt")||s.parentNodeTypes.includes("DropStmt"))&&s.objtype==="OBJECT_AGGREGATE"?e+="(*)":s.parentNodeTypes.includes("CreateOpClassItem")||(e+="()"));return e}AlterOperatorStmt(t,s){let e=["ALTER","OPERATOR"];if(t.opername&&e.push(this.ObjectWithArgs(t.opername,s)),e.push("SET"),t.options&&t.options.length>0){let i=s.spawn("AlterOperatorStmt"),r=c.unwrapList(t.options).map(n=>this.visit(n,i));e.push(`(${r.join(", ")})`);}return e.join(" ")}AlterFdwStmt(t,s){let e=["ALTER","FOREIGN","DATA","WRAPPER"];if(t.fdwname&&e.push(m.quoteIdentifier(t.fdwname)),t.func_options&&t.func_options.length>0){let i=s.spawn("AlterFdwStmt"),r=c.unwrapList(t.func_options).map(n=>this.visit(n,i));e.push(r.join(" "));}if(t.options&&t.options.length>0){e.push("OPTIONS");let i=s.spawn("AlterFdwStmt"),r=c.unwrapList(t.options).map(n=>this.visit(n,i));e.push(`(${r.join(", ")})`);}return e.join(" ")}CreateForeignServerStmt(t,s){let e=["CREATE","SERVER"];if(t.if_not_exists&&e.push("IF","NOT","EXISTS"),t.servername&&e.push(m.quoteIdentifier(t.servername)),t.servertype&&e.push("TYPE",m.escape(t.servertype)),t.version&&e.push("VERSION",m.escape(t.version)),t.fdwname&&e.push("FOREIGN","DATA","WRAPPER",m.quoteIdentifier(t.fdwname)),t.options&&t.options.length>0){e.push("OPTIONS"),e.push("(");let i=s.spawn("CreateForeignServerStmt"),r=c.unwrapList(t.options).map(n=>this.visit(n,i));e.push(r.join(", ")),e.push(")");}return e.join(" ")}AlterForeignServerStmt(t,s){let e=["ALTER","SERVER"];if(t.servername&&e.push(m.quoteIdentifier(t.servername)),t.version&&e.push("VERSION",m.escape(t.version)),t.options&&t.options.length>0){e.push("OPTIONS"),e.push("(");let i=s.spawn("AlterForeignServerStmt"),r=c.unwrapList(t.options).map(n=>this.visit(n,i));e.push(r.join(", ")),e.push(")");}return e.join(" ")}AlterUserMappingStmt(t,s){let e=["ALTER","USER","MAPPING","FOR"];if(t.user?e.push(this.RoleSpec(t.user,s)):e.push("CURRENT_USER"),e.push("SERVER"),t.servername&&e.push(m.quoteIdentifier(t.servername)),t.options&&t.options.length>0){e.push("OPTIONS");let i=s.spawn("AlterUserMappingStmt"),r=c.unwrapList(t.options).map(n=>this.visit(n,i));e.push(`(${r.join(", ")})`);}return e.join(" ")}DropUserMappingStmt(t,s){let e=["DROP","USER","MAPPING"];return t.missing_ok&&e.push("IF","EXISTS"),e.push("FOR"),t.user?e.push(this.RoleSpec(t.user,s)):e.push("CURRENT_USER"),e.push("SERVER"),t.servername&&e.push(m.quoteIdentifier(t.servername)),e.join(" ")}ImportForeignSchemaStmt(t,s){let e=["IMPORT","FOREIGN","SCHEMA"];if(t.remote_schema&&e.push(m.quoteIdentifier(t.remote_schema)),t.list_type)switch(t.list_type){case "FDW_IMPORT_SCHEMA_ALL":break;case "FDW_IMPORT_SCHEMA_LIMIT_TO":if(e.push("LIMIT","TO"),t.table_list&&t.table_list.length>0){let i=c.unwrapList(t.table_list).map(r=>this.visit(r,s));e.push(`(${i.join(", ")})`);}break;case "FDW_IMPORT_SCHEMA_EXCEPT":if(e.push("EXCEPT"),t.table_list&&t.table_list.length>0){let i=c.unwrapList(t.table_list).map(r=>this.visit(r,s));e.push(`(${i.join(", ")})`);}break;default:throw new Error(`Unsupported ImportForeignSchemaStmt list_type: ${t.list_type}`)}if(e.push("FROM","SERVER"),t.server_name&&e.push(m.quoteIdentifier(t.server_name)),e.push("INTO"),t.local_schema&&e.push(m.quoteIdentifier(t.local_schema)),t.options&&t.options.length>0){let i=s.spawn("ImportForeignSchemaStmt"),r=c.unwrapList(t.options).map(n=>this.visit(n,i));e.push(`OPTIONS (${r.join(", ")})`);}return e.join(" ")}ClusterStmt(t,s){let e=["CLUSTER"];if(t.relation&&(e.push(this.RangeVar(t.relation,s)),t.indexname&&e.push("USING",m.quoteIdentifier(t.indexname))),t.params&&t.params.length>0){let i=c.unwrapList(t.params).map(r=>this.visit(r,s));e.push(`(${i.join(", ")})`);}return e.join(" ")}VacuumStmt(t,s){let e=[t.is_vacuumcmd?"VACUUM":"ANALYZE"];if(t.options&&t.options.length>0){let i=c.unwrapList(t.options).map(r=>this.visit(r,s));e.push(`(${i.join(", ")})`);}if(t.rels&&t.rels.length>0){let i=c.unwrapList(t.rels).map(r=>this.visit(r,s));e.push(i.join(", "));}return e.join(" ")}ExplainStmt(t,s){let e=["EXPLAIN"];if(t.options&&t.options.length>0){let i=s.spawn("ExplainStmt"),r=c.unwrapList(t.options).map(n=>this.visit(n,i));e.push(`(${r.join(", ")})`);}return t.query&&e.push(this.visit(t.query,s)),e.join(" ")}ReindexStmt(t,s){let e=["REINDEX"];if(t.params&&t.params.length>0){let i=c.unwrapList(t.params).map(r=>this.visit(r,s));e.push(`(${i.join(", ")})`);}if(t.kind)switch(t.kind){case "REINDEX_OBJECT_INDEX":e.push("INDEX");break;case "REINDEX_OBJECT_TABLE":e.push("TABLE");break;case "REINDEX_OBJECT_SCHEMA":e.push("SCHEMA");break;case "REINDEX_OBJECT_SYSTEM":e.push("SYSTEM");break;case "REINDEX_OBJECT_DATABASE":e.push("DATABASE");break;default:throw new Error(`Unsupported ReindexStmt kind: ${t.kind}`)}return t.relation&&e.push(this.RangeVar(t.relation,s)),t.name&&e.push(m.quoteIdentifier(t.name)),e.join(" ")}CallStmt(t,s){let e=["CALL"];if(t.funccall){let i=t.funccall;if(i.funcname&&i.funcname.length>0){let n=i.funcname.map(u=>u.String?u.String.sval:this.visit(u,s)).join("."),o="";i.args&&i.args.length>0?o=`(${i.args.map(l=>this.visit(l,s)).join(", ")})`:o="()",e.push(`${n}${o}`);}}else if(t.funcexpr)e.push(this.FuncExpr(t.funcexpr,s));else throw new Error("CallStmt requires either funccall or funcexpr");return e.join(" ")}CreatedbStmt(t,s){let e=["CREATE DATABASE"];if(!t.dbname)throw new Error("CreatedbStmt requires dbname");if(e.push(m.quoteIdentifier(t.dbname)),t.options&&t.options.length>0){let i=c.unwrapList(t.options).map(r=>this.visit(r,s)).join(" ");e.push("WITH",i);}return e.join(" ")}DropdbStmt(t,s){let e=["DROP DATABASE"];if(t.missing_ok&&e.push("IF EXISTS"),!t.dbname)throw new Error("DropdbStmt requires dbname");if(e.push(m.quoteIdentifier(t.dbname)),t.options&&t.options.length>0){let i=c.unwrapList(t.options).map(r=>this.visit(r,s)).join(" ");e.push("WITH",i);}return e.join(" ")}RenameStmt(t,s){let e=["ALTER"];if(!t.renameType)throw new Error("RenameStmt requires renameType");switch(t.renameType){case "OBJECT_TABLE":e.push("TABLE");break;case "OBJECT_VIEW":e.push("VIEW");break;case "OBJECT_INDEX":e.push("INDEX");break;case "OBJECT_SEQUENCE":e.push("SEQUENCE");break;case "OBJECT_FUNCTION":e.push("FUNCTION");break;case "OBJECT_PROCEDURE":e.push("PROCEDURE");break;case "OBJECT_SCHEMA":e.push("SCHEMA");break;case "OBJECT_DATABASE":e.push("DATABASE");break;case "OBJECT_COLUMN":t.relationType==="OBJECT_FOREIGN_TABLE"?e.push("FOREIGN TABLE"):t.relationType==="OBJECT_VIEW"?e.push("VIEW"):e.push("TABLE");break;case "OBJECT_DOMAIN":e.push("DOMAIN");break;case "OBJECT_TYPE":e.push("TYPE");break;case "OBJECT_DOMCONSTRAINT":e.push("DOMAIN");break;case "OBJECT_TABCONSTRAINT":e.push("TABLE");break;case "OBJECT_AGGREGATE":e.push("AGGREGATE");break;case "OBJECT_COLLATION":e.push("COLLATION");break;case "OBJECT_CONVERSION":e.push("CONVERSION");break;case "OBJECT_EXTENSION":e.push("EXTENSION");break;case "OBJECT_FOREIGN_SERVER":e.push("SERVER");break;case "OBJECT_FOREIGN_TABLE":e.push("FOREIGN TABLE");break;case "OBJECT_LANGUAGE":e.push("LANGUAGE");break;case "OBJECT_MATVIEW":e.push("MATERIALIZED VIEW");break;case "OBJECT_OPCLASS":e.push("OPERATOR CLASS");break;case "OBJECT_OPERATOR":e.push("OPERATOR");break;case "OBJECT_OPFAMILY":e.push("OPERATOR FAMILY");break;case "OBJECT_POLICY":e.push("POLICY"),t.subname&&e.push(m.quoteIdentifier(t.subname));break;case "OBJECT_PUBLICATION":e.push("PUBLICATION");break;case "OBJECT_ROLE":e.push("ROLE");break;case "OBJECT_RULE":e.push("RULE");break;case "OBJECT_SUBSCRIPTION":e.push("SUBSCRIPTION");break;case "OBJECT_TABLESPACE":e.push("TABLESPACE");break;case "OBJECT_TRIGGER":e.push("TRIGGER");break;case "OBJECT_TSCONFIGURATION":e.push("TEXT SEARCH CONFIGURATION");break;case "OBJECT_TSDICTIONARY":e.push("TEXT SEARCH DICTIONARY");break;case "OBJECT_TSPARSER":e.push("TEXT SEARCH PARSER");break;case "OBJECT_TSTEMPLATE":e.push("TEXT SEARCH TEMPLATE");break;case "OBJECT_FDW":e.push("FOREIGN DATA WRAPPER");break;case "OBJECT_EVENT_TRIGGER":e.push("EVENT TRIGGER");break;case "OBJECT_ATTRIBUTE":t.relationType==="OBJECT_TYPE"?e.push("TYPE"):e.push("TABLE");break;case "OBJECT_ROUTINE":e.push("ROUTINE");break;default:throw new Error(`Unsupported RenameStmt renameType: ${t.renameType}`)}if(t.missing_ok&&e.push("IF EXISTS"),t.renameType==="OBJECT_RULE"&&t.subname&&t.relation)e.push(m.quoteIdentifier(t.subname)),e.push("ON"),e.push(this.RangeVar(t.relation,s));else if(t.relation){let i=s.spawn("RenameStmt",{objtype:t.relationType});t.renameType==="OBJECT_POLICY"&&e.push("ON"),e.push(this.RangeVar(t.relation,i));}else if(t.object)if((t.renameType==="OBJECT_OPFAMILY"||t.renameType==="OBJECT_OPCLASS")&&t.object.List){let i=c.unwrapList(t.object);if(i.length===2){let r=i[0].String?.sval||"",n=i[1].String?.sval||"";e.push(`${m.quoteIdentifier(n)} USING ${r}`);}else e.push(this.visit(t.object,s));}else if(t.renameType==="OBJECT_SCHEMA"&&t.object.List){let i=c.unwrapList(t.object);i.length>0&&i[0].String?e.push(this.quoteIfNeeded(i[0].String.sval)):e.push(this.visit(t.object,s));}else e.push(this.visit(t.object,s));if(t.renameType==="OBJECT_COLUMN"&&t.subname?e.push("RENAME COLUMN",m.quoteIdentifier(t.subname),"TO"):t.renameType==="OBJECT_DOMCONSTRAINT"&&t.subname?e.push("RENAME CONSTRAINT",m.quoteIdentifier(t.subname),"TO"):t.renameType==="OBJECT_TABCONSTRAINT"&&t.subname?e.push("RENAME CONSTRAINT",m.quoteIdentifier(t.subname),"TO"):t.renameType==="OBJECT_ATTRIBUTE"&&t.subname?e.push("RENAME ATTRIBUTE",m.quoteIdentifier(t.subname),"TO"):t.renameType==="OBJECT_ROLE"&&t.subname?e.push(m.quoteIdentifier(t.subname),"RENAME TO"):t.renameType==="OBJECT_SCHEMA"&&t.subname?e.push(this.quoteIfNeeded(t.subname),"RENAME TO"):(t.renameType,e.push("RENAME TO")),!t.newname)throw new Error("RenameStmt requires newname");return e.push(m.quoteIdentifier(t.newname)),t.behavior==="DROP_CASCADE"&&e.push("CASCADE"),e.join(" ")}AlterOwnerStmt(t,s){let e=["ALTER"];if(!t.objectType)throw new Error("AlterOwnerStmt requires objectType");if(e.push(this.getObjectTypeKeyword(t.objectType)),t.relation)e.push(this.RangeVar(t.relation,s));else if(t.object)if((t.objectType==="OBJECT_OPFAMILY"||t.objectType==="OBJECT_OPCLASS")&&t.object.List){let i=c.unwrapList(t.object);if(i.length===2){let r=i[0].String?.sval||"",n=i[1].String?.sval||"";e.push(`${m.quoteIdentifier(n)} USING ${r}`);}else e.push(this.visit(t.object,s));}else e.push(this.visit(t.object,s));if(e.push("OWNER TO"),!t.newowner)throw new Error("AlterOwnerStmt requires newowner");return e.push(this.RoleSpec(t.newowner,s)),e.join(" ")}GrantStmt(t,s){let e=[];if(t.is_grant?e.push("GRANT"):(e.push("REVOKE"),t.grant_option&&e.push("GRANT OPTION FOR")),t.privileges&&t.privileges.length>0){let i=s.spawn("GrantStmt"),r=c.unwrapList(t.privileges).map(n=>this.visit(n,i)).join(", ");e.push(r);}else e.push("ALL");if(e.push("ON"),t.objtype&&t.targtype==="ACL_TARGET_DEFAULTS")switch(t.objtype){case "OBJECT_TABLE":e.push("TABLES");break;case "OBJECT_SEQUENCE":e.push("SEQUENCES");break;case "OBJECT_FUNCTION":e.push("FUNCTIONS");break;case "OBJECT_PROCEDURE":e.push("PROCEDURES");break;case "OBJECT_ROUTINE":e.push("ROUTINES");break;case "OBJECT_TYPE":e.push("TYPES");break;case "OBJECT_SCHEMA":e.push("SCHEMAS");break;}switch(t.targtype){case "ACL_TARGET_OBJECT":if(t.objtype==="OBJECT_SCHEMA"?e.push("SCHEMA"):t.objtype==="OBJECT_LANGUAGE"?e.push("LANGUAGE"):t.objtype==="OBJECT_FUNCTION"?e.push("FUNCTION"):t.objtype==="OBJECT_PROCEDURE"?e.push("PROCEDURE"):t.objtype==="OBJECT_TYPE"?e.push("TYPE"):t.objtype==="OBJECT_DOMAIN"?e.push("DOMAIN"):t.objtype==="OBJECT_LARGEOBJECT"?e.push("LARGE OBJECT"):t.objtype==="OBJECT_FDW"?e.push("FOREIGN","DATA","WRAPPER"):t.objtype==="OBJECT_FOREIGN_SERVER"?e.push("FOREIGN","SERVER"):t.objtype==="OBJECT_DATABASE"&&e.push("DATABASE"),t.objects&&t.objects.length>0){let i=c.unwrapList(t.objects).map(r=>this.visit(r,s)).join(", ");e.push(i);}break;case "ACL_TARGET_ALL_IN_SCHEMA":switch(t.objtype){case "OBJECT_TABLE":e.push("ALL TABLES IN SCHEMA");break;case "OBJECT_SEQUENCE":e.push("ALL SEQUENCES IN SCHEMA");break;case "OBJECT_FUNCTION":e.push("ALL FUNCTIONS IN SCHEMA");break;case "OBJECT_PROCEDURE":e.push("ALL PROCEDURES IN SCHEMA");break;case "OBJECT_ROUTINE":e.push("ALL ROUTINES IN SCHEMA");break;case "OBJECT_TYPE":e.push("ALL TYPES IN SCHEMA");break;default:e.push("ALL TABLES IN SCHEMA");break}if(t.objects&&t.objects.length>0){let i=c.unwrapList(t.objects).map(r=>this.visit(r,s)).join(", ");e.push(i);}break;default:if(t.objects&&t.objects.length>0){let i=c.unwrapList(t.objects).map(r=>this.visit(r,s)).join(", ");e.push(i);}}if(t.is_grant?e.push("TO"):e.push("FROM"),t.grantees&&t.grantees.length>0){let i=c.unwrapList(t.grantees).map(r=>this.visit(r,s)).join(", ");e.push(i);}return t.grant_option&&t.is_grant&&e.push("WITH GRANT OPTION"),t.is_grant||(t.behavior==="DROP_CASCADE"?e.push("CASCADE"):t.behavior==="DROP_RESTRICT"&&e.push("RESTRICT")),e.join(" ")}GrantRoleStmt(t,s){let e=[],i=false,r=false,n=false,o,u,l;if(t.opt&&t.opt.length>0){let p=c.unwrapList(t.opt),f=p.find(g=>g.DefElem&&g.DefElem.defname==="inherit"),h=p.find(g=>g.String&&g.String.sval==="admin"||g.DefElem&&g.DefElem.defname==="admin"),E=p.find(g=>g.DefElem&&g.DefElem.defname==="set");f&&f.DefElem&&(i=true,o=f.DefElem.arg?.Boolean?.boolval),h&&(r=true,h.DefElem&&h.DefElem.arg&&(u=h.DefElem.arg.Boolean?.boolval)),E&&E.DefElem&&(n=true,l=E.DefElem.arg?.Boolean?.boolval);}if(t.is_grant?e.push("GRANT"):(e.push("REVOKE"),i?e.push("INHERIT OPTION FOR"):r&&e.push("ADMIN OPTION FOR")),t.granted_roles&&t.granted_roles.length>0){let p=c.unwrapList(t.granted_roles).map(f=>this.visit(f,s)).join(", ");e.push(p);}if(t.is_grant?e.push("TO"):e.push("FROM"),t.grantee_roles&&t.grantee_roles.length>0){let p=c.unwrapList(t.grantee_roles).map(f=>this.visit(f,s)).join(", ");e.push(p);}if(t.is_grant){let p=[];r&&(u===true?p.push("ADMIN OPTION"):u===false?p.push("ADMIN FALSE"):p.push("ADMIN OPTION")),i&&(o===true?p.push("INHERIT OPTION"):o===false&&p.push("INHERIT FALSE")),n&&(l===true?p.push("SET TRUE"):l===false&&p.push("SET FALSE")),p.length>0&&e.push("WITH",p.join(", "));}return e.join(" ")}SecLabelStmt(t,s){let e=["SECURITY LABEL"];if(t.provider&&e.push("FOR",m.quoteIdentifier(t.provider)),e.push("ON"),t.objtype)switch(t.objtype){case "OBJECT_TABLE":e.push("TABLE");break;case "OBJECT_COLUMN":e.push("COLUMN");break;case "OBJECT_FUNCTION":e.push("FUNCTION");break;case "OBJECT_SCHEMA":e.push("SCHEMA");break;case "OBJECT_DATABASE":e.push("DATABASE");break;case "OBJECT_ROLE":e.push("ROLE");break;default:e.push(t.objtype.replace("OBJECT_",""));}return t.object&&e.push(this.visit(t.object,s)),e.push("IS"),t.label?e.push(`'${t.label}'`):e.push("NULL"),e.join(" ")}AlterDefaultPrivilegesStmt(t,s){let e=["ALTER DEFAULT PRIVILEGES"];if(t.options&&t.options.length>0){let i=c.unwrapList(t.options);for(let r of i){let n=this.getNodeData(r);if(n.defname==="schemas"){if(e.push("IN SCHEMA"),n.arg){let o=c.unwrapList(n.arg).map(u=>this.visit(u,s)).join(", ");e.push(o);}}else if(n.defname==="roles"&&(e.push("FOR ROLE"),n.arg)){let o=c.unwrapList(n.arg).map(u=>this.visit(u,s)).join(", ");e.push(o);}}}if(t.action){let i=this.GrantStmt(t.action,s);if(s.isPretty())return e.join(" ")+s.newline()+s.indent(i);e.push(i);}return e.join(" ")}CreateConversionStmt(t,s){let e=["CREATE"];if(t.def&&e.push("DEFAULT"),e.push("CONVERSION"),t.conversion_name&&t.conversion_name.length>0){let i=c.unwrapList(t.conversion_name).map(r=>this.visit(r,s)).join(".");e.push(i);}if(t.for_encoding_name&&e.push("FOR",`'${t.for_encoding_name}'`),t.to_encoding_name&&e.push("TO",`'${t.to_encoding_name}'`),t.func_name&&t.func_name.length>0){e.push("FROM");let i=c.unwrapList(t.func_name).map(r=>this.visit(r,s)).join(".");e.push(i);}return e.join(" ")}CreateCastStmt(t,s){let e=["CREATE CAST"];if(e.push("("),t.sourcetype&&e.push(this.TypeName(t.sourcetype,s)),e.push("AS"),t.targettype&&e.push(this.TypeName(t.targettype,s)),e.push(")"),t.func?(e.push("WITH FUNCTION"),e.push(this.ObjectWithArgs(t.func,s))):t.inout?e.push("WITH INOUT"):e.push("WITHOUT FUNCTION"),t.context)switch(t.context){case "COERCION_IMPLICIT":e.push("AS IMPLICIT");break;case "COERCION_ASSIGNMENT":e.push("AS ASSIGNMENT");break;case "COERCION_EXPLICIT":break;default:throw new Error(`Unsupported CreateCastStmt context: ${t.context}`)}else t.context==="COERCION_ASSIGNMENT"&&e.push("AS ASSIGNMENT");return e.join(" ")}CreatePLangStmt(t,s){let e=["CREATE"];if(t.replace&&e.push("OR REPLACE"),t.pltrusted&&e.push("TRUSTED"),e.push("LANGUAGE"),t.plname&&e.push(m.quoteIdentifier(t.plname)),t.plhandler&&t.plhandler.length>0){e.push("HANDLER");let i=c.unwrapList(t.plhandler).map(r=>this.visit(r,s)).join(".");e.push(i);}if(t.plinline&&t.plinline.length>0){e.push("INLINE");let i=c.unwrapList(t.plinline).map(r=>this.visit(r,s)).join(".");e.push(i);}if(t.plvalidator&&t.plvalidator.length>0){e.push("VALIDATOR");let i=c.unwrapList(t.plvalidator).map(r=>this.visit(r,s)).join(".");e.push(i);}return e.join(" ")}CreateTransformStmt(t,s){let e=["CREATE"];t.replace&&e.push("OR REPLACE"),e.push("TRANSFORM FOR"),t.type_name&&e.push(this.TypeName(t.type_name,s)),e.push("LANGUAGE"),t.lang&&e.push(m.quoteIdentifier(t.lang)),e.push("(");let i=[];if(t.fromsql){let r=this.ObjectWithArgs(t.fromsql,s);i.push(`FROM SQL WITH FUNCTION ${r}`);}if(t.tosql){let r=this.ObjectWithArgs(t.tosql,s);i.push(`TO SQL WITH FUNCTION ${r}`);}return e.push(i.join(", ")),e.push(")"),e.join(" ")}CreateTrigStmt(t,s){let e=["CREATE"];if(t.replace&&e.push("OR REPLACE"),t.isconstraint&&e.push("CONSTRAINT"),e.push("TRIGGER"),t.trigname&&e.push(m.quoteIdentifier(t.trigname)),s.isPretty()){let i=[],r=[];t.timing&2?r.push("BEFORE"):t.timing&64?r.push("INSTEAD OF"):r.push("AFTER");let n=[];if(t.events&4&&n.push("INSERT"),t.events&8&&n.push("DELETE"),t.events&16){let u="UPDATE";if(t.columns&&t.columns.length>0){let l=c.unwrapList(t.columns).map(p=>this.visit(p,s)).join(", ");u+=" OF "+l;}n.push(u);}if(t.events&32&&n.push("TRUNCATE"),i.push(s.indent(r.join(" ")+" "+n.join(" OR "))),t.relation&&i.push(s.indent("ON "+this.RangeVar(t.relation,s))),t.transitionRels&&t.transitionRels.length>0){let u=c.unwrapList(t.transitionRels).map(l=>this.visit(l,s)).join(" ");i.push(s.indent("REFERENCING "+u));}if(t.deferrable&&i.push(s.indent("DEFERRABLE")),t.initdeferred&&i.push(s.indent("INITIALLY DEFERRED")),t.row?i.push(s.indent("FOR EACH ROW")):i.push(s.indent("FOR EACH STATEMENT")),t.whenClause){let u="WHEN ("+this.visit(t.whenClause,s)+")";i.push(s.indent(u));}let o="EXECUTE";if(t.funcname&&t.funcname.length>0){let u=c.unwrapList(t.funcname).map(l=>this.visit(l,s)).join(".");o+=" PROCEDURE "+u;}if(t.args&&t.args.length>0){let u=s.spawn("CreateTrigStmt",{isStringLiteral:true}),l=c.unwrapList(t.args).map(p=>this.visit(p,u)).join(", ");o+="("+l+")";}else o+="()";return i.push(s.indent(o)),e.join(" ")+s.newline()+i.join(s.newline())}else {let i=[];t.timing&2?i.push("BEFORE"):t.timing&64?i.push("INSTEAD OF"):i.push("AFTER"),e.push(i.join(" "));let r=[];if(t.events&4&&r.push("INSERT"),t.events&8&&r.push("DELETE"),t.events&16&&r.push("UPDATE"),t.events&32&&r.push("TRUNCATE"),e.push(r.join(" OR ")),t.columns&&t.columns.length>0){e.push("OF");let n=c.unwrapList(t.columns).map(o=>this.visit(o,s)).join(", ");e.push(n);}if(e.push("ON"),t.relation&&e.push(this.RangeVar(t.relation,s)),t.constrrel&&(e.push("FROM"),e.push(this.RangeVar(t.constrrel,s))),t.deferrable&&e.push("DEFERRABLE"),t.initdeferred&&e.push("INITIALLY DEFERRED"),t.transitionRels&&t.transitionRels.length>0){e.push("REFERENCING");let n=c.unwrapList(t.transitionRels).map(o=>this.visit(o,s)).join(" ");e.push(n);}if(t.row?e.push("FOR EACH ROW"):e.push("FOR EACH STATEMENT"),t.whenClause&&(e.push("WHEN"),e.push("("),e.push(this.visit(t.whenClause,s)),e.push(")")),e.push("EXECUTE"),t.funcname&&t.funcname.length>0){let n=c.unwrapList(t.funcname).map(o=>this.visit(o,s)).join(".");e.push("FUNCTION",n);}if(t.args&&t.args.length>0){e.push("(");let n=s.spawn("CreateTrigStmt",{isStringLiteral:true}),o=c.unwrapList(t.args).map(u=>this.visit(u,n)).join(", ");e.push(o),e.push(")");}else e.push("()");return e.join(" ")}}TriggerTransition(t,s){let e=[];return t.isNew?e.push("NEW TABLE AS"):e.push("OLD TABLE AS"),t.name&&e.push(m.quoteIdentifier(t.name)),e.join(" ")}CreateEventTrigStmt(t,s){let e=["CREATE EVENT TRIGGER"];if(t.trigname&&e.push(m.quoteIdentifier(t.trigname)),e.push("ON"),t.eventname&&e.push(t.eventname),t.whenclause&&t.whenclause.length>0){e.push("WHEN");let i=s.spawn("CreateEventTrigStmt"),r=c.unwrapList(t.whenclause).map(n=>this.visit(n,i)).join(" AND ");e.push(r);}if(e.push("EXECUTE"),t.funcname&&t.funcname.length>0){let i=c.unwrapList(t.funcname).map(r=>this.visit(r,s)).join(".");e.push("PROCEDURE",i+"()");}return e.join(" ")}AlterEventTrigStmt(t,s){let e=["ALTER EVENT TRIGGER"];if(t.trigname&&e.push(m.quoteIdentifier(t.trigname)),t.tgenabled)switch(t.tgenabled){case "O":e.push("ENABLE");break;case "D":e.push("DISABLE");break;case "R":e.push("ENABLE REPLICA");break;case "A":e.push("ENABLE ALWAYS");break;default:throw new Error(`Unsupported trigger enable state: ${t.tgenabled}`)}return e.join(" ")}CreateOpClassStmt(t,s){let e=["CREATE OPERATOR CLASS"];if(t.opclassname&&t.opclassname.length>0){let i=c.unwrapList(t.opclassname).map(r=>this.visit(r,s)).join(".");e.push(i);}if(t.isDefault&&e.push("DEFAULT"),e.push("FOR TYPE"),t.datatype&&e.push(this.TypeName(t.datatype,s)),e.push("USING"),t.amname&&e.push(t.amname),t.opfamilyname&&t.opfamilyname.length>0){e.push("FAMILY");let i=c.unwrapList(t.opfamilyname).map(r=>this.visit(r,s)).join(".");e.push(i);}if(e.push("AS"),t.items&&t.items.length>0){let i=c.unwrapList(t.items).map(r=>this.visit(r,s)).join(", ");e.push(i);}return e.join(" ")}CreateOpFamilyStmt(t,s){let e=["CREATE OPERATOR FAMILY"];if(t.opfamilyname&&t.opfamilyname.length>0){let i=c.unwrapList(t.opfamilyname).map(r=>this.visit(r,s)).join(".");e.push(i);}return e.push("USING"),t.amname&&e.push(t.amname),e.join(" ")}AlterOpFamilyStmt(t,s){let e=["ALTER OPERATOR FAMILY"];if(t.opfamilyname&&t.opfamilyname.length>0){let i=c.unwrapList(t.opfamilyname).map(r=>this.visit(r,s)).join(".");e.push(i);}if(e.push("USING"),t.amname&&e.push(t.amname),t.isDrop?e.push("DROP"):e.push("ADD"),t.items&&t.items.length>0){let i=c.unwrapList(t.items).map(r=>this.visit(r,s)).join(", ");e.push(i);}return e.join(" ")}MergeStmt(t,s){let e=[];if(t.withClause&&e.push(this.WithClause(t.withClause,s)),e.push("MERGE INTO"),t.relation&&e.push(this.RangeVar(t.relation,s)),t.sourceRelation&&(e.push("USING"),e.push(this.visit(t.sourceRelation,s))),t.joinCondition&&(e.push("ON"),e.push(this.visit(t.joinCondition,s))),t.mergeWhenClauses&&t.mergeWhenClauses.length>0){let i=c.unwrapList(t.mergeWhenClauses).map(r=>this.visit(r,s)).join(" ");e.push(i);}return e.join(" ")}AlterTableMoveAllStmt(t,s){let e=["ALTER"];return t.objtype==="OBJECT_TABLE"?e.push("TABLE"):t.objtype==="OBJECT_INDEX"?e.push("INDEX"):e.push("TABLE"),e.push("ALL","IN","TABLESPACE"),t.orig_tablespacename&&e.push(m.quoteIdentifier(t.orig_tablespacename)),e.push("SET","TABLESPACE"),t.new_tablespacename&&e.push(m.quoteIdentifier(t.new_tablespacename)),t.nowait&&e.push("NOWAIT"),e.join(" ")}CreateSeqStmt(t,s){let e=["CREATE"];if(t.sequence&&t.sequence.relpersistence==="t"&&e.push("TEMPORARY"),e.push("SEQUENCE"),t.if_not_exists&&e.push("IF NOT EXISTS"),t.sequence){let i=[],r=t.sequence;r.schemaname&&i.push(m.quoteIdentifier(r.schemaname)),r.relname&&i.push(m.quoteIdentifier(r.relname)),e.push(i.join("."));}if(t.options&&t.options.length>0){let i=s.spawn("CreateSeqStmt"),r=c.unwrapList(t.options).filter(n=>n!=null&&this.getNodeType(n)!=="undefined").map(n=>{try{return this.visit(n,i)}catch(o){return console.warn(`Error processing option in CreateSeqStmt: ${o instanceof Error?o.message:String(o)}`),""}}).filter(n=>n!=="").join(" ");r&&e.push(r);}return e.join(" ")}AlterSeqStmt(t,s){let e=["ALTER","SEQUENCE"];if(t.missing_ok&&e.push("IF EXISTS"),t.sequence){let i=[],r=t.sequence;r.schemaname&&i.push(m.quoteIdentifier(r.schemaname)),r.relname&&i.push(m.quoteIdentifier(r.relname)),e.push(i.join("."));}if(t.options&&t.options.length>0){let i=s.spawn("AlterSeqStmt"),r=c.unwrapList(t.options).filter(n=>n&&n!==void 0).map(n=>{try{return !n||this.getNodeType(n)==="undefined"?"":this.visit(n,i)}catch(o){return console.warn(`Error processing option in AlterSeqStmt: ${o instanceof Error?o.message:String(o)}`),""}}).filter(n=>n&&n.trim().length>0).join(" ");r&&e.push(r);}return t.for_identity&&e.push("FOR IDENTITY"),e.join(" ")}CompositeTypeStmt(t,s){let e=["CREATE","TYPE"];if(t.typevar){let i=s.spawn("CompositeTypeStmt");e.push(this.RangeVar(t.typevar,i));}if(e.push("AS"),t.coldeflist&&t.coldeflist.length>0){let i=c.unwrapList(t.coldeflist).map(r=>this.visit(r,s)).join(", ");e.push(`(${i})`);}else e.push("()");return e.join(" ")}CreateRangeStmt(t,s){let e=["CREATE","TYPE"];if(t.typeName&&t.typeName.length>0){let i=c.unwrapList(t.typeName).map(r=>this.visit(r,s)).join(".");e.push(i);}if(e.push("AS","RANGE"),t.params&&t.params.length>0){let i=c.unwrapList(t.params).map(r=>{let n=this.getNodeData(r);if(n.defname&&n.arg){let o=this.visit(n.arg,s);return `${n.defname} = ${o}`}return this.visit(r,s)});e.push(`(${i.join(", ")})`);}return e.join(" ")}AlterEnumStmt(t,s){let e=["ALTER","TYPE"];if(t.typeName&&t.typeName.length>0){let i=c.unwrapList(t.typeName).map(r=>this.visit(r,s)).join(".");e.push(i);}if(t.oldVal&&t.newVal){let i=t.oldVal.replace(/'/g,"''"),r=t.newVal.replace(/'/g,"''");e.push("RENAME","VALUE",`'${i}'`,"TO",`'${r}'`);}else if(t.newVal){e.push("ADD","VALUE"),t.skipIfNewValExists&&e.push("IF NOT EXISTS");let i=t.newVal.replace(/'/g,"''");if(e.push(`'${i}'`),t.newValNeighbor){let r=t.newValNeighbor.replace(/'/g,"''");t.newValIsAfter?e.push("AFTER",`'${r}'`):e.push("BEFORE",`'${r}'`);}}return e.join(" ")}AlterTypeStmt(t,s){let e=["ALTER","TYPE"];if(t.typeName&&t.typeName.length>0){let i=c.unwrapList(t.typeName).map(r=>this.visit(r,s)).join(".");e.push(i);}if(e.push("SET"),t.options&&t.options.length>0){let i=c.unwrapList(t.options).map(r=>{let n=this.getNodeData(r);if(n.defname&&n.arg){let o=this.visit(n.arg,s);return `${n.defname} = ${o}`}return this.visit(r,s)});e.push(`(${i.join(", ")})`);}return e.join(" ")}AlterRoleStmt(t,s){let e=t.options&&c.unwrapList(t.options).some(r=>r.DefElem&&r.DefElem.defname==="rolemembers"),i=["ALTER",e?"GROUP":"ROLE"];if(t.role&&i.push(this.RoleSpec(t.role,s)),t.options){let r=s.spawn("AlterRoleStmt");if(e){let n=c.unwrapList(t.options).find(o=>o.DefElem&&o.DefElem.defname==="rolemembers");if(n&&n.DefElem){let o=t.action===1?"ADD":"DROP";if(i.push(o,"USER"),n.DefElem.arg&&n.DefElem.arg.List){let u=c.unwrapList(n.DefElem.arg.List.items).map(l=>this.visit(l,r)).join(", ");i.push(u);}}}else {let n=c.unwrapList(t.options).map(o=>this.visit(o,r)).join(" ");n&&i.push(n);}}return i.join(" ")}DropRoleStmt(t,s){let e=["DROP","ROLE"];if(t.missing_ok&&e.push("IF EXISTS"),t.roles){let i=c.unwrapList(t.roles).map(r=>this.visit(r,s)).join(", ");e.push(i);}return e.join(" ")}targetList(t,s){return !t||!Array.isArray(t)?"":t.map(e=>this.visit(e,s)).join(", ")}CreateAggregateStmt(t,s){let e=["CREATE"];if(t.replace&&e.push("OR REPLACE"),e.push("AGGREGATE"),t.defnames&&t.defnames.length>0){let r=c.unwrapList(t.defnames).map(n=>this.visit(n,s)).join(".");e.push(r);}if(e.push("("),t.args&&t.args.length>0){let r=c.unwrapList(t.args).map(n=>this.visit(n,s)).join(", ");e.push(r);}else e.push("*");e.push(")"),e.push("(");let i=[];if(t.definition&&t.definition.length>0){let r=c.unwrapList(t.definition).map(n=>{let o=this.getNodeData(n);return o.defname==="sfunc"||o.defname==="sfunc1"?`SFUNC = ${this.visit(o.arg,s)}`:o.defname==="stype"||o.defname==="stype1"?`STYPE = ${this.visit(o.arg,s)}`:o.defname==="basetype"?`BASETYPE = ${this.visit(o.arg,s)}`:o.defname==="finalfunc"?`FINALFUNC = ${this.visit(o.arg,s)}`:o.defname==="initcond"||o.defname==="initcond1"?`INITCOND = ${this.visit(o.arg,s)}`:o.defname==="combinefunc"?`COMBINEFUNC = ${this.visit(o.arg,s)}`:o.defname==="serialfunc"?`SERIALFUNC = ${this.visit(o.arg,s)}`:o.defname==="deserialfunc"?`DESERIALFUNC = ${this.visit(o.arg,s)}`:o.defname==="parallel"?`PARALLEL = ${this.visit(o.arg,s)}`:this.visit(n,s)});i.push(...r);}return e.push(i.join(", ")),e.push(")"),e.join(" ")}CreateTableAsStmt(t,s){let e=["CREATE"];if(t.objtype==="OBJECT_MATVIEW"?e.push("MATERIALIZED VIEW"):t.into&&t.into.rel&&t.into.rel.relpersistence==="t"?e.push("TEMPORARY TABLE"):e.push("TABLE"),t.if_not_exists&&e.push("IF NOT EXISTS"),t.into&&t.into.rel&&e.push(this.RangeVar(t.into.rel,s)),t.into&&t.into.colNames&&t.into.colNames.length>0){e.push("(");let i=c.unwrapList(t.into.colNames).map(r=>this.visit(r,s)).join(", ");e.push(i),e.push(")");}if(t.into&&t.into.accessMethod&&(e.push("USING"),e.push(t.into.accessMethod)),t.into&&t.into.onCommit&&t.into.onCommit!=="ONCOMMIT_NOOP")switch(e.push("ON COMMIT"),t.into.onCommit){case "ONCOMMIT_PRESERVE_ROWS":e.push("PRESERVE ROWS");break;case "ONCOMMIT_DELETE_ROWS":e.push("DELETE ROWS");break;case "ONCOMMIT_DROP":e.push("DROP");break}if(e.push("AS"),t.query&&e.push(this.visit(t.query,s)),t.into&&t.into.options&&t.into.options.length>0){e.push("WITH");let i=c.unwrapList(t.into.options).map(r=>this.visit(r,s)).join(", ");e.push(`(${i})`);}return t.into&&t.into.skipData&&e.push("WITH NO DATA"),e.join(" ")}RefreshMatViewStmt(t,s){let e=["REFRESH","MATERIALIZED","VIEW"];return t.concurrent&&e.push("CONCURRENTLY"),t.relation&&e.push(this.visit(t.relation,s)),t.skipData&&e.push("WITH NO DATA"),e.join(" ")}AccessPriv(t,s){let e=[];if(t.priv_name?e.push(t.priv_name.toUpperCase()):e.push("ALL"),t.cols&&t.cols.length>0){e.push("(");let i=s.spawn("AccessPriv"),r=c.unwrapList(t.cols).map(n=>this.visit(n,i));e.push(r.join(", ")),e.push(")");}return e.join(" ")}aliasname(t,s){return typeof t=="string"?m.quoteIdentifier(t):this.visit(t,s)}DefineStmt(t,s){let e=[];if(!t.kind)throw new Error("DefineStmt requires kind property");switch(t.kind){case "OBJECT_OPERATOR":if(e.push("CREATE OPERATOR"),t.defnames&&t.defnames.length>0){let i=c.unwrapList(t.defnames).map((r,n)=>{if(n===t.defnames.length-1){let o=this.getNodeData(r);if(o&&o.sval)return o.sval}return this.visit(r,s)});e.push(i.join("."));}if(t.definition&&t.definition.length>0){e.push("(");let i=c.unwrapList(t.definition).map(r=>{if(r.DefElem){let n=r.DefElem,o=n.defname,u=n.arg;if(o&&u){let l=m.quoteIdentifier(o),p=l!==o?l:this.preserveOperatorDefElemCase(o);if((o.toLowerCase()==="commutator"||o.toLowerCase()==="negator")&&u.List){let f=c.unwrapList(u.List.items);if(f.length===1&&f[0].String)return `${p} = ${f[0].String.sval}`}return o.toLowerCase()==="commutator"||o.toLowerCase()==="negator"?`${p} = ${this.visit(u,s)}`:`${p} = ${this.visit(u,s)}`}else if(o&&!u)return o==="Hashes"||o==="Merges"?m.quoteIdentifier(o):this.preserveOperatorDefElemCase(o).toUpperCase()}return this.visit(r,s)});e.push(i.join(", ")),e.push(")");}break;case "OBJECT_TYPE":if(e.push("CREATE TYPE"),t.defnames&&t.defnames.length>0&&e.push(c.unwrapList(t.defnames).map(i=>this.visit(i,s)).join(".")),t.definition&&t.definition.length>0){let i=s.spawn("DefineStmt"),r=c.unwrapList(t.definition).map(n=>this.visit(n,i));e.push(`(${r.join(", ")})`);}break;case "OBJECT_AGGREGATE":if(e.push("CREATE"),t.replace&&e.push("OR REPLACE"),e.push("AGGREGATE"),t.defnames&&t.defnames.length>0){let i=c.unwrapList(t.defnames).map(r=>this.visit(r,s));e.push(i.join("."));}if(t.args&&t.args.length>0){let i=c.unwrapList(t.args),r=i.some(u=>u.Integer&&u.Integer.ival===1),n=i.length>=2&&i[0].List&&i[0].List.items&&i[0].List.items.length===1&&i[0].List.items[0].FunctionParameter&&i[0].List.items[0].FunctionParameter.mode==="FUNC_PARAM_DEFAULT"&&i[1].Integer&&Object.keys(i[1].Integer).length===0,o=i.filter(u=>!(u.Integer&&(u.Integer.ival===-1||u.Integer.ival===1)||u.Integer&&Object.keys(u.Integer).length===0&&n));if(o.length>0)if(n){let u=o[0];if(u.List&&u.List.items&&u.List.items[0].FunctionParameter){let l=u.List.items[0].FunctionParameter,p;if(l.argType&&l.argType.names){let f=l.argType.names;f.length>=2&&f[0].String&&f[0].String.sval==="pg_catalog"?p=f[1].String.sval:f.length>=1&&f[0].String?p=f[0].String.sval:p="unknown";}else p=this.visit({TypeName:l.argType},s);e.push(`(ORDER BY ${p})`);}else {let l=this.visit(u,s);e.push(`(ORDER BY ${l})`);}}else if(r&&o.length===1&&o[0].List){let u=o[0].List;if(u.items&&u.items.length>=2){let l=c.unwrapList(u.items),p=this.visit(l[0],s),f=l.slice(1).map(h=>this.visit(h,s));e.push(`(${p} ORDER BY ${f.join(", ")})`);}else if(u.items&&u.items.length===1){let l=u.items[0];if(l.FunctionParameter&&l.FunctionParameter.mode==="FUNC_PARAM_VARIADIC"){let p=this.visit(l,s);e.push(`(${p} ORDER BY ${p})`);}else {let p=this.visit(l,s);e.push(`(${p})`);}}else {let l=o.map(p=>Object.keys(p).length===0?"*":this.visit(p,s));e.push(`(${l.join(", ")})`);}}else {let u=o.map(l=>Object.keys(l).length===0?"*":this.visit(l,s));e.push(`(${u.join(", ")})`);}}if(t.definition&&t.definition.length>0){let i=c.unwrapList(t.definition).map(r=>{if(r.DefElem){let n=r.DefElem,o=n.defname,u=n.arg;if(o&&u){let l=m.quoteIdentifier(o),p=l!==o?l:o;return u.String?`${p} = '${u.String.sval}'`:`${p} = ${this.visit(u,s)}`}}return this.visit(r,s)});e.push(`(${i.join(", ")})`);}break;case "OBJECT_TSDICTIONARY":if(e.push("CREATE TEXT SEARCH DICTIONARY"),t.defnames&&t.defnames.length>0&&e.push(c.unwrapList(t.defnames).map(i=>this.visit(i,s)).join(".")),t.definition&&t.definition.length>0){e.push("(");let i=c.unwrapList(t.definition).map(r=>{if(r.DefElem){let n=r.DefElem,o=n.defname,u=n.arg;if(o&&u)return `${o} = ${this.visit(u,s)}`}return this.visit(r,s)});e.push(i.join(", ")),e.push(")");}break;case "OBJECT_TSCONFIGURATION":if(e.push("CREATE TEXT SEARCH CONFIGURATION"),t.defnames&&t.defnames.length>0&&e.push(c.unwrapList(t.defnames).map(i=>this.visit(i,s)).join(".")),t.definition&&t.definition.length>0){e.push("(");let i=c.unwrapList(t.definition).map(r=>{if(r.DefElem){let n=r.DefElem,o=n.defname,u=n.arg;if(o&&u)return `${o} = ${this.visit(u,s)}`}return this.visit(r,s)});e.push(i.join(", ")),e.push(")");}break;case "OBJECT_TSPARSER":if(e.push("CREATE TEXT SEARCH PARSER"),t.defnames&&t.defnames.length>0){let i=c.unwrapList(t.defnames).map(r=>this.visit(r,s)).join(".");e.push(i);}if(t.definition&&t.definition.length>0){e.push("(");let i=c.unwrapList(t.definition).map(r=>{if(r.DefElem){let n=r.DefElem,o=n.defname,u=n.arg;if(o&&u)return `${o} = ${this.visit(u,s)}`}return this.visit(r,s)});e.push(i.join(", ")),e.push(")");}break;case "OBJECT_TSTEMPLATE":if(e.push("CREATE TEXT SEARCH TEMPLATE"),t.defnames&&t.defnames.length>0){let i=c.unwrapList(t.defnames).map(r=>this.visit(r,s)).join(".");e.push(i);}if(t.definition&&t.definition.length>0){e.push("(");let i=c.unwrapList(t.definition).map(r=>{if(r.DefElem){let n=r.DefElem,o=n.defname,u=n.arg;if(o&&u)return `${o} = ${this.visit(u,s)}`}return this.visit(r,s)});e.push(i.join(", ")),e.push(")");}break;case "OBJECT_COLLATION":if(e.push("CREATE COLLATION"),t.defnames&&t.defnames.length>0&&e.push(c.unwrapList(t.defnames).map(i=>this.visit(i,s)).join(".")),t.definition&&t.definition.length>0){let i=c.unwrapList(t.definition).map(n=>{if(n.DefElem){let o=n.DefElem,u=o.defname,l=o.arg;if(u&&l){if(u==="from")return `FROM ${this.visit(l,s)}`;let p;return l.String?p=`'${l.String.sval}'`:p=this.visit(l,s),`${u} = ${p}`}}return this.visit(n,s)});i.some(n=>n.startsWith("FROM "))?e.push(i.join(" ")):e.push(`(${i.join(", ")})`);}break;default:throw new Error(`Unsupported DefineStmt kind: ${t.kind}`)}return e.join(" ")}AlterDatabaseStmt(t,s){let e=["ALTER","DATABASE"];if(t.dbname&&e.push(m.quoteIdentifier(t.dbname)),t.options&&t.options.length>0){let i=c.unwrapList(t.options).map(r=>this.visit(r,s));e.push(i.join(" "));}return e.join(" ")}AlterDatabaseRefreshCollStmt(t,s){let e=["ALTER","DATABASE"];return t.dbname&&e.push(m.quoteIdentifier(t.dbname)),e.push("REFRESH","COLLATION","VERSION"),e.join(" ")}AlterDatabaseSetStmt(t,s){let e=["ALTER","DATABASE"];if(t.dbname&&e.push(m.quoteIdentifier(t.dbname)),t.setstmt){let i=this.VariableSetStmt(t.setstmt,s);e.push(i);}return e.join(" ")}DeclareCursorStmt(t,s){let e=["DECLARE"];t.portalname&&e.push(m.quoteIdentifier(t.portalname));let i=[];return t.options&&(t.options&2?i.push("SCROLL"):t.options&4&&i.push("NO SCROLL"),t.options&1&&i.push("BINARY"),t.options&8&&i.push("INSENSITIVE")),i.length>0&&e.push(...i),e.push("CURSOR"),t.options&&t.options&32&&e.push("WITH HOLD"),e.push("FOR"),t.query&&e.push(this.visit(t.query,s)),e.join(" ")}PublicationObjSpec(t,s){let e=[];return t.pubobjtype==="PUBLICATIONOBJ_TABLE"?(e.push("TABLE"),t.pubtable&&e.push(this.PublicationTable(t.pubtable,s))):t.pubobjtype==="PUBLICATIONOBJ_TABLES_IN_SCHEMA"?(e.push("TABLES IN SCHEMA"),t.name&&e.push(m.quoteIdentifier(t.name))):t.pubobjtype==="PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA"&&e.push("TABLES IN SCHEMA CURRENT_SCHEMA"),e.join(" ")}PublicationTable(t,s){let e=[];if(t.relation&&e.push(this.RangeVar(t.relation,s)),t.columns&&t.columns.length>0){let i=c.unwrapList(t.columns).map(r=>this.visit(r,s));e.push(`(${i.join(", ")})`);}return t.whereClause&&(e.push("WHERE"),e.push(this.visit(t.whereClause,s))),e.join(" ")}CreateAmStmt(t,s){let e=["CREATE","ACCESS","METHOD"];switch(t.amname&&e.push(m.quoteIdentifier(t.amname)),e.push("TYPE"),t.amtype){case "i":e.push("INDEX");break;case "t":e.push("TABLE");break;default:e.push(t.amtype||"");break}if(t.handler_name&&t.handler_name.length>0){e.push("HANDLER");let i=c.unwrapList(t.handler_name).map(r=>this.visit(r,s)).join(".");e.push(i);}return e.join(" ")}IntoClause(t,s){let e=[];if(t.rel&&e.push(this.RangeVar(t.rel,s)),t.colNames&&t.colNames.length>0){let i=c.unwrapList(t.colNames).map(r=>this.visit(r,s)).join(", ");e.push(`(${i})`);}if(t.accessMethod&&e.push("USING",t.accessMethod),t.options&&t.options.length>0){e.push("WITH");let i=c.unwrapList(t.options).map(r=>this.visit(r,s)).join(", ");e.push(`(${i})`);}if(t.onCommit&&t.onCommit!=="ONCOMMIT_NOOP")switch(e.push("ON COMMIT"),t.onCommit){case "ONCOMMIT_PRESERVE_ROWS":e.push("PRESERVE ROWS");break;case "ONCOMMIT_DELETE_ROWS":e.push("DELETE ROWS");break;case "ONCOMMIT_DROP":e.push("DROP");break}return t.tableSpaceName&&e.push("TABLESPACE",m.quoteIdentifier(t.tableSpaceName)),e.join(" ")}OnConflictExpr(t,s){let e=["ON CONFLICT"];if(t.arbiterElems&&t.arbiterElems.length>0){let i=c.unwrapList(t.arbiterElems).map(r=>this.visit(r,s)).join(", ");e.push(`(${i})`);}if(t.arbiterWhere&&(e.push("WHERE"),e.push(this.visit(t.arbiterWhere,s))),t.action==="ONCONFLICT_NOTHING")e.push("DO NOTHING");else if(t.action==="ONCONFLICT_UPDATE"){if(e.push("DO UPDATE SET"),t.onConflictSet&&t.onConflictSet.length>0){let i=c.unwrapList(t.onConflictSet).map(r=>this.visit(r,s)).join(", ");e.push(i);}t.onConflictWhere&&(e.push("WHERE"),e.push(this.visit(t.onConflictWhere,s)));}return e.join(" ")}ScanToken(t,s){return ""}CreateOpClassItem(t,s){let e=[];if(t.itemtype===1){e.push("OPERATOR");let i=t.number!==void 0?t.number:0;if(e.push(i.toString()),t.name){let r=s.spawn("CreateOpClassItem");e.push(this.ObjectWithArgs(t.name,r));}}else if(t.itemtype===2){e.push("FUNCTION");let i=t.number!==void 0?t.number:0;if(e.push(i.toString()),t.name){let r=s.spawn("CreateOpClassItem");e.push(this.ObjectWithArgs(t.name,r));}}else t.itemtype===3&&(e.push("STORAGE"),t.storedtype&&e.push(this.TypeName(t.storedtype,s)));if(t.order_family&&t.order_family.length>0){e.push("FOR ORDER BY");let i=c.unwrapList(t.order_family).map(r=>this.visit(r,s)).join(".");e.push(i);}if(t.class_args&&t.class_args.length>0){let i=c.unwrapList(t.class_args).map(r=>this.visit(r,s)).join(", ");e.push(`(${i})`);}return e.join(" ")}Var(t,s){return t.varno&&t.varattno?`$${t.varno}.${t.varattno}`:"$var"}TableFunc(t,s){let e=[];if(t.functype==="TFT_XMLTABLE"){if(e.push("XMLTABLE"),t.ns_names&&t.ns_names.length>0){e.push("XMLNAMESPACES");let i=c.unwrapList(t.ns_names).map(r=>this.visit(r,s)).join(", ");e.push(`(${i})`);}if(t.rowexpr&&e.push(`(${this.visit(t.rowexpr,s)})`),t.docexpr&&(e.push("PASSING"),e.push(this.visit(t.docexpr,s))),t.colexprs&&t.colexprs.length>0){e.push("COLUMNS");let i=c.unwrapList(t.colexprs).map(r=>this.visit(r,s)).join(", ");e.push(i);}}else if(t.functype==="TFT_JSON_TABLE"&&(e.push("JSON_TABLE"),t.docexpr&&e.push(`(${this.visit(t.docexpr,s)})`),t.rowexpr&&(e.push(","),e.push(`'${this.visit(t.rowexpr,s)}'`)),t.colexprs&&t.colexprs.length>0)){e.push("COLUMNS");let i=c.unwrapList(t.colexprs).map(r=>this.visit(r,s)).join(", ");e.push(`(${i})`);}return e.join(" ")}RangeTableFunc(t,s){let e=[];if(t.lateral&&e.push("LATERAL"),t.docexpr&&e.push(this.visit(t.docexpr,s)),t.rowexpr&&(e.push("PASSING"),e.push(this.visit(t.rowexpr,s))),t.columns&&t.columns.length>0){e.push("COLUMNS");let i=c.unwrapList(t.columns).map(r=>this.visit(r,s)).join(", ");e.push(`(${i})`);}return t.alias&&e.push(this.Alias(t.alias,s)),e.join(" ")}RangeTableFuncCol(t,s){let e=[];return t.colname&&e.push(m.quoteIdentifier(t.colname)),t.for_ordinality?e.push("FOR ORDINALITY"):t.typeName&&e.push(this.TypeName(t.typeName,s)),t.colexpr&&(e.push("PATH"),e.push(`'${this.visit(t.colexpr,s)}'`)),t.coldefexpr&&(e.push("DEFAULT"),e.push(this.visit(t.coldefexpr,s))),e.join(" ")}JsonArrayQueryConstructor(t,s){let e=["JSON_ARRAYAGG"];return t.query&&e.push(`(${this.visit(t.query,s)})`),t.format&&e.push("FORMAT JSON"),t.output&&e.push("RETURNING TEXT"),t.absent_on_null?e.push("ABSENT ON NULL"):e.push("NULL ON NULL"),e.join(" ")}RangeFunction(t,s){let e=[];if(t.lateral&&e.push("LATERAL"),t.is_rowsfrom){if(e.push("ROWS FROM"),t.functions&&t.functions.length>0){let i=c.unwrapList(t.functions).filter(r=>r!=null).map(r=>{try{if(this.getNodeType(r)==="List"){let o=this.getNodeData(r);if(o&&o.items&&Array.isArray(o.items)){let u=o.items;if(u.length>=2){let l=this.visit(u[0],s),p=this.getNodeData(u[1]);if(p&&p.items&&Array.isArray(p.items)){let f=p.items.map(h=>this.visit(h,s)).filter(h=>h&&h.trim());if(f.length>0)return `${l} AS (${f.join(", ")})`}return l}else if(u.length===1)return this.visit(u[0],s)}}return this.visit(r,s)}catch(n){return console.warn(`Error processing function in RangeFunction: ${n instanceof Error?n.message:String(n)}`),""}}).filter(r=>r&&r.trim());i.length>0&&e.push(`(${i.join(", ")})`);}}else if(t.functions&&t.functions.length>0){let i=c.unwrapList(t.functions).filter(r=>r!=null).map(r=>{try{if(this.getNodeType(r)==="List"){let o=this.getNodeData(r);if(o&&o.items&&Array.isArray(o.items)){let u=o.items;if(u.length>=1)return this.visit(u[0],s)}}return this.visit(r,s)}catch(n){return console.warn(`Error processing function in RangeFunction: ${n instanceof Error?n.message:String(n)}`),""}}).filter(r=>r&&r.trim());i.length>0&&e.push(i.join(", "));}if(t.ordinality&&e.push("WITH ORDINALITY"),t.alias)if(t.coldeflist&&t.coldeflist.length>0){let i=t.alias.aliasname,r=c.unwrapList(t.coldeflist).map(n=>this.visit(n,s)).filter(n=>n&&n.trim());e.push(`${i} (${r.join(", ")})`);}else e.push(this.Alias(t.alias,s));else if(t.coldeflist&&t.coldeflist.length>0){let i=c.unwrapList(t.coldeflist).map(r=>this.visit(r,s)).filter(r=>r&&r.trim());e.push(`AS (${i.join(", ")})`);}return e.join(" ")}XmlExpr(t,s){if(t.op==="IS_XMLPI")if(t.name&&t.args&&t.args.length>0){let i=c.unwrapList(t.args).map(r=>this.visit(r,s));return `xmlpi(name ${m.quoteIdentifier(t.name)}, ${i.join(", ")})`}else return t.name?`xmlpi(name ${m.quoteIdentifier(t.name)})`:"XMLPI()";let e=[];switch(t.op){case "IS_XMLCONCAT":e.push("XMLCONCAT");break;case "IS_XMLELEMENT":e.push("XMLELEMENT");let i=[];if(t.name&&i.push(`NAME ${m.quoteIdentifier(t.name)}`),t.named_args&&t.named_args.length>0){let n=c.unwrapList(t.named_args).map(o=>this.visit(o,s));i.push(`XMLATTRIBUTES(${n.join(", ")})`);}if(t.args&&t.args.length>0){let n=c.unwrapList(t.args).map(o=>this.visit(o,s));i.push(...n);}i.length>0&&e.push(`(${i.join(", ")})`);break;case "IS_XMLFOREST":e.push("XMLFOREST");break;case "IS_XMLPARSE":e.push("XMLPARSE");let r=[];if(t.xmloption&&(t.xmloption==="XMLOPTION_DOCUMENT"?r.push("DOCUMENT"):t.xmloption==="XMLOPTION_CONTENT"&&r.push("CONTENT")),t.args&&t.args.length>0){let n=c.unwrapList(t.args).map(o=>this.visit(o,s));n.length>0&&r.push(n[0]);}r.length>0&&e.push(`(${r.join(" ")})`);break;case "IS_XMLROOT":if(e.push("XMLROOT"),t.args&&t.args.length>0){let n=c.unwrapList(t.args),o=[];if(n[0]&&o.push(this.visit(n[0],s)),n[1]){let u=n[1];u.A_Const&&u.A_Const.isnull?o.push("version NO VALUE"):o.push(`version ${this.visit(u,s)}`);}if(n[2]){let u=n[2];u.A_Const&&u.A_Const.ival!==void 0?u.A_Const.ival.ival===1?o.push("STANDALONE NO"):u.A_Const.ival.ival===2?o.push("STANDALONE NO VALUE"):u.A_Const.ival.ival===3||(Object.keys(u.A_Const.ival).length===0?o.push("STANDALONE YES"):o.push(`STANDALONE ${this.visit(u,s)}`)):o.push(`STANDALONE ${this.visit(u,s)}`);}o.length>0&&e.push(`(${o.join(", ")})`);}break;case "IS_XMLSERIALIZE":e.push("XMLSERIALIZE");break;case "IS_DOCUMENT":if(t.args&&t.args.length>0){let n=c.unwrapList(t.args).map(o=>this.visit(o,s));e.push(`${n[0]} IS DOCUMENT`);}else e.push("IS DOCUMENT");break;default:throw new Error(`Unsupported XmlExpr op: ${t.op}`)}if(t.op!=="IS_XMLELEMENT"&&t.op!=="IS_XMLPARSE"&&t.op!=="IS_XMLROOT"&&t.op!=="IS_DOCUMENT"){if(t.name){let i=m.quoteIdentifier(t.name);e.push(`NAME ${i}`);}if(t.args&&t.args.length>0){let i=c.unwrapList(t.args).map(r=>this.visit(r,s));e.push(`(${i.join(", ")})`);}}if(t.named_args&&t.named_args.length>0&&t.op!=="IS_XMLELEMENT"){let i=c.unwrapList(t.named_args).map(r=>this.visit(r,s));t.op==="IS_XMLFOREST"?e.push(`(${i.join(", ")})`):e.push(`XMLATTRIBUTES(${i.join(", ")})`);}return e.join(" ")}schemaname(t,s){if(typeof t=="string")return m.quoteIdentifier(t);if(t&&t.String&&t.String.sval)return m.quoteIdentifier(t.String.sval);if(t&&typeof t=="object"){if(t.sval!==void 0)return m.quoteIdentifier(t.sval);if(t.List&&Array.isArray(t.List.items)){let e=t.List.items;if(e.length>0&&e[0].String&&e[0].String.sval)return m.quoteIdentifier(e[0].String.sval)}return t.val!==void 0?m.quoteIdentifier(t.val):""}return ""}RangeTableSample(t,s){let e=[];if(t.relation&&e.push(this.visit(t.relation,s)),e.push("TABLESAMPLE"),t.method&&t.method.length>0){let i=t.method.map(r=>this.visit(r,s));e.push(i.join("."));}if(t.args&&t.args.length>0){let i=t.args.map(r=>this.visit(r,s));e.push(`(${i.join(", ")})`);}return t.repeatable&&(e.push("REPEATABLE"),e.push(`(${this.visit(t.repeatable,s)})`)),e.join(" ")}XmlSerialize(t,s){let e=["XMLSERIALIZE"];return e.push("("),t.typeName&&(t.xmloption==="XMLOPTION_DOCUMENT"?e.push("DOCUMENT"):e.push("CONTENT"),e.push(this.visit(t.expr,s)),e.push("AS"),e.push(this.TypeName(t.typeName,s))),e.push(")"),e.join(" ")}ctes(t,s){if(!t||!Array.isArray(t))return "";let e=["WITH"];t.length>0&&t[0]&&t[0].CommonTableExpr&&t[0].CommonTableExpr.recursive&&e.push("RECURSIVE");let i=t.map(r=>this.visit(r,s));return e.push(i.join(", ")),e.join(" ")}RuleStmt(t,s){let e=["CREATE"];if(t.replace&&e.push("OR REPLACE"),e.push("RULE"),t.rulename&&e.push(m.quoteIdentifier(t.rulename)),e.push("AS ON"),t.event)switch(t.event){case "CMD_SELECT":e.push("SELECT");break;case "CMD_INSERT":e.push("INSERT");break;case "CMD_UPDATE":e.push("UPDATE");break;case "CMD_DELETE":e.push("DELETE");break;default:e.push(t.event.toString());}if(e.push("TO"),t.relation&&e.push(this.RangeVar(t.relation,s)),t.whereClause&&(e.push("WHERE"),e.push(this.visit(t.whereClause,s))),e.push("DO"),t.instead&&e.push("INSTEAD"),t.actions&&t.actions.length>0)if(t.actions.length===1)e.push(this.visit(t.actions[0],s));else {e.push("(");let i=c.unwrapList(t.actions).map(r=>this.visit(r,s));e.push(i.join("; ")),e.push(")");}else e.push("NOTHING");return e.join(" ")}RangeSubselect(t,s){let e=[];return t.lateral&&e.push("LATERAL"),t.subquery&&(e.push("("),e.push(this.visit(t.subquery,s)),e.push(")")),t.alias&&e.push(this.Alias(t.alias,s)),e.join(" ")}relname(t,s){return typeof t=="string"?m.quoteIdentifier(t):t&&t.String&&t.String.sval?m.quoteIdentifier(t.String.sval):t&&typeof t=="object"&&t.relname?m.quoteIdentifier(t.relname):this.visit(t,s)}rel(t,s){return typeof t=="string"?m.quoteIdentifier(t):t&&t.String&&t.String.sval?m.quoteIdentifier(t.String.sval):t&&t.RangeVar?this.RangeVar(t.RangeVar,s):t&&typeof t=="object"&&t.relname?m.quoteIdentifier(t.relname):this.visit(t,s)}objname(t,s){return typeof t=="string"?m.quoteIdentifier(t):t&&t.String&&t.String.sval?m.quoteIdentifier(t.String.sval):Array.isArray(t)?t.map(i=>i&&i.String&&i.String.sval?m.quoteIdentifier(i.String.sval):this.visit(i,s)).join("."):this.visit(t,s)}SQLValueFunction(t,s){switch(t.op){case "SVFOP_CURRENT_DATE":return "CURRENT_DATE";case "SVFOP_CURRENT_TIME":return "CURRENT_TIME";case "SVFOP_CURRENT_TIME_N":return `CURRENT_TIME(${t.typmod||0})`;case "SVFOP_CURRENT_TIMESTAMP":return "CURRENT_TIMESTAMP";case "SVFOP_CURRENT_TIMESTAMP_N":return `CURRENT_TIMESTAMP(${t.typmod||0})`;case "SVFOP_LOCALTIME":return "LOCALTIME";case "SVFOP_LOCALTIME_N":return `LOCALTIME(${t.typmod||0})`;case "SVFOP_LOCALTIMESTAMP":return "LOCALTIMESTAMP";case "SVFOP_LOCALTIMESTAMP_N":return `LOCALTIMESTAMP(${t.typmod||0})`;case "SVFOP_CURRENT_ROLE":return "CURRENT_ROLE";case "SVFOP_CURRENT_USER":return "CURRENT_USER";case "SVFOP_USER":return "USER";case "SVFOP_SESSION_USER":return "SESSION_USER";case "SVFOP_CURRENT_CATALOG":return "CURRENT_CATALOG";case "SVFOP_CURRENT_SCHEMA":return "CURRENT_SCHEMA";default:throw new Error(`Unsupported SQLValueFunction op: ${t.op}`)}}GroupingFunc(t,s){let e=["GROUPING"];if(t.args&&t.args.length>0){let i=c.unwrapList(t.args).map(r=>this.visit(r,s));e.push(`(${i.join(", ")})`);}else e.push("()");return e.join("")}MultiAssignRef(t,s){let e=[];return t.source&&e.push(this.visit(t.source,s)),t.colno>0&&e.push(`[${t.colno}]`),e.join("")}SetToDefault(t,s){return "DEFAULT"}CurrentOfExpr(t,s){let e=["CURRENT OF"];return t.cursor_name&&e.push(m.quoteIdentifier(t.cursor_name)),t.cursor_param>0&&e.push(`$${t.cursor_param}`),e.join(" ")}TableLikeClause(t,s){let e=["LIKE"];if(t.relation&&e.push(this.visit(t.relation,s)),t.options&&typeof t.options=="number")if(t.options===2147483647||t.options===2147483647)e.push("INCLUDING ALL");else {let i=[];t.options&1&&i.push("INCLUDING COMMENTS"),t.options&4&&i.push("INCLUDING CONSTRAINTS"),t.options&8&&i.push("INCLUDING DEFAULTS"),t.options&16&&i.push("INCLUDING GENERATED"),t.options&32&&i.push("INCLUDING IDENTITY"),t.options&64&&i.push("INCLUDING INDEXES"),t.options&128&&i.push("INCLUDING STATISTICS"),t.options&256&&i.push("INCLUDING STORAGE"),i.length>0&&e.push(i.join(" "));}return e.join(" ")}AlterFunctionStmt(t,s){let e=["ALTER"];if(t.objtype==="OBJECT_PROCEDURE"?e.push("PROCEDURE"):e.push("FUNCTION"),t.func&&e.push(this.ObjectWithArgs(t.func,s)),t.actions&&t.actions.length>0){let i=s.spawn("AlterFunctionStmt"),r=c.unwrapList(t.actions).map(n=>this.visit(n,i));e.push(r.join(" "));}return e.join(" ")}AlterObjectSchemaStmt(t,s){let e=["ALTER"];try{e.push(this.getObjectTypeKeyword(t.objectType));}catch{e.push(t.objectType.toString());}if(t.missing_ok&&e.push("IF EXISTS"),t.relation&&(t.objectType==="OBJECT_TABLE"||t.objectType==="OBJECT_FOREIGN_TABLE"||t.objectType==="OBJECT_MATVIEW"))e.push(this.RangeVar(t.relation,s));else if(t.object)if(t.objectType==="OBJECT_DOMAIN"&&t.object.List){let i=c.unwrapList(t.object);if(i.length===2){let r=i[0].String?.sval||"",n=i[1].String?.sval||"";e.push(m.quoteQualifiedIdentifier(r,n));}else e.push(this.visit(t.object,s));}else if(t.objectType==="OBJECT_TYPE"&&t.object.List){let i=c.unwrapList(t.object);if(i.length===2){let r=i[0].String?.sval||"",n=i[1].String?.sval||"";e.push(m.quoteQualifiedIdentifier(r,n));}else e.push(this.visit(t.object,s));}else if(t.objectType==="OBJECT_CONVERSION"&&t.object.List){let i=c.unwrapList(t.object);if(i.length===2){let r=i[0].String?.sval||"",n=i[1].String?.sval||"";e.push(m.quoteQualifiedIdentifier(r,n));}else e.push(this.visit(t.object,s));}else if(t.objectType==="OBJECT_TSPARSER"&&t.object.List){let i=c.unwrapList(t.object);if(i.length===2){let r=i[0].String?.sval||"",n=i[1].String?.sval||"";e.push(m.quoteQualifiedIdentifier(r,n));}else e.push(this.visit(t.object,s));}else if(t.objectType==="OBJECT_TSCONFIGURATION"&&t.object.List){let i=c.unwrapList(t.object);if(i.length===2){let r=i[0].String?.sval||"",n=i[1].String?.sval||"";e.push(m.quoteQualifiedIdentifier(r,n));}else e.push(this.visit(t.object,s));}else if(t.objectType==="OBJECT_TSTEMPLATE"&&t.object.List){let i=c.unwrapList(t.object);if(i.length===2){let r=i[0].String?.sval||"",n=i[1].String?.sval||"";e.push(m.quoteQualifiedIdentifier(r,n));}else e.push(this.visit(t.object,s));}else if(t.objectType==="OBJECT_TSDICTIONARY"&&t.object.List){let i=c.unwrapList(t.object);if(i.length===2){let r=i[0].String?.sval||"",n=i[1].String?.sval||"";e.push(m.quoteQualifiedIdentifier(r,n));}else e.push(this.visit(t.object,s));}else if(t.objectType==="OBJECT_OPCLASS"&&t.object.List){let i=c.unwrapList(t.object);if(i.length===2){let r=i[0].String?.sval||"",n=i[1].String?.sval||"";e.push(`${m.quoteIdentifier(n)} USING ${r}`);}else if(i.length===3){let r=i[0].String?.sval||"",n=i[1].String?.sval||"",o=i[2].String?.sval||"";e.push(`${m.quoteQualifiedIdentifier(n,o)} USING ${r}`);}else e.push(this.visit(t.object,s));}else if(t.objectType==="OBJECT_OPFAMILY"&&t.object.List){let i=c.unwrapList(t.object);if(i.length===2){let r=i[0].String?.sval||"",n=i[1].String?.sval||"";e.push(`${m.quoteIdentifier(n)} USING ${r}`);}else if(i.length===3){let r=i[0].String?.sval||"",n=i[1].String?.sval||"",o=i[2].String?.sval||"";e.push(`${m.quoteQualifiedIdentifier(n,o)} USING ${r}`);}else e.push(this.visit(t.object,s));}else e.push(this.visit(t.object,s));return e.push("SET SCHEMA"),t.newschema&&e.push(m.quoteIdentifier(t.newschema)),e.join(" ")}AlterRoleSetStmt(t,s){let e=["ALTER","ROLE"];if(t.role?e.push(this.RoleSpec(t.role,s)):e.push("ALL"),t.database&&(e.push("IN DATABASE"),e.push(this.quoteIfNeeded(t.database))),t.setstmt){if(t.setstmt.kind==="VAR_RESET")e.push("RESET"),t.setstmt.name&&e.push(t.setstmt.name);else if(e.push("SET"),t.setstmt.name&&e.push(t.setstmt.name),t.setstmt.args&&t.setstmt.args.length>0){e.push("TO");let i=c.unwrapList(t.setstmt.args).map(r=>this.visit(r,s)).join(", ");e.push(i);}}return e.join(" ")}CreateForeignTableStmt(t,s){let e=["CREATE FOREIGN TABLE"];if(t.base&&t.base.relation){let i=s.spawn("CreateForeignTableStmt");e.push(this.RangeVar(t.base.relation,i));}if(t.base&&t.base.tableElts){let i=c.unwrapList(t.base.tableElts).map(r=>this.visit(r,s));e.push(`(${i.join(", ")})`);}else t.base?.partbound||e.push("()");if(t.base&&t.base.inhRelations&&t.base.inhRelations.length>0)if(t.base.partbound){let i=c.unwrapList(t.base.inhRelations).map(r=>this.visit(r,s));e.push(`PARTITION OF ${i.join(", ")}`),t.base.partbound.is_default&&e.push("DEFAULT");}else {let i=c.unwrapList(t.base.inhRelations).map(r=>this.visit(r,s));e.push(`INHERITS (${i.join(", ")})`);}if(t.servername&&(e.push("SERVER"),e.push(m.quoteIdentifier(t.servername))),t.options&&t.options.length>0){let i=s.spawn("CreateForeignTableStmt"),r=c.unwrapList(t.options).map(n=>this.visit(n,i));e.push(`OPTIONS (${r.join(", ")})`);}return e.join(" ")}containsMultilineStringLiteral(t){return /'[^']*\n[^']*'/g.test(t)}};});var Gr=P(()=>{Vr();Ys();Ze.deparse;});function ee(a){if("String"in a)return a.String.sval}function _t(a){return a.map(ee).filter(t=>t!=null)}function Wr(a){return Object.keys(a)[0]}function Hr(a){if("A_Const"in a){if(a.A_Const.ival)return a.A_Const.ival.ival;if(a.A_Const.fval)return a.A_Const.fval.fval;if(a.A_Const.sval)return a.A_Const.sval.sval;if(a.A_Const.boolval)return a.A_Const.boolval.boolval;if(a.A_Const.isnull)return null}}var ts=P(()=>{Gr();});function Jr(a){let t=a.toLowerCase();return ["serial","serial4","bigserial","serial8","smallserial","serial2"].includes(t)}function Yr(a){let t=a.toLowerCase();return ["varchar","character varying","char","character","bpchar"].includes(t)}function Xr(a){let t=a.toLowerCase();return ["numeric","decimal"].includes(t)}var Xs,es,cl,Ks=P(()=>{ts();Xs=class extends Error{},es=class extends Xs{constructor(s,e){super(e??`Unsupported node type: ${Wr(s)}`);this.node=s;}};cl={CreateEnumStmt:{react:"ignore"},CreateDomainStmt:{react:"warn"},CreateSeqStmt:{react:"error"},AlterSeqStmt:{react:"error"},CreateSchemaStmt:{react:"warn"},CreatePolicyStmt:{react:"ignore"},PartitionElem:{react:"error"},PartitionCmd:{react:"error"},VariableSetStmt:{react:"ignore"},CompositeTypeStmt:{react:"error"},AlterEnumStmt:{react:"error"},AlterObjectSchemaStmt:{react:"error"},AlterOwnerStmt:{react:"error"},AlterTypeStmt:{react:"error"},AlterFunctionStmt:{react:"error"},AlterDefaultPrivilegesStmt:{react:"error"},GrantStmt:{react:"error"},GrantRoleStmt:{react:"error"},CopyStmt:{react:"error"},CreateCastStmt:{react:"error"},AlterOpFamilyStmt:{react:"error"},AlterOperatorStmt:{react:"error"},TruncateStmt:{react:"error"},A_Indirection:{react:"error"},XmlExpr:{react:"error"},XmlSerialize:{react:"error"},RangeTableSample:{react:"error"},GroupingSet:{react:"error"}},new Map(Object.entries(cl));});var nt,ss,Kr=P(()=>{ts();Ks();nt=class extends es{constructor(t,s){super(t,`Unsupported expression: ${s}`);}},ss=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 s=Object.keys(t)[0],e=this[s];if(!e)throw new nt({[s]:t},`Unsupported expression: ${s}`);return e.call(this,t[s])}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 e=this.isJwtAccessor(t.A_Expr);return e||this.A_Expr(t.A_Expr)}if("BoolExpr"in t)return this.BoolExpr(t.BoolExpr);let s=Object.keys(t)[0];throw new nt({[s]:t},`deparseValue: ${s}`)}A_Expr(t){if(t.kind==="AEXPR_OP"){let s=t.name?.[0],e=s?ee(s):void 0;if(!e)throw new nt({A_Expr:t},"A_Expr missing operator");let i=this.isJwtAccessor(t);if(i)return {[i]:{}};let r=t.lexpr?this.deparseValue(t.lexpr):void 0,n=t.rexpr?this.deparseValue(t.rexpr):void 0,o=this.mapOperator(e);if(!o)throw new nt({A_Expr:t},`Unsupported operator: ${e}`);let u=t.rexpr!=null&&"ColumnRef"in t.rexpr;if(typeof r=="string"&&r.startsWith("{{")&&u)return {[n]:{[o]:r}};let l=u&&typeof n=="string"?{$ref:n}:n;return {[r]:{[o]:l}}}if(t.kind==="AEXPR_LIKE"||t.kind==="AEXPR_ILIKE"){let s=t.lexpr?this.deparseValue(t.lexpr):void 0,e=t.rexpr?this.deparseValue(t.rexpr):void 0,r=(t.name?.[0]?ee(t.name[0]):"~~")==="!~~"?"$notLike":"$like";return {[s]:{[r]:e}}}if(t.kind==="AEXPR_IN"){let s=t.lexpr?this.deparseValue(t.lexpr):void 0,e=t.rexpr&&"List"in t.rexpr&&t.rexpr.List.items?t.rexpr.List.items.map(i=>this.deparseValue(i)):[];return {[s]:{$in:e}}}throw new nt({A_Expr:t},`A_Expr kind: ${t.kind}`)}BoolExpr(t){let s=t.args??[];switch(t.boolop){case "AND_EXPR":return {$and:s.map(e=>this.deparse(e))};case "OR_EXPR":return {$or:s.map(e=>this.deparse(e))};case "NOT_EXPR":return {$not:this.deparse(s[0])};default:throw new nt({BoolExpr:t},`BoolExpr op: ${t.boolop}`)}}NullTest(t){let s=t.arg?this.deparseValue(t.arg):void 0;return t.nulltesttype==="IS_NULL"?{[s]:{$is:null}}:{[s]:{$isNot:null}}}SubLink(t){if(t.subLinkType==="ANY_SUBLINK"){let s=t.testexpr?this.deparseValue(t.testexpr):void 0,e=t.subselect?this.SelectStmt(t.subselect.SelectStmt):void 0;return {[s]:{$in:e}}}if(t.subLinkType==="EXISTS_SUBLINK")return {$exists:t.subselect?this.SelectStmt(t.subselect.SelectStmt):void 0};if(t.subLinkType==="EXPR_SUBLINK"){let s=t.subselect?t.subselect.SelectStmt:void 0;if(s?.fromClause?.length)return this.SelectStmt(s);if(s?.targetList?.[0]){let e=s.targetList[0],i="ResTarget"in e?e.ResTarget:void 0;if(i?.val){let r=this.deparseValue(i.val);return r}}}throw new nt({SubLink:t},`SubLink type: ${t.subLinkType}`)}SelectStmt(t){let{from:s,schema:e,join:i}=this.deparseFromClause(t.fromClause??[]),r=[];for(let h of t.targetList??[]){let E="ResTarget"in h?h.ResTarget:void 0;if(E?.val){let g=this.deparseValue(E.val);Array.isArray(g)?r.push(...g.map(String)):g!=null&&g!==""&&r.push(String(g));}}let n=t.whereClause?this.deparse(t.whereClause):void 0,o=this.deparseSortClause(t.sortClause),u=this.deparseLimit(t.limitCount),l=this.deparseLimit(t.limitOffset),p=this.deparseGroupClause(t.groupClause),f={type:"query",from:s,select:r};return e&&(f.schema=e),Object.keys(i).length>0&&(f.join=i),n&&(f.where=n),o.length>0&&(f.order=o),u!==void 0&&(f.limit=u),l!==void 0&&(f.offset=l),p.length>0&&(f.group=p),f}FuncCall(t){let s=this.isAuthFunc(t.funcname??[]);if(s)return s;throw new nt({FuncCall:t},`FuncCall: ${_t(t.funcname??[]).join(".")}`)}ColumnRef(t){let s=_t(t.fields??[]);return s.length===1?s[0]:s.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 nt({A_Const:t},"A_Const: unknown variant")}TypeCast(t){if(!t.arg)throw new nt({TypeCast:t},"TypeCast: missing arg");return this.deparseValue(t.arg)}BooleanTest(t){let s=t.arg?this.deparseValue(t.arg):void 0;return t.booltesttype==="IS_TRUE"?{[s]:{$eq:true}}:{[s]:{$eq:false}}}deparseFromClause(t){let s={};if(t.length===0)return {from:"",join:s};let e=t[0];if("RangeVar"in e){let i=e.RangeVar;return {from:i.relname??"",schema:i.schemaname,join:s}}if("JoinExpr"in e){let{from:i,schema:r}=this.walkJoinExpr(e.JoinExpr,s);return {from:i,schema:r,join:s}}return {from:"",join:s}}walkJoinExpr(t,s){let e={from:""};if(t.larg)if("RangeVar"in t.larg){let i=t.larg.RangeVar;e={from:i.relname??"",schema:i.schemaname};}else "JoinExpr"in t.larg&&(e=this.walkJoinExpr(t.larg.JoinExpr,s));if(t.rarg&&"RangeVar"in t.rarg){let i=t.rarg.RangeVar,r=i.relname??"",n=i.alias?.aliasname??r,o=t.jointype==="JOIN_LEFT"?"left":"inner",u={from:r,type:o};t.quals&&(u.on=this.deparse(t.quals));let l=n;if(l in s){let p=2;for(;`${l}_${p}`in s;)p++;l=`${l}_${p}`;}s[l]=u;}return e}deparseSortClause(t){if(!t)return [];let s=[];for(let e of t){if(!("SortBy"in e))continue;let i=e.SortBy;if(!i.node)continue;let r=String(this.deparseValue(i.node)),n=i.sortby_dir==="SORTBY_DESC"?"desc":"asc",o={column:r,direction:n};i.sortby_nulls==="SORTBY_NULLS_FIRST"?o.nullsFirst=true:i.sortby_nulls==="SORTBY_NULLS_LAST"&&(o.nullsFirst=false),s.push(o);}return s}deparseLimit(t){if(!t)return;let s=this.deparseValue(t);return typeof s=="number"?s:Number(s)}deparseGroupClause(t){return t?t.map(s=>String(this.deparseValue(s))):[]}isAuthFunc(t){let s=_t(t);if(s.length===2&&s[0]==="auth"){if(s[1]==="uid")return "{{auth.uid}}";if(s[1]==="jwt")return "{{auth.jwt}}";if(s[1]==="role")return "{{auth.role}}";throw new Error(`Unsupported auth function: "${s.slice(1).join(".")}"`)}return null}isJwtAccessor(t){if(t.kind!=="AEXPR_OP")return null;let s=t.name?.[0]?ee(t.name[0]):void 0;if(s!=="->"&&s!=="->>")return null;let e=t.rexpr&&"A_Const"in t.rexpr?t.rexpr.A_Const.sval?.sval:void 0;if(e===void 0)return null;if(t.lexpr&&"FuncCall"in t.lexpr)return this.isAuthFunc(t.lexpr.FuncCall.funcname??[])==="{{auth.jwt}}"?`{{auth.jwt.${e}}}`:null;if(t.lexpr&&"A_Expr"in t.lexpr){let i=this.isJwtAccessor(t.lexpr.A_Expr);if(i)return `${i.slice(0,-2)}.${e}}}`}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 is,zr=P(()=>{is=class a{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 a(t)}};});var se,zs=P(()=>{se=class extends Error{constructor(s,e,i,r){super(`check constraint "${i}" violated for ${s}.${e}`);this.table=s;this.column=e;this.constraint=i;this.value=r;this.name="CheckConstraintError";}};});var X,mt=P(()=>{zs();X=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,s){return {status:"fail",message:t,action:s}}validationPass(){return {status:"pass",message:null}}isNullish(t){return t==null}toColumnDDL(t){let{includeNullable:s=true}=t??{},e=[],i=this.context.column;e.push(this.quoteIfNeeded(i)),e.push(this.sqliteType),this.context.isPrimaryKey&&e.push("PRIMARY KEY"),this.context.isSerial&&this.context.isPrimaryKey&&e.push("AUTOINCREMENT"),s&&!this.context.nullable&&!this.context.isPrimaryKey&&e.push("NOT NULL"),this.context.isUnique&&!this.context.isPrimaryKey&&e.push("UNIQUE"),this.context.defaultValue!==null&&e.push(`DEFAULT ${this.context.defaultValue}`);let r=this.checkConstraint();return r&&e.push(`CHECK (${r})`),e.join(" ")}checkError(t,s){return new se(this.context.table,this.context.column,t,s)}quoteIfNeeded(t){return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)?t:`"${t}"`}};});var wt,rs=P(()=>{mt();wt=class extends X{get sqliteType(){return "INTEGER"}};});var ie,Qs=P(()=>{rs();ie=class extends wt{constructor(t){super({...t,isSerial:true});}};});function fl(a,t){let{precision:s,scale:e}=t,i=10**e,r=10**(s-e);return Math.abs(Math.round(a*i)-a*i)<1e-4&&Math.abs(a)<r}var re,Zs=P(()=>{mt();re=class extends X{numericPrecision;constructor(t,s){super(t),this.numericPrecision=s;}get isShimBacked(){return this.numericPrecision!==void 0}get sqliteType(){return "REAL"}checkConstraint(){if(this.numericPrecision){let{precision:t,scale:s}=this.numericPrecision,e=this.context.column,i=10**s,r=10**(t-s);return `ABS(ROUND(${e} * ${i}) - ${e} * ${i}) < 0.0001 AND ABS(${e}) < ${r}`}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:s,scale:e}=this.numericPrecision;if(!fl(t,this.numericPrecision))return this.validationFail(`Does not fit numeric(${s}, ${e}).`,"Patch rows within numeric precision.")}return this.validationPass()}};});var q,ut=P(()=>{mt();q=class extends X{lengthConstraint;constructor(t,s){super(t),this.lengthConstraint=s;}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 ne,ti=P(()=>{mt();ne=class extends X{get sqliteType(){return "BLOB"}};});var ae,ei=P(()=>{mt();ae=class extends X{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}checkConstraint(){return `${this.context.column} IN (0, 1)`}serialize(t){if(this.isNullish(t))return t;if(t===true||t===1)return 1;if(t===false||t===0)return 0;throw this.checkError("boolean_range",t)}deserialize(t){return this.isNullish(t)?t:t===1?true:t===0?false:t}validateStorage(t){return this.isNullish(t)?this.validationPass():t===1||t===0?this.validationPass():this.validationFail("Expected 0 or 1.","Patch rows with boolean values.")}};});function Qr(a){try{return {ok:!0,value:JSON.parse(a)}}catch{return {ok:false}}}var oe,si=P(()=>{mt();oe=class extends X{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 s=Qr(t);return s.ok?s.value:t}return t}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"?this.validationFail("Expected JSON text.","Patch rows with JSON values."):Qr(t).ok?this.validationPass():this.validationFail("Invalid JSON text.","Patch rows with valid JSON.")}};});function hl(a){if(!/^\d{4}-\d{2}-\d{2}$/.test(a))return false;let t=new Date(`${a}T00:00:00.000Z`);return !Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===a}var ue,ii=P(()=>{ut();ue=class extends q{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"||!hl(t)?this.validationFail("Invalid date.","Patch rows with YYYY-MM-DD dates."):this.validationPass()}};});function ml(a){let t=a.match(/^(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?([+-](\d{2}):?(\d{2}))?$/);if(!t)return false;let s=Number(t[1]),e=Number(t[2]),i=t[3]===void 0?0:Number(t[3]),r=t[5]===void 0?null:Number(t[5]),n=t[6]===void 0?null:Number(t[6]),o=r===null||n!==null&&r<=15&&n<=59;return s<=24&&e<=59&&i<=59&&(s!==24||e===0&&i===0)&&o}var le,ri=P(()=>{ut();le=class extends q{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"||!ml(t)?this.validationFail("Invalid time.","Patch rows with HH:MM[:SS] times."):this.validationPass()}};});function El(a){let t=a.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 s=Number(t[1]),e=Number(t[2]),i=Number(t[3]),r=Number(t[4]),n=Number(t[5]),o=t[6]===void 0?0:Number(t[6]),u=t[8]===void 0?null:Number(t[8]),l=t[9]===void 0?null:Number(t[9]),p=new Date(Date.UTC(s,e-1,i)),f=p.getUTCFullYear()===s&&p.getUTCMonth()===e-1&&p.getUTCDate()===i,h=r<=24&&n<=59&&o<=59&&(r!==24||n===0&&o===0),E=u===null||l!==null&&u<=15&&l<=59;return f&&h&&E}var pe,ni=P(()=>{ut();pe=class extends q{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"||!El(t)?this.validationFail("Invalid timestamp.","Patch rows with ISO timestamps."):this.validationPass()}};});var ce,ai=P(()=>{ut();ce=class extends q{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 fe,oi=P(()=>{ut();fe=class extends q{enumValues;constructor(t,s){super(t),this.enumValues=s;}get isShimBacked(){return true}checkConstraint(){let t=this.context.column,s=this.enumValues.map(e=>`'${e.replace(/'/g,"''")}'`).join(", ");return `${t} IN (${s})`}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 Zr(a){try{return {ok:!0,value:JSON.parse(a)}}catch{return {ok:false}}}var Ft,ui=P(()=>{mt();Ft=class extends X{elementField;constructor(t,s){super(t),this.elementField=s;}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(s=>this.elementField.serialize(s))):JSON.stringify(t)}deserialize(t){if(this.isNullish(t))return t;if(typeof t=="string"){let s=Zr(t);if(s.ok&&Array.isArray(s.value))return this.elementField?s.value.map(e=>this.elementField.deserialize(e)):s.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 s=Zr(t);if(!s.ok)return this.validationFail("Invalid JSON array text.","Patch rows with array values.");if(!Array.isArray(s.value))return this.validationFail("Expected JSON array.","Patch rows with array values.");if(this.elementField)for(let e of s.value){let i=this.elementField.validateStorage(e);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 tn(a){return Tl.test(a.toLowerCase())}var gl,Tl,he,li=P(()=>{ut();gl="????????-????-????-????-????????????",Tl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;he=class extends q{get isShimBacked(){return true}checkConstraint(){let t=this.quoteIfNeeded(this.context.column);return `${t} IS NULL OR ${t} GLOB '${gl}'`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string")throw this.checkError("uuid_format",t);let s=t.toLowerCase();if(!tn(s))throw this.checkError("uuid_format",t);return s}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!tn(t)?this.validationFail("Invalid UUID.","Patch rows with valid UUIDs."):this.validationPass()}};});function Sl(a){let t=a.split("/");if(t.length>2)return null;let s=t[0];if(!s)return null;if(t.length===1)return {address:s,prefix:null};let e=t[1];return !e||!/^\d+$/.test(e)?null:{address:s,prefix:Number(e)}}function Al(a){let t=a.split(".");return t.length!==4?false:t.every(s=>{if(!/^\d+$/.test(s))return false;let e=Number(s);return e>=0&&e<=255})}function Cl(a){if(!a.includes(":"))return false;try{return new URL(`http://[${a}]/`),!0}catch{return false}}function en(a){let t=Sl(a);return t?Al(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=32:Cl(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=128:false:false}var me,pi=P(()=>{ut();me=class extends q{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 s=t.trim();if(!en(s))throw this.checkError("inet_format",t);return s}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!en(t.trim())?this.validationFail("Invalid inet address.","Patch rows with valid inet strings."):this.validationPass()}};});var Ee,ci=P(()=>{ut();Ee=class extends q{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 ge(a,t){if(t?.isArray){let e=ge(a,{...t,isArray:false});return new Ft(a,e)}if(t?.enumValues)return new fe(a,t.enumValues);let s=a.pgTypeName.toLowerCase().trim();if(s.startsWith("_")||s.endsWith("[]")){let e=s.startsWith("_")?s.slice(1):s.slice(0,-2),i={...a,pgTypeName:e},r=ge(i);return new Ft(a,r)}return Nl.has(s)?new ie(a):Rl.has(s)?new wt(a):wl.has(s)?new ae(a):dl.has(s)?new oe(a):vl.has(s)?new ue(a):Dl.has(s)?new le(a):Pl.has(s)?new pe(a):$l.has(s)?new ce(a):_l.has(s)?new ne(a):bl.has(s)?new re(a,t?.numericPrecision):yl.has(s)?new he(a):Ll.has(s)?new q(a,63):Il.has(s)?new me(a):Ol.has(s)?new q(a,t?.lengthConstraint):new Ee(a)}var Rl,Nl,bl,Ol,_l,wl,dl,yl,Ll,Il,vl,Dl,Pl,$l,sn=P(()=>{rs();Qs();Zs();ut();ti();ei();si();ii();ri();ni();ai();oi();ui();li();pi();ci();Rl=new Set(["int2","smallint","int4","integer","int","int8","bigint"]),Nl=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]),bl=new Set(["float4","real","float8","double precision","numeric","decimal"]),Ol=new Set(["text","varchar","character varying","char","character","bpchar"]),_l=new Set(["bytea"]),wl=new Set(["bool","boolean"]),dl=new Set(["json","jsonb"]),yl=new Set(["uuid"]),Ll=new Set(["name"]),Il=new Set(["inet"]),vl=new Set(["date"]),Dl=new Set(["time","timetz","time without time zone","time with time zone"]),Pl=new Set(["timestamp","timestamptz","timestamp without time zone","timestamp with time zone"]),$l=new Set(["interval"]);});var rn=P(()=>{});var Te,nn=P(()=>{Te=class{table;schema;fields;constructor(t,s="public",e=new Map){this.table=t,this.schema=s,this.fields=e;}get(t){return this.fields.get(t)}has(t){return this.fields.has(t)}set(t,s){this.fields.set(t,s);}columns(){return Array.from(this.fields.keys())}all(){return Array.from(this.fields.values())}serializeRow(t){let s={};for(let[e,i]of Object.entries(t)){let r=this.fields.get(e);s[e]=r?r.serialize(i):i;}return s}deserializeRow(t){let s={};for(let[e,i]of Object.entries(t)){let r=this.fields.get(e);s[e]=r?r.deserialize(i):i;}return s}applyDefaults(t){let s={...t};for(let[e,i]of this.fields)!(e in s)&&i.context.defaultFn&&(s[e]=i.context.defaultFn());return s}};});var an=P(()=>{mt();zs();rs();Qs();Zs();ut();ti();ei();si();ii();ri();ni();ai();oi();ui();li();pi();ci();sn();rn();nn();});var on={};yn(on,{_resetWarnedMissingToClauseForTests:()=>jl,collectComments:()=>xl,collectEnums:()=>kl,collectPolicies:()=>Ul,collectSchema:()=>Bl,collectTableConstraints:()=>Ml,collectVariables:()=>Fl});function jl(){fi.clear();}function kl(a){let t=new Map;for(let s of a.stmts??[]){if(!s.stmt||!("CreateEnumStmt"in s.stmt))continue;let e=s.stmt.CreateEnumStmt,i=_t(e.typeName??[]).join(".");if(!i||!e.vals)continue;let r=_t(e.vals);t.set(i.toLowerCase(),r);}return t}function Fl(a){let t=new Map;for(let s of a.stmts??[]){if(!s.stmt||!("VariableSetStmt"in s.stmt))continue;let e=s.stmt.VariableSetStmt,i=e.name,r=Hr(e.args?.[0]??{});t.set(i,{value:r,local:e.is_local});}return t}function Ul(a){let t=new ss,s=new Set,e=[];for(let i of a.stmts??[])if(i.stmt){if("CreatePolicyStmt"in i.stmt){let r=i.stmt.CreatePolicyStmt,n=r.table?.relname??"",o=r.table?.schemaname,u={select:"SELECT",insert:"INSERT",update:"UPDATE",delete:"DELETE"},l=r.cmd_name?u[r.cmd_name]??"ALL":"ALL",p=r.permissive===true,f=[],h=false;for(let b of r.roles??[])if("RoleSpec"in b){let d=b.RoleSpec;d.roletype==="ROLESPEC_PUBLIC"?d.location===-1&&(h=true):d.roletype==="ROLESPEC_CSTRING"&&d.rolename&&f.push(d.rolename);}if(h){let b=o?`${o}.${n}`:n,d=r.policy_name??"",O=`${b}::${d}`;fi.has(O)||(fi.add(O),console.warn(`[supalite] policy "${d}" on "${b}" has no TO clause \u2014 applies to all roles (PUBLIC). For clarity, prefer an explicit \`TO <role>\` clause (e.g. \`TO authenticated\`).`));}let E=r.qual?t.deparse(r.qual):void 0,g=r.with_check?t.deparse(r.with_check):void 0,R=new is({name:r.policy_name??"",table:n,schema:o,command:l,permissive:p,roles:f,using:E,withCheck:g});e.push(R);}if("AlterTableStmt"in i.stmt){let r=i.stmt.AlterTableStmt;if((r.cmds??[]).some(u=>"AlterTableCmd"in u&&(u.AlterTableCmd.subtype==="AT_EnableRowSecurity"||u.AlterTableCmd.subtype==="AT_ForceRowSecurity"))){let u=r.relation?.relname??"";s.add(u);}}}return {policies:e,tables:s}}function Bl(a,t){let s=new Map;for(let e of a.stmts??[]){if(!e.stmt||!("CreateStmt"in e.stmt))continue;let i=e.stmt.CreateStmt,r=i.relation?.relname??"",n=i.relation?.schemaname??"public";if(!r)continue;let o=new Te(r,n);for(let u of i.tableElts??[]){if(!("ColumnDef"in u))continue;let l=u.ColumnDef,p=l.colname;if(!p)continue;let f=l.typeName?.names?.map(_=>_.String?.sval||_.String?.str).filter(Boolean),h=f&&(f.length===2&&f[0]==="pg_catalog"?f[1]:f[0]);if(!h)continue;let E=!!l.typeName?.arrayBounds?.length,g=Array.isArray(l.typeName?.typmods)?l.typeName.typmods:[],R=_=>g[_]?.A_Const?.ival?.ival??g[_]?.A_Const?.val?.ival?.ival,b={isArray:E};if(Yr(h)&&g.length>0){let _=R(0);typeof _=="number"&&_>0&&(b.lengthConstraint=_);}if(Xr(h)&&g.length>=2){let _=R(0),j=R(1);typeof _=="number"&&typeof j=="number"&&_>0&&j>=0&&(b.numericPrecision={precision:_,scale:j});}let d=t.get(h.toLowerCase());d&&(b.enumValues=d);let O=Array.isArray(l.constraints)?l.constraints:[],J=O.some(_=>_.Constraint?.contype==="CONSTR_PRIMARY"),et=Jr(h)||O.some(_=>_.Constraint?.contype==="CONSTR_IDENTITY"),Y=O.some(_=>_.Constraint?.contype==="CONSTR_NOTNULL"),W=O.find(_=>_.Constraint?.contype==="CONSTR_UNIQUE"),z=O.find(_=>_.Constraint?.contype==="CONSTR_GENERATED"),w=O.find(_=>_.Constraint?.contype==="CONSTR_FOREIGN"),L=O.find(_=>_.Constraint?.contype==="CONSTR_CHECK"),A;if(w){let _=w.Constraint,j=_.pktable?.relname,S=_.pktable?.schemaname,T=_.pk_attrs?.[0]?.String?.sval;j&&T&&(A={refSchema:S,refTable:j,refColumn:T,constraintName:_.conname||void 0});}let K={schema:n,table:r,column:p,pgTypeName:h,nullable:!Y&&!J,defaultValue:null,defaultFn:null,isPrimaryKey:J,isUnique:!!W,isSerial:et,isGenerated:!!z,fkRef:A,hasCheck:!!L,checkConstraintName:L?.Constraint?.conname||void 0,uniqueConstraintName:W?.Constraint?.conname||void 0};o.set(p,ge(K,b));}s.set(`${n}.${r}`,o);}return s}function Ml(a){let t=[];for(let s of a.stmts??[]){if(!s.stmt||!("CreateStmt"in s.stmt))continue;let e=s.stmt.CreateStmt,i=e.relation?.relname??"",r=e.relation?.schemaname??"public";if(i)for(let n of e.tableElts??[]){if("ColumnDef"in n)continue;let o=n;if(!o.Constraint)continue;let u=o.Constraint,l=u.contype;if(l==="CONSTR_UNIQUE"){let p=(u.keys??[]).map(f=>f.String?.sval??f.String?.str).filter(Boolean);if(p.length===0)continue;t.push({schema:r,table:i,kind:"unique",name:u.conname||void 0,columns:p});}else if(l==="CONSTR_CHECK")t.push({schema:r,table:i,kind:"check",name:u.conname||void 0,columns:[]});else if(l==="CONSTR_FOREIGN"){let p=(u.fk_attrs??[]).map(E=>E.String?.sval??E.String?.str).filter(Boolean),f=(u.pk_attrs??[]).map(E=>E.String?.sval??E.String?.str).filter(Boolean),h=u.pktable?.relname;if(!h)continue;t.push({schema:r,table:i,kind:"foreign_key",name:u.conname||void 0,columns:p,refSchema:u.pktable?.schemaname,refTable:h,refColumns:f});}}}return t}function xl(a){let t=[];for(let s of a.stmts??[]){if(!s.stmt||!("CommentStmt"in s.stmt))continue;let e=s.stmt.CommentStmt,i=e.comment??"";if(!i)continue;let r=e.objtype,n=(e.object?.List?.items??e.object?.items??[]).map(o=>o.String?.sval??o.String?.str).filter(Boolean);if(n.length!==0){if(r==="OBJECT_TABLE"||r==="OBJECT_VIEW"){let[o,u]=n.length>=2?n:["public",n[0]];t.push({schema:o,table:u,text:i});}else if(r==="OBJECT_COLUMN"){let o="public",u,l;n.length>=3?[o,u,l]=n:[u,l]=n,t.push({schema:o,table:u,column:l,text:i});}}}return t}var fi,un=P(()=>{Kr();ts();zr();an();Ks();fi=new Set;});function at(a,t){Ne.existsSync(a)||(Ne.mkdirSync(a,{recursive:true}),t?.());}function Rt(a,t,s){Ne.existsSync(a)||(Ne.writeFileSync(a,t),s?.());}var ht=class a{root;constructor(t,s){let e=s??a.projectDir();this.root=v__default.join(e,t??"");}ensureRoot(){at(this.root);}static homeDir(){return v__default.join(In.homedir(),".lite")}static projectDir(){return v__default.join(process.cwd(),"supabase")}deleteAll(t=false){try{Ne.rmSync(this.root,{recursive:!0});}catch(s){if(!t)throw s}this.ensureRoot();}delete(t,s=false){try{Ne.unlinkSync(v__default.join(this.root,t));}catch(e){if(!s)throw e}}write(t,s,e=false){try{this.ensureRoot(),Ne.writeFileSync(v__default.join(this.root,t),s);}catch(i){if(!e)throw i}}read(t,s=false){try{return Ne.readFileSync(v__default.join(this.root,t),"utf8")}catch(e){if(!s)throw e}}relativePath(t){return t?v__default.relative(process.cwd(),v__default.join(this.root,t)):this.root}path(t){return t?v__default.join(this.root,t):this.root}};var Bt=process.env.SUPALITE_CLOUD_URL??(process.env.LOCAL?"http://localhost:2000":"https://www.lite.dev");var _e=class{root;constructor(t){this.root=t??v__default.join(In.homedir(),".lite","auth"),at(this.root);}async getItem(t){try{return Ne.readFileSync(v__default.join(this.root,t+".json"),"utf8")}catch{return null}}async setItem(t,s){Ne.writeFileSync(v__default.join(this.root,t+".json"),s);}async removeItem(t){try{Ne.unlinkSync(v__default.join(this.root,t+".json"));}catch{return}}};var yt=class{constructor(t){this.config=t;this.tempFs=new ht(".temp",this.config.root),this.projectFs=new ht("supabase",this.config.root),this.schemaFs=new ht("schemas",this.config.root),this.authStorage=this.config.authStorage??new _e(v__default.join(ht.homeDir(),"auth")),this._client=this.config.withSupabaseClient!==false?this.config.client??createClient(this.config.host??Bt,process.env.SUPALITE_CLOUD_ANON_KEY??"...",{auth:{storage:this.authStorage}}):void 0;}tempFs;projectFs;schemaFs;_client;authStorage;async fetch(t,s){if(!this.config.token)throw new Error("Not authenticated, sign in first.");let e=t instanceof URL?t:new URL(t,this.config.host??Bt);return await fetch(e,{...s,headers:{...s?.headers,Authorization:`Bearer ${this.config.token}`}})}};var Lt=class extends yt{constructor(s){super(s);this.config=s;}get client(){if(!this._client)throw new Error("Supabase client not initialized");return this._client}projectRef(){return this.tempFs.read("project-ref",true)}projectUrl(s){let e=new URL(this.config.host),i=e.hostname==="localhost"?"supalite.local":e.hostname,r=i.split(".").filter(o=>o!=="www"),n=r.length>=2?r.slice(-2).join("."):i;return `${e.protocol}//${s}.${n}${e.port?`:${e.port}`:""}`}};var gt={config_dir:"supabase",default_db_url:"file:supabase/.temp/data.db",default_db_dir:"supabase/.temp/data"};var Ht=Ut(Mt());function Fn(a,t){let s=a.slice(0,t).split(/\r\n|\n|\r/g);return [s.length,s.pop().length+1]}function Un(a,t,s){let e=a.split(/\r\n|\n|\r/g),i="",r=(Math.log10(t+1)|0)+1;for(let n=t-1;n<=t+1;n++){let o=e[n-1];o&&(i+=n.toString().padEnd(r," "),i+=": ",i+=o,i+=`
42
- `,n===t&&(i+=" ".repeat(r+s+2),i+=`^
43
- `));}return i}var y=class extends Error{line;column;codeblock;constructor(t,s){let[e,i]=Fn(s.toml,s.ptr),r=Un(s.toml,e,i);super(`Invalid TOML document: ${t}
12
+ var ci=Object.create;var De=Object.defineProperty;var ui=Object.getOwnPropertyDescriptor;var fi=Object.getOwnPropertyNames;var pi=Object.getPrototypeOf,mi=Object.prototype.hasOwnProperty;var L=(e,t)=>()=>(e&&(t=e(e=0)),t);var pt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),hi=(e,t)=>{for(var n in t)De(e,n,{get:t[n],enumerable:true});},di=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of fi(t))!mi.call(e,i)&&i!==n&&De(e,i,{get:()=>t[i],enumerable:!(r=ui(t,i))||r.enumerable});return e};var Rt=(e,t,n)=>(n=e!=null?ci(pi(e)):{},di(De(n,"default",{value:e,enumerable:true}),e));var $t=pt((Al,Me)=>{var me=process||{},Pn=me.argv||[],pe=me.env||{},xi=!(pe.NO_COLOR||Pn.includes("--no-color"))&&(!!pe.FORCE_COLOR||Pn.includes("--color")||me.platform==="win32"||(me.stdout||{}).isTTY&&pe.TERM!=="dumb"||!!pe.CI),Si=(e,t,n=e)=>r=>{let i=""+r,s=i.indexOf(t,e.length);return ~s?e+Ei(i,t,n,s)+t:e+i+t},Ei=(e,t,n,r)=>{let i="",s=0;do i+=e.substring(s,r)+n,s=r+t.length,r=e.indexOf(t,s);while(~r);return i+e.substring(s)},Ln=(e=xi)=>{let t=e?Si:()=>String;return {isColorSupported:e,reset:t("\x1B[0m","\x1B[0m"),bold:t("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:t("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:t("\x1B[3m","\x1B[23m"),underline:t("\x1B[4m","\x1B[24m"),inverse:t("\x1B[7m","\x1B[27m"),hidden:t("\x1B[8m","\x1B[28m"),strikethrough:t("\x1B[9m","\x1B[29m"),black:t("\x1B[30m","\x1B[39m"),red:t("\x1B[31m","\x1B[39m"),green:t("\x1B[32m","\x1B[39m"),yellow:t("\x1B[33m","\x1B[39m"),blue:t("\x1B[34m","\x1B[39m"),magenta:t("\x1B[35m","\x1B[39m"),cyan:t("\x1B[36m","\x1B[39m"),white:t("\x1B[37m","\x1B[39m"),gray:t("\x1B[90m","\x1B[39m"),bgBlack:t("\x1B[40m","\x1B[49m"),bgRed:t("\x1B[41m","\x1B[49m"),bgGreen:t("\x1B[42m","\x1B[49m"),bgYellow:t("\x1B[43m","\x1B[49m"),bgBlue:t("\x1B[44m","\x1B[49m"),bgMagenta:t("\x1B[45m","\x1B[49m"),bgCyan:t("\x1B[46m","\x1B[49m"),bgWhite:t("\x1B[47m","\x1B[49m"),blackBright:t("\x1B[90m","\x1B[39m"),redBright:t("\x1B[91m","\x1B[39m"),greenBright:t("\x1B[92m","\x1B[39m"),yellowBright:t("\x1B[93m","\x1B[39m"),blueBright:t("\x1B[94m","\x1B[39m"),magentaBright:t("\x1B[95m","\x1B[39m"),cyanBright:t("\x1B[96m","\x1B[39m"),whiteBright:t("\x1B[97m","\x1B[39m"),bgBlackBright:t("\x1B[100m","\x1B[49m"),bgRedBright:t("\x1B[101m","\x1B[49m"),bgGreenBright:t("\x1B[102m","\x1B[49m"),bgYellowBright:t("\x1B[103m","\x1B[49m"),bgBlueBright:t("\x1B[104m","\x1B[49m"),bgMagentaBright:t("\x1B[105m","\x1B[49m"),bgCyanBright:t("\x1B[106m","\x1B[49m"),bgWhiteBright:t("\x1B[107m","\x1B[49m")}};Me.exports=Ln();Me.exports.createColors=Ln;});var It=pt((Tu,lr)=>{var ir="[^\\\\/]",no="(?=.)",sr="[^/]",tn="(?:\\/|$)",or="(?:^|\\/)",en=`\\.{1,2}${tn}`,ro="(?!\\.)",io=`(?!${or}${en})`,so=`(?!\\.{0,1}${tn})`,oo=`(?!${en})`,ao="[^.\\/]",lo=`${sr}*?`,co="/",ar={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:no,QMARK:sr,END_ANCHOR:tn,DOTS_SLASH:en,NO_DOT:ro,NO_DOTS:io,NO_DOT_SLASH:so,NO_DOTS_SLASH:oo,QMARK_NO_DOT:ao,STAR:lo,START_ANCHOR:or,SEP:co},uo={...ar,SLASH_LITERAL:"[\\\\/]",QMARK:ir,STAR:`${ir}*?`,DOTS_SLASH:"\\.{1,2}(?:[\\\\/]|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:[\\\\/]|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:[\\\\/]|$))",QMARK_NO_DOT:"[^.\\\\/]",START_ANCHOR:"(?:^|[\\\\/])",END_ANCHOR:"(?:[\\\\/]|$)",SEP:"\\"},fo={alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};lr.exports={MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:fo,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars(e){return {"!":{type:"negate",open:"(?:(?!(?:",close:`))${e.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(e){return e===true?uo:ar}};});var Dt=pt(X=>{var{REGEX_BACKSLASH:po,REGEX_REMOVE_BACKSLASH:mo,REGEX_SPECIAL_CHARS:ho,REGEX_SPECIAL_CHARS_GLOBAL:go}=It();X.isObject=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);X.hasRegexChars=e=>ho.test(e);X.isRegexChar=e=>e.length===1&&X.hasRegexChars(e);X.escapeRegex=e=>e.replace(go,"\\$1");X.toPosixSlashes=e=>e.replace(po,"/");X.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let e=navigator.platform.toLowerCase();return e==="win32"||e==="windows"}return typeof process<"u"&&process.platform?process.platform==="win32":false};X.removeBackslashes=e=>e.replace(mo,t=>t==="\\"?"":t);X.escapeLast=(e,t,n)=>{let r=e.lastIndexOf(t,n);return r===-1?e:e[r-1]==="\\"?X.escapeLast(e,t,r-1):`${e.slice(0,r)}\\${e.slice(r)}`};X.removePrefix=(e,t={})=>{let n=e;return n.startsWith("./")&&(n=n.slice(2),t.prefix="./"),n};X.wrapOutput=(e,t={},n={})=>{let r=n.contains?"":"^",i=n.contains?"":"$",s=`${r}(?:${e})${i}`;return t.negated===true&&(s=`(?:^(?!${s}).*$)`),s};X.basename=(e,{windows:t}={})=>{let n=e.split(t?/[\\/]/:"/"),r=n[n.length-1];return r===""?n[n.length-2]:r};});var gr=pt((Cu,dr)=>{var cr=Dt(),{CHAR_ASTERISK:nn,CHAR_AT:yo,CHAR_BACKWARD_SLASH:jt,CHAR_COMMA:bo,CHAR_DOT:rn,CHAR_EXCLAMATION_MARK:sn,CHAR_FORWARD_SLASH:hr,CHAR_LEFT_CURLY_BRACE:on,CHAR_LEFT_PARENTHESES:an,CHAR_LEFT_SQUARE_BRACKET:wo,CHAR_PLUS:xo,CHAR_QUESTION_MARK:ur,CHAR_RIGHT_CURLY_BRACE:So,CHAR_RIGHT_PARENTHESES:fr,CHAR_RIGHT_SQUARE_BRACKET:Eo}=It(),pr=e=>e===hr||e===jt,mr=e=>{e.isPrefix!==true&&(e.depth=e.isGlobstar?1/0:1);},Ao=(e,t)=>{let n=t||{},r=e.length-1,i=n.parts===true||n.scanToEnd===true,s=[],o=[],a=[],l=e,c=-1,u=0,h=0,d=false,b=false,w=false,E=false,_=false,$=false,x=false,G=false,Z=false,B=false,U=0,W,A,C={value:"",depth:0,isGlob:false},m=()=>c>=r,V=()=>l.charCodeAt(c+1),S=()=>(W=A,l.charCodeAt(++c));for(;c<r;){A=S();let P;if(A===jt){x=C.backslashes=true,A=S(),A===on&&($=true);continue}if($===true||A===on){for(U++;m()!==true&&(A=S());){if(A===jt){x=C.backslashes=true,S();continue}if(A===on){U++;continue}if($!==true&&A===rn&&(A=S())===rn){if(d=C.isBrace=true,w=C.isGlob=true,B=true,i===true)continue;break}if($!==true&&A===bo){if(d=C.isBrace=true,w=C.isGlob=true,B=true,i===true)continue;break}if(A===So&&(U--,U===0)){$=false,d=C.isBrace=true,B=true;break}}if(i===true)continue;break}if(A===hr){if(s.push(c),o.push(C),C={value:"",depth:0,isGlob:false},B===true)continue;if(W===rn&&c===u+1){u+=2;continue}h=c+1;continue}if(n.noext!==true&&(A===xo||A===yo||A===nn||A===ur||A===sn)===true&&V()===an){if(w=C.isGlob=true,E=C.isExtglob=true,B=true,A===sn&&c===u&&(Z=true),i===true){for(;m()!==true&&(A=S());){if(A===jt){x=C.backslashes=true,A=S();continue}if(A===fr){w=C.isGlob=true,B=true;break}}continue}break}if(A===nn){if(W===nn&&(_=C.isGlobstar=true),w=C.isGlob=true,B=true,i===true)continue;break}if(A===ur){if(w=C.isGlob=true,B=true,i===true)continue;break}if(A===wo){for(;m()!==true&&(P=S());){if(P===jt){x=C.backslashes=true,S();continue}if(P===Eo){b=C.isBracket=true,w=C.isGlob=true,B=true;break}}if(i===true)continue;break}if(n.nonegate!==true&&A===sn&&c===u){G=C.negated=true,u++;continue}if(n.noparen!==true&&A===an){if(w=C.isGlob=true,i===true){for(;m()!==true&&(A=S());){if(A===an){x=C.backslashes=true,A=S();continue}if(A===fr){B=true;break}}continue}break}if(w===true){if(B=true,i===true)continue;break}}n.noext===true&&(E=false,w=false);let k=l,p="",f="";u>0&&(p=l.slice(0,u),l=l.slice(u),h-=u),k&&w===true&&h>0?(k=l.slice(0,h),f=l.slice(h)):w===true?(k="",f=l):k=l,k&&k!==""&&k!=="/"&&k!==l&&pr(k.charCodeAt(k.length-1))&&(k=k.slice(0,-1)),n.unescape===true&&(f&&(f=cr.removeBackslashes(f)),k&&x===true&&(k=cr.removeBackslashes(k)));let J={prefix:p,input:e,start:u,base:k,glob:f,isBrace:d,isBracket:b,isGlob:w,isExtglob:E,isGlobstar:_,negated:G,negatedExtglob:Z};if(n.tokens===true&&(J.maxDepth=0,pr(A)||o.push(C),J.tokens=o),n.parts===true||n.tokens===true){let P;for(let F=0;F<s.length;F++){let it=P?P+1:u,Y=s[F],lt=e.slice(it,Y);n.tokens&&(F===0&&u!==0?(o[F].isPrefix=true,o[F].value=p):o[F].value=lt,mr(o[F]),J.maxDepth+=o[F].depth),(F!==0||lt!=="")&&a.push(lt),P=Y;}if(P&&P+1<e.length){let F=e.slice(P+1);a.push(F),n.tokens&&(o[o.length-1].value=F,mr(o[o.length-1]),J.maxDepth+=o[o.length-1].depth);}J.slashes=s,J.parts=a;}return J};dr.exports=Ao;});var wr=pt((Ru,br)=>{var Re=It(),rt=Dt(),{MAX_LENGTH:ve,POSIX_REGEX_SOURCE:To,REGEX_NON_SPECIAL_CHARS:_o,REGEX_SPECIAL_CHARS_BACKREF:Co,REPLACEMENTS:yr}=Re,Ro=(e,t)=>{if(typeof t.expandRange=="function")return t.expandRange(...e,t);e.sort();let n=`[${e.join("-")}]`;try{new RegExp(n);}catch{return e.map(i=>rt.escapeRegex(i)).join("..")}return n},Et=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`,ln=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a string");e=yr[e]||e;let n={...t},r=typeof n.maxLength=="number"?Math.min(ve,n.maxLength):ve,i=e.length;if(i>r)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${r}`);let s={type:"bos",value:"",output:n.prepend||""},o=[s],a=n.capture?"":"?:",l=Re.globChars(n.windows),c=Re.extglobChars(l),{DOT_LITERAL:u,PLUS_LITERAL:h,SLASH_LITERAL:d,ONE_CHAR:b,DOTS_SLASH:w,NO_DOT:E,NO_DOT_SLASH:_,NO_DOTS_SLASH:$,QMARK:x,QMARK_NO_DOT:G,STAR:Z,START_ANCHOR:B}=l,U=y=>`(${a}(?:(?!${B}${y.dot?w:u}).)*?)`,W=n.dot?"":E,A=n.dot?x:G,C=n.bash===true?U(n):Z;n.capture&&(C=`(${C})`),typeof n.noext=="boolean"&&(n.noextglob=n.noext);let m={input:e,index:-1,start:0,dot:n.dot===true,consumed:"",output:"",prefix:"",backtrack:false,negated:false,brackets:0,braces:0,parens:0,quotes:0,globstar:false,tokens:o};e=rt.removePrefix(e,m),i=e.length;let V=[],S=[],k=[],p=s,f,J=()=>m.index===i-1,P=m.peek=(y=1)=>e[m.index+y],F=m.advance=()=>e[++m.index]||"",it=()=>e.slice(m.index+1),Y=(y="",O=0)=>{m.consumed+=y,m.index+=O;},lt=y=>{m.output+=y.output!=null?y.output:y.value,Y(y.value);},ai=()=>{let y=1;for(;P()==="!"&&(P(2)!=="("||P(3)==="?");)F(),m.start++,y++;return y%2===0?false:(m.negated=true,m.start++,true)},se=y=>{m[y]++,k.push(y);},ft=y=>{m[y]--,k.pop();},v=y=>{if(p.type==="globstar"){let O=m.braces>0&&(y.type==="comma"||y.type==="brace"),g=y.extglob===true||V.length&&(y.type==="pipe"||y.type==="paren");y.type!=="slash"&&y.type!=="paren"&&!O&&!g&&(m.output=m.output.slice(0,-p.output.length),p.type="star",p.value="*",p.output=C,m.output+=p.output);}if(V.length&&y.type!=="paren"&&(V[V.length-1].inner+=y.value),(y.value||y.output)&&lt(y),p&&p.type==="text"&&y.type==="text"){p.output=(p.output||p.value)+y.value,p.value+=y.value;return}y.prev=p,o.push(y),p=y;},oe=(y,O)=>{let g={...c[O],conditions:1,inner:""};g.prev=p,g.parens=m.parens,g.output=m.output;let R=(n.capture?"(":"")+g.open;se("parens"),v({type:y,value:O,output:m.output?"":b}),v({type:"paren",extglob:true,value:F(),output:R}),V.push(g);},li=y=>{let O=y.close+(n.capture?")":""),g;if(y.type==="negate"){let R=C;if(y.inner&&y.inner.length>1&&y.inner.includes("/")&&(R=U(n)),(R!==C||J()||/^\)+$/.test(it()))&&(O=y.close=`)$))${R}`),y.inner.includes("*")&&(g=it())&&/^\.[^\\/.]+$/.test(g)){let I=ln(g,{...t,fastpaths:false}).output;O=y.close=`)${I})${R})`;}y.prev.type==="bos"&&(m.negatedExtglob=true);}v({type:"paren",extglob:true,value:f,output:O}),ft("parens");};if(n.fastpaths!==false&&!/(^[*!]|[/()[\]{}"])/.test(e)){let y=false,O=e.replace(Co,(g,R,I,z,H,Ie)=>z==="\\"?(y=true,g):z==="?"?R?R+z+(H?x.repeat(H.length):""):Ie===0?A+(H?x.repeat(H.length):""):x.repeat(I.length):z==="."?u.repeat(I.length):z==="*"?R?R+z+(H?C:""):C:R?g:`\\${g}`);return y===true&&(n.unescape===true?O=O.replace(/\\/g,""):O=O.replace(/\\+/g,g=>g.length%2===0?"\\\\":g?"\\":"")),O===e&&n.contains===true?(m.output=e,m):(m.output=rt.wrapOutput(O,m,t),m)}for(;!J();){if(f=F(),f==="\0")continue;if(f==="\\"){let g=P();if(g==="/"&&n.bash!==true||g==="."||g===";")continue;if(!g){f+="\\",v({type:"text",value:f});continue}let R=/^\\+/.exec(it()),I=0;if(R&&R[0].length>2&&(I=R[0].length,m.index+=I,I%2!==0&&(f+="\\")),n.unescape===true?f=F():f+=F(),m.brackets===0){v({type:"text",value:f});continue}}if(m.brackets>0&&(f!=="]"||p.value==="["||p.value==="[^")){if(n.posix!==false&&f===":"){let g=p.value.slice(1);if(g.includes("[")&&(p.posix=true,g.includes(":"))){let R=p.value.lastIndexOf("["),I=p.value.slice(0,R),z=p.value.slice(R+2),H=To[z];if(H){p.value=I+H,m.backtrack=true,F(),!s.output&&o.indexOf(p)===1&&(s.output=b);continue}}}(f==="["&&P()!==":"||f==="-"&&P()==="]")&&(f=`\\${f}`),f==="]"&&(p.value==="["||p.value==="[^")&&(f=`\\${f}`),n.posix===true&&f==="!"&&p.value==="["&&(f="^"),p.value+=f,lt({value:f});continue}if(m.quotes===1&&f!=='"'){f=rt.escapeRegex(f),p.value+=f,lt({value:f});continue}if(f==='"'){m.quotes=m.quotes===1?0:1,n.keepQuotes===true&&v({type:"text",value:f});continue}if(f==="("){se("parens"),v({type:"paren",value:f});continue}if(f===")"){if(m.parens===0&&n.strictBrackets===true)throw new SyntaxError(Et("opening","("));let g=V[V.length-1];if(g&&m.parens===g.parens+1){li(V.pop());continue}v({type:"paren",value:f,output:m.parens?")":"\\)"}),ft("parens");continue}if(f==="["){if(n.nobracket===true||!it().includes("]")){if(n.nobracket!==true&&n.strictBrackets===true)throw new SyntaxError(Et("closing","]"));f=`\\${f}`;}else se("brackets");v({type:"bracket",value:f});continue}if(f==="]"){if(n.nobracket===true||p&&p.type==="bracket"&&p.value.length===1){v({type:"text",value:f,output:`\\${f}`});continue}if(m.brackets===0){if(n.strictBrackets===true)throw new SyntaxError(Et("opening","["));v({type:"text",value:f,output:`\\${f}`});continue}ft("brackets");let g=p.value.slice(1);if(p.posix!==true&&g[0]==="^"&&!g.includes("/")&&(f=`/${f}`),p.value+=f,lt({value:f}),n.literalBrackets===false||rt.hasRegexChars(g))continue;let R=rt.escapeRegex(p.value);if(m.output=m.output.slice(0,-p.value.length),n.literalBrackets===true){m.output+=R,p.value=R;continue}p.value=`(${a}${R}|${p.value})`,m.output+=p.value;continue}if(f==="{"&&n.nobrace!==true){se("braces");let g={type:"brace",value:f,output:"(",outputIndex:m.output.length,tokensIndex:m.tokens.length};S.push(g),v(g);continue}if(f==="}"){let g=S[S.length-1];if(n.nobrace===true||!g){v({type:"text",value:f,output:f});continue}let R=")";if(g.dots===true){let I=o.slice(),z=[];for(let H=I.length-1;H>=0&&(o.pop(),I[H].type!=="brace");H--)I[H].type!=="dots"&&z.unshift(I[H].value);R=Ro(z,n),m.backtrack=true;}if(g.comma!==true&&g.dots!==true){let I=m.output.slice(0,g.outputIndex),z=m.tokens.slice(g.tokensIndex);g.value=g.output="\\{",f=R="\\}",m.output=I;for(let H of z)m.output+=H.output||H.value;}v({type:"brace",value:f,output:R}),ft("braces"),S.pop();continue}if(f==="|"){V.length>0&&V[V.length-1].conditions++,v({type:"text",value:f});continue}if(f===","){let g=f,R=S[S.length-1];R&&k[k.length-1]==="braces"&&(R.comma=true,g="|"),v({type:"comma",value:f,output:g});continue}if(f==="/"){if(p.type==="dot"&&m.index===m.start+1){m.start=m.index+1,m.consumed="",m.output="",o.pop(),p=s;continue}v({type:"slash",value:f,output:d});continue}if(f==="."){if(m.braces>0&&p.type==="dot"){p.value==="."&&(p.output=u);let g=S[S.length-1];p.type="dots",p.output+=f,p.value+=f,g.dots=true;continue}if(m.braces+m.parens===0&&p.type!=="bos"&&p.type!=="slash"){v({type:"text",value:f,output:u});continue}v({type:"dot",value:f,output:u});continue}if(f==="?"){if(!(p&&p.value==="(")&&n.noextglob!==true&&P()==="("&&P(2)!=="?"){oe("qmark",f);continue}if(p&&p.type==="paren"){let R=P(),I=f;(p.value==="("&&!/[!=<:]/.test(R)||R==="<"&&!/<([!=]|\w+>)/.test(it()))&&(I=`\\${f}`),v({type:"text",value:f,output:I});continue}if(n.dot!==true&&(p.type==="slash"||p.type==="bos")){v({type:"qmark",value:f,output:G});continue}v({type:"qmark",value:f,output:x});continue}if(f==="!"){if(n.noextglob!==true&&P()==="("&&(P(2)!=="?"||!/[!=<:]/.test(P(3)))){oe("negate",f);continue}if(n.nonegate!==true&&m.index===0){ai();continue}}if(f==="+"){if(n.noextglob!==true&&P()==="("&&P(2)!=="?"){oe("plus",f);continue}if(p&&p.value==="("||n.regex===false){v({type:"plus",value:f,output:h});continue}if(p&&(p.type==="bracket"||p.type==="paren"||p.type==="brace")||m.parens>0){v({type:"plus",value:f});continue}v({type:"plus",value:h});continue}if(f==="@"){if(n.noextglob!==true&&P()==="("&&P(2)!=="?"){v({type:"at",extglob:true,value:f,output:""});continue}v({type:"text",value:f});continue}if(f!=="*"){(f==="$"||f==="^")&&(f=`\\${f}`);let g=_o.exec(it());g&&(f+=g[0],m.index+=g[0].length),v({type:"text",value:f});continue}if(p&&(p.type==="globstar"||p.star===true)){p.type="star",p.star=true,p.value+=f,p.output=C,m.backtrack=true,m.globstar=true,Y(f);continue}let y=it();if(n.noextglob!==true&&/^\([^?]/.test(y)){oe("star",f);continue}if(p.type==="star"){if(n.noglobstar===true){Y(f);continue}let g=p.prev,R=g.prev,I=g.type==="slash"||g.type==="bos",z=R&&(R.type==="star"||R.type==="globstar");if(n.bash===true&&(!I||y[0]&&y[0]!=="/")){v({type:"star",value:f,output:""});continue}let H=m.braces>0&&(g.type==="comma"||g.type==="brace"),Ie=V.length&&(g.type==="pipe"||g.type==="paren");if(!I&&g.type!=="paren"&&!H&&!Ie){v({type:"star",value:f,output:""});continue}for(;y.slice(0,3)==="/**";){let ae=e[m.index+4];if(ae&&ae!=="/")break;y=y.slice(3),Y("/**",3);}if(g.type==="bos"&&J()){p.type="globstar",p.value+=f,p.output=U(n),m.output=p.output,m.globstar=true,Y(f);continue}if(g.type==="slash"&&g.prev.type!=="bos"&&!z&&J()){m.output=m.output.slice(0,-(g.output+p.output).length),g.output=`(?:${g.output}`,p.type="globstar",p.output=U(n)+(n.strictSlashes?")":"|$)"),p.value+=f,m.globstar=true,m.output+=g.output+p.output,Y(f);continue}if(g.type==="slash"&&g.prev.type!=="bos"&&y[0]==="/"){let ae=y[1]!==void 0?"|$":"";m.output=m.output.slice(0,-(g.output+p.output).length),g.output=`(?:${g.output}`,p.type="globstar",p.output=`${U(n)}${d}|${d}${ae})`,p.value+=f,m.output+=g.output+p.output,m.globstar=true,Y(f+F()),v({type:"slash",value:"/",output:""});continue}if(g.type==="bos"&&y[0]==="/"){p.type="globstar",p.value+=f,p.output=`(?:^|${d}|${U(n)}${d})`,m.output=p.output,m.globstar=true,Y(f+F()),v({type:"slash",value:"/",output:""});continue}m.output=m.output.slice(0,-p.output.length),p.type="globstar",p.output=U(n),p.value+=f,m.output+=p.output,m.globstar=true,Y(f);continue}let O={type:"star",value:f,output:C};if(n.bash===true){O.output=".*?",(p.type==="bos"||p.type==="slash")&&(O.output=W+O.output),v(O);continue}if(p&&(p.type==="bracket"||p.type==="paren")&&n.regex===true){O.output=f,v(O);continue}(m.index===m.start||p.type==="slash"||p.type==="dot")&&(p.type==="dot"?(m.output+=_,p.output+=_):n.dot===true?(m.output+=$,p.output+=$):(m.output+=W,p.output+=W),P()!=="*"&&(m.output+=b,p.output+=b)),v(O);}for(;m.brackets>0;){if(n.strictBrackets===true)throw new SyntaxError(Et("closing","]"));m.output=rt.escapeLast(m.output,"["),ft("brackets");}for(;m.parens>0;){if(n.strictBrackets===true)throw new SyntaxError(Et("closing",")"));m.output=rt.escapeLast(m.output,"("),ft("parens");}for(;m.braces>0;){if(n.strictBrackets===true)throw new SyntaxError(Et("closing","}"));m.output=rt.escapeLast(m.output,"{"),ft("braces");}if(n.strictSlashes!==true&&(p.type==="star"||p.type==="bracket")&&v({type:"maybe_slash",value:"",output:`${d}?`}),m.backtrack===true){m.output="";for(let y of m.tokens)m.output+=y.output!=null?y.output:y.value,y.suffix&&(m.output+=y.suffix);}return m};ln.fastpaths=(e,t)=>{let n={...t},r=typeof n.maxLength=="number"?Math.min(ve,n.maxLength):ve,i=e.length;if(i>r)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${r}`);e=yr[e]||e;let{DOT_LITERAL:s,SLASH_LITERAL:o,ONE_CHAR:a,DOTS_SLASH:l,NO_DOT:c,NO_DOTS:u,NO_DOTS_SLASH:h,STAR:d,START_ANCHOR:b}=Re.globChars(n.windows),w=n.dot?u:c,E=n.dot?h:c,_=n.capture?"":"?:",$={negated:false,prefix:""},x=n.bash===true?".*?":d;n.capture&&(x=`(${x})`);let G=W=>W.noglobstar===true?x:`(${_}(?:(?!${b}${W.dot?l:s}).)*?)`,Z=W=>{switch(W){case "*":return `${w}${a}${x}`;case ".*":return `${s}${a}${x}`;case "*.*":return `${w}${x}${s}${a}${x}`;case "*/*":return `${w}${x}${o}${a}${E}${x}`;case "**":return w+G(n);case "**/*":return `(?:${w}${G(n)}${o})?${E}${a}${x}`;case "**/*.*":return `(?:${w}${G(n)}${o})?${E}${x}${s}${a}${x}`;case "**/.*":return `(?:${w}${G(n)}${o})?${s}${a}${x}`;default:{let A=/^(.*?)\.(\w+)$/.exec(W);if(!A)return;let C=Z(A[1]);return C?C+s+A[2]:void 0}}},B=rt.removePrefix(e,$),U=Z(B);return U&&n.strictSlashes!==true&&(U+=`${o}?`),U};br.exports=ln;});var Er=pt((vu,Sr)=>{var vo=gr(),cn=wr(),xr=Dt(),$o=It(),No=e=>e&&typeof e=="object"&&!Array.isArray(e),j=(e,t,n=false)=>{if(Array.isArray(e)){let u=e.map(d=>j(d,t,n));return d=>{for(let b of u){let w=b(d);if(w)return w}return false}}let r=No(e)&&e.tokens&&e.input;if(e===""||typeof e!="string"&&!r)throw new TypeError("Expected pattern to be a non-empty string");let i=t||{},s=i.windows,o=r?j.compileRe(e,t):j.makeRe(e,t,false,true),a=o.state;delete o.state;let l=()=>false;if(i.ignore){let u={...t,ignore:null,onMatch:null,onResult:null};l=j(i.ignore,u,n);}let c=(u,h=false)=>{let{isMatch:d,match:b,output:w}=j.test(u,o,t,{glob:e,posix:s}),E={glob:e,state:a,regex:o,posix:s,input:u,output:w,match:b,isMatch:d};return typeof i.onResult=="function"&&i.onResult(E),d===false?(E.isMatch=false,h?E:false):l(u)?(typeof i.onIgnore=="function"&&i.onIgnore(E),E.isMatch=false,h?E:false):(typeof i.onMatch=="function"&&i.onMatch(E),h?E:true)};return n&&(c.state=a),c};j.test=(e,t,n,{glob:r,posix:i}={})=>{if(typeof e!="string")throw new TypeError("Expected input to be a string");if(e==="")return {isMatch:false,output:""};let s=n||{},o=s.format||(i?xr.toPosixSlashes:null),a=e===r,l=a&&o?o(e):e;return a===false&&(l=o?o(e):e,a=l===r),(a===false||s.capture===true)&&(s.matchBase===true||s.basename===true?a=j.matchBase(e,t,n,i):a=t.exec(l)),{isMatch:!!a,match:a,output:l}};j.matchBase=(e,t,n)=>(t instanceof RegExp?t:j.makeRe(t,n)).test(xr.basename(e));j.isMatch=(e,t,n)=>j(t,n)(e);j.parse=(e,t)=>Array.isArray(e)?e.map(n=>j.parse(n,t)):cn(e,{...t,fastpaths:false});j.scan=(e,t)=>vo(e,t);j.compileRe=(e,t,n=false,r=false)=>{if(n===true)return e.output;let i=t||{},s=i.contains?"":"^",o=i.contains?"":"$",a=`${s}(?:${e.output})${o}`;e&&e.negated===true&&(a=`^(?!${a}).*$`);let l=j.toRegex(a,t);return r===true&&(l.state=e),l};j.makeRe=(e,t={},n=false,r=false)=>{if(!e||typeof e!="string")throw new TypeError("Expected a non-empty string");let i={negated:false,fastpaths:true};return t.fastpaths!==false&&(e[0]==="."||e[0]==="*")&&(i.output=cn.fastpaths(e,t)),i.output||(i=cn(e,t)),j.compileRe(i,t,n,r)};j.toRegex=(e,t)=>{try{let n=t||{};return new RegExp(e,n.flags||(n.nocase?"i":""))}catch(n){if(t&&t.debug===true)throw n;return /$^/}};j.constants=$o;Sr.exports=j;});var Cr=pt(($u,_r)=>{var Ar=Er(),ko=Dt();function Tr(e,t,n=false){return t&&(t.windows===null||t.windows===void 0)&&(t={...t,windows:ko.isWindows()}),Ar(e,t,n)}Object.assign(Tr,Ar);_r.exports=Tr;});function Ht(e){if("String"in e)return e.String.sval}function gt(e){return e.map(Ht).filter(t=>t!=null)}function Pr(e){return Object.keys(e)[0]}function Lr(e){if("A_Const"in e){if(e.A_Const.ival)return e.A_Const.ival.ival;if(e.A_Const.fval)return e.A_Const.fval.fval;if(e.A_Const.sval)return e.A_Const.sval.sval;if(e.A_Const.boolval)return e.A_Const.boolval.boolval;if(e.A_Const.isnull)return null}}var Ne=L(()=>{});function Or(e){let t=e.toLowerCase();return ["serial","serial4","bigserial","serial8","smallserial","serial2"].includes(t)}function Fr(e){let t=e.toLowerCase();return ["varchar","character varying","char","character","bpchar"].includes(t)}function Ir(e){let t=e.toLowerCase();return ["numeric","decimal"].includes(t)}var pn,ke,ea,mn=L(()=>{Ne();pn=class extends Error{},ke=class extends pn{constructor(n,r){super(r??`Unsupported node type: ${Pr(n)}`);this.node=n;}};ea={CreateEnumStmt:{react:"ignore"},CreateDomainStmt:{react:"warn"},CreateSeqStmt:{react:"error"},AlterSeqStmt:{react:"error"},CreateSchemaStmt:{react:"warn"},CreatePolicyStmt:{react:"ignore"},PartitionElem:{react:"error"},PartitionCmd:{react:"error"},VariableSetStmt:{react:"ignore"},CompositeTypeStmt:{react:"error"},AlterEnumStmt:{react:"error"},AlterObjectSchemaStmt:{react:"error"},AlterOwnerStmt:{react:"error"},AlterTypeStmt:{react:"error"},AlterFunctionStmt:{react:"error"},AlterDefaultPrivilegesStmt:{react:"error"},GrantStmt:{react:"error"},GrantRoleStmt:{react:"error"},CopyStmt:{react:"error"},CreateCastStmt:{react:"error"},AlterOpFamilyStmt:{react:"error"},AlterOperatorStmt:{react:"error"},TruncateStmt:{react:"error"},A_Indirection:{react:"error"},XmlExpr:{react:"error"},XmlSerialize:{react:"error"},RangeTableSample:{react:"error"},GroupingSet:{react:"error"}},new Map(Object.entries(ea));});var Q,Pe,Dr=L(()=>{Ne();mn();Q=class extends ke{constructor(t,n){super(t,`Unsupported expression: ${n}`);}},Pe=class{deparse(t){if("A_Const"in t){let i=t.A_Const;if(i.boolval!==void 0)return i.boolval.boolval?{}:{$always:false}}let n=Object.keys(t)[0],r=this[n];if(!r)throw new Q({[n]:t},`Unsupported expression: ${n}`);return r.call(this,t[n])}deparseValue(t){if("A_Const"in t)return this.A_Const(t.A_Const);if("ColumnRef"in t)return this.ColumnRef(t.ColumnRef);if("FuncCall"in t)return this.FuncCall(t.FuncCall);if("SubLink"in t)return this.SubLink(t.SubLink);if("TypeCast"in t)return this.TypeCast(t.TypeCast);if("A_Expr"in t){let r=this.isJwtAccessor(t.A_Expr);return r||this.A_Expr(t.A_Expr)}if("BoolExpr"in t)return this.BoolExpr(t.BoolExpr);let n=Object.keys(t)[0];throw new Q({[n]:t},`deparseValue: ${n}`)}A_Expr(t){if(t.kind==="AEXPR_OP"){let n=t.name?.[0],r=n?Ht(n):void 0;if(!r)throw new Q({A_Expr:t},"A_Expr missing operator");let i=this.isJwtAccessor(t);if(i)return {[i]:{}};let s=t.lexpr?this.deparseValue(t.lexpr):void 0,o=t.rexpr?this.deparseValue(t.rexpr):void 0,a=this.mapOperator(r);if(!a)throw new Q({A_Expr:t},`Unsupported operator: ${r}`);let l=t.rexpr!=null&&"ColumnRef"in t.rexpr;if(typeof s=="string"&&s.startsWith("{{")&&l)return {[o]:{[a]:s}};let c=l&&typeof o=="string"?{$ref:o}:o;return {[s]:{[a]:c}}}if(t.kind==="AEXPR_LIKE"||t.kind==="AEXPR_ILIKE"){let n=t.lexpr?this.deparseValue(t.lexpr):void 0,r=t.rexpr?this.deparseValue(t.rexpr):void 0,s=(t.name?.[0]?Ht(t.name[0]):"~~")==="!~~"?"$notLike":"$like";return {[n]:{[s]:r}}}if(t.kind==="AEXPR_IN"){let n=t.lexpr?this.deparseValue(t.lexpr):void 0,r=t.rexpr&&"List"in t.rexpr&&t.rexpr.List.items?t.rexpr.List.items.map(i=>this.deparseValue(i)):[];return {[n]:{$in:r}}}throw new Q({A_Expr:t},`A_Expr kind: ${t.kind}`)}BoolExpr(t){let n=t.args??[];switch(t.boolop){case "AND_EXPR":return {$and:n.map(r=>this.deparse(r))};case "OR_EXPR":return {$or:n.map(r=>this.deparse(r))};case "NOT_EXPR":return {$not:this.deparse(n[0])};default:throw new Q({BoolExpr:t},`BoolExpr op: ${t.boolop}`)}}NullTest(t){let n=t.arg?this.deparseValue(t.arg):void 0;return t.nulltesttype==="IS_NULL"?{[n]:{$is:null}}:{[n]:{$isNot:null}}}SubLink(t){if(t.subLinkType==="ANY_SUBLINK"){let n=t.testexpr?this.deparseValue(t.testexpr):void 0,r=t.subselect?this.SelectStmt(t.subselect.SelectStmt):void 0;return {[n]:{$in:r}}}if(t.subLinkType==="EXISTS_SUBLINK")return {$exists:t.subselect?this.SelectStmt(t.subselect.SelectStmt):void 0};if(t.subLinkType==="EXPR_SUBLINK"){let n=t.subselect?t.subselect.SelectStmt:void 0;if(n?.fromClause?.length)return this.SelectStmt(n);if(n?.targetList?.[0]){let r=n.targetList[0],i="ResTarget"in r?r.ResTarget:void 0;if(i?.val){let s=this.deparseValue(i.val);return s}}}throw new Q({SubLink:t},`SubLink type: ${t.subLinkType}`)}SelectStmt(t){let{from:n,schema:r,join:i}=this.deparseFromClause(t.fromClause??[]),s=[];for(let d of t.targetList??[]){let b="ResTarget"in d?d.ResTarget:void 0;if(b?.val){let w=this.deparseValue(b.val);Array.isArray(w)?s.push(...w.map(String)):w!=null&&w!==""&&s.push(String(w));}}let o=t.whereClause?this.deparse(t.whereClause):void 0,a=this.deparseSortClause(t.sortClause),l=this.deparseLimit(t.limitCount),c=this.deparseLimit(t.limitOffset),u=this.deparseGroupClause(t.groupClause),h={type:"query",from:n,select:s};return r&&(h.schema=r),Object.keys(i).length>0&&(h.join=i),o&&(h.where=o),a.length>0&&(h.order=a),l!==void 0&&(h.limit=l),c!==void 0&&(h.offset=c),u.length>0&&(h.group=u),h}FuncCall(t){let n=this.isAuthFunc(t.funcname??[]);if(n)return n;throw new Q({FuncCall:t},`FuncCall: ${gt(t.funcname??[]).join(".")}`)}ColumnRef(t){let n=gt(t.fields??[]);return n.length===1?n[0]:n.join(".")}A_Const(t){if(t.boolval!==void 0)return t.boolval.boolval;if(t.ival!==void 0)return t.ival.ival??0;if(t.fval!==void 0)return parseFloat(t.fval.fval??"0");if(t.sval!==void 0)return t.sval.sval??"";if(t.isnull)return null;throw new Q({A_Const:t},"A_Const: unknown variant")}TypeCast(t){if(!t.arg)throw new Q({TypeCast:t},"TypeCast: missing arg");return this.deparseValue(t.arg)}BooleanTest(t){let n=t.arg?this.deparseValue(t.arg):void 0;return t.booltesttype==="IS_TRUE"?{[n]:{$eq:true}}:{[n]:{$eq:false}}}deparseFromClause(t){let n={};if(t.length===0)return {from:"",join:n};let r=t[0];if("RangeVar"in r){let i=r.RangeVar;return {from:i.relname??"",schema:i.schemaname,join:n}}if("JoinExpr"in r){let{from:i,schema:s}=this.walkJoinExpr(r.JoinExpr,n);return {from:i,schema:s,join:n}}return {from:"",join:n}}walkJoinExpr(t,n){let r={from:""};if(t.larg)if("RangeVar"in t.larg){let i=t.larg.RangeVar;r={from:i.relname??"",schema:i.schemaname};}else "JoinExpr"in t.larg&&(r=this.walkJoinExpr(t.larg.JoinExpr,n));if(t.rarg&&"RangeVar"in t.rarg){let i=t.rarg.RangeVar,s=i.relname??"",o=i.alias?.aliasname??s,a=t.jointype==="JOIN_LEFT"?"left":"inner",l={from:s,type:a};t.quals&&(l.on=this.deparse(t.quals));let c=o;if(c in n){let u=2;for(;`${c}_${u}`in n;)u++;c=`${c}_${u}`;}n[c]=l;}return r}deparseSortClause(t){if(!t)return [];let n=[];for(let r of t){if(!("SortBy"in r))continue;let i=r.SortBy;if(!i.node)continue;let s=String(this.deparseValue(i.node)),o=i.sortby_dir==="SORTBY_DESC"?"desc":"asc",a={column:s,direction:o};i.sortby_nulls==="SORTBY_NULLS_FIRST"?a.nullsFirst=true:i.sortby_nulls==="SORTBY_NULLS_LAST"&&(a.nullsFirst=false),n.push(a);}return n}deparseLimit(t){if(!t)return;let n=this.deparseValue(t);return typeof n=="number"?n:Number(n)}deparseGroupClause(t){return t?t.map(n=>String(this.deparseValue(n))):[]}isAuthFunc(t){let n=gt(t);if(n.length===2&&n[0]==="auth"){if(n[1]==="uid")return "{{auth.uid}}";if(n[1]==="jwt")return "{{auth.jwt}}";if(n[1]==="role")return "{{auth.role}}";throw new Error(`Unsupported auth function: "${n.slice(1).join(".")}"`)}return null}isJwtAccessor(t){if(t.kind!=="AEXPR_OP")return null;let n=t.name?.[0]?Ht(t.name[0]):void 0;if(n!=="->"&&n!=="->>")return null;let r=t.rexpr&&"A_Const"in t.rexpr?t.rexpr.A_Const.sval?.sval:void 0;if(r===void 0)return null;if(t.lexpr&&"FuncCall"in t.lexpr)return this.isAuthFunc(t.lexpr.FuncCall.funcname??[])==="{{auth.jwt}}"?`{{auth.jwt.${r}}}`:null;if(t.lexpr&&"A_Expr"in t.lexpr){let i=this.isJwtAccessor(t.lexpr.A_Expr);if(i)return `${i.slice(0,-2)}.${r}}}`}return null}mapOperator(t){switch(t){case "=":return "$eq";case "<>":case "!=":return "$neq";case ">":return "$gt";case ">=":return "$gte";case "<":return "$lt";case "<=":return "$lte";case "~~":return "$like";case "!~~":return "$notLike";default:return}}};});var Le,jr=L(()=>{Le=class e{constructor(t){this.data=t;}appliesTo(t){return this.data.command==="ALL"||this.data.command===t}appliesToRole(t){return this.data.roles.length===0||this.data.roles.includes(t)}toJSON(){return this.data}static fromJSON(t){return new e(t)}};});var Bt,hn=L(()=>{Bt=class extends Error{constructor(n,r,i,s){super(`check constraint "${i}" violated for ${n}.${r}`);this.table=n;this.column=r;this.constraint=i;this.value=s;this.name="CheckConstraintError";}};});var q,at=L(()=>{hn();q=class{context;constructor(t){this.context=t;}get isShimBacked(){return false}checkConstraint(){return null}serialize(t){return t}deserialize(t){return t}validateStorage(t){return {status:"pass",message:null}}validationFail(t,n){return {status:"fail",message:t,action:n}}validationPass(){return {status:"pass",message:null}}isNullish(t){return t==null}toColumnDDL(t){let{includeNullable:n=true}=t??{},r=[],i=this.context.column;r.push(this.quoteIfNeeded(i)),r.push(this.sqliteType),this.context.isPrimaryKey&&r.push("PRIMARY KEY"),this.context.isSerial&&this.context.isPrimaryKey&&r.push("AUTOINCREMENT"),n&&!this.context.nullable&&!this.context.isPrimaryKey&&r.push("NOT NULL"),this.context.isUnique&&!this.context.isPrimaryKey&&r.push("UNIQUE"),this.context.defaultValue!==null&&r.push(`DEFAULT ${this.context.defaultValue}`);let s=this.checkConstraint();return s&&r.push(`CHECK (${s})`),r.join(" ")}checkError(t,n){return new Bt(this.context.table,this.context.column,t,n)}quoteIfNeeded(t){return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)?t:`"${t}"`}};});var yt,Oe=L(()=>{at();yt=class extends q{get sqliteType(){return "INTEGER"}};});var qt,dn=L(()=>{Oe();qt=class extends yt{constructor(t){super({...t,isSerial:true});}};});function na(e,t){let{precision:n,scale:r}=t,i=10**r,s=10**(n-r);return Math.abs(Math.round(e*i)-e*i)<1e-4&&Math.abs(e)<s}var Vt,gn=L(()=>{at();Vt=class extends q{numericPrecision;constructor(t,n){super(t),this.numericPrecision=n;}get isShimBacked(){return this.numericPrecision!==void 0}get sqliteType(){return "REAL"}checkConstraint(){if(this.numericPrecision){let{precision:t,scale:n}=this.numericPrecision,r=this.context.column,i=10**n,s=10**(t-n);return `ABS(ROUND(${r} * ${i}) - ${r} * ${i}) < 0.0001 AND ABS(${r}) < ${s}`}return null}validateStorage(t){if(this.isNullish(t))return this.validationPass();if(typeof t!="number"||!Number.isFinite(t))return this.validationFail("Expected finite number.","Patch rows with finite numbers.");if(this.numericPrecision){let{precision:n,scale:r}=this.numericPrecision;if(!na(t,this.numericPrecision))return this.validationFail(`Does not fit numeric(${n}, ${r}).`,"Patch rows within numeric precision.")}return this.validationPass()}};});var D,et=L(()=>{at();D=class extends q{lengthConstraint;constructor(t,n){super(t),this.lengthConstraint=n;}get isShimBacked(){return this.lengthConstraint!==void 0}get sqliteType(){return "TEXT"}checkConstraint(){return this.lengthConstraint!==void 0?`length(${this.context.column}) <= ${this.lengthConstraint}`:null}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"?this.validationFail("Expected text.","Patch rows with text values."):this.lengthConstraint!==void 0&&Array.from(t).length>this.lengthConstraint?this.validationFail(`Exceeds length ${this.lengthConstraint}.`,"Patch rows with shorter text."):this.validationPass()}};});var Gt,yn=L(()=>{at();Gt=class extends q{get sqliteType(){return "BLOB"}};});var Wt,bn=L(()=>{at();Wt=class extends q{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}checkConstraint(){return `${this.context.column} IN (0, 1)`}serialize(t){if(this.isNullish(t))return t;if(t===true||t===1)return 1;if(t===false||t===0)return 0;throw this.checkError("boolean_range",t)}deserialize(t){return this.isNullish(t)?t:t===1?true:t===0?false:t}validateStorage(t){return this.isNullish(t)?this.validationPass():t===1||t===0?this.validationPass():this.validationFail("Expected 0 or 1.","Patch rows with boolean values.")}};});function Mr(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var zt,wn=L(()=>{at();zt=class extends q{get isShimBacked(){return true}get sqliteType(){return "TEXT"}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR json_valid(${t})`}serialize(t){if(this.isNullish(t))return t;try{return JSON.stringify(t)}catch{throw this.checkError("json_valid",t)}}deserialize(t){if(this.isNullish(t))return t;if(typeof t=="string"){let n=Mr(t);return n.ok?n.value:t}return t}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"?this.validationFail("Expected JSON text.","Patch rows with JSON values."):Mr(t).ok?this.validationPass():this.validationFail("Invalid JSON text.","Patch rows with valid JSON.")}};});function ra(e){if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return false;let t=new Date(`${e}T00:00:00.000Z`);return !Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e}var Kt,xn=L(()=>{et();Kt=class extends D{get isShimBacked(){return true}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR date(${t}) IS NOT NULL`}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!ra(t)?this.validationFail("Invalid date.","Patch rows with YYYY-MM-DD dates."):this.validationPass()}};});function ia(e){let t=e.match(/^(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?([+-](\d{2}):?(\d{2}))?$/);if(!t)return false;let n=Number(t[1]),r=Number(t[2]),i=t[3]===void 0?0:Number(t[3]),s=t[5]===void 0?null:Number(t[5]),o=t[6]===void 0?null:Number(t[6]),a=s===null||o!==null&&s<=15&&o<=59;return n<=24&&r<=59&&i<=59&&(n!==24||r===0&&i===0)&&a}var Xt,Sn=L(()=>{et();Xt=class extends D{get isShimBacked(){return true}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR time(${t}) IS NOT NULL`}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!ia(t)?this.validationFail("Invalid time.","Patch rows with HH:MM[:SS] times."):this.validationPass()}};});function sa(e){let t=e.match(/^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?(?:Z|([+-](\d{2}):?(\d{2})))?$/);if(!t)return false;let n=Number(t[1]),r=Number(t[2]),i=Number(t[3]),s=Number(t[4]),o=Number(t[5]),a=t[6]===void 0?0:Number(t[6]),l=t[8]===void 0?null:Number(t[8]),c=t[9]===void 0?null:Number(t[9]),u=new Date(Date.UTC(n,r-1,i)),h=u.getUTCFullYear()===n&&u.getUTCMonth()===r-1&&u.getUTCDate()===i,d=s<=24&&o<=59&&a<=59&&(s!==24||o===0&&a===0),b=l===null||c!==null&&l<=15&&c<=59;return h&&d&&b}var Jt,En=L(()=>{et();Jt=class extends D{get isShimBacked(){return true}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR datetime(${t}) IS NOT NULL`}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!sa(t)?this.validationFail("Invalid timestamp.","Patch rows with ISO timestamps."):this.validationPass()}};});var Yt,An=L(()=>{et();Yt=class extends D{get isShimBacked(){return true}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||t.trim().length===0?this.validationFail("Expected interval text.","Patch rows with interval strings."):/^-?\d+(?:\.\d+)?$/.test(t.trim())?this.validationFail("Ambiguous numeric interval.","Patch rows with explicit interval strings."):this.validationPass()}};});var Qt,Tn=L(()=>{et();Qt=class extends D{enumValues;constructor(t,n){super(t),this.enumValues=n;}get isShimBacked(){return true}checkConstraint(){let t=this.context.column,n=this.enumValues.map(r=>`'${r.replace(/'/g,"''")}'`).join(", ");return `${t} IN (${n})`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string"||!this.enumValues.includes(t))throw this.checkError("enum_membership",t);return t}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!this.enumValues.includes(t)?this.validationFail("Invalid enum value.","Patch rows with declared enum values."):this.validationPass()}};});function Ur(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var Ct,_n=L(()=>{at();Ct=class extends q{elementField;constructor(t,n){super(t),this.elementField=n;}get sqliteType(){return "TEXT"}get isShimBacked(){return true}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR (json_valid(${t}) AND json_type(${t}) = 'array')`}serialize(t){if(this.isNullish(t))return t;if(!Array.isArray(t))throw this.checkError("array_type",t);return this.elementField?JSON.stringify(t.map(n=>this.elementField.serialize(n))):JSON.stringify(t)}deserialize(t){if(this.isNullish(t))return t;if(typeof t=="string"){let n=Ur(t);if(n.ok&&Array.isArray(n.value))return this.elementField?n.value.map(r=>this.elementField.deserialize(r)):n.value}return t}validateStorage(t){if(this.isNullish(t))return this.validationPass();if(typeof t!="string")return this.validationFail("Expected JSON array text.","Patch rows with array values.");let n=Ur(t);if(!n.ok)return this.validationFail("Invalid JSON array text.","Patch rows with array values.");if(!Array.isArray(n.value))return this.validationFail("Expected JSON array.","Patch rows with array values.");if(this.elementField)for(let r of n.value){let i=this.elementField.validateStorage(r);if(i.status==="fail")return this.validationFail(`Invalid ${this.elementField.context.pgTypeName} array element.`,i.action??"Patch rows with valid array elements.")}return this.validationPass()}};});function Hr(e){return aa.test(e.toLowerCase())}var oa,aa,Zt,Cn=L(()=>{et();oa="????????-????-????-????-????????????",aa=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;Zt=class extends D{get isShimBacked(){return true}checkConstraint(){let t=this.quoteIfNeeded(this.context.column);return `${t} IS NULL OR ${t} GLOB '${oa}'`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string")throw this.checkError("uuid_format",t);let n=t.toLowerCase();if(!Hr(n))throw this.checkError("uuid_format",t);return n}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!Hr(t)?this.validationFail("Invalid UUID.","Patch rows with valid UUIDs."):this.validationPass()}};});function la(e){let t=e.split("/");if(t.length>2)return null;let n=t[0];if(!n)return null;if(t.length===1)return {address:n,prefix:null};let r=t[1];return !r||!/^\d+$/.test(r)?null:{address:n,prefix:Number(r)}}function ca(e){let t=e.split(".");return t.length!==4?false:t.every(n=>{if(!/^\d+$/.test(n))return false;let r=Number(n);return r>=0&&r<=255})}function ua(e){if(!e.includes(":"))return false;try{return new URL(`http://[${e}]/`),!0}catch{return false}}function Br(e){let t=la(e);return t?ca(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=32:ua(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=128:false:false}var te,Rn=L(()=>{et();te=class extends D{get isShimBacked(){return true}checkConstraint(){let t=this.quoteIfNeeded(this.context.column);return `${t} IS NULL OR (length(${t}) BETWEEN 3 AND 49 AND (instr(${t}, '.') > 0 OR instr(${t}, ':') > 0))`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string")throw this.checkError("inet_format",t);let n=t.trim();if(!Br(n))throw this.checkError("inet_format",t);return n}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!Br(t.trim())?this.validationFail("Invalid inet address.","Patch rows with valid inet strings."):this.validationPass()}};});var ee,vn=L(()=>{et();ee=class extends D{serialize(t){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}deserialize(t){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}toColumnDDL(){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}};});function ne(e,t){if(t?.isArray){let r=ne(e,{...t,isArray:false});return new Ct(e,r)}if(t?.enumValues)return new Qt(e,t.enumValues);let n=e.pgTypeName.toLowerCase().trim();if(n.startsWith("_")||n.endsWith("[]")){let r=n.startsWith("_")?n.slice(1):n.slice(0,-2),i={...e,pgTypeName:r},s=ne(i);return new Ct(e,s)}return pa.has(n)?new qt(e):fa.has(n)?new yt(e):ga.has(n)?new Wt(e):ya.has(n)?new zt(e):Sa.has(n)?new Kt(e):Ea.has(n)?new Xt(e):Aa.has(n)?new Jt(e):Ta.has(n)?new Yt(e):da.has(n)?new Gt(e):ma.has(n)?new Vt(e,t?.numericPrecision):ba.has(n)?new Zt(e):wa.has(n)?new D(e,63):xa.has(n)?new te(e):ha.has(n)?new D(e,t?.lengthConstraint):new ee(e)}var fa,pa,ma,ha,da,ga,ya,ba,wa,xa,Sa,Ea,Aa,Ta,qr=L(()=>{Oe();dn();gn();et();yn();bn();wn();xn();Sn();En();An();Tn();_n();Cn();Rn();vn();fa=new Set(["int2","smallint","int4","integer","int","int8","bigint"]),pa=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]),ma=new Set(["float4","real","float8","double precision","numeric","decimal"]),ha=new Set(["text","varchar","character varying","char","character","bpchar"]),da=new Set(["bytea"]),ga=new Set(["bool","boolean"]),ya=new Set(["json","jsonb"]),ba=new Set(["uuid"]),wa=new Set(["name"]),xa=new Set(["inet"]),Sa=new Set(["date"]),Ea=new Set(["time","timetz","time without time zone","time with time zone"]),Aa=new Set(["timestamp","timestamptz","timestamp without time zone","timestamp with time zone"]),Ta=new Set(["interval"]);});var Vr=L(()=>{});var re,Gr=L(()=>{re=class{table;schema;fields;constructor(t,n="public",r=new Map){this.table=t,this.schema=n,this.fields=r;}get(t){return this.fields.get(t)}has(t){return this.fields.has(t)}set(t,n){this.fields.set(t,n);}columns(){return Array.from(this.fields.keys())}all(){return Array.from(this.fields.values())}serializeRow(t){let n={};for(let[r,i]of Object.entries(t)){let s=this.fields.get(r);n[r]=s?s.serialize(i):i;}return n}deserializeRow(t){let n={};for(let[r,i]of Object.entries(t)){let s=this.fields.get(r);n[r]=s?s.deserialize(i):i;}return n}applyDefaults(t){let n={...t};for(let[r,i]of this.fields)!(r in n)&&i.context.defaultFn&&(n[r]=i.context.defaultFn());return n}};});var Wr=L(()=>{at();hn();Oe();dn();gn();et();yn();bn();wn();xn();Sn();En();An();Tn();_n();Cn();Rn();vn();qr();Vr();Gr();});var zr={};hi(zr,{_resetWarnedMissingToClauseForTests:()=>_a,collectComments:()=>ka,collectEnums:()=>Ca,collectPolicies:()=>va,collectSchema:()=>$a,collectTableConstraints:()=>Na,collectVariables:()=>Ra});function _a(){$n.clear();}function Ca(e){let t=new Map;for(let n of e.stmts??[]){if(!n.stmt||!("CreateEnumStmt"in n.stmt))continue;let r=n.stmt.CreateEnumStmt,i=gt(r.typeName??[]).join(".");if(!i||!r.vals)continue;let s=gt(r.vals);t.set(i.toLowerCase(),s);}return t}function Ra(e){let t=new Map;for(let n of e.stmts??[]){if(!n.stmt||!("VariableSetStmt"in n.stmt))continue;let r=n.stmt.VariableSetStmt,i=r.name,s=Lr(r.args?.[0]??{});t.set(i,{value:s,local:r.is_local});}return t}function va(e){let t=new Pe,n=new Set,r=[];for(let i of e.stmts??[])if(i.stmt){if("CreatePolicyStmt"in i.stmt){let s=i.stmt.CreatePolicyStmt,o=s.table?.relname??"",a=s.table?.schemaname,l={select:"SELECT",insert:"INSERT",update:"UPDATE",delete:"DELETE"},c=s.cmd_name?l[s.cmd_name]??"ALL":"ALL",u=s.permissive===true,h=[],d=false;for(let _ of s.roles??[])if("RoleSpec"in _){let $=_.RoleSpec;$.roletype==="ROLESPEC_PUBLIC"?$.location===-1&&(d=true):$.roletype==="ROLESPEC_CSTRING"&&$.rolename&&h.push($.rolename);}if(d){let _=a?`${a}.${o}`:o,$=s.policy_name??"",x=`${_}::${$}`;$n.has(x)||($n.add(x),console.warn(`[supalite] policy "${$}" on "${_}" has no TO clause \u2014 applies to all roles (PUBLIC). For clarity, prefer an explicit \`TO <role>\` clause (e.g. \`TO authenticated\`).`));}let b=s.qual?t.deparse(s.qual):void 0,w=s.with_check?t.deparse(s.with_check):void 0,E=new Le({name:s.policy_name??"",table:o,schema:a,command:c,permissive:u,roles:h,using:b,withCheck:w});r.push(E);}if("AlterTableStmt"in i.stmt){let s=i.stmt.AlterTableStmt;if((s.cmds??[]).some(l=>"AlterTableCmd"in l&&(l.AlterTableCmd.subtype==="AT_EnableRowSecurity"||l.AlterTableCmd.subtype==="AT_ForceRowSecurity"))){let l=s.relation?.relname??"";n.add(l);}}}return {policies:r,tables:n}}function $a(e,t){let n=new Map;for(let r of e.stmts??[]){if(!r.stmt||!("CreateStmt"in r.stmt))continue;let i=r.stmt.CreateStmt,s=i.relation?.relname??"",o=i.relation?.schemaname??"public";if(!s)continue;let a=new re(s,o);for(let l of i.tableElts??[]){if(!("ColumnDef"in l))continue;let c=l.ColumnDef,u=c.colname;if(!u)continue;let h=c.typeName?.names?.map(S=>S.String?.sval||S.String?.str).filter(Boolean),d=h&&(h.length===2&&h[0]==="pg_catalog"?h[1]:h[0]);if(!d)continue;let b=!!c.typeName?.arrayBounds?.length,w=Array.isArray(c.typeName?.typmods)?c.typeName.typmods:[],E=S=>w[S]?.A_Const?.ival?.ival??w[S]?.A_Const?.val?.ival?.ival,_={isArray:b};if(Fr(d)&&w.length>0){let S=E(0);typeof S=="number"&&S>0&&(_.lengthConstraint=S);}if(Ir(d)&&w.length>=2){let S=E(0),k=E(1);typeof S=="number"&&typeof k=="number"&&S>0&&k>=0&&(_.numericPrecision={precision:S,scale:k});}let $=t.get(d.toLowerCase());$&&(_.enumValues=$);let x=Array.isArray(c.constraints)?c.constraints:[],G=x.some(S=>S.Constraint?.contype==="CONSTR_PRIMARY"),Z=Or(d)||x.some(S=>S.Constraint?.contype==="CONSTR_IDENTITY"),B=x.some(S=>S.Constraint?.contype==="CONSTR_NOTNULL"),U=x.find(S=>S.Constraint?.contype==="CONSTR_UNIQUE"),W=x.find(S=>S.Constraint?.contype==="CONSTR_GENERATED"),A=x.find(S=>S.Constraint?.contype==="CONSTR_FOREIGN"),C=x.find(S=>S.Constraint?.contype==="CONSTR_CHECK"),m;if(A){let S=A.Constraint,k=S.pktable?.relname,p=S.pktable?.schemaname,f=S.pk_attrs?.[0]?.String?.sval;k&&f&&(m={refSchema:p,refTable:k,refColumn:f,constraintName:S.conname||void 0});}let V={schema:o,table:s,column:u,pgTypeName:d,nullable:!B&&!G,defaultValue:null,defaultFn:null,isPrimaryKey:G,isUnique:!!U,isSerial:Z,isGenerated:!!W,fkRef:m,hasCheck:!!C,checkConstraintName:C?.Constraint?.conname||void 0,uniqueConstraintName:U?.Constraint?.conname||void 0};a.set(u,ne(V,_));}n.set(`${o}.${s}`,a);}return n}function Na(e){let t=[];for(let n of e.stmts??[]){if(!n.stmt||!("CreateStmt"in n.stmt))continue;let r=n.stmt.CreateStmt,i=r.relation?.relname??"",s=r.relation?.schemaname??"public";if(i)for(let o of r.tableElts??[]){if("ColumnDef"in o)continue;let a=o;if(!a.Constraint)continue;let l=a.Constraint,c=l.contype;if(c==="CONSTR_UNIQUE"){let u=(l.keys??[]).map(h=>h.String?.sval??h.String?.str).filter(Boolean);if(u.length===0)continue;t.push({schema:s,table:i,kind:"unique",name:l.conname||void 0,columns:u});}else if(c==="CONSTR_CHECK")t.push({schema:s,table:i,kind:"check",name:l.conname||void 0,columns:[]});else if(c==="CONSTR_FOREIGN"){let u=(l.fk_attrs??[]).map(b=>b.String?.sval??b.String?.str).filter(Boolean),h=(l.pk_attrs??[]).map(b=>b.String?.sval??b.String?.str).filter(Boolean),d=l.pktable?.relname;if(!d)continue;t.push({schema:s,table:i,kind:"foreign_key",name:l.conname||void 0,columns:u,refSchema:l.pktable?.schemaname,refTable:d,refColumns:h});}}}return t}function ka(e){let t=[];for(let n of e.stmts??[]){if(!n.stmt||!("CommentStmt"in n.stmt))continue;let r=n.stmt.CommentStmt,i=r.comment??"";if(!i)continue;let s=r.objtype,o=(r.object?.List?.items??r.object?.items??[]).map(a=>a.String?.sval??a.String?.str).filter(Boolean);if(o.length!==0){if(s==="OBJECT_TABLE"||s==="OBJECT_VIEW"){let[a,l]=o.length>=2?o:["public",o[0]];t.push({schema:a,table:l,text:i});}else if(s==="OBJECT_COLUMN"){let a="public",l,c;o.length>=3?[a,l,c]=o:[l,c]=o,t.push({schema:a,table:l,column:c,text:i});}}}return t}var $n,Kr=L(()=>{Dr();Ne();jr();Wr();mn();$n=new Set;});function tt(e,t){le.existsSync(e)||(le.mkdirSync(e,{recursive:true}),t?.());}function mt(e,t,n){le.existsSync(e)||(le.writeFileSync(e,t),n?.());}var ot=class e{root;constructor(t,n){let r=n??e.projectDir();this.root=nt__default.join(r,t??"");}ensureRoot(){tt(this.root);}static homeDir(){return nt__default.join(gi.homedir(),".lite")}static projectDir(){return nt__default.join(process.cwd(),"supabase")}deleteAll(t=false){try{le.rmSync(this.root,{recursive:!0});}catch(n){if(!t)throw n}this.ensureRoot();}delete(t,n=false){try{le.unlinkSync(nt__default.join(this.root,t));}catch(r){if(!n)throw r}}write(t,n,r=false){try{this.ensureRoot(),le.writeFileSync(nt__default.join(this.root,t),n);}catch(i){if(!r)throw i}}read(t,n=false){try{return le.readFileSync(nt__default.join(this.root,t),"utf8")}catch(r){if(!n)throw r}}relativePath(t){return t?nt__default.relative(process.cwd(),nt__default.join(this.root,t)):this.root}path(t){return t?nt__default.join(this.root,t):this.root}};var vt=process.env.SUPALITE_CLOUD_URL??(process.env.LOCAL?"http://localhost:2000":"https://www.lite.dev");var fe=class{root;constructor(t){this.root=t??nt__default.join(gi.homedir(),".lite","auth"),tt(this.root);}async getItem(t){try{return le.readFileSync(nt__default.join(this.root,t+".json"),"utf8")}catch{return null}}async setItem(t,n){le.writeFileSync(nt__default.join(this.root,t+".json"),n);}async removeItem(t){try{le.unlinkSync(nt__default.join(this.root,t+".json"));}catch{return}}};var wt=class{constructor(t){this.config=t;this.tempFs=new ot(".temp",this.config.root),this.projectFs=new ot("supabase",this.config.root),this.schemaFs=new ot("schemas",this.config.root),this.authStorage=this.config.authStorage??new fe(nt__default.join(ot.homeDir(),"auth")),this._client=this.config.withSupabaseClient!==false?this.config.client??createClient(this.config.host??vt,process.env.SUPALITE_CLOUD_ANON_KEY??"...",{auth:{storage:this.authStorage}}):void 0;}tempFs;projectFs;schemaFs;_client;authStorage;async fetch(t,n){if(!this.config.token)throw new Error("Not authenticated, sign in first.");let r=t instanceof URL?t:new URL(t,this.config.host??vt);return await fetch(r,{...n,headers:{...n?.headers,Authorization:`Bearer ${this.config.token}`}})}};var xt=class extends wt{constructor(n){super(n);this.config=n;}get client(){if(!this._client)throw new Error("Supabase client not initialized");return this._client}projectRef(){return this.tempFs.read("project-ref",true)}projectUrl(n){let r=new URL(this.config.host),i=r.hostname==="localhost"?"supalite.local":r.hostname,s=i.split(".").filter(a=>a!=="www"),o=s.length>=2?s.slice(-2).join("."):i;return `${r.protocol}//${n}.${o}${r.port?`:${r.port}`:""}`}};var ct={config_dir:"supabase",default_db_url:"file:supabase/.temp/data.db",default_db_dir:"supabase/.temp/data"};var Ft=Rt($t());function Ai(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return [n.length,n.pop().length+1]}function Ti(e,t,n){let r=e.split(/\r\n|\n|\r/g),i="",s=(Math.log10(t+1)|0)+1;for(let o=t-1;o<=t+1;o++){let a=r[o-1];a&&(i+=o.toString().padEnd(s," "),i+=": ",i+=a,i+=`
13
+ `,o===t&&(i+=" ".repeat(s+n+2),i+=`^
14
+ `));}return i}var T=class extends Error{line;column;codeblock;constructor(t,n){let[r,i]=Ai(n.toml,n.ptr),s=Ti(n.toml,r,i);super(`Invalid TOML document: ${t}
44
15
 
45
- ${r}`,s),this.line=e,this.column=i,this.codeblock=r;}};function Bn(a,t){let s=0;for(;a[t-++s]==="\\";);return --s&&s%2}function ye(a,t=0,s=a.length){let e=a.indexOf(`
46
- `,t);return a[e-1]==="\r"&&e--,e<=s?e:-1}function It(a,t){for(let s=t;s<a.length;s++){let e=a[s];if(e===`
47
- `)return s;if(e==="\r"&&a[s+1]===`
48
- `)return s+1;if(e<" "&&e!==" "||e==="\x7F")throw new y("control characters are not allowed in comments",{toml:a,ptr:t})}return a.length}function Z(a,t,s,e){let i;for(;(i=a[t])===" "||i===" "||!s&&(i===`
49
- `||i==="\r"&&a[t+1]===`
50
- `);)t++;return e||i!=="#"?t:Z(a,It(a,t),s)}function Ti(a,t,s,e,i=false){if(!e)return t=ye(a,t),t<0?a.length:t;for(let r=t;r<a.length;r++){let n=a[r];if(n==="#")r=ye(a,r);else {if(n===s)return r+1;if(n===e||i&&(n===`
51
- `||n==="\r"&&a[r+1]===`
52
- `))return r}}throw new y("cannot find end of structure",{toml:a,ptr:t})}function Le(a,t){let s=a[t],e=s===a[t+1]&&a[t+1]===a[t+2]?a.slice(t,t+3):s;t+=e.length-1;do t=a.indexOf(e,++t);while(t>-1&&s!=="'"&&Bn(a,t));return t>-1&&(t+=e.length,e.length>1&&(a[t]===s&&t++,a[t]===s&&t++)),t}var Mn=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,xt=class a extends Date{#e=false;#s=false;#t=null;constructor(t){let s=true,e=true,i="Z";if(typeof t=="string"){let r=t.match(Mn);r?(r[1]||(s=false,t=`0000-01-01T${t}`),e=!!r[2],e&&t[10]===" "&&(t=t.replace(" ","T")),r[2]&&+r[2]>23?t="":(i=r[3]||null,t=t.toUpperCase(),!i&&e&&(t+="Z"))):t="";}super(t),isNaN(this.getTime())||(this.#e=s,this.#s=e,this.#t=i);}isDateTime(){return this.#e&&this.#s}isLocal(){return !this.#e||!this.#s||!this.#t}isDate(){return this.#e&&!this.#s}isTime(){return this.#s&&!this.#e}isValid(){return this.#e||this.#s}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 s=+this.#t.slice(1,3)*60+ +this.#t.slice(4,6);return s=this.#t[0]==="-"?s:-s,new Date(this.getTime()-s*6e4).toISOString().slice(0,-1)+this.#t}static wrapAsOffsetDateTime(t,s="Z"){let e=new a(t);return e.#t=s,e}static wrapAsLocalDateTime(t){let s=new a(t);return s.#t=null,s}static wrapAsLocalDate(t){let s=new a(t);return s.#s=false,s.#t=null,s}static wrapAsLocalTime(t){let s=new a(t);return s.#e=false,s.#t=null,s}};var xn=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,qn=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,Vn=/^[+-]?0[0-9_]/,Gn=/^[0-9a-f]{2,8}$/i,Si={b:"\b",t:" ",n:`
53
- `,f:"\f",r:"\r",e:"\x1B",'"':'"',"\\":"\\"};function Ie(a,t=0,s=a.length){let e=a[t]==="'",i=a[t++]===a[t]&&a[t]===a[t+1];i&&(s-=2,a[t+=2]==="\r"&&t++,a[t]===`
54
- `&&t++);let r=0,n,o="",u=t;for(;t<s-1;){let l=a[t++];if(l===`
55
- `||l==="\r"&&a[t]===`
56
- `){if(!i)throw new y("newlines are not allowed in strings",{toml:a,ptr:t-1})}else if(l<" "&&l!==" "||l==="\x7F")throw new y("control characters are not allowed in strings",{toml:a,ptr:t-1});if(n){if(n=false,l==="x"||l==="u"||l==="U"){let p=a.slice(t,t+=l==="x"?2:l==="u"?4:8);if(!Gn.test(p))throw new y("invalid unicode escape",{toml:a,ptr:r});try{o+=String.fromCodePoint(parseInt(p,16));}catch{throw new y("invalid unicode escape",{toml:a,ptr:r})}}else if(i&&(l===`
57
- `||l===" "||l===" "||l==="\r")){if(t=Z(a,t-1,true),a[t]!==`
58
- `&&a[t]!=="\r")throw new y("invalid escape: only line-ending whitespace may be escaped",{toml:a,ptr:r});t=Z(a,t);}else if(l in Si)o+=Si[l];else throw new y("unrecognized escape sequence",{toml:a,ptr:r});u=t;}else !e&&l==="\\"&&(r=t-1,n=true,o+=a.slice(u,r));}return o+a.slice(u,s-1)}function Ai(a,t,s,e){if(a==="true")return true;if(a==="false")return false;if(a==="-inf")return -1/0;if(a==="inf"||a==="+inf")return 1/0;if(a==="nan"||a==="+nan"||a==="-nan")return NaN;if(a==="-0")return e?0n:0;let i=xn.test(a);if(i||qn.test(a)){if(Vn.test(a))throw new y("leading zeroes are not allowed",{toml:t,ptr:s});a=a.replace(/_/g,"");let n=+a;if(isNaN(n))throw new y("invalid number",{toml:t,ptr:s});if(i){if((i=!Number.isSafeInteger(n))&&!e)throw new y("integer value cannot be represented losslessly",{toml:t,ptr:s});(i||e===true)&&(n=BigInt(a));}return n}let r=new xt(a);if(!r.isValid())throw new y("invalid value",{toml:t,ptr:s});return r}function Wn(a,t,s){let e=a.slice(t,s),i=e.indexOf("#");return i>-1&&(It(a,i),e=e.slice(0,i)),[e.trimEnd(),i]}function qt(a,t,s,e,i){if(e===0)throw new y("document contains excessively nested structures. aborting.",{toml:a,ptr:t});let r=a[t];if(r==="["||r==="{"){let[u,l]=r==="["?Ri(a,t,e,i):Ci(a,t,e,i);if(s){if(l=Z(a,l),a[l]===",")l++;else if(a[l]!==s)throw new y("expected comma or end of structure",{toml:a,ptr:l})}return [u,l]}let n;if(r==='"'||r==="'"){n=Le(a,t);let u=Ie(a,t,n);if(s){if(n=Z(a,n),a[n]&&a[n]!==","&&a[n]!==s&&a[n]!==`
59
- `&&a[n]!=="\r")throw new y("unexpected character encountered",{toml:a,ptr:n});n+=+(a[n]===",");}return [u,n]}n=Ti(a,t,",",s);let o=Wn(a,t,n-+(a[n-1]===","));if(!o[0])throw new y("incomplete key-value declaration: no value specified",{toml:a,ptr:t});return s&&o[1]>-1&&(n=Z(a,t+o[1]),n+=+(a[n]===",")),[Ai(o[0],a,t,i),n]}var Hn=/^[a-zA-Z0-9-_]+[ \t]*$/;function ve(a,t,s="="){let e=t-1,i=[],r=a.indexOf(s,t);if(r<0)throw new y("incomplete key-value: cannot find end of key",{toml:a,ptr:t});do{let n=a[t=++e];if(n!==" "&&n!==" ")if(n==='"'||n==="'"){if(n===a[t+1]&&n===a[t+2])throw new y("multiline strings are not allowed in keys",{toml:a,ptr:t});let o=Le(a,t);if(o<0)throw new y("unfinished string encountered",{toml:a,ptr:t});e=a.indexOf(".",o);let u=a.slice(o,e<0||e>r?r:e),l=ye(u);if(l>-1)throw new y("newlines are not allowed in keys",{toml:a,ptr:t+e+l});if(u.trimStart())throw new y("found extra tokens after the string part",{toml:a,ptr:o});if(r<o&&(r=a.indexOf(s,o),r<0))throw new y("incomplete key-value: cannot find end of key",{toml:a,ptr:t});i.push(Ie(a,t,o));}else {e=a.indexOf(".",t);let o=a.slice(t,e<0||e>r?r:e);if(!Hn.test(o))throw new y("only letter, numbers, dashes and underscores are allowed in keys",{toml:a,ptr:t});i.push(o.trimEnd());}}while(e+1&&e<r);return [i,Z(a,r+1,true,true)]}function Ci(a,t,s,e){let i={},r=new Set,n;for(t++;(n=a[t++])!=="}"&&n;){if(n===",")throw new y("expected value, found comma",{toml:a,ptr:t-1});if(n==="#")t=It(a,t);else if(n!==" "&&n!==" "&&n!==`
60
- `&&n!=="\r"){let o,u=i,l=false,[p,f]=ve(a,t-1);for(let g=0;g<p.length;g++){if(g&&(u=l?u[o]:u[o]={}),o=p[g],(l=Object.hasOwn(u,o))&&(typeof u[o]!="object"||r.has(u[o])))throw new y("trying to redefine an already defined value",{toml:a,ptr:t});!l&&o==="__proto__"&&Object.defineProperty(u,o,{enumerable:true,configurable:true,writable:true});}if(l)throw new y("trying to redefine an already defined value",{toml:a,ptr:t});let[h,E]=qt(a,f,"}",s-1,e);r.add(h),u[o]=h,t=E;}}if(!n)throw new y("unfinished table encountered",{toml:a,ptr:t});return [i,t]}function Ri(a,t,s,e){let i=[],r;for(t++;(r=a[t++])!=="]"&&r;){if(r===",")throw new y("expected value, found comma",{toml:a,ptr:t-1});if(r==="#")t=It(a,t);else if(r!==" "&&r!==" "&&r!==`
61
- `&&r!=="\r"){let n=qt(a,t-1,"]",s-1,e);i.push(n[0]),t=n[1];}}if(!r)throw new y("unfinished array encountered",{toml:a,ptr:t});return [i,t]}function Ni(a,t,s,e){let i=t,r=s,n,o=false,u;for(let l=0;l<a.length;l++){if(l){if(i=o?i[n]:i[n]={},r=(u=r[n]).c,e===0&&(u.t===1||u.t===2))return null;if(u.t===2){let p=i.length-1;i=i[p],r=r[p].c;}}if(n=a[l],(o=Object.hasOwn(i,n))&&r[n]?.t===0&&r[n]?.d)return null;o||(n==="__proto__"&&(Object.defineProperty(i,n,{enumerable:true,configurable:true,writable:true}),Object.defineProperty(r,n,{enumerable:true,configurable:true,writable:true})),r[n]={t:l<a.length-1&&e===2?3:e,d:false,i:0,c:{}});}if(u=r[n],u.t!==e&&!(e===1&&u.t===3)||(e===2&&(u.d||(u.d=true,i[n]=[]),i[n].push(i={}),u.c[u.i++]=u={t:1,d:false,i:0,c:{}}),u.d))return null;if(u.d=true,e===1)i=o?i[n]:i[n]={};else if(e===0&&o)return null;return [n,i,u.c]}function Vt(a,{maxDepth:t=1e3,integersAsBigInt:s}={}){let e={},i={},r=e,n=i;for(let o=Z(a,0);o<a.length;){if(a[o]==="["){let u=a[++o]==="[",l=ve(a,o+=+u,"]");if(u){if(a[l[1]-1]!=="]")throw new y("expected end of table declaration",{toml:a,ptr:l[1]-1});l[1]++;}let p=Ni(l[0],e,i,u?2:1);if(!p)throw new y("trying to redefine an already defined table or value",{toml:a,ptr:o});n=p[2],r=p[1],o=l[1];}else {let u=ve(a,o),l=Ni(u[0],r,n,0);if(!l)throw new y("trying to redefine an already defined table or value",{toml:a,ptr:o});let p=qt(a,u[1],void 0,t,s);l[1][l[0]]=p[0],o=p[1];}if(o=Z(a,o,true),a[o]&&a[o]!==`
62
- `&&a[o]!=="\r")throw new y("each key-value declaration must be followed by an end-of-line",{toml:a,ptr:o});o=Z(a,o);}return e}var bi=/^[a-z0-9-_]+$/i;function Gt(a){let t=typeof a;if(t==="object"){if(Array.isArray(a))return "array";if(a instanceof Date)return "date"}return t}function Jn(a){for(let t=0;t<a.length;t++)if(Gt(a[t])!=="object")return false;return a.length!=0}function ps(a){return JSON.stringify(a).replace(/\x7f/g,"\\u007f")}function cs(a,t,s,e){if(s===0)throw new Error("Could not stringify the object: maximum object depth exceeded");if(t==="number")return isNaN(a)?"nan":a===1/0?"inf":a===-1/0?"-inf":e&&Number.isInteger(a)?a.toFixed(1):a.toString();if(t==="bigint"||t==="boolean")return a.toString();if(t==="string")return ps(a);if(t==="date"){if(isNaN(a.getTime()))throw new TypeError("cannot serialize invalid date");return a.toISOString()}if(t==="object")return Yn(a,s,e);if(t==="array")return Xn(a,s,e)}function Yn(a,t,s){let e=Object.keys(a);if(e.length===0)return "{}";let i="{ ";for(let r=0;r<e.length;r++){let n=e[r];r&&(i+=", "),i+=bi.test(n)?n:ps(n),i+=" = ",i+=cs(a[n],Gt(a[n]),t-1,s);}return i+" }"}function Xn(a,t,s){if(a.length===0)return "[]";let e="[ ";for(let i=0;i<a.length;i++){if(i&&(e+=", "),a[i]===null||a[i]===void 0)throw new TypeError("arrays cannot contain null or undefined values");e+=cs(a[i],Gt(a[i]),t-1,s);}return e+" ]"}function Kn(a,t,s,e){if(s===0)throw new Error("Could not stringify the object: maximum object depth exceeded");let i="";for(let r=0;r<a.length;r++)i+=`${i&&`
16
+ ${s}`,n),this.line=r,this.column=i,this.codeblock=s;}};function _i(e,t){let n=0;for(;e[t-++n]==="\\";);return --n&&n%2}function he(e,t=0,n=e.length){let r=e.indexOf(`
17
+ `,t);return e[r-1]==="\r"&&r--,r<=n?r:-1}function St(e,t){for(let n=t;n<e.length;n++){let r=e[n];if(r===`
18
+ `)return n;if(r==="\r"&&e[n+1]===`
19
+ `)return n+1;if(r<" "&&r!==" "||r==="\x7F")throw new T("control characters are not allowed in comments",{toml:e,ptr:t})}return e.length}function K(e,t,n,r){let i;for(;(i=e[t])===" "||i===" "||!n&&(i===`
20
+ `||i==="\r"&&e[t+1]===`
21
+ `);)t++;return r||i!=="#"?t:K(e,St(e,t),n)}function On(e,t,n,r,i=false){if(!r)return t=he(e,t),t<0?e.length:t;for(let s=t;s<e.length;s++){let o=e[s];if(o==="#")s=he(e,s);else {if(o===n)return s+1;if(o===r||i&&(o===`
22
+ `||o==="\r"&&e[s+1]===`
23
+ `))return s}}throw new T("cannot find end of structure",{toml:e,ptr:t})}function de(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!=="'"&&_i(e,t));return t>-1&&(t+=r.length,r.length>1&&(e[t]===n&&t++,e[t]===n&&t++)),t}var Ci=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,Nt=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(Ci);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 Ri=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,vi=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,$i=/^[+-]?0[0-9_]/,Ni=/^[0-9a-f]{2,8}$/i,Fn={b:"\b",t:" ",n:`
24
+ `,f:"\f",r:"\r",e:"\x1B",'"':'"',"\\":"\\"};function ge(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
+ `&&t++);let s=0,o,a="",l=t;for(;t<n-1;){let c=e[t++];if(c===`
26
+ `||c==="\r"&&e[t]===`
27
+ `){if(!i)throw new T("newlines are not allowed in strings",{toml:e,ptr:t-1})}else if(c<" "&&c!==" "||c==="\x7F")throw new T("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(!Ni.test(u))throw new T("invalid unicode escape",{toml:e,ptr:s});try{a+=String.fromCodePoint(parseInt(u,16));}catch{throw new T("invalid unicode escape",{toml:e,ptr:s})}}else if(i&&(c===`
28
+ `||c===" "||c===" "||c==="\r")){if(t=K(e,t-1,true),e[t]!==`
29
+ `&&e[t]!=="\r")throw new T("invalid escape: only line-ending whitespace may be escaped",{toml:e,ptr:s});t=K(e,t);}else if(c in Fn)a+=Fn[c];else throw new T("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 In(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=Ri.test(e);if(i||vi.test(e)){if($i.test(e))throw new T("leading zeroes are not allowed",{toml:t,ptr:n});e=e.replace(/_/g,"");let o=+e;if(isNaN(o))throw new T("invalid number",{toml:t,ptr:n});if(i){if((i=!Number.isSafeInteger(o))&&!r)throw new T("integer value cannot be represented losslessly",{toml:t,ptr:n});(i||r===true)&&(o=BigInt(e));}return o}let s=new Nt(e);if(!s.isValid())throw new T("invalid value",{toml:t,ptr:n});return s}function ki(e,t,n){let r=e.slice(t,n),i=r.indexOf("#");return i>-1&&(St(e,i),r=r.slice(0,i)),[r.trimEnd(),i]}function kt(e,t,n,r,i){if(r===0)throw new T("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):Dn(e,t,r,i);if(n){if(c=K(e,c),e[c]===",")c++;else if(e[c]!==n)throw new T("expected comma or end of structure",{toml:e,ptr:c})}return [l,c]}let o;if(s==='"'||s==="'"){o=de(e,t);let l=ge(e,t,o);if(n){if(o=K(e,o),e[o]&&e[o]!==","&&e[o]!==n&&e[o]!==`
30
+ `&&e[o]!=="\r")throw new T("unexpected character encountered",{toml:e,ptr:o});o+=+(e[o]===",");}return [l,o]}o=On(e,t,",",n);let a=ki(e,t,o-+(e[o-1]===","));if(!a[0])throw new T("incomplete key-value declaration: no value specified",{toml:e,ptr:t});return n&&a[1]>-1&&(o=K(e,t+a[1]),o+=+(e[o]===",")),[In(a[0],e,t,i),o]}var Pi=/^[a-zA-Z0-9-_]+[ \t]*$/;function ye(e,t,n="="){let r=t-1,i=[],s=e.indexOf(n,t);if(s<0)throw new T("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 T("multiline strings are not allowed in keys",{toml:e,ptr:t});let a=de(e,t);if(a<0)throw new T("unfinished string encountered",{toml:e,ptr:t});r=e.indexOf(".",a);let l=e.slice(a,r<0||r>s?s:r),c=he(l);if(c>-1)throw new T("newlines are not allowed in keys",{toml:e,ptr:t+r+c});if(l.trimStart())throw new T("found extra tokens after the string part",{toml:e,ptr:a});if(s<a&&(s=e.indexOf(n,a),s<0))throw new T("incomplete key-value: cannot find end of key",{toml:e,ptr:t});i.push(ge(e,t,a));}else {r=e.indexOf(".",t);let a=e.slice(t,r<0||r>s?s:r);if(!Pi.test(a))throw new T("only letter, numbers, dashes and underscores are allowed in keys",{toml:e,ptr:t});i.push(a.trimEnd());}}while(r+1&&r<s);return [i,K(e,s+1,true,true)]}function Dn(e,t,n,r){let i={},s=new Set,o;for(t++;(o=e[t++])!=="}"&&o;){if(o===",")throw new T("expected value, found comma",{toml:e,ptr:t-1});if(o==="#")t=St(e,t);else if(o!==" "&&o!==" "&&o!==`
31
+ `&&o!=="\r"){let a,l=i,c=false,[u,h]=ye(e,t-1);for(let w=0;w<u.length;w++){if(w&&(l=c?l[a]:l[a]={}),a=u[w],(c=Object.hasOwn(l,a))&&(typeof l[a]!="object"||s.has(l[a])))throw new T("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 T("trying to redefine an already defined value",{toml:e,ptr:t});let[d,b]=kt(e,h,"}",n-1,r);s.add(d),l[a]=d,t=b;}}if(!o)throw new T("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 T("expected value, found comma",{toml:e,ptr:t-1});if(s==="#")t=St(e,t);else if(s!==" "&&s!==" "&&s!==`
32
+ `&&s!=="\r"){let o=kt(e,t-1,"]",n-1,r);i.push(o[0]),t=o[1];}}if(!s)throw new T("unfinished array encountered",{toml:e,ptr:t});return [i,t]}function Mn(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 Pt(e,{maxDepth:t=1e3,integersAsBigInt:n}={}){let r={},i={},s=r,o=i;for(let a=K(e,0);a<e.length;){if(e[a]==="["){let l=e[++a]==="[",c=ye(e,a+=+l,"]");if(l){if(e[c[1]-1]!=="]")throw new T("expected end of table declaration",{toml:e,ptr:c[1]-1});c[1]++;}let u=Mn(c[0],r,i,l?2:1);if(!u)throw new T("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=ye(e,a),c=Mn(l[0],s,o,0);if(!c)throw new T("trying to redefine an already defined table or value",{toml:e,ptr:a});let u=kt(e,l[1],void 0,t,n);c[1][c[0]]=u[0],a=u[1];}if(a=K(e,a,true),e[a]&&e[a]!==`
33
+ `&&e[a]!=="\r")throw new T("each key-value declaration must be followed by an end-of-line",{toml:e,ptr:a});a=K(e,a);}return r}var Un=/^[a-z0-9-_]+$/i;function Lt(e){let t=typeof e;if(t==="object"){if(Array.isArray(e))return "array";if(e instanceof Date)return "date"}return t}function Li(e){for(let t=0;t<e.length;t++)if(Lt(e[t])!=="object")return false;return e.length!=0}function Ue(e){return JSON.stringify(e).replace(/\x7f/g,"\\u007f")}function He(e,t,n,r){if(n===0)throw new Error("Could not stringify the object: maximum object depth exceeded");if(t==="number")return isNaN(e)?"nan":e===1/0?"inf":e===-1/0?"-inf":r&&Number.isInteger(e)?e.toFixed(1):e.toString();if(t==="bigint"||t==="boolean")return e.toString();if(t==="string")return Ue(e);if(t==="date"){if(isNaN(e.getTime()))throw new TypeError("cannot serialize invalid date");return e.toISOString()}if(t==="object")return Oi(e,n,r);if(t==="array")return Fi(e,n,r)}function Oi(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+=Un.test(o)?o:Ue(o),i+=" = ",i+=He(e[o],Lt(e[o]),t-1,n);}return i+" }"}function Fi(e,t,n){if(e.length===0)return "[]";let r="[ ";for(let i=0;i<e.length;i++){if(i&&(r+=", "),e[i]===null||e[i]===void 0)throw new TypeError("arrays cannot contain null or undefined values");r+=He(e[i],Lt(e[i]),t-1,n);}return r+" ]"}function Ii(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&&`
63
34
  `}[[${t}]]
64
- `,i+=fs(0,a[r],t,s,e);return i}function fs(a,t,s,e,i){if(e===0)throw new Error("Could not stringify the object: maximum object depth exceeded");let r="",n="",o=Object.keys(t);for(let u=0;u<o.length;u++){let l=o[u];if(t[l]!==null&&t[l]!==void 0){let p=Gt(t[l]);if(p==="symbol"||p==="function")throw new TypeError(`cannot serialize values of type '${p}'`);let f=bi.test(l)?l:ps(l);if(p==="array"&&Jn(t[l]))n+=(n&&`
65
- `)+Kn(t[l],s?`${s}.${f}`:f,e-1,i);else if(p==="object"){let h=s?`${s}.${f}`:f;n+=(n&&`
66
- `)+fs(h,t[l],h,e-1,i);}else r+=f,r+=" = ",r+=cs(t[l],p,e,i),r+=`
67
- `;}}return a&&(r||!n)&&(r=r?`[${a}]
68
- ${r}`:`[${a}]`),r&&n?`${r}
69
- ${n}`:r||n}function hs(a,{maxDepth:t=1e3,numbersAsFloat:s=false}={}){if(Gt(a)!=="object")throw new TypeError("stringify can only be called with an object");let e=fs(0,a,"",t,s);return e[e.length-1]!==`
70
- `?e+`
71
- `:e}var zn={storage:"EXPERIMENTAL_STORAGE",cloud:"EXPERIMENTAL_CLOUD"},Qn=["storage","cloud"];Object.fromEntries(Qn.map(a=>[a,Zn(a)]));function Zn(a){let t=typeof process<"u"&&process.env||void 0;return t?t.NODE_ENV==="test"?true:t[zn[a]]==="1":false}function De(a){let t=[],s="",e=0,i=a.length,r=n=>{ea(n).length>0&&t.push(n.trim());};for(;e<i;){let n=a[e],o=a[e+1];if(n==="-"&&o==="-"){for(;e<i&&a[e]!==`
72
- `;)s+=a[e],e++;continue}if(n==="/"&&o==="*"){for(s+="/*",e+=2;e<i&&!(a[e]==="*"&&a[e+1]==="/");)s+=a[e],e++;e<i&&(s+="*/",e+=2);continue}if(n==="'"){for(s+=n,e++;e<i;){if(a[e]==="'"&&a[e+1]==="'"){s+="''",e+=2;continue}if(s+=a[e],a[e]==="'"){e++;break}e++;}continue}if(n==='"'){for(s+=n,e++;e<i;){if(a[e]==='"'&&a[e+1]==='"'){s+='""',e+=2;continue}if(s+=a[e],a[e]==='"'){e++;break}e++;}continue}if(n==="$"){let u=a.indexOf("$",e+1);if(u!==-1){let l=a.slice(e,u+1);if(/^\$[A-Za-z_][A-Za-z0-9_]*\$$|^\$\$$/.test(l)){s+=l,e=u+1;let f=a.indexOf(l,e);f===-1?(s+=a.slice(e),e=i):(s+=a.slice(e,f+l.length),e=f+l.length);continue}}}if(n===";"){r(s),s="",e++;continue}s+=n,e++;}return r(s),t}function ea(a){let t="",s=0,e=a.length;for(;s<e;){let i=a[s],r=a[s+1];if(i==="-"&&r==="-"){for(;s<e&&a[s]!==`
73
- `;)s++;continue}if(i==="/"&&r==="*"){for(s+=2;s<e&&!(a[s]==="*"&&a[s+1]==="/");)s++;s+=2;continue}t+=i,s++;}return t.trim()}function ms(a){return typeof a=="number"?a:Number.parseInt(String(a),10)}var $e=class{driver=G;basePath;constructor(t){this.basePath=v.resolve(t.basePath);}filePath(t,s){return v.join(this.basePath,t,s)}async ensureDir(t){await G.mkdir(v.dirname(t),{recursive:true});}async getObject(t,s,e,i){let r=this.filePath(t,s),n=await G.stat(r),o=`"${createHash("md5").update(`${r}:${n.mtimeMs}`).digest("hex")}"`;if(i?.ifNoneMatch===o)return {httpStatusCode:304,metadata:this.buildMetadata(n,o,s)};if(i?.ifModifiedSince){let h=new Date(i.ifModifiedSince);if(n.mtime<=h)return {httpStatusCode:304,metadata:this.buildMetadata(n,o,s)}}let u,l,p=n.size,f=200;if(i?.range){let h=i.range.match(/^bytes=(\d+)-(\d*)$/);if(h){let E=Number.parseInt(h[1],10),g=h[2]?Number.parseInt(h[2],10):n.size-1;p=g-E+1,l=`bytes ${E}-${g}/${n.size}`,f=206,u=(await G.open(r,"r")).readableWebStream();}else u=(await G.open(r,"r")).readableWebStream();}else u=(await G.open(r,"r")).readableWebStream();return {httpStatusCode:f,metadata:{...this.buildMetadata(n,o,s),contentLength:p,contentRange:l},body:u}}async uploadObject(t,s,e,i,r,n){let o=this.filePath(t,s);await this.ensureDir(o);let u;if(i instanceof Uint8Array||Buffer.isBuffer(i))u=i;else {let f=[],h=i.getReader();for(;;){let{done:E,value:g}=await h.read();if(E)break;f.push(g);}u=Buffer.concat(f);}await G.writeFile(o,u);let l=await G.stat(o),p=`"${createHash("md5").update(u).digest("hex")}"`;return {cacheControl:n,contentLength:l.size,size:l.size,mimetype:r,lastModified:l.mtime,eTag:p}}async deleteObject(t,s,e){let i=this.filePath(t,s);await G.unlink(i).catch(r=>{if(r.code!=="ENOENT")throw r});}async deleteObjects(t,s){for(let e of s)await this.deleteObject(t,e,void 0);}async copyObject(t,s,e,i,r){let n=this.filePath(t,s),o=this.filePath(t,i);await this.ensureDir(o),await G.copyFile(n,o);let u=await G.stat(o),l=await G.readFile(o);return {httpStatusCode:200,eTag:`"${createHash("md5").update(l).digest("hex")}"`,lastModified:u.mtime}}async headObject(t,s,e){let i=this.filePath(t,s),r=await G.stat(i),n=`"${createHash("md5").update(`${i}:${r.mtimeMs}`).digest("hex")}"`;return this.buildMetadata(r,n,s)}async privateAssetUrl(t,s,e){return `file://${this.filePath(t,s)}`}buildMetadata(t,s,e){return {cacheControl:"no-cache",contentLength:ms(t.size),size:ms(t.size),mimetype:sa(e),lastModified:t.mtime,eTag:s}}};function sa(a){let t=v.extname(a).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 ia=new Function("spec","return import(spec)");async function Es(a,t,s){try{return await ia(a)}catch(e){throw e?.code==="ERR_MODULE_NOT_FOUND"||/Cannot find package/.test(String(e?.message))?new Error(`Driver '${t}' selected but '${s}' is not installed. Run: bun add ${s}`):e}}function _i(a,t={}){let s=v__default.resolve(t.cwd??process.cwd()),e=t.env??process.env,i=process.env.SUPABASE_ENV||"development",r=[`.env.${i}.local`,i==="test"?null:".env.local",`.env.${i}`,".env"].filter(o=>o!==null),n=aa(v__default.resolve(a),s);for(let o of n)for(let u of r){let l=v__default.join(o,u),p;try{p=Ne.readFileSync(l,"utf-8");}catch{continue}let f;try{f=parse(p);}catch(h){throw new Error(`Failed to parse ${l}: ${h.message}`)}for(let[h,E]of Object.entries(f))e[h]===void 0&&(e[h]=E);}}function aa(a,t){let s=[],e=a,i=v__default.parse(e).root;for(;s.push(e),!(e===t||e===i);){let r=v__default.dirname(e);if(r===e)break;e=r;}return s}var oa=/^env\((\w+)\)$/;function wi(a,t=process.env){return gs(a,t)}function gs(a,t){if(typeof a=="string"){let s=a.match(oa);return s?t[s[1]]??"":a}if(Array.isArray(a))return a.map(s=>gs(s,t));if(a&&typeof a=="object"){let s={};for(let[e,i]of Object.entries(a))s[e]=gs(i,t);return s}return a}var la=["toml","json","ts","mts","js","mjs","cjs"],je=class extends Lt{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 s=v__default.relative(process.cwd(),gt.config_dir);if(!t)for(let e of la){let i=v__default.join(s,`config.${e}`);if(await G__default.access(i).then(()=>true).catch(()=>false)){t=i;break}}return t}async readConfig(t){let s=await this.getConfigPath(t);if(!s)return {};console.log(Ht.default.dim(`Using config file: ${Ht.default.cyan(`./${s}`)}`));let e=v__default.dirname(v__default.resolve(s));_i(e);let i=s.split(".").pop(),r;switch(i){case "toml":r=Vt(await G__default.readFile(s,"utf-8"));break;case "json":r=JSON.parse(await G__default.readFile(s,"utf-8"));break;case "ts":case "mts":case "js":case "mjs":case "cjs":try{r=(await import(v__default.join(process.cwd(),s))).default;break}catch(n){throw console.error("Failed to import config file",n),n}default:throw new Error(`Unsupported config file type: ${s}`)}return wi(r)}async createConnection(){throw new Error("Not implemented")}async getConfig(t){let s=await this.readConfig(t);if("connection"in s)return {...s,connection:await s.connection};let e,i;switch(s.db?.driver){case "sqlite":i=s.db?.url??gt.default_db_url,e=await createConnection({url:i,ddlDialect:"sqlite"});break;case "pglite":{i=s.db?.url??v__default.join(process.cwd(),gt.default_db_dir);let{createPgliteConnection:r}=await Es("@supabase/lite/pglite","pglite","@electric-sql/pglite");e=await r({url:i});break}case "postgres":{i=s.db?.url??"";let{createPostgresConnection:r}=await Es("@supabase/lite/postgres","postgres","postgres");e=await r({url:i});break}default:i=s.db?.url??gt.default_db_url,e=await createConnection({url:i,ddlDialect:"postgres"});break}if(!e)throw new Error("Failed to create connection");return console.log(Ht.default.green(" \u279C"),"Database located at",Ht.default.cyan(i??"in-memory")),{...s,connection:e}}async createApp(t){let s=await this.getConfig(t),e=new App(s);return e.config.storage?.enabled&&process.env.EXPERIMENTAL_STORAGE==="1"&&!e._storageAdapter&&(e._storageAdapter=new $e({basePath:v__default.join(process.cwd(),gt.config_dir,".temp/storage")})),await e.init()}};var ke=class extends Lt{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 s=await t.json();if(!s||!s.data)throw new Error("Failed to list projects");return s.data}async get(t){if(t=t??this.projectRef(),!t)throw new Error("No project ref found");let s=await this.fetch(`/v1/projects/${t}`);if(!s.ok)throw new Error(`Failed to get project: ${s.status} ${s.statusText}`);let e=await s.json();if(!e||!e.id)throw new Error("Failed to get project");return e}async create(t={}){let s=await this.fetch("/v1/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok)throw new Error(`Failed to create project: ${s.status} ${s.statusText}`);let e=await s.json();if(!e.data||!e.data.id)throw new Error("Failed to create project");return e.data}async getConfig(t){let s=await this.fetch(`/v1/projects/${t}/config`);if(!s.ok)throw new Error(`Failed to get project config: ${s.status} ${s.statusText}`);let e=await s.json();if(!e)throw new Error("Failed to get project config");return e}async setConfig(t,s){let e=await this.fetch(`/v1/projects/${t}/config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!e.ok)throw new Error(`Failed to set project config: ${e.status} ${e.statusText}`);return true}async createApp(t){if(!this.config.host)throw new Error("No host specified");let{data:s,error:e}=await this.client.auth.getSession();if(e)throw e;if(!s?.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:s.session.access_token,host:this.config.host})}).init()}};var Fe=class extends yt{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:s}=await this.getSession();if(s)throw s;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 je(t),remote:new ke(t)},this}};async function fa(a={}){return await new Fe({host:Bt,root:ht.projectDir(),...a}).init()}var Rs=Ut(Mt());var As=Ut(Mt());var ha=["toml","json","ts","mts","js","mjs","cjs"];async function Be(a){let t=v__default.relative(process.cwd(),gt.config_dir);if(!a)for(let s of ha){let e=v__default.join(t,`config.${s}`);if(await G__default.access(e).then(()=>true).catch(()=>false)){a=e;break}}return a}async function yi(a){let t=await Be(a);if(!t)return {};switch(console.log(As.default.dim(`Using config file: ${As.default.cyan(`./${t}`)}`)),t.split(".").pop()){case "toml":return Vt(await G__default.readFile(t,"utf-8"));case "json":return JSON.parse(await G__default.readFile(t,"utf-8"));case "ts":case "mts":case "js":case "mjs":case "cjs":try{return (await import(v__default.join(process.cwd(),t))).default}catch(e){throw console.error("Failed to import config file",e),e}default:throw new Error(`Unsupported config file type: ${t}`)}}function Li(a){if(!a||a===":memory:")return;let t=a;if(t.startsWith("file://")?t=t.slice(7):t.startsWith("file:")&&(t=t.slice(5)),!(!t||t===":memory:"))return v__default.resolve(process.cwd(),t)}async function ma(a={}){let t=process.cwd();if(a.recreate){console.log(Rs.default.dim("Recreating database..."));try{let e=await Be();if(e&&!/\.(ts|mts|js|mjs|cjs)$/.test(e)){let r=(await yi(e))?.db?.url,n=r?Li(r):void 0;n&&Ne.existsSync(n)&&(Ne.rmSync(n,{recursive:!0,force:!0}),console.log(Rs.default.dim(` \u279C removed ${v__default.relative(t,n)}`)));}}catch{}try{Ne.rmSync(v__default.join(t,"supabase",".temp"),{recursive:!0,force:!0});}catch{}}if(at(v__default.join(t,"supabase")),!await Be()){let e={db:{driver:"sqlite-postgres",url:"file:./supabase/.temp/data.db"},auth:{enabled:true}};a.driver==="pglite"&&(e.db.driver="pglite",e.db.url=v__default.relative(process.cwd(),v__default.join(t,"supabase",".temp","data")));let i=a.configFormat??"toml",r=v__default.join(t,"supabase",`config.${i}`);i==="json"?Rt(r,JSON.stringify(e)):Rt(r,hs(e));}at(v__default.join(t,"supabase",".temp")),at(v__default.join(t,"supabase","schemas"),()=>{Rt(v__default.join(t,"supabase","schemas","schema.sql"),a.template?Ea:`-- This is a schema file for the database
74
- `);}),Rt(v__default.join(t,"supabase","seed.sql"),a.template?ga:`-- This is a seed file for the database
75
- `);}var Ea=`
35
+ `,i+=Be(0,e[s],t,n,r);return i}function Be(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=Lt(t[c]);if(u==="symbol"||u==="function")throw new TypeError(`cannot serialize values of type '${u}'`);let h=Un.test(c)?c:Ue(c);if(u==="array"&&Li(t[c]))o+=(o&&`
36
+ `)+Ii(t[c],n?`${n}.${h}`:h,r-1,i);else if(u==="object"){let d=n?`${n}.${h}`:h;o+=(o&&`
37
+ `)+Be(d,t[c],d,r-1,i);}else s+=h,s+=" = ",s+=He(t[c],u,r,i),s+=`
38
+ `;}}return e&&(s||!o)&&(s=s?`[${e}]
39
+ ${s}`:`[${e}]`),s&&o?`${s}
40
+ ${o}`:s||o}function qe(e,{maxDepth:t=1e3,numbersAsFloat:n=false}={}){if(Lt(e)!=="object")throw new TypeError("stringify can only be called with an object");let r=Be(0,e,"",t,n);return r[r.length-1]!==`
41
+ `?r+`
42
+ `:r}var Di={storage:"EXPERIMENTAL_STORAGE",cloud:"EXPERIMENTAL_CLOUD"},ji=["storage","cloud"];Object.fromEntries(ji.map(e=>[e,Mi(e)]));function Mi(e){let t=typeof process<"u"&&process.env||void 0;return t?t.NODE_ENV==="test"?true:t[Di[e]]==="1":false}function be(e){let t=[],n="",r=0,i=e.length,s=o=>{Hi(o).length>0&&t.push(o.trim());};for(;r<i;){let o=e[r],a=e[r+1];if(o==="-"&&a==="-"){for(;r<i&&e[r]!==`
43
+ `;)n+=e[r],r++;continue}if(o==="/"&&a==="*"){for(n+="/*",r+=2;r<i&&!(e[r]==="*"&&e[r+1]==="/");)n+=e[r],r++;r<i&&(n+="*/",r+=2);continue}if(o==="'"){for(n+=o,r++;r<i;){if(e[r]==="'"&&e[r+1]==="'"){n+="''",r+=2;continue}if(n+=e[r],e[r]==="'"){r++;break}r++;}continue}if(o==='"'){for(n+=o,r++;r<i;){if(e[r]==='"'&&e[r+1]==='"'){n+='""',r+=2;continue}if(n+=e[r],e[r]==='"'){r++;break}r++;}continue}if(o==="$"){let l=e.indexOf("$",r+1);if(l!==-1){let c=e.slice(r,l+1);if(/^\$[A-Za-z_][A-Za-z0-9_]*\$$|^\$\$$/.test(c)){n+=c,r=l+1;let h=e.indexOf(c,r);h===-1?(n+=e.slice(r),r=i):(n+=e.slice(r,h+c.length),r=h+c.length);continue}}}if(o===";"){s(n),n="",r++;continue}n+=o,r++;}return s(n),t}function Hi(e){let t="",n=0,r=e.length;for(;n<r;){let i=e[n],s=e[n+1];if(i==="-"&&s==="-"){for(;n<r&&e[n]!==`
44
+ `;)n++;continue}if(i==="/"&&s==="*"){for(n+=2;n<r&&!(e[n]==="*"&&e[n+1]==="/");)n++;n+=2;continue}t+=i,n++;}return t.trim()}function Ve(e){return typeof e=="number"?e:Number.parseInt(String(e),10)}var xe=class{driver=M;basePath;constructor(t){this.basePath=nt.resolve(t.basePath);}filePath(t,n){return nt.join(this.basePath,t,n)}async ensureDir(t){await M.mkdir(nt.dirname(t),{recursive:true});}async getObject(t,n,r,i){let s=this.filePath(t,n),o=await M.stat(s),a=`"${createHash("md5").update(`${s}:${o.mtimeMs}`).digest("hex")}"`;if(i?.ifNoneMatch===a)return {httpStatusCode:304,metadata:this.buildMetadata(o,a,n)};if(i?.ifModifiedSince){let d=new Date(i.ifModifiedSince);if(o.mtime<=d)return {httpStatusCode:304,metadata:this.buildMetadata(o,a,n)}}let l,c,u=o.size,h=200;if(i?.range){let d=i.range.match(/^bytes=(\d+)-(\d*)$/);if(d){let b=Number.parseInt(d[1],10),w=d[2]?Number.parseInt(d[2],10):o.size-1;u=w-b+1,c=`bytes ${b}-${w}/${o.size}`,h=206,l=(await M.open(s,"r")).readableWebStream();}else l=(await M.open(s,"r")).readableWebStream();}else l=(await M.open(s,"r")).readableWebStream();return {httpStatusCode:h,metadata:{...this.buildMetadata(o,a,n),contentLength:u,contentRange:c},body:l}}async uploadObject(t,n,r,i,s,o){let a=this.filePath(t,n);await this.ensureDir(a);let l;if(i instanceof Uint8Array||Buffer.isBuffer(i))l=i;else {let h=[],d=i.getReader();for(;;){let{done:b,value:w}=await d.read();if(b)break;h.push(w);}l=Buffer.concat(h);}await M.writeFile(a,l);let c=await M.stat(a),u=`"${createHash("md5").update(l).digest("hex")}"`;return {cacheControl:o,contentLength:c.size,size:c.size,mimetype:s,lastModified:c.mtime,eTag:u}}async deleteObject(t,n,r){let i=this.filePath(t,n);await M.unlink(i).catch(s=>{if(s.code!=="ENOENT")throw s});}async deleteObjects(t,n){for(let r of n)await this.deleteObject(t,r,void 0);}async copyObject(t,n,r,i,s){let o=this.filePath(t,n),a=this.filePath(t,i);await this.ensureDir(a),await M.copyFile(o,a);let l=await M.stat(a),c=await M.readFile(a);return {httpStatusCode:200,eTag:`"${createHash("md5").update(c).digest("hex")}"`,lastModified:l.mtime}}async headObject(t,n,r){let i=this.filePath(t,n),s=await M.stat(i),o=`"${createHash("md5").update(`${i}:${s.mtimeMs}`).digest("hex")}"`;return this.buildMetadata(s,o,n)}async privateAssetUrl(t,n,r){return `file://${this.filePath(t,n)}`}buildMetadata(t,n,r){return {cacheControl:"no-cache",contentLength:Ve(t.size),size:Ve(t.size),mimetype:Bi(r),lastModified:t.mtime,eTag:n}}};function Bi(e){let t=nt.extname(e).toLowerCase();return {".html":"text/html",".css":"text/css",".js":"application/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".webp":"image/webp",".avif":"image/avif",".pdf":"application/pdf",".txt":"text/plain",".xml":"application/xml",".zip":"application/zip",".mp4":"video/mp4",".webm":"video/webm",".mp3":"audio/mpeg",".wav":"audio/wav",".woff":"font/woff",".woff2":"font/woff2"}[t]??"application/octet-stream"}var qi=new Function("spec","return import(spec)");async function Ge(e,t,n){try{return await qi(e)}catch(r){throw r?.code==="ERR_MODULE_NOT_FOUND"||/Cannot find package/.test(String(r?.message))?new Error(`Driver '${t}' selected but '${n}' is not installed. Run: bun add ${n}`):r}}function Bn(e,t={}){let n=nt__default.resolve(t.cwd??process.cwd()),r=t.env??process.env,i=process.env.SUPABASE_ENV||"development",s=[`.env.${i}.local`,i==="test"?null:".env.local",`.env.${i}`,".env"].filter(a=>a!==null),o=Wi(nt__default.resolve(e),n);for(let a of o)for(let l of s){let c=nt__default.join(a,l),u;try{u=le.readFileSync(c,"utf-8");}catch{continue}let h;try{h=parse(u);}catch(d){throw new Error(`Failed to parse ${c}: ${d.message}`)}for(let[d,b]of Object.entries(h))r[d]===void 0&&(r[d]=b);}}function Wi(e,t){let n=[],r=e,i=nt__default.parse(r).root;for(;n.push(r),!(r===t||r===i);){let s=nt__default.dirname(r);if(s===r)break;r=s;}return n}var zi=/^env\((\w+)\)$/;function qn(e,t=process.env){return We(e,t)}function We(e,t){if(typeof e=="string"){let n=e.match(zi);return n?t[n[1]]??"":e}if(Array.isArray(e))return e.map(n=>We(n,t));if(e&&typeof e=="object"){let n={};for(let[r,i]of Object.entries(e))n[r]=We(i,t);return n}return e}var Xi=["toml","json","ts","mts","js","mjs","cjs"],Se=class extends xt{ref(){return this.projectRef()}setRef(t){return this.tempFs.write("project-ref",t),this}link(t){return this.setRef(t.id),t}unlink(){return this.tempFs.delete("project-ref"),this}url(){let t=this.ref();if(!t)throw new Error("No project linked");return this.projectUrl(t)}async getConfigPath(t){let n=nt__default.relative(process.cwd(),ct.config_dir);if(!t)for(let r of Xi){let i=nt__default.join(n,`config.${r}`);if(await M__default.access(i).then(()=>true).catch(()=>false)){t=i;break}}return t}async readConfig(t){let n=await this.getConfigPath(t);if(!n)return {};console.log(Ft.default.dim(`Using config file: ${Ft.default.cyan(`./${n}`)}`));let r=nt__default.dirname(nt__default.resolve(n));Bn(r);let i=n.split(".").pop(),s;switch(i){case "toml":s=Pt(await M__default.readFile(n,"utf-8"));break;case "json":s=JSON.parse(await M__default.readFile(n,"utf-8"));break;case "ts":case "mts":case "js":case "mjs":case "cjs":try{s=(await import(nt__default.join(process.cwd(),n))).default;break}catch(o){throw console.error("Failed to import config file",o),o}default:throw new Error(`Unsupported config file type: ${n}`)}return qn(s)}async createConnection(){throw new Error("Not implemented")}async getConfig(t){let n=await this.readConfig(t);if("connection"in n)return {...n,connection:await n.connection};let r,i;switch(n.db?.driver){case "sqlite":i=n.db?.url??ct.default_db_url,r=await createConnection({url:i,ddlDialect:"sqlite"});break;case "pglite":{i=n.db?.url??nt__default.join(process.cwd(),ct.default_db_dir);let{createPgliteConnection:s}=await Ge("@supabase/lite/pglite","pglite","@electric-sql/pglite");r=await s({url:i});break}case "postgres":{i=n.db?.url??"";let{createPostgresConnection:s}=await Ge("@supabase/lite/postgres","postgres","postgres");r=await s({url:i});break}default:i=n.db?.url??ct.default_db_url,r=await createConnection({url:i,ddlDialect:"postgres"});break}if(!r)throw new Error("Failed to create connection");return console.log(Ft.default.green(" \u279C"),"Database located at",Ft.default.cyan(i??"in-memory")),{...n,connection:r}}async createApp(t){let n=await this.getConfig(t),r=new App(n);return r.config.storage?.enabled&&process.env.EXPERIMENTAL_STORAGE==="1"&&!r._storageAdapter&&(r._storageAdapter=new xe({basePath:nt__default.join(process.cwd(),ct.config_dir,".temp/storage")})),await r.init()}};var Ee=class extends xt{url(t){return this.projectUrl(t)}async ping(){return (await this.fetch("/v1/system/ping")).ok}async list(){let t=await this.fetch("/v1/projects");if(!t.ok)throw new Error("Failed to list projects");let n=await t.json();if(!n||!n.data)throw new Error("Failed to list projects");return n.data}async get(t){if(t=t??this.projectRef(),!t)throw new Error("No project ref found");let n=await this.fetch(`/v1/projects/${t}`);if(!n.ok)throw new Error(`Failed to get project: ${n.status} ${n.statusText}`);let r=await n.json();if(!r||!r.id)throw new Error("Failed to get project");return r}async create(t={}){let n=await this.fetch("/v1/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)throw new Error(`Failed to create project: ${n.status} ${n.statusText}`);let r=await n.json();if(!r.data||!r.data.id)throw new Error("Failed to create project");return r.data}async getConfig(t){let n=await this.fetch(`/v1/projects/${t}/config`);if(!n.ok)throw new Error(`Failed to get project config: ${n.status} ${n.statusText}`);let r=await n.json();if(!r)throw new Error("Failed to get project config");return r}async setConfig(t,n){let r=await this.fetch(`/v1/projects/${t}/config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok)throw new Error(`Failed to set project config: ${r.status} ${r.statusText}`);return true}async createApp(t){if(!this.config.host)throw new Error("No host specified");let{data:n,error:r}=await this.client.auth.getSession();if(r)throw r;if(!n?.session?.access_token)throw new Error("Not authenticated, sign in first.");let i=await this.getConfig(t);return await new App({...i.config,connection:cloud({projectRef:t,token:n.session.access_token,host:this.config.host})}).init()}};var Ae=class extends wt{project;get client(){if(!this._client)throw new Error("Supabase client not initialized");return this._client}async getSession(){return await this.client.auth.getSession()}async getAccessToken(){let{data:t,error:n}=await this.getSession();if(n)throw n;return t?.session?.access_token}async requireSession(){let t=await this.getAccessToken();if(!t)throw new Error("Not authenticated, sign in first.");return t}async init(){let t={...this.config};return this.config.withSupabaseClient!==false&&(t.client=this.client,t.token=await this.getAccessToken()),this.project={local:new Se(t),remote:new Ee(t)},this}};async function Qi(e={}){return await new Ae({host:vt,root:ot.projectDir(),...e}).init()}var Ye=Rt($t());var Xe=Rt($t());var Zi=["toml","json","ts","mts","js","mjs","cjs"];async function _e(e){let t=nt__default.relative(process.cwd(),ct.config_dir);if(!e)for(let n of Zi){let r=nt__default.join(t,`config.${n}`);if(await M__default.access(r).then(()=>true).catch(()=>false)){e=r;break}}return e}async function Gn(e){let t=await _e(e);if(!t)return {};switch(console.log(Xe.default.dim(`Using config file: ${Xe.default.cyan(`./${t}`)}`)),t.split(".").pop()){case "toml":return Pt(await M__default.readFile(t,"utf-8"));case "json":return JSON.parse(await M__default.readFile(t,"utf-8"));case "ts":case "mts":case "js":case "mjs":case "cjs":try{return (await import(nt__default.join(process.cwd(),t))).default}catch(r){throw console.error("Failed to import config file",r),r}default:throw new Error(`Unsupported config file type: ${t}`)}}function Wn(e){if(!e||e===":memory:")return;let t=e;if(t.startsWith("file://")?t=t.slice(7):t.startsWith("file:")&&(t=t.slice(5)),!(!t||t===":memory:"))return nt__default.resolve(process.cwd(),t)}async function ts(e={}){let t=process.cwd();if(e.recreate){console.log(Ye.default.dim("Recreating database..."));try{let r=await _e();if(r&&!/\.(ts|mts|js|mjs|cjs)$/.test(r)){let s=(await Gn(r))?.db?.url,o=s?Wn(s):void 0;o&&le.existsSync(o)&&(le.rmSync(o,{recursive:!0,force:!0}),console.log(Ye.default.dim(` \u279C removed ${nt__default.relative(t,o)}`)));}}catch{}try{le.rmSync(nt__default.join(t,"supabase",".temp"),{recursive:!0,force:!0});}catch{}}if(tt(nt__default.join(t,"supabase")),!await _e()){let r={db:{driver:"sqlite-postgres",url:"file:./supabase/.temp/data.db"},auth:{enabled:true}};e.driver==="pglite"&&(r.db.driver="pglite",r.db.url=nt__default.relative(process.cwd(),nt__default.join(t,"supabase",".temp","data")));let i=e.configFormat??"toml",s=nt__default.join(t,"supabase",`config.${i}`);i==="json"?mt(s,JSON.stringify(r)):mt(s,qe(r));}tt(nt__default.join(t,"supabase",".temp")),tt(nt__default.join(t,"supabase","schemas"),()=>{mt(nt__default.join(t,"supabase","schemas","schema.sql"),e.template?es:`-- This is a schema file for the database
45
+ `);}),mt(nt__default.join(t,"supabase","seed.sql"),e.template?ns:`-- This is a seed file for the database
46
+ `);}var es=`
76
47
  create table todos (
77
48
  id serial primary key,
78
49
  title text not null,
@@ -85,13 +56,13 @@ create table todos (
85
56
  create table test (
86
57
  id serial primary key,
87
58
  name text not null
88
- )`,ga="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 Ii=createRequire(import.meta.url);function ba(a){let t=normalize(a);return t.length>1&&t[t.length-1]===sep&&(t=t.substring(0,t.length-1)),t}var Oa=/[\\/]/g;function Pi(a,t){return a.replace(Oa,t)}var _a=/^[a-z]:[\\/]$/i;function wa(a){return a==="/"||_a.test(a)}function Ns(a,t){let{resolvePaths:s,normalizePath:e,pathSeparator:i}=t,r=process.platform==="win32"&&a.includes("/")||a.startsWith(".");if(s&&(a=resolve$1(a)),(e||r)&&(a=ba(a)),a===".")return "";let n=a[a.length-1]!==i;return Pi(n?a+i:a,i)}function $i(a,t){return t+a}function da(a,t){return function(s,e){return e.startsWith(a)?e.slice(a.length)+s:Pi(relative$1(a,e),t.pathSeparator)+t.pathSeparator+s}}function ya(a){return a}function La(a,t,s){return t+a+s}function Ia(a,t){let{relativePaths:s,includeBasePath:e}=t;return s&&a?da(a,t):e?$i:ya}function va(a){return function(t,s){s.push(t.substring(a.length)||".");}}function Da(a){return function(t,s,e){let i=t.substring(a.length)||".";e.every(r=>r(i,true))&&s.push(i);}}var Pa=(a,t)=>{t.push(a||".");},$a=(a,t,s)=>{let e=a||".";s.every(i=>i(e,true))&&t.push(e);},ja=()=>{};function ka(a,t){let{includeDirs:s,filters:e,relativePaths:i}=t;return s?i?e&&e.length?Da(a):va(a):e&&e.length?$a:Pa:ja}var Fa=(a,t,s,e)=>{e.every(i=>i(a,false))&&s.files++;},Ua=(a,t,s,e)=>{e.every(i=>i(a,false))&&t.push(a);},Ba=(a,t,s,e)=>{s.files++;},Ma=(a,t)=>{t.push(a);},xa=()=>{};function qa(a){let{excludeFiles:t,filters:s,onlyCounts:e}=a;return t?xa:s&&s.length?e?Fa:Ua:e?Ba:Ma}var Va=a=>a,Ga=()=>[""].slice(0,0);function Wa(a){return a.group?Ga:Va}var Ha=(a,t,s)=>{a.push({directory:t,files:s,dir:t});},Ja=()=>{};function Ya(a){return a.group?Ha:Ja}var Xa=function(a,t,s){let{queue:e,fs:i,options:{suppressErrors:r}}=t;e.enqueue(),i.realpath(a,(n,o)=>{if(n)return e.dequeue(r?null:n,t);i.stat(o,(u,l)=>{if(u)return e.dequeue(r?null:u,t);if(l.isDirectory()&&ji(a,o,t))return e.dequeue(null,t);s(l,o),e.dequeue(null,t);});});},Ka=function(a,t,s){let{queue:e,fs:i,options:{suppressErrors:r}}=t;e.enqueue();try{let n=i.realpathSync(a),o=i.statSync(n);if(o.isDirectory()&&ji(a,n,t))return;s(o,n);}catch(n){if(!r)throw n}};function za(a,t){return !a.resolveSymlinks||a.excludeSymlinks?null:t?Ka:Xa}function ji(a,t,s){if(s.options.useRealPaths)return Qa(t,s);let e=dirname(a),i=1;for(;e!==s.root&&i<2;){let r=s.symlinks.get(e);!!r&&(r===t||r.startsWith(t)||t.startsWith(r))?i++:e=dirname(e);}return s.symlinks.set(a,t),i>1}function Qa(a,t){return t.visited.includes(a+t.options.pathSeparator)}var Za=a=>a.counts,to=a=>a.groups,eo=a=>a.paths,so=a=>a.paths.slice(0,a.options.maxFiles),io=(a,t,s)=>(Me(t,s,a.counts,a.options.suppressErrors),null),ro=(a,t,s)=>(Me(t,s,a.paths,a.options.suppressErrors),null),no=(a,t,s)=>(Me(t,s,a.paths.slice(0,a.options.maxFiles),a.options.suppressErrors),null),ao=(a,t,s)=>(Me(t,s,a.groups,a.options.suppressErrors),null);function Me(a,t,s,e){t(a&&!e?a:null,s);}function oo(a,t){let{onlyCounts:s,group:e,maxFiles:i}=a;return s?t?Za:io:e?t?to:ao:i?t?so:no:t?eo:ro}var ki={withFileTypes:true},uo=(a,t,s,e,i)=>{if(a.queue.enqueue(),e<0)return a.queue.dequeue(null,a);let{fs:r}=a;a.visited.push(t),a.counts.directories++,r.readdir(t||".",ki,(n,o=[])=>{i(o,s,e),a.queue.dequeue(a.options.suppressErrors?null:n,a);});},lo=(a,t,s,e,i)=>{let{fs:r}=a;if(e<0)return;a.visited.push(t),a.counts.directories++;let n=[];try{n=r.readdirSync(t||".",ki);}catch(o){if(!a.options.suppressErrors)throw o}i(n,s,e);};function po(a){return a?lo:uo}var co=class{count=0;constructor(a){this.onQueueEmpty=a;}enqueue(){return this.count++,this.count}dequeue(a,t){this.onQueueEmpty&&(--this.count<=0||a)&&(this.onQueueEmpty(a,t),a&&(t.controller.abort(),this.onQueueEmpty=void 0));}},fo=class{_files=0;_directories=0;set files(a){this._files=a;}get files(){return this._files}set directories(a){this._directories=a;}get directories(){return this._directories}get dirs(){return this._directories}},ho=class{aborted=false;abort(){this.aborted=true;}},Fi=class{root;isSynchronous;state;joinPath;pushDirectory;pushFile;getArray;groupFiles;resolveSymlink;walkDirectory;callbackInvoker;constructor(a,t,s){this.isSynchronous=!s,this.callbackInvoker=oo(t,this.isSynchronous),this.root=Ns(a,t),this.state={root:wa(this.root)?this.root:this.root.slice(0,-1),paths:[""].slice(0,0),groups:[],counts:new fo,options:t,queue:new co((e,i)=>this.callbackInvoker(i,e,s)),symlinks:new Map,visited:[""].slice(0,0),controller:new ho,fs:t.fs||Dt},this.joinPath=Ia(this.root,t),this.pushDirectory=ka(this.root,t),this.pushFile=qa(t),this.getArray=Wa(t),this.groupFiles=Ya(t),this.resolveSymlink=za(t,this.isSynchronous),this.walkDirectory=po(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=(a,t,s)=>{let{paths:e,options:{filters:i,resolveSymlinks:r,excludeSymlinks:n,exclude:o,maxFiles:u,signal:l,useRealPaths:p,pathSeparator:f},controller:h}=this.state;if(h.aborted||l&&l.aborted||u&&e.length>u)return;let E=this.getArray(this.state.paths);for(let g=0;g<a.length;++g){let R=a[g];if(R.isFile()||R.isSymbolicLink()&&!r&&!n){let b=this.joinPath(R.name,t);this.pushFile(b,E,this.state.counts,i);}else if(R.isDirectory()){let b=La(R.name,t,this.state.options.pathSeparator);if(o&&o(R.name,b))continue;this.pushDirectory(b,e,i),this.walkDirectory(this.state,b,b,s-1,this.walk);}else if(this.resolveSymlink&&R.isSymbolicLink()){let b=$i(R.name,t);this.resolveSymlink(b,this.state,(d,O)=>{if(d.isDirectory()){if(O=Ns(O,this.state.options),o&&o(R.name,p?O:b+f))return;this.walkDirectory(this.state,O,p?O:b+f,s-1,this.walk);}else {O=p?O:b;let J=basename(O),et=Ns(dirname(O),this.state.options);O=this.joinPath(J,et),this.pushFile(O,E,this.state.counts,i);}});}}this.groupFiles(this.state.groups,t,E);}};function mo(a,t){return new Promise((s,e)=>{Ui(a,t,(i,r)=>{if(i)return e(i);s(r);});})}function Ui(a,t,s){new Fi(a,t,s).start();}function Eo(a,t){return new Fi(a,t).start()}var vi=class{constructor(a,t){this.root=a,this.options=t;}withPromise(){return mo(this.root,this.options)}withCallback(a){Ui(this.root,this.options,a);}sync(){return Eo(this.root,this.options)}},Bi=null;try{Ii.resolve("picomatch"),Bi=Ii("picomatch");}catch{}var Mi=class{globCache={};options={maxDepth:1/0,suppressErrors:true,pathSeparator:sep,filters:[]};globFunction;constructor(a){this.options={...this.options,...a},this.globFunction=this.options.globFunction;}group(){return this.options.group=true,this}withPathSeparator(a){return this.options.pathSeparator=a,this}withBasePath(){return this.options.includeBasePath=true,this}withRelativePaths(){return this.options.relativePaths=true,this}withDirs(){return this.options.includeDirs=true,this}withMaxDepth(a){return this.options.maxDepth=a,this}withMaxFiles(a){return this.options.maxFiles=a,this}withFullPaths(){return this.options.resolvePaths=true,this.options.includeBasePath=true,this}withErrors(){return this.options.suppressErrors=false,this}withSymlinks({resolvePaths:a=true}={}){return this.options.resolveSymlinks=true,this.options.useRealPaths=a,this.withFullPaths()}withAbortSignal(a){return this.options.signal=a,this}normalize(){return this.options.normalizePath=true,this}filter(a){return this.options.filters.push(a),this}onlyDirs(){return this.options.excludeFiles=true,this.options.includeDirs=true,this}exclude(a){return this.options.exclude=a,this}onlyCounts(){return this.options.onlyCounts=true,this}crawl(a){return new vi(a||".",this.options)}withGlobFunction(a){return this.globFunction=a,this}crawlWithOptions(a,t){return this.options={...this.options,...t},new vi(a||".",this.options)}glob(...a){return this.globFunction?this.globWithOptions(a):this.globWithOptions(a,{dot:true})}globWithOptions(a,...t){let s=this.globFunction||Bi;if(!s)throw new Error("Please specify a glob function to use glob matching.");var e=this.globCache[a.join("\0")];return e||(e=s(a,...t),this.globCache[a.join("\0")]=e),this.options.filters.push(i=>e(i)),this}};var $t=Ut(lr()),Jo=Array.isArray,fr=process.platform==="win32",Yo=/^(\/?\.\.)+$/;function Xo(a,t={}){let s=a.length,e=Array(s),i=Array(s),r=!t.noglobstar;for(let n=0;n<s;n++){let o=hr(a[n]);e[n]=o;let u=o.length,l=Array(u);for(let p=0;p<u;p++)l[p]=(0, $t.default)(o[p],t);i[n]=l;}return n=>{let o=n.split("/");if(o[0]===".."&&Yo.test(n))return true;for(let u=0;u<a.length;u++){let l=e[u],p=i[u],f=o.length,h=Math.min(f,l.length),E=0;for(;E<h;){let g=l[E];if(g.includes("/"))return true;if(!p[E](o[E]))break;if(r&&g==="**")return true;E++;}if(E===f)return true}return false}}var Ko=/^[A-Z]:\/$/i,zo=fr?a=>Ko.test(a):a=>a==="/";function pr(a,t,s){if(a===t||t.startsWith(`${a}/`)){if(s){let i=zo(a)?a.length:a.length+1;return (r,n)=>r.slice(i,n?-1:void 0)||"."}let e=t.slice(a.length+1);return e?(i,r)=>{if(i===".")return e;let n=`${e}/${i}`;return r?n.slice(0,-1):n}:(i,r)=>r&&i!=="."?i.slice(0,-1):i}return s?e=>posix.relative(a,e)||".":e=>posix.relative(a,`${t}/${e}`)||"."}function Qo(a,t){if(t.startsWith(`${a}/`)){let s=t.slice(a.length+1);return e=>`${s}/${e}`}return s=>{let e=posix.relative(a,`${t}/${s}`);return s.endsWith("/")&&e!==""?`${e}/`:e||"."}}var Zo={parts:true};function hr(a){var t;let s=$t.default.scan(a,Zo);return !((t=s.parts)===null||t===void 0)&&t.length?s.parts:[a]}var tu=/(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g,eu=/(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g,su=a=>a.replace(tu,"\\$&"),iu=a=>a.replace(eu,"\\$&"),ru=fr?iu:su;function nu(a,t){let s=$t.default.scan(a);return s.isGlob||s.negated}function Pt(...a){console.log(`[tinyglobby ${new Date().toLocaleTimeString("es")}]`,...a);}var au=/^(\/?\.\.)+/,ou=/\\(?=[()[\]{}!*+?@|])/g,Ve=/\\/g;function Ps(a,t,s,e,i){let r=a;a.endsWith("/")&&(r=a.slice(0,-1)),!r.endsWith("*")&&t&&(r+="/**");let n=ru(s);cr.isAbsolute(r.replace(ou,""))?r=posix.relative(n,r):r=posix.normalize(r);let o=au.exec(r),u=hr(r);if(o?.[0]){let p=(o[0].length+1)/3,f=0,h=n.split("/");for(;f<p&&u[f+p]===h[h.length+f-p];)r=r.slice(0,(p-f-1)*3)+r.slice((p-f)*3+u[f+p].length+1)||".",f++;let E=posix.join(s,o[0].slice(f*3));!E.startsWith(".")&&e.root.length>E.length&&(e.root=E,e.depthOffset=-p+f);}if(!i&&e.depthOffset>=0){var l;(l=e.commonPath)!==null&&l!==void 0||(e.commonPath=u);let p=[],f=Math.min(e.commonPath.length,u.length);for(let h=0;h<f;h++){let E=u[h];if(E==="**"&&!u[h+1]){p.pop();break}if(E!==e.commonPath[h]||nu(E)||h===u.length-1)break;p.push(E);}e.depthOffset=p.length,e.commonPath=p,e.root=p.length>0?posix.join(s,...p):s;}return r}function uu({patterns:a=["**/*"],ignore:t=[],expandDirectories:s=true},e,i){typeof a=="string"&&(a=[a]),typeof t=="string"&&(t=[t]);let r=[],n=[];for(let o of t)o&&(o[0]!=="!"||o[1]==="(")&&n.push(Ps(o,s,e,i,true));for(let o of a)o&&(o[0]!=="!"||o[1]==="("?r.push(Ps(o,s,e,i,false)):(o[1]!=="!"||o[2]==="(")&&n.push(Ps(o.slice(1),s,e,i,true)));return {match:r,ignore:n}}function lu(a,t){for(let s=a.length-1;s>=0;s--){let e=a[s];a[s]=t(e);}return a}function pu(a){return a?a instanceof URL?fileURLToPath(a).replace(Ve,"/"):cr.resolve(a).replace(Ve,"/"):process.cwd().replace(Ve,"/")}function cu(a,t={}){let s=process.env.TINYGLOBBY_DEBUG?{...t,debug:true}:t,e=pu(s.cwd);if(s.debug&&Pt("globbing with:",{patterns:a,options:s,cwd:e}),Array.isArray(a)&&a.length===0)return [{sync:()=>[],withPromise:async()=>[]},false];let i={root:e,commonPath:null,depthOffset:0},r=uu({...s,patterns:a},e,i);s.debug&&Pt("internal processing patterns:",r);let n={dot:s.dot,nobrace:s.braceExpansion===false,nocase:s.caseSensitiveMatch===false,noextglob:s.extglob===false,noglobstar:s.globstar===false,posix:true},o=(0, $t.default)(r.match,{...n,ignore:r.ignore}),u=(0, $t.default)(r.ignore,n),l=Xo(r.match,n),p=pr(e,i.root,s.absolute),f=s.absolute?p:pr(e,i.root,true),h={filters:[s.debug?(R,b)=>{let d=p(R,b),O=o(d);return O&&Pt(`matched ${d}`),O}:(R,b)=>o(p(R,b))],exclude:s.debug?(R,b)=>{let d=f(b,true),O=d!=="."&&!l(d)||u(d);return Pt(O?`skipped ${b}`:`crawling ${b}`),O}:(R,b)=>{let d=f(b,true);return d!=="."&&!l(d)||u(d)},fs:s.fs?{readdir:s.fs.readdir||Dt__default.readdir,readdirSync:s.fs.readdirSync||Dt__default.readdirSync,realpath:s.fs.realpath||Dt__default.realpath,realpathSync:s.fs.realpathSync||Dt__default.realpathSync,stat:s.fs.stat||Dt__default.stat,statSync:s.fs.statSync||Dt__default.statSync}:void 0,pathSeparator:"/",relativePaths:true,resolveSymlinks:true,signal:s.signal};s.deep!==void 0&&(h.maxDepth=Math.round(s.deep-i.depthOffset)),s.absolute&&(h.relativePaths=false,h.resolvePaths=true,h.includeBasePath=true),s.followSymbolicLinks===false&&(h.resolveSymlinks=false,h.excludeSymlinks=true),s.onlyDirectories?(h.excludeFiles=true,h.includeDirs=true):s.onlyFiles===false&&(h.includeDirs=true),i.root=i.root.replace(Ve,"");let E=i.root;s.debug&&Pt("internal properties:",i);let g=e!==E&&!s.absolute&&Qo(e,i.root);return [new Mi(h).crawl(E),g]}async function Kt(a,t){if(a&&t?.patterns)throw new Error("Cannot pass patterns as both an argument and an option");let s=Jo(a)||typeof a=="string",e=s?t:a,i=s?a:a.patterns,[r,n]=cu(i,e);return n?lu(await r.withPromise(),n):r.withPromise()}var $=Ut(Mt());var st={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},$s={root:".",fileFilter:a=>true,directoryFilter:a=>true,type:st.FILE_TYPE,lstat:false,depth:2147483648,alwaysStat:false,highWaterMark:4096};Object.freeze($s);var Ar="READDIRP_RECURSIVE_ERROR",Au=new Set(["ENOENT","EPERM","EACCES","ELOOP",Ar]),gr=[st.DIR_TYPE,st.EVERYTHING_TYPE,st.FILE_DIR_TYPE,st.FILE_TYPE],Cu=new Set([st.DIR_TYPE,st.EVERYTHING_TYPE,st.FILE_DIR_TYPE]),Ru=new Set([st.EVERYTHING_TYPE,st.FILE_DIR_TYPE,st.FILE_TYPE]),Nu=a=>Au.has(a.code),bu=process.platform==="win32",Tr=a=>true,Sr=a=>{if(a===void 0)return Tr;if(typeof a=="function")return a;if(typeof a=="string"){let t=a.trim();return s=>s.basename===t}if(Array.isArray(a)){let t=a.map(s=>s.trim());return s=>t.some(e=>s.basename===e)}return Tr},js=class extends Readable{parents;reading;parent;_stat;_maxDepth;_wantsDir;_wantsFile;_wantsEverything;_root;_isDirent;_statsProp;_rdOptions;_fileFilter;_directoryFilter;constructor(t={}){super({objectMode:true,autoDestroy:true,highWaterMark:t.highWaterMark});let s={...$s,...t},{root:e,type:i}=s;this._fileFilter=Sr(s.fileFilter),this._directoryFilter=Sr(s.directoryFilter);let r=s.lstat?lstat:stat;bu?this._stat=n=>r(n,{bigint:true}):this._stat=r,this._maxDepth=s.depth!=null&&Number.isSafeInteger(s.depth)?s.depth:$s.depth,this._wantsDir=i?Cu.has(i):false,this._wantsFile=i?Ru.has(i):false,this._wantsEverything=i===st.EVERYTHING_TYPE,this._root=resolve(e),this._isDirent=!s.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(e,1)],this.reading=false,this.parent=void 0;}async _read(t){if(!this.reading){this.reading=true;try{for(;!this.destroyed&&t>0;){let s=this.parent,e=s&&s.files;if(e&&e.length>0){let{path:i,depth:r}=s,n=e.splice(0,t).map(u=>this._formatEntry(u,i)),o=await Promise.all(n);for(let u of o){if(!u)continue;if(this.destroyed)return;let l=await this._getEntryType(u);l==="directory"&&this._directoryFilter(u)?(r<=this._maxDepth&&this.parents.push(this._exploreDir(u.fullPath,r+1)),this._wantsDir&&(this.push(u),t--)):(l==="file"||this._includeAsFile(u))&&this._fileFilter(u)&&this._wantsFile&&(this.push(u),t--);}}else {let i=this.parents.pop();if(!i){this.push(null);break}if(this.parent=await i,this.destroyed)return}}}catch(s){this.destroy(s);}finally{this.reading=false;}}}async _exploreDir(t,s){let e;try{e=await readdir(t,this._rdOptions);}catch(i){this._onError(i);}return {files:e,depth:s,path:t}}async _formatEntry(t,s){let e,i=this._isDirent?t.name:t;try{let r=resolve(join(s,i));e={path:relative(this._root,r),fullPath:r,basename:i},e[this._statsProp]=this._isDirent?t:await this._stat(r);}catch(r){this._onError(r);return}return e}_onError(t){Nu(t)&&!this.destroyed?this.emit("warn",t):this.destroy(t);}async _getEntryType(t){if(!t&&this._statsProp in t)return "";let s=t[this._statsProp];if(s.isFile())return "file";if(s.isDirectory())return "directory";if(s&&s.isSymbolicLink()){let e=t.fullPath;try{let i=await realpath(e),r=await lstat(i);if(r.isFile())return "file";if(r.isDirectory()){let n=i.length;if(e.startsWith(i)&&e.substr(n,1)===sep$1){let o=new Error(`Circular symlink detected: "${e}" points to "${i}"`);return o.code=Ar,this._onError(o)}return "directory"}}catch(i){return this._onError(i),""}}}_includeAsFile(t){let s=t&&t[this._statsProp];return s&&this._wantsEverything&&!s.isDirectory()}};function Cr(a,t={}){let s=t.entryType||t.type;if(s==="both"&&(s=st.FILE_DIR_TYPE),s&&(t.type=s),a){if(typeof a!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(s&&!gr.includes(s))throw new Error(`readdirp: Invalid type passed. Use one of ${gr.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return t.root=a,new js(t)}var Lu="data",Bs="end",Or="close",Ye=()=>{};var Xe=process.platform,Ms=Xe==="win32",Iu=Xe==="darwin",vu=Xe==="linux",Du=Xe==="freebsd",_r=type()==="OS400",x={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},ot=x,Pu="watch",$u={lstat:lstat,stat:stat},Ot="listeners",Ge="errHandlers",jt="rawEmitters",ju=[Ot,Ge,jt],ku=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),Fu=a=>ku.has(v.extname(a).slice(1).toLowerCase()),Us=(a,t)=>{a instanceof Set?a.forEach(t):t(a);},zt=(a,t,s)=>{let e=a[t];e instanceof Set||(a[t]=e=new Set([e])),e.add(s);},Uu=a=>t=>{let s=a[t];s instanceof Set?s.clear():delete a[t];},Qt=(a,t,s)=>{let e=a[t];e instanceof Set?e.delete(s):e===s&&delete a[t];},wr=a=>a instanceof Set?a.size===0:!a,We=new Map;function Nr(a,t,s,e,i){let r=(n,o)=>{s(a),i(n,o,{watchedPath:a}),o&&a!==o&&He(v.resolve(a,o),Ot,v.join(a,o));};try{return watch(a,{persistent:t.persistent},r)}catch(n){e(n);return}}var He=(a,t,s,e,i)=>{let r=We.get(a);r&&Us(r[t],n=>{n(s,e,i);});},Bu=(a,t,s,e)=>{let{listener:i,errHandler:r,rawEmitter:n}=e,o=We.get(t),u;if(!s.persistent)return u=Nr(a,s,i,r,n),u?u.close.bind(u):void 0;if(o)zt(o,Ot,i),zt(o,Ge,r),zt(o,jt,n);else {if(u=Nr(a,s,He.bind(null,t,Ot),r,He.bind(null,t,jt)),!u)return;u.on(ot.ERROR,async l=>{let p=He.bind(null,t,Ge);if(o&&(o.watcherUnusable=true),Ms&&l.code==="EPERM")try{await(await open(a,"r")).close(),p(l);}catch{}else p(l);}),o={listeners:i,errHandlers:r,rawEmitters:n,watcher:u},We.set(t,o);}return ()=>{Qt(o,Ot,i),Qt(o,Ge,r),Qt(o,jt,n),wr(o.listeners)&&(o.watcher.close(),We.delete(t),ju.forEach(Uu(o)),o.watcher=void 0,Object.freeze(o));}},Fs=new Map,Mu=(a,t,s,e)=>{let{listener:i,rawEmitter:r}=e,n=Fs.get(t),o=n&&n.options;return o&&(o.persistent<s.persistent||o.interval>s.interval)&&(unwatchFile(t),n=void 0),n?(zt(n,Ot,i),zt(n,jt,r)):(n={listeners:i,rawEmitters:r,options:s,watcher:watchFile(t,s,(u,l)=>{Us(n.rawEmitters,f=>{f(ot.CHANGE,t,{curr:u,prev:l});});let p=u.mtimeMs;(u.size!==l.size||p>l.mtimeMs||p===0)&&Us(n.listeners,f=>f(a,u));})},Fs.set(t,n)),()=>{Qt(n,Ot,i),Qt(n,jt,r),wr(n.listeners)&&(Fs.delete(t),unwatchFile(t),n.options=n.watcher=void 0,Object.freeze(n));}},Je=class{fsw;_boundHandleError;constructor(t){this.fsw=t,this._boundHandleError=s=>t._handleError(s);}_watchWithNodeFs(t,s){let e=this.fsw.options,i=v.dirname(t),r=v.basename(t);this.fsw._getWatchedDir(i).add(r);let o=v.resolve(t),u={persistent:e.persistent};s||(s=Ye);let l;if(e.usePolling){let p=e.interval!==e.binaryInterval;u.interval=p&&Fu(r)?e.binaryInterval:e.interval,l=Mu(t,o,u,{listener:s,rawEmitter:this.fsw._emitRaw});}else l=Bu(t,o,u,{listener:s,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return l}_handleFile(t,s,e){if(this.fsw.closed)return;let i=v.dirname(t),r=v.basename(t),n=this.fsw._getWatchedDir(i),o=s;if(n.has(r))return;let u=async(p,f)=>{if(this.fsw._throttle(Pu,t,5)){if(!f||f.mtimeMs===0)try{let h=await stat(t);if(this.fsw.closed)return;let E=h.atimeMs,g=h.mtimeMs;if((!E||E<=g||g!==o.mtimeMs)&&this.fsw._emit(ot.CHANGE,t,h),(Iu||vu||Du)&&o.ino!==h.ino){this.fsw._closeFile(p),o=h;let R=this._watchWithNodeFs(t,u);R&&this.fsw._addPathCloser(p,R);}else o=h;}catch{this.fsw._remove(i,r);}else if(n.has(r)){let h=f.atimeMs,E=f.mtimeMs;(!h||h<=E||E!==o.mtimeMs)&&this.fsw._emit(ot.CHANGE,t,f),o=f;}}},l=this._watchWithNodeFs(t,u);if(!(e&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(t)){if(!this.fsw._throttle(ot.ADD,t,0))return;this.fsw._emit(ot.ADD,t,s);}return l}async _handleSymlink(t,s,e,i){if(this.fsw.closed)return;let r=t.fullPath,n=this.fsw._getWatchedDir(s);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let o;try{o=await realpath(e);}catch{return this.fsw._emitReady(),true}return this.fsw.closed?void 0:(n.has(i)?this.fsw._symlinkPaths.get(r)!==o&&(this.fsw._symlinkPaths.set(r,o),this.fsw._emit(ot.CHANGE,e,t.stats)):(n.add(i),this.fsw._symlinkPaths.set(r,o),this.fsw._emit(ot.ADD,e,t.stats)),this.fsw._emitReady(),true)}if(this.fsw._symlinkPaths.has(r))return true;this.fsw._symlinkPaths.set(r,true);}_handleRead(t,s,e,i,r,n,o){t=v.join(t,"");let u=i?`${t}:${i}`:t;if(o=this.fsw._throttle("readdir",u,1e3),!o)return;let l=this.fsw._getWatchedDir(e.path),p=new Set,f=this.fsw._readdirp(t,{fileFilter:h=>e.filterPath(h),directoryFilter:h=>e.filterDir(h)});if(f)return f.on(Lu,async h=>{if(this.fsw.closed){f=void 0;return}let E=h.path,g=v.join(t,E);if(p.add(E),!(h.stats.isSymbolicLink()&&await this._handleSymlink(h,t,g,E))){if(this.fsw.closed){f=void 0;return}(E===i||!i&&!l.has(E))&&(this.fsw._incrReadyCount(),g=v.join(r,v.relative(r,g)),this._addToNodeFs(g,s,e,n+1));}}).on(ot.ERROR,this._boundHandleError),new Promise((h,E)=>{if(!f)return E();f.once(Bs,()=>{if(this.fsw.closed){f=void 0;return}let g=o?o.clear():false;h(void 0),l.getChildren().filter(R=>R!==t&&!p.has(R)).forEach(R=>{this.fsw._remove(t,R);}),f=void 0,g&&this._handleRead(t,false,e,i,r,n,o);});})}async _handleDir(t,s,e,i,r,n,o){let u=this.fsw._getWatchedDir(v.dirname(t)),l=u.has(v.basename(t));!(e&&this.fsw.options.ignoreInitial)&&!r&&!l&&this.fsw._emit(ot.ADD_DIR,t,s),u.add(v.basename(t)),this.fsw._getWatchedDir(t);let p,f,h=this.fsw.options.depth;if((h==null||i<=h)&&!this.fsw._symlinkPaths.has(o)){if(!r&&(await this._handleRead(t,e,n,r,t,i,p),this.fsw.closed))return;f=this._watchWithNodeFs(t,(E,g)=>{g&&g.mtimeMs===0||this._handleRead(E,false,n,r,t,i,p);});}return f}async _addToNodeFs(t,s,e,i,r){let n=this.fsw._emitReady;if(this.fsw._isIgnored(t)||this.fsw.closed)return n(),false;let o=this.fsw._getWatchHelpers(t);e&&(o.filterPath=u=>e.filterPath(u),o.filterDir=u=>e.filterDir(u));try{let u=await $u[o.statMethod](o.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(o.watchPath,u))return n(),!1;let l=this.fsw.options.followSymlinks,p;if(u.isDirectory()){let f=v.resolve(t),h=l?await realpath(t):t;if(this.fsw.closed||(p=await this._handleDir(o.watchPath,u,s,i,r,o,h),this.fsw.closed))return;f!==h&&h!==void 0&&this.fsw._symlinkPaths.set(f,h);}else if(u.isSymbolicLink()){let f=l?await realpath(t):t;if(this.fsw.closed)return;let h=v.dirname(o.watchPath);if(this.fsw._getWatchedDir(h).add(o.watchPath),this.fsw._emit(ot.ADD,o.watchPath,u),p=await this._handleDir(h,u,s,i,t,o,f),this.fsw.closed)return;f!==void 0&&this.fsw._symlinkPaths.set(v.resolve(t),f);}else p=this._handleFile(o.watchPath,u,s);return n(),p&&this.fsw._addPathCloser(t,p),!1}catch(u){if(this.fsw._handleError(u))return n(),t}}};var xs="/",Wu="//",vr=".",Hu="..",Ju="string",Yu=/\\/g,Dr=/\/\//g,Xu=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Ku=/^\.[/\\]/;function Ke(a){return Array.isArray(a)?a:[a]}var qs=a=>typeof a=="object"&&a!==null&&!(a instanceof RegExp);function zu(a){return typeof a=="function"?a:typeof a=="string"?t=>a===t:a instanceof RegExp?t=>a.test(t):typeof a=="object"&&a!==null?t=>{if(a.path===t)return true;if(a.recursive){let s=v.relative(a.path,t);return s?!s.startsWith("..")&&!v.isAbsolute(s):false}return false}:()=>false}function Qu(a){if(typeof a!="string")throw new Error("string expected");a=v.normalize(a),a=a.replace(/\\/g,"/");let t=false;return a.startsWith("//")&&(t=true),a=a.replace(Dr,"/"),t&&(a="/"+a),a}function dr(a,t,s){let e=Qu(t);for(let i=0;i<a.length;i++){let r=a[i];if(r(e,s))return true}return false}function Zu(a,t){if(a==null)throw new TypeError("anymatch: specify first argument");let e=Ke(a).map(i=>zu(i));return t==null?(i,r)=>dr(e,i,r):dr(e,t)}var yr=a=>{let t=Ke(a).flat();if(!t.every(s=>typeof s===Ju))throw new TypeError(`Non-string provided as watch path: ${t}`);return t.map(Pr)},Lr=a=>{let t=a.replace(Yu,xs),s=false;return t.startsWith(Wu)&&(s=true),t=t.replace(Dr,xs),s&&(t=xs+t),t},Pr=a=>Lr(v.normalize(Lr(a))),Ir=(a="")=>t=>typeof t=="string"?Pr(v.isAbsolute(t)?t:v.join(a,t)):t,tl=(a,t)=>v.isAbsolute(a)?a:v.join(t,a),el=Object.freeze(new Set),Vs=class{path;_removeWatcher;items;constructor(t,s){this.path=t,this._removeWatcher=s,this.items=new Set;}add(t){let{items:s}=this;s&&t!==vr&&t!==Hu&&s.add(t);}async remove(t){let{items:s}=this;if(!s||(s.delete(t),s.size>0))return;let e=this.path;try{await readdir(e);}catch{this._removeWatcher&&this._removeWatcher(v.dirname(e),v.basename(e));}}has(t){let{items:s}=this;if(s)return s.has(t)}getChildren(){let{items:t}=this;return t?[...t.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=Ye,this.items=el,Object.freeze(this);}},sl="stat",il="lstat",Gs=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(t,s,e){this.fsw=e;let i=t;this.path=t=t.replace(Ku,""),this.watchPath=i,this.fullWatchPath=v.resolve(i),this.dirParts=[],this.dirParts.forEach(r=>{r.length>1&&r.pop();}),this.followSymlinks=s,this.statMethod=s?sl:il;}entryPath(t){return v.join(this.watchPath,v.relative(this.watchPath,t.fullPath))}filterPath(t){let{stats:s}=t;if(s&&s.isSymbolicLink())return this.filterDir(t);let e=this.entryPath(t);return this.fsw._isntIgnored(e,s)&&this.fsw._hasReadPermissions(s)}filterDir(t){return this.fsw._isntIgnored(this.entryPath(t),t.stats)}},ze=class extends EventEmitter{closed;options;_closers;_ignoredPaths;_throttled;_streams;_symlinkPaths;_watched;_pendingWrites;_pendingUnlinks;_readyCount;_emitReady;_closePromise;_userIgnored;_readyEmitted;_emitRaw;_boundRemove;_nodeFsHandler;constructor(t={}){super(),this.closed=false,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=false;let s=t.awaitWriteFinish,e={stabilityThreshold:2e3,pollInterval:100},i={persistent:true,ignoreInitial:false,ignorePermissionErrors:false,interval:100,binaryInterval:300,followSymlinks:true,usePolling:false,atomic:true,...t,ignored:t.ignored?Ke(t.ignored):Ke([]),awaitWriteFinish:s===true?e:typeof s=="object"?{...e,...s}:false};_r&&(i.usePolling=true),i.atomic===void 0&&(i.atomic=!i.usePolling);let r=process.env.CHOKIDAR_USEPOLLING;if(r!==void 0){let u=r.toLowerCase();u==="false"||u==="0"?i.usePolling=false:u==="true"||u==="1"?i.usePolling=true:i.usePolling=!!u;}let n=process.env.CHOKIDAR_INTERVAL;n&&(i.interval=Number.parseInt(n,10));let o=0;this._emitReady=()=>{o++,o>=this._readyCount&&(this._emitReady=Ye,this._readyEmitted=true,process.nextTick(()=>this.emit(x.READY)));},this._emitRaw=(...u)=>this.emit(x.RAW,...u),this._boundRemove=this._remove.bind(this),this.options=i,this._nodeFsHandler=new Je(this),Object.freeze(i);}_addIgnoredPath(t){if(qs(t)){for(let s of this._ignoredPaths)if(qs(s)&&s.path===t.path&&s.recursive===t.recursive)return}this._ignoredPaths.add(t);}_removeIgnoredPath(t){if(this._ignoredPaths.delete(t),typeof t=="string")for(let s of this._ignoredPaths)qs(s)&&s.path===t&&this._ignoredPaths.delete(s);}add(t,s,e){let{cwd:i}=this.options;this.closed=false,this._closePromise=void 0;let r=yr(t);return i&&(r=r.map(n=>tl(n,i))),r.forEach(n=>{this._removeIgnoredPath(n);}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=r.length,Promise.all(r.map(async n=>{let o=await this._nodeFsHandler._addToNodeFs(n,!e,void 0,0,s);return o&&this._emitReady(),o})).then(n=>{this.closed||n.forEach(o=>{o&&this.add(v.dirname(o),v.basename(s||o));});}),this}unwatch(t){if(this.closed)return this;let s=yr(t),{cwd:e}=this.options;return s.forEach(i=>{!v.isAbsolute(i)&&!this._closers.has(i)&&(e&&(i=v.join(e,i)),i=v.resolve(i)),this._closePath(i),this._addIgnoredPath(i),this._watched.has(i)&&this._addIgnoredPath({path:i,recursive:true}),this._userIgnored=void 0;}),this}close(){if(this._closePromise)return this._closePromise;this.closed=true,this.removeAllListeners();let t=[];return this._closers.forEach(s=>s.forEach(e=>{let i=e();i instanceof Promise&&t.push(i);})),this._streams.forEach(s=>s.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=false,this._watched.forEach(s=>s.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=t.length?Promise.all(t).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let t={};return this._watched.forEach((s,e)=>{let r=(this.options.cwd?v.relative(this.options.cwd,e):e)||vr;t[r]=s.getChildren().sort();}),t}emitWithAll(t,s){this.emit(t,...s),t!==x.ERROR&&this.emit(x.ALL,t,...s);}async _emit(t,s,e){if(this.closed)return;let i=this.options;Ms&&(s=v.normalize(s)),i.cwd&&(s=v.relative(i.cwd,s));let r=[s];e!=null&&r.push(e);let n=i.awaitWriteFinish,o;if(n&&(o=this._pendingWrites.get(s)))return o.lastChange=new Date,this;if(i.atomic){if(t===x.UNLINK)return this._pendingUnlinks.set(s,[t,...r]),setTimeout(()=>{this._pendingUnlinks.forEach((u,l)=>{this.emit(...u),this.emit(x.ALL,...u),this._pendingUnlinks.delete(l);});},typeof i.atomic=="number"?i.atomic:100),this;t===x.ADD&&this._pendingUnlinks.has(s)&&(t=x.CHANGE,this._pendingUnlinks.delete(s));}if(n&&(t===x.ADD||t===x.CHANGE)&&this._readyEmitted){let u=(l,p)=>{l?(t=x.ERROR,r[0]=l,this.emitWithAll(t,r)):p&&(r.length>1?r[1]=p:r.push(p),this.emitWithAll(t,r));};return this._awaitWriteFinish(s,n.stabilityThreshold,t,u),this}if(t===x.CHANGE&&!this._throttle(x.CHANGE,s,50))return this;if(i.alwaysStat&&e===void 0&&(t===x.ADD||t===x.ADD_DIR||t===x.CHANGE)){let u=i.cwd?v.join(i.cwd,s):s,l;try{l=await stat(u);}catch{}if(!l||this.closed)return;r.push(l);}return this.emitWithAll(t,r),this}_handleError(t){let s=t&&t.code;return t&&s!=="ENOENT"&&s!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||s!=="EPERM"&&s!=="EACCES")&&this.emit(x.ERROR,t),t||this.closed}_throttle(t,s,e){this._throttled.has(t)||this._throttled.set(t,new Map);let i=this._throttled.get(t);if(!i)throw new Error("invalid throttle");let r=i.get(s);if(r)return r.count++,false;let n,o=()=>{let l=i.get(s),p=l?l.count:0;return i.delete(s),clearTimeout(n),l&&clearTimeout(l.timeoutObject),p};n=setTimeout(o,e);let u={timeoutObject:n,clear:o,count:0};return i.set(s,u),u}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(t,s,e,i){let r=this.options.awaitWriteFinish;if(typeof r!="object")return;let n=r.pollInterval,o,u=t;this.options.cwd&&!v.isAbsolute(t)&&(u=v.join(this.options.cwd,t));let l=new Date,p=this._pendingWrites;function f(h){stat$1(u,(E,g)=>{if(E||!p.has(t)){E&&E.code!=="ENOENT"&&i(E);return}let R=Number(new Date);h&&g.size!==h.size&&(p.get(t).lastChange=R);let b=p.get(t);R-b.lastChange>=s?(p.delete(t),i(void 0,g)):o=setTimeout(f,n,g);});}p.has(t)||(p.set(t,{lastChange:l,cancelWait:()=>(p.delete(t),clearTimeout(o),e)}),o=setTimeout(f,n));}_isIgnored(t,s){if(this.options.atomic&&Xu.test(t))return true;if(!this._userIgnored){let{cwd:e}=this.options,r=(this.options.ignored||[]).map(Ir(e)),o=[...[...this._ignoredPaths].map(Ir(e)),...r];this._userIgnored=Zu(o,void 0);}return this._userIgnored(t,s)}_isntIgnored(t,s){return !this._isIgnored(t,s)}_getWatchHelpers(t){return new Gs(t,this.options.followSymlinks,this)}_getWatchedDir(t){let s=v.resolve(t);return this._watched.has(s)||this._watched.set(s,new Vs(s,this._boundRemove)),this._watched.get(s)}_hasReadPermissions(t){return this.options.ignorePermissionErrors?true:!!(Number(t.mode)&256)}_remove(t,s,e){let i=v.join(t,s),r=v.resolve(i);if(e=e??(this._watched.has(i)||this._watched.has(r)),!this._throttle("remove",i,100))return;!e&&this._watched.size===1&&this.add(t,s,true),this._getWatchedDir(i).getChildren().forEach(h=>this._remove(i,h));let u=this._getWatchedDir(t),l=u.has(s);u.remove(s),this._symlinkPaths.has(r)&&this._symlinkPaths.delete(r);let p=i;if(this.options.cwd&&(p=v.relative(this.options.cwd,i)),this.options.awaitWriteFinish&&this._pendingWrites.has(p)&&this._pendingWrites.get(p).cancelWait()===x.ADD)return;this._watched.delete(i),this._watched.delete(r);let f=e?x.UNLINK_DIR:x.UNLINK;l&&!this._isIgnored(i)&&this._emit(f,i),this._closePath(i);}_closePath(t){this._closeFile(t);let s=v.dirname(t);this._getWatchedDir(s).remove(v.basename(t));}_closeFile(t){let s=this._closers.get(t);s&&(s.forEach(e=>e()),this._closers.delete(t));}_addPathCloser(t,s){if(!s)return;let e=this._closers.get(t);e||(e=[],this._closers.set(t,e)),e.push(s);}_readdirp(t,s){if(this.closed)return;let e={type:x.ALL,alwaysStat:true,lstat:true,...s,depth:0},i=Cr(t,e);return this._streams.add(i),i.once(Or,()=>{i=void 0;}),i.once(Bs,()=>{i&&(this._streams.delete(i),i=void 0);}),i}};function rl(a,t={}){let s=new ze(t);return s.add(a),s}var $r={watch:rl,FSWatcher:ze};var al=/^(\d{14})(?:_([^.]+))?\.sql$/;function jr(a){return a.config?.db?.driver==="sqlite"?"./sqlite-migrations/*.sql":"./migrations/*.sql"}function ol(a){return v__default.posix.dirname(jr(a))}async function Zt(a){let t=v__default.join(process.cwd(),"supabase"),s=await Kt([jr(a)],{cwd:t,absolute:true}),e=[];for(let i of s){let r=v__default.basename(i),n=al.exec(r);if(!n)continue;let o=await G__default.readFile(i,"utf-8");e.push({version:n[1],name:n[2]??null,filename:r,path:i,sql:o});}return e.sort((i,r)=>i.version.localeCompare(r.version))}var fn="supabase/.temp/.translation-cache.json",hn=2;async function Vl(a,t){let s=await a.connection.introspect(),e=hi(s);await mn(a,{...t,dbHasTables:s.tables.length>0,dbFingerprint:e}),s.tables.length===0&&await Hl(a);let i=await a.connection.introspect();gn(i,a);}async function Gl(a){let t=await Kt(a.config.db?.seed?.sql_paths??["./seed.sql"],{cwd:v__default.join(process.cwd(),"supabase"),absolute:true});return (await Promise.all(t.map(e=>G__default.readFile(e,"utf-8")))).flatMap(e=>splitSqlStatements(e))}async function Wl(a,t){let s=await Gl(a);if(s.length===0)return 0;console.log($.default.dim("Seeding database..."));try{return await a.connection.transaction(s),s.length}catch(e){let i="Fix `supabase/seed.sql`, then run `bun run dev --recreate` to reset and reseed.";throw new Error(`Seed failed and was rolled back: ${String(e.message??e)}
89
- ${i}`)}}async function Hl(a){await Wl(a);}async function Jl(a){let t=await Kt(a.config?.db?.migrations?.schema_paths??["./schemas/*.sql"],{cwd:v__default.join(process.cwd(),"supabase"),absolute:true}),s=await Promise.all(t.map(async e=>await G__default.readFile(e,"utf-8"))).then(e=>e.map(i=>i.split(`
90
- `).filter(r=>r.trim().length>0&&!r.trim().startsWith("--")).join(`
59
+ )`,ns="insert into todos (`id`, `title`, `description`, `completed`) values (1, 'test', 'test', false);\ninsert into todos (`id`, `title`, `description`, `completed`) values (2, 'test2', 'test2', true);\ninsert into test (`id`, `name`) values (1, 'test');\n";var zn=createRequire(import.meta.url);function cs(e){let t=normalize(e);return t.length>1&&t[t.length-1]===sep&&(t=t.substring(0,t.length-1)),t}var us=/[\\/]/g;function Jn(e,t){return e.replace(us,t)}var fs=/^[a-z]:[\\/]$/i;function ps(e){return e==="/"||fs.test(e)}function Qe(e,t){let{resolvePaths:n,normalizePath:r,pathSeparator:i}=t,s=process.platform==="win32"&&e.includes("/")||e.startsWith(".");if(n&&(e=resolve(e)),(r||s)&&(e=cs(e)),e===".")return "";let o=e[e.length-1]!==i;return Jn(o?e+i:e,i)}function Yn(e,t){return t+e}function ms(e,t){return function(n,r){return r.startsWith(e)?r.slice(e.length)+n:Jn(relative(e,r),t.pathSeparator)+t.pathSeparator+n}}function hs(e){return e}function ds(e,t,n){return t+e+n}function gs(e,t){let{relativePaths:n,includeBasePath:r}=t;return n&&e?ms(e,t):r?Yn:hs}function ys(e){return function(t,n){n.push(t.substring(e.length)||".");}}function bs(e){return function(t,n,r){let i=t.substring(e.length)||".";r.every(s=>s(i,true))&&n.push(i);}}var ws=(e,t)=>{t.push(e||".");},xs=(e,t,n)=>{let r=e||".";n.every(i=>i(r,true))&&t.push(r);},Ss=()=>{};function Es(e,t){let{includeDirs:n,filters:r,relativePaths:i}=t;return n?i?r&&r.length?bs(e):ys(e):r&&r.length?xs:ws:Ss}var As=(e,t,n,r)=>{r.every(i=>i(e,false))&&n.files++;},Ts=(e,t,n,r)=>{r.every(i=>i(e,false))&&t.push(e);},_s=(e,t,n,r)=>{n.files++;},Cs=(e,t)=>{t.push(e);},Rs=()=>{};function vs(e){let{excludeFiles:t,filters:n,onlyCounts:r}=e;return t?Rs:n&&n.length?r?As:Ts:r?_s:Cs}var $s=e=>e,Ns=()=>[""].slice(0,0);function ks(e){return e.group?Ns:$s}var Ps=(e,t,n)=>{e.push({directory:t,files:n,dir:t});},Ls=()=>{};function Os(e){return e.group?Ps:Ls}var Fs=function(e,t,n){let{queue:r,fs:i,options:{suppressErrors:s}}=t;r.enqueue(),i.realpath(e,(o,a)=>{if(o)return r.dequeue(s?null:o,t);i.stat(a,(l,c)=>{if(l)return r.dequeue(s?null:l,t);if(c.isDirectory()&&Qn(e,a,t))return r.dequeue(null,t);n(c,a),r.dequeue(null,t);});});},Is=function(e,t,n){let{queue:r,fs:i,options:{suppressErrors:s}}=t;r.enqueue();try{let o=i.realpathSync(e),a=i.statSync(o);if(a.isDirectory()&&Qn(e,o,t))return;n(a,o);}catch(o){if(!s)throw o}};function Ds(e,t){return !e.resolveSymlinks||e.excludeSymlinks?null:t?Is:Fs}function Qn(e,t,n){if(n.options.useRealPaths)return js(t,n);let r=dirname(e),i=1;for(;r!==n.root&&i<2;){let s=n.symlinks.get(r);!!s&&(s===t||s.startsWith(t)||t.startsWith(s))?i++:r=dirname(r);}return n.symlinks.set(e,t),i>1}function js(e,t){return t.visited.includes(e+t.options.pathSeparator)}var Ms=e=>e.counts,Us=e=>e.groups,Hs=e=>e.paths,Bs=e=>e.paths.slice(0,e.options.maxFiles),qs=(e,t,n)=>(Ce(t,n,e.counts,e.options.suppressErrors),null),Vs=(e,t,n)=>(Ce(t,n,e.paths,e.options.suppressErrors),null),Gs=(e,t,n)=>(Ce(t,n,e.paths.slice(0,e.options.maxFiles),e.options.suppressErrors),null),Ws=(e,t,n)=>(Ce(t,n,e.groups,e.options.suppressErrors),null);function Ce(e,t,n,r){t(e&&!r?e:null,n);}function zs(e,t){let{onlyCounts:n,group:r,maxFiles:i}=e;return n?t?Ms:qs:r?t?Us:Ws:i?t?Bs:Gs:t?Hs:Vs}var Zn={withFileTypes:true},Ks=(e,t,n,r,i)=>{if(e.queue.enqueue(),r<0)return e.queue.dequeue(null,e);let{fs:s}=e;e.visited.push(t),e.counts.directories++,s.readdir(t||".",Zn,(o,a=[])=>{i(a,n,r),e.queue.dequeue(e.options.suppressErrors?null:o,e);});},Xs=(e,t,n,r,i)=>{let{fs:s}=e;if(r<0)return;e.visited.push(t),e.counts.directories++;let o=[];try{o=s.readdirSync(t||".",Zn);}catch(a){if(!e.options.suppressErrors)throw a}i(o,n,r);};function Js(e){return e?Xs:Ks}var Ys=class{count=0;constructor(e){this.onQueueEmpty=e;}enqueue(){return this.count++,this.count}dequeue(e,t){this.onQueueEmpty&&(--this.count<=0||e)&&(this.onQueueEmpty(e,t),e&&(t.controller.abort(),this.onQueueEmpty=void 0));}},Qs=class{_files=0;_directories=0;set files(e){this._files=e;}get files(){return this._files}set directories(e){this._directories=e;}get directories(){return this._directories}get dirs(){return this._directories}},Zs=class{aborted=false;abort(){this.aborted=true;}},tr=class{root;isSynchronous;state;joinPath;pushDirectory;pushFile;getArray;groupFiles;resolveSymlink;walkDirectory;callbackInvoker;constructor(e,t,n){this.isSynchronous=!n,this.callbackInvoker=zs(t,this.isSynchronous),this.root=Qe(e,t),this.state={root:ps(this.root)?this.root:this.root.slice(0,-1),paths:[""].slice(0,0),groups:[],counts:new Qs,options:t,queue:new Ys((r,i)=>this.callbackInvoker(i,r,n)),symlinks:new Map,visited:[""].slice(0,0),controller:new Zs,fs:t.fs||At},this.joinPath=gs(this.root,t),this.pushDirectory=Es(this.root,t),this.pushFile=vs(t),this.getArray=ks(t),this.groupFiles=Os(t),this.resolveSymlink=Ds(t,this.isSynchronous),this.walkDirectory=Js(this.isSynchronous);}start(){return this.pushDirectory(this.root,this.state.paths,this.state.options.filters),this.walkDirectory(this.state,this.root,this.root,this.state.options.maxDepth,this.walk),this.isSynchronous?this.callbackInvoker(this.state,null):null}walk=(e,t,n)=>{let{paths:r,options:{filters:i,resolveSymlinks:s,excludeSymlinks:o,exclude:a,maxFiles:l,signal:c,useRealPaths:u,pathSeparator:h},controller:d}=this.state;if(d.aborted||c&&c.aborted||l&&r.length>l)return;let b=this.getArray(this.state.paths);for(let w=0;w<e.length;++w){let E=e[w];if(E.isFile()||E.isSymbolicLink()&&!s&&!o){let _=this.joinPath(E.name,t);this.pushFile(_,b,this.state.counts,i);}else if(E.isDirectory()){let _=ds(E.name,t,this.state.options.pathSeparator);if(a&&a(E.name,_))continue;this.pushDirectory(_,r,i),this.walkDirectory(this.state,_,_,n-1,this.walk);}else if(this.resolveSymlink&&E.isSymbolicLink()){let _=Yn(E.name,t);this.resolveSymlink(_,this.state,($,x)=>{if($.isDirectory()){if(x=Qe(x,this.state.options),a&&a(E.name,u?x:_+h))return;this.walkDirectory(this.state,x,u?x:_+h,n-1,this.walk);}else {x=u?x:_;let G=basename(x),Z=Qe(dirname(x),this.state.options);x=this.joinPath(G,Z),this.pushFile(x,b,this.state.counts,i);}});}}this.groupFiles(this.state.groups,t,b);}};function to(e,t){return new Promise((n,r)=>{er(e,t,(i,s)=>{if(i)return r(i);n(s);});})}function er(e,t,n){new tr(e,t,n).start();}function eo(e,t){return new tr(e,t).start()}var Kn=class{constructor(e,t){this.root=e,this.options=t;}withPromise(){return to(this.root,this.options)}withCallback(e){er(this.root,this.options,e);}sync(){return eo(this.root,this.options)}},nr=null;try{zn.resolve("picomatch"),nr=zn("picomatch");}catch{}var rr=class{globCache={};options={maxDepth:1/0,suppressErrors:true,pathSeparator:sep,filters:[]};globFunction;constructor(e){this.options={...this.options,...e},this.globFunction=this.options.globFunction;}group(){return this.options.group=true,this}withPathSeparator(e){return this.options.pathSeparator=e,this}withBasePath(){return this.options.includeBasePath=true,this}withRelativePaths(){return this.options.relativePaths=true,this}withDirs(){return this.options.includeDirs=true,this}withMaxDepth(e){return this.options.maxDepth=e,this}withMaxFiles(e){return this.options.maxFiles=e,this}withFullPaths(){return this.options.resolvePaths=true,this.options.includeBasePath=true,this}withErrors(){return this.options.suppressErrors=false,this}withSymlinks({resolvePaths:e=true}={}){return this.options.resolveSymlinks=true,this.options.useRealPaths=e,this.withFullPaths()}withAbortSignal(e){return this.options.signal=e,this}normalize(){return this.options.normalizePath=true,this}filter(e){return this.options.filters.push(e),this}onlyDirs(){return this.options.excludeFiles=true,this.options.includeDirs=true,this}exclude(e){return this.options.exclude=e,this}onlyCounts(){return this.options.onlyCounts=true,this}crawl(e){return new Kn(e||".",this.options)}withGlobFunction(e){return this.globFunction=e,this}crawlWithOptions(e,t){return this.options={...this.options,...t},new Kn(e||".",this.options)}glob(...e){return this.globFunction?this.globWithOptions(e):this.globWithOptions(e,{dot:true})}globWithOptions(e,...t){let n=this.globFunction||nr;if(!n)throw new Error("Please specify a glob function to use glob matching.");var r=this.globCache[e.join("\0")];return r||(r=n(e,...t),this.globCache[e.join("\0")]=r),this.options.filters.push(i=>r(i)),this}};var _t=Rt(Cr()),Lo=Array.isArray,$r=process.platform==="win32",Oo=/^(\/?\.\.)+$/;function Fo(e,t={}){let n=e.length,r=Array(n),i=Array(n),s=!t.noglobstar;for(let o=0;o<n;o++){let a=Nr(e[o]);r[o]=a;let l=a.length,c=Array(l);for(let u=0;u<l;u++)c[u]=(0, _t.default)(a[u],t);i[o]=c;}return o=>{let a=o.split("/");if(a[0]===".."&&Oo.test(o))return true;for(let l=0;l<e.length;l++){let c=r[l],u=i[l],h=a.length,d=Math.min(h,c.length),b=0;for(;b<d;){let w=c[b];if(w.includes("/"))return true;if(!u[b](a[b]))break;if(s&&w==="**")return true;b++;}if(b===h)return true}return false}}var Io=/^[A-Z]:\/$/i,Do=$r?e=>Io.test(e):e=>e==="/";function Rr(e,t,n){if(e===t||t.startsWith(`${e}/`)){if(n){let i=Do(e)?e.length:e.length+1;return (s,o)=>s.slice(i,o?-1:void 0)||"."}let r=t.slice(e.length+1);return r?(i,s)=>{if(i===".")return r;let o=`${r}/${i}`;return s?o.slice(0,-1):o}:(i,s)=>s&&i!=="."?i.slice(0,-1):i}return n?r=>posix.relative(e,r)||".":r=>posix.relative(e,`${t}/${r}`)||"."}function jo(e,t){if(t.startsWith(`${e}/`)){let n=t.slice(e.length+1);return r=>`${n}/${r}`}return n=>{let r=posix.relative(e,`${t}/${n}`);return n.endsWith("/")&&r!==""?`${r}/`:r||"."}}var Mo={parts:true};function Nr(e){var t;let n=_t.default.scan(e,Mo);return !((t=n.parts)===null||t===void 0)&&t.length?n.parts:[e]}var Uo=/(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g,Ho=/(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g,Bo=e=>e.replace(Uo,"\\$&"),qo=e=>e.replace(Ho,"\\$&"),Vo=$r?qo:Bo;function Go(e,t){let n=_t.default.scan(e);return n.isGlob||n.negated}function Tt(...e){console.log(`[tinyglobby ${new Date().toLocaleTimeString("es")}]`,...e);}var Wo=/^(\/?\.\.)+/,zo=/\\(?=[()[\]{}!*+?@|])/g,$e=/\\/g;function un(e,t,n,r,i){let s=e;e.endsWith("/")&&(s=e.slice(0,-1)),!s.endsWith("*")&&t&&(s+="/**");let o=Vo(n);vr.isAbsolute(s.replace(zo,""))?s=posix.relative(o,s):s=posix.normalize(s);let a=Wo.exec(s),l=Nr(s);if(a?.[0]){let u=(a[0].length+1)/3,h=0,d=o.split("/");for(;h<u&&l[h+u]===d[d.length+h-u];)s=s.slice(0,(u-h-1)*3)+s.slice((u-h)*3+l[h+u].length+1)||".",h++;let b=posix.join(n,a[0].slice(h*3));!b.startsWith(".")&&r.root.length>b.length&&(r.root=b,r.depthOffset=-u+h);}if(!i&&r.depthOffset>=0){var c;(c=r.commonPath)!==null&&c!==void 0||(r.commonPath=l);let u=[],h=Math.min(r.commonPath.length,l.length);for(let d=0;d<h;d++){let b=l[d];if(b==="**"&&!l[d+1]){u.pop();break}if(b!==r.commonPath[d]||Go(b)||d===l.length-1)break;u.push(b);}r.depthOffset=u.length,r.commonPath=u,r.root=u.length>0?posix.join(n,...u):n;}return s}function Ko({patterns:e=["**/*"],ignore:t=[],expandDirectories:n=true},r,i){typeof e=="string"&&(e=[e]),typeof t=="string"&&(t=[t]);let s=[],o=[];for(let a of t)a&&(a[0]!=="!"||a[1]==="(")&&o.push(un(a,n,r,i,true));for(let a of e)a&&(a[0]!=="!"||a[1]==="("?s.push(un(a,n,r,i,false)):(a[1]!=="!"||a[2]==="(")&&o.push(un(a.slice(1),n,r,i,true)));return {match:s,ignore:o}}function Xo(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];e[n]=t(r);}return e}function Jo(e){return e?e instanceof URL?fileURLToPath(e).replace($e,"/"):vr.resolve(e).replace($e,"/"):process.cwd().replace($e,"/")}function Yo(e,t={}){let n=process.env.TINYGLOBBY_DEBUG?{...t,debug:true}:t,r=Jo(n.cwd);if(n.debug&&Tt("globbing with:",{patterns:e,options:n,cwd:r}),Array.isArray(e)&&e.length===0)return [{sync:()=>[],withPromise:async()=>[]},false];let i={root:r,commonPath:null,depthOffset:0},s=Ko({...n,patterns:e},r,i);n.debug&&Tt("internal processing patterns:",s);let o={dot:n.dot,nobrace:n.braceExpansion===false,nocase:n.caseSensitiveMatch===false,noextglob:n.extglob===false,noglobstar:n.globstar===false,posix:true},a=(0, _t.default)(s.match,{...o,ignore:s.ignore}),l=(0, _t.default)(s.ignore,o),c=Fo(s.match,o),u=Rr(r,i.root,n.absolute),h=n.absolute?u:Rr(r,i.root,true),d={filters:[n.debug?(E,_)=>{let $=u(E,_),x=a($);return x&&Tt(`matched ${$}`),x}:(E,_)=>a(u(E,_))],exclude:n.debug?(E,_)=>{let $=h(_,true),x=$!=="."&&!c($)||l($);return Tt(x?`skipped ${_}`:`crawling ${_}`),x}:(E,_)=>{let $=h(_,true);return $!=="."&&!c($)||l($)},fs:n.fs?{readdir:n.fs.readdir||At__default.readdir,readdirSync:n.fs.readdirSync||At__default.readdirSync,realpath:n.fs.realpath||At__default.realpath,realpathSync:n.fs.realpathSync||At__default.realpathSync,stat:n.fs.stat||At__default.stat,statSync:n.fs.statSync||At__default.statSync}:void 0,pathSeparator:"/",relativePaths:true,resolveSymlinks:true,signal:n.signal};n.deep!==void 0&&(d.maxDepth=Math.round(n.deep-i.depthOffset)),n.absolute&&(d.relativePaths=false,d.resolvePaths=true,d.includeBasePath=true),n.followSymbolicLinks===false&&(d.resolveSymlinks=false,d.excludeSymlinks=true),n.onlyDirectories?(d.excludeFiles=true,d.includeDirs=true):n.onlyFiles===false&&(d.includeDirs=true),i.root=i.root.replace($e,"");let b=i.root;n.debug&&Tt("internal properties:",i);let w=r!==b&&!n.absolute&&jo(r,i.root);return [new rr(d).crawl(b),w]}async function Mt(e,t){if(e&&t?.patterns)throw new Error("Cannot pass patterns as both an argument and an option");let n=Lo(e)||typeof e=="string",r=n?t:e,i=n?e:e.patterns,[s,o]=Yo(i,r);return o?Xo(await s.withPromise(),o):s.withPromise()}var N=Rt($t());var Zo=/^(\d{14})(?:_([^.]+))?\.sql$/;function kr(e){return e.config?.db?.driver==="sqlite"?"./sqlite-migrations/*.sql":"./migrations/*.sql"}function ta(e){return nt__default.posix.dirname(kr(e))}async function Ut(e){let t=nt__default.join(process.cwd(),"supabase"),n=await Mt([kr(e)],{cwd:t,absolute:true}),r=[];for(let i of n){let s=nt__default.basename(i),o=Zo.exec(s);if(!o)continue;let a=await M__default.readFile(i,"utf-8");r.push({version:o[1],name:o[2]??null,filename:s,path:i,sql:a});}return r.sort((i,s)=>i.version.localeCompare(s.version))}var Qr="supabase/.temp/.translation-cache.json",Zr=2;async function Oa(e,t){let n=await e.connection.introspect(),r=Nn(n);await ti(e,{...t,dbHasTables:n.tables.length>0,dbFingerprint:r}),n.tables.length===0&&await Da(e);let i=await e.connection.introspect();ni(i,e);}async function Fa(e){let t=await Mt(e.config.db?.seed?.sql_paths??["./seed.sql"],{cwd:nt__default.join(process.cwd(),"supabase"),absolute:true});return (await Promise.all(t.map(r=>M__default.readFile(r,"utf-8")))).flatMap(r=>splitSqlStatements(r))}async function Ia(e,t){let n=await Fa(e);if(n.length===0)return 0;console.log(N.default.dim("Seeding database..."));try{return await e.connection.transaction(n),n.length}catch(r){let i="Fix `supabase/seed.sql`, then run `bun run dev --recreate` to reset and reseed.";throw new Error(`Seed failed and was rolled back: ${String(r.message??r)}
60
+ ${i}`)}}async function Da(e){await Ia(e);}async function ja(e){let t=await Mt(e.config?.db?.migrations?.schema_paths??["./schemas/*.sql"],{cwd:nt__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(`
61
+ `).filter(s=>s.trim().length>0&&!s.trim().startsWith("--")).join(`
91
62
  `)).join(`
92
- `));return s||""}async function mn(a,t){let s=await Jl(a);if(!(!s&&(await Zt(a)).length>0)&&!(!s&&!a.connection.config.baseSchema)){if(t?.dbHasTables&&await Xl(a,s,t.dbFingerprint)){console.log($.default.dim("Schema unchanged \u2014 skipping translation."));return}try{let e=a.connection.createMigrator(s),i=await e.diff(),r=e.translationResult?.ast,n=await a.connection.introspect(),o=hi(n);if(i.plan.steps.length===0){await pn(a,s,r,o);return}await e.migratePlan(i.plan,{force:t?.force??!1}),Zl(i);let u=await a.connection.introspect();return await pn(a,s,r,hi(u)),console.log(""),tp(i),i}catch(e){if(String(e).includes("likely empty"))console.log($.default.dim("Nothing to migrate."));else {console.error("Migration error: "+String(e));try{await a.connection.exec("rollback");}catch{}}}}}function Yl(a){return a.connection.config?.baseSchema??""}function En(a,t){let s=createHash("sha256");return s.update(JSON.stringify([Yl(a),t??""])),s.digest("hex")}function hi(a){let t=(e,i)=>[...e].sort((r,n)=>i(r).localeCompare(i(n))),s={tables:t(a.tables??[],e=>`${e.schema??""}.${e.name}`).map(e=>({schema:e.schema,name:e.name,type:e.type,sql:e.sql})),columns:t(a.columns??[],e=>`${e.schema??""}.${e.table}.${e.name}`).map(e=>({schema:e.schema,table:e.table,name:e.name,type:e.type,nullable:e.nullable,default_value:e.default_value,is_primary_key:e.is_primary_key})),indexes:t(a.indexes??[],e=>`${e.schema??""}.${e.table}.${e.name}`).map(e=>({schema:e.schema,table:e.table,name:e.name,unique:e.unique,columns:e.columns})),foreign_keys:t(a.foreign_keys??[],e=>`${e.schema??""}.${e.table}.${e.column}->${e.ref_table}.${e.ref_column}`).map(e=>({schema:e.schema,table:e.table,column:e.column,ref_schema:e.ref_schema,ref_table:e.ref_table,ref_column:e.ref_column})),primary_keys:t(a.primary_keys??[],e=>`${e.schema??""}.${e.table}`).map(e=>({schema:e.schema,table:e.table,columns:e.columns})),check_constraints:t(a.check_constraints??[],e=>`${e.schema??""}.${e.table}.${e.name??""}.${e.column??""}`).map(e=>({schema:e.schema,table:e.table,name:e.name,column:e.column,expression:e.expression})),unique_constraints:t(a.unique_constraints??[],e=>`${e.schema??""}.${e.table}.${e.name}`).map(e=>({schema:e.schema,table:e.table,name:e.name,columns:e.columns})),views:t(a.views??[],e=>`${e.schema??""}.${e.name}`).map(e=>({schema:e.schema,name:e.name,sql:e.sql})),triggers:t(a.triggers??[],e=>`${e.schema??""}.${e.table}.${e.name}`).map(e=>({schema:e.schema,table:e.table,name:e.name,sql:e.sql})),custom_types:t(a.custom_types??[],e=>`${e.schema??""}.${e.type}`).map(e=>({schema:e.schema,type:e.type,kind:e.kind,values:e.values,fields:e.fields}))};return createHash("sha256").update(JSON.stringify(s)).digest("hex")}async function Xl(a,t,s){let e=a.connection;if(typeof e.updateDeparseInfo!="function")return false;let i=v__default.join(process.cwd(),fn),r;try{r=await G__default.readFile(i,"utf-8");}catch{return false}let n;try{n=JSON.parse(r);}catch{return false}if(n.v!==hn||n.hash!==En(a,t)||!s||n.dbFingerprint!==s||!n.ast||typeof n.ast!="object")return false;try{let o=await Promise.resolve().then(()=>(un(),on)),u=n.ast,l=o.collectEnums(u),p=o.collectSchema(u,l),f=o.collectVariables(u),h=o.collectTableConstraints(u),E=o.collectComments(u),{policies:g,tables:R}=o.collectPolicies(u);return e.updateDeparseInfo({enums:l,rls:{tables:R,policies:g},schema:p,vars:f,tableConstraints:h,comments:E}),!0}catch{return false}}async function pn(a,t,s,e){if(!s||typeof s!="object")return;let i={v:hn,hash:En(a,t),dbFingerprint:e,ast:s},r=v__default.join(process.cwd(),fn);try{await G__default.mkdir(v__default.dirname(r),{recursive:!0}),await G__default.writeFile(r,JSON.stringify(i),"utf-8");}catch{}}function gn(a,t){console.log();let s=(i,r)=>{let n=u=>{let l=$.default.dim;return typeof u=="number"&&(u>=0&&(l=u>0?$.default.green:$.default.dim),u<0&&(l=$.default.red)),typeof u=="boolean"?u?$.default.green("\u2713"):$.default.red("\u2717"):l(String(u))},o=Object.entries(r).map(([u,l])=>`${u}: ${n(l)}`).join($.default.dim(" / "));console.log(`${$.default.dim("[")} ${i} ${$.default.dim("]")} ${o}`);};s($.default.green("DATA"),{tables:a.tables.length,columns:a.columns.length,indexes:a.indexes.length});let e=t.config.rls??t.connection.config.translation?.deparse?.rls??{tables:new Set([]),policies:[]};s($.default.green("AUTH"),{enabled:!!t.config.auth?.enabled,tables:ensureVar.Set(e.tables).size,policies:ensureVar.Array(e.policies).length});}function Kl(a,t){setTimeout(()=>{console.log($.default.dim("Watching for changes...")),$r.watch("./supabase/schemas").on("change",async e=>{console.log(),console.log($.default.dim(`Schema changed: ${e}`)),await mn(a,t);let i=await a.connection.introspect();gn(i,a);});},200);}function zl(a,t){let s=e=>e;return a.plan.steps.flatMap(e=>[e.description?s(`-- ${e.description}`):"",e.sql+`
93
- `]).filter(e=>e.trim().length>0).join(`
94
- `)}function Ql(a){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 Zl(a,t){let s="./supabase/.temp/migrations";at(s);let e=Ql(),i=zl(a);Rt(v__default.join(s,e),i),console.log($.default.dim(`Migration written to ${$.default.cyan(v__default.join(s,e))}`));}function tp({diff:a}){if(typeof a=="string"){console.log($.default.cyan(a));return}if(!a.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(a.tables.length>0){console.log($.default.dim("Tables:"));for(let s of a.tables){let{color:e,symbol:i}=t[s.type];console.log(e(`${i} ${s.name}`));}console.log();}if(a.columns.length>0){console.log($.default.dim("Columns:"));for(let s of a.columns){let{color:e,symbol:i}=t[s.type],r="";s.changes&&(r=Object.entries(s.changes).map(([n,o])=>`${n}: ${o.from} \u2192 ${o.to}`).join(", ")),console.log(e(`${i} ${s.table}.${s.name}${r?` (${r})`:""}`));}console.log();}if(a.indexes.length>0){console.log($.default.dim("Indexes:"));for(let s of a.indexes){let{color:e,symbol:i}=t[s.type];console.log(e(`${i} ${s.name} on ${s.table}`));}console.log();}if(a.foreign_keys.length>0){console.log($.default.dim("Foreign Keys:"));for(let s of a.foreign_keys){let{color:e,symbol:i}=t[s.type];console.log(e(`${i} ${s.table}.${s.column} \u2192 ${s.ref_table}.${s.ref_column}`));}console.log();}}function ns(a){return a.dialect==="postgres"?"pg":a.config?.ddlDialect==="sqlite"?"sqlite":"pg-flat"}function Tn(a){return a==="sqlite"?{schema_migrations:"migrations",seed_files:null}:a==="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 mi(a){return `'${a.replace(/'/g,"''")}'`}function ep(a){return `'${`{${a.map(e=>`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`).join(",")}}`.replace(/'/g,"''")}'`}function sp(a){return a==="sqlite"?[`CREATE TABLE IF NOT EXISTS migrations (
63
+ `));return n||""}async function ti(e,t){let n=await ja(e);if(!(!n&&(await Ut(e)).length>0)&&!(!n&&!e.connection.config.baseSchema)){if(t?.dbHasTables&&await Ua(e,n,t.dbFingerprint)){console.log(N.default.dim("Schema unchanged \u2014 skipping translation."));return}try{let r=e.connection.createMigrator(n),i=await r.diff(),s=r.translationResult?.ast,o=await e.connection.introspect(),a=Nn(o);if(i.plan.steps.length===0){await Jr(e,n,s,a);return}await r.migratePlan(i.plan,{force:t?.force??!1}),Va(i);let l=await e.connection.introspect();return await Jr(e,n,s,Nn(l)),console.log(""),Ga(i),i}catch(r){if(String(r).includes("likely empty"))console.log(N.default.dim("Nothing to migrate."));else {console.error("Migration error: "+String(r));try{await e.connection.exec("rollback");}catch{}}}}}function Ma(e){return e.connection.config?.baseSchema??""}function ei(e,t){let n=createHash("sha256");return n.update(JSON.stringify([Ma(e),t??""])),n.digest("hex")}function Nn(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 Ua(e,t,n){let r=e.connection;if(typeof r.updateDeparseInfo!="function")return false;let i=nt__default.join(process.cwd(),Qr),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!==Zr||o.hash!==ei(e,t)||!n||o.dbFingerprint!==n||!o.ast||typeof o.ast!="object")return false;try{let a=await Promise.resolve().then(()=>(Kr(),zr)),l=o.ast,c=a.collectEnums(l),u=a.collectSchema(l,c),h=a.collectVariables(l),d=a.collectTableConstraints(l),b=a.collectComments(l),{policies:w,tables:E}=a.collectPolicies(l);return r.updateDeparseInfo({enums:c,rls:{tables:E,policies:w},schema:u,vars:h,tableConstraints:d,comments:b}),!0}catch{return false}}async function Jr(e,t,n,r){if(!n||typeof n!="object")return;let i={v:Zr,hash:ei(e,t),dbFingerprint:r,ast:n},s=nt__default.join(process.cwd(),Qr);try{await M__default.mkdir(nt__default.dirname(s),{recursive:!0}),await M__default.writeFile(s,JSON.stringify(i),"utf-8");}catch{}}function ni(e,t){console.log();let n=(i,s)=>{let o=l=>{let c=N.default.dim;return typeof l=="number"&&(l>=0&&(c=l>0?N.default.green:N.default.dim),l<0&&(c=N.default.red)),typeof l=="boolean"?l?N.default.green("\u2713"):N.default.red("\u2717"):c(String(l))},a=Object.entries(s).map(([l,c])=>`${l}: ${o(c)}`).join(N.default.dim(" / "));console.log(`${N.default.dim("[")} ${i} ${N.default.dim("]")} ${a}`);};n(N.default.green("DATA"),{tables:e.tables.length,columns:e.columns.length,indexes:e.indexes.length});let r=t.config.rls??t.connection.config.translation?.deparse?.rls??{tables:new Set([]),policies:[]};n(N.default.green("AUTH"),{enabled:!!t.config.auth?.enabled,tables:ensureVar.Set(r.tables).size,policies:ensureVar.Array(r.policies).length});}function Ha(e,t){setTimeout(()=>{console.log(N.default.dim("Watching for changes...")),La.watch("./supabase/schemas").on("change",async r=>{console.log(),console.log(N.default.dim(`Schema changed: ${r}`)),await ti(e,t);let i=await e.connection.introspect();ni(i,e);});},200);}function Ba(e,t){let n=r=>r;return e.plan.steps.flatMap(r=>[r.description?n(`-- ${r.description}`):"",r.sql+`
64
+ `]).filter(r=>r.trim().length>0).join(`
65
+ `)}function qa(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 Va(e,t){let n="./supabase/.temp/migrations";tt(n);let r=qa(),i=Ba(e);mt(nt__default.join(n,r),i),console.log(N.default.dim(`Migration written to ${N.default.cyan(nt__default.join(n,r))}`));}function Ga({diff:e}){if(typeof e=="string"){console.log(N.default.cyan(e));return}if(!e.has_changes)return;console.log(N.default.bgWhite(N.default.black(" Schema Diff "))),console.log();let t={added:{color:N.default.green,symbol:"+"},removed:{color:N.default.red,symbol:"-"},modified:{color:N.default.yellow,symbol:"~"}};if(e.tables.length>0){console.log(N.default.dim("Tables:"));for(let n of e.tables){let{color:r,symbol:i}=t[n.type];console.log(r(`${i} ${n.name}`));}console.log();}if(e.columns.length>0){console.log(N.default.dim("Columns:"));for(let n of e.columns){let{color:r,symbol:i}=t[n.type],s="";n.changes&&(s=Object.entries(n.changes).map(([o,a])=>`${o}: ${a.from} \u2192 ${a.to}`).join(", ")),console.log(r(`${i} ${n.table}.${n.name}${s?` (${s})`:""}`));}console.log();}if(e.indexes.length>0){console.log(N.default.dim("Indexes:"));for(let n of e.indexes){let{color:r,symbol:i}=t[n.type];console.log(r(`${i} ${n.name} on ${n.table}`));}console.log();}if(e.foreign_keys.length>0){console.log(N.default.dim("Foreign Keys:"));for(let n of e.foreign_keys){let{color:r,symbol:i}=t[n.type];console.log(r(`${i} ${n.table}.${n.column} \u2192 ${n.ref_table}.${n.ref_column}`));}console.log();}}function Fe(e){return e.dialect==="postgres"?"pg":e.config?.ddlDialect==="sqlite"?"sqlite":"pg-flat"}function ri(e){return e==="sqlite"?{schema_migrations:"migrations",seed_files:null}:e==="pg-flat"?{schema_migrations:'"supabase_migrations.schema_migrations"',seed_files:'"supabase_migrations.seed_files"'}:{schema_migrations:"supabase_migrations.schema_migrations",seed_files:"supabase_migrations.seed_files"}}function kn(e){return `'${e.replace(/'/g,"''")}'`}function Wa(e){return `'${`{${e.map(r=>`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`).join(",")}}`.replace(/'/g,"''")}'`}function za(e){return e==="sqlite"?[`CREATE TABLE IF NOT EXISTS migrations (
95
66
  version TEXT NOT NULL PRIMARY KEY,
96
67
  statements TEXT,
97
68
  name TEXT
@@ -102,9 +73,9 @@ ${i}`)}}async function Hl(a){await Wl(a);}async function Jl(a){let t=await Kt(a.
102
73
  )`,`CREATE TABLE IF NOT EXISTS supabase_migrations.seed_files (
103
74
  path text NOT NULL PRIMARY KEY,
104
75
  hash text NOT NULL
105
- )`]}function Sn(a,t){let{schema_migrations:s}=Tn(a),e=t.name===null?"NULL":mi(t.name),i=a==="pg"?ep(t.statements):mi(JSON.stringify(t.statements));return `INSERT INTO ${s} (version, statements, name) VALUES (${mi(t.version)}, ${i}, ${e})`}function ip(a){let{schema_migrations:t}=Tn(a);return `SELECT version FROM ${t} ORDER BY version ASC`}async function rp(a,t){if(a.dialect==="postgres"||a.config.ddlDialect==="sqlite")return t;let e=await a.translateDdl(t);return typeof e=="string"?e:e.ddl??t}function np(a){return a.split(/;\s*(?:\n|$)/).map(t=>t.trim()).filter(t=>t.length>0)}async function An(a){let t=ns(a),e=sp(t).map(r=>r.trim()).join(`;
106
- `)+";",i=await rp(a,e);for(let r of np(i))await a.exec(r);}async function Cn(a){let t=ns(a);return ((await a.exec(ip(t)))?.rows??[]).map(e=>e.version)}async function ap(a){await up(a),await An(a.connection);let t=new Set(await Cn(a.connection)),s=await Zt(a),e=ns(a.connection),i=[],r=[];for(let n of s){if(t.has(n.version)){r.push(n);continue}let o=De(n.sql),u;if(e==="pg-flat"){let p=await a.connection.translateDdl(n.sql),f=typeof p=="string"?p:p.ddl??"";u=De(f);}else u=o;let l=Sn(e,{version:n.version,name:n.name,statements:o});await a.connection.transaction([...u,l],{intent:"migration"}),i.push(n);}return s.length>0&&e!=="sqlite"&&await op(a,s),{applied:i,skipped:r}}async function op(a,t){let s=t.map(n=>n.sql).join(`
107
- `);if(!s.trim())return;let e=a.connection;if(typeof e.translateDdl!="function"||typeof e.updateDeparseInfo!="function")return;let i=await e.translateDdl(s),r=e.config?.translation?.deparse??{};e.updateDeparseInfo({...r,...i});}async function up(a){let t=a.connection.config?.baseSchema;if(!t||!t.trim())return;let s=a.connection,e=t;if(s.dialect==="sqlite"&&s.config.ddlDialect!=="sqlite"&&s.translateDdl){let i=await s.translateDdl(t);e=typeof i=="string"?i:i.ddl??t;}for(let i of De(e))try{await s.exec(i);}catch{}}/*! Bundled license information:
76
+ )`]}function ii(e,t){let{schema_migrations:n}=ri(e),r=t.name===null?"NULL":kn(t.name),i=e==="pg"?Wa(t.statements):kn(JSON.stringify(t.statements));return `INSERT INTO ${n} (version, statements, name) VALUES (${kn(t.version)}, ${i}, ${r})`}function Ka(e){let{schema_migrations:t}=ri(e);return `SELECT version FROM ${t} ORDER BY version ASC`}async function Xa(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 Ja(e){return e.split(/;\s*(?:\n|$)/).map(t=>t.trim()).filter(t=>t.length>0)}async function si(e){let t=Fe(e),r=za(t).map(s=>s.trim()).join(`;
77
+ `)+";",i=await Xa(e,r);for(let s of Ja(i))await e.exec(s);}async function oi(e){let t=Fe(e);return ((await e.exec(Ka(t)))?.rows??[]).map(r=>r.version)}async function Ya(e){await Za(e),await si(e.connection);let t=new Set(await oi(e.connection)),n=await Ut(e),r=Fe(e.connection),i=[],s=[];for(let o of n){if(t.has(o.version)){s.push(o);continue}let a=be(o.sql),l;if(r==="pg-flat"){let u=await e.connection.translateDdl(o.sql),h=typeof u=="string"?u:u.ddl??"";l=be(h);}else l=a;let c=ii(r,{version:o.version,name:o.name,statements:a});await e.connection.transaction([...l,c],{intent:"migration"}),i.push(o);}return n.length>0&&r!=="sqlite"&&await Qa(e,n),{applied:i,skipped:s}}async function Qa(e,t){let n=t.map(o=>o.sql).join(`
78
+ `);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 Za(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 be(r))try{await n.exec(i);}catch{}}/*! Bundled license information:
108
79
 
109
80
  smol-toml/dist/error.js:
110
81
  smol-toml/dist/util.js:
@@ -142,7 +113,4 @@ smol-toml/dist/index.js:
142
113
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
143
114
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
144
115
  *)
145
-
146
- chokidar/index.js:
147
- (*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) *)
148
- */export{ap as applyPendingMigrations,fa as createApi,ma as ensureInitialStructure,Vl as ensureSchema,Zt as listMigrationFiles,ol as migrationsDir,Kl as watchSchema};
116
+ */export{Ya as applyPendingMigrations,Qi as createApi,ts as ensureInitialStructure,Oa as ensureSchema,Ut as listMigrationFiles,ta as migrationsDir,Ha as watchSchema};