@supabase/lite 0.9.0 → 0.9.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.
Files changed (64) hide show
  1. package/FEATURES.md +176 -0
  2. package/LIMITATIONS.md +9 -6
  3. package/PATTERNS.md +66 -6
  4. package/README.md +16 -8
  5. package/STATUS.md +33 -20
  6. package/dist/{Connection-ZWTDByQ5.d.ts → Connection-f_d5HhQ0.d.ts} +301 -293
  7. package/dist/cli/index.js +127 -124
  8. package/dist/cli/lib.d.ts +1 -12
  9. package/dist/cli/lib.js +44 -39
  10. package/dist/db/fallback.d.ts +1 -1
  11. package/dist/db/postgres/PostgresConnection.js +18 -18
  12. package/dist/db/postgres/pglite/PgliteConnection.js +17 -17
  13. package/dist/index.d.ts +116 -40
  14. package/dist/index.js +181 -73
  15. package/dist/static/.vite/manifest.json +34 -2
  16. package/dist/static/assets/InterVariable-Dx4kXJAl.woff2 +0 -0
  17. package/dist/static/assets/InterVariable-Italic-DpCbqKDY.woff2 +0 -0
  18. package/dist/static/assets/SourceCodePro-Variable-BP8Zz55n.woff2 +0 -0
  19. package/dist/static/assets/SourceCodePro-Variable-Italic-eALmlzX7.woff2 +0 -0
  20. package/dist/static/assets/main-BY4iigay.css +1 -0
  21. package/dist/static/assets/main-BnQ-v4V9.js +199 -0
  22. package/dist/static/assets/manrope-latin-ext-wght-normal-Ch3YOpNY.woff2 +0 -0
  23. package/dist/static/assets/manrope-latin-wght-normal-DHIcAJRg.woff2 +0 -0
  24. package/dist/vite/index.d.ts +627 -31
  25. package/dist/vite/index.js +2 -2
  26. package/docs/auth/email.mdx +214 -0
  27. package/docs/auth/not-supported.mdx +57 -0
  28. package/docs/auth/overview.mdx +52 -0
  29. package/docs/auth/supported-flows.mdx +120 -0
  30. package/docs/cli/overview.mdx +112 -0
  31. package/docs/cli/telemetry.mdx +34 -0
  32. package/docs/compatibility.mdx +115 -0
  33. package/docs/database/backends.mdx +118 -0
  34. package/docs/database/data-api.mdx +90 -0
  35. package/docs/database/functions-triggers.mdx +93 -0
  36. package/docs/database/migrations.mdx +95 -0
  37. package/docs/database/overview.mdx +66 -0
  38. package/docs/database/postgres-sqlite-translation.mdx +130 -0
  39. package/docs/database/rls.mdx +161 -0
  40. package/docs/database/schemas.mdx +58 -0
  41. package/docs/index.mdx +49 -0
  42. package/docs/integrations/embedded.mdx +100 -0
  43. package/docs/integrations/frameworks.mdx +83 -0
  44. package/docs/integrations/vite.mdx +87 -0
  45. package/docs/llms.txt +52 -0
  46. package/docs/other/edge-functions.mdx +34 -0
  47. package/docs/other/realtime.mdx +22 -0
  48. package/docs/quickstart.mdx +150 -0
  49. package/docs/running.mdx +127 -0
  50. package/docs/storage/adapters.mdx +75 -0
  51. package/docs/storage/limitations.mdx +21 -0
  52. package/docs/storage/overview.mdx +88 -0
  53. package/docs/upgrade.mdx +108 -0
  54. package/package.json +5 -1
  55. package/skills/supalite/SKILL.md +6 -4
  56. package/dist/static/assets/main-1bwWb_1q.js +0 -40996
  57. package/dist/static/assets/main-BDsRycsc.css +0 -4045
  58. package/dist/static/fonts/CustomFont-Black.woff2 +0 -0
  59. package/dist/static/fonts/CustomFont-BlackItalic.woff2 +0 -0
  60. package/dist/static/fonts/CustomFont-Bold.woff2 +0 -0
  61. package/dist/static/fonts/CustomFont-BoldItalic.woff2 +0 -0
  62. package/dist/static/fonts/CustomFont-Book.woff2 +0 -0
  63. package/dist/static/fonts/CustomFont-BookItalic.woff2 +0 -0
  64. package/dist/static/fonts/CustomFont-Medium.woff2 +0 -0
package/dist/cli/lib.js CHANGED
@@ -1,4 +1,4 @@
1
- import'pgsql-deparser';import*as ie from'node:path';import ie__default from'node:path';import as from'node:os';import St from'node:fs';import {createClient}from'@supabase/supabase-js';import {ensureVar,SqliteConnection,App,cloud,splitSqlStatements}from'@supabase/lite';import {createConnection}from'@supabase/lite/sqlite';import*as V from'node:fs/promises';import V__default from'node:fs/promises';import {createHash}from'node:crypto';import'jsonv-ts';import {parse}from'dotenv';import'node:url';import*as ro from'fs';import {statSync,stat,realpathSync,realpath,readdirSync,readdir}from'fs';import {resolve,posix,sep,isAbsolute,basename,dirname,normalize,relative}from'path';import {fileURLToPath}from'url';import {createRequire}from'module';import oc from'chokidar';try {
1
+ import'pgsql-deparser';import*as le from'node:path';import le__default from'node:path';import Os from'node:os';import Lt from'node:fs';import {createClient}from'@supabase/supabase-js';import {ensureVar,SqliteConnection,App,cloud,splitSqlStatements}from'@supabase/lite';import {createConnection}from'@supabase/lite/sqlite';import*as W from'node:fs/promises';import W__default from'node:fs/promises';import {createHash,randomUUID}from'node:crypto';import'jsonv-ts';import {parse}from'dotenv';import'node:url';import*as $o from'fs';import {statSync,stat,realpathSync,realpath,readdirSync,readdir}from'fs';import {resolve,posix,sep,isAbsolute,basename,dirname,normalize,relative}from'path';import {fileURLToPath}from'url';import {createRequire}from'module';import Zc from'chokidar';try {
2
2
  /**
3
3
  * Adding this to avoid warnings from node:sqlite being experimental
4
4
  */
@@ -9,44 +9,44 @@ import'pgsql-deparser';import*as ie from'node:path';import ie__default from'node
9
9
  };
10
10
  } catch {}
11
11
 
12
- var es=Object.create;var Kt=Object.defineProperty;var ts=Object.getOwnPropertyDescriptor;var ns=Object.getOwnPropertyNames;var rs=Object.getPrototypeOf,is=Object.prototype.hasOwnProperty;var F=(t,e)=>()=>(t&&(e=t(t=0)),e);var xe=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ss=(t,e)=>{for(var n in e)Kt(t,n,{get:e[n],enumerable:true});},os=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ns(e))!is.call(t,i)&&i!==n&&Kt(t,i,{get:()=>e[i],enumerable:!(r=ts(e,i))||r.enumerable});return t};var Pe=(t,e,n)=>(n=t!=null?es(rs(t)):{},os(Kt(n,"default",{value:t,enumerable:true}),t));var Fe=xe((nu,Xt)=>{var Rt=process||{},rr=Rt.argv||[],Ct=Rt.env||{},fs=!(Ct.NO_COLOR||rr.includes("--no-color"))&&(!!Ct.FORCE_COLOR||rr.includes("--color")||Rt.platform==="win32"||(Rt.stdout||{}).isTTY&&Ct.TERM!=="dumb"||!!Ct.CI),ps=(t,e,n=t)=>r=>{let i=""+r,s=i.indexOf(e,t.length);return ~s?t+ms(i,e,n,s)+e:t+i+e},ms=(t,e,n,r)=>{let i="",s=0;do i+=t.substring(s,r)+n,s=r+e.length,r=t.indexOf(e,s);while(~r);return i+t.substring(s)},ir=(t=fs)=>{let e=t?ps:()=>String;return {isColorSupported:t,reset:e("\x1B[0m","\x1B[0m"),bold:e("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:e("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:e("\x1B[3m","\x1B[23m"),underline:e("\x1B[4m","\x1B[24m"),inverse:e("\x1B[7m","\x1B[27m"),hidden:e("\x1B[8m","\x1B[28m"),strikethrough:e("\x1B[9m","\x1B[29m"),black:e("\x1B[30m","\x1B[39m"),red:e("\x1B[31m","\x1B[39m"),green:e("\x1B[32m","\x1B[39m"),yellow:e("\x1B[33m","\x1B[39m"),blue:e("\x1B[34m","\x1B[39m"),magenta:e("\x1B[35m","\x1B[39m"),cyan:e("\x1B[36m","\x1B[39m"),white:e("\x1B[37m","\x1B[39m"),gray:e("\x1B[90m","\x1B[39m"),bgBlack:e("\x1B[40m","\x1B[49m"),bgRed:e("\x1B[41m","\x1B[49m"),bgGreen:e("\x1B[42m","\x1B[49m"),bgYellow:e("\x1B[43m","\x1B[49m"),bgBlue:e("\x1B[44m","\x1B[49m"),bgMagenta:e("\x1B[45m","\x1B[49m"),bgCyan:e("\x1B[46m","\x1B[49m"),bgWhite:e("\x1B[47m","\x1B[49m"),blackBright:e("\x1B[90m","\x1B[39m"),redBright:e("\x1B[91m","\x1B[39m"),greenBright:e("\x1B[92m","\x1B[39m"),yellowBright:e("\x1B[93m","\x1B[39m"),blueBright:e("\x1B[94m","\x1B[39m"),magentaBright:e("\x1B[95m","\x1B[39m"),cyanBright:e("\x1B[96m","\x1B[39m"),whiteBright:e("\x1B[97m","\x1B[39m"),bgBlackBright:e("\x1B[100m","\x1B[49m"),bgRedBright:e("\x1B[101m","\x1B[49m"),bgGreenBright:e("\x1B[102m","\x1B[49m"),bgYellowBright:e("\x1B[103m","\x1B[49m"),bgBlueBright:e("\x1B[104m","\x1B[49m"),bgMagentaBright:e("\x1B[105m","\x1B[49m"),bgCyanBright:e("\x1B[106m","\x1B[49m"),bgWhiteBright:e("\x1B[107m","\x1B[49m")}};Xt.exports=ir();Xt.exports.createColors=ir;});var We=xe((gp,Fr)=>{var Nr="[^\\\\/]",Qo="(?=.)",Lr="[^/]",hn="(?:\\/|$)",Pr="(?:^|\\/)",gn=`\\.{1,2}${hn}`,Zo="(?!\\.)",ea=`(?!${Pr}${gn})`,ta=`(?!\\.{0,1}${hn})`,na=`(?!${gn})`,ra="[^.\\/]",ia=`${Lr}*?`,sa="/",Or={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:Qo,QMARK:Lr,END_ANCHOR:hn,DOTS_SLASH:gn,NO_DOT:Zo,NO_DOTS:ea,NO_DOT_SLASH:ta,NO_DOTS_SLASH:na,QMARK_NO_DOT:ra,STAR:ia,START_ANCHOR:Pr,SEP:sa},oa={...Or,SLASH_LITERAL:"[\\\\/]",QMARK:Nr,STAR:`${Nr}*?`,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:"\\"},aa={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};Fr.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:aa,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(t){return {"!":{type:"negate",open:"(?:(?!(?:",close:`))${t.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(t){return t===true?oa:Or}};});var Ke=xe(J=>{var{REGEX_BACKSLASH:la,REGEX_REMOVE_BACKSLASH:ca,REGEX_SPECIAL_CHARS:ua,REGEX_SPECIAL_CHARS_GLOBAL:fa}=We();J.isObject=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);J.hasRegexChars=t=>ua.test(t);J.isRegexChar=t=>t.length===1&&J.hasRegexChars(t);J.escapeRegex=t=>t.replace(fa,"\\$1");J.toPosixSlashes=t=>t.replace(la,"/");J.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let t=navigator.platform.toLowerCase();return t==="win32"||t==="windows"}return typeof process<"u"&&process.platform?process.platform==="win32":false};J.removeBackslashes=t=>t.replace(ca,e=>e==="\\"?"":e);J.escapeLast=(t,e,n)=>{let r=t.lastIndexOf(e,n);return r===-1?t:t[r-1]==="\\"?J.escapeLast(t,e,r-1):`${t.slice(0,r)}\\${t.slice(r)}`};J.removePrefix=(t,e={})=>{let n=t;return n.startsWith("./")&&(n=n.slice(2),e.prefix="./"),n};J.wrapOutput=(t,e={},n={})=>{let r=n.contains?"":"^",i=n.contains?"":"$",s=`${r}(?:${t})${i}`;return e.negated===true&&(s=`(?:^(?!${s}).*$)`),s};J.basename=(t,{windows:e}={})=>{let n=t.split(e?/[\\/]/:"/"),r=n[n.length-1];return r===""?n[n.length-2]:r};});var qr=xe((bp,Hr)=>{var Ir=Ke(),{CHAR_ASTERISK:yn,CHAR_AT:pa,CHAR_BACKWARD_SLASH:ze,CHAR_COMMA:ma,CHAR_DOT:bn,CHAR_EXCLAMATION_MARK:wn,CHAR_FORWARD_SLASH:Mr,CHAR_LEFT_CURLY_BRACE:xn,CHAR_LEFT_PARENTHESES:Sn,CHAR_LEFT_SQUARE_BRACKET:da,CHAR_PLUS:ha,CHAR_QUESTION_MARK:Dr,CHAR_RIGHT_CURLY_BRACE:ga,CHAR_RIGHT_PARENTHESES:jr,CHAR_RIGHT_SQUARE_BRACKET:ya}=We(),Ur=t=>t===Mr||t===ze,Br=t=>{t.isPrefix!==true&&(t.depth=t.isGlobstar?1/0:1);},ba=(t,e)=>{let n=e||{},r=t.length-1,i=n.parts===true||n.scanToEnd===true,s=[],o=[],a=[],l=t,c=-1,u=0,f=0,m=false,g=false,y=false,E=false,T=false,q=false,S=false,M=false,K=false,O=false,$=0,v,A,C={value:"",depth:0,isGlob:false},d=()=>c>=r,z=()=>l.charCodeAt(c+1),x=()=>(v=A,l.charCodeAt(++c));for(;c<r;){A=x();let P;if(A===ze){S=C.backslashes=true,A=x(),A===xn&&(q=true);continue}if(q===true||A===xn){for($++;d()!==true&&(A=x());){if(A===ze){S=C.backslashes=true,x();continue}if(A===xn){$++;continue}if(q!==true&&A===bn&&(A=x())===bn){if(m=C.isBrace=true,y=C.isGlob=true,O=true,i===true)continue;break}if(q!==true&&A===ma){if(m=C.isBrace=true,y=C.isGlob=true,O=true,i===true)continue;break}if(A===ga&&($--,$===0)){q=false,m=C.isBrace=true,O=true;break}}if(i===true)continue;break}if(A===Mr){if(s.push(c),o.push(C),C={value:"",depth:0,isGlob:false},O===true)continue;if(v===bn&&c===u+1){u+=2;continue}f=c+1;continue}if(n.noext!==true&&(A===ha||A===pa||A===yn||A===Dr||A===wn)===true&&z()===Sn){if(y=C.isGlob=true,E=C.isExtglob=true,O=true,A===wn&&c===u&&(K=true),i===true){for(;d()!==true&&(A=x());){if(A===ze){S=C.backslashes=true,A=x();continue}if(A===jr){y=C.isGlob=true,O=true;break}}continue}break}if(A===yn){if(v===yn&&(T=C.isGlobstar=true),y=C.isGlob=true,O=true,i===true)continue;break}if(A===Dr){if(y=C.isGlob=true,O=true,i===true)continue;break}if(A===da){for(;d()!==true&&(P=x());){if(P===ze){S=C.backslashes=true,x();continue}if(P===ya){g=C.isBracket=true,y=C.isGlob=true,O=true;break}}if(i===true)continue;break}if(n.nonegate!==true&&A===wn&&c===u){M=C.negated=true,u++;continue}if(n.noparen!==true&&A===Sn){if(y=C.isGlob=true,i===true){for(;d()!==true&&(A=x());){if(A===Sn){S=C.backslashes=true,A=x();continue}if(A===jr){O=true;break}}continue}break}if(y===true){if(O=true,i===true)continue;break}}n.noext===true&&(E=false,y=false);let L=l,h="",p="";u>0&&(h=l.slice(0,u),l=l.slice(u),f-=u),L&&y===true&&f>0?(L=l.slice(0,f),p=l.slice(f)):y===true?(L="",p=l):L=l,L&&L!==""&&L!=="/"&&L!==l&&Ur(L.charCodeAt(L.length-1))&&(L=L.slice(0,-1)),n.unescape===true&&(p&&(p=Ir.removeBackslashes(p)),L&&S===true&&(L=Ir.removeBackslashes(L)));let Z={prefix:h,input:t,start:u,base:L,glob:p,isBrace:m,isBracket:g,isGlob:y,isExtglob:E,isGlobstar:T,negated:M,negatedExtglob:K};if(n.tokens===true&&(Z.maxDepth=0,Ur(A)||o.push(C),Z.tokens=o),n.parts===true||n.tokens===true){let P;for(let U=0;U<s.length;U++){let ue=P?P+1:u,ee=s[U],he=t.slice(ue,ee);n.tokens&&(U===0&&u!==0?(o[U].isPrefix=true,o[U].value=h):o[U].value=he,Br(o[U]),Z.maxDepth+=o[U].depth),(U!==0||he!=="")&&a.push(he),P=ee;}if(P&&P+1<t.length){let U=t.slice(P+1);a.push(U),n.tokens&&(o[o.length-1].value=U,Br(o[o.length-1]),Z.maxDepth+=o[o.length-1].depth);}Z.slashes=s,Z.parts=a;}return Z};Hr.exports=ba;});var zr=xe((wp,Kr)=>{var Xe=We(),Q=Ke(),{MAX_LENGTH:Bt,POSIX_REGEX_SOURCE:wa,REGEX_NON_SPECIAL_CHARS:xa,REGEX_SPECIAL_CHARS_BACKREF:Sa,REPLACEMENTS:Vr}=Xe,Ea=(t,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...t,e);t.sort();let n=`[${t.join("-")}]`;try{new RegExp(n);}catch{return t.map(i=>Q.escapeRegex(i)).join("..")}return n},ve=(t,e)=>`Missing ${t}: "${e}" - use "\\\\${e}" to match literal characters`,Gr=t=>{let e=[],n=0,r=0,i=0,s="",o=false;for(let a of t){if(o===true){s+=a,o=false;continue}if(a==="\\"){s+=a,o=true;continue}if(a==='"'){i=i===1?0:1,s+=a;continue}if(i===0){if(a==="[")n++;else if(a==="]"&&n>0)n--;else if(n===0){if(a==="(")r++;else if(a===")"&&r>0)r--;else if(a==="|"&&r===0){e.push(s),s="";continue}}}s+=a;}return e.push(s),e},Ta=t=>{let e=false;for(let n of t){if(e===true){e=false;continue}if(n==="\\"){e=true;continue}if(/[?*+@!()[\]{}]/.test(n))return false}return true},Wr=t=>{let e=t.trim(),n=true;for(;n===true;)n=false,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),n=true);if(Ta(e))return e.replace(/\\(.)/g,"$1")},Aa=t=>{let e=t.map(Wr).filter(Boolean);for(let n=0;n<e.length;n++)for(let r=n+1;r<e.length;r++){let i=e[n],s=e[r],o=i[0];if(!(!o||i!==o.repeat(i.length)||s!==o.repeat(s.length))&&(i===s||i.startsWith(s)||s.startsWith(i)))return true}return false},En=(t,e=true)=>{if(t[0]!=="+"&&t[0]!=="*"||t[1]!=="(")return;let n=0,r=0,i=0,s=false;for(let o=1;o<t.length;o++){let a=t[o];if(s===true){s=false;continue}if(a==="\\"){s=true;continue}if(a==='"'){i=i===1?0:1;continue}if(i!==1){if(a==="["){n++;continue}if(a==="]"&&n>0){n--;continue}if(!(n>0)){if(a==="("){r++;continue}if(a===")"&&(r--,r===0))return e===true&&o!==t.length-1?void 0:{type:t[0],body:t.slice(2,o),end:o}}}}},_a=t=>{let e=0,n=[];for(;e<t.length;){let i=En(t.slice(e),false);if(!i||i.type!=="*")return;let s=Gr(i.body).map(a=>a.trim());if(s.length!==1)return;let o=Wr(s[0]);if(!o||o.length!==1)return;n.push(o),e+=i.end+1;}return n.length<1?void 0:`${n.length===1?Q.escapeRegex(n[0]):`[${n.map(i=>Q.escapeRegex(i)).join("")}]`}*`},Ca=t=>{let e=0,n=t.trim(),r=En(n);for(;r;)e++,n=r.body.trim(),r=En(n);return e},Ra=(t,e)=>{if(e.maxExtglobRecursion===false)return {risky:false};let n=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:Xe.DEFAULT_MAX_EXTGLOB_RECURSION,r=Gr(t).map(i=>i.trim());if(r.length>1&&(r.some(i=>i==="")||r.some(i=>/^[*?]+$/.test(i))||Aa(r)))return {risky:true};for(let i of r){let s=_a(i);if(s)return {risky:true,safeOutput:s};if(Ca(i)>n)return {risky:true}}return {risky:false}},Tn=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");t=Vr[t]||t;let n={...e},r=typeof n.maxLength=="number"?Math.min(Bt,n.maxLength):Bt,i=t.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=Xe.globChars(n.windows),c=Xe.extglobChars(l),{DOT_LITERAL:u,PLUS_LITERAL:f,SLASH_LITERAL:m,ONE_CHAR:g,DOTS_SLASH:y,NO_DOT:E,NO_DOT_SLASH:T,NO_DOTS_SLASH:q,QMARK:S,QMARK_NO_DOT:M,STAR:K,START_ANCHOR:O}=l,$=w=>`(${a}(?:(?!${O}${w.dot?y:u}).)*?)`,v=n.dot?"":E,A=n.dot?S:M,C=n.bash===true?$(n):K;n.capture&&(C=`(${C})`),typeof n.noext=="boolean"&&(n.noextglob=n.noext);let d={input:t,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};t=Q.removePrefix(t,d),i=t.length;let z=[],x=[],L=[],h=s,p,Z=()=>d.index===i-1,P=d.peek=(w=1)=>t[d.index+w],U=d.advance=()=>t[++d.index]||"",ue=()=>t.slice(d.index+1),ee=(w="",j=0)=>{d.consumed+=w,d.index+=j;},he=w=>{d.output+=w.output!=null?w.output:w.value,ee(w.value);},Qi=()=>{let w=1;for(;P()==="!"&&(P(2)!=="("||P(3)==="?");)U(),d.start++,w++;return w%2===0?false:(d.negated=true,d.start++,true)},wt=w=>{d[w]++,L.push(w);},ge=w=>{d[w]--,L.pop();},R=w=>{if(h.type==="globstar"){let j=d.braces>0&&(w.type==="comma"||w.type==="brace"),b=w.extglob===true||z.length&&(w.type==="pipe"||w.type==="paren");w.type!=="slash"&&w.type!=="paren"&&!j&&!b&&(d.output=d.output.slice(0,-h.output.length),h.type="star",h.value="*",h.output=C,d.output+=h.output);}if(z.length&&w.type!=="paren"&&(z[z.length-1].inner+=w.value),(w.value||w.output)&&he(w),h&&h.type==="text"&&w.type==="text"){h.output=(h.output||h.value)+w.value,h.value+=w.value;return}w.prev=h,o.push(w),h=w;},xt=(w,j)=>{let b={...c[j],conditions:1,inner:""};b.prev=h,b.parens=d.parens,b.output=d.output,b.startIndex=d.index,b.tokensIndex=o.length;let k=(n.capture?"(":"")+b.open;wt("parens"),R({type:w,value:j,output:d.output?"":g}),R({type:"paren",extglob:true,value:U(),output:k}),z.push(b);},Zi=w=>{let j=t.slice(w.startIndex,d.index+1),b=t.slice(w.startIndex+2,d.index),k=Ra(b,n);if((w.type==="plus"||w.type==="star")&&k.risky){let I=k.safeOutput?(w.output?"":g)+(n.capture?`(${k.safeOutput})`:k.safeOutput):void 0,ae=o[w.tokensIndex];ae.type="text",ae.value=j,ae.output=I||Q.escapeRegex(j);for(let le=w.tokensIndex+1;le<o.length;le++)o[le].value="",o[le].output="",delete o[le].suffix;d.output=w.output+ae.output,d.backtrack=true,R({type:"paren",extglob:true,value:p,output:""}),ge("parens");return}let D=w.close+(n.capture?")":""),G;if(w.type==="negate"){let I=C;if(w.inner&&w.inner.length>1&&w.inner.includes("/")&&(I=$(n)),(I!==C||Z()||/^\)+$/.test(ue()))&&(D=w.close=`)$))${I}`),w.inner.includes("*")&&(G=ue())&&/^\.[^\\/.]+$/.test(G)){let ae=Tn(G,{...e,fastpaths:false}).output;D=w.close=`)${ae})${I})`;}w.prev.type==="bos"&&(d.negatedExtglob=true);}R({type:"paren",extglob:true,value:p,output:D}),ge("parens");};if(n.fastpaths!==false&&!/(^[*!]|[/()[\]{}"])/.test(t)){let w=false,j=t.replace(Sa,(b,k,D,G,I,ae)=>G==="\\"?(w=true,b):G==="?"?k?k+G+(I?S.repeat(I.length):""):ae===0?A+(I?S.repeat(I.length):""):S.repeat(D.length):G==="."?u.repeat(D.length):G==="*"?k?k+G+(I?C:""):C:k?b:`\\${b}`);return w===true&&(n.unescape===true?j=j.replace(/\\/g,""):j=j.replace(/\\+/g,b=>b.length%2===0?"\\\\":b?"\\":"")),j===t&&n.contains===true?(d.output=t,d):(d.output=Q.wrapOutput(j,d,e),d)}for(;!Z();){if(p=U(),p==="\0")continue;if(p==="\\"){let b=P();if(b==="/"&&n.bash!==true||b==="."||b===";")continue;if(!b){p+="\\",R({type:"text",value:p});continue}let k=/^\\+/.exec(ue()),D=0;if(k&&k[0].length>2&&(D=k[0].length,d.index+=D,D%2!==0&&(p+="\\")),n.unescape===true?p=U():p+=U(),d.brackets===0){R({type:"text",value:p});continue}}if(d.brackets>0&&(p!=="]"||h.value==="["||h.value==="[^")){if(n.posix!==false&&p===":"){let b=h.value.slice(1);if(b.includes("[")&&(h.posix=true,b.includes(":"))){let k=h.value.lastIndexOf("["),D=h.value.slice(0,k),G=h.value.slice(k+2),I=wa[G];if(I){h.value=D+I,d.backtrack=true,U(),!s.output&&o.indexOf(h)===1&&(s.output=g);continue}}}(p==="["&&P()!==":"||p==="-"&&P()==="]")&&(p=`\\${p}`),p==="]"&&(h.value==="["||h.value==="[^")&&(p=`\\${p}`),n.posix===true&&p==="!"&&h.value==="["&&(p="^"),h.value+=p,he({value:p});continue}if(d.quotes===1&&p!=='"'){p=Q.escapeRegex(p),h.value+=p,he({value:p});continue}if(p==='"'){d.quotes=d.quotes===1?0:1,n.keepQuotes===true&&R({type:"text",value:p});continue}if(p==="("){wt("parens"),R({type:"paren",value:p});continue}if(p===")"){if(d.parens===0&&n.strictBrackets===true)throw new SyntaxError(ve("opening","("));let b=z[z.length-1];if(b&&d.parens===b.parens+1){Zi(z.pop());continue}R({type:"paren",value:p,output:d.parens?")":"\\)"}),ge("parens");continue}if(p==="["){if(n.nobracket===true||!ue().includes("]")){if(n.nobracket!==true&&n.strictBrackets===true)throw new SyntaxError(ve("closing","]"));p=`\\${p}`;}else wt("brackets");R({type:"bracket",value:p});continue}if(p==="]"){if(n.nobracket===true||h&&h.type==="bracket"&&h.value.length===1){R({type:"text",value:p,output:`\\${p}`});continue}if(d.brackets===0){if(n.strictBrackets===true)throw new SyntaxError(ve("opening","["));R({type:"text",value:p,output:`\\${p}`});continue}ge("brackets");let b=h.value.slice(1);if(h.posix!==true&&b[0]==="^"&&!b.includes("/")&&(p=`/${p}`),h.value+=p,he({value:p}),n.literalBrackets===false||Q.hasRegexChars(b))continue;let k=Q.escapeRegex(h.value);if(d.output=d.output.slice(0,-h.value.length),n.literalBrackets===true){d.output+=k,h.value=k;continue}h.value=`(${a}${k}|${h.value})`,d.output+=h.value;continue}if(p==="{"&&n.nobrace!==true){wt("braces");let b={type:"brace",value:p,output:"(",outputIndex:d.output.length,tokensIndex:d.tokens.length};x.push(b),R(b);continue}if(p==="}"){let b=x[x.length-1];if(n.nobrace===true||!b){R({type:"text",value:p,output:p});continue}let k=")";if(b.dots===true){let D=o.slice(),G=[];for(let I=D.length-1;I>=0&&(o.pop(),D[I].type!=="brace");I--)D[I].type!=="dots"&&G.unshift(D[I].value);k=Ea(G,n),d.backtrack=true;}if(b.comma!==true&&b.dots!==true){let D=d.output.slice(0,b.outputIndex),G=d.tokens.slice(b.tokensIndex);b.value=b.output="\\{",p=k="\\}",d.output=D;for(let I of G)d.output+=I.output||I.value;}R({type:"brace",value:p,output:k}),ge("braces"),x.pop();continue}if(p==="|"){z.length>0&&z[z.length-1].conditions++,R({type:"text",value:p});continue}if(p===","){let b=p,k=x[x.length-1];k&&L[L.length-1]==="braces"&&(k.comma=true,b="|"),R({type:"comma",value:p,output:b});continue}if(p==="/"){if(h.type==="dot"&&d.index===d.start+1){d.start=d.index+1,d.consumed="",d.output="",o.pop(),h=s;continue}R({type:"slash",value:p,output:m});continue}if(p==="."){if(d.braces>0&&h.type==="dot"){h.value==="."&&(h.output=u);let b=x[x.length-1];h.type="dots",h.output+=p,h.value+=p,b.dots=true;continue}if(d.braces+d.parens===0&&h.type!=="bos"&&h.type!=="slash"){R({type:"text",value:p,output:u});continue}R({type:"dot",value:p,output:u});continue}if(p==="?"){if(!(h&&h.value==="(")&&n.noextglob!==true&&P()==="("&&P(2)!=="?"){xt("qmark",p);continue}if(h&&h.type==="paren"){let k=P(),D=p;(h.value==="("&&!/[!=<:]/.test(k)||k==="<"&&!/<([!=]|\w+>)/.test(ue()))&&(D=`\\${p}`),R({type:"text",value:p,output:D});continue}if(n.dot!==true&&(h.type==="slash"||h.type==="bos")){R({type:"qmark",value:p,output:M});continue}R({type:"qmark",value:p,output:S});continue}if(p==="!"){if(n.noextglob!==true&&P()==="("&&(P(2)!=="?"||!/[!=<:]/.test(P(3)))){xt("negate",p);continue}if(n.nonegate!==true&&d.index===0){Qi();continue}}if(p==="+"){if(n.noextglob!==true&&P()==="("&&P(2)!=="?"){xt("plus",p);continue}if(h&&h.value==="("||n.regex===false){R({type:"plus",value:p,output:f});continue}if(h&&(h.type==="bracket"||h.type==="paren"||h.type==="brace")||d.parens>0){R({type:"plus",value:p});continue}R({type:"plus",value:f});continue}if(p==="@"){if(n.noextglob!==true&&P()==="("&&P(2)!=="?"){R({type:"at",extglob:true,value:p,output:""});continue}R({type:"text",value:p});continue}if(p!=="*"){(p==="$"||p==="^")&&(p=`\\${p}`);let b=xa.exec(ue());b&&(p+=b[0],d.index+=b[0].length),R({type:"text",value:p});continue}if(h&&(h.type==="globstar"||h.star===true)){h.type="star",h.star=true,h.value+=p,h.output=C,d.backtrack=true,d.globstar=true,ee(p);continue}let w=ue();if(n.noextglob!==true&&/^\([^?]/.test(w)){xt("star",p);continue}if(h.type==="star"){if(n.noglobstar===true){ee(p);continue}let b=h.prev,k=b.prev,D=b.type==="slash"||b.type==="bos",G=k&&(k.type==="star"||k.type==="globstar");if(n.bash===true&&(!D||w[0]&&w[0]!=="/")){R({type:"star",value:p,output:""});continue}let I=d.braces>0&&(b.type==="comma"||b.type==="brace"),ae=z.length&&(b.type==="pipe"||b.type==="paren");if(!D&&b.type!=="paren"&&!I&&!ae){R({type:"star",value:p,output:""});continue}for(;w.slice(0,3)==="/**";){let le=t[d.index+4];if(le&&le!=="/")break;w=w.slice(3),ee("/**",3);}if(b.type==="bos"&&Z()){h.type="globstar",h.value+=p,h.output=$(n),d.output=h.output,d.globstar=true,ee(p);continue}if(b.type==="slash"&&b.prev.type!=="bos"&&!G&&Z()){d.output=d.output.slice(0,-(b.output+h.output).length),b.output=`(?:${b.output}`,h.type="globstar",h.output=$(n)+(n.strictSlashes?")":"|$)"),h.value+=p,d.globstar=true,d.output+=b.output+h.output,ee(p);continue}if(b.type==="slash"&&b.prev.type!=="bos"&&w[0]==="/"){let le=w[1]!==void 0?"|$":"";d.output=d.output.slice(0,-(b.output+h.output).length),b.output=`(?:${b.output}`,h.type="globstar",h.output=`${$(n)}${m}|${m}${le})`,h.value+=p,d.output+=b.output+h.output,d.globstar=true,ee(p+U()),R({type:"slash",value:"/",output:""});continue}if(b.type==="bos"&&w[0]==="/"){h.type="globstar",h.value+=p,h.output=`(?:^|${m}|${$(n)}${m})`,d.output=h.output,d.globstar=true,ee(p+U()),R({type:"slash",value:"/",output:""});continue}d.output=d.output.slice(0,-h.output.length),h.type="globstar",h.output=$(n),h.value+=p,d.output+=h.output,d.globstar=true,ee(p);continue}let j={type:"star",value:p,output:C};if(n.bash===true){j.output=".*?",(h.type==="bos"||h.type==="slash")&&(j.output=v+j.output),R(j);continue}if(h&&(h.type==="bracket"||h.type==="paren")&&n.regex===true){j.output=p,R(j);continue}(d.index===d.start||h.type==="slash"||h.type==="dot")&&(h.type==="dot"?(d.output+=T,h.output+=T):n.dot===true?(d.output+=q,h.output+=q):(d.output+=v,h.output+=v),P()!=="*"&&(d.output+=g,h.output+=g)),R(j);}for(;d.brackets>0;){if(n.strictBrackets===true)throw new SyntaxError(ve("closing","]"));d.output=Q.escapeLast(d.output,"["),ge("brackets");}for(;d.parens>0;){if(n.strictBrackets===true)throw new SyntaxError(ve("closing",")"));d.output=Q.escapeLast(d.output,"("),ge("parens");}for(;d.braces>0;){if(n.strictBrackets===true)throw new SyntaxError(ve("closing","}"));d.output=Q.escapeLast(d.output,"{"),ge("braces");}if(n.strictSlashes!==true&&(h.type==="star"||h.type==="bracket")&&R({type:"maybe_slash",value:"",output:`${m}?`}),d.backtrack===true){d.output="";for(let w of d.tokens)d.output+=w.output!=null?w.output:w.value,w.suffix&&(d.output+=w.suffix);}return d};Tn.fastpaths=(t,e)=>{let n={...e},r=typeof n.maxLength=="number"?Math.min(Bt,n.maxLength):Bt,i=t.length;if(i>r)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${r}`);t=Vr[t]||t;let{DOT_LITERAL:s,SLASH_LITERAL:o,ONE_CHAR:a,DOTS_SLASH:l,NO_DOT:c,NO_DOTS:u,NO_DOTS_SLASH:f,STAR:m,START_ANCHOR:g}=Xe.globChars(n.windows),y=n.dot?u:c,E=n.dot?f:c,T=n.capture?"":"?:",q={negated:false,prefix:""},S=n.bash===true?".*?":m;n.capture&&(S=`(${S})`);let M=v=>v.noglobstar===true?S:`(${T}(?:(?!${g}${v.dot?l:s}).)*?)`,K=v=>{switch(v){case "*":return `${y}${a}${S}`;case ".*":return `${s}${a}${S}`;case "*.*":return `${y}${S}${s}${a}${S}`;case "*/*":return `${y}${S}${o}${a}${E}${S}`;case "**":return y+M(n);case "**/*":return `(?:${y}${M(n)}${o})?${E}${a}${S}`;case "**/*.*":return `(?:${y}${M(n)}${o})?${E}${S}${s}${a}${S}`;case "**/.*":return `(?:${y}${M(n)}${o})?${s}${a}${S}`;default:{let A=/^(.*?)\.(\w+)$/.exec(v);if(!A)return;let C=K(A[1]);return C?C+s+A[2]:void 0}}},O=Q.removePrefix(t,q),$=K(O);return $&&n.strictSlashes!==true&&($+=`${o}?`),$};Kr.exports=Tn;});var Yr=xe((xp,Jr)=>{var ka=qr(),An=zr(),Xr=Ke(),$a=We(),va=t=>t&&typeof t=="object"&&!Array.isArray(t),H=(t,e,n=false)=>{if(Array.isArray(t)){let u=t.map(m=>H(m,e,n));return m=>{for(let g of u){let y=g(m);if(y)return y}return false}}let r=va(t)&&t.tokens&&t.input;if(t===""||typeof t!="string"&&!r)throw new TypeError("Expected pattern to be a non-empty string");let i=e||{},s=i.windows,o=r?H.compileRe(t,e):H.makeRe(t,e,false,true),a=o.state;delete o.state;let l=()=>false;if(i.ignore){let u={...e,ignore:null,onMatch:null,onResult:null};l=H(i.ignore,u,n);}let c=(u,f=false)=>{let{isMatch:m,match:g,output:y}=H.test(u,o,e,{glob:t,posix:s}),E={glob:t,state:a,regex:o,posix:s,input:u,output:y,match:g,isMatch:m};return typeof i.onResult=="function"&&i.onResult(E),m===false?(E.isMatch=false,f?E:false):l(u)?(typeof i.onIgnore=="function"&&i.onIgnore(E),E.isMatch=false,f?E:false):(typeof i.onMatch=="function"&&i.onMatch(E),f?E:true)};return n&&(c.state=a),c};H.test=(t,e,n,{glob:r,posix:i}={})=>{if(typeof t!="string")throw new TypeError("Expected input to be a string");if(t==="")return {isMatch:false,output:""};let s=n||{},o=s.format||(i?Xr.toPosixSlashes:null),a=t===r,l=a&&o?o(t):t;return a===false&&(l=o?o(t):t,a=l===r),(a===false||s.capture===true)&&(s.matchBase===true||s.basename===true?a=H.matchBase(t,e,n,i):a=e.exec(l)),{isMatch:!!a,match:a,output:l}};H.matchBase=(t,e,n)=>(e instanceof RegExp?e:H.makeRe(e,n)).test(Xr.basename(t));H.isMatch=(t,e,n)=>H(e,n)(t);H.parse=(t,e)=>Array.isArray(t)?t.map(n=>H.parse(n,e)):An(t,{...e,fastpaths:false});H.scan=(t,e)=>ka(t,e);H.compileRe=(t,e,n=false,r=false)=>{if(n===true)return t.output;let i=e||{},s=i.contains?"":"^",o=i.contains?"":"$",a=`${s}(?:${t.output})${o}`;t&&t.negated===true&&(a=`^(?!${a}).*$`);let l=H.toRegex(a,e);return r===true&&(l.state=t),l};H.makeRe=(t,e={},n=false,r=false)=>{if(!t||typeof t!="string")throw new TypeError("Expected a non-empty string");let i={negated:false,fastpaths:true};return e.fastpaths!==false&&(t[0]==="."||t[0]==="*")&&(i.output=An.fastpaths(t,e)),i.output||(i=An(t,e)),H.compileRe(i,e,n,r)};H.toRegex=(t,e)=>{try{let n=e||{};return new RegExp(t,n.flags||(n.nocase?"i":""))}catch(n){if(e&&e.debug===true)throw n;return /$^/}};H.constants=$a;Jr.exports=H;});var ti=xe((Sp,ei)=>{var Qr=Yr(),Na=Ke();function Zr(t,e,n=false){return e&&(e.windows===null||e.windows===void 0)&&(e={...e,windows:Na.isWindows()}),Qr(t,e,n)}Object.assign(Zr,Qr);ei.exports=Zr;});function tt(t){if("String"in t)return t.String.sval}function me(t){return t.map(tt).filter(e=>e!=null)}function Si(t){return Object.keys(t)[0]}function Ei(t){if("A_Const"in t){if(t.A_Const.ival)return t.A_Const.ival.ival;if(t.A_Const.fval)return t.A_Const.fval.fval;if(t.A_Const.sval)return t.A_Const.sval.sval;if(t.A_Const.boolval)return t.A_Const.boolval.boolval;if(t.A_Const.isnull)return null}}var Ht=F(()=>{});function Ti(t){let e=t.toLowerCase();return ["serial","serial4","bigserial","serial8","smallserial","serial2"].includes(e)}function Ai(t){let e=t.toLowerCase();return ["varchar","character varying","char","character","bpchar"].includes(e)}function _i(t){let e=t.toLowerCase();return ["numeric","decimal"].includes(e)}var Nn,qt,Rl,Ln=F(()=>{Ht();Nn=class extends Error{},qt=class extends Nn{constructor(n,r){super(r??`Unsupported node type: ${Si(n)}`);this.node=n;}};Rl={CreateEnumStmt:{react:"ignore"},CreateDomainStmt:{react:"warn"},CreateSeqStmt:{react:"ignore"},AlterSeqStmt:{react:"ignore"},CreateSchemaStmt:{react:"warn"},CreatePolicyStmt:{react:"ignore"},AlterPolicyStmt:{react:"ignore"},PartitionElem:{react:"error"},PartitionCmd:{react:"error"},VariableSetStmt:{react:"ignore"},CompositeTypeStmt:{react:"error"},AlterEnumStmt:{react:"error"},AlterObjectSchemaStmt:{react:"error"},AlterOwnerStmt:{react:"error"},AlterTypeStmt:{react:"error"},AlterFunctionStmt:{react:"error"},AlterDefaultPrivilegesStmt:{react:"error"},GrantStmt:{react:"error"},GrantRoleStmt:{react:"error"},CopyStmt:{react:"error"},CreateCastStmt:{react:"error"},AlterOpFamilyStmt:{react:"error"},AlterOperatorStmt:{react:"error"},TruncateStmt:{react:"error"},A_Indirection:{react:"error"},XmlExpr:{react:"error"},XmlSerialize:{react:"error"},RangeTableSample:{react:"error"},GroupingSet:{react:"error"}},new Map(Object.entries(Rl));});var ne,Vt,Ci=F(()=>{Ht();Ln();ne=class extends qt{constructor(e,n){super(e,`Unsupported expression: ${n}`);}},Vt=class{deparse(e){if("A_Const"in e){let i=e.A_Const;if(i.boolval!==void 0)return i.boolval.boolval?{}:{$always:false}}let n=Object.keys(e)[0],r=this[n];if(!r)throw new ne({[n]:e},`Unsupported expression: ${n}`);return r.call(this,e[n])}deparseValue(e){if("A_Const"in e)return this.A_Const(e.A_Const);if("ColumnRef"in e)return this.ColumnRef(e.ColumnRef);if("FuncCall"in e)return this.FuncCall(e.FuncCall);if("SubLink"in e)return this.SubLink(e.SubLink);if("TypeCast"in e)return this.TypeCast(e.TypeCast);if("A_Expr"in e){let r=this.isJwtAccessor(e.A_Expr);return r||this.A_Expr(e.A_Expr)}if("BoolExpr"in e)return this.BoolExpr(e.BoolExpr);let n=Object.keys(e)[0];throw new ne({[n]:e},`deparseValue: ${n}`)}A_Expr(e){if(e.kind==="AEXPR_OP"){let n=e.name?.[0],r=n?tt(n):void 0;if(!r)throw new ne({A_Expr:e},"A_Expr missing operator");let i=this.isJwtAccessor(e);if(i)return {[i]:{}};let s=e.lexpr?this.deparseValue(e.lexpr):void 0,o=e.rexpr?this.deparseValue(e.rexpr):void 0,a=this.mapOperator(r);if(!a)throw new ne({A_Expr:e},`Unsupported operator: ${r}`);let l=e.rexpr!=null&&"ColumnRef"in e.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(e.kind==="AEXPR_LIKE"||e.kind==="AEXPR_ILIKE"){let n=e.lexpr?this.deparseValue(e.lexpr):void 0,r=e.rexpr?this.deparseValue(e.rexpr):void 0,s=(e.name?.[0]?tt(e.name[0]):"~~")==="!~~"?"$notLike":"$like";return {[n]:{[s]:r}}}if(e.kind==="AEXPR_IN"){let n=e.lexpr?this.deparseValue(e.lexpr):void 0,r=e.rexpr&&"List"in e.rexpr&&e.rexpr.List.items?e.rexpr.List.items.map(i=>this.deparseValue(i)):[];return {[n]:{$in:r}}}throw new ne({A_Expr:e},`A_Expr kind: ${e.kind}`)}BoolExpr(e){let n=e.args??[];switch(e.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 ne({BoolExpr:e},`BoolExpr op: ${e.boolop}`)}}NullTest(e){let n=e.arg?this.deparseValue(e.arg):void 0;return e.nulltesttype==="IS_NULL"?{[n]:{$is:null}}:{[n]:{$isNot:null}}}SubLink(e){if(e.subLinkType==="ANY_SUBLINK"){let n=e.testexpr?this.deparseValue(e.testexpr):void 0,r=e.subselect?this.SelectStmt(e.subselect.SelectStmt):void 0;return {[n]:{$in:r}}}if(e.subLinkType==="EXISTS_SUBLINK")return {$exists:e.subselect?this.SelectStmt(e.subselect.SelectStmt):void 0};if(e.subLinkType==="EXPR_SUBLINK"){let n=e.subselect?e.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 ne({SubLink:e},`SubLink type: ${e.subLinkType}`)}SelectStmt(e){let{from:n,schema:r,join:i}=this.deparseFromClause(e.fromClause??[]),s=[];for(let m of e.targetList??[]){let g="ResTarget"in m?m.ResTarget:void 0;if(g?.val){let y=this.deparseValue(g.val);Array.isArray(y)?s.push(...y.map(String)):y!=null&&y!==""&&s.push(String(y));}}let o=e.whereClause?this.deparse(e.whereClause):void 0,a=this.deparseSortClause(e.sortClause),l=this.deparseLimit(e.limitCount),c=this.deparseLimit(e.limitOffset),u=this.deparseGroupClause(e.groupClause),f={type:"query",from:n,select:s};return r&&(f.schema=r),Object.keys(i).length>0&&(f.join=i),o&&(f.where=o),a.length>0&&(f.order=a),l!==void 0&&(f.limit=l),c!==void 0&&(f.offset=c),u.length>0&&(f.group=u),f}FuncCall(e){let n=this.isAuthFunc(e.funcname??[]);if(n)return n;throw new ne({FuncCall:e},`FuncCall: ${me(e.funcname??[]).join(".")}`)}ColumnRef(e){let n=me(e.fields??[]);return n.length===1?n[0]:n.join(".")}A_Const(e){if(e.boolval!==void 0)return e.boolval.boolval;if(e.ival!==void 0)return e.ival.ival??0;if(e.fval!==void 0)return parseFloat(e.fval.fval??"0");if(e.sval!==void 0)return e.sval.sval??"";if(e.isnull)return null;throw new ne({A_Const:e},"A_Const: unknown variant")}TypeCast(e){if(!e.arg)throw new ne({TypeCast:e},"TypeCast: missing arg");return this.deparseValue(e.arg)}BooleanTest(e){let n=e.arg?this.deparseValue(e.arg):void 0;return e.booltesttype==="IS_TRUE"?{[n]:{$eq:true}}:{[n]:{$eq:false}}}deparseFromClause(e){let n={};if(e.length===0)return {from:"",join:n};let r=e[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(e,n){let r={from:""};if(e.larg)if("RangeVar"in e.larg){let i=e.larg.RangeVar;r={from:i.relname??"",schema:i.schemaname};}else "JoinExpr"in e.larg&&(r=this.walkJoinExpr(e.larg.JoinExpr,n));if(e.rarg&&"RangeVar"in e.rarg){let i=e.rarg.RangeVar,s=i.relname??"",o=i.alias?.aliasname??s,a=e.jointype==="JOIN_LEFT"?"left":"inner",l={from:s,type:a};e.quals&&(l.on=this.deparse(e.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(e){if(!e)return [];let n=[];for(let r of e){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(e){if(!e)return;let n=this.deparseValue(e);return typeof n=="number"?n:Number(n)}deparseGroupClause(e){return e?e.map(n=>String(this.deparseValue(n))):[]}isAuthFunc(e){let n=me(e);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(e){if(e.kind!=="AEXPR_OP")return null;let n=e.name?.[0]?tt(e.name[0]):void 0;if(n!=="->"&&n!=="->>")return null;let r=e.rexpr&&"A_Const"in e.rexpr?e.rexpr.A_Const.sval?.sval:void 0;if(r===void 0)return null;if(e.lexpr&&"FuncCall"in e.lexpr)return this.isAuthFunc(e.lexpr.FuncCall.funcname??[])==="{{auth.jwt}}"?`{{auth.jwt.${r}}}`:null;if(e.lexpr&&"A_Expr"in e.lexpr){let i=this.isJwtAccessor(e.lexpr.A_Expr);if(i)return `${i.slice(0,-2)}.${r}}}`}return null}mapOperator(e){switch(e){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 _e,Ri=F(()=>{_e=class t{constructor(e){this.data=e;}appliesTo(e){return this.data.command==="ALL"||this.data.command===e}appliesToRole(e){return this.data.roles.length===0||this.data.roles.includes(e)}toJSON(){return this.data}static fromJSON(e){return new t(e)}};});var nt,Pn=F(()=>{nt=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 W,de=F(()=>{Pn();W=class{context;factoryExtra;constructor(e){this.context=e;}get isShimBacked(){return false}checkConstraint(){return null}serialize(e){return e}deserialize(e){return e}validateStorage(e){return {status:"pass",message:null}}validationFail(e,n){return {status:"fail",message:e,action:n}}validationPass(){return {status:"pass",message:null}}isNullish(e){return e==null}toColumnDDL(e){let{includeNullable:n=true}=e??{},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(e,n){return new nt(this.context.table,this.context.column,e,n)}quoteIfNeeded(e){return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)?e:`"${e}"`}};});var Ce,Gt=F(()=>{de();Ce=class extends W{get sqliteType(){return "INTEGER"}};});var rt,On=F(()=>{Gt();rt=class extends Ce{constructor(e){super({...e,isSerial:true});}};});function kl(t,e){let{precision:n,scale:r}=e,i=10**r,s=10**(n-r);return Math.abs(Math.round(t*i)-t*i)<1e-4&&Math.abs(t)<s}var it,Fn=F(()=>{de();it=class extends W{numericPrecision;constructor(e,n){super(e),this.numericPrecision=n;}get isShimBacked(){return this.numericPrecision!==void 0}get sqliteType(){return "REAL"}checkConstraint(){if(this.numericPrecision){let{precision:e,scale:n}=this.numericPrecision,r=this.context.column,i=10**n,s=10**(e-n);return `ABS(ROUND(${r} * ${i}) - ${r} * ${i}) < 0.0001 AND ABS(${r}) < ${s}`}return null}validateStorage(e){if(this.isNullish(e))return this.validationPass();if(typeof e!="number"||!Number.isFinite(e))return this.validationFail("Expected finite number.","Patch rows with finite numbers.");if(this.numericPrecision){let{precision:n,scale:r}=this.numericPrecision;if(!kl(e,this.numericPrecision))return this.validationFail(`Does not fit numeric(${n}, ${r}).`,"Patch rows within numeric precision.")}return this.validationPass()}};});var B,se=F(()=>{de();B=class extends W{lengthConstraint;constructor(e,n){super(e),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(e){return this.isNullish(e)?this.validationPass():typeof e!="string"?this.validationFail("Expected text.","Patch rows with text values."):this.lengthConstraint!==void 0&&Array.from(e).length>this.lengthConstraint?this.validationFail(`Exceeds length ${this.lengthConstraint}.`,"Patch rows with shorter text."):this.validationPass()}};});var st,In=F(()=>{de();st=class extends W{get sqliteType(){return "BLOB"}};});var ot,Dn=F(()=>{de();ot=class extends W{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}checkConstraint(){return `${this.context.column} IN (0, 1)`}serialize(e){if(this.isNullish(e))return e;if(e===true||e===1)return 1;if(e===false||e===0)return 0;throw this.checkError("boolean_range",e)}deserialize(e){if(this.isNullish(e)||e===true||e===false)return e;if(typeof e=="number"&&Number.isFinite(e)){if(e===1)return true;if(e===0)return false}return e===1n?true:e===0n?false:e==="1"||e==="true"?true:e==="0"||e==="false"?false:e}validateStorage(e){return this.isNullish(e)?this.validationPass():e===1||e===0?this.validationPass():this.validationFail("Expected 0 or 1.","Patch rows with boolean values.")}};});function ki(t){try{return {ok:!0,value:JSON.parse(t)}}catch{return {ok:false}}}var at,jn=F(()=>{de();at=class extends W{get isShimBacked(){return true}get sqliteType(){return "TEXT"}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR json_valid(${e})`}serialize(e){if(this.isNullish(e))return e;try{return JSON.stringify(e)}catch{throw this.checkError("json_valid",e)}}deserialize(e){if(this.isNullish(e))return e;if(typeof e=="string"){let n=ki(e);return n.ok?n.value:e}return e}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"?this.validationFail("Expected JSON text.","Patch rows with JSON values."):ki(e).ok?this.validationPass():this.validationFail("Invalid JSON text.","Patch rows with valid JSON.")}};});function $l(t){if(!/^\d{4}-\d{2}-\d{2}$/.test(t))return false;let e=new Date(`${t}T00:00:00.000Z`);return !Number.isNaN(e.getTime())&&e.toISOString().slice(0,10)===t}var lt,Un=F(()=>{se();lt=class extends B{get isShimBacked(){return true}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR date(${e}) IS NOT NULL`}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!$l(e)?this.validationFail("Invalid date.","Patch rows with YYYY-MM-DD dates."):this.validationPass()}};});function vl(t){let e=t.match(/^(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?([+-](\d{2}):?(\d{2}))?$/);if(!e)return false;let n=Number(e[1]),r=Number(e[2]),i=e[3]===void 0?0:Number(e[3]),s=e[5]===void 0?null:Number(e[5]),o=e[6]===void 0?null:Number(e[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 ct,Bn=F(()=>{se();ct=class extends B{get isShimBacked(){return true}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR time(${e}) IS NOT NULL`}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!vl(e)?this.validationFail("Invalid time.","Patch rows with HH:MM[:SS] times."):this.validationPass()}};});function Nl(t){let e=t.match(/^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?(?:Z|([+-](\d{2}):?(\d{2})))?$/);if(!e)return false;let n=Number(e[1]),r=Number(e[2]),i=Number(e[3]),s=Number(e[4]),o=Number(e[5]),a=e[6]===void 0?0:Number(e[6]),l=e[8]===void 0?null:Number(e[8]),c=e[9]===void 0?null:Number(e[9]),u=new Date(Date.UTC(n,r-1,i)),f=u.getUTCFullYear()===n&&u.getUTCMonth()===r-1&&u.getUTCDate()===i,m=s<=24&&o<=59&&a<=59&&(s!==24||o===0&&a===0),g=l===null||c!==null&&l<=15&&c<=59;return f&&m&&g}var ut,Mn=F(()=>{se();ut=class extends B{get isShimBacked(){return true}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR datetime(${e}) IS NOT NULL`}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!Nl(e)?this.validationFail("Invalid timestamp.","Patch rows with ISO timestamps."):this.validationPass()}};});var ft,Hn=F(()=>{se();ft=class extends B{get isShimBacked(){return true}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||e.trim().length===0?this.validationFail("Expected interval text.","Patch rows with interval strings."):/^-?\d+(?:\.\d+)?$/.test(e.trim())?this.validationFail("Ambiguous numeric interval.","Patch rows with explicit interval strings."):this.validationPass()}};});var pt,qn=F(()=>{se();pt=class extends B{enumValues;constructor(e,n){super(e),this.enumValues=n;}get isShimBacked(){return true}checkConstraint(){let e=this.context.column,n=this.enumValues.map(r=>`'${r.replace(/'/g,"''")}'`).join(", ");return `${e} IN (${n})`}serialize(e){if(this.isNullish(e))return e;if(typeof e!="string"||!this.enumValues.includes(e))throw this.checkError("enum_membership",e);return e}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!this.enumValues.includes(e)?this.validationFail("Invalid enum value.","Patch rows with declared enum values."):this.validationPass()}};});function $i(t){try{return {ok:!0,value:JSON.parse(t)}}catch{return {ok:false}}}var Le,Vn=F(()=>{de();Le=class extends W{elementField;constructor(e,n){super(e),this.elementField=n;}get sqliteType(){return "TEXT"}get isShimBacked(){return true}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR (json_valid(${e}) AND json_type(${e}) = 'array')`}serialize(e){if(this.isNullish(e))return e;if(!Array.isArray(e))throw this.checkError("array_type",e);return this.elementField?JSON.stringify(e.map(n=>this.elementField.serialize(n))):JSON.stringify(e)}deserialize(e){if(this.isNullish(e))return e;if(typeof e=="string"){let n=$i(e);if(n.ok&&Array.isArray(n.value))return this.elementField?n.value.map(r=>this.elementField.deserialize(r)):n.value}return e}validateStorage(e){if(this.isNullish(e))return this.validationPass();if(typeof e!="string")return this.validationFail("Expected JSON array text.","Patch rows with array values.");let n=$i(e);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 vi(t){return Pl.test(t.toLowerCase())}var Ll,Pl,mt,Gn=F(()=>{se();Ll="????????-????-????-????-????????????",Pl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;mt=class extends B{get isShimBacked(){return true}checkConstraint(){let e=this.quoteIfNeeded(this.context.column);return `${e} IS NULL OR ${e} GLOB '${Ll}'`}serialize(e){if(this.isNullish(e))return e;if(typeof e!="string")throw this.checkError("uuid_format",e);let n=e.toLowerCase();if(!vi(n))throw this.checkError("uuid_format",e);return n}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!vi(e)?this.validationFail("Invalid UUID.","Patch rows with valid UUIDs."):this.validationPass()}};});function Ol(t){let e=t.split("/");if(e.length>2)return null;let n=e[0];if(!n)return null;if(e.length===1)return {address:n,prefix:null};let r=e[1];return !r||!/^\d+$/.test(r)?null:{address:n,prefix:Number(r)}}function Fl(t){let e=t.split(".");return e.length!==4?false:e.every(n=>{if(!/^\d+$/.test(n))return false;let r=Number(n);return r>=0&&r<=255})}function Il(t){if(!t.includes(":"))return false;try{return new URL(`http://[${t}]/`),!0}catch{return false}}function Ni(t){let e=Ol(t);return e?Fl(e.address)?e.prefix===null||e.prefix>=0&&e.prefix<=32:Il(e.address)?e.prefix===null||e.prefix>=0&&e.prefix<=128:false:false}var dt,Wn=F(()=>{se();dt=class extends B{get isShimBacked(){return true}checkConstraint(){let e=this.quoteIfNeeded(this.context.column);return `${e} IS NULL OR (length(${e}) BETWEEN 3 AND 49 AND (instr(${e}, '.') > 0 OR instr(${e}, ':') > 0))`}serialize(e){if(this.isNullish(e))return e;if(typeof e!="string")throw this.checkError("inet_format",e);let n=e.trim();if(!Ni(n))throw this.checkError("inet_format",e);return n}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!Ni(e.trim())?this.validationFail("Invalid inet address.","Patch rows with valid inet strings."):this.validationPass()}};});var ht,Kn=F(()=>{se();ht=class extends B{serialize(e){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}deserialize(e){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 gt(t,e){let n=Yl(t,e);if(e){let{enumValues:r,...i}=e;n.factoryExtra=i;}return n}function Yl(t,e){if(e?.isArray){let r=gt(t,{...e,isArray:false});return new Le(t,r)}if(e?.enumValues)return new pt(t,e.enumValues);let n=t.pgTypeName.toLowerCase().trim();if(n.startsWith("_")||n.endsWith("[]")){let r=n.startsWith("_")?n.slice(1):n.slice(0,-2),i={...t,pgTypeName:r},s=gt(i);return new Le(t,s)}return jl.has(n)?new rt(t):Dl.has(n)?new Ce(t):Hl.has(n)?new ot(t):ql.has(n)?new at(t):Kl.has(n)?new lt(t):zl.has(n)?new ct(t):Xl.has(n)?new ut(t):Jl.has(n)?new ft(t):Ml.has(n)?new st(t):Ul.has(n)?new it(t,e?.numericPrecision):Vl.has(n)?new mt(t):Gl.has(n)?new B(t,63):Wl.has(n)?new dt(t):Bl.has(n)?new B(t,e?.lengthConstraint):new ht(t)}var Dl,jl,Ul,Bl,Ml,Hl,ql,Vl,Gl,Wl,Kl,zl,Xl,Jl,Li=F(()=>{Gt();On();Fn();se();In();Dn();jn();Un();Bn();Mn();Hn();qn();Vn();Gn();Wn();Kn();Dl=new Set(["int2","smallint","int4","integer","int","int8","bigint"]),jl=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]),Ul=new Set(["float4","real","float8","double precision","numeric","decimal"]),Bl=new Set(["text","varchar","character varying","char","character","bpchar"]),Ml=new Set(["bytea"]),Hl=new Set(["bool","boolean"]),ql=new Set(["json","jsonb"]),Vl=new Set(["uuid"]),Gl=new Set(["name"]),Wl=new Set(["inet"]),Kl=new Set(["date"]),zl=new Set(["time","timetz","time without time zone","time with time zone"]),Xl=new Set(["timestamp","timestamptz","timestamp without time zone","timestamp with time zone"]),Jl=new Set(["interval"]);});var Pi=F(()=>{});var yt,Oi=F(()=>{yt=class{table;schema;fields;constructor(e,n="public",r=new Map){this.table=e,this.schema=n,this.fields=r;}get(e){return this.fields.get(e)}has(e){return this.fields.has(e)}set(e,n){this.fields.set(e,n);}columns(){return Array.from(this.fields.keys())}all(){return Array.from(this.fields.values())}serializeRow(e){let n={};for(let[r,i]of Object.entries(e)){let s=this.fields.get(r);n[r]=s?s.serialize(i):i;}return n}deserializeRow(e){let n={};for(let[r,i]of Object.entries(e)){let s=this.fields.get(r);n[r]=s?s.deserialize(i):i;}return n}applyDefaults(e){let n={...e};for(let[r,i]of this.fields)!(r in n)&&i.context.defaultFn&&(n[r]=i.context.defaultFn());return n}};});var Fi=F(()=>{de();Pn();Gt();On();Fn();se();In();Dn();jn();Un();Bn();Mn();Hn();qn();Vn();Gn();Wn();Kn();Li();Pi();Oi();});var Ui={};ss(Ui,{_resetWarnedMissingToClauseForTests:()=>Ql,collectComments:()=>ic,collectEnums:()=>Zl,collectPolicies:()=>tc,collectSchema:()=>nc,collectTableConstraints:()=>rc,collectVariables:()=>ec,lookupEnumValue:()=>ji});function Ql(){Jn.clear();}function Zl(t){let e=new Map;for(let n of t.stmts??[]){if(!n.stmt||!("CreateEnumStmt"in n.stmt))continue;let r=n.stmt.CreateEnumStmt,i=me(r.typeName??[]).join(".");if(!i||!r.vals)continue;let s=me(r.vals),o=i.toLowerCase();e.set(o,s),o.startsWith("public.")&&e.set(o.slice(7),s);}return e}function ji(t,e){let n=e.toLowerCase(),r=t.get(n);return r||(n.startsWith("public.")?t.get(n.slice(7)):t.get(`public.${n}`))}function ec(t){let e=new Map;for(let n of t.stmts??[]){if(!n.stmt||!("VariableSetStmt"in n.stmt))continue;let r=n.stmt.VariableSetStmt,i=r.name,s=Ei(r.args?.[0]??{});e.set(i,{value:s,local:r.is_local});}return e}function Ii(t){let e=[],n=false;for(let r of t??[])if("RoleSpec"in r){let i=r.RoleSpec;i.roletype==="ROLESPEC_PUBLIC"?i.location===-1&&(n=true):i.roletype==="ROLESPEC_CSTRING"&&i.rolename&&e.push(i.rolename);}return {roles:e,implicitPublic:n}}function Wt(t,e){return t&&t.length>0?t:e}function zn(t,e,n){return t.findIndex(r=>r.data.name===e.name&&r.data.table===e.table&&Wt(r.data.schema,n)===Wt(e.schema,n))}function Xn(t,e){return new Error(`policy "${t}" for table "${e}" does not exist`)}function Di(t,e,n,r){return t.data.table===e&&Wt(t.data.schema,r)===Wt(n,r)}function tc(t,e={}){let n=e.defaultSchema||"public",r=e.validateMutations===true,i=new Vt,s=new Set,o=[];for(let a of t.stmts??[])if(a.stmt){if("CreatePolicyStmt"in a.stmt){let l=a.stmt.CreatePolicyStmt,c=l.table?.relname??"",u=l.table?.schemaname,f={select:"SELECT",insert:"INSERT",update:"UPDATE",delete:"DELETE"},m=l.cmd_name?f[l.cmd_name]??"ALL":"ALL",g=l.permissive===true,{roles:y,implicitPublic:E}=Ii(l.roles),T=l.qual?i.deparse(l.qual):void 0,q=l.with_check?i.deparse(l.with_check):void 0;if(E){let M=u?`${u}.${c}`:c,K=l.policy_name??"",O=`${M}::${K}`;if(!Jn.has(O)){Jn.add(O);let $=JSON.stringify(T)+JSON.stringify(q);/\{\{auth\.(uid|jwt|role)/i.test($)||console.warn(`[supalite] policy "${K}" on "${M}" has no TO clause \u2014 applies to all roles (PUBLIC). For clarity, prefer an explicit \`TO <role>\` clause (e.g. \`TO authenticated\`).`);}}let S=new _e({name:l.policy_name??"",table:c,schema:u,command:m,permissive:g,roles:y,using:T,withCheck:q});o.push(S);}if("DropStmt"in a.stmt&&a.stmt.DropStmt.removeType==="OBJECT_POLICY"){let l=a.stmt.DropStmt,c=l.objects?.[0];if(c&&"List"in c){let u=me(c.List.items??[]),f=u[u.length-1],m=u[u.length-2],g=u.length>=3?u[u.length-3]:void 0;if(f&&m){let y=zn(o,{name:f,table:m,schema:g},n);if(y!==-1)o.splice(y,1);else if(r&&!l.missing_ok)throw Xn(f,m)}}}if("AlterPolicyStmt"in a.stmt){let l=a.stmt.AlterPolicyStmt,c=l.policy_name??"",u=l.table?.relname??"",f=l.table?.schemaname,m=zn(o,{name:c,table:u,schema:f},n);if(m===-1){if(r)throw Xn(c,u);continue}let g=o[m].data,y=l.roles?Ii(l.roles).roles:g.roles,E=l.qual?i.deparse(l.qual):g.using,T=l.with_check?i.deparse(l.with_check):g.withCheck;o[m]=new _e({...g,roles:y,using:E,withCheck:T});}if("RenameStmt"in a.stmt&&a.stmt.RenameStmt.renameType==="OBJECT_POLICY"){let l=a.stmt.RenameStmt,c=l.subname??"",u=l.relation?.relname??"",f=l.relation?.schemaname,m=zn(o,{name:c,table:u,schema:f},n);if(m===-1){if(r)throw Xn(c,u);continue}l.newname&&(o[m]=new _e({...o[m].data,name:l.newname}));}if("RenameStmt"in a.stmt&&a.stmt.RenameStmt.renameType==="OBJECT_TABLE"){let l=a.stmt.RenameStmt,c=l.relation?.relname??"",u=l.newname??"",f=l.relation?.schemaname;if(c&&u&&c!==u){s.delete(c)&&s.add(u);for(let m=0;m<o.length;m++)Di(o[m],c,f,n)&&(o[m]=new _e({...o[m].data,table:u}));}}if("DropStmt"in a.stmt&&a.stmt.DropStmt.removeType==="OBJECT_TABLE")for(let l of a.stmt.DropStmt.objects??[]){if(!("List"in l))continue;let c=me(l.List.items??[]),u=c[c.length-1],f=c.length>=2?c[c.length-2]:void 0;if(u){s.delete(u);for(let m=o.length-1;m>=0;m--)Di(o[m],u,f,n)&&o.splice(m,1);}}if("AlterTableStmt"in a.stmt){let l=a.stmt.AlterTableStmt,c=l.relation?.relname??"";for(let u of l.cmds??[]){if(!("AlterTableCmd"in u))continue;let f=u.AlterTableCmd.subtype;f==="AT_EnableRowSecurity"?s.add(c):f==="AT_DisableRowSecurity"&&s.delete(c);}}}return {policies:o,tables:s}}function nc(t,e){let n=new Map;for(let r of t.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 yt(s,o);for(let l of i.tableElts??[]){if(!("ColumnDef"in l))continue;let c=l.ColumnDef,u=c.colname;if(!u)continue;let f=c.typeName?.names?.map(x=>x.String?.sval||x.String?.str).filter(Boolean),m=f&&f.length>0?f.length===2&&f[0]==="pg_catalog"?f[1]:f.join("."):void 0;if(!m)continue;let g=!!c.typeName?.arrayBounds?.length,y=Array.isArray(c.typeName?.typmods)?c.typeName.typmods:[],E=x=>y[x]?.A_Const?.ival?.ival??y[x]?.A_Const?.val?.ival?.ival,T={isArray:g};if(Ai(m)&&y.length>0){let x=E(0);typeof x=="number"&&x>0&&(T.lengthConstraint=x);}if(_i(m)&&y.length>=2){let x=E(0),L=E(1);typeof x=="number"&&typeof L=="number"&&x>0&&L>=0&&(T.numericPrecision={precision:x,scale:L});}let q=ji(e,m);q&&(T.enumValues=q);let S=Array.isArray(c.constraints)?c.constraints:[],M=S.some(x=>x.Constraint?.contype==="CONSTR_PRIMARY"),K=Ti(m)||S.some(x=>x.Constraint?.contype==="CONSTR_IDENTITY"),O=S.some(x=>x.Constraint?.contype==="CONSTR_NOTNULL"),$=S.find(x=>x.Constraint?.contype==="CONSTR_UNIQUE"),v=S.find(x=>x.Constraint?.contype==="CONSTR_GENERATED"),A=S.find(x=>x.Constraint?.contype==="CONSTR_FOREIGN"),C=S.find(x=>x.Constraint?.contype==="CONSTR_CHECK"),d;if(A){let x=A.Constraint,L=x.pktable?.relname,h=x.pktable?.schemaname,p=x.pk_attrs?.[0]?.String?.sval;L&&p&&(d={refSchema:h,refTable:L,refColumn:p,constraintName:x.conname||void 0});}let z={schema:o,table:s,column:u,pgTypeName:m,nullable:!O&&!M,defaultValue:null,defaultFn:null,isPrimaryKey:M,isUnique:!!$,isSerial:K,isGenerated:!!v,fkRef:d,hasCheck:!!C,checkConstraintName:C?.Constraint?.conname||void 0,uniqueConstraintName:$?.Constraint?.conname||void 0};a.set(u,gt(z,T));}n.set(`${o}.${s}`,a);}return n}function rc(t){let e=[];for(let n of t.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){let u=o.ColumnDef,f=u?.colname;if(!f)continue;for(let m of u.constraints??[]){let g=m?.Constraint;if(!g||g.contype!=="CONSTR_FOREIGN")continue;let y=g.pktable?.relname;if(!y)continue;let E=(g.pk_attrs??[]).map(T=>T.String?.sval??T.String?.str).filter(Boolean);e.push({schema:s,table:i,kind:"foreign_key",name:g.conname||void 0,columns:[f],refSchema:g.pktable?.schemaname,refTable:y,refColumns:E});}continue}let a=o;if(!a.Constraint)continue;let l=a.Constraint,c=l.contype;if(c==="CONSTR_UNIQUE"){let u=(l.keys??[]).map(f=>f.String?.sval??f.String?.str).filter(Boolean);if(u.length===0)continue;e.push({schema:s,table:i,kind:"unique",name:l.conname||void 0,columns:u});}else if(c==="CONSTR_CHECK")e.push({schema:s,table:i,kind:"check",name:l.conname||void 0,columns:[]});else if(c==="CONSTR_FOREIGN"){let u=(l.fk_attrs??[]).map(g=>g.String?.sval??g.String?.str).filter(Boolean),f=(l.pk_attrs??[]).map(g=>g.String?.sval??g.String?.str).filter(Boolean),m=l.pktable?.relname;if(!m)continue;e.push({schema:s,table:i,kind:"foreign_key",name:l.conname||void 0,columns:u,refSchema:l.pktable?.schemaname,refTable:m,refColumns:f});}}}return e}function ic(t){let e=[];for(let n of t.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]];e.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,e.push({schema:a,table:l,column:c,text:i});}}}return e}var Jn,Bi=F(()=>{Ci();Ht();Ri();Fi();Ln();Jn=new Set;});var nr=process.stdin.isTTY?null:(async()=>{let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf8")})();nr&&process.stdin.unref?.();function re(t,e){St.existsSync(t)||(St.mkdirSync(t,{recursive:true}),e?.());}function Se(t,e,n){St.existsSync(t)||(St.writeFileSync(t,e),n?.());}var pe=class t{root;constructor(e,n){let r=n??t.projectDir();this.root=ie__default.join(r,e??"");}ensureRoot(){re(this.root);}static homeDir(){return ie__default.join(as.homedir(),".lite")}static projectDir(){return ie__default.join(process.cwd(),"supabase")}deleteAll(e=false){try{St.rmSync(this.root,{recursive:!0});}catch(n){if(!e)throw n}this.ensureRoot();}delete(e,n=false){try{St.unlinkSync(ie__default.join(this.root,e));}catch(r){if(!n)throw r}}write(e,n,r=false){try{this.ensureRoot(),St.writeFileSync(ie__default.join(this.root,e),n);}catch(i){if(!r)throw i}}read(e,n=false){try{return St.readFileSync(ie__default.join(this.root,e),"utf8")}catch(r){if(!n)throw r}}relativePath(e){return e?ie__default.relative(process.cwd(),ie__default.join(this.root,e)):this.root}path(e){return e?ie__default.join(this.root,e):this.root}};var Oe=process.env.LITE_CLOUD_URL??(process.env.LOCAL?"http://localhost:2001":"https://api.lite.dev"),Tt=process.env.LITE_CLOUD_PROJECTS_URL??(process.env.LOCAL?"http://supalite.local":"https://lite.black");var _t=class{root;constructor(e){this.root=e??ie__default.join(as.homedir(),".lite","auth"),re(this.root);}async getItem(e){try{return St.readFileSync(ie__default.join(this.root,e+".json"),"utf8")}catch{return null}}async setItem(e,n){St.writeFileSync(ie__default.join(this.root,e+".json"),n);}async removeItem(e){try{St.unlinkSync(ie__default.join(this.root,e+".json"));}catch{return}}};var Re=class{constructor(e){this.config=e;this.tempFs=new pe(".temp",this.config.root),this.projectFs=new pe("supabase",this.config.root),this.schemaFs=new pe("schemas",this.config.root),this.authStorage=this.config.authStorage??new _t(ie__default.join(pe.homeDir(),"auth")),this._client=this.config.withSupabaseClient!==false?this.config.client??createClient(this.config.host??Oe,process.env.LITE_CLOUD_ANON_KEY??"...",{auth:{storage:this.authStorage}}):void 0;}tempFs;projectFs;schemaFs;_client;authStorage;async fetch(e,n){if(!this.config.token)throw new Error("Not authenticated, sign in first.");let r=e instanceof URL?e:new URL(e,this.config.host??Oe);return await fetch(r,{...n,headers:{...n?.headers,Authorization:`Bearer ${this.config.token}`}})}};var ke=class extends Re{constructor(n){super(n);this.config=n;}get client(){if(!this._client)throw new Error("Supabase client not initialized");return this._client}projectRef(){return this.tempFs.read("project-ref",true)}projectUrl(n){let r=new URL(this.config.projectsHost??Tt),i=r.hostname.replace(/^www\./,"");return `${r.protocol}//${n}.${i}${r.port?`:${r.port}`:""}`}};var Y={config_dir:"supabase",default_db_url:"file:supabase/.temp/data.db",default_db_dir:"supabase/.temp/data"};var Ve=Pe(Fe());function ds(t,e){let n=t.slice(0,e).split(/\r\n|\n|\r/g);return [n.length,n.pop().length+1]}function hs(t,e,n){let r=t.split(/\r\n|\n|\r/g),i="",s=(Math.log10(e+1)|0)+1;for(let o=e-1;o<=e+1;o++){let a=r[o-1];a&&(i+=o.toString().padEnd(s," "),i+=": ",i+=a,i+=`
12
+ var As=Object.create;var cn=Object.defineProperty;var Cs=Object.getOwnPropertyDescriptor;var Rs=Object.getOwnPropertyNames;var ks=Object.getPrototypeOf,$s=Object.prototype.hasOwnProperty;var F=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ne=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ns=(t,e)=>{for(var n in e)cn(t,n,{get:e[n],enumerable:true});},vs=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Rs(e))!$s.call(t,i)&&i!==n&&cn(t,i,{get:()=>e[i],enumerable:!(r=Cs(e,i))||r.enumerable});return t};var je=(t,e,n)=>(n=t!=null?As(ks(t)):{},vs(cn(n,"default",{value:t,enumerable:true}),t));var Ue=Ne((Qu,fn)=>{var qt=process||{},Sr=qt.argv||[],Mt=qt.env||{},Fs=!(Mt.NO_COLOR||Sr.includes("--no-color"))&&(!!Mt.FORCE_COLOR||Sr.includes("--color")||qt.platform==="win32"||(qt.stdout||{}).isTTY&&Mt.TERM!=="dumb"||!!Mt.CI),Ds=(t,e,n=t)=>r=>{let i=""+r,s=i.indexOf(e,t.length);return ~s?t+js(i,e,n,s)+e:t+i+e},js=(t,e,n,r)=>{let i="",s=0;do i+=t.substring(s,r)+n,s=r+e.length,r=t.indexOf(e,s);while(~r);return i+t.substring(s)},Er=(t=Fs)=>{let e=t?Ds:()=>String;return {isColorSupported:t,reset:e("\x1B[0m","\x1B[0m"),bold:e("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:e("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:e("\x1B[3m","\x1B[23m"),underline:e("\x1B[4m","\x1B[24m"),inverse:e("\x1B[7m","\x1B[27m"),hidden:e("\x1B[8m","\x1B[28m"),strikethrough:e("\x1B[9m","\x1B[29m"),black:e("\x1B[30m","\x1B[39m"),red:e("\x1B[31m","\x1B[39m"),green:e("\x1B[32m","\x1B[39m"),yellow:e("\x1B[33m","\x1B[39m"),blue:e("\x1B[34m","\x1B[39m"),magenta:e("\x1B[35m","\x1B[39m"),cyan:e("\x1B[36m","\x1B[39m"),white:e("\x1B[37m","\x1B[39m"),gray:e("\x1B[90m","\x1B[39m"),bgBlack:e("\x1B[40m","\x1B[49m"),bgRed:e("\x1B[41m","\x1B[49m"),bgGreen:e("\x1B[42m","\x1B[49m"),bgYellow:e("\x1B[43m","\x1B[49m"),bgBlue:e("\x1B[44m","\x1B[49m"),bgMagenta:e("\x1B[45m","\x1B[49m"),bgCyan:e("\x1B[46m","\x1B[49m"),bgWhite:e("\x1B[47m","\x1B[49m"),blackBright:e("\x1B[90m","\x1B[39m"),redBright:e("\x1B[91m","\x1B[39m"),greenBright:e("\x1B[92m","\x1B[39m"),yellowBright:e("\x1B[93m","\x1B[39m"),blueBright:e("\x1B[94m","\x1B[39m"),magentaBright:e("\x1B[95m","\x1B[39m"),cyanBright:e("\x1B[96m","\x1B[39m"),whiteBright:e("\x1B[97m","\x1B[39m"),bgBlackBright:e("\x1B[100m","\x1B[49m"),bgRedBright:e("\x1B[101m","\x1B[49m"),bgGreenBright:e("\x1B[102m","\x1B[49m"),bgYellowBright:e("\x1B[103m","\x1B[49m"),bgBlueBright:e("\x1B[104m","\x1B[49m"),bgMagentaBright:e("\x1B[105m","\x1B[49m"),bgCyanBright:e("\x1B[106m","\x1B[49m"),bgWhiteBright:e("\x1B[107m","\x1B[49m")}};fn.exports=Er();fn.exports.createColors=Er;});var ot=Ne((dm,Zr)=>{var zr="[^\\\\/]",_a="(?=.)",Jr="[^/]",$n="(?:\\/|$)",Yr="(?:^|\\/)",Nn=`\\.{1,2}${$n}`,Ta="(?!\\.)",Aa=`(?!${Yr}${Nn})`,Ca=`(?!\\.{0,1}${$n})`,Ra=`(?!${Nn})`,ka="[^.\\/]",$a=`${Jr}*?`,Na="/",Qr={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:_a,QMARK:Jr,END_ANCHOR:$n,DOTS_SLASH:Nn,NO_DOT:Ta,NO_DOTS:Aa,NO_DOT_SLASH:Ca,NO_DOTS_SLASH:Ra,QMARK_NO_DOT:ka,STAR:$a,START_ANCHOR:Yr,SEP:Na},va={...Qr,SLASH_LITERAL:"[\\\\/]",QMARK:zr,STAR:`${zr}*?`,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:"\\"},Oa={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};Zr.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:Oa,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(t){return {"!":{type:"negate",open:"(?:(?!(?:",close:`))${t.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(t){return t===true?va:Qr}};});var at=Ne(ee=>{var{REGEX_BACKSLASH:Pa,REGEX_REMOVE_BACKSLASH:La,REGEX_SPECIAL_CHARS:Ia,REGEX_SPECIAL_CHARS_GLOBAL:Fa}=ot();ee.isObject=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);ee.hasRegexChars=t=>Ia.test(t);ee.isRegexChar=t=>t.length===1&&ee.hasRegexChars(t);ee.escapeRegex=t=>t.replace(Fa,"\\$1");ee.toPosixSlashes=t=>t.replace(Pa,"/");ee.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let t=navigator.platform.toLowerCase();return t==="win32"||t==="windows"}return typeof process<"u"&&process.platform?process.platform==="win32":false};ee.removeBackslashes=t=>t.replace(La,e=>e==="\\"?"":e);ee.escapeLast=(t,e,n)=>{let r=t.lastIndexOf(e,n);return r===-1?t:t[r-1]==="\\"?ee.escapeLast(t,e,r-1):`${t.slice(0,r)}\\${t.slice(r)}`};ee.removePrefix=(t,e={})=>{let n=t;return n.startsWith("./")&&(n=n.slice(2),e.prefix="./"),n};ee.wrapOutput=(t,e={},n={})=>{let r=n.contains?"":"^",i=n.contains?"":"$",s=`${r}(?:${t})${i}`;return e.negated===true&&(s=`(?:^(?!${s}).*$)`),s};ee.basename=(t,{windows:e}={})=>{let n=t.split(e?/[\\/]/:"/"),r=n[n.length-1];return r===""?n[n.length-2]:r};});var ai=Ne((gm,oi)=>{var ei=at(),{CHAR_ASTERISK:vn,CHAR_AT:Da,CHAR_BACKWARD_SLASH:lt,CHAR_COMMA:ja,CHAR_DOT:On,CHAR_EXCLAMATION_MARK:Pn,CHAR_FORWARD_SLASH:si,CHAR_LEFT_CURLY_BRACE:Ln,CHAR_LEFT_PARENTHESES:In,CHAR_LEFT_SQUARE_BRACKET:Ma,CHAR_PLUS:qa,CHAR_QUESTION_MARK:ti,CHAR_RIGHT_CURLY_BRACE:Ua,CHAR_RIGHT_PARENTHESES:ni,CHAR_RIGHT_SQUARE_BRACKET:Ba}=ot(),ri=t=>t===si||t===lt,ii=t=>{t.isPrefix!==true&&(t.depth=t.isGlobstar?1/0:1);},Ha=(t,e)=>{let n=e||{},r=t.length-1,i=n.parts===true||n.scanToEnd===true,s=[],o=[],a=[],c=t,l=-1,f=0,m=0,u=false,p=false,d=false,b=false,S=false,v=false,E=false,I=false,z=false,N=false,O=0,P,T,C={value:"",depth:0,isGlob:false},h=()=>l>=r,Y=()=>c.charCodeAt(l+1),V=()=>(P=T,c.charCodeAt(++l));for(;l<r;){T=V();let $;if(T===lt){E=C.backslashes=true,T=V(),T===Ln&&(v=true);continue}if(v===true||T===Ln){for(O++;h()!==true&&(T=V());){if(T===lt){E=C.backslashes=true,V();continue}if(T===Ln){O++;continue}if(v!==true&&T===On&&(T=V())===On){if(u=C.isBrace=true,d=C.isGlob=true,N=true,i===true)continue;break}if(v!==true&&T===ja){if(u=C.isBrace=true,d=C.isGlob=true,N=true,i===true)continue;break}if(T===Ua&&(O--,O===0)){v=false,u=C.isBrace=true,N=true;break}}if(i===true)continue;break}if(T===si){if(s.push(l),o.push(C),C={value:"",depth:0,isGlob:false},N===true)continue;if(P===On&&l===f+1){f+=2;continue}m=l+1;continue}if(n.noext!==true&&(T===qa||T===Da||T===vn||T===ti||T===Pn)===true&&Y()===In){if(d=C.isGlob=true,b=C.isExtglob=true,N=true,T===Pn&&l===f&&(z=true),i===true){for(;h()!==true&&(T=V());){if(T===lt){E=C.backslashes=true,T=V();continue}if(T===ni){d=C.isGlob=true,N=true;break}}continue}break}if(T===vn){if(P===vn&&(S=C.isGlobstar=true),d=C.isGlob=true,N=true,i===true)continue;break}if(T===ti){if(d=C.isGlob=true,N=true,i===true)continue;break}if(T===Ma){for(;h()!==true&&($=V());){if($===lt){E=C.backslashes=true,V();continue}if($===Ba){p=C.isBracket=true,d=C.isGlob=true,N=true;break}}if(i===true)continue;break}if(n.nonegate!==true&&T===Pn&&l===f){I=C.negated=true,f++;continue}if(n.noparen!==true&&T===In){if(d=C.isGlob=true,i===true){for(;h()!==true&&(T=V());){if(T===In){E=C.backslashes=true,T=V();continue}if(T===ni){N=true;break}}continue}break}if(d===true){if(N=true,i===true)continue;break}}n.noext===true&&(b=false,d=false);let q=c,g="",y="";f>0&&(g=c.slice(0,f),c=c.slice(f),m-=f),q&&d===true&&m>0?(q=c.slice(0,m),y=c.slice(m)):d===true?(q="",y=c):q=c,q&&q!==""&&q!=="/"&&q!==c&&ri(q.charCodeAt(q.length-1))&&(q=q.slice(0,-1)),n.unescape===true&&(y&&(y=ei.removeBackslashes(y)),q&&E===true&&(q=ei.removeBackslashes(q)));let _={prefix:g,input:t,start:f,base:q,glob:y,isBrace:u,isBracket:p,isGlob:d,isExtglob:b,isGlobstar:S,negated:I,negatedExtglob:z};if(n.tokens===true&&(_.maxDepth=0,ri(T)||o.push(C),_.tokens=o),n.parts===true||n.tokens===true){let $;for(let U=0;U<s.length;U++){let ie=$?$+1:f,se=s[U],Ee=t.slice(ie,se);n.tokens&&(U===0&&f!==0?(o[U].isPrefix=true,o[U].value=g):o[U].value=Ee,ii(o[U]),_.maxDepth+=o[U].depth),(U!==0||Ee!=="")&&a.push(Ee),$=se;}if($&&$+1<t.length){let U=t.slice($+1);a.push(U),n.tokens&&(o[o.length-1].value=U,ii(o[o.length-1]),_.maxDepth+=o[o.length-1].depth);}_.slashes=s,_.parts=a;}return _};oi.exports=Ha;});var pi=Ne((ym,fi)=>{var ct=ot(),re=at(),{MAX_LENGTH:Zt,POSIX_REGEX_SOURCE:Va,REGEX_NON_SPECIAL_CHARS:Ka,REGEX_SPECIAL_CHARS_BACKREF:Ga,REPLACEMENTS:li}=ct,Wa=(t,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...t,e);t.sort();let n=`[${t.join("-")}]`;try{new RegExp(n);}catch{return t.map(i=>re.escapeRegex(i)).join("..")}return n},Ve=(t,e)=>`Missing ${t}: "${e}" - use "\\\\${e}" to match literal characters`,ci=t=>{let e=[],n=0,r=0,i=0,s="",o=false;for(let a of t){if(o===true){s+=a,o=false;continue}if(a==="\\"){s+=a,o=true;continue}if(a==='"'){i=i===1?0:1,s+=a;continue}if(i===0){if(a==="[")n++;else if(a==="]"&&n>0)n--;else if(n===0){if(a==="(")r++;else if(a===")"&&r>0)r--;else if(a==="|"&&r===0){e.push(s),s="";continue}}}s+=a;}return e.push(s),e},Xa=t=>{let e=false;for(let n of t){if(e===true){e=false;continue}if(n==="\\"){e=true;continue}if(/[?*+@!()[\]{}]/.test(n))return false}return true},ui=t=>{let e=t.trim(),n=true;for(;n===true;)n=false,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),n=true);if(Xa(e))return e.replace(/\\(.)/g,"$1")},za=t=>{let e=t.map(ui).filter(Boolean);for(let n=0;n<e.length;n++)for(let r=n+1;r<e.length;r++){let i=e[n],s=e[r],o=i[0];if(!(!o||i!==o.repeat(i.length)||s!==o.repeat(s.length))&&(i===s||i.startsWith(s)||s.startsWith(i)))return true}return false},Fn=(t,e=true)=>{if(t[0]!=="+"&&t[0]!=="*"||t[1]!=="(")return;let n=0,r=0,i=0,s=false;for(let o=1;o<t.length;o++){let a=t[o];if(s===true){s=false;continue}if(a==="\\"){s=true;continue}if(a==='"'){i=i===1?0:1;continue}if(i!==1){if(a==="["){n++;continue}if(a==="]"&&n>0){n--;continue}if(!(n>0)){if(a==="("){r++;continue}if(a===")"&&(r--,r===0))return e===true&&o!==t.length-1?void 0:{type:t[0],body:t.slice(2,o),end:o}}}}},Ja=t=>{let e=0,n=[];for(;e<t.length;){let i=Fn(t.slice(e),false);if(!i||i.type!=="*")return;let s=ci(i.body).map(a=>a.trim());if(s.length!==1)return;let o=ui(s[0]);if(!o||o.length!==1)return;n.push(o),e+=i.end+1;}return n.length<1?void 0:`${n.length===1?re.escapeRegex(n[0]):`[${n.map(i=>re.escapeRegex(i)).join("")}]`}*`},Ya=t=>{let e=0,n=t.trim(),r=Fn(n);for(;r;)e++,n=r.body.trim(),r=Fn(n);return e},Qa=(t,e)=>{if(e.maxExtglobRecursion===false)return {risky:false};let n=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:ct.DEFAULT_MAX_EXTGLOB_RECURSION,r=ci(t).map(i=>i.trim());if(r.length>1&&(r.some(i=>i==="")||r.some(i=>/^[*?]+$/.test(i))||za(r)))return {risky:true};for(let i of r){let s=Ja(i);if(s)return {risky:true,safeOutput:s};if(Ya(i)>n)return {risky:true}}return {risky:false}},Dn=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");t=li[t]||t;let n={...e},r=typeof n.maxLength=="number"?Math.min(Zt,n.maxLength):Zt,i=t.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?"":"?:",c=ct.globChars(n.windows),l=ct.extglobChars(c),{DOT_LITERAL:f,PLUS_LITERAL:m,SLASH_LITERAL:u,ONE_CHAR:p,DOTS_SLASH:d,NO_DOT:b,NO_DOT_SLASH:S,NO_DOTS_SLASH:v,QMARK:E,QMARK_NO_DOT:I,STAR:z,START_ANCHOR:N}=c,O=x=>`(${a}(?:(?!${N}${x.dot?d:f}).)*?)`,P=n.dot?"":b,T=n.dot?E:I,C=n.bash===true?O(n):z;n.capture&&(C=`(${C})`),typeof n.noext=="boolean"&&(n.noextglob=n.noext);let h={input:t,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};t=re.removePrefix(t,h),i=t.length;let Y=[],V=[],q=[],g=s,y,_=()=>h.index===i-1,$=h.peek=(x=1)=>t[h.index+x],U=h.advance=()=>t[++h.index]||"",ie=()=>t.slice(h.index+1),se=(x="",H=0)=>{h.consumed+=x,h.index+=H;},Ee=x=>{h.output+=x.output!=null?x.output:x.value,se(x.value);},_s=()=>{let x=1;for(;$()==="!"&&($(2)!=="("||$(3)==="?");)U(),h.start++,x++;return x%2===0?false:(h.negated=true,h.start++,true)},Ot=x=>{h[x]++,q.push(x);},_e=x=>{h[x]--,q.pop();},R=x=>{if(g.type==="globstar"){let H=h.braces>0&&(x.type==="comma"||x.type==="brace"),w=x.extglob===true||Y.length&&(x.type==="pipe"||x.type==="paren");x.type!=="slash"&&x.type!=="paren"&&!H&&!w&&(h.output=h.output.slice(0,-g.output.length),g.type="star",g.value="*",g.output=C,h.output+=g.output);}if(Y.length&&x.type!=="paren"&&(Y[Y.length-1].inner+=x.value),(x.value||x.output)&&Ee(x),g&&g.type==="text"&&x.type==="text"){g.output=(g.output||g.value)+x.value,g.value+=x.value;return}x.prev=g,o.push(x),g=x;},Pt=(x,H)=>{let w={...l[H],conditions:1,inner:""};w.prev=g,w.parens=h.parens,w.output=h.output,w.startIndex=h.index,w.tokensIndex=o.length;let k=(n.capture?"(":"")+w.open;Ot("parens"),R({type:x,value:H,output:h.output?"":p}),R({type:"paren",extglob:true,value:U(),output:k}),Y.push(w);},Ts=x=>{let H=t.slice(x.startIndex,h.index+1),w=t.slice(x.startIndex+2,h.index),k=Qa(w,n);if((x.type==="plus"||x.type==="star")&&k.risky){let j=k.safeOutput?(x.output?"":p)+(n.capture?`(${k.safeOutput})`:k.safeOutput):void 0,pe=o[x.tokensIndex];pe.type="text",pe.value=H,pe.output=j||re.escapeRegex(H);for(let me=x.tokensIndex+1;me<o.length;me++)o[me].value="",o[me].output="",delete o[me].suffix;h.output=x.output+pe.output,h.backtrack=true,R({type:"paren",extglob:true,value:y,output:""}),_e("parens");return}let B=x.close+(n.capture?")":""),X;if(x.type==="negate"){let j=C;if(x.inner&&x.inner.length>1&&x.inner.includes("/")&&(j=O(n)),(j!==C||_()||/^\)+$/.test(ie()))&&(B=x.close=`)$))${j}`),x.inner.includes("*")&&(X=ie())&&/^\.[^\\/.]+$/.test(X)){let pe=Dn(X,{...e,fastpaths:false}).output;B=x.close=`)${pe})${j})`;}x.prev.type==="bos"&&(h.negatedExtglob=true);}R({type:"paren",extglob:true,value:y,output:B}),_e("parens");};if(n.fastpaths!==false&&!/(^[*!]|[/()[\]{}"])/.test(t)){let x=false,H=t.replace(Ga,(w,k,B,X,j,pe)=>X==="\\"?(x=true,w):X==="?"?k?k+X+(j?E.repeat(j.length):""):pe===0?T+(j?E.repeat(j.length):""):E.repeat(B.length):X==="."?f.repeat(B.length):X==="*"?k?k+X+(j?C:""):C:k?w:`\\${w}`);return x===true&&(n.unescape===true?H=H.replace(/\\/g,""):H=H.replace(/\\+/g,w=>w.length%2===0?"\\\\":w?"\\":"")),H===t&&n.contains===true?(h.output=t,h):(h.output=re.wrapOutput(H,h,e),h)}for(;!_();){if(y=U(),y==="\0")continue;if(y==="\\"){let w=$();if(w==="/"&&n.bash!==true||w==="."||w===";")continue;if(!w){y+="\\",R({type:"text",value:y});continue}let k=/^\\+/.exec(ie()),B=0;if(k&&k[0].length>2&&(B=k[0].length,h.index+=B,B%2!==0&&(y+="\\")),n.unescape===true?y=U():y+=U(),h.brackets===0){R({type:"text",value:y});continue}}if(h.brackets>0&&(y!=="]"||g.value==="["||g.value==="[^")){if(n.posix!==false&&y===":"){let w=g.value.slice(1);if(w.includes("[")&&(g.posix=true,w.includes(":"))){let k=g.value.lastIndexOf("["),B=g.value.slice(0,k),X=g.value.slice(k+2),j=Va[X];if(j){g.value=B+j,h.backtrack=true,U(),!s.output&&o.indexOf(g)===1&&(s.output=p);continue}}}(y==="["&&$()!==":"||y==="-"&&$()==="]")&&(y=`\\${y}`),y==="]"&&(g.value==="["||g.value==="[^")&&(y=`\\${y}`),n.posix===true&&y==="!"&&g.value==="["&&(y="^"),g.value+=y,Ee({value:y});continue}if(h.quotes===1&&y!=='"'){y=re.escapeRegex(y),g.value+=y,Ee({value:y});continue}if(y==='"'){h.quotes=h.quotes===1?0:1,n.keepQuotes===true&&R({type:"text",value:y});continue}if(y==="("){Ot("parens"),R({type:"paren",value:y});continue}if(y===")"){if(h.parens===0&&n.strictBrackets===true)throw new SyntaxError(Ve("opening","("));let w=Y[Y.length-1];if(w&&h.parens===w.parens+1){Ts(Y.pop());continue}R({type:"paren",value:y,output:h.parens?")":"\\)"}),_e("parens");continue}if(y==="["){if(n.nobracket===true||!ie().includes("]")){if(n.nobracket!==true&&n.strictBrackets===true)throw new SyntaxError(Ve("closing","]"));y=`\\${y}`;}else Ot("brackets");R({type:"bracket",value:y});continue}if(y==="]"){if(n.nobracket===true||g&&g.type==="bracket"&&g.value.length===1){R({type:"text",value:y,output:`\\${y}`});continue}if(h.brackets===0){if(n.strictBrackets===true)throw new SyntaxError(Ve("opening","["));R({type:"text",value:y,output:`\\${y}`});continue}_e("brackets");let w=g.value.slice(1);if(g.posix!==true&&w[0]==="^"&&!w.includes("/")&&(y=`/${y}`),g.value+=y,Ee({value:y}),n.literalBrackets===false||re.hasRegexChars(w))continue;let k=re.escapeRegex(g.value);if(h.output=h.output.slice(0,-g.value.length),n.literalBrackets===true){h.output+=k,g.value=k;continue}g.value=`(${a}${k}|${g.value})`,h.output+=g.value;continue}if(y==="{"&&n.nobrace!==true){Ot("braces");let w={type:"brace",value:y,output:"(",outputIndex:h.output.length,tokensIndex:h.tokens.length};V.push(w),R(w);continue}if(y==="}"){let w=V[V.length-1];if(n.nobrace===true||!w){R({type:"text",value:y,output:y});continue}let k=")";if(w.dots===true){let B=o.slice(),X=[];for(let j=B.length-1;j>=0&&(o.pop(),B[j].type!=="brace");j--)B[j].type!=="dots"&&X.unshift(B[j].value);k=Wa(X,n),h.backtrack=true;}if(w.comma!==true&&w.dots!==true){let B=h.output.slice(0,w.outputIndex),X=h.tokens.slice(w.tokensIndex);w.value=w.output="\\{",y=k="\\}",h.output=B;for(let j of X)h.output+=j.output||j.value;}R({type:"brace",value:y,output:k}),_e("braces"),V.pop();continue}if(y==="|"){Y.length>0&&Y[Y.length-1].conditions++,R({type:"text",value:y});continue}if(y===","){let w=y,k=V[V.length-1];k&&q[q.length-1]==="braces"&&(k.comma=true,w="|"),R({type:"comma",value:y,output:w});continue}if(y==="/"){if(g.type==="dot"&&h.index===h.start+1){h.start=h.index+1,h.consumed="",h.output="",o.pop(),g=s;continue}R({type:"slash",value:y,output:u});continue}if(y==="."){if(h.braces>0&&g.type==="dot"){g.value==="."&&(g.output=f);let w=V[V.length-1];g.type="dots",g.output+=y,g.value+=y,w.dots=true;continue}if(h.braces+h.parens===0&&g.type!=="bos"&&g.type!=="slash"){R({type:"text",value:y,output:f});continue}R({type:"dot",value:y,output:f});continue}if(y==="?"){if(!(g&&g.value==="(")&&n.noextglob!==true&&$()==="("&&$(2)!=="?"){Pt("qmark",y);continue}if(g&&g.type==="paren"){let k=$(),B=y;(g.value==="("&&!/[!=<:]/.test(k)||k==="<"&&!/<([!=]|\w+>)/.test(ie()))&&(B=`\\${y}`),R({type:"text",value:y,output:B});continue}if(n.dot!==true&&(g.type==="slash"||g.type==="bos")){R({type:"qmark",value:y,output:I});continue}R({type:"qmark",value:y,output:E});continue}if(y==="!"){if(n.noextglob!==true&&$()==="("&&($(2)!=="?"||!/[!=<:]/.test($(3)))){Pt("negate",y);continue}if(n.nonegate!==true&&h.index===0){_s();continue}}if(y==="+"){if(n.noextglob!==true&&$()==="("&&$(2)!=="?"){Pt("plus",y);continue}if(g&&g.value==="("||n.regex===false){R({type:"plus",value:y,output:m});continue}if(g&&(g.type==="bracket"||g.type==="paren"||g.type==="brace")||h.parens>0){R({type:"plus",value:y});continue}R({type:"plus",value:m});continue}if(y==="@"){if(n.noextglob!==true&&$()==="("&&$(2)!=="?"){R({type:"at",extglob:true,value:y,output:""});continue}R({type:"text",value:y});continue}if(y!=="*"){(y==="$"||y==="^")&&(y=`\\${y}`);let w=Ka.exec(ie());w&&(y+=w[0],h.index+=w[0].length),R({type:"text",value:y});continue}if(g&&(g.type==="globstar"||g.star===true)){g.type="star",g.star=true,g.value+=y,g.output=C,h.backtrack=true,h.globstar=true,se(y);continue}let x=ie();if(n.noextglob!==true&&/^\([^?]/.test(x)){Pt("star",y);continue}if(g.type==="star"){if(n.noglobstar===true){se(y);continue}let w=g.prev,k=w.prev,B=w.type==="slash"||w.type==="bos",X=k&&(k.type==="star"||k.type==="globstar");if(n.bash===true&&(!B||x[0]&&x[0]!=="/")){R({type:"star",value:y,output:""});continue}let j=h.braces>0&&(w.type==="comma"||w.type==="brace"),pe=Y.length&&(w.type==="pipe"||w.type==="paren");if(!B&&w.type!=="paren"&&!j&&!pe){R({type:"star",value:y,output:""});continue}for(;x.slice(0,3)==="/**";){let me=t[h.index+4];if(me&&me!=="/")break;x=x.slice(3),se("/**",3);}if(w.type==="bos"&&_()){g.type="globstar",g.value+=y,g.output=O(n),h.output=g.output,h.globstar=true,se(y);continue}if(w.type==="slash"&&w.prev.type!=="bos"&&!X&&_()){h.output=h.output.slice(0,-(w.output+g.output).length),w.output=`(?:${w.output}`,g.type="globstar",g.output=O(n)+(n.strictSlashes?")":"|$)"),g.value+=y,h.globstar=true,h.output+=w.output+g.output,se(y);continue}if(w.type==="slash"&&w.prev.type!=="bos"&&x[0]==="/"){let me=x[1]!==void 0?"|$":"";h.output=h.output.slice(0,-(w.output+g.output).length),w.output=`(?:${w.output}`,g.type="globstar",g.output=`${O(n)}${u}|${u}${me})`,g.value+=y,h.output+=w.output+g.output,h.globstar=true,se(y+U()),R({type:"slash",value:"/",output:""});continue}if(w.type==="bos"&&x[0]==="/"){g.type="globstar",g.value+=y,g.output=`(?:^|${u}|${O(n)}${u})`,h.output=g.output,h.globstar=true,se(y+U()),R({type:"slash",value:"/",output:""});continue}h.output=h.output.slice(0,-g.output.length),g.type="globstar",g.output=O(n),g.value+=y,h.output+=g.output,h.globstar=true,se(y);continue}let H={type:"star",value:y,output:C};if(n.bash===true){H.output=".*?",(g.type==="bos"||g.type==="slash")&&(H.output=P+H.output),R(H);continue}if(g&&(g.type==="bracket"||g.type==="paren")&&n.regex===true){H.output=y,R(H);continue}(h.index===h.start||g.type==="slash"||g.type==="dot")&&(g.type==="dot"?(h.output+=S,g.output+=S):n.dot===true?(h.output+=v,g.output+=v):(h.output+=P,g.output+=P),$()!=="*"&&(h.output+=p,g.output+=p)),R(H);}for(;h.brackets>0;){if(n.strictBrackets===true)throw new SyntaxError(Ve("closing","]"));h.output=re.escapeLast(h.output,"["),_e("brackets");}for(;h.parens>0;){if(n.strictBrackets===true)throw new SyntaxError(Ve("closing",")"));h.output=re.escapeLast(h.output,"("),_e("parens");}for(;h.braces>0;){if(n.strictBrackets===true)throw new SyntaxError(Ve("closing","}"));h.output=re.escapeLast(h.output,"{"),_e("braces");}if(n.strictSlashes!==true&&(g.type==="star"||g.type==="bracket")&&R({type:"maybe_slash",value:"",output:`${u}?`}),h.backtrack===true){h.output="";for(let x of h.tokens)h.output+=x.output!=null?x.output:x.value,x.suffix&&(h.output+=x.suffix);}return h};Dn.fastpaths=(t,e)=>{let n={...e},r=typeof n.maxLength=="number"?Math.min(Zt,n.maxLength):Zt,i=t.length;if(i>r)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${r}`);t=li[t]||t;let{DOT_LITERAL:s,SLASH_LITERAL:o,ONE_CHAR:a,DOTS_SLASH:c,NO_DOT:l,NO_DOTS:f,NO_DOTS_SLASH:m,STAR:u,START_ANCHOR:p}=ct.globChars(n.windows),d=n.dot?f:l,b=n.dot?m:l,S=n.capture?"":"?:",v={negated:false,prefix:""},E=n.bash===true?".*?":u;n.capture&&(E=`(${E})`);let I=P=>P.noglobstar===true?E:`(${S}(?:(?!${p}${P.dot?c:s}).)*?)`,z=P=>{switch(P){case "*":return `${d}${a}${E}`;case ".*":return `${s}${a}${E}`;case "*.*":return `${d}${E}${s}${a}${E}`;case "*/*":return `${d}${E}${o}${a}${b}${E}`;case "**":return d+I(n);case "**/*":return `(?:${d}${I(n)}${o})?${b}${a}${E}`;case "**/*.*":return `(?:${d}${I(n)}${o})?${b}${E}${s}${a}${E}`;case "**/.*":return `(?:${d}${I(n)}${o})?${s}${a}${E}`;default:{let T=/^(.*?)\.(\w+)$/.exec(P);if(!T)return;let C=z(T[1]);return C?C+s+T[2]:void 0}}},N=re.removePrefix(t,v),O=z(N);return O&&n.strictSlashes!==true&&(O+=`${o}?`),O};fi.exports=Dn;});var hi=Ne((bm,di)=>{var Za=ai(),jn=pi(),mi=at(),el=ot(),tl=t=>t&&typeof t=="object"&&!Array.isArray(t),G=(t,e,n=false)=>{if(Array.isArray(t)){let f=t.map(u=>G(u,e,n));return u=>{for(let p of f){let d=p(u);if(d)return d}return false}}let r=tl(t)&&t.tokens&&t.input;if(t===""||typeof t!="string"&&!r)throw new TypeError("Expected pattern to be a non-empty string");let i=e||{},s=i.windows,o=r?G.compileRe(t,e):G.makeRe(t,e,false,true),a=o.state;delete o.state;let c=()=>false;if(i.ignore){let f={...e,ignore:null,onMatch:null,onResult:null};c=G(i.ignore,f,n);}let l=(f,m=false)=>{let{isMatch:u,match:p,output:d}=G.test(f,o,e,{glob:t,posix:s}),b={glob:t,state:a,regex:o,posix:s,input:f,output:d,match:p,isMatch:u};return typeof i.onResult=="function"&&i.onResult(b),u===false?(b.isMatch=false,m?b:false):c(f)?(typeof i.onIgnore=="function"&&i.onIgnore(b),b.isMatch=false,m?b:false):(typeof i.onMatch=="function"&&i.onMatch(b),m?b:true)};return n&&(l.state=a),l};G.test=(t,e,n,{glob:r,posix:i}={})=>{if(typeof t!="string")throw new TypeError("Expected input to be a string");if(t==="")return {isMatch:false,output:""};let s=n||{},o=s.format||(i?mi.toPosixSlashes:null),a=t===r,c=a&&o?o(t):t;return a===false&&(c=o?o(t):t,a=c===r),(a===false||s.capture===true)&&(s.matchBase===true||s.basename===true?a=G.matchBase(t,e,n,i):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};G.matchBase=(t,e,n)=>(e instanceof RegExp?e:G.makeRe(e,n)).test(mi.basename(t));G.isMatch=(t,e,n)=>G(e,n)(t);G.parse=(t,e)=>Array.isArray(t)?t.map(n=>G.parse(n,e)):jn(t,{...e,fastpaths:false});G.scan=(t,e)=>Za(t,e);G.compileRe=(t,e,n=false,r=false)=>{if(n===true)return t.output;let i=e||{},s=i.contains?"":"^",o=i.contains?"":"$",a=`${s}(?:${t.output})${o}`;t&&t.negated===true&&(a=`^(?!${a}).*$`);let c=G.toRegex(a,e);return r===true&&(c.state=t),c};G.makeRe=(t,e={},n=false,r=false)=>{if(!t||typeof t!="string")throw new TypeError("Expected a non-empty string");let i={negated:false,fastpaths:true};return e.fastpaths!==false&&(t[0]==="."||t[0]==="*")&&(i.output=jn.fastpaths(t,e)),i.output||(i=jn(t,e)),G.compileRe(i,e,n,r)};G.toRegex=(t,e)=>{try{let n=e||{};return new RegExp(t,n.flags||(n.nocase?"i":""))}catch(n){if(e&&e.debug===true)throw n;return /$^/}};G.constants=el;di.exports=G;});var wi=Ne((wm,bi)=>{var gi=hi(),nl=at();function yi(t,e,n=false){return e&&(e.windows===null||e.windows===void 0)&&(e={...e,windows:nl.isWindows()}),gi(t,e,n)}Object.assign(yi,gi);bi.exports=yi;});function Ge(t){if("String"in t)return t.String.sval}function M(t){return t.map(Ge).filter(e=>e!=null)}function Ki(t){return Object.keys(t)[0]}function Gi(t){if("A_Const"in t){if(t.A_Const.ival)return t.A_Const.ival.ival;if(t.A_Const.fval)return t.A_Const.fval.fval;if(t.A_Const.sval)return t.A_Const.sval.sval;if(t.A_Const.boolval)return t.A_Const.boolval.boolval;if(t.A_Const.isnull)return null}}var nn=F(()=>{});function Wi(t){let e=t.toLowerCase();return ["serial","serial4","bigserial","serial8","smallserial","serial2"].includes(e)}function Xi(t){let e=t.toLowerCase();return ["varchar","character varying","char","character","bpchar"].includes(e)}function zi(t){let e=t.toLowerCase();return ["numeric","decimal"].includes(e)}var Wn,rn,bc,Xn=F(()=>{nn();Wn=class extends Error{},rn=class extends Wn{constructor(n,r){super(r??`Unsupported node type: ${Ki(n)}`);this.node=n;}};bc={CreateEnumStmt:{react:"ignore"},CreateDomainStmt:{react:"warn"},CreateSeqStmt:{react:"ignore"},AlterSeqStmt:{react:"ignore"},CreateSchemaStmt:{react:"warn"},CreatePolicyStmt:{react:"ignore"},AlterPolicyStmt:{react:"ignore"},PartitionElem:{react:"error"},PartitionCmd:{react:"error"},VariableSetStmt:{react:"ignore"},CompositeTypeStmt:{react:"error"},AlterEnumStmt:{react:"error"},AlterObjectSchemaStmt:{react:"error"},AlterOwnerStmt:{react:"error"},AlterTypeStmt:{react:"error"},AlterFunctionStmt:{react:"error"},AlterDefaultPrivilegesStmt:{react:"error"},GrantStmt:{react:"error"},GrantRoleStmt:{react:"error"},CopyStmt:{react:"error"},CreateCastStmt:{react:"error"},AlterOpFamilyStmt:{react:"error"},AlterOperatorStmt:{react:"error"},TruncateStmt:{react:"error"},A_Indirection:{react:"error"},XmlExpr:{react:"error"},XmlSerialize:{react:"error"},RangeTableSample:{react:"error"},GroupingSet:{react:"error"}},new Map(Object.entries(bc));});function Re(t){return t!=null&&typeof t=="object"&&t.kind==="storage.foldername"}function ke(t){if(t==null||typeof t!="object")return false;let e=t.kind;return e==="storage.filename"||e==="storage.extension"}function ht(t,e,n){return {$storageObject:{function:t.kind.slice(8),column:t.column,ops:{[e]:n}}}}function wc(t){return t.startsWith("storage.")?t.slice(8):t}function xc(t){return t==="{{storage.operation}}"}function Sc(t){switch(t){case "~~":return "$like";case "!~~":return "$notLike";case "~~*":return "$ilike";case "!~~*":return "$notIlike";default:return}}function zn(t){switch(t){case "$gt":return "$lt";case "$gte":return "$lte";case "$lt":return "$gt";case "$lte":return "$gte";default:return t}}function sn(t,e){return t?"TypeCast"in t&&t.TypeCast.arg?sn(t.TypeCast.arg,e):"A_Const"in t?true:typeof e=="string"&&e.startsWith("{{")&&e.endsWith("}}"):false}var D,on,Ji=F(()=>{nn();Xn();D=class extends rn{constructor(e,n){super(e,`Unsupported expression: ${n}`);}},on=class{deparse(e){if("A_Const"in e){let i=e.A_Const;if(i.boolval!==void 0)return i.boolval.boolval?{}:{$always:false}}if("FuncCall"in e){let i=this.storageOperationPredicate(e.FuncCall);if(i)return i}let n=Object.keys(e)[0],r=this[n];if(!r)throw new D({[n]:e},`Unsupported expression: ${n}`);return r.call(this,e[n])}deparseValue(e){if("A_Const"in e)return this.A_Const(e.A_Const);if("ColumnRef"in e)return this.ColumnRef(e.ColumnRef);if("FuncCall"in e)return this.FuncCall(e.FuncCall);if("SubLink"in e)return this.SubLink(e.SubLink);if("TypeCast"in e)return this.TypeCast(e.TypeCast);if("A_Indirection"in e)return this.A_Indirection(e.A_Indirection);if("A_Expr"in e){let r=this.isJwtAccessor(e.A_Expr);return r||this.A_Expr(e.A_Expr)}if("BoolExpr"in e)return this.BoolExpr(e.BoolExpr);let n=Object.keys(e)[0];throw new D({[n]:e},`deparseValue: ${n}`)}A_Expr(e){if(e.kind==="AEXPR_OP"){let n=e.name?.[0],r=n?Ge(n):void 0;if(!r)throw new D({A_Expr:e},"A_Expr missing operator");let i=this.isJwtAccessor(e);if(i)return {[i]:{}};let s=e.lexpr?this.deparseValue(e.lexpr):void 0,o=e.rexpr?this.deparseValue(e.rexpr):void 0,a=this.mapOperator(r);if(!a)throw new D({A_Expr:e},`Unsupported operator: ${r}`);if(Re(s)&&Re(o))throw new D({A_Expr:e},"comparisons between storage.foldername expressions are unsupported");if(Re(s))return {$storageFolder:{column:s.column,index:s.index,ops:{[a]:o}}};if(Re(o)){if(!sn(e.lexpr,s))throw new D({A_Expr:e},"storage.foldername RHS comparisons require a literal or auth placeholder");return {$storageFolder:{column:o.column,index:o.index,ops:{[zn(a)]:s}}}}if(ke(s)&&ke(o))throw new D({A_Expr:e},"comparisons between Storage object helper expressions are unsupported");if(ke(s))return ht(s,a,o);if(ke(o)){if(!sn(e.lexpr,s))throw new D({A_Expr:e},"Storage object helper RHS comparisons require a literal or auth placeholder");return ht(o,zn(a),s)}if(xc(o)){if(!sn(e.lexpr,s))throw new D({A_Expr:e},"storage.operation RHS comparisons require a literal or auth placeholder");return {[o]:{[zn(a)]:s}}}let c=e.rexpr!=null&&"ColumnRef"in e.rexpr;if(typeof s=="string"&&s.startsWith("{{")&&c)return {[o]:{[a]:s}};let l=c&&typeof o=="string"?{$ref:o}:o;return {[s]:{[a]:l}}}if(e.kind==="AEXPR_LIKE"||e.kind==="AEXPR_ILIKE"){let n=e.lexpr?this.deparseValue(e.lexpr):void 0,r=e.rexpr?this.deparseValue(e.rexpr):void 0,i=e.kind==="AEXPR_ILIKE"?"~~*":"~~",s=e.name?.[0]?Ge(e.name[0])??i:i,o=Sc(s);if(!o)throw new D({A_Expr:e},`Unsupported pattern operator: ${s}`);if(Re(r))throw new D({A_Expr:e},"storage.foldername on the right of a pattern predicate is unsupported");if(Re(n))return {$storageFolder:{column:n.column,index:n.index,ops:{[o]:r}}};if(ke(r))throw new D({A_Expr:e},"Storage object helpers on the right of a pattern predicate are unsupported");return ke(n)?ht(n,o,r):{[n]:{[o]:r}}}if(e.kind==="AEXPR_IN"){let n=e.lexpr?this.deparseValue(e.lexpr):void 0,i=(e.name?.[0]?Ge(e.name[0]):"=")==="<>"?"$notIn":"$in",s=e.rexpr&&"List"in e.rexpr&&e.rexpr.List.items?e.rexpr.List.items.map(o=>this.deparseValue(o)):[];return Re(n)?{$storageFolder:{column:n.column,index:n.index,ops:{[i]:s}}}:ke(n)?ht(n,i,s):{[n]:{[i]:s}}}throw new D({A_Expr:e},`A_Expr kind: ${e.kind}`)}BoolExpr(e){let n=e.args??[];switch(e.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 D({BoolExpr:e},`BoolExpr op: ${e.boolop}`)}}NullTest(e){let n=e.arg?this.deparseValue(e.arg):void 0,r=e.nulltesttype==="IS_NULL"?"$is":"$isNot";return Re(n)?{$storageFolder:{column:n.column,index:n.index,ops:{[r]:null}}}:ke(n)?ht(n,r,null):{[n]:{[r]:null}}}SubLink(e){if(e.subLinkType==="ANY_SUBLINK"){let n=e.testexpr?this.deparseValue(e.testexpr):void 0,r=e.subselect?this.SelectStmt(e.subselect.SelectStmt):void 0;return {[n]:{$in:r}}}if(e.subLinkType==="EXISTS_SUBLINK")return {$exists:e.subselect?this.SelectStmt(e.subselect.SelectStmt):void 0};if(e.subLinkType==="EXPR_SUBLINK"){let n=e.subselect?e.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 D({SubLink:e},`SubLink type: ${e.subLinkType}`)}SelectStmt(e){let{from:n,schema:r,join:i}=this.deparseFromClause(e.fromClause??[]),s=[];for(let u of e.targetList??[]){let p="ResTarget"in u?u.ResTarget:void 0;if(p?.val){let d=this.deparseValue(p.val);Array.isArray(d)?s.push(...d.map(String)):d!=null&&d!==""&&s.push(String(d));}}let o=e.whereClause?this.deparse(e.whereClause):void 0,a=this.deparseSortClause(e.sortClause),c=this.deparseLimit(e.limitCount),l=this.deparseLimit(e.limitOffset),f=this.deparseGroupClause(e.groupClause),m={type:"query",from:n,select:s};return r&&(m.schema=r),Object.keys(i).length>0&&(m.join=i),o&&(m.where=o),a.length>0&&(m.order=a),c!==void 0&&(m.limit=c),l!==void 0&&(m.offset=l),f.length>0&&(m.group=f),m}FuncCall(e){let n=this.isAuthFunc(e.funcname??[]);if(n)return n;let r=M(e.funcname??[]);if(r.length===2&&r[0]==="storage"&&r[1]==="operation"&&(e.args?.length??0)===0)return "{{storage.operation}}";if(r.length===2&&r[0]==="storage"&&(r[1]==="filename"||r[1]==="extension")){let i=e.args?.[0];if(e.args?.length!==1||!i||!("ColumnRef"in i))throw new D({FuncCall:e},`storage.${r[1]} requires one column argument`);let s=this.ColumnRef(i.ColumnRef);if(s!=="name")throw new D({FuncCall:e},`only storage.${r[1]}(name) is supported`);return {kind:`storage.${r[1]}`,column:s}}throw new D({FuncCall:e},`FuncCall: ${M(e.funcname??[]).join(".")}`)}storageOperationPredicate(e){let n=M(e.funcname??[]);if(n.length!==2||n[0]!=="storage"||n[1]!=="allow_only_operation"&&n[1]!=="allow_any_operation")return null;let r=e.args?.[0],i;if(n[1]==="allow_only_operation"&&e.args?.length===1&&r)i=[this.deparseValue(r)];else if(n[1]==="allow_any_operation"&&e.args?.length===1&&r)if("A_ArrayExpr"in r)i=(r.A_ArrayExpr.elements??[]).map(o=>this.deparseValue(o));else if(this.deparseValue(r)===null)i=[];else throw new D({FuncCall:e},`storage.${n[1]} requires its canonical operation argument`);else throw new D({FuncCall:e},`storage.${n[1]} requires its canonical operation argument`);if(!i.every(o=>o===null||typeof o=="string"))throw new D({FuncCall:e},`storage.${n[1]} requires text operation names`);let s=i.filter(o=>typeof o=="string"&&o!=="").map(wc);return n[1]==="allow_only_operation"&&s.length===0?{$always:false}:{"{{storage.normalizedOperation}}":n[1]==="allow_only_operation"?{$eq:s[0]}:{$in:s.filter(Boolean)}}}ColumnRef(e){let n=M(e.fields??[]);return n.length===1?n[0]:n.join(".")}A_Const(e){if(e.boolval!==void 0)return e.boolval.boolval;if(e.ival!==void 0)return e.ival.ival??0;if(e.fval!==void 0)return parseFloat(e.fval.fval??"0");if(e.sval!==void 0)return e.sval.sval??"";if(e.isnull)return null;throw new D({A_Const:e},"A_Const: unknown variant")}TypeCast(e){if(!e.arg)throw new D({TypeCast:e},"TypeCast: missing arg");return this.deparseValue(e.arg)}A_Indirection(e){let n=e.arg?.FuncCall,r=n?M(n.funcname??[]):[],i=e.indirection??[],s=i[0]?.A_Indices,o=s?.uidx?.A_Const,a=o?this.A_Const(o):void 0,c=n?.args?.[0];if(r.length!==2||r[0]!=="storage"||r[1]!=="foldername"||!c||!("ColumnRef"in c)||i.length!==1||s?.is_slice===true||s?.lidx!=null||typeof a!="number"||!Number.isInteger(a)||a<1)throw new D({A_Indirection:e},"only indexed storage.foldername(column) expressions are supported");let l=this.ColumnRef(c.ColumnRef);if(l!=="name")throw new D({A_Indirection:e},"only indexed storage.foldername(name) expressions are supported");return {kind:"storage.foldername",column:l,index:a}}BooleanTest(e){let n=e.arg?this.deparseValue(e.arg):void 0;return e.booltesttype==="IS_TRUE"?{[n]:{$eq:true}}:{[n]:{$eq:false}}}deparseFromClause(e){let n={};if(e.length===0)return {from:"",join:n};let r=e[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(e,n){let r={from:""};if(e.larg)if("RangeVar"in e.larg){let i=e.larg.RangeVar;r={from:i.relname??"",schema:i.schemaname};}else "JoinExpr"in e.larg&&(r=this.walkJoinExpr(e.larg.JoinExpr,n));if(e.rarg&&"RangeVar"in e.rarg){let i=e.rarg.RangeVar,s=i.relname??"",o=i.alias?.aliasname??s,a=e.jointype==="JOIN_LEFT"?"left":"inner",c={from:s,type:a};e.quals&&(c.on=this.deparse(e.quals));let l=o;if(l in n){let f=2;for(;`${l}_${f}`in n;)f++;l=`${l}_${f}`;}n[l]=c;}return r}deparseSortClause(e){if(!e)return [];let n=[];for(let r of e){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(e){if(!e)return;let n=this.deparseValue(e);return typeof n=="number"?n:Number(n)}deparseGroupClause(e){return e?e.map(n=>String(this.deparseValue(n))):[]}isAuthFunc(e){let n=M(e);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(e){if(e.kind!=="AEXPR_OP")return null;let n=e.name?.[0]?Ge(e.name[0]):void 0;if(n!=="->"&&n!=="->>")return null;let r=e.rexpr&&"A_Const"in e.rexpr?e.rexpr.A_Const.sval?.sval:void 0;if(r===void 0)return null;if(e.lexpr&&"FuncCall"in e.lexpr)return this.isAuthFunc(e.lexpr.FuncCall.funcname??[])==="{{auth.jwt}}"?`{{auth.jwt.${r}}}`:null;if(e.lexpr&&"A_Expr"in e.lexpr){let i=this.isJwtAccessor(e.lexpr.A_Expr);if(i)return `${i.slice(0,-2)}.${r}}}`}return null}mapOperator(e){switch(e){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 Ie,Yi=F(()=>{Ie=class t{constructor(e){this.data=e;}appliesTo(e){return this.data.command==="ALL"||this.data.command===e}appliesToRole(e){return this.data.roles.length===0||this.data.roles.includes(e)}toJSON(){return this.data}static fromJSON(e){return new t(e)}};});var gt,Jn=F(()=>{gt=class extends Error{constructor(n,r,i,s){super(`check constraint "${i}" violated for ${n}.${r}`);this.table=n;this.column=r;this.constraint=i;this.value=s;this.name="CheckConstraintError";}};});var J,Se=F(()=>{Jn();J=class{context;factoryExtra;constructor(e){this.context=e;}get isShimBacked(){return false}checkConstraint(){return null}serialize(e){return e}deserialize(e){return e}validateStorage(e){return {status:"pass",message:null}}validationFail(e,n){return {status:"fail",message:e,action:n}}validationPass(){return {status:"pass",message:null}}isNullish(e){return e==null}toColumnDDL(e){let{includeNullable:n=true}=e??{},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(e,n){return new gt(this.context.table,this.context.column,e,n)}quoteIfNeeded(e){return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)?e:`"${e}"`}};});var Fe,an=F(()=>{Se();Fe=class extends J{get sqliteType(){return "INTEGER"}};});var yt,Yn=F(()=>{an();yt=class extends Fe{constructor(e){super({...e,isSerial:true});}};});function Ec(t,e){let{precision:n,scale:r}=e,i=10**r,s=10**(n-r);return Math.abs(Math.round(t*i)-t*i)<1e-4&&Math.abs(t)<s}var bt,Qn=F(()=>{Se();bt=class extends J{numericPrecision;constructor(e,n){super(e),this.numericPrecision=n;}get isShimBacked(){return this.numericPrecision!==void 0}get sqliteType(){return "REAL"}checkConstraint(){if(this.numericPrecision){let{precision:e,scale:n}=this.numericPrecision,r=this.context.column,i=10**n,s=10**(e-n);return `ABS(ROUND(${r} * ${i}) - ${r} * ${i}) < 0.0001 AND ABS(${r}) < ${s}`}return null}validateStorage(e){if(this.isNullish(e))return this.validationPass();if(typeof e!="number"||!Number.isFinite(e))return this.validationFail("Expected finite number.","Patch rows with finite numbers.");if(this.numericPrecision){let{precision:n,scale:r}=this.numericPrecision;if(!Ec(e,this.numericPrecision))return this.validationFail(`Does not fit numeric(${n}, ${r}).`,"Patch rows within numeric precision.")}return this.validationPass()}};});var K,ce=F(()=>{Se();K=class extends J{lengthConstraint;constructor(e,n){super(e),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(e){return this.isNullish(e)?this.validationPass():typeof e!="string"?this.validationFail("Expected text.","Patch rows with text values."):this.lengthConstraint!==void 0&&Array.from(e).length>this.lengthConstraint?this.validationFail(`Exceeds length ${this.lengthConstraint}.`,"Patch rows with shorter text."):this.validationPass()}};});var wt,Zn=F(()=>{Se();wt=class extends J{get sqliteType(){return "BLOB"}};});var xt,er=F(()=>{Se();xt=class extends J{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}checkConstraint(){return `${this.context.column} IN (0, 1)`}serialize(e){if(this.isNullish(e))return e;if(e===true||e===1)return 1;if(e===false||e===0)return 0;throw this.checkError("boolean_range",e)}deserialize(e){if(this.isNullish(e)||e===true||e===false)return e;if(typeof e=="number"&&Number.isFinite(e)){if(e===1)return true;if(e===0)return false}return e===1n?true:e===0n?false:e==="1"||e==="true"?true:e==="0"||e==="false"?false:e}validateStorage(e){return this.isNullish(e)?this.validationPass():e===1||e===0?this.validationPass():this.validationFail("Expected 0 or 1.","Patch rows with boolean values.")}};});function Qi(t){try{return {ok:!0,value:JSON.parse(t)}}catch{return {ok:false}}}var St,tr=F(()=>{Se();St=class extends J{get isShimBacked(){return true}get sqliteType(){return "TEXT"}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR json_valid(${e})`}serialize(e){if(this.isNullish(e))return e;try{return JSON.stringify(e)}catch{throw this.checkError("json_valid",e)}}deserialize(e){if(this.isNullish(e))return e;if(typeof e=="string"){let n=Qi(e);return n.ok?n.value:e}return e}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"?this.validationFail("Expected JSON text.","Patch rows with JSON values."):Qi(e).ok?this.validationPass():this.validationFail("Invalid JSON text.","Patch rows with valid JSON.")}};});function _c(t){if(!/^\d{4}-\d{2}-\d{2}$/.test(t))return false;let e=new Date(`${t}T00:00:00.000Z`);return !Number.isNaN(e.getTime())&&e.toISOString().slice(0,10)===t}var Et,nr=F(()=>{ce();Et=class extends K{get isShimBacked(){return true}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR date(${e}) IS NOT NULL`}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!_c(e)?this.validationFail("Invalid date.","Patch rows with YYYY-MM-DD dates."):this.validationPass()}};});function Tc(t){let e=t.match(/^(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?([+-](\d{2}):?(\d{2}))?$/);if(!e)return false;let n=Number(e[1]),r=Number(e[2]),i=e[3]===void 0?0:Number(e[3]),s=e[5]===void 0?null:Number(e[5]),o=e[6]===void 0?null:Number(e[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 _t,rr=F(()=>{ce();_t=class extends K{get isShimBacked(){return true}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR time(${e}) IS NOT NULL`}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!Tc(e)?this.validationFail("Invalid time.","Patch rows with HH:MM[:SS] times."):this.validationPass()}};});function Ac(t){let e=t.match(/^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?(?:Z|([+-](\d{2}):?(\d{2})))?$/);if(!e)return false;let n=Number(e[1]),r=Number(e[2]),i=Number(e[3]),s=Number(e[4]),o=Number(e[5]),a=e[6]===void 0?0:Number(e[6]),c=e[8]===void 0?null:Number(e[8]),l=e[9]===void 0?null:Number(e[9]),f=new Date(Date.UTC(n,r-1,i)),m=f.getUTCFullYear()===n&&f.getUTCMonth()===r-1&&f.getUTCDate()===i,u=s<=24&&o<=59&&a<=59&&(s!==24||o===0&&a===0),p=c===null||l!==null&&c<=15&&l<=59;return m&&u&&p}var Tt,ir=F(()=>{ce();Tt=class extends K{get isShimBacked(){return true}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR datetime(${e}) IS NOT NULL`}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!Ac(e)?this.validationFail("Invalid timestamp.","Patch rows with ISO timestamps."):this.validationPass()}};});var At,sr=F(()=>{ce();At=class extends K{get isShimBacked(){return true}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||e.trim().length===0?this.validationFail("Expected interval text.","Patch rows with interval strings."):/^-?\d+(?:\.\d+)?$/.test(e.trim())?this.validationFail("Ambiguous numeric interval.","Patch rows with explicit interval strings."):this.validationPass()}};});var Ct,or=F(()=>{ce();Ct=class extends K{enumValues;constructor(e,n){super(e),this.enumValues=n;}get isShimBacked(){return true}checkConstraint(){let e=this.context.column,n=this.enumValues.map(r=>`'${r.replace(/'/g,"''")}'`).join(", ");return `${e} IN (${n})`}serialize(e){if(this.isNullish(e))return e;if(typeof e!="string"||!this.enumValues.includes(e))throw this.checkError("enum_membership",e);return e}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!this.enumValues.includes(e)?this.validationFail("Invalid enum value.","Patch rows with declared enum values."):this.validationPass()}};});function Zi(t){try{return {ok:!0,value:JSON.parse(t)}}catch{return {ok:false}}}var We,ar=F(()=>{Se();We=class extends J{elementField;constructor(e,n){super(e),this.elementField=n;}get sqliteType(){return "TEXT"}get isShimBacked(){return true}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR (json_valid(${e}) AND json_type(${e}) = 'array')`}serialize(e){if(this.isNullish(e))return e;if(!Array.isArray(e))throw this.checkError("array_type",e);return this.elementField?JSON.stringify(e.map(n=>this.elementField.serialize(n))):JSON.stringify(e)}deserialize(e){if(this.isNullish(e))return e;if(typeof e=="string"){let n=Zi(e);if(n.ok&&Array.isArray(n.value))return this.elementField?n.value.map(r=>this.elementField.deserialize(r)):n.value}return e}validateStorage(e){if(this.isNullish(e))return this.validationPass();if(typeof e!="string")return this.validationFail("Expected JSON array text.","Patch rows with array values.");let n=Zi(e);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 es(t){return Rc.test(t.toLowerCase())}var Cc,Rc,Rt,lr=F(()=>{ce();Cc="????????-????-????-????-????????????",Rc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;Rt=class extends K{get isShimBacked(){return true}checkConstraint(){let e=this.quoteIfNeeded(this.context.column);return `${e} IS NULL OR ${e} GLOB '${Cc}'`}serialize(e){if(this.isNullish(e))return e;if(typeof e!="string")throw this.checkError("uuid_format",e);let n=e.toLowerCase();if(!es(n))throw this.checkError("uuid_format",e);return n}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!es(e)?this.validationFail("Invalid UUID.","Patch rows with valid UUIDs."):this.validationPass()}};});function kc(t){let e=t.split("/");if(e.length>2)return null;let n=e[0];if(!n)return null;if(e.length===1)return {address:n,prefix:null};let r=e[1];return !r||!/^\d+$/.test(r)?null:{address:n,prefix:Number(r)}}function $c(t){let e=t.split(".");return e.length!==4?false:e.every(n=>{if(!/^\d+$/.test(n))return false;let r=Number(n);return r>=0&&r<=255})}function Nc(t){if(!t.includes(":"))return false;try{return new URL(`http://[${t}]/`),!0}catch{return false}}function ts(t){let e=kc(t);return e?$c(e.address)?e.prefix===null||e.prefix>=0&&e.prefix<=32:Nc(e.address)?e.prefix===null||e.prefix>=0&&e.prefix<=128:false:false}var kt,cr=F(()=>{ce();kt=class extends K{get isShimBacked(){return true}checkConstraint(){let e=this.quoteIfNeeded(this.context.column);return `${e} IS NULL OR (length(${e}) BETWEEN 3 AND 49 AND (instr(${e}, '.') > 0 OR instr(${e}, ':') > 0))`}serialize(e){if(this.isNullish(e))return e;if(typeof e!="string")throw this.checkError("inet_format",e);let n=e.trim();if(!ts(n))throw this.checkError("inet_format",e);return n}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!ts(e.trim())?this.validationFail("Invalid inet address.","Patch rows with valid inet strings."):this.validationPass()}};});var $t,ur=F(()=>{ce();$t=class extends K{serialize(e){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}deserialize(e){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 ue(t,e){let n=Kc(t,e);if(e){let{enumValues:r,...i}=e;n.factoryExtra=i;}return n}function Kc(t,e){if(e?.isArray){let r=ue(t,{...e,isArray:false});return new We(t,r)}if(e?.enumValues)return new Ct(t,e.enumValues);let n=t.pgTypeName.toLowerCase().trim();if(n.startsWith("_")||n.endsWith("[]")){let r=n.startsWith("_")?n.slice(1):n.slice(0,-2),i={...t,pgTypeName:r},s=ue(i);return new We(t,s)}return Oc.has(n)?new yt(t):vc.has(n)?new Fe(t):Fc.has(n)?new xt(t):Dc.has(n)?new St(t):Uc.has(n)?new Et(t):Bc.has(n)?new _t(t):Hc.has(n)?new Tt(t):Vc.has(n)?new At(t):Ic.has(n)?new wt(t):Pc.has(n)?new bt(t,e?.numericPrecision):jc.has(n)?new Rt(t):Mc.has(n)?new K(t,63):qc.has(n)?new kt(t):Lc.has(n)?new K(t,e?.lengthConstraint):new $t(t)}var vc,Oc,Pc,Lc,Ic,Fc,Dc,jc,Mc,qc,Uc,Bc,Hc,Vc,ns=F(()=>{an();Yn();Qn();ce();Zn();er();tr();nr();rr();ir();sr();or();ar();lr();cr();ur();vc=new Set(["int2","smallint","int4","integer","int","int8","bigint"]),Oc=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]),Pc=new Set(["float4","real","float8","double precision","numeric","decimal"]),Lc=new Set(["text","varchar","character varying","char","character","bpchar"]),Ic=new Set(["bytea"]),Fc=new Set(["bool","boolean"]),Dc=new Set(["json","jsonb"]),jc=new Set(["uuid"]),Mc=new Set(["name"]),qc=new Set(["inet"]),Uc=new Set(["date"]),Bc=new Set(["time","timetz","time without time zone","time with time zone"]),Hc=new Set(["timestamp","timestamptz","timestamp without time zone","timestamp with time zone"]),Vc=new Set(["interval"]);});var rs=F(()=>{});var De,is=F(()=>{De=class{table;schema;fields;constructor(e,n="public",r=new Map){this.table=e,this.schema=n,this.fields=r;}get(e){return this.fields.get(e)}has(e){return this.fields.has(e)}set(e,n){this.fields.set(e,n);}columns(){return Array.from(this.fields.keys())}all(){return Array.from(this.fields.values())}serializeRow(e){let n={};for(let[r,i]of Object.entries(e)){let s=this.fields.get(r);n[r]=s?s.serialize(i):i;}return n}deserializeRow(e){let n={};for(let[r,i]of Object.entries(e)){let s=this.fields.get(r);n[r]=s?s.deserialize(i):i;}return n}applyDefaults(e){let n={...e};for(let[r,i]of this.fields)!(r in n)&&i.context.defaultFn&&(n[r]=i.context.defaultFn());return n}};});var ss=F(()=>{Se();Jn();an();Yn();Qn();ce();Zn();er();tr();nr();rr();ir();sr();or();ar();lr();cr();ur();ns();rs();is();});var ls={};Ns(ls,{_resetWarnedMissingToClauseForTests:()=>Gc,collectComments:()=>Yc,collectEnums:()=>Wc,collectPolicies:()=>zc,collectSchema:()=>dr,collectTableConstraints:()=>Jc,collectVariables:()=>Xc,lookupEnumValue:()=>$e});function Gc(){mr.clear();}function Wc(t){let e=new Map,n=s=>{let o=s.toLowerCase();return o.startsWith("public.")?[o,o.slice(7)]:o.includes(".")?[o]:[o,`public.${o}`]},r=(s,o)=>{for(let a of n(s))e.set(a,o);},i=s=>{for(let o of n(s))e.delete(o);};for(let s of t.stmts??[])if(s.stmt){if("CreateEnumStmt"in s.stmt){let o=s.stmt.CreateEnumStmt,a=M(o.typeName??[]).join(".");a&&o.vals&&r(a,M(o.vals));continue}if("AlterEnumStmt"in s.stmt){let o=s.stmt.AlterEnumStmt,a=M(o.typeName??[]).join("."),c=$e(e,a);if(!a||!c||!o.newVal)continue;let l=[...c];if(o.oldVal){let u=l.indexOf(o.oldVal);u!==-1&&(l[u]=o.newVal),r(a,l);continue}if(c.includes(o.newVal))continue;let f=o.newValNeighbor?l.indexOf(o.newValNeighbor):-1,m=f===-1?l.length:f+(o.newValIsAfter===true?1:0);l.splice(m,0,o.newVal),r(a,l);continue}if("RenameStmt"in s.stmt&&s.stmt.RenameStmt.renameType==="OBJECT_TYPE"){let o=s.stmt.RenameStmt,a=o.object&&"List"in o.object?M(o.object.List.items??[]):[],c=a.join("."),l=$e(e,c);if(!c||!o.newname||!l)continue;i(c),r([...a.slice(0,-1),o.newname].join("."),l);continue}if("DropStmt"in s.stmt&&s.stmt.DropStmt.removeType==="OBJECT_TYPE")for(let o of s.stmt.DropStmt.objects??[])"TypeName"in o&&i(M(o.TypeName.names??[]).join("."));}return e}function $e(t,e){let n=e.toLowerCase(),r=t.get(n);return r||(n.startsWith("public.")?t.get(n.slice(7)):t.get(`public.${n}`))}function Xc(t){let e=new Map;for(let n of t.stmts??[]){if(!n.stmt||!("VariableSetStmt"in n.stmt))continue;let r=n.stmt.VariableSetStmt,i=r.name,s=Gi(r.args?.[0]??{});e.set(i,{value:s,local:r.is_local});}return e}function os(t){let e=[],n=false;for(let r of t??[])if("RoleSpec"in r){let i=r.RoleSpec;i.roletype==="ROLESPEC_PUBLIC"?i.location===-1&&(n=true):i.roletype==="ROLESPEC_CSTRING"&&i.rolename&&e.push(i.rolename);}return {roles:e,implicitPublic:n}}function ln(t,e){return t&&t.length>0?t:e}function fr(t,e,n){return t.findIndex(r=>r.data.name===e.name&&r.data.table===e.table&&ln(r.data.schema,n)===ln(e.schema,n))}function pr(t,e){return new Error(`policy "${t}" for table "${e}" does not exist`)}function as(t,e,n,r){return t.data.table===e&&ln(t.data.schema,r)===ln(n,r)}function zc(t,e={}){let n=e.defaultSchema||"public",r=e.validateMutations===true,i=new on,s=new Set,o=[];for(let a of t.stmts??[])if(a.stmt){if("CreatePolicyStmt"in a.stmt){let c=a.stmt.CreatePolicyStmt,l=c.table?.relname??"",f=c.table?.schemaname,m={select:"SELECT",insert:"INSERT",update:"UPDATE",delete:"DELETE"},u=c.cmd_name?m[c.cmd_name]??"ALL":"ALL",p=c.permissive===true,{roles:d,implicitPublic:b}=os(c.roles),S=c.qual?i.deparse(c.qual):void 0,v=c.with_check?i.deparse(c.with_check):void 0;if(b){let I=f?`${f}.${l}`:l,z=c.policy_name??"",N=`${I}::${z}`;if(!mr.has(N)){mr.add(N);let O=JSON.stringify(S)+JSON.stringify(v);/\{\{auth\.(uid|jwt|role)/i.test(O)||console.warn(`[supalite] policy "${z}" on "${I}" has no TO clause \u2014 applies to all roles (PUBLIC). For clarity, prefer an explicit \`TO <role>\` clause (e.g. \`TO authenticated\`).`);}}let E=new Ie({name:c.policy_name??"",table:l,schema:f,command:u,permissive:p,roles:d,using:S,withCheck:v});o.push(E);}if("DropStmt"in a.stmt&&a.stmt.DropStmt.removeType==="OBJECT_POLICY"){let c=a.stmt.DropStmt,l=c.objects?.[0];if(l&&"List"in l){let f=M(l.List.items??[]),m=f[f.length-1],u=f[f.length-2],p=f.length>=3?f[f.length-3]:void 0;if(m&&u){let d=fr(o,{name:m,table:u,schema:p},n);if(d!==-1)o.splice(d,1);else if(r&&!c.missing_ok)throw pr(m,u)}}}if("AlterPolicyStmt"in a.stmt){let c=a.stmt.AlterPolicyStmt,l=c.policy_name??"",f=c.table?.relname??"",m=c.table?.schemaname,u=fr(o,{name:l,table:f,schema:m},n);if(u===-1){if(r)throw pr(l,f);continue}let p=o[u].data,d=c.roles?os(c.roles).roles:p.roles,b=c.qual?i.deparse(c.qual):p.using,S=c.with_check?i.deparse(c.with_check):p.withCheck;o[u]=new Ie({...p,roles:d,using:b,withCheck:S});}if("RenameStmt"in a.stmt&&a.stmt.RenameStmt.renameType==="OBJECT_POLICY"){let c=a.stmt.RenameStmt,l=c.subname??"",f=c.relation?.relname??"",m=c.relation?.schemaname,u=fr(o,{name:l,table:f,schema:m},n);if(u===-1){if(r)throw pr(l,f);continue}c.newname&&(o[u]=new Ie({...o[u].data,name:c.newname}));}if("RenameStmt"in a.stmt&&a.stmt.RenameStmt.renameType==="OBJECT_TABLE"){let c=a.stmt.RenameStmt,l=c.relation?.relname??"",f=c.newname??"",m=c.relation?.schemaname;if(l&&f&&l!==f){s.delete(l)&&s.add(f);for(let u=0;u<o.length;u++)as(o[u],l,m,n)&&(o[u]=new Ie({...o[u].data,table:f}));}}if("DropStmt"in a.stmt&&a.stmt.DropStmt.removeType==="OBJECT_TABLE")for(let c of a.stmt.DropStmt.objects??[]){if(!("List"in c))continue;let l=M(c.List.items??[]),f=l[l.length-1],m=l.length>=2?l[l.length-2]:void 0;if(f){s.delete(f);for(let u=o.length-1;u>=0;u--)as(o[u],f,m,n)&&o.splice(u,1);}}if("AlterTableStmt"in a.stmt){let c=a.stmt.AlterTableStmt,l=c.relation?.relname??"";for(let f of c.cmds??[]){if(!("AlterTableCmd"in f))continue;let m=f.AlterTableCmd.subtype;m==="AT_EnableRowSecurity"?s.add(l):m==="AT_DisableRowSecurity"&&s.delete(l);}}}return {policies:o,tables:s}}function Xe(t,e=new Set){if(Array.isArray(t)){for(let i of t)Xe(i,e);return e}if(!t||typeof t!="object")return e;let n=t,r=n.ColumnRef;if(r?.fields){let i=M(r.fields),s=i[i.length-1];s&&s!=="*"&&e.add(s);}for(let i of Object.values(n))Xe(i,e);return e}function Q(t,e,n){if(n.length===0)return;let r=e==="unique"?"key":e==="foreign_key"?"fkey":"check";return `${t}_${n.join("_")}_${r}`}function dr(t,e,n){let r=new Map;for(let i of t.stmts??[])if(i.stmt){if("CreateStmt"in i.stmt){let s=i.stmt.CreateStmt,o=s.relation?.relname??"",a=s.relation?.schemaname??"public";if(!o)continue;let c=`${a}.${o}`;if(s.if_not_exists&&r.has(c))continue;let l=new De(o,a);for(let m of s.tableElts??[]){if(!("ColumnDef"in m))continue;let u=m.ColumnDef,p=u.colname;if(!p)continue;let d=u.typeName?.names?.map(_=>_.String?.sval||_.String?.str).filter(Boolean),b=d&&d.length>0?d.length===2&&d[0]==="pg_catalog"?d[1]:d.join("."):void 0;if(!b)continue;let S=!!u.typeName?.arrayBounds?.length,v=Array.isArray(u.typeName?.typmods)?u.typeName.typmods:[],E=_=>v[_]?.A_Const?.ival?.ival??v[_]?.A_Const?.val?.ival?.ival,I={isArray:S};if(Xi(b)&&v.length>0){let _=E(0);typeof _=="number"&&_>0&&(I.lengthConstraint=_);}if(zi(b)&&v.length>=2){let _=E(0),$=E(1);typeof _=="number"&&typeof $=="number"&&_>0&&$>=0&&(I.numericPrecision={precision:_,scale:$});}let z=$e(e,b);z&&(I.enumValues=z);let N=Array.isArray(u.constraints)?u.constraints:[],O=N.some(_=>_.Constraint?.contype==="CONSTR_PRIMARY"),P=N.find(_=>_.Constraint?.contype==="CONSTR_DEFAULT"),T=Wi(b)||n?.has(u)===true||N.some(_=>_.Constraint?.contype==="CONSTR_IDENTITY")||M(P?.Constraint?.raw_expr?.FuncCall?.funcname??[]).join(".")==="nextval",C=N.some(_=>_.Constraint?.contype==="CONSTR_NOTNULL"),h=N.find(_=>_.Constraint?.contype==="CONSTR_UNIQUE"),Y=N.find(_=>_.Constraint?.contype==="CONSTR_GENERATED"),V=N.find(_=>_.Constraint?.contype==="CONSTR_FOREIGN"),q=N.find(_=>_.Constraint?.contype==="CONSTR_CHECK"),g;if(V){let _=V.Constraint,$=_.pktable?.relname,U=_.pktable?.schemaname,ie=_.pk_attrs?.[0]?.String?.sval;$&&ie&&(g={refSchema:U,refTable:$,refColumn:ie,constraintName:_.conname||Q(o,"foreign_key",[p])});}let y={schema:a,table:o,column:p,pgTypeName:b,nullable:!C&&!O,defaultValue:null,defaultFn:null,isPrimaryKey:O,isUnique:!!h,isSerial:T,isGenerated:!!Y,fkRef:g,hasCheck:!!q,checkConstraintName:q?q.Constraint?.conname||Q(o,"check",[p]):void 0,uniqueConstraintName:h?h.Constraint?.conname||Q(o,"unique",[p]):void 0};l.set(p,ue(y,I));}let f=(m,u)=>{let p=l.get(m);if(!p)return;let d={...p.context,...u},b=$e(e,d.pgTypeName);l.set(m,ue(d,{...p.factoryExtra,...b?{enumValues:b}:{}}));};for(let m of s.tableElts??[]){if(!("Constraint"in m))continue;let u=m.Constraint,p=M(u.keys??[]);if(u.contype==="CONSTR_PRIMARY")for(let d of p)f(d,{isPrimaryKey:true,nullable:false});else if(u.contype==="CONSTR_UNIQUE"&&p.length===1)f(p[0],{isUnique:true,uniqueConstraintName:u.conname||Q(o,"unique",p)});else if(u.contype==="CONSTR_FOREIGN"&&p.length===1){let d=u.pktable?.relname,b=M(u.pk_attrs??[])[0];d&&b&&f(p[0],{fkRef:{refSchema:u.pktable?.schemaname,refTable:d,refColumn:b,constraintName:u.conname||Q(o,"foreign_key",p)}});}else if(u.contype==="CONSTR_CHECK"){let d=[...Xe(u.raw_expr)];d.length===1&&f(d[0],{hasCheck:true,checkConstraintName:u.conname||Q(o,"check",d)});}}r.set(c,l);continue}if("RenameStmt"in i.stmt){let s=i.stmt.RenameStmt,o=s.relation?.schemaname??"public",a=s.relation?.relname??"",c=r.get(`${o}.${a}`);if(!c)continue;let l=s.renameType==="OBJECT_TABLE"?s.newname:void 0,f=s.renameType==="OBJECT_COLUMN"?s.newname:void 0,m=s.renameType==="OBJECT_COLUMN"?s.subname:void 0;if(!l&&!(f&&m))continue;let u=l??a,p=new De(u,o);for(let d of c.all()){let b=d.context.column===m?f:d.context.column,S={...d.context,table:u,column:b},v=$e(e,S.pgTypeName);p.set(b,ue(S,{...d.factoryExtra,...v?{enumValues:v}:{}}));}r.delete(`${o}.${a}`),r.set(`${o}.${u}`,p);for(let d of r.values())for(let b of d.all()){let S=b.context.fkRef;if(!S||(S.refSchema??"public")!==o||S.refTable!==a)continue;let v=m&&S.refColumn===m?f:S.refColumn,E={...b.context,fkRef:{...S,refTable:u,refColumn:v}},I=$e(e,E.pgTypeName);d.set(E.column,ue(E,{...b.factoryExtra,...I?{enumValues:I}:{}}));}continue}if("AlterTableStmt"in i.stmt){let s=i.stmt.AlterTableStmt,o=s.relation?.relname??"",a=s.relation?.schemaname??"public",c=`${a}.${o}`,l=r.get(c);if(!l)continue;let f=(m,u,p)=>{let d=l.get(m);if(!d)return;let b={...d.context,...u},S=$e(e,b.pgTypeName);l.set(m,ue(b,{...p??d.factoryExtra,...S?{enumValues:S}:{}}));};for(let m of s.cmds??[]){if(!("AlterTableCmd"in m))continue;let u=m.AlterTableCmd;if(u.subtype==="AT_AddColumn"&&u.def&&"ColumnDef"in u.def){let p=dr({stmts:[{stmt:{CreateStmt:{relation:s.relation,tableElts:[u.def]}}}]},e,n).get(c)?.all()[0];p&&l.set(p.context.column,p);continue}if(u.subtype==="AT_AlterColumnType"&&u.name&&u.def&&"ColumnDef"in u.def){let p=dr({stmts:[{stmt:{CreateStmt:{relation:s.relation,tableElts:[{ColumnDef:{...u.def.ColumnDef,colname:u.name}}]}}}]},e,n).get(c)?.get(u.name);p&&f(u.name,{pgTypeName:p.context.pgTypeName,isSerial:p.context.isSerial},p.factoryExtra);continue}if(u.subtype==="AT_SetNotNull"&&u.name){f(u.name,{nullable:false});continue}if(u.subtype==="AT_DropNotNull"&&u.name){let p=l.get(u.name);f(u.name,{nullable:!p?.context.isPrimaryKey});continue}if(u.subtype==="AT_AddConstraint"&&u.def&&"Constraint"in u.def){let p=u.def.Constraint,d=M(p.keys??p.fk_attrs??[]);if(p.contype==="CONSTR_PRIMARY")for(let b of d)f(b,{isPrimaryKey:true,nullable:false});else if(p.contype==="CONSTR_UNIQUE"&&d.length===1)f(d[0],{isUnique:true,uniqueConstraintName:p.conname||Q(o,"unique",d)});else if(p.contype==="CONSTR_FOREIGN"&&d.length===1){let b=p.pktable?.relname,S=M(p.pk_attrs??[])[0];b&&S&&f(d[0],{fkRef:{refSchema:p.pktable?.schemaname,refTable:b,refColumn:S,constraintName:p.conname||Q(o,"foreign_key",d)}});}else if(p.contype==="CONSTR_CHECK"){let b=[...Xe(p.raw_expr)];b.length===1&&f(b[0],{hasCheck:true,checkConstraintName:p.conname||Q(o,"check",b)});}continue}if(u.subtype==="AT_DropConstraint"&&u.name){for(let p of l.all()){let d=p.context;d.uniqueConstraintName===u.name&&f(d.column,{isUnique:false,uniqueConstraintName:void 0}),d.checkConstraintName===u.name&&f(d.column,{hasCheck:false,checkConstraintName:void 0}),d.fkRef?.constraintName===u.name&&f(d.column,{fkRef:void 0});}continue}if(u.subtype==="AT_DropColumn"&&u.name){let p=new De(o,a);for(let d of l.all())d.context.column!==u.name&&p.set(d.context.column,d);l=p,r.set(c,p);for(let d of r.values())for(let b of d.all()){let S=b.context.fkRef;if((S?.refSchema??"public")===a&&S?.refTable===o&&S.refColumn===u.name){let v={...b.context,fkRef:void 0};d.set(v.column,ue(v,b.factoryExtra));}}}}continue}if("DropStmt"in i.stmt&&i.stmt.DropStmt.removeType==="OBJECT_TABLE")for(let s of i.stmt.DropStmt.objects??[]){if(!("List"in s))continue;let o=M(s.List.items??[]),a=o[o.length-1],c=o.length>=2?o[o.length-2]:"public";if(a){r.delete(`${c}.${a}`);for(let l of r.values())for(let f of l.all()){let m=f.context.fkRef;if((m?.refSchema??"public")===c&&m?.refTable===a){let u={...f.context,fkRef:void 0};l.set(u.column,ue(u,f.factoryExtra));}}}}}return r}function Jc(t){let e=[],n=new Set,r=(i,s,o)=>{let a=i.contype,c=M(i.keys??i.fk_attrs??[]);if(a==="CONSTR_UNIQUE"&&c.length>0)e.push({schema:s,table:o,kind:"unique",name:i.conname||Q(o,"unique",c),columns:c});else if(a==="CONSTR_CHECK"){let l=[...Xe(i.raw_expr)];e.push({schema:s,table:o,kind:"check",name:i.conname||Q(o,"check",l),columns:l});}else if(a==="CONSTR_FOREIGN"){let l=i.pktable?.relname;if(!l)return;e.push({schema:s,table:o,kind:"foreign_key",name:i.conname||Q(o,"foreign_key",c),columns:c,refSchema:i.pktable?.schemaname,refTable:l,refColumns:M(i.pk_attrs??[])});}};for(let i of t.stmts??[]){if(!i.stmt)continue;if("RenameStmt"in i.stmt){let l=i.stmt.RenameStmt,f=l.relation?.schemaname??"public",m=l.relation?.relname;if(!m||!l.newname)continue;if(l.renameType==="OBJECT_TABLE"){n.delete(`${f}.${m}`),n.add(`${f}.${l.newname}`);for(let u of e)u.schema===f&&u.table===m&&(u.table=l.newname),(u.refSchema??"public")===f&&u.refTable===m&&(u.refTable=l.newname);}else if(l.renameType==="OBJECT_COLUMN"&&l.subname)for(let u of e)u.schema===f&&u.table===m&&(u.columns=u.columns.map(p=>p===l.subname?l.newname:p)),(u.refSchema??"public")===f&&u.refTable===m&&(u.refColumns=u.refColumns?.map(p=>p===l.subname?l.newname:p));continue}if("AlterTableStmt"in i.stmt){let l=i.stmt.AlterTableStmt,f=l.relation?.schemaname??"public",m=l.relation?.relname??"";for(let u of l.cmds??[]){if(!("AlterTableCmd"in u))continue;let p=u.AlterTableCmd;if(p.subtype==="AT_AddConstraint"&&p.def&&"Constraint"in p.def)r(p.def.Constraint,f,m);else if(p.subtype==="AT_DropConstraint"&&p.name)for(let d=e.length-1;d>=0;d--){let b=e[d];b.schema===f&&b.table===m&&b.name===p.name&&e.splice(d,1);}else if(p.subtype==="AT_DropColumn"&&p.name)for(let d=e.length-1;d>=0;d--){let b=e[d];(b.schema===f&&b.table===m&&b.columns.includes(p.name)||(b.refSchema??"public")===f&&b.refTable===m&&b.refColumns?.includes(p.name))&&e.splice(d,1);}}continue}if("DropStmt"in i.stmt&&i.stmt.DropStmt.removeType==="OBJECT_TABLE"){for(let l of i.stmt.DropStmt.objects??[]){if(!("List"in l))continue;let f=M(l.List.items??[]),m=f[f.length-1],u=f.length>=2?f[f.length-2]:"public";m&&n.delete(`${u}.${m}`);for(let p=e.length-1;p>=0;p--){let d=e[p];(d.schema===u&&d.table===m||(d.refSchema??"public")===u&&d.refTable===m)&&e.splice(p,1);}}continue}if(!("CreateStmt"in i.stmt))continue;let s=i.stmt.CreateStmt,o=s.relation?.relname??"",a=s.relation?.schemaname??"public";if(!o)continue;let c=`${a}.${o}`;if(!(s.if_not_exists&&n.has(c))){n.add(c);for(let l of s.tableElts??[]){if("ColumnDef"in l){let p=l.ColumnDef,d=p?.colname;if(!d)continue;for(let b of p.constraints??[]){let S=b?.Constraint;if(!S||S.contype!=="CONSTR_FOREIGN")continue;let v=S.pktable?.relname;if(!v)continue;let E=(S.pk_attrs??[]).map(I=>I.String?.sval??I.String?.str).filter(Boolean);e.push({schema:a,table:o,kind:"foreign_key",name:S.conname||Q(o,"foreign_key",[d]),columns:[d],refSchema:S.pktable?.schemaname,refTable:v,refColumns:E});}continue}let f=l;if(!f.Constraint)continue;let m=f.Constraint,u=m.contype;if(u==="CONSTR_UNIQUE"){let p=(m.keys??[]).map(d=>d.String?.sval??d.String?.str).filter(Boolean);if(p.length===0)continue;e.push({schema:a,table:o,kind:"unique",name:m.conname||Q(o,"unique",p),columns:p});}else if(u==="CONSTR_CHECK"){let p=[...Xe(m.raw_expr)];e.push({schema:a,table:o,kind:"check",name:m.conname||Q(o,"check",p),columns:p});}else if(u==="CONSTR_FOREIGN"){let p=(m.fk_attrs??[]).map(S=>S.String?.sval??S.String?.str).filter(Boolean),d=(m.pk_attrs??[]).map(S=>S.String?.sval??S.String?.str).filter(Boolean),b=m.pktable?.relname;if(!b)continue;e.push({schema:a,table:o,kind:"foreign_key",name:m.conname||Q(o,"foreign_key",p),columns:p,refSchema:m.pktable?.schemaname,refTable:b,refColumns:d});}}}}return e}function Yc(t){let e=new Map,n=r=>`${r.schema}.${r.table}.${r.column??""}`;for(let r of t.stmts??[]){if(!r.stmt)continue;if("RenameStmt"in r.stmt){let l=r.stmt.RenameStmt,f=l.relation?.schemaname??"public",m=l.relation?.relname;if(!m||!l.newname)continue;let u=new Map;for(let p of e.values()){if(p.schema!==f||p.table!==m){u.set(n(p),p);continue}let d={...p,table:l.renameType==="OBJECT_TABLE"?l.newname:p.table,column:l.renameType==="OBJECT_COLUMN"&&p.column===l.subname?l.newname:p.column};u.set(n(d),d);}e.clear();for(let[p,d]of u)e.set(p,d);continue}if("AlterTableStmt"in r.stmt){let l=r.stmt.AlterTableStmt,f=l.relation?.schemaname??"public",m=l.relation?.relname??"";for(let u of l.cmds??[])"AlterTableCmd"in u&&u.AlterTableCmd.subtype==="AT_DropColumn"&&u.AlterTableCmd.name&&e.delete(n({schema:f,table:m,column:u.AlterTableCmd.name}));continue}if("DropStmt"in r.stmt&&(r.stmt.DropStmt.removeType==="OBJECT_TABLE"||r.stmt.DropStmt.removeType==="OBJECT_VIEW")){for(let l of r.stmt.DropStmt.objects??[]){if(!("List"in l))continue;let f=M(l.List.items??[]),m=f[f.length-1],u=f.length>=2?f[f.length-2]:"public";for(let[p,d]of e)d.schema===u&&d.table===m&&e.delete(p);}continue}if(!("CommentStmt"in r.stmt))continue;let i=r.stmt.CommentStmt,s=i.objtype,o=(i.object?.List?.items??i.object?.items??[]).map(l=>l.String?.sval??l.String?.str).filter(Boolean);if(o.length===0)continue;let a;if(s==="OBJECT_TABLE"||s==="OBJECT_VIEW"){let[l,f]=o.length>=2?o:["public",o[0]];a={schema:l,table:f};}else if(s==="OBJECT_COLUMN"){let l="public",f,m;o.length>=3?[l,f,m]=o:[f,m]=o,a={schema:l,table:f,column:m};}if(!a)continue;let c=n(a);i.comment===null||i.comment===void 0?e.delete(c):e.set(c,{...a,text:String(i.comment)});}return [...e.values()]}var mr,cs=F(()=>{Ji();nn();Yi();ss();Xn();mr=new Set;});var xr=process.stdin.isTTY?null:(async()=>{let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf8")})();xr&&process.stdin.unref?.();function ae(t,e){Lt.existsSync(t)||(Lt.mkdirSync(t,{recursive:true}),e?.());}function ve(t,e,n){Lt.existsSync(t)||(Lt.writeFileSync(t,e),n?.());}var be=class t{root;constructor(e,n){let r=n??t.projectDir();this.root=le__default.join(r,e??"");}ensureRoot(){ae(this.root);}static homeDir(){return le__default.join(Os.homedir(),".lite")}static projectDir(){return le__default.join(process.cwd(),"supabase")}deleteAll(e=false){try{Lt.rmSync(this.root,{recursive:!0});}catch(n){if(!e)throw n}this.ensureRoot();}delete(e,n=false){try{Lt.unlinkSync(le__default.join(this.root,e));}catch(r){if(!n)throw r}}write(e,n,r=false){try{this.ensureRoot(),Lt.writeFileSync(le__default.join(this.root,e),n);}catch(i){if(!r)throw i}}read(e,n=false){try{return Lt.readFileSync(le__default.join(this.root,e),"utf8")}catch(r){if(!n)throw r}}relativePath(e){return e?le__default.relative(process.cwd(),le__default.join(this.root,e)):this.root}path(e){return e?le__default.join(this.root,e):this.root}};var ze=process.env.LITE_CLOUD_URL??(process.env.LOCAL?"http://localhost:2001":"https://api.lite.dev"),Ft=process.env.LITE_CLOUD_PROJECTS_URL??(process.env.LOCAL?"http://supalite.local":"https://lite.black");var jt=class{root;constructor(e){this.root=e??le__default.join(Os.homedir(),".lite","auth"),ae(this.root);}async getItem(e){try{return Lt.readFileSync(le__default.join(this.root,e+".json"),"utf8")}catch{return null}}async setItem(e,n){Lt.writeFileSync(le__default.join(this.root,e+".json"),n);}async removeItem(e){try{Lt.unlinkSync(le__default.join(this.root,e+".json"));}catch{return}}};var Me=class{constructor(e){this.config=e;this.tempFs=new be(".temp",this.config.root),this.projectFs=new be("supabase",this.config.root),this.schemaFs=new be("schemas",this.config.root),this.authStorage=this.config.authStorage??new jt(le__default.join(be.homeDir(),"auth")),this._client=this.config.withSupabaseClient!==false?this.config.client??createClient(this.config.host??ze,process.env.LITE_CLOUD_ANON_KEY??"...",{auth:{storage:this.authStorage}}):void 0;}tempFs;projectFs;schemaFs;_client;authStorage;async fetch(e,n){if(!this.config.token)throw new Error("Not authenticated, sign in first.");let r=e instanceof URL?e:new URL(e,this.config.host??ze);return await fetch(r,{...n,headers:{...n?.headers,Authorization:`Bearer ${this.config.token}`}})}};var qe=class extends Me{constructor(n){super(n);this.config=n;}get client(){if(!this._client)throw new Error("Supabase client not initialized");return this._client}projectRef(){return this.tempFs.read("project-ref",true)}projectUrl(n){let r=new URL(this.config.projectsHost??Ft),i=r.hostname.replace(/^www\./,"");return `${r.protocol}//${n}.${i}${r.port?`:${r.port}`:""}`}};var ne={config_dir:"supabase",default_db_url:"file:supabase/.temp/data.db",default_db_dir:"supabase/.temp/data"};var it=je(Ue());function Ms(t,e){let n=t.slice(0,e).split(/\r\n|\n|\r/g);return [n.length,n.pop().length+1]}function qs(t,e,n){let r=t.split(/\r\n|\n|\r/g),i="",s=(Math.log10(e+1)|0)+1;for(let o=e-1;o<=e+1;o++){let a=r[o-1];a&&(i+=o.toString().padEnd(s," "),i+=": ",i+=a,i+=`
13
13
  `,o===e&&(i+=" ".repeat(s+n+2),i+=`^
14
- `));}return i}var _=class extends Error{line;column;codeblock;constructor(e,n){let[r,i]=ds(n.toml,n.ptr),s=hs(n.toml,r,i);super(`Invalid TOML document: ${e}
14
+ `));}return i}var A=class extends Error{line;column;codeblock;constructor(e,n){let[r,i]=Ms(n.toml,n.ptr),s=qs(n.toml,r,i);super(`Invalid TOML document: ${e}
15
15
 
16
- ${s}`,n),this.line=r,this.column=i,this.codeblock=s;}};function gs(t,e){let n=0;for(;t[e-++n]==="\\";);return --n&&n%2}function kt(t,e=0,n=t.length){let r=t.indexOf(`
17
- `,e);return t[r-1]==="\r"&&r--,r<=n?r:-1}function $e(t,e){for(let n=e;n<t.length;n++){let r=t[n];if(r===`
16
+ ${s}`,n),this.line=r,this.column=i,this.codeblock=s;}};function Us(t,e){let n=0;for(;t[e-++n]==="\\";);return --n&&n%2}function Ut(t,e=0,n=t.length){let r=t.indexOf(`
17
+ `,e);return t[r-1]==="\r"&&r--,r<=n?r:-1}function Be(t,e){for(let n=e;n<t.length;n++){let r=t[n];if(r===`
18
18
  `)return n;if(r==="\r"&&t[n+1]===`
19
- `)return n+1;if(r<" "&&r!==" "||r==="\x7F")throw new _("control characters are not allowed in comments",{toml:t,ptr:e})}return t.length}function X(t,e,n,r){let i;for(;(i=t[e])===" "||i===" "||!n&&(i===`
19
+ `)return n+1;if(r<" "&&r!==" "||r==="\x7F")throw new A("control characters are not allowed in comments",{toml:t,ptr:e})}return t.length}function Z(t,e,n,r){let i;for(;(i=t[e])===" "||i===" "||!n&&(i===`
20
20
  `||i==="\r"&&t[e+1]===`
21
- `);)e++;return r||i!=="#"?e:X(t,$e(t,e),n)}function sr(t,e,n,r,i=false){if(!r)return e=kt(t,e),e<0?t.length:e;for(let s=e;s<t.length;s++){let o=t[s];if(o==="#")s=kt(t,s);else {if(o===n)return s+1;if(o===r||i&&(o===`
21
+ `);)e++;return r||i!=="#"?e:Z(t,Be(t,e),n)}function _r(t,e,n,r,i=false){if(!r)return e=Ut(t,e),e<0?t.length:e;for(let s=e;s<t.length;s++){let o=t[s];if(o==="#")s=Ut(t,s);else {if(o===n)return s+1;if(o===r||i&&(o===`
22
22
  `||o==="\r"&&t[s+1]===`
23
- `))return s}}throw new _("cannot find end of structure",{toml:t,ptr:e})}function $t(t,e){let n=t[e],r=n===t[e+1]&&t[e+1]===t[e+2]?t.slice(e,e+3):n;e+=r.length-1;do e=t.indexOf(r,++e);while(e>-1&&n!=="'"&&gs(t,e));return e>-1&&(e+=r.length,r.length>1&&(t[e]===n&&e++,t[e]===n&&e++)),e}var ys=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,Ie=class t extends Date{#t=false;#n=false;#e=null;constructor(e){let n=true,r=true,i="Z";if(typeof e=="string"){let s=e.match(ys);s?(s[1]||(n=false,e=`0000-01-01T${e}`),r=!!s[2],r&&e[10]===" "&&(e=e.replace(" ","T")),s[2]&&+s[2]>23?e="":(i=s[3]||null,e=e.toUpperCase(),!i&&r&&(e+="Z"))):e="";}super(e),isNaN(this.getTime())||(this.#t=n,this.#n=r,this.#e=i);}isDateTime(){return this.#t&&this.#n}isLocal(){return !this.#t||!this.#n||!this.#e}isDate(){return this.#t&&!this.#n}isTime(){return this.#n&&!this.#t}isValid(){return this.#t||this.#n}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#e===null)return e.slice(0,-1);if(this.#e==="Z")return e;let n=+this.#e.slice(1,3)*60+ +this.#e.slice(4,6);return n=this.#e[0]==="-"?n:-n,new Date(this.getTime()-n*6e4).toISOString().slice(0,-1)+this.#e}static wrapAsOffsetDateTime(e,n="Z"){let r=new t(e);return r.#e=n,r}static wrapAsLocalDateTime(e){let n=new t(e);return n.#e=null,n}static wrapAsLocalDate(e){let n=new t(e);return n.#n=false,n.#e=null,n}static wrapAsLocalTime(e){let n=new t(e);return n.#t=false,n.#e=null,n}};var bs=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,ws=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,xs=/^[+-]?0[0-9_]/,Ss=/^[0-9a-f]{2,8}$/i,or={b:"\b",t:" ",n:`
24
- `,f:"\f",r:"\r",e:"\x1B",'"':'"',"\\":"\\"};function vt(t,e=0,n=t.length){let r=t[e]==="'",i=t[e++]===t[e]&&t[e]===t[e+1];i&&(n-=2,t[e+=2]==="\r"&&e++,t[e]===`
25
- `&&e++);let s=0,o,a="",l=e;for(;e<n-1;){let c=t[e++];if(c===`
26
- `||c==="\r"&&t[e]===`
27
- `){if(!i)throw new _("newlines are not allowed in strings",{toml:t,ptr:e-1})}else if(c<" "&&c!==" "||c==="\x7F")throw new _("control characters are not allowed in strings",{toml:t,ptr:e-1});if(o){if(o=false,c==="x"||c==="u"||c==="U"){let u=t.slice(e,e+=c==="x"?2:c==="u"?4:8);if(!Ss.test(u))throw new _("invalid unicode escape",{toml:t,ptr:s});try{a+=String.fromCodePoint(parseInt(u,16));}catch{throw new _("invalid unicode escape",{toml:t,ptr:s})}}else if(i&&(c===`
28
- `||c===" "||c===" "||c==="\r")){if(e=X(t,e-1,true),t[e]!==`
29
- `&&t[e]!=="\r")throw new _("invalid escape: only line-ending whitespace may be escaped",{toml:t,ptr:s});e=X(t,e);}else if(c in or)a+=or[c];else throw new _("unrecognized escape sequence",{toml:t,ptr:s});l=e;}else !r&&c==="\\"&&(s=e-1,o=true,a+=t.slice(l,s));}return a+t.slice(l,n-1)}function ar(t,e,n,r){if(t==="true")return true;if(t==="false")return false;if(t==="-inf")return -1/0;if(t==="inf"||t==="+inf")return 1/0;if(t==="nan"||t==="+nan"||t==="-nan")return NaN;if(t==="-0")return r?0n:0;let i=bs.test(t);if(i||ws.test(t)){if(xs.test(t))throw new _("leading zeroes are not allowed",{toml:e,ptr:n});t=t.replace(/_/g,"");let o=+t;if(isNaN(o))throw new _("invalid number",{toml:e,ptr:n});if(i){if((i=!Number.isSafeInteger(o))&&!r)throw new _("integer value cannot be represented losslessly",{toml:e,ptr:n});(i||r===true)&&(o=BigInt(t));}return o}let s=new Ie(t);if(!s.isValid())throw new _("invalid value",{toml:e,ptr:n});return s}function Es(t,e,n){let r=t.slice(e,n),i=r.indexOf("#");return i>-1&&($e(t,i),r=r.slice(0,i)),[r.trimEnd(),i]}function De(t,e,n,r,i){if(r===0)throw new _("document contains excessively nested structures. aborting.",{toml:t,ptr:e});let s=t[e];if(s==="["||s==="{"){let[l,c]=s==="["?cr(t,e,r,i):lr(t,e,r,i);if(n){if(c=X(t,c),t[c]===",")c++;else if(t[c]!==n)throw new _("expected comma or end of structure",{toml:t,ptr:c})}return [l,c]}let o;if(s==='"'||s==="'"){o=$t(t,e);let l=vt(t,e,o);if(n){if(o=X(t,o),t[o]&&t[o]!==","&&t[o]!==n&&t[o]!==`
30
- `&&t[o]!=="\r")throw new _("unexpected character encountered",{toml:t,ptr:o});o+=+(t[o]===",");}return [l,o]}o=sr(t,e,",",n);let a=Es(t,e,o-+(t[o-1]===","));if(!a[0])throw new _("incomplete key-value declaration: no value specified",{toml:t,ptr:e});return n&&a[1]>-1&&(o=X(t,e+a[1]),o+=+(t[o]===",")),[ar(a[0],t,e,i),o]}var Ts=/^[a-zA-Z0-9-_]+[ \t]*$/;function Nt(t,e,n="="){let r=e-1,i=[],s=t.indexOf(n,e);if(s<0)throw new _("incomplete key-value: cannot find end of key",{toml:t,ptr:e});do{let o=t[e=++r];if(o!==" "&&o!==" ")if(o==='"'||o==="'"){if(o===t[e+1]&&o===t[e+2])throw new _("multiline strings are not allowed in keys",{toml:t,ptr:e});let a=$t(t,e);if(a<0)throw new _("unfinished string encountered",{toml:t,ptr:e});r=t.indexOf(".",a);let l=t.slice(a,r<0||r>s?s:r),c=kt(l);if(c>-1)throw new _("newlines are not allowed in keys",{toml:t,ptr:e+r+c});if(l.trimStart())throw new _("found extra tokens after the string part",{toml:t,ptr:a});if(s<a&&(s=t.indexOf(n,a),s<0))throw new _("incomplete key-value: cannot find end of key",{toml:t,ptr:e});i.push(vt(t,e,a));}else {r=t.indexOf(".",e);let a=t.slice(e,r<0||r>s?s:r);if(!Ts.test(a))throw new _("only letter, numbers, dashes and underscores are allowed in keys",{toml:t,ptr:e});i.push(a.trimEnd());}}while(r+1&&r<s);return [i,X(t,s+1,true,true)]}function lr(t,e,n,r){let i={},s=new Set,o;for(e++;(o=t[e++])!=="}"&&o;){if(o===",")throw new _("expected value, found comma",{toml:t,ptr:e-1});if(o==="#")e=$e(t,e);else if(o!==" "&&o!==" "&&o!==`
31
- `&&o!=="\r"){let a,l=i,c=false,[u,f]=Nt(t,e-1);for(let y=0;y<u.length;y++){if(y&&(l=c?l[a]:l[a]={}),a=u[y],(c=Object.hasOwn(l,a))&&(typeof l[a]!="object"||s.has(l[a])))throw new _("trying to redefine an already defined value",{toml:t,ptr:e});!c&&a==="__proto__"&&Object.defineProperty(l,a,{enumerable:true,configurable:true,writable:true});}if(c)throw new _("trying to redefine an already defined value",{toml:t,ptr:e});let[m,g]=De(t,f,"}",n-1,r);s.add(m),l[a]=m,e=g;}}if(!o)throw new _("unfinished table encountered",{toml:t,ptr:e});return [i,e]}function cr(t,e,n,r){let i=[],s;for(e++;(s=t[e++])!=="]"&&s;){if(s===",")throw new _("expected value, found comma",{toml:t,ptr:e-1});if(s==="#")e=$e(t,e);else if(s!==" "&&s!==" "&&s!==`
32
- `&&s!=="\r"){let o=De(t,e-1,"]",n-1,r);i.push(o[0]),e=o[1];}}if(!s)throw new _("unfinished array encountered",{toml:t,ptr:e});return [i,e]}function ur(t,e,n,r){let i=e,s=n,o,a=false,l;for(let c=0;c<t.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=t[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<t.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 je(t,{maxDepth:e=1e3,integersAsBigInt:n}={}){let r={},i={},s=r,o=i;for(let a=X(t,0);a<t.length;){if(t[a]==="["){let l=t[++a]==="[",c=Nt(t,a+=+l,"]");if(l){if(t[c[1]-1]!=="]")throw new _("expected end of table declaration",{toml:t,ptr:c[1]-1});c[1]++;}let u=ur(c[0],r,i,l?2:1);if(!u)throw new _("trying to redefine an already defined table or value",{toml:t,ptr:a});o=u[2],s=u[1],a=c[1];}else {let l=Nt(t,a),c=ur(l[0],s,o,0);if(!c)throw new _("trying to redefine an already defined table or value",{toml:t,ptr:a});let u=De(t,l[1],void 0,e,n);c[1][c[0]]=u[0],a=u[1];}if(a=X(t,a,true),t[a]&&t[a]!==`
33
- `&&t[a]!=="\r")throw new _("each key-value declaration must be followed by an end-of-line",{toml:t,ptr:a});a=X(t,a);}return r}var fr=/^[a-z0-9-_]+$/i;function Ue(t){let e=typeof t;if(e==="object"){if(Array.isArray(t))return "array";if(t instanceof Date)return "date"}return e}function As(t){for(let e=0;e<t.length;e++)if(Ue(t[e])!=="object")return false;return t.length!=0}function Jt(t){return JSON.stringify(t).replace(/\x7f/g,"\\u007f")}function Yt(t,e,n,r){if(n===0)throw new Error("Could not stringify the object: maximum object depth exceeded");if(e==="number")return isNaN(t)?"nan":t===1/0?"inf":t===-1/0?"-inf":r&&Number.isInteger(t)?t.toFixed(1):t.toString();if(e==="bigint"||e==="boolean")return t.toString();if(e==="string")return Jt(t);if(e==="date"){if(isNaN(t.getTime()))throw new TypeError("cannot serialize invalid date");return t.toISOString()}if(e==="object")return _s(t,n,r);if(e==="array")return Cs(t,n,r)}function _s(t,e,n){let r=Object.keys(t);if(r.length===0)return "{}";let i="{ ";for(let s=0;s<r.length;s++){let o=r[s];s&&(i+=", "),i+=fr.test(o)?o:Jt(o),i+=" = ",i+=Yt(t[o],Ue(t[o]),e-1,n);}return i+" }"}function Cs(t,e,n){if(t.length===0)return "[]";let r="[ ";for(let i=0;i<t.length;i++){if(i&&(r+=", "),t[i]===null||t[i]===void 0)throw new TypeError("arrays cannot contain null or undefined values");r+=Yt(t[i],Ue(t[i]),e-1,n);}return r+" ]"}function Rs(t,e,n,r){if(n===0)throw new Error("Could not stringify the object: maximum object depth exceeded");let i="";for(let s=0;s<t.length;s++)i+=`${i&&`
23
+ `))return s}}throw new A("cannot find end of structure",{toml:t,ptr:e})}function Bt(t,e){let n=t[e],r=n===t[e+1]&&t[e+1]===t[e+2]?t.slice(e,e+3):n;e+=r.length-1;do e=t.indexOf(r,++e);while(e>-1&&n!=="'"&&Us(t,e));return e>-1&&(e+=r.length,r.length>1&&(t[e]===n&&e++,t[e]===n&&e++)),e}var Bs=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,Je=class t extends Date{#t=false;#n=false;#e=null;constructor(e){let n=true,r=true,i="Z";if(typeof e=="string"){let s=e.match(Bs);s?(s[1]||(n=false,e=`0000-01-01T${e}`),r=!!s[2],r&&e[10]===" "&&(e=e.replace(" ","T")),s[2]&&+s[2]>23?e="":(i=s[3]||null,e=e.toUpperCase(),!i&&r&&(e+="Z"))):e="";}super(e),isNaN(this.getTime())||(this.#t=n,this.#n=r,this.#e=i);}isDateTime(){return this.#t&&this.#n}isLocal(){return !this.#t||!this.#n||!this.#e}isDate(){return this.#t&&!this.#n}isTime(){return this.#n&&!this.#t}isValid(){return this.#t||this.#n}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#e===null)return e.slice(0,-1);if(this.#e==="Z")return e;let n=+this.#e.slice(1,3)*60+ +this.#e.slice(4,6);return n=this.#e[0]==="-"?n:-n,new Date(this.getTime()-n*6e4).toISOString().slice(0,-1)+this.#e}static wrapAsOffsetDateTime(e,n="Z"){let r=new t(e);return r.#e=n,r}static wrapAsLocalDateTime(e){let n=new t(e);return n.#e=null,n}static wrapAsLocalDate(e){let n=new t(e);return n.#n=false,n.#e=null,n}static wrapAsLocalTime(e){let n=new t(e);return n.#t=false,n.#e=null,n}};var Hs=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,Vs=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,Ks=/^[+-]?0[0-9_]/,Gs=/^[0-9a-f]{2,8}$/i,Tr={b:"\b",t:" ",n:`
24
+ `,f:"\f",r:"\r",e:"\x1B",'"':'"',"\\":"\\"};function Ht(t,e=0,n=t.length){let r=t[e]==="'",i=t[e++]===t[e]&&t[e]===t[e+1];i&&(n-=2,t[e+=2]==="\r"&&e++,t[e]===`
25
+ `&&e++);let s=0,o,a="",c=e;for(;e<n-1;){let l=t[e++];if(l===`
26
+ `||l==="\r"&&t[e]===`
27
+ `){if(!i)throw new A("newlines are not allowed in strings",{toml:t,ptr:e-1})}else if(l<" "&&l!==" "||l==="\x7F")throw new A("control characters are not allowed in strings",{toml:t,ptr:e-1});if(o){if(o=false,l==="x"||l==="u"||l==="U"){let f=t.slice(e,e+=l==="x"?2:l==="u"?4:8);if(!Gs.test(f))throw new A("invalid unicode escape",{toml:t,ptr:s});try{a+=String.fromCodePoint(parseInt(f,16));}catch{throw new A("invalid unicode escape",{toml:t,ptr:s})}}else if(i&&(l===`
28
+ `||l===" "||l===" "||l==="\r")){if(e=Z(t,e-1,true),t[e]!==`
29
+ `&&t[e]!=="\r")throw new A("invalid escape: only line-ending whitespace may be escaped",{toml:t,ptr:s});e=Z(t,e);}else if(l in Tr)a+=Tr[l];else throw new A("unrecognized escape sequence",{toml:t,ptr:s});c=e;}else !r&&l==="\\"&&(s=e-1,o=true,a+=t.slice(c,s));}return a+t.slice(c,n-1)}function Ar(t,e,n,r){if(t==="true")return true;if(t==="false")return false;if(t==="-inf")return -1/0;if(t==="inf"||t==="+inf")return 1/0;if(t==="nan"||t==="+nan"||t==="-nan")return NaN;if(t==="-0")return r?0n:0;let i=Hs.test(t);if(i||Vs.test(t)){if(Ks.test(t))throw new A("leading zeroes are not allowed",{toml:e,ptr:n});t=t.replace(/_/g,"");let o=+t;if(isNaN(o))throw new A("invalid number",{toml:e,ptr:n});if(i){if((i=!Number.isSafeInteger(o))&&!r)throw new A("integer value cannot be represented losslessly",{toml:e,ptr:n});(i||r===true)&&(o=BigInt(t));}return o}let s=new Je(t);if(!s.isValid())throw new A("invalid value",{toml:e,ptr:n});return s}function Ws(t,e,n){let r=t.slice(e,n),i=r.indexOf("#");return i>-1&&(Be(t,i),r=r.slice(0,i)),[r.trimEnd(),i]}function Ye(t,e,n,r,i){if(r===0)throw new A("document contains excessively nested structures. aborting.",{toml:t,ptr:e});let s=t[e];if(s==="["||s==="{"){let[c,l]=s==="["?Rr(t,e,r,i):Cr(t,e,r,i);if(n){if(l=Z(t,l),t[l]===",")l++;else if(t[l]!==n)throw new A("expected comma or end of structure",{toml:t,ptr:l})}return [c,l]}let o;if(s==='"'||s==="'"){o=Bt(t,e);let c=Ht(t,e,o);if(n){if(o=Z(t,o),t[o]&&t[o]!==","&&t[o]!==n&&t[o]!==`
30
+ `&&t[o]!=="\r")throw new A("unexpected character encountered",{toml:t,ptr:o});o+=+(t[o]===",");}return [c,o]}o=_r(t,e,",",n);let a=Ws(t,e,o-+(t[o-1]===","));if(!a[0])throw new A("incomplete key-value declaration: no value specified",{toml:t,ptr:e});return n&&a[1]>-1&&(o=Z(t,e+a[1]),o+=+(t[o]===",")),[Ar(a[0],t,e,i),o]}var Xs=/^[a-zA-Z0-9-_]+[ \t]*$/;function Vt(t,e,n="="){let r=e-1,i=[],s=t.indexOf(n,e);if(s<0)throw new A("incomplete key-value: cannot find end of key",{toml:t,ptr:e});do{let o=t[e=++r];if(o!==" "&&o!==" ")if(o==='"'||o==="'"){if(o===t[e+1]&&o===t[e+2])throw new A("multiline strings are not allowed in keys",{toml:t,ptr:e});let a=Bt(t,e);if(a<0)throw new A("unfinished string encountered",{toml:t,ptr:e});r=t.indexOf(".",a);let c=t.slice(a,r<0||r>s?s:r),l=Ut(c);if(l>-1)throw new A("newlines are not allowed in keys",{toml:t,ptr:e+r+l});if(c.trimStart())throw new A("found extra tokens after the string part",{toml:t,ptr:a});if(s<a&&(s=t.indexOf(n,a),s<0))throw new A("incomplete key-value: cannot find end of key",{toml:t,ptr:e});i.push(Ht(t,e,a));}else {r=t.indexOf(".",e);let a=t.slice(e,r<0||r>s?s:r);if(!Xs.test(a))throw new A("only letter, numbers, dashes and underscores are allowed in keys",{toml:t,ptr:e});i.push(a.trimEnd());}}while(r+1&&r<s);return [i,Z(t,s+1,true,true)]}function Cr(t,e,n,r){let i={},s=new Set,o;for(e++;(o=t[e++])!=="}"&&o;){if(o===",")throw new A("expected value, found comma",{toml:t,ptr:e-1});if(o==="#")e=Be(t,e);else if(o!==" "&&o!==" "&&o!==`
31
+ `&&o!=="\r"){let a,c=i,l=false,[f,m]=Vt(t,e-1);for(let d=0;d<f.length;d++){if(d&&(c=l?c[a]:c[a]={}),a=f[d],(l=Object.hasOwn(c,a))&&(typeof c[a]!="object"||s.has(c[a])))throw new A("trying to redefine an already defined value",{toml:t,ptr:e});!l&&a==="__proto__"&&Object.defineProperty(c,a,{enumerable:true,configurable:true,writable:true});}if(l)throw new A("trying to redefine an already defined value",{toml:t,ptr:e});let[u,p]=Ye(t,m,"}",n-1,r);s.add(u),c[a]=u,e=p;}}if(!o)throw new A("unfinished table encountered",{toml:t,ptr:e});return [i,e]}function Rr(t,e,n,r){let i=[],s;for(e++;(s=t[e++])!=="]"&&s;){if(s===",")throw new A("expected value, found comma",{toml:t,ptr:e-1});if(s==="#")e=Be(t,e);else if(s!==" "&&s!==" "&&s!==`
32
+ `&&s!=="\r"){let o=Ye(t,e-1,"]",n-1,r);i.push(o[0]),e=o[1];}}if(!s)throw new A("unfinished array encountered",{toml:t,ptr:e});return [i,e]}function kr(t,e,n,r){let i=e,s=n,o,a=false,c;for(let l=0;l<t.length;l++){if(l){if(i=a?i[o]:i[o]={},s=(c=s[o]).c,r===0&&(c.t===1||c.t===2))return null;if(c.t===2){let f=i.length-1;i=i[f],s=s[f].c;}}if(o=t[l],(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:l<t.length-1&&r===2?3:r,d:false,i:0,c:{}});}if(c=s[o],c.t!==r&&!(r===1&&c.t===3)||(r===2&&(c.d||(c.d=true,i[o]=[]),i[o].push(i={}),c.c[c.i++]=c={t:1,d:false,i:0,c:{}}),c.d))return null;if(c.d=true,r===1)i=a?i[o]:i[o]={};else if(r===0&&a)return null;return [o,i,c.c]}function Qe(t,{maxDepth:e=1e3,integersAsBigInt:n}={}){let r={},i={},s=r,o=i;for(let a=Z(t,0);a<t.length;){if(t[a]==="["){let c=t[++a]==="[",l=Vt(t,a+=+c,"]");if(c){if(t[l[1]-1]!=="]")throw new A("expected end of table declaration",{toml:t,ptr:l[1]-1});l[1]++;}let f=kr(l[0],r,i,c?2:1);if(!f)throw new A("trying to redefine an already defined table or value",{toml:t,ptr:a});o=f[2],s=f[1],a=l[1];}else {let c=Vt(t,a),l=kr(c[0],s,o,0);if(!l)throw new A("trying to redefine an already defined table or value",{toml:t,ptr:a});let f=Ye(t,c[1],void 0,e,n);l[1][l[0]]=f[0],a=f[1];}if(a=Z(t,a,true),t[a]&&t[a]!==`
33
+ `&&t[a]!=="\r")throw new A("each key-value declaration must be followed by an end-of-line",{toml:t,ptr:a});a=Z(t,a);}return r}var $r=/^[a-z0-9-_]+$/i;function Ze(t){let e=typeof t;if(e==="object"){if(Array.isArray(t))return "array";if(t instanceof Date)return "date"}return e}function zs(t){for(let e=0;e<t.length;e++)if(Ze(t[e])!=="object")return false;return t.length!=0}function pn(t){return JSON.stringify(t).replace(/\x7f/g,"\\u007f")}function mn(t,e,n,r){if(n===0)throw new Error("Could not stringify the object: maximum object depth exceeded");if(e==="number")return isNaN(t)?"nan":t===1/0?"inf":t===-1/0?"-inf":r&&Number.isInteger(t)?t.toFixed(1):t.toString();if(e==="bigint"||e==="boolean")return t.toString();if(e==="string")return pn(t);if(e==="date"){if(isNaN(t.getTime()))throw new TypeError("cannot serialize invalid date");return t.toISOString()}if(e==="object")return Js(t,n,r);if(e==="array")return Ys(t,n,r)}function Js(t,e,n){let r=Object.keys(t);if(r.length===0)return "{}";let i="{ ";for(let s=0;s<r.length;s++){let o=r[s];s&&(i+=", "),i+=$r.test(o)?o:pn(o),i+=" = ",i+=mn(t[o],Ze(t[o]),e-1,n);}return i+" }"}function Ys(t,e,n){if(t.length===0)return "[]";let r="[ ";for(let i=0;i<t.length;i++){if(i&&(r+=", "),t[i]===null||t[i]===void 0)throw new TypeError("arrays cannot contain null or undefined values");r+=mn(t[i],Ze(t[i]),e-1,n);}return r+" ]"}function Qs(t,e,n,r){if(n===0)throw new Error("Could not stringify the object: maximum object depth exceeded");let i="";for(let s=0;s<t.length;s++)i+=`${i&&`
34
34
  `}[[${e}]]
35
- `,i+=Qt(0,t[s],e,n,r);return i}function Qt(t,e,n,r,i){if(r===0)throw new Error("Could not stringify the object: maximum object depth exceeded");let s="",o="",a=Object.keys(e);for(let l=0;l<a.length;l++){let c=a[l];if(e[c]!==null&&e[c]!==void 0){let u=Ue(e[c]);if(u==="symbol"||u==="function")throw new TypeError(`cannot serialize values of type '${u}'`);let f=fr.test(c)?c:Jt(c);if(u==="array"&&As(e[c]))o+=(o&&`
36
- `)+Rs(e[c],n?`${n}.${f}`:f,r-1,i);else if(u==="object"){let m=n?`${n}.${f}`:f;o+=(o&&`
37
- `)+Qt(m,e[c],m,r-1,i);}else s+=f,s+=" = ",s+=Yt(e[c],u,r,i),s+=`
35
+ `,i+=dn(0,t[s],e,n,r);return i}function dn(t,e,n,r,i){if(r===0)throw new Error("Could not stringify the object: maximum object depth exceeded");let s="",o="",a=Object.keys(e);for(let c=0;c<a.length;c++){let l=a[c];if(e[l]!==null&&e[l]!==void 0){let f=Ze(e[l]);if(f==="symbol"||f==="function")throw new TypeError(`cannot serialize values of type '${f}'`);let m=$r.test(l)?l:pn(l);if(f==="array"&&zs(e[l]))o+=(o&&`
36
+ `)+Qs(e[l],n?`${n}.${m}`:m,r-1,i);else if(f==="object"){let u=n?`${n}.${m}`:m;o+=(o&&`
37
+ `)+dn(u,e[l],u,r-1,i);}else s+=m,s+=" = ",s+=mn(e[l],f,r,i),s+=`
38
38
  `;}}return t&&(s||!o)&&(s=s?`[${t}]
39
39
  ${s}`:`[${t}]`),s&&o?`${s}
40
- ${o}`:s||o}function Zt(t,{maxDepth:e=1e3,numbersAsFloat:n=false}={}){if(Ue(t)!=="object")throw new TypeError("stringify can only be called with an object");let r=Qt(0,t,"",e,n);return r[r.length-1]!==`
40
+ ${o}`:s||o}function hn(t,{maxDepth:e=1e3,numbersAsFloat:n=false}={}){if(Ze(t)!=="object")throw new TypeError("stringify can only be called with an object");let r=dn(0,t,"",e,n);return r[r.length-1]!==`
41
41
  `?r+`
42
- `:r}var ks={storage:"EXPERIMENTAL_STORAGE",cloud:"EXPERIMENTAL_CLOUD"},$s=["storage","cloud"];Object.fromEntries($s.map(t=>[t,vs(t)]));function vs(t){let e=typeof process<"u"&&process.env||void 0;return e?e.NODE_ENV==="test"?true:e[ks[t]]==="1":false}function en(t){let e=[],n="",r=0,i=t.length,s=false,o=false,a=0,l=/^create(\s+or\s+replace)?(\s+temp(orary)?)?$/i,c=f=>{mr(f).length>0&&e.push(f.trim());},u=()=>{s=false,o=false,a=0;};for(;r<i;){let f=t[r],m=t[r+1];if(f==="-"&&m==="-"){for(;r<i&&t[r]!==`
43
- `;)n+=t[r],r++;continue}if(f==="/"&&m==="*"){for(n+="/*",r+=2;r<i&&!(t[r]==="*"&&t[r+1]==="/");)n+=t[r],r++;r<i&&(n+="*/",r+=2);continue}if(f==="'"){for(n+=f,r++;r<i;){if(t[r]==="'"&&t[r+1]==="'"){n+="''",r+=2;continue}if(n+=t[r],t[r]==="'"){r++;break}r++;}continue}if(f==='"'){for(n+=f,r++;r<i;){if(t[r]==='"'&&t[r+1]==='"'){n+='""',r+=2;continue}if(n+=t[r],t[r]==='"'){r++;break}r++;}continue}if(f==="$"){let g=t.indexOf("$",r+1);if(g!==-1){let y=t.slice(r,g+1);if(/^\$[A-Za-z_][A-Za-z0-9_]*\$$|^\$\$$/.test(y)){n+=y,r=g+1;let T=t.indexOf(y,r);T===-1?(n+=t.slice(r),r=i):(n+=t.slice(r,T+y.length),r=T+y.length);continue}}}if(/[A-Za-z_]/.test(f)){let g=r;for(;g<i&&/[A-Za-z0-9_]/.test(t[g]);)g++;let y=t.slice(r,g),E=y.toLowerCase();if(E==="trigger"&&l.test(mr(n))?s=true:s&&E==="begin"?(o=true,a++):s&&o&&E==="case"?a++:s&&o&&E==="end"&&a>0&&a--,n+=y,r=g,s&&o&&a===0){let T=r;for(;T<i&&/\s/.test(t[T]);)T++;t[T]===";"&&(r=T+1),c(n),n="",u();}continue}if(f===";"){if(s&&o&&a>0){n+=f,r++;continue}c(n),n="",u(),r++;continue}n+=f,r++;}return c(n),e}function mr(t){let e="",n=0,r=t.length;for(;n<r;){let i=t[n],s=t[n+1];if(i==="-"&&s==="-"){for(;n<r&&t[n]!==`
44
- `;)n++;continue}if(i==="/"&&s==="*"){for(n+=2;n<r&&!(t[n]==="*"&&t[n+1]==="/");)n++;n+=2;continue}e+=i,n++;}return e.trim()}function tn(t){return typeof t=="number"?t:Number.parseInt(String(t),10)}var Pt=class{driver=V;basePath;constructor(e){this.basePath=ie.resolve(e.basePath);}filePath(e,n){return ie.join(this.basePath,e,n)}async ensureDir(e){await V.mkdir(ie.dirname(e),{recursive:true});}async getObject(e,n,r,i){let s=this.filePath(e,n),o=await V.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 m=new Date(i.ifModifiedSince);if(o.mtime<=m)return {httpStatusCode:304,metadata:this.buildMetadata(o,a,n)}}let l,c,u=o.size,f=200;if(i?.range){let m=i.range.match(/^bytes=(\d+)-(\d*)$/);if(m){let g=Number.parseInt(m[1],10),y=m[2]?Number.parseInt(m[2],10):o.size-1;u=y-g+1,c=`bytes ${g}-${y}/${o.size}`,f=206,l=(await V.open(s,"r")).readableWebStream();}else l=(await V.open(s,"r")).readableWebStream();}else l=(await V.open(s,"r")).readableWebStream();return {httpStatusCode:f,metadata:{...this.buildMetadata(o,a,n),contentLength:u,contentRange:c},body:l}}async uploadObject(e,n,r,i,s,o){let a=this.filePath(e,n);await this.ensureDir(a);let l;if(i instanceof Uint8Array||Buffer.isBuffer(i))l=i;else {let f=[],m=i.getReader();for(;;){let{done:g,value:y}=await m.read();if(g)break;f.push(y);}l=Buffer.concat(f);}await V.writeFile(a,l);let c=await V.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(e,n,r){let i=this.filePath(e,n);await V.unlink(i).catch(s=>{if(s.code!=="ENOENT")throw s});}async deleteObjects(e,n){for(let r of n)await this.deleteObject(e,r,void 0);}async copyObject(e,n,r,i,s){let o=this.filePath(e,n),a=this.filePath(e,i);await this.ensureDir(a),await V.copyFile(o,a);let l=await V.stat(a),c=await V.readFile(a);return {httpStatusCode:200,eTag:`"${createHash("md5").update(c).digest("hex")}"`,lastModified:l.mtime}}async headObject(e,n,r){let i=this.filePath(e,n),s=await V.stat(i),o=`"${createHash("md5").update(`${i}:${s.mtimeMs}`).digest("hex")}"`;return this.buildMetadata(s,o,n)}async privateAssetUrl(e,n,r){return `file://${this.filePath(e,n)}`}buildMetadata(e,n,r){return {cacheControl:"no-cache",contentLength:tn(e.size),size:tn(e.size),mimetype:Ls(r),lastModified:e.mtime,eTag:n}}};function Ls(t){let e=ie.extname(t).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"}[e]??"application/octet-stream"}var Ps=new Function("spec","return import(spec)");async function nn(t,e,n){try{return await Ps(t)}catch(r){throw r?.code==="ERR_MODULE_NOT_FOUND"||/Cannot find package/.test(String(r?.message))?new Error(`Driver '${e}' selected but '${n}' is not installed. Run: bun add ${n}`):r}}function Me(t,e={}){let n=ie__default.resolve(e.cwd??process.cwd()),r=e.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=Is(ie__default.resolve(t),n);for(let a of o)for(let l of s){let c=ie__default.join(a,l),u;try{u=St.readFileSync(c,"utf-8");}catch{continue}let f;try{f=parse(u);}catch(m){throw new Error(`Failed to parse ${c}: ${m.message}`)}for(let[m,g]of Object.entries(f))r[m]===void 0&&(r[m]=g);}}function Is(t,e){let n=[],r=t,i=ie__default.parse(r).root;for(;n.push(r),!(r===e||r===i);){let s=ie__default.dirname(r);if(s===r)break;r=s;}return n}var Ds=/^env\((\w+)\)$/;function He(t,e=process.env){return rn(t,e)}function rn(t,e){if(typeof t=="string"){let n=t.match(Ds);return n?e[n[1]]??"":t}if(Array.isArray(t))return t.map(n=>rn(n,e));if(t&&typeof t=="object"){let n=Object.getPrototypeOf(t);if(n!==Object.prototype&&n!==null)return t;let r={};for(let[i,s]of Object.entries(t))r[i]=rn(s,e);return r}return t}var js=process.env.LITE_VERBOSE==="1";function qe(...t){js&&console.error(...t);}var Bs=["toml","json","ts","mts","js","mjs","cjs"],Ot=class extends ke{ref(){return this.projectRef()}setRef(e){return this.tempFs.write("project-ref",e),this}link(e){return this.setRef(e.id),e}unlink(){return this.tempFs.delete("project-ref"),this}url(){let e=this.ref();if(!e)throw new Error("No project linked");return this.projectUrl(e)}async getConfigPath(e){let n=ie__default.relative(process.cwd(),Y.config_dir);if(!e)for(let r of Bs){let i=ie__default.join(n,`config.${r}`);if(await V__default.access(i).then(()=>true).catch(()=>false)){e=i;break}}return e}async readConfig(e){let n=await this.getConfigPath(e);if(!n)return {};qe(Ve.default.dim(`Using config file: ${Ve.default.cyan(`./${n}`)}`));let r=ie__default.dirname(ie__default.resolve(n));Me(r);let i=n.split(".").pop(),s;switch(i){case "toml":s=je(await V__default.readFile(n,"utf-8"));break;case "json":s=JSON.parse(await V__default.readFile(n,"utf-8"));break;case "ts":case "mts":case "js":case "mjs":case "cjs":try{s=(await import(ie__default.join(process.cwd(),n))).default;break}catch(o){throw console.error("Failed to import config file",o),o}default:throw new Error(`Unsupported config file type: ${n}`)}return He(s)}async createConnection(){throw new Error("Not implemented")}async getConfig(e){let n=await this.readConfig(e);if("connection"in n)return {...n,connection:await n.connection};let r,i;switch(n.db?.driver){case "sqlite":i=n.db?.url??Y.default_db_url,r=await createConnection({url:i,ddlDialect:"sqlite"});break;case "pglite":{i=n.db?.url??ie__default.join(process.cwd(),Y.default_db_dir);let{createPgliteConnection:s}=await nn("@supabase/lite/pglite","pglite","@electric-sql/pglite");r=await s({url:i});break}case "postgres":{i=n.db?.url??"";let{createPostgresConnection:s}=await nn("@supabase/lite/postgres","postgres","postgres");r=await s({url:i});break}default:i=n.db?.url??Y.default_db_url,r=await createConnection({url:i,ddlDialect:"postgres"});break}if(!r)throw new Error("Failed to create connection");return qe(Ve.default.green(" \u279C"),"Database located at",Ve.default.cyan(i??"in-memory")),{...n,connection:r}}async createApp(e,n){let r=await this.getConfig(e),i=new App({...r,options:{...r.options,server:{...r.options?.server,admin:n?.admin??r.options?.server?.admin??n?.adminDefault}}});return i.config.storage?.enabled&&process.env.EXPERIMENTAL_STORAGE==="1"&&!i._storageAdapter&&(i._storageAdapter=new Pt({basePath:ie__default.join(process.cwd(),Y.config_dir,".temp/storage")})),await i.init()}};var Ft=class extends ke{url(e){return this.projectUrl(e)}async ping(){return (await this.fetch("/v1/system/ping")).ok}async list(){let e=await this.fetch("/v1/projects");if(!e.ok)throw new Error("Failed to list projects");let n=await e.json();if(!Array.isArray(n))throw new Error("Failed to list projects");return n}async get(e){if(e=e??this.projectRef(),!e)throw new Error("No project ref found");let n=await this.fetch(`/v1/projects/${e}`);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(e){if(!e.name)throw new Error("Project name is required");let n=await this.fetch("/v1/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!n.ok){let i=await n.text().catch(()=>"");throw new Error(`Failed to create project: ${n.status} ${n.statusText}${i?` \u2014 ${i}`:""}`)}let r=await n.json();if(!r||!r.id)throw new Error("Failed to create project");return r}async getConfig(e){let n=await this.fetch(`/v1/projects/${e}/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(e,n){let r=await this.fetch(`/v1/projects/${e}/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(e){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(e);return await new App({...i.config,connection:cloud({projectRef:e,token:n.session.access_token,host:this.config.host})}).init()}};var It=class extends Re{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:e,error:n}=await this.getSession();if(n)throw n;return e?.session?.access_token}async requireSession(){let e=await this.getAccessToken();if(!e)throw new Error("Not authenticated, sign in first.");return e}async init(){let e={...this.config};return this.config.withSupabaseClient!==false&&(e.client=this.client,e.token=await this.getAccessToken()),this.project={local:new Ot(e),remote:new Ft(e)},this}};async function qs(t={}){return await new It({host:Oe,projectsHost:Tt,root:pe.projectDir(),...t}).init()}var pn=Pe(Fe());var an=Pe(Fe());var Vs=["toml","json","ts","mts","js","mjs","cjs"];async function Ge(t){let e=ie__default.relative(process.cwd(),Y.config_dir);if(!t)for(let n of Vs){let r=ie__default.join(e,`config.${n}`);if(await V__default.access(r).then(()=>true).catch(()=>false)){t=r;break}}return t}async function hr(t){let e=await Ge(t);if(!e)return {};switch(qe(an.default.dim(`Using config file: ${an.default.cyan(`./${e}`)}`)),e.split(".").pop()){case "toml":return je(await V__default.readFile(e,"utf-8"));case "json":return JSON.parse(await V__default.readFile(e,"utf-8"));case "ts":case "mts":case "js":case "mjs":case "cjs":try{return (await import(ie__default.join(process.cwd(),e))).default}catch(r){throw console.error("Failed to import config file",r),r}default:throw new Error(`Unsupported config file type: ${e}`)}}async function Gs(t,e=process.env){try{let n=await Ge(t);if(!n)return;Me(ie__default.dirname(ie__default.resolve(n)),{env:e});let i=He(await hr(t),e)?.auth?.publishable_key;return typeof i=="string"&&i.length>0?i:void 0}catch{return}}function Ws(t){if(!t||t===":memory:")return;let e=t;if(e.startsWith("file://")?e=e.slice(7):e.startsWith("file:")&&(e=e.slice(5)),!(!e||e===":memory:"))return ie__default.resolve(process.cwd(),e)}async function gr(t){let e=await Ge(t);e&&Me(ie__default.dirname(ie__default.resolve(e)));let n=He(await hr(t));if("connection"in n)return;let r=n?.db?.driver;if(r==="postgres")return;let i=n?.db?.url??(r==="pglite"?Y.default_db_dir:Y.default_db_url);return Ws(i)}var Ks="supabase-self-hosted";function ln(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function yr(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return new Uint8Array(n)}async function cn(t,e=Ks,n){let r=crypto.getRandomValues(new Uint8Array(17)),i=`sb_${t}_`,s=i+ln(r).slice(0,22),o=ln(await yr(`${e}|${s}`)).slice(0,8),a=`${s}_${o}`,l=await zs(a),c=a.slice(0,i.length+5);return {key:a,hash:l,prefix:c,type:t}}async function zs(t){return ln(await yr(t))}function br(t,e){let n="";try{n=St.readFileSync(t,"utf-8");}catch{n="";}let r=n.length>0?n.split(`
45
- `):[];r.length>0&&r[r.length-1]===""&&r.pop();let i=r.filter(s=>{let o=s.match(/^([A-Za-z_][A-Za-z0-9_]*)=/);return !(o&&o[1]in e)});for(let[s,o]of Object.entries(e))i.push(`${s}=${o}`);St.writeFileSync(t,i.join(`
42
+ `:r}var Zs={storage:"EXPERIMENTAL_STORAGE",cloud:"EXPERIMENTAL_CLOUD"},eo=["storage","cloud"];Object.fromEntries(eo.map(t=>[t,to(t)]));function to(t){let e=typeof process<"u"&&process.env||void 0;return e?e.NODE_ENV==="test"?true:e[Zs[t]]==="1":false}function He(t){let e=[],n="",r=0,i=t.length,s=false,o=false,a=0,c=/^create(\s+or\s+replace)?(\s+temp(orary)?)?$/i,l=m=>{vr(m).length>0&&e.push(m.trim());},f=()=>{s=false,o=false,a=0;};for(;r<i;){let m=t[r],u=t[r+1];if(m==="-"&&u==="-"){for(;r<i&&t[r]!==`
43
+ `;)n+=t[r],r++;continue}if(m==="/"&&u==="*"){for(n+="/*",r+=2;r<i&&!(t[r]==="*"&&t[r+1]==="/");)n+=t[r],r++;r<i&&(n+="*/",r+=2);continue}if(m==="'"){for(n+=m,r++;r<i;){if(t[r]==="'"&&t[r+1]==="'"){n+="''",r+=2;continue}if(n+=t[r],t[r]==="'"){r++;break}r++;}continue}if(m==='"'){for(n+=m,r++;r<i;){if(t[r]==='"'&&t[r+1]==='"'){n+='""',r+=2;continue}if(n+=t[r],t[r]==='"'){r++;break}r++;}continue}if(m==="$"){let p=t.indexOf("$",r+1);if(p!==-1){let d=t.slice(r,p+1);if(/^\$[A-Za-z_][A-Za-z0-9_]*\$$|^\$\$$/.test(d)){n+=d,r=p+1;let S=t.indexOf(d,r);S===-1?(n+=t.slice(r),r=i):(n+=t.slice(r,S+d.length),r=S+d.length);continue}}}if(/[A-Za-z_]/.test(m)){let p=r;for(;p<i&&/[A-Za-z0-9_]/.test(t[p]);)p++;let d=t.slice(r,p),b=d.toLowerCase();if(b==="trigger"&&c.test(vr(n))?s=true:s&&b==="begin"?(o=true,a++):s&&o&&b==="case"?a++:s&&o&&b==="end"&&a>0&&a--,n+=d,r=p,s&&o&&a===0){let S=r;for(;S<i&&/\s/.test(t[S]);)S++;t[S]===";"&&(r=S+1),l(n),n="",f();}continue}if(m===";"){if(s&&o&&a>0){n+=m,r++;continue}l(n),n="",f(),r++;continue}n+=m,r++;}return l(n),e}function vr(t){let e="",n=0,r=t.length;for(;n<r;){let i=t[n],s=t[n+1];if(i==="-"&&s==="-"){for(;n<r&&t[n]!==`
44
+ `;)n++;continue}if(i==="/"&&s==="*"){for(n+=2;n<r&&!(t[n]==="*"&&t[n+1]==="/");)n++;n+=2;continue}e+=i,n++;}return e.trim()}function gn(t){return typeof t=="number"?t:Number.parseInt(String(t),10)}var Gt=class{driver=W;basePath;constructor(e){this.basePath=le.resolve(e.basePath);}filePath(e,n){return le.join(this.basePath,e,n)}async ensureDir(e){await W.mkdir(le.dirname(e),{recursive:true});}async getObject(e,n,r,i){let s=this.filePath(e,n),o=await W.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 u=new Date(i.ifModifiedSince);if(o.mtime<=u)return {httpStatusCode:304,metadata:this.buildMetadata(o,a,n)}}let c,l,f=o.size,m=200;if(i?.range){let u=i.range.match(/^bytes=(\d+)-(\d*)$/);if(u){let p=Number.parseInt(u[1],10),d=u[2]?Number.parseInt(u[2],10):o.size-1;f=d-p+1,l=`bytes ${p}-${d}/${o.size}`,m=206,c=(await W.open(s,"r")).readableWebStream();}else c=(await W.open(s,"r")).readableWebStream();}else c=(await W.open(s,"r")).readableWebStream();return {httpStatusCode:m,metadata:{...this.buildMetadata(o,a,n),contentLength:f,contentRange:l},body:c}}async uploadObject(e,n,r,i,s,o){let a=this.filePath(e,n);await this.ensureDir(a);let c;if(i instanceof Uint8Array||Buffer.isBuffer(i))c=i;else {let m=[],u=i.getReader();for(;;){let{done:p,value:d}=await u.read();if(p)break;m.push(d);}c=Buffer.concat(m);}await W.writeFile(a,c);let l=await W.stat(a),f=`"${createHash("md5").update(c).digest("hex")}"`;return {cacheControl:o,contentLength:l.size,size:l.size,mimetype:s,lastModified:l.mtime,eTag:f}}async deleteObject(e,n,r){let i=this.filePath(e,n);await W.unlink(i).catch(s=>{if(s.code!=="ENOENT")throw s});}async deleteObjects(e,n){for(let r of n)await this.deleteObject(e,r,void 0);}async copyObject(e,n,r,i,s,o){let a=this.filePath(e,n),c=this.filePath(i,s);await this.ensureDir(c),await W.copyFile(a,c);let l=await W.stat(c),f=await W.readFile(c);return {httpStatusCode:200,eTag:`"${createHash("md5").update(f).digest("hex")}"`,lastModified:l.mtime}}async headObject(e,n,r){let i=this.filePath(e,n),s=await W.stat(i),o=`"${createHash("md5").update(`${i}:${s.mtimeMs}`).digest("hex")}"`;return this.buildMetadata(s,o,n)}async privateAssetUrl(e,n,r){return `file://${this.filePath(e,n)}`}buildMetadata(e,n,r){return {cacheControl:"no-cache",contentLength:gn(e.size),size:gn(e.size),mimetype:ro(r),lastModified:e.mtime,eTag:n}}};function ro(t){let e=le.extname(t).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"}[e]??"application/octet-stream"}var io=new Function("spec","return import(spec)");async function yn(t,e,n){try{return await io(t)}catch(r){throw r?.code==="ERR_MODULE_NOT_FOUND"||/Cannot find package/.test(String(r?.message))?new Error(`Driver '${e}' selected but '${n}' is not installed. Run: bun add ${n}`):r}}function tt(t,e={}){let n=le__default.resolve(e.cwd??process.cwd()),r=e.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=ao(le__default.resolve(t),n);for(let a of o)for(let c of s){let l=le__default.join(a,c),f;try{f=Lt.readFileSync(l,"utf-8");}catch{continue}let m;try{m=parse(f);}catch(u){throw new Error(`Failed to parse ${l}: ${u.message}`)}for(let[u,p]of Object.entries(m))r[u]===void 0&&(r[u]=p);}}function ao(t,e){let n=[],r=t,i=le__default.parse(r).root;for(;n.push(r),!(r===e||r===i);){let s=le__default.dirname(r);if(s===r)break;r=s;}return n}var lo=/^env\((\w+)\)$/;function nt(t,e=process.env){return bn(t,e)}function bn(t,e){if(typeof t=="string"){let n=t.match(lo);return n?e[n[1]]??"":t}if(Array.isArray(t))return t.map(n=>bn(n,e));if(t&&typeof t=="object"){let n=Object.getPrototypeOf(t);if(n!==Object.prototype&&n!==null)return t;let r={};for(let[i,s]of Object.entries(t))r[i]=bn(s,e);return r}return t}var co=process.env.LITE_VERBOSE==="1";function rt(...t){co&&console.error(...t);}var fo=["toml","json","ts","mts","js","mjs","cjs"],Wt=class extends qe{ref(){return this.projectRef()}setRef(e){return this.tempFs.write("project-ref",e),this}link(e){return this.setRef(e.id),e}unlink(){return this.tempFs.delete("project-ref"),this}url(){let e=this.ref();if(!e)throw new Error("No project linked");return this.projectUrl(e)}async getConfigPath(e){let n=le__default.relative(process.cwd(),ne.config_dir);if(!e)for(let r of fo){let i=le__default.join(n,`config.${r}`);if(await W__default.access(i).then(()=>true).catch(()=>false)){e=i;break}}return e}async readConfig(e){let n=await this.getConfigPath(e);if(!n)return {};rt(it.default.dim(`Using config file: ${it.default.cyan(`./${n}`)}`));let r=le__default.dirname(le__default.resolve(n));tt(r);let i=n.split(".").pop(),s;switch(i){case "toml":s=Qe(await W__default.readFile(n,"utf-8"));break;case "json":s=JSON.parse(await W__default.readFile(n,"utf-8"));break;case "ts":case "mts":case "js":case "mjs":case "cjs":try{s=(await import(le__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 nt(s)}async createConnection(){throw new Error("Not implemented")}async getConfig(e){let n=await this.readConfig(e);if("connection"in n)return {...n,connection:await n.connection};let r,i;switch(n.db?.driver){case "sqlite":i=n.db?.url??ne.default_db_url,r=await createConnection({url:i,ddlDialect:"sqlite"});break;case "pglite":{i=n.db?.url??le__default.join(process.cwd(),ne.default_db_dir);let{createPgliteConnection:s}=await yn("@supabase/lite/pglite","pglite","@electric-sql/pglite");r=await s({url:i});break}case "postgres":{i=n.db?.url??"";let{createPostgresConnection:s}=await yn("@supabase/lite/postgres","postgres","postgres");r=await s({url:i});break}default:i=n.db?.url??ne.default_db_url,r=await createConnection({url:i,ddlDialect:"postgres"});break}if(!r)throw new Error("Failed to create connection");return rt(it.default.green(" \u279C"),"Database located at",it.default.cyan(i??"in-memory")),{...n,connection:r}}async createApp(e,n){let r=await this.getConfig(e),i=new App({...r,options:{...r.options,server:{...r.options?.server,admin:n?.admin??r.options?.server?.admin??n?.adminDefault}}});return i.config.storage?.enabled&&process.env.EXPERIMENTAL_STORAGE==="1"&&!i._storageAdapter&&(i._storageAdapter=new Gt({basePath:le__default.join(process.cwd(),ne.config_dir,".temp/storage")})),await i.init()}};var Xt=class extends qe{url(e){return this.projectUrl(e)}async ping(){return (await this.fetch("/v1/system/ping")).ok}async list(){let e=await this.fetch("/v1/projects");if(!e.ok)throw new Error("Failed to list projects");let n=await e.json();if(!Array.isArray(n))throw new Error("Failed to list projects");return n}async get(e){if(e=e??this.projectRef(),!e)throw new Error("No project ref found");let n=await this.fetch(`/v1/projects/${e}`);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(e){if(!e.name)throw new Error("Project name is required");let n=await this.fetch("/v1/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!n.ok){let i=await n.text().catch(()=>"");throw new Error(`Failed to create project: ${n.status} ${n.statusText}${i?` \u2014 ${i}`:""}`)}let r=await n.json();if(!r||!r.id)throw new Error("Failed to create project");return r}async getConfig(e){let n=await this.fetch(`/v1/projects/${e}/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(e,n){let r=await this.fetch(`/v1/projects/${e}/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(e){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(e);return await new App({...i.config,connection:cloud({projectRef:e,token:n.session.access_token,host:this.config.host})}).init()}};var zt=class extends Me{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:e,error:n}=await this.getSession();if(n)throw n;return e?.session?.access_token}async requireSession(){let e=await this.getAccessToken();if(!e)throw new Error("Not authenticated, sign in first.");return e}async init(){let e={...this.config};return this.config.withSupabaseClient!==false&&(e.client=this.client,e.token=await this.getAccessToken()),this.project={local:new Wt(e),remote:new Xt(e)},this}};async function ho(t={}){return await new zt({host:ze,projectsHost:Ft,root:be.projectDir(),...t}).init()}var Cn=je(Ue());var Sn=je(Ue());var go=["toml","json","ts","mts","js","mjs","cjs"];async function st(t){let e=le__default.relative(process.cwd(),ne.config_dir);if(!t)for(let n of go){let r=le__default.join(e,`config.${n}`);if(await W__default.access(r).then(()=>true).catch(()=>false)){t=r;break}}return t}async function Pr(t){let e=await st(t);if(!e)return {};switch(rt(Sn.default.dim(`Using config file: ${Sn.default.cyan(`./${e}`)}`)),e.split(".").pop()){case "toml":return Qe(await W__default.readFile(e,"utf-8"));case "json":return JSON.parse(await W__default.readFile(e,"utf-8"));case "ts":case "mts":case "js":case "mjs":case "cjs":try{return (await import(le__default.join(process.cwd(),e))).default}catch(r){throw console.error("Failed to import config file",r),r}default:throw new Error(`Unsupported config file type: ${e}`)}}async function yo(t,e=process.env){try{let n=await st(t);if(!n)return;tt(le__default.dirname(le__default.resolve(n)),{env:e});let i=nt(await Pr(t),e)?.auth?.publishable_key;return typeof i=="string"&&i.length>0?i:void 0}catch{return}}function bo(t){if(!t||t===":memory:")return;let e=t;if(e.startsWith("file://")?e=e.slice(7):e.startsWith("file:")&&(e=e.slice(5)),!(!e||e===":memory:"))return le__default.resolve(process.cwd(),e)}async function Lr(t){let e=await st(t);e&&tt(le__default.dirname(le__default.resolve(e)));let n=nt(await Pr(t));if("connection"in n)return;let r=n?.db?.driver;if(r==="postgres")return;let i=n?.db?.url??(r==="pglite"?ne.default_db_dir:ne.default_db_url);return bo(i)}var wo="supabase-self-hosted";function En(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Ir(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return new Uint8Array(n)}async function _n(t,e=wo,n){let r=crypto.getRandomValues(new Uint8Array(17)),i=`sb_${t}_`,s=i+En(r).slice(0,22),o=En(await Ir(`${e}|${s}`)).slice(0,8),a=`${s}_${o}`,c=await xo(a),l=a.slice(0,i.length+5);return {key:a,hash:c,prefix:l,type:t}}async function xo(t){return En(await Ir(t))}function Fr(t,e){let n="";try{n=Lt.readFileSync(t,"utf-8");}catch{n="";}let r=n.length>0?n.split(`
45
+ `):[];r.length>0&&r[r.length-1]===""&&r.pop();let i=r.filter(s=>{let o=s.match(/^([A-Za-z_][A-Za-z0-9_]*)=/);return !(o&&o[1]in e)});for(let[s,o]of Object.entries(e))i.push(`${s}=${o}`);Lt.writeFileSync(t,i.join(`
46
46
  `)+`
47
- `);}function wr(t,e){let n;try{n=St.readFileSync(t,"utf-8");}catch{return [...e]}return e.filter(r=>!n.match(new RegExp(`^${r}=(.+)$`,"m"))?.[1]?.replace(/^"(.*)"$|^'(.*)'$/,(o,a,l)=>a??l??"")?.trim())}var Dt="SUPABASE_PUBLISHABLE_KEY",jt="SUPABASE_SECRET_KEY";async function Xs(t={}){let e=process.cwd();if(t.recreate){console.log(pn.default.dim("Recreating database..."));try{let a=await gr();a&&St.existsSync(a)&&(St.rmSync(a,{recursive:!0,force:!0}),console.log(pn.default.dim(` \u279C removed ${ie__default.relative(e,a)}`)));}catch{}try{St.rmSync(ie__default.join(e,"supabase",".temp"),{recursive:!0,force:!0});}catch{}}re(ie__default.join(e,"supabase"));let n=await Ge(),r=!n;if(!n){let a={api:{port:54321},db:{driver:"sqlite-postgres",url:"file:./supabase/.temp/data.db",migrations:{schema_paths:["./schemas/schema.sql"]},seed:{sql_paths:["./seed.sql"]}},auth:{enabled:true,jwt_secret:"dev-secret-change-me",jwt_expiry:3600,enable_signup:true,publishable_key:`env(${Dt})`,secret_key:`env(${jt})`,email:{enable_confirmations:false}}};t.driver==="pglite"&&(a.db.driver="pglite",a.db.url=ie__default.relative(process.cwd(),ie__default.join(e,"supabase",".temp","data")));let l=t.configFormat??"toml",c=ie__default.join(e,"supabase",`config.${l}`);l==="json"?Se(c,JSON.stringify(a)):Se(c,Zt(a));}re(ie__default.join(e,"supabase",".temp")),re(ie__default.join(e,"supabase","schemas"),()=>{Se(ie__default.join(e,"supabase","schemas","schema.sql"),t.template?Js:`-- This is a schema file for the database
48
- `);}),Se(ie__default.join(e,"supabase","seed.sql"),t.template?Ys:`-- This is a seed file for the database
49
- `);let i=ie__default.join(e,".env"),s=wr(i,[Dt,jt]),o;if(s.length>0){let a={};if(o={},s.includes(Dt)){let l=await cn("publishable");a[Dt]=l.key,o.publishable=l.key;}if(s.includes(jt)){let l=await cn("secret");a[jt]=l.key,o.secret=l.key;}br(i,a);}return {generatedKeys:o,created:r}}var Js=`
47
+ `);}function Dr(t,e){let n;try{n=Lt.readFileSync(t,"utf-8");}catch{return [...e]}return e.filter(r=>!n.match(new RegExp(`^${r}=(.+)$`,"m"))?.[1]?.replace(/^"(.*)"$|^'(.*)'$/,(o,a,c)=>a??c??"")?.trim())}var Jt="SUPABASE_PUBLISHABLE_KEY",Yt="SUPABASE_SECRET_KEY";async function So(t={}){let e=process.cwd();if(t.recreate){console.log(Cn.default.dim("Recreating database..."));try{let a=await Lr();a&&Lt.existsSync(a)&&(Lt.rmSync(a,{recursive:!0,force:!0}),console.log(Cn.default.dim(` \u279C removed ${le__default.relative(e,a)}`)));}catch{}try{Lt.rmSync(le__default.join(e,"supabase",".temp"),{recursive:!0,force:!0});}catch{}}ae(le__default.join(e,"supabase"));let n=await st(),r=!n;if(!n){let a={api:{port:54321},db:{driver:"sqlite-postgres",url:"file:./supabase/.temp/data.db",migrations:{schema_paths:["./schemas/schema.sql"]},seed:{sql_paths:["./seed.sql"]}},auth:{enabled:true,jwt_secret:"dev-secret-change-me",jwt_expiry:3600,enable_signup:true,publishable_key:`env(${Jt})`,secret_key:`env(${Yt})`,email:{enable_confirmations:false}}};t.driver==="pglite"&&(a.db.driver="pglite",a.db.url=le__default.relative(process.cwd(),le__default.join(e,"supabase",".temp","data")));let c=t.configFormat??"toml",l=le__default.join(e,"supabase",`config.${c}`);c==="json"?ve(l,JSON.stringify(a)):ve(l,hn(a));}ae(le__default.join(e,"supabase",".temp")),ae(le__default.join(e,"supabase","schemas"),()=>{ve(le__default.join(e,"supabase","schemas","schema.sql"),t.template?Eo:`-- This is a schema file for the database
48
+ `);}),ve(le__default.join(e,"supabase","seed.sql"),t.template?_o:`-- This is a seed file for the database
49
+ `);let i=le__default.join(e,".env"),s=Dr(i,[Jt,Yt]),o;if(s.length>0){let a={};if(o={},s.includes(Jt)){let c=await _n("publishable");a[Jt]=c.key,o.publishable=c.key;}if(s.includes(Yt)){let c=await _n("secret");a[Yt]=c.key,o.secret=c.key;}Fr(i,a);}return {generatedKeys:o,created:r}}var Eo=`
50
50
  create table todos (
51
51
  id serial primary key,
52
52
  title text not null,
@@ -59,7 +59,7 @@ create table todos (
59
59
  create table test (
60
60
  id serial primary key,
61
61
  name text not null
62
- )`,Ys="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 xr=createRequire(import.meta.url);function io(t){let e=normalize(t);return e.length>1&&e[e.length-1]===sep&&(e=e.substring(0,e.length-1)),e}var so=/[\\/]/g;function Tr(t,e){return t.replace(so,e)}var oo=/^[a-z]:[\\/]$/i;function ao(t){return t==="/"||oo.test(t)}function mn(t,e){let{resolvePaths:n,normalizePath:r,pathSeparator:i}=e,s=process.platform==="win32"&&t.includes("/")||t.startsWith(".");if(n&&(t=resolve(t)),(r||s)&&(t=io(t)),t===".")return "";let o=t[t.length-1]!==i;return Tr(o?t+i:t,i)}function Ar(t,e){return e+t}function lo(t,e){return function(n,r){return r.startsWith(t)?r.slice(t.length)+n:Tr(relative(t,r),e.pathSeparator)+e.pathSeparator+n}}function co(t){return t}function uo(t,e,n){return e+t+n}function fo(t,e){let{relativePaths:n,includeBasePath:r}=e;return n&&t?lo(t,e):r?Ar:co}function po(t){return function(e,n){n.push(e.substring(t.length)||".");}}function mo(t){return function(e,n,r){let i=e.substring(t.length)||".";r.every(s=>s(i,true))&&n.push(i);}}var ho=(t,e)=>{e.push(t||".");},go=(t,e,n)=>{let r=t||".";n.every(i=>i(r,true))&&e.push(r);},yo=()=>{};function bo(t,e){let{includeDirs:n,filters:r,relativePaths:i}=e;return n?i?r&&r.length?mo(t):po(t):r&&r.length?go:ho:yo}var wo=(t,e,n,r)=>{r.every(i=>i(t,false))&&n.files++;},xo=(t,e,n,r)=>{r.every(i=>i(t,false))&&e.push(t);},So=(t,e,n,r)=>{n.files++;},Eo=(t,e)=>{e.push(t);},To=()=>{};function Ao(t){let{excludeFiles:e,filters:n,onlyCounts:r}=t;return e?To:n&&n.length?r?wo:xo:r?So:Eo}var _o=t=>t,Co=()=>[""].slice(0,0);function Ro(t){return t.group?Co:_o}var ko=(t,e,n)=>{t.push({directory:e,files:n,dir:e});},$o=()=>{};function vo(t){return t.group?ko:$o}var No=function(t,e,n){let{queue:r,fs:i,options:{suppressErrors:s}}=e;r.enqueue(),i.realpath(t,(o,a)=>{if(o)return r.dequeue(s?null:o,e);i.stat(a,(l,c)=>{if(l)return r.dequeue(s?null:l,e);if(c.isDirectory()&&_r(t,a,e))return r.dequeue(null,e);n(c,a),r.dequeue(null,e);});});},Lo=function(t,e,n){let{queue:r,fs:i,options:{suppressErrors:s}}=e;r.enqueue();try{let o=i.realpathSync(t),a=i.statSync(o);if(a.isDirectory()&&_r(t,o,e))return;n(a,o);}catch(o){if(!s)throw o}};function Po(t,e){return !t.resolveSymlinks||t.excludeSymlinks?null:e?Lo:No}function _r(t,e,n){if(n.options.useRealPaths)return Oo(e,n);let r=dirname(t),i=1;for(;r!==n.root&&i<2;){let s=n.symlinks.get(r);!!s&&(s===e||s.startsWith(e)||e.startsWith(s))?i++:r=dirname(r);}return n.symlinks.set(t,e),i>1}function Oo(t,e){return e.visited.includes(t+e.options.pathSeparator)}var Fo=t=>t.counts,Io=t=>t.groups,Do=t=>t.paths,jo=t=>t.paths.slice(0,t.options.maxFiles),Uo=(t,e,n)=>(Ut(e,n,t.counts,t.options.suppressErrors),null),Bo=(t,e,n)=>(Ut(e,n,t.paths,t.options.suppressErrors),null),Mo=(t,e,n)=>(Ut(e,n,t.paths.slice(0,t.options.maxFiles),t.options.suppressErrors),null),Ho=(t,e,n)=>(Ut(e,n,t.groups,t.options.suppressErrors),null);function Ut(t,e,n,r){e(t&&!r?t:null,n);}function qo(t,e){let{onlyCounts:n,group:r,maxFiles:i}=t;return n?e?Fo:Uo:r?e?Io:Ho:i?e?jo:Mo:e?Do:Bo}var Cr={withFileTypes:true},Vo=(t,e,n,r,i)=>{if(t.queue.enqueue(),r<0)return t.queue.dequeue(null,t);let{fs:s}=t;t.visited.push(e),t.counts.directories++,s.readdir(e||".",Cr,(o,a=[])=>{i(a,n,r),t.queue.dequeue(t.options.suppressErrors?null:o,t);});},Go=(t,e,n,r,i)=>{let{fs:s}=t;if(r<0)return;t.visited.push(e),t.counts.directories++;let o=[];try{o=s.readdirSync(e||".",Cr);}catch(a){if(!t.options.suppressErrors)throw a}i(o,n,r);};function Wo(t){return t?Go:Vo}var Ko=class{count=0;constructor(t){this.onQueueEmpty=t;}enqueue(){return this.count++,this.count}dequeue(t,e){this.onQueueEmpty&&(--this.count<=0||t)&&(this.onQueueEmpty(t,e),t&&(e.controller.abort(),this.onQueueEmpty=void 0));}},zo=class{_files=0;_directories=0;set files(t){this._files=t;}get files(){return this._files}set directories(t){this._directories=t;}get directories(){return this._directories}get dirs(){return this._directories}},Xo=class{aborted=false;abort(){this.aborted=true;}},Rr=class{root;isSynchronous;state;joinPath;pushDirectory;pushFile;getArray;groupFiles;resolveSymlink;walkDirectory;callbackInvoker;constructor(t,e,n){this.isSynchronous=!n,this.callbackInvoker=qo(e,this.isSynchronous),this.root=mn(t,e),this.state={root:ao(this.root)?this.root:this.root.slice(0,-1),paths:[""].slice(0,0),groups:[],counts:new zo,options:e,queue:new Ko((r,i)=>this.callbackInvoker(i,r,n)),symlinks:new Map,visited:[""].slice(0,0),controller:new Xo,fs:e.fs||ro},this.joinPath=fo(this.root,e),this.pushDirectory=bo(this.root,e),this.pushFile=Ao(e),this.getArray=Ro(e),this.groupFiles=vo(e),this.resolveSymlink=Po(e,this.isSynchronous),this.walkDirectory=Wo(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=(t,e,n)=>{let{paths:r,options:{filters:i,resolveSymlinks:s,excludeSymlinks:o,exclude:a,maxFiles:l,signal:c,useRealPaths:u,pathSeparator:f},controller:m}=this.state;if(m.aborted||c&&c.aborted||l&&r.length>l)return;let g=this.getArray(this.state.paths);for(let y=0;y<t.length;++y){let E=t[y];if(E.isFile()||E.isSymbolicLink()&&!s&&!o){let T=this.joinPath(E.name,e);this.pushFile(T,g,this.state.counts,i);}else if(E.isDirectory()){let T=uo(E.name,e,this.state.options.pathSeparator);if(a&&a(E.name,T))continue;this.pushDirectory(T,r,i),this.walkDirectory(this.state,T,T,n-1,this.walk);}else if(this.resolveSymlink&&E.isSymbolicLink()){let T=Ar(E.name,e);this.resolveSymlink(T,this.state,(q,S)=>{if(q.isDirectory()){if(S=mn(S,this.state.options),a&&a(E.name,u?S:T+f))return;this.walkDirectory(this.state,S,u?S:T+f,n-1,this.walk);}else {S=u?S:T;let M=basename(S),K=mn(dirname(S),this.state.options);S=this.joinPath(M,K),this.pushFile(S,g,this.state.counts,i);}});}}this.groupFiles(this.state.groups,e,g);}};function Jo(t,e){return new Promise((n,r)=>{kr(t,e,(i,s)=>{if(i)return r(i);n(s);});})}function kr(t,e,n){new Rr(t,e,n).start();}function Yo(t,e){return new Rr(t,e).start()}var Sr=class{constructor(t,e){this.root=t,this.options=e;}withPromise(){return Jo(this.root,this.options)}withCallback(t){kr(this.root,this.options,t);}sync(){return Yo(this.root,this.options)}},$r=null;try{xr.resolve("picomatch"),$r=xr("picomatch");}catch{}var vr=class{globCache={};options={maxDepth:1/0,suppressErrors:true,pathSeparator:sep,filters:[]};globFunction;constructor(t){this.options={...this.options,...t},this.globFunction=this.options.globFunction;}group(){return this.options.group=true,this}withPathSeparator(t){return this.options.pathSeparator=t,this}withBasePath(){return this.options.includeBasePath=true,this}withRelativePaths(){return this.options.relativePaths=true,this}withDirs(){return this.options.includeDirs=true,this}withMaxDepth(t){return this.options.maxDepth=t,this}withMaxFiles(t){return this.options.maxFiles=t,this}withFullPaths(){return this.options.resolvePaths=true,this.options.includeBasePath=true,this}withErrors(){return this.options.suppressErrors=false,this}withSymlinks({resolvePaths:t=true}={}){return this.options.resolveSymlinks=true,this.options.useRealPaths=t,this.withFullPaths()}withAbortSignal(t){return this.options.signal=t,this}normalize(){return this.options.normalizePath=true,this}filter(t){return this.options.filters.push(t),this}onlyDirs(){return this.options.excludeFiles=true,this.options.includeDirs=true,this}exclude(t){return this.options.exclude=t,this}onlyCounts(){return this.options.onlyCounts=true,this}crawl(t){return new Sr(t||".",this.options)}withGlobFunction(t){return this.globFunction=t,this}crawlWithOptions(t,e){return this.options={...this.options,...e},new Sr(t||".",this.options)}glob(...t){return this.globFunction?this.globWithOptions(t):this.globWithOptions(t,{dot:true})}globWithOptions(t,...e){let n=this.globFunction||$r;if(!n)throw new Error("Please specify a glob function to use glob matching.");var r=this.globCache[t.join("\0")];return r||(r=n(t,...e),this.globCache[t.join("\0")]=r),this.options.filters.push(i=>r(i)),this}};var Ne=Pe(ti()),Ma=Array.isArray,si=/\\/g,Ha=/^[A-Za-z]:$/,oi=process.platform==="win32",qa=/^(\/?\.\.)+$/;function Va(t,e={}){let n=t.length,r=Array(n),i=Array(n),s,o;for(s=0;s<n;s++){let a=ai(t[s]);r[s]=a;let l=a.length,c=Array(l);for(o=0;o<l;o++)c[o]=(0, Ne.default)(a[o],e);i[s]=c;}return a=>{let l=a.split("/");if(l[0]===".."&&qa.test(a))return true;for(s=0;s<n;s++){let c=r[s],u=i[s],f=l.length,m=Math.min(f,c.length);for(o=0;o<m;){let g=c[o];if(g.includes("/"))return true;if(!u[o](l[o]))break;if(!e.noglobstar&&g==="**")return true;o++;}if(o===f)return true}return false}}var Ga=/^[A-Z]:\/$/i,Wa=oi?t=>Ga.test(t):t=>t==="/";function ni(t,e,n){if(t===e||e.startsWith(`${t}/`)){if(n){let i=t.length+ +!Wa(t);return (s,o)=>s.slice(i,o?-1:void 0)||"."}let r=e.slice(t.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(t,r)||".":r=>posix.relative(t,`${e}/${r}`)||"."}function Ka(t,e){if(e.startsWith(`${t}/`)){let n=e.slice(t.length+1);return r=>`${n}/${r}`}return n=>{let r=posix.relative(t,`${e}/${n}`);return n[n.length-1]==="/"&&r!==""?`${r}/`:r||"."}}function ri(t){return t.replace(Ha,e=>`${e}/`)}var za={parts:true};function ai(t){var e;let n=Ne.default.scan(t,za);return !((e=n.parts)===null||e===void 0)&&e.length?n.parts:[t]}var Xa=/(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g,Ja=/(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g,Ya=t=>t.replace(Xa,"\\$&"),Qa=t=>t.replace(Ja,"\\$&"),Za=oi?Qa:Ya;function el(t,e){let n=Ne.default.scan(t);return n.isGlob||n.negated}function Je(...t){console.log(`[tinyglobby ${new Date().toLocaleTimeString("es")}]`,...t);}function li(t){return typeof t=="string"?[t]:t??[]}var tl=/^(\/?\.\.)+/,nl=/\\(?=[()[\]{}!*+?@|])/g;function _n(t,e,n,r){var i;let s=e.cwd,o=t;t[t.length-1]==="/"&&(o=t.slice(0,-1)),o[o.length-1]!=="*"&&e.expandDirectories&&(o+="/**");let a=Za(s);o=isAbsolute(o.replace(nl,""))?posix.relative(a,o):posix.normalize(o);let l=(i=tl.exec(o))===null||i===void 0?void 0:i[0],c=ai(o);if(l){let f=(l.length+1)/3,m=0,g=a.split("/");for(;m<f&&c[m+f]===g[g.length+m-f];)o=o.slice(0,(f-m-1)*3)+o.slice((f-m)*3+c[m+f].length+1)||".",m++;let y=posix.join(s,l.slice(m*3));y[0]!=="."&&n.root.length>y.length&&(n.root=ri(y),n.depthOffset=-f+m);}if(!r&&n.depthOffset>=0){var u;(u=n.commonPath)!==null&&u!==void 0||(n.commonPath=c);let f=[],m=Math.min(n.commonPath.length,c.length);for(let g=0;g<m;g++){let y=c[g];if(y==="**"&&!c[g+1]){f.pop();break}if(g===c.length-1||y!==n.commonPath[g]||el(y))break;f.push(y);}n.depthOffset=f.length,n.commonPath=f,n.root=ri(f.length>0?posix.join(s,...f):s);}return o}function rl(t,e,n){let r=[],i=[];for(let s of t.ignore)s&&(s[0]!=="!"||s[1]==="(")&&i.push(_n(s,t,n,true));for(let s of e)s&&(s[0]!=="!"||s[1]==="("?r.push(_n(s,t,n,false)):(s[1]!=="!"||s[2]==="(")&&i.push(_n(s.slice(1),t,n,true)));return {match:r,ignore:i}}function il(t,e){let n=t.cwd,r={root:n,depthOffset:0},i=rl(t,e,r);t.debug&&Je("internal processing patterns:",i);let{absolute:s,caseSensitiveMatch:o,debug:a,dot:l,followSymbolicLinks:c,onlyDirectories:u}=t,f=r.root.replace(si,""),m={dot:l,nobrace:t.braceExpansion===false,nocase:!o,noextglob:t.extglob===false,noglobstar:t.globstar===false,posix:true},g=(0, Ne.default)(i.match,m),y=(0, Ne.default)(i.ignore,m),E=Va(i.match,m),T=ni(n,f,s),q=s?T:ni(n,f,true),S=(O,$)=>{let v=q($,true);return v!=="."&&!E(v)||y(v)},M;t.deep!==void 0&&(M=Math.round(t.deep-r.depthOffset));let K=new vr({filters:[a?(O,$)=>{let v=T(O,$),A=g(v)&&!y(v);return A&&Je(`matched ${v}`),A}:(O,$)=>{let v=T(O,$);return g(v)&&!y(v)}],exclude:a?(O,$)=>{let v=S(O,$);return Je(`${v?"skipped":"crawling"} ${$}`),v}:S,fs:t.fs,pathSeparator:"/",relativePaths:!s,resolvePaths:s,includeBasePath:s,resolveSymlinks:c,excludeSymlinks:!c,excludeFiles:u,includeDirs:u||!t.onlyFiles,maxDepth:M,signal:t.signal}).crawl(f);return t.debug&&Je("internal properties:",{...r,root:f}),[K,n!==f&&!s&&Ka(n,f)]}function sl(t,e){if(e)for(let n=t.length-1;n>=0;n--)t[n]=e(t[n]);return t}var ii={caseSensitiveMatch:true,debug:!!process.env.TINYGLOBBY_DEBUG,expandDirectories:true,followSymbolicLinks:true,onlyFiles:true};function ol(t){let e=Object.assign({},t);for(let n in ii)e[n]===void 0&&Object.assign(e,{[n]:ii[n]});return e.cwd=(e.cwd instanceof URL?fileURLToPath(e.cwd):resolve(e.cwd||process.cwd())).replace(si,"/"),e.ignore=li(e.ignore),e.fs&&(e.fs={readdir:e.fs.readdir||readdir,readdirSync:e.fs.readdirSync||readdirSync,realpath:e.fs.realpath||realpath,realpathSync:e.fs.realpathSync||realpathSync,stat:e.fs.stat||stat,statSync:e.fs.statSync||statSync}),e.debug&&Je("globbing with options:",e),e}function al(t,e={}){var n;if(t&&e?.patterns)throw new Error("Cannot pass patterns as both an argument and an option");let r=Ma(t)||typeof t=="string",i=li((n=r?t:t.patterns)!==null&&n!==void 0?n:"**/*"),s=ol(r?e:t);return i.length>0?il(s,i):[]}async function Ye(t,e){let[n,r]=al(t,e);return n?sl(await n.withPromise(),r):[]}var N=Pe(Fe());function te(t){return t.dialect==="postgres"?"pg":t.config?.ddlDialect==="sqlite"?"sqlite":"pg-flat"}function we(t){return t==="sqlite"?{schema_migrations:"migrations",seed_files:"seed_files"}:t==="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 Qe(t){return `'${t.replace(/'/g,"''")}'`}function ll(t){return `'${`{${t.map(r=>`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`).join(",")}}`.replace(/'/g,"''")}'`}function ci(t,e){return e==null?"NULL":t==="pg"?ll(e):Qe(JSON.stringify(e))}function Cn(t){return t==null?"NULL":Qe(t)}function ui(t){if(t==null)return [];if(Array.isArray(t))return t;if(typeof t=="string"){let e=t.trim();if(e==="")return [];try{let n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return []}}return []}function cl(t){return {version:String(t.version),name:t.name??null,statements:ui(t.statements),rollback:ui(t.rollback),created_by:t.created_by??null,idempotency_key:t.idempotency_key??null}}var ul=[{name:"created_by",pgType:"text",sqliteType:"TEXT"},{name:"idempotency_key",pgType:"text",sqliteType:"TEXT"},{name:"rollback",pgType:"text[]",sqliteType:"TEXT"}];function fl(t){let{schema_migrations:e,seed_files:n}=we(t);return t==="pg"?["CREATE SCHEMA IF NOT EXISTS supabase_migrations",`CREATE TABLE IF NOT EXISTS ${e} (
62
+ )`,_o="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 jr=createRequire(import.meta.url);function No(t){let e=normalize(t);return e.length>1&&e[e.length-1]===sep&&(e=e.substring(0,e.length-1)),e}var vo=/[\\/]/g;function Ur(t,e){return t.replace(vo,e)}var Oo=/^[a-z]:[\\/]$/i;function Po(t){return t==="/"||Oo.test(t)}function Rn(t,e){let{resolvePaths:n,normalizePath:r,pathSeparator:i}=e,s=process.platform==="win32"&&t.includes("/")||t.startsWith(".");if(n&&(t=resolve(t)),(r||s)&&(t=No(t)),t===".")return "";let o=t[t.length-1]!==i;return Ur(o?t+i:t,i)}function Br(t,e){return e+t}function Lo(t,e){return function(n,r){return r.startsWith(t)?r.slice(t.length)+n:Ur(relative(t,r),e.pathSeparator)+e.pathSeparator+n}}function Io(t){return t}function Fo(t,e,n){return e+t+n}function Do(t,e){let{relativePaths:n,includeBasePath:r}=e;return n&&t?Lo(t,e):r?Br:Io}function jo(t){return function(e,n){n.push(e.substring(t.length)||".");}}function Mo(t){return function(e,n,r){let i=e.substring(t.length)||".";r.every(s=>s(i,true))&&n.push(i);}}var qo=(t,e)=>{e.push(t||".");},Uo=(t,e,n)=>{let r=t||".";n.every(i=>i(r,true))&&e.push(r);},Bo=()=>{};function Ho(t,e){let{includeDirs:n,filters:r,relativePaths:i}=e;return n?i?r&&r.length?Mo(t):jo(t):r&&r.length?Uo:qo:Bo}var Vo=(t,e,n,r)=>{r.every(i=>i(t,false))&&n.files++;},Ko=(t,e,n,r)=>{r.every(i=>i(t,false))&&e.push(t);},Go=(t,e,n,r)=>{n.files++;},Wo=(t,e)=>{e.push(t);},Xo=()=>{};function zo(t){let{excludeFiles:e,filters:n,onlyCounts:r}=t;return e?Xo:n&&n.length?r?Vo:Ko:r?Go:Wo}var Jo=t=>t,Yo=()=>[""].slice(0,0);function Qo(t){return t.group?Yo:Jo}var Zo=(t,e,n)=>{t.push({directory:e,files:n,dir:e});},ea=()=>{};function ta(t){return t.group?Zo:ea}var na=function(t,e,n){let{queue:r,fs:i,options:{suppressErrors:s}}=e;r.enqueue(),i.realpath(t,(o,a)=>{if(o)return r.dequeue(s?null:o,e);i.stat(a,(c,l)=>{if(c)return r.dequeue(s?null:c,e);if(l.isDirectory()&&Hr(t,a,e))return r.dequeue(null,e);n(l,a),r.dequeue(null,e);});});},ra=function(t,e,n){let{queue:r,fs:i,options:{suppressErrors:s}}=e;r.enqueue();try{let o=i.realpathSync(t),a=i.statSync(o);if(a.isDirectory()&&Hr(t,o,e))return;n(a,o);}catch(o){if(!s)throw o}};function ia(t,e){return !t.resolveSymlinks||t.excludeSymlinks?null:e?ra:na}function Hr(t,e,n){if(n.options.useRealPaths)return sa(e,n);let r=dirname(t),i=1;for(;r!==n.root&&i<2;){let s=n.symlinks.get(r);!!s&&(s===e||s.startsWith(e)||e.startsWith(s))?i++:r=dirname(r);}return n.symlinks.set(t,e),i>1}function sa(t,e){return e.visited.includes(t+e.options.pathSeparator)}var oa=t=>t.counts,aa=t=>t.groups,la=t=>t.paths,ca=t=>t.paths.slice(0,t.options.maxFiles),ua=(t,e,n)=>(Qt(e,n,t.counts,t.options.suppressErrors),null),fa=(t,e,n)=>(Qt(e,n,t.paths,t.options.suppressErrors),null),pa=(t,e,n)=>(Qt(e,n,t.paths.slice(0,t.options.maxFiles),t.options.suppressErrors),null),ma=(t,e,n)=>(Qt(e,n,t.groups,t.options.suppressErrors),null);function Qt(t,e,n,r){e(t&&!r?t:null,n);}function da(t,e){let{onlyCounts:n,group:r,maxFiles:i}=t;return n?e?oa:ua:r?e?aa:ma:i?e?ca:pa:e?la:fa}var Vr={withFileTypes:true},ha=(t,e,n,r,i)=>{if(t.queue.enqueue(),r<0)return t.queue.dequeue(null,t);let{fs:s}=t;t.visited.push(e),t.counts.directories++,s.readdir(e||".",Vr,(o,a=[])=>{i(a,n,r),t.queue.dequeue(t.options.suppressErrors?null:o,t);});},ga=(t,e,n,r,i)=>{let{fs:s}=t;if(r<0)return;t.visited.push(e),t.counts.directories++;let o=[];try{o=s.readdirSync(e||".",Vr);}catch(a){if(!t.options.suppressErrors)throw a}i(o,n,r);};function ya(t){return t?ga:ha}var ba=class{count=0;constructor(t){this.onQueueEmpty=t;}enqueue(){return this.count++,this.count}dequeue(t,e){this.onQueueEmpty&&(--this.count<=0||t)&&(this.onQueueEmpty(t,e),t&&(e.controller.abort(),this.onQueueEmpty=void 0));}},wa=class{_files=0;_directories=0;set files(t){this._files=t;}get files(){return this._files}set directories(t){this._directories=t;}get directories(){return this._directories}get dirs(){return this._directories}},xa=class{aborted=false;abort(){this.aborted=true;}},Kr=class{root;isSynchronous;state;joinPath;pushDirectory;pushFile;getArray;groupFiles;resolveSymlink;walkDirectory;callbackInvoker;constructor(t,e,n){this.isSynchronous=!n,this.callbackInvoker=da(e,this.isSynchronous),this.root=Rn(t,e),this.state={root:Po(this.root)?this.root:this.root.slice(0,-1),paths:[""].slice(0,0),groups:[],counts:new wa,options:e,queue:new ba((r,i)=>this.callbackInvoker(i,r,n)),symlinks:new Map,visited:[""].slice(0,0),controller:new xa,fs:e.fs||$o},this.joinPath=Do(this.root,e),this.pushDirectory=Ho(this.root,e),this.pushFile=zo(e),this.getArray=Qo(e),this.groupFiles=ta(e),this.resolveSymlink=ia(e,this.isSynchronous),this.walkDirectory=ya(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=(t,e,n)=>{let{paths:r,options:{filters:i,resolveSymlinks:s,excludeSymlinks:o,exclude:a,maxFiles:c,signal:l,useRealPaths:f,pathSeparator:m},controller:u}=this.state;if(u.aborted||l&&l.aborted||c&&r.length>c)return;let p=this.getArray(this.state.paths);for(let d=0;d<t.length;++d){let b=t[d];if(b.isFile()||b.isSymbolicLink()&&!s&&!o){let S=this.joinPath(b.name,e);this.pushFile(S,p,this.state.counts,i);}else if(b.isDirectory()){let S=Fo(b.name,e,this.state.options.pathSeparator);if(a&&a(b.name,S))continue;this.pushDirectory(S,r,i),this.walkDirectory(this.state,S,S,n-1,this.walk);}else if(this.resolveSymlink&&b.isSymbolicLink()){let S=Br(b.name,e);this.resolveSymlink(S,this.state,(v,E)=>{if(v.isDirectory()){if(E=Rn(E,this.state.options),a&&a(b.name,f?E:S+m))return;this.walkDirectory(this.state,E,f?E:S+m,n-1,this.walk);}else {E=f?E:S;let I=basename(E),z=Rn(dirname(E),this.state.options);E=this.joinPath(I,z),this.pushFile(E,p,this.state.counts,i);}});}}this.groupFiles(this.state.groups,e,p);}};function Sa(t,e){return new Promise((n,r)=>{Gr(t,e,(i,s)=>{if(i)return r(i);n(s);});})}function Gr(t,e,n){new Kr(t,e,n).start();}function Ea(t,e){return new Kr(t,e).start()}var Mr=class{constructor(t,e){this.root=t,this.options=e;}withPromise(){return Sa(this.root,this.options)}withCallback(t){Gr(this.root,this.options,t);}sync(){return Ea(this.root,this.options)}},Wr=null;try{jr.resolve("picomatch"),Wr=jr("picomatch");}catch{}var Xr=class{globCache={};options={maxDepth:1/0,suppressErrors:true,pathSeparator:sep,filters:[]};globFunction;constructor(t){this.options={...this.options,...t},this.globFunction=this.options.globFunction;}group(){return this.options.group=true,this}withPathSeparator(t){return this.options.pathSeparator=t,this}withBasePath(){return this.options.includeBasePath=true,this}withRelativePaths(){return this.options.relativePaths=true,this}withDirs(){return this.options.includeDirs=true,this}withMaxDepth(t){return this.options.maxDepth=t,this}withMaxFiles(t){return this.options.maxFiles=t,this}withFullPaths(){return this.options.resolvePaths=true,this.options.includeBasePath=true,this}withErrors(){return this.options.suppressErrors=false,this}withSymlinks({resolvePaths:t=true}={}){return this.options.resolveSymlinks=true,this.options.useRealPaths=t,this.withFullPaths()}withAbortSignal(t){return this.options.signal=t,this}normalize(){return this.options.normalizePath=true,this}filter(t){return this.options.filters.push(t),this}onlyDirs(){return this.options.excludeFiles=true,this.options.includeDirs=true,this}exclude(t){return this.options.exclude=t,this}onlyCounts(){return this.options.onlyCounts=true,this}crawl(t){return new Mr(t||".",this.options)}withGlobFunction(t){return this.globFunction=t,this}crawlWithOptions(t,e){return this.options={...this.options,...e},new Mr(t||".",this.options)}glob(...t){return this.globFunction?this.globWithOptions(t):this.globWithOptions(t,{dot:true})}globWithOptions(t,...e){let n=this.globFunction||Wr;if(!n)throw new Error("Please specify a glob function to use glob matching.");var r=this.globCache[t.join("\0")];return r||(r=n(t,...e),this.globCache[t.join("\0")]=r),this.options.filters.push(i=>r(i)),this}};var Ke=je(wi()),pl=Array.isArray,_i=/\\/g,ml=/^[A-Za-z]:$/,Ti=process.platform==="win32",dl=/^(\/?\.\.)+$/;function hl(t,e={}){let n=t.length,r=Array(n),i=Array(n),s,o;for(s=0;s<n;s++){let a=Ai(t[s]);r[s]=a;let c=a.length,l=Array(c);for(o=0;o<c;o++)l[o]=(0, Ke.default)(a[o],e);i[s]=l;}return a=>{let c=a.split("/");if(c[0]===".."&&dl.test(a))return true;for(s=0;s<n;s++){let l=r[s],f=i[s],m=c.length,u=Math.min(m,l.length);for(o=0;o<u;){let p=l[o];if(p.includes("/"))return true;if(!f[o](c[o]))break;if(!e.noglobstar&&p==="**")return true;o++;}if(o===m)return true}return false}}var gl=/^[A-Z]:\/$/i,yl=Ti?t=>gl.test(t):t=>t==="/";function xi(t,e,n){if(t===e||e.startsWith(`${t}/`)){if(n){let i=t.length+ +!yl(t);return (s,o)=>s.slice(i,o?-1:void 0)||"."}let r=e.slice(t.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(t,r)||".":r=>posix.relative(t,`${e}/${r}`)||"."}function bl(t,e){if(e.startsWith(`${t}/`)){let n=e.slice(t.length+1);return r=>`${n}/${r}`}return n=>{let r=posix.relative(t,`${e}/${n}`);return n[n.length-1]==="/"&&r!==""?`${r}/`:r||"."}}function Si(t){return t.replace(ml,e=>`${e}/`)}var wl={parts:true};function Ai(t){var e;let n=Ke.default.scan(t,wl);return !((e=n.parts)===null||e===void 0)&&e.length?n.parts:[t]}var xl=/(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g,Sl=/(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g,El=t=>t.replace(xl,"\\$&"),_l=t=>t.replace(Sl,"\\$&"),Tl=Ti?_l:El;function Al(t,e){let n=Ke.default.scan(t);return n.isGlob||n.negated}function ut(...t){console.log(`[tinyglobby ${new Date().toLocaleTimeString("es")}]`,...t);}function Ci(t){return typeof t=="string"?[t]:t??[]}var Cl=/^(\/?\.\.)+/,Rl=/\\(?=[()[\]{}!*+?@|])/g;function Mn(t,e,n,r){var i;let s=e.cwd,o=t;t[t.length-1]==="/"&&(o=t.slice(0,-1)),o[o.length-1]!=="*"&&e.expandDirectories&&(o+="/**");let a=Tl(s);o=isAbsolute(o.replace(Rl,""))?posix.relative(a,o):posix.normalize(o);let c=(i=Cl.exec(o))===null||i===void 0?void 0:i[0],l=Ai(o);if(c){let m=(c.length+1)/3,u=0,p=a.split("/");for(;u<m&&l[u+m]===p[p.length+u-m];)o=o.slice(0,(m-u-1)*3)+o.slice((m-u)*3+l[u+m].length+1)||".",u++;let d=posix.join(s,c.slice(u*3));d[0]!=="."&&n.root.length>d.length&&(n.root=Si(d),n.depthOffset=-m+u);}if(!r&&n.depthOffset>=0){var f;(f=n.commonPath)!==null&&f!==void 0||(n.commonPath=l);let m=[],u=Math.min(n.commonPath.length,l.length);for(let p=0;p<u;p++){let d=l[p];if(d==="**"&&!l[p+1]){m.pop();break}if(p===l.length-1||d!==n.commonPath[p]||Al(d))break;m.push(d);}n.depthOffset=m.length,n.commonPath=m,n.root=Si(m.length>0?posix.join(s,...m):s);}return o}function kl(t,e,n){let r=[],i=[];for(let s of t.ignore)s&&(s[0]!=="!"||s[1]==="(")&&i.push(Mn(s,t,n,true));for(let s of e)s&&(s[0]!=="!"||s[1]==="("?r.push(Mn(s,t,n,false)):(s[1]!=="!"||s[2]==="(")&&i.push(Mn(s.slice(1),t,n,true)));return {match:r,ignore:i}}function $l(t,e){let n=t.cwd,r={root:n,depthOffset:0},i=kl(t,e,r);t.debug&&ut("internal processing patterns:",i);let{absolute:s,caseSensitiveMatch:o,debug:a,dot:c,followSymbolicLinks:l,onlyDirectories:f}=t,m=r.root.replace(_i,""),u={dot:c,nobrace:t.braceExpansion===false,nocase:!o,noextglob:t.extglob===false,noglobstar:t.globstar===false,posix:true},p=(0, Ke.default)(i.match,u),d=(0, Ke.default)(i.ignore,u),b=hl(i.match,u),S=xi(n,m,s),v=s?S:xi(n,m,true),E=(N,O)=>{let P=v(O,true);return P!=="."&&!b(P)||d(P)},I;t.deep!==void 0&&(I=Math.round(t.deep-r.depthOffset));let z=new Xr({filters:[a?(N,O)=>{let P=S(N,O),T=p(P)&&!d(P);return T&&ut(`matched ${P}`),T}:(N,O)=>{let P=S(N,O);return p(P)&&!d(P)}],exclude:a?(N,O)=>{let P=E(N,O);return ut(`${P?"skipped":"crawling"} ${O}`),P}:E,fs:t.fs,pathSeparator:"/",relativePaths:!s,resolvePaths:s,includeBasePath:s,resolveSymlinks:l,excludeSymlinks:!l,excludeFiles:f,includeDirs:f||!t.onlyFiles,maxDepth:I,signal:t.signal}).crawl(m);return t.debug&&ut("internal properties:",{...r,root:m}),[z,n!==m&&!s&&bl(n,m)]}function Nl(t,e){if(e)for(let n=t.length-1;n>=0;n--)t[n]=e(t[n]);return t}var Ei={caseSensitiveMatch:true,debug:!!process.env.TINYGLOBBY_DEBUG,expandDirectories:true,followSymbolicLinks:true,onlyFiles:true};function vl(t){let e=Object.assign({},t);for(let n in Ei)e[n]===void 0&&Object.assign(e,{[n]:Ei[n]});return e.cwd=(e.cwd instanceof URL?fileURLToPath(e.cwd):resolve(e.cwd||process.cwd())).replace(_i,"/"),e.ignore=Ci(e.ignore),e.fs&&(e.fs={readdir:e.fs.readdir||readdir,readdirSync:e.fs.readdirSync||readdirSync,realpath:e.fs.realpath||realpath,realpathSync:e.fs.realpathSync||realpathSync,stat:e.fs.stat||stat,statSync:e.fs.statSync||statSync}),e.debug&&ut("globbing with options:",e),e}function Ol(t,e={}){var n;if(t&&e?.patterns)throw new Error("Cannot pass patterns as both an argument and an option");let r=pl(t)||typeof t=="string",i=Ci((n=r?t:t.patterns)!==null&&n!==void 0?n:"**/*"),s=vl(r?e:t);return i.length>0?$l(s,i):[]}async function ft(t,e){let[n,r]=Ol(t,e);return n?Nl(await n.withPromise(),r):[]}var L=je(Ue());var Bi=je(Ue());function Pl(t,e){return t==="migrations"||t==="supabase_migrations.schema_migrations"||t==="supabase_migrations.seed_files"||e==="sqlite"&&t==="seed_files"}function en(t,e){let n=r=>Pl(r,e);return {...t,tables:t.tables.filter(r=>!n(r.name)),columns:t.columns.filter(r=>!n(r.table)),indexes:t.indexes.filter(r=>!n(r.table)),foreign_keys:t.foreign_keys.filter(r=>!n(r.table)),primary_keys:t.primary_keys.filter(r=>!n(r.table))}}function oe(t){return t.dialect==="postgres"?"pg":t.config?.ddlDialect==="sqlite"?"sqlite":"pg-flat"}function Ce(t){return t==="sqlite"?{schema_migrations:"migrations",seed_files:"seed_files"}:t==="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 pt(t){return `'${t.replace(/'/g,"''")}'`}function Ll(t){return `'${`{${t.map(r=>`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`).join(",")}}`.replace(/'/g,"''")}'`}function Ri(t,e){return e==null?"NULL":t==="pg"?Ll(e):pt(JSON.stringify(e))}function qn(t){return t==null?"NULL":pt(t)}function ki(t){if(t==null)return [];if(Array.isArray(t))return t;if(typeof t=="string"){let e=t.trim();if(e==="")return [];try{let n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return []}}return []}function Il(t,e){let n=()=>{throw new Error(`Migration history ${String(e)} has invalid statements`)};if(t==null)return n();let r=t;if(typeof t=="string")try{r=JSON.parse(t);}catch{return n()}return !Array.isArray(r)||!r.every(i=>typeof i=="string")?n():r}function Fl(t){return {version:String(t.version),name:t.name??null,statements:ki(t.statements),rollback:ki(t.rollback),created_by:t.created_by??null,idempotency_key:t.idempotency_key??null}}function Dl(t){return {...Fl(t),statements:Il(t.statements,t.version)}}var jl=[{name:"created_by",pgType:"text",sqliteType:"TEXT"},{name:"idempotency_key",pgType:"text",sqliteType:"TEXT"},{name:"rollback",pgType:"text[]",sqliteType:"TEXT"}];function Ml(t){let{schema_migrations:e,seed_files:n}=Ce(t);return t==="pg"?["CREATE SCHEMA IF NOT EXISTS supabase_migrations",`CREATE TABLE IF NOT EXISTS ${e} (
63
63
  version text NOT NULL PRIMARY KEY,
64
64
  statements text[],
65
65
  name text,
@@ -79,20 +79,25 @@ create table test (
79
79
  )`,`CREATE TABLE IF NOT EXISTS ${n} (
80
80
  path TEXT NOT NULL PRIMARY KEY,
81
81
  hash TEXT NOT NULL
82
- )`]}function pl(t){let{schema_migrations:e}=we(t);return [`CREATE UNIQUE INDEX IF NOT EXISTS ${t==="sqlite"?"migrations_idempotency_key_idx":"schema_migrations_idempotency_key_idx"} ON ${e} (idempotency_key)`]}function fi(t,e){let{schema_migrations:n}=we(t);return `INSERT INTO ${n} (version, name, statements, rollback, created_by, idempotency_key) VALUES (${Qe(e.version)}, ${Cn(e.name)}, ${ci(t,e.statements)}, ${ci(t,e.rollback??null)}, ${Cn(e.created_by??null)}, ${Cn(e.idempotency_key??null)}) ON CONFLICT (idempotency_key) DO UPDATE SET version = EXCLUDED.version, name = EXCLUDED.name, statements = EXCLUDED.statements, rollback = EXCLUDED.rollback, created_by = EXCLUDED.created_by`}function ml(t){let{schema_migrations:e}=we(t);return `SELECT version FROM ${e} ORDER BY version ASC`}var dl="version, name, statements, rollback, created_by, idempotency_key";function hl(t){let{schema_migrations:e}=we(t);return `SELECT ${dl} FROM ${e} ORDER BY version ASC`}function gl(t){let{seed_files:e}=we(t);return e?`SELECT path, hash FROM ${e}`:null}function pi(t,e){let{seed_files:n}=we(t);return n?`INSERT INTO ${n} (path, hash) VALUES (${Qe(e.path)}, ${Qe(e.hash)}) ON CONFLICT (path) DO UPDATE SET hash = EXCLUDED.hash`:null}async function yl(t,e){let{schema_migrations:n}=we(e);for(let r of ul){let i=e==="pg"?r.pgType:r.sqliteType;if(e==="pg")await t.exec(`ALTER TABLE ${n} ADD COLUMN IF NOT EXISTS ${r.name} ${i}`);else try{await t.exec(`ALTER TABLE ${n} ADD COLUMN ${r.name} ${i}`);}catch{}}}async function Rn(t){let e=te(t);for(let n of fl(e))await t.exec(n);await yl(t,e);for(let n of pl(e))await t.exec(n);}async function mi(t){let e=te(t);return ((await t.exec(ml(e)))?.rows??[]).map(r=>r.version)}async function di(t){let e=te(t);return ((await t.exec(hl(e)))?.rows??[]).map(cl)}async function hi(t){let e=te(t),n=gl(e);return n?((await t.exec(n))?.rows??[]).map(i=>({path:i.path,hash:i.hash})):[]}var wl=/^(\d{14})(?:_([^.]+))?\.sql$/;function gi(t){return te(t.connection)==="sqlite"?"./sqlite-migrations/*.sql":"./migrations/*.sql"}function xl(t){return ie__default.posix.dirname(gi(t))}async function Ze(t){let e=ie__default.join(process.cwd(),"supabase"),n=await Ye([gi(t)],{cwd:e,absolute:true}),r=[];for(let i of n){let s=ie__default.basename(i),o=wl.exec(s);if(!o)continue;let a=await V__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))}async function yi(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(r=>r.toString(16).padStart(2,"0")).join("")}async function bi(t){let e=[...t].sort((r,i)=>r.version.localeCompare(i.version)),n=await Promise.all(e.map(async r=>{let i=await yi((r.statements??[]).join(";"));return [r.version,i]}));return yi(JSON.stringify(n))}var El="supabase/.temp/.deparse-cache.json",Tl=2;function Al(t){return te(t.connection)==="pg-flat"}function _l(){return ie__default.join(process.cwd(),El)}async function Cl(t){let e=[];try{e=await di(t.connection);}catch(n){if(!String(n).includes("no such table"))throw n}return bi(e)}async function Ae(t){if(Al(t))try{let e=t.connection,n=SqliteConnection.serializeDeparseInfo(e.config?.translation?.deparse),[r,i]=await Promise.all([Cl(t),Mt(t,await et(t))]),s={v:Tl,fingerprint:r,schemaHash:i,deparse:n},o=_l();await V__default.mkdir(ie__default.dirname(o),{recursive:!0}),await V__default.writeFile(o,JSON.stringify(s),"utf-8");}catch{}}var qi=["./schemas/*.sql"],Vi="supabase/.temp/.translation-cache.json",Gi=3;async function ac(t,e){let n=await t.connection.introspect(),r=Yn(n);await Wi(t,{...e,dbHasTables:n.tables.length>0,dbFingerprint:r}),await fc(t);let i=await t.connection.introspect();Ki(i,t);}async function lc(t){return Ye(t.config.db?.seed?.sql_paths??["./seed.sql"],{cwd:ie__default.join(process.cwd(),"supabase"),absolute:true})}async function cc(t){let e=await lc(t);return Promise.all(e.map(async n=>{let r=await V__default.readFile(n,"utf-8"),i=createHash("sha256").update(r).digest("hex");return {path:ie__default.relative(process.cwd(),n),hash:i,statements:splitSqlStatements(r)}}))}async function uc(t,e){if(t.config.db?.seed?.enabled===false)return 0;let r=(await cc(t)).filter(l=>l.statements.length>0);if(r.length===0)return 0;await Rn(t.connection);let i=te(t.connection),s=new Map((await hi(t.connection)).map(l=>[l.path,l.hash])),o=r.filter(l=>s.get(l.path)!==l.hash);if(o.length===0)return 0;console.log(N.default.dim("Seeding database..."));let a=[];for(let l of o){a.push(...l.statements);let c=pi(i,{path:l.path,hash:l.hash});c&&a.push(c);}try{await t.connection.transaction(a);}catch(l){let c="Fix `supabase/seed.sql`, then re-run `lite dev` to reapply the schema and reseed.";throw new Error(`Seed failed and was rolled back: ${String(l.message??l)}
83
- ${c}`)}return o.reduce((l,c)=>l+c.statements.length,0)}async function fc(t){await uc(t);}async function et(t){let e=await Ye(t.config?.db?.migrations?.schema_paths??qi,{cwd:ie__default.join(process.cwd(),Y.config_dir),absolute:true}),n=await Promise.all(e.map(async r=>await V__default.readFile(r,"utf-8"))).then(r=>r.map(i=>i.split(`
82
+ )`]}function ql(t){let{schema_migrations:e}=Ce(t);return [`CREATE UNIQUE INDEX IF NOT EXISTS ${t==="sqlite"?"migrations_idempotency_key_idx":"schema_migrations_idempotency_key_idx"} ON ${e} (idempotency_key)`]}function $i(t,e){let{schema_migrations:n}=Ce(t);return `INSERT INTO ${n} (version, name, statements, rollback, created_by, idempotency_key) VALUES (${pt(e.version)}, ${qn(e.name)}, ${Ri(t,e.statements)}, ${Ri(t,e.rollback??null)}, ${qn(e.created_by??null)}, ${qn(e.idempotency_key??null)}) ON CONFLICT (idempotency_key) DO UPDATE SET version = EXCLUDED.version, name = EXCLUDED.name, statements = EXCLUDED.statements, rollback = EXCLUDED.rollback, created_by = EXCLUDED.created_by`}function Ul(t){let{schema_migrations:e}=Ce(t);return `SELECT version FROM ${e} ORDER BY version ASC`}var Bl="version, name, statements, rollback, created_by, idempotency_key";function Hl(t){let{schema_migrations:e}=Ce(t);return `SELECT ${Bl} FROM ${e} ORDER BY version ASC`}function Vl(t){let{seed_files:e}=Ce(t);return e?`SELECT path, hash FROM ${e}`:null}function Ni(t,e){let{seed_files:n}=Ce(t);return n?`INSERT INTO ${n} (path, hash) VALUES (${pt(e.path)}, ${pt(e.hash)}) ON CONFLICT (path) DO UPDATE SET hash = EXCLUDED.hash`:null}async function Kl(t,e){let{schema_migrations:n}=Ce(e);for(let r of jl){let i=e==="pg"?r.pgType:r.sqliteType;if(e==="pg")await t.exec(`ALTER TABLE ${n} ADD COLUMN IF NOT EXISTS ${r.name} ${i}`);else try{await t.exec(`ALTER TABLE ${n} ADD COLUMN ${r.name} ${i}`);}catch{}}}async function Un(t){let e=oe(t);for(let n of Ml(e))await t.exec(n);await Kl(t,e);for(let n of ql(e))await t.exec(n);}async function vi(t){let e=oe(t);return ((await t.exec(Ul(e)))?.rows??[]).map(r=>r.version)}async function Oi(t){let e=oe(t);return ((await t.exec(Hl(e)))?.rows??[]).map(Dl)}async function Pi(t){let e=oe(t),n=Vl(e);return n?((await t.exec(n))?.rows??[]).map(i=>({path:i.path,hash:i.hash})):[]}function we(t){let e=(r,i)=>[...r].sort((s,o)=>i(s).localeCompare(i(o))),n={tables:e(t.tables??[],r=>`${r.schema??""}.${r.name}`).map(r=>({schema:r.schema,name:r.name,type:r.type,sql:r.sql})),columns:e(t.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:e(t.indexes??[],r=>`${r.schema??""}.${r.table}.${r.name}`).map(r=>({schema:r.schema,table:r.table,name:r.name,unique:r.unique,columns:r.columns,sql:r.sql})),foreign_keys:e(t.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:e(t.primary_keys??[],r=>`${r.schema??""}.${r.table}`).map(r=>({schema:r.schema,table:r.table,columns:r.columns})),check_constraints:e(t.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:e(t.unique_constraints??[],r=>`${r.schema??""}.${r.table}.${r.name}`).map(r=>({schema:r.schema,table:r.table,name:r.name,columns:r.columns})),views:e(t.views??[],r=>`${r.schema??""}.${r.name}`).map(r=>({schema:r.schema,name:r.name,sql:r.sql})),triggers:e(t.triggers??[],r=>`${r.schema??""}.${r.table}.${r.name}`).map(r=>({schema:r.schema,table:r.table,name:r.name,sql:r.sql})),custom_types:e(t.custom_types??[],r=>`${r.schema??""}.${r.type}`).map(r=>({schema:r.schema,type:r.type,kind:r.kind,values:r.values,fields:r.fields}))};return createHash("sha256").update(JSON.stringify(n)).digest("hex")}var de=class extends Error{constructor(n,r,i){super(r,i);this.failure=n;this.name="AppliedMetadataError";}};function Ii(t){return createHash("sha256").update(JSON.stringify(t)).digest("hex")}function Bn(t){return t.connection.config.baseSchema??""}function Fi(t){return {...t.connection.config.translation?.schemas??{}}}function Xl(t){return Ii(t.map(({version:e,statements:n})=>({version:e,statements:n})))}function Hn(t){return Ii({baseSchema:Bn(t),translationSchemas:Fi(t)})}function zl(t){return String(t).toLowerCase().includes("no such table")}async function Jl(t){try{return await Oi(t.connection)}catch(e){if(zl(e))return [];throw new de("invalid-history",`Applied migration history is invalid: ${String(e)}`,{cause:e})}}async function Di(t){let e=await t.introspect({postprocess:false}),n=t.config.ddlDialect;return we(en(e,n))}async function Vn(t){let e=await Jl(t);return {rows:e,sourceHash:Xl(e),runtimeHash:Hn(t),dbFingerprint:await Di(t.connection)}}function Yl(t){return t.map(e=>e.statements.join(`;
83
+ `)).filter(e=>e.trim().length>0).join(`;
84
+
85
+ `)}async function ji(t){let{createConnection:e}=await import('@supabase/lite/sqlite');return await e({url:":memory:",ddlDialect:"postgres",translation:{schemas:Fi(t)}})}async function Ql(t,e){if(!e.trim())return;let n=await t.translateDdl(e,{strict:true}),r=typeof n=="string"?n:n.ddl??"";for(let i of He(r))try{await t.exec(i);}catch{}}async function Zl(t,e){let n=await ji(t);try{await Ql(n,Bn(t));for(let r of e){let i=r.statements.join(`;
86
+ `);if(!i.trim())continue;let s=await n.translateDdl(i),o=typeof s=="string"?s:s.ddl??"";await n.transaction(He(o),{intent:"migration"});}return await Di(n)}finally{await n.close();}}async function ec(t,e){let n=await ji(t);try{let r=[Bn(t),Yl(e)].filter(s=>s.trim()).join(`
87
+
88
+ `),i=await n.translateDdl(r,{strict:!0});return SqliteConnection.serializeDeparseInfo(typeof i=="string"?void 0:i)}finally{await n.close();}}async function Mi(t,e){let n=e??await Vn(t);try{let[r,i]=await Promise.all([ec(t,n.rows),Zl(t,n.rows)]);if(i!==n.dbFingerprint)throw new de("drift","The live database structure differs from the applied migration history.");return {...n,deparse:r}}catch(r){throw r instanceof de?r:new de("translation",`Applied migration history could not be replayed: ${String(r)}`,{cause:r})}}function qi(t,e){let n=t.connection;typeof n.updateDeparseInfo=="function"&&n.updateDeparseInfo(SqliteConnection.parseDeparseInfo(e,{strict:true}));}function Kn(t){return oe(t.connection)==="pg-flat"}var Hi="supabase/.temp/.runtime-metadata-cache.json",sc=3,Ui=new WeakMap;function oc(){return le__default.join(process.cwd(),Hi)}function ac(t){return createHash("sha256").update(JSON.stringify(t)).digest("hex")}async function lc(t){let e=t.connection,n=await e.introspect({postprocess:false});return we(en(n,e.config.ddlDialect))}async function cc(t,e,n=W__default){let r=le__default.join(le__default.dirname(t),`.${le__default.basename(t)}.${process.pid}.${randomUUID()}.tmp`);await n.mkdir(le__default.dirname(t),{recursive:true});try{await n.writeFile(r,e,"utf-8"),await n.rename(r,t);}catch(i){throw await n.unlink(r).catch(()=>{}),i}}async function dt(t,e){if(!Kn(t))return false;try{let n=t.connection,r=e.metadata??SqliteConnection.serializeDeparseInfo(n.config?.translation?.deparse),i={v:sc,workflow:e.workflow,sourceHash:e.sourceHash,runtimeHash:e.runtimeHash??Hn(t),dbFingerprint:e.dbFingerprint??await lc(t),payloadChecksum:ac(r),metadata:r};return await cc(oc(),JSON.stringify(i)),!0}catch(n){return console.warn(Bi.default.yellow(`Could not write ${Hi}: ${String(n)}`)),false}}var uc=new Set(["SELECT","INSERT","UPDATE","DELETE","ALL"]),fc=new Set(["unique","check","foreign_key"]),he=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),te=t=>typeof t=="string",Le=t=>typeof t=="string"&&t.length>0,tn=t=>Array.isArray(t)&&t.every(te),xe=(t,e)=>t==null||e(t),Gn=(t,e)=>he(t)&&Object.values(t).every(e);function pc(t){return !he(t)||!te(t.name)||!Le(t.table)||!xe(t.schema,te)||!te(t.command)||!uc.has(t.command)||typeof t.permissive!="boolean"||!tn(t.roles)||!xe(t.using,e=>typeof e=="object")?false:xe(t.withCheck,e=>typeof e=="object")}function mc(t){if(!he(t)||!he(t.context))return false;let e=t.context;return !te(e.schema)||!Le(e.table)||!Le(e.column)||!Le(e.pgTypeName)||typeof e.nullable!="boolean"||typeof e.isPrimaryKey!="boolean"||typeof e.isUnique!="boolean"||typeof e.isSerial!="boolean"||!(e.defaultValue===null||te(e.defaultValue))?false:xe(t.extra,he)}function dc(t){return !he(t)||!te(t.schema)||!Le(t.table)||!te(t.kind)||!fc.has(t.kind)||!tn(t.columns)||!xe(t.name,te)||!xe(t.refSchema,te)||!xe(t.refTable,te)?false:xe(t.refColumns,tn)}function hc(t){return !he(t)||!te(t.schema)||!Le(t.table)||!te(t.text)?false:xe(t.column,te)}function gc(t){return !(!he(t)||!he(t.rls)||!Array.isArray(t.rls.tables)||!t.rls.tables.every(Le)||!Array.isArray(t.rls.policies)||!t.rls.policies.every(pc)||!Gn(t.vars,he)||!Gn(t.enums,tn)||!Gn(t.schema,e=>Array.isArray(e)&&e.every(mc))||!Array.isArray(t.tableConstraints)||!t.tableConstraints.every(dc)||!Array.isArray(t.comments)||!t.comments.every(hc))}async function yc(t,e){let n=await Mi(t,e);if(!gc(n.deparse))throw new de("translation","Rebuilt runtime metadata is incomplete.");return qi(t,n.deparse),await dt(t,{workflow:"migrations",sourceHash:n.sourceHash,runtimeHash:n.runtimeHash,dbFingerprint:n.dbFingerprint,metadata:n.deparse}),n}async function Vi(t){if(!Kn(t))return true;try{let e=await Vn(t);return await yc(t,e),Ui.delete(t),!0}catch(e){let n=e instanceof de?e:new de("translation",String(e),{cause:e});return Ui.set(t,n),false}}var ms=["./schemas/*.sql"],ds="supabase/.temp/.translation-cache.json",hs=3;async function eu(t,e){let n=await t.connection.introspect(),r=we(n);await gs(t,{...e,dbHasTables:n.tables.length>0,dbFingerprint:r}),await iu(t);let i=await t.connection.introspect();ys(i,t);}async function tu(t){return ft(t.config.db?.seed?.sql_paths??["./seed.sql"],{cwd:le__default.join(process.cwd(),"supabase"),absolute:true})}async function nu(t){let e=await tu(t);return Promise.all(e.map(async n=>{let r=await W__default.readFile(n,"utf-8"),i=createHash("sha256").update(r).digest("hex");return {path:le__default.relative(process.cwd(),n),hash:i,statements:splitSqlStatements(r)}}))}async function ru(t,e){if(t.config.db?.seed?.enabled===false)return 0;let r=(await nu(t)).filter(c=>c.statements.length>0);if(r.length===0)return 0;await Un(t.connection);let i=oe(t.connection),s=new Map((await Pi(t.connection)).map(c=>[c.path,c.hash])),o=r.filter(c=>s.get(c.path)!==c.hash);if(o.length===0)return 0;console.log(L.default.dim("Seeding database..."));let a=[];for(let c of o){a.push(...c.statements);let l=Ni(i,{path:c.path,hash:c.hash});l&&a.push(l);}try{await t.connection.transaction(a);}catch(c){let l="Fix `supabase/seed.sql`, then re-run `lite dev` to reapply the schema and reseed.";throw new Error(`Seed failed and was rolled back: ${String(c.message??c)}
89
+ ${l}`)}return o.reduce((c,l)=>c+l.statements.length,0)}async function iu(t){await ru(t);}async function su(t){let e=await ft(t.config?.db?.migrations?.schema_paths??ms,{cwd:le__default.join(process.cwd(),ne.config_dir),absolute:true}),n=await Promise.all(e.map(async r=>await W__default.readFile(r,"utf-8"))).then(r=>r.map(i=>i.split(`
84
90
  `).filter(s=>s.trim().length>0&&!s.trim().startsWith("--")).join(`
85
91
  `)).join(`
86
- `));return n||""}async function Wi(t,e){let n=await et(t);if(!(!n&&(await Ze(t)).length>0)&&!(!n&&!t.connection.config.baseSchema)){if(e?.dbHasTables&&await mc(t,n,e.dbFingerprint)){console.log(N.default.dim("Schema unchanged \u2014 skipping translation.")),await Ae(t);return}try{let r=t.connection.createMigrator(n),i=await r.diff(),s=r.translationResult?.ast,o=await t.connection.introspect(),a=Yn(o);if(i.plan.steps.length===0){await Hi(t,n,s,a),await Ae(t);return}await r.migratePlan(i.plan,{force:e?.force??!1}),bc(i);let l=await t.connection.introspect();return await Hi(t,n,s,Yn(l)),await Ae(t),console.log(""),wc(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 t.connection.exec("rollback");}catch{}}}}}function pc(t){return t.connection.config?.baseSchema??""}function Mt(t,e){let n=createHash("sha256");return n.update(JSON.stringify([pc(t),e??""])),n.digest("hex")}function Yn(t){let e=(r,i)=>[...r].sort((s,o)=>i(s).localeCompare(i(o))),n={tables:e(t.tables??[],r=>`${r.schema??""}.${r.name}`).map(r=>({schema:r.schema,name:r.name,type:r.type,sql:r.sql})),columns:e(t.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:e(t.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:e(t.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:e(t.primary_keys??[],r=>`${r.schema??""}.${r.table}`).map(r=>({schema:r.schema,table:r.table,columns:r.columns})),check_constraints:e(t.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:e(t.unique_constraints??[],r=>`${r.schema??""}.${r.table}.${r.name}`).map(r=>({schema:r.schema,table:r.table,name:r.name,columns:r.columns})),views:e(t.views??[],r=>`${r.schema??""}.${r.name}`).map(r=>({schema:r.schema,name:r.name,sql:r.sql})),triggers:e(t.triggers??[],r=>`${r.schema??""}.${r.table}.${r.name}`).map(r=>({schema:r.schema,table:r.table,name:r.name,sql:r.sql})),custom_types:e(t.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 mc(t,e,n){let r=t.connection;if(typeof r.updateDeparseInfo!="function")return false;let i=ie__default.join(process.cwd(),Vi),s;try{s=await V__default.readFile(i,"utf-8");}catch{return false}let o;try{o=JSON.parse(s);}catch{return false}if(o.v!==Gi||o.hash!==Mt(t,e)||!n||o.dbFingerprint!==n||!o.ast||typeof o.ast!="object")return false;try{let a=await Promise.resolve().then(()=>(Bi(),Ui)),l=o.ast,c=a.collectEnums(l),u=a.collectSchema(l,c),f=a.collectVariables(l),m=a.collectTableConstraints(l),g=a.collectComments(l),y=r.config?.translation?.schemas?.defaultSchema,{policies:E,tables:T}=a.collectPolicies(l,{defaultSchema:y});return r.updateDeparseInfo({enums:c,rls:{tables:T,policies:E},schema:u,vars:f,tableConstraints:m,comments:g}),!0}catch{return false}}async function Hi(t,e,n,r){if(!n||typeof n!="object")return;let i={v:Gi,hash:Mt(t,e),dbFingerprint:r,ast:n},s=ie__default.join(process.cwd(),Vi);try{await V__default.mkdir(ie__default.dirname(s),{recursive:!0}),await V__default.writeFile(s,JSON.stringify(i),"utf-8");}catch{}}function Ki(t,e){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:t.tables.length,columns:t.columns.length,indexes:t.indexes.length});let r=e.config.rls??e.connection.config.translation?.deparse?.rls??{tables:new Set([]),policies:[]};n(N.default.green("AUTH"),{enabled:!!e.config.auth?.enabled,tables:ensureVar.Set(r.tables).size,policies:ensureVar.Array(r.policies).length});}function dc(t){let e=ie__default.join(process.cwd(),Y.config_dir),r=(t.config?.db?.migrations?.schema_paths??qi).map(i=>{let s=i.split("/"),o=s.findIndex(l=>/[*?[{]/.test(l)),a=(o===-1?s.slice(0,-1):s.slice(0,o)).join("/");return ie__default.resolve(e,a||".")});return [...new Set(r)]}function hc(t,e){let n,r=setTimeout(()=>{console.log(N.default.dim("Watching for changes...")),n=oc.watch(dc(t),{ignoreInitial:true});let i=async s=>{if(!s.endsWith(".sql"))return;console.log(),console.log(N.default.dim(`Schema changed: ${s}`)),await Wi(t,e);let o=await t.connection.introspect();Ki(o,t);};n.on("change",i),n.on("add",i);},200);return async()=>{clearTimeout(r),await n?.close();}}function gc(t,e){let n=r=>r;return t.plan.steps.flatMap(r=>[r.description?n(`-- ${r.description}`):"",r.sql+`
92
+ `));return n||""}async function gs(t,e){let n=await su(t);if(!n){if(!await Vi(t))throw new Error("Applied migration metadata could not be rebuilt. Run `lite db reset`.");return}if(e?.dbHasTables&&await au(t,n,e.dbFingerprint)){console.log(L.default.dim("Schema unchanged \u2014 skipping translation.")),await dt(t,{workflow:"declarative",sourceHash:Nt(t,n)});return}try{let r=t.connection.createMigrator(n),i=await r.diff(),s=r.translationResult?.ast,o=await t.connection.introspect(),a=we(o);if(i.plan.steps.length===0){await fs(t,n,s,a),await dt(t,{workflow:"declarative",sourceHash:Nt(t,n)});return}await r.migratePlan(i.plan,{force:e?.force??!1}),pu(i);let c=await t.connection.introspect();return await fs(t,n,s,we(c)),await dt(t,{workflow:"declarative",sourceHash:Nt(t,n)}),console.log(""),mu(i),i}catch(r){if(String(r).includes("likely empty"))console.log(L.default.dim("Nothing to migrate."));else {console.error("Migration error: "+String(r));try{await t.connection.exec("rollback");}catch{}}}}function ou(t){return t.connection.config?.baseSchema??""}function Nt(t,e){let n=createHash("sha256");return n.update(JSON.stringify([ou(t),e??""])),n.digest("hex")}async function au(t,e,n){let r=t.connection;if(typeof r.updateDeparseInfo!="function")return false;let i=le__default.join(process.cwd(),ds),s;try{s=await W__default.readFile(i,"utf-8");}catch{return false}let o;try{o=JSON.parse(s);}catch{return false}if(o.v!==hs||o.hash!==Nt(t,e)||!n||o.dbFingerprint!==n||!o.ast||typeof o.ast!="object")return false;try{let a=await Promise.resolve().then(()=>(cs(),ls)),c=o.ast,l=a.collectEnums(c),f=a.collectSchema(c,l),m=a.collectVariables(c),u=a.collectTableConstraints(c),p=a.collectComments(c),d=r.config?.translation?.schemas?.defaultSchema,{policies:b,tables:S}=a.collectPolicies(c,{defaultSchema:d});return r.updateDeparseInfo({enums:l,rls:{tables:S,policies:b},schema:f,vars:m,tableConstraints:u,comments:p}),!0}catch{return false}}async function fs(t,e,n,r){if(!n||typeof n!="object")return;let i={v:hs,hash:Nt(t,e),dbFingerprint:r,ast:n},s=le__default.join(process.cwd(),ds);try{await W__default.mkdir(le__default.dirname(s),{recursive:!0}),await W__default.writeFile(s,JSON.stringify(i),"utf-8");}catch{}}function ys(t,e){console.log();let n=(i,s)=>{let o=c=>{let l=L.default.dim;return typeof c=="number"&&(c>=0&&(l=c>0?L.default.green:L.default.dim),c<0&&(l=L.default.red)),typeof c=="boolean"?c?L.default.green("\u2713"):L.default.red("\u2717"):l(String(c))},a=Object.entries(s).map(([c,l])=>`${c}: ${o(l)}`).join(L.default.dim(" / "));console.log(`${L.default.dim("[")} ${i} ${L.default.dim("]")} ${a}`);};n(L.default.green("DATA"),{tables:t.tables.length,columns:t.columns.length,indexes:t.indexes.length});let r=e.config.rls??e.connection.config.translation?.deparse?.rls??{tables:new Set([]),policies:[]};n(L.default.green("AUTH"),{enabled:!!e.config.auth?.enabled,tables:ensureVar.Set(r.tables).size,policies:ensureVar.Array(r.policies).length});}function lu(t){let e=le__default.join(process.cwd(),ne.config_dir),r=(t.config?.db?.migrations?.schema_paths??ms).map(i=>{let s=i.split("/"),o=s.findIndex(c=>/[*?[{]/.test(c)),a=(o===-1?s.slice(0,-1):s.slice(0,o)).join("/");return le__default.resolve(e,a||".")});return [...new Set(r)]}function cu(t,e){let n,r=setTimeout(()=>{console.log(L.default.dim("Watching for changes...")),n=Zc.watch(lu(t),{ignoreInitial:true});let i=async s=>{if(!s.endsWith(".sql"))return;console.log(),console.log(L.default.dim(`Schema changed: ${s}`)),await gs(t,e);let o=await t.connection.introspect();ys(o,t);};n.on("change",i),n.on("add",i);},200);return async()=>{clearTimeout(r),await n?.close();}}function uu(t,e){let n=r=>r;return t.plan.steps.flatMap(r=>[r.description?n(`-- ${r.description}`):"",r.sql+`
87
93
  `]).filter(r=>r.trim().length>0).join(`
88
- `)}function yc(t){let e=new Date;return `${e.getFullYear().toString()+(e.getMonth()+1).toString().padStart(2,"0")+e.getDate().toString().padStart(2,"0")+e.getHours().toString().padStart(2,"0")+e.getMinutes().toString().padStart(2,"0")+e.getSeconds().toString().padStart(2,"0")}.sql`}function bc(t,e){let n="./supabase/.temp/migrations";re(n);let r=yc(),i=gc(t);Se(ie__default.join(n,r),i),console.log(N.default.dim(`Migration written to ${N.default.cyan(ie__default.join(n,r))}`));}function wc({diff:t}){if(typeof t=="string"){console.log(N.default.cyan(t));return}if(!t.has_changes)return;console.log(N.default.bgWhite(N.default.black(" Schema Diff "))),console.log();let e={added:{color:N.default.green,symbol:"+"},removed:{color:N.default.red,symbol:"-"},modified:{color:N.default.yellow,symbol:"~"}};if(t.tables.length>0){console.log(N.default.dim("Tables:"));for(let n of t.tables){let{color:r,symbol:i}=e[n.type];console.log(r(`${i} ${n.name}`));}console.log();}if(t.columns.length>0){console.log(N.default.dim("Columns:"));for(let n of t.columns){let{color:r,symbol:i}=e[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(t.indexes.length>0){console.log(N.default.dim("Indexes:"));for(let n of t.indexes){let{color:r,symbol:i}=e[n.type];console.log(r(`${i} ${n.name} on ${n.table}`));}console.log();}if(t.foreign_keys.length>0){console.log(N.default.dim("Foreign Keys:"));for(let n of t.foreign_keys){let{color:r,symbol:i}=e[n.type];console.log(r(`${i} ${n.table}.${n.column} \u2192 ${n.ref_table}.${n.ref_column}`));}console.log();}}var er=["anon","authenticated","service_role"];function xc(t){return t==="service_role"?"NOLOGIN BYPASSRLS":"NOLOGIN"}function tr(t){return t.size===0?"":`DO $$ BEGIN${[...t].map(n=>`
94
+ `)}function fu(t){let e=new Date;return `${e.getFullYear().toString()+(e.getMonth()+1).toString().padStart(2,"0")+e.getDate().toString().padStart(2,"0")+e.getHours().toString().padStart(2,"0")+e.getMinutes().toString().padStart(2,"0")+e.getSeconds().toString().padStart(2,"0")}.sql`}function pu(t,e){let n="./supabase/.temp/migrations";ae(n);let r=fu(),i=uu(t);ve(le__default.join(n,r),i),console.log(L.default.dim(`Migration written to ${L.default.cyan(le__default.join(n,r))}`));}function mu({diff:t}){if(typeof t=="string"){console.log(L.default.cyan(t));return}if(!t.has_changes)return;console.log(L.default.bgWhite(L.default.black(" Schema Diff "))),console.log();let e={added:{color:L.default.green,symbol:"+"},removed:{color:L.default.red,symbol:"-"},modified:{color:L.default.yellow,symbol:"~"}};if(t.tables.length>0){console.log(L.default.dim("Tables:"));for(let n of t.tables){let{color:r,symbol:i}=e[n.type];console.log(r(`${i} ${n.name}`));}console.log();}if(t.columns.length>0){console.log(L.default.dim("Columns:"));for(let n of t.columns){let{color:r,symbol:i}=e[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(t.indexes.length>0){console.log(L.default.dim("Indexes:"));for(let n of t.indexes){let{color:r,symbol:i}=e[n.type];console.log(r(`${i} ${n.name} on ${n.table}`));}console.log();}if(t.foreign_keys.length>0){console.log(L.default.dim("Foreign Keys:"));for(let n of t.foreign_keys){let{color:r,symbol:i}=e[n.type];console.log(r(`${i} ${n.table}.${n.column} \u2192 ${n.ref_table}.${n.ref_column}`));}console.log();}}var hu=/^(\d{14})(?:_([^.]+))?\.sql$/;function bs(t){return oe(t.connection)==="sqlite"?"./sqlite-migrations/*.sql":"./migrations/*.sql"}function gu(t){return le__default.posix.dirname(bs(t))}async function gr(t){let e=le__default.join(process.cwd(),"supabase"),n=await ft([bs(t)],{cwd:e,absolute:true}),r=[];for(let i of n){let s=le__default.basename(i),o=hu.exec(s);if(!o)continue;let a=await W__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 br=["anon","authenticated","service_role"];function yu(t){return t==="service_role"?"NOLOGIN BYPASSRLS":"NOLOGIN"}function wr(t){return t.size===0?"":`DO $$ BEGIN${[...t].map(n=>`
89
95
  IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '${n}') THEN
90
- CREATE ROLE ${n} ${xc(n)};
96
+ CREATE ROLE ${n} ${yu(n)};
91
97
  END IF;`).join("")}
92
98
  END $$;
93
- `}tr(new Set(er));function Xi(t,e){return t?t.quoted?t.value===e:t.value.toLowerCase()===e:false}function oe(t){return t?.quoted?t.value:t?.value.toLowerCase()}function Sc(t,e){let n="",r=e+1;for(;r<t.length;){if(t[r]==='"'&&t[r+1]==='"'){n+='"',r+=2;continue}if(t[r]==='"')return {token:{value:n,quoted:true},end:r+1};n+=t[r],r++;}return {token:{value:n,quoted:true},end:r}}function Ec(t,e){let n=e+1;for(;n<t.length;){if(t[n]==="'"&&t[n+1]==="'"){n+=2;continue}if(t[n]==="'")return n+1;n++;}return n}function Tc(t,e){let n=/^\$[A-Za-z_][A-Za-z0-9_]*\$|^\$\$/.exec(t.slice(e))?.[0];if(!n)return;let r=e+n.length,i=t.indexOf(n,r);return i===-1?t.length:i+n.length}function Ji(t){let e=[],n=0;for(;n<t.length;){let r=t[n],i=t[n+1];if(/\s/.test(r)){n++;continue}if(r==="-"&&i==="-"){for(n+=2;n<t.length&&t[n]!==`
94
- `;)n++;continue}if(r==="/"&&i==="*"){for(n+=2;n<t.length&&!(t[n]==="*"&&t[n+1]==="/");)n++;n=n<t.length?n+2:n;continue}if(r==="'"){n=Ec(t,n);continue}if(r==="$"){let s=Tc(t,n);if(s!==void 0){n=s;continue}}if(r==='"'){let{token:s,end:o}=Sc(t,n);e.push(s),n=o;continue}if(r===","||r===";"){e.push({value:r,quoted:false}),n++;continue}if(/[A-Za-z_]/.test(r)){let s=n;for(n++;n<t.length&&/[A-Za-z0-9_$]/.test(t[n]);)n++;e.push({value:t.slice(s,n).toLowerCase(),quoted:false});continue}n++;}return e}function Ac(t,e){let n=oe(t[e]),r=oe(t[e+1]);if((n==="create"||n==="alter")&&(r==="role"||r==="user"||r==="group"))return t[e+2]}function _c(t){let e=new Set,n=Ji(t);for(let r=0;r<n.length;r++){if(oe(n[r])!=="create")continue;let i=Ac(n,r);for(let s of er)Xi(i,s)&&e.add(s);}return e}function Zn(t,e,n){let r=new Set([";","as","by","check","for","granted","in","on","option","using","where","with"]);for(let i=e;i<t.length;i++){let s=oe(t[i]);if(!s||r.has(s))return;for(let o of er)Xi(t[i],o)&&n.add(o);}}function Cc(t){let e=[],n=[];for(let r of t){if(oe(r)===";"){n.length>0&&e.push(n),n=[];continue}n.push(r);}return n.length>0&&e.push(n),e}function zi(t,e){return t.some(n=>oe(n)===e)}function Rc(t){let e=new Set,n=Cc(Ji(t));for(let r of n){let i=oe(r[0]);for(let a=0;a<r.length;a++){let l=oe(r[a]);l==="to"&&(zi(r,"grant")||zi(r,"policy")||oe(r[a-1])==="owner")&&Zn(r,a+1,e),l==="from"&&i==="revoke"&&Zn(r,a+1,e);}let s=r.findIndex(a=>oe(a)==="to"),o=r.findIndex(a=>oe(a)==="on");i==="grant"&&s>1&&(o===-1||s<o)&&Zn(r,1,e);}return e}function Yi(t){let e=_c(t);return new Set([...Rc(t)].filter(n=>!e.has(n)))}async function kc(t,e={}){await t.ensureSystemSchema();let n=new Set(await mi(t.connection)),r=await Ze(t),i=te(t.connection),s=[],o=[];for(let l of r){if(n.has(l.version)){o.push(l);continue}let c=en(l.sql),u;if(i==="pg-flat"){let m=await t.connection.translateDdl(l.sql),g=typeof m=="string"?m:m.ddl??"";u=en(g);}else u=c;let f=fi(i,{version:l.version,name:l.name,statements:c});if(i==="pg"){let m=tr(Yi(l.sql));m&&await t.connection.exec(m);}await t.connection.transaction([...u,f],{intent:"migration"}),s.push(l);}let a=true;return i==="pg-flat"&&!e.persistWithDeclarative&&(await et(t)).trim()&&(a=false),i!=="sqlite"&&(r.length>0?await $c(t,r,{persist:a}):i==="pg-flat"&&a&&await Ae(t)),{applied:s,skipped:o}}async function $c(t,e,n){let r=e.map(a=>a.sql).join(`
95
- `);if(!r.trim())return;let i=t.connection;if(typeof i.translateDdl!="function"||typeof i.updateDeparseInfo!="function")return;let s=await i.translateDdl(r),o=i.config?.translation?.deparse??{};i.updateDeparseInfo({...o,...s}),n?.persist!==false&&await Ae(t);}/*! Bundled license information:
99
+ `}wr(new Set(br));function xs(t,e){return t?t.quoted?t.value===e:t.value.toLowerCase()===e:false}function fe(t){return t?.quoted?t.value:t?.value.toLowerCase()}function bu(t,e){let n="",r=e+1;for(;r<t.length;){if(t[r]==='"'&&t[r+1]==='"'){n+='"',r+=2;continue}if(t[r]==='"')return {token:{value:n,quoted:true},end:r+1};n+=t[r],r++;}return {token:{value:n,quoted:true},end:r}}function wu(t,e){let n=e+1;for(;n<t.length;){if(t[n]==="'"&&t[n+1]==="'"){n+=2;continue}if(t[n]==="'")return n+1;n++;}return n}function xu(t,e){let n=/^\$[A-Za-z_][A-Za-z0-9_]*\$|^\$\$/.exec(t.slice(e))?.[0];if(!n)return;let r=e+n.length,i=t.indexOf(n,r);return i===-1?t.length:i+n.length}function Ss(t){let e=[],n=0;for(;n<t.length;){let r=t[n],i=t[n+1];if(/\s/.test(r)){n++;continue}if(r==="-"&&i==="-"){for(n+=2;n<t.length&&t[n]!==`
100
+ `;)n++;continue}if(r==="/"&&i==="*"){for(n+=2;n<t.length&&!(t[n]==="*"&&t[n+1]==="/");)n++;n=n<t.length?n+2:n;continue}if(r==="'"){n=wu(t,n);continue}if(r==="$"){let s=xu(t,n);if(s!==void 0){n=s;continue}}if(r==='"'){let{token:s,end:o}=bu(t,n);e.push(s),n=o;continue}if(r===","||r===";"){e.push({value:r,quoted:false}),n++;continue}if(/[A-Za-z_]/.test(r)){let s=n;for(n++;n<t.length&&/[A-Za-z0-9_$]/.test(t[n]);)n++;e.push({value:t.slice(s,n).toLowerCase(),quoted:false});continue}n++;}return e}function Su(t,e){let n=fe(t[e]),r=fe(t[e+1]);if((n==="create"||n==="alter")&&(r==="role"||r==="user"||r==="group"))return t[e+2]}function Eu(t){let e=new Set,n=Ss(t);for(let r=0;r<n.length;r++){if(fe(n[r])!=="create")continue;let i=Su(n,r);for(let s of br)xs(i,s)&&e.add(s);}return e}function yr(t,e,n){let r=new Set([";","as","by","check","for","granted","in","on","option","using","where","with"]);for(let i=e;i<t.length;i++){let s=fe(t[i]);if(!s||r.has(s))return;for(let o of br)xs(t[i],o)&&n.add(o);}}function _u(t){let e=[],n=[];for(let r of t){if(fe(r)===";"){n.length>0&&e.push(n),n=[];continue}n.push(r);}return n.length>0&&e.push(n),e}function ws(t,e){return t.some(n=>fe(n)===e)}function Tu(t){let e=new Set,n=_u(Ss(t));for(let r of n){let i=fe(r[0]);for(let a=0;a<r.length;a++){let c=fe(r[a]);c==="to"&&(ws(r,"grant")||ws(r,"policy")||fe(r[a-1])==="owner")&&yr(r,a+1,e),c==="from"&&i==="revoke"&&yr(r,a+1,e);}let s=r.findIndex(a=>fe(a)==="to"),o=r.findIndex(a=>fe(a)==="on");i==="grant"&&s>1&&(o===-1||s<o)&&yr(r,1,e);}return e}function Es(t){let e=Eu(t);return new Set([...Tu(t)].filter(n=>!e.has(n)))}async function Au(t){await t.ensureSystemSchema();let e=new Set(await vi(t.connection)),n=await gr(t),r=oe(t.connection),i=[],s=[];for(let o of n){if(e.has(o.version)){s.push(o);continue}let a=He(o.sql),c;if(r==="pg-flat"){let f=await t.connection.translateDdl(o.sql),m=typeof f=="string"?f:f.ddl??"";c=He(m);}else c=a;let l=$i(r,{version:o.version,name:o.name,statements:a});if(r==="pg"){let f=wr(Es(o.sql));f&&await t.connection.exec(f);}await t.connection.transaction([...c,l],{intent:"migration"}),i.push(o);}return {applied:i,skipped:s}}/*! Bundled license information:
96
101
 
97
102
  smol-toml/dist/error.js:
98
103
  smol-toml/dist/util.js:
@@ -130,4 +135,4 @@ smol-toml/dist/index.js:
130
135
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
131
136
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
132
137
  *)
133
- */export{kc as applyPendingMigrations,qs as createApi,Xs as ensureInitialStructure,ac as ensureSchema,Ze as listMigrationFiles,xl as migrationsDir,Gs as resolveConfiguredPublishableKey,hc as watchSchema};
138
+ */export{Au as applyPendingMigrations,ho as createApi,So as ensureInitialStructure,eu as ensureSchema,gr as listMigrationFiles,gu as migrationsDir,yo as resolveConfiguredPublishableKey,cu as watchSchema};