@supabase/lite 0.3.1-next.1 → 0.3.1-next.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LIMITATIONS.md +49 -0
- package/PATTERNS.md +119 -0
- package/README.md +47 -7
- package/STATUS.md +75 -2
- package/dist/cli/index.js +1 -1
- package/dist/cli/lib.js +2 -2
- package/dist/index.js +1 -1
- package/package.json +4 -1
- package/skills/supalite/SKILL.md +38 -0
package/dist/cli/index.js
CHANGED
|
@@ -60,7 +60,7 @@ create table test (
|
|
|
60
60
|
`)}function Kn(e){let t=[],r="",n=0,s=e.length,i=o=>{dg(o).length>0&&t.push(o.trim());};for(;n<s;){let o=e[n],a=e[n+1];if(o==="-"&&a==="-"){for(;n<s&&e[n]!==`
|
|
61
61
|
`;)r+=e[n],n++;continue}if(o==="/"&&a==="*"){for(r+="/*",n+=2;n<s&&!(e[n]==="*"&&e[n+1]==="/");)r+=e[n],n++;n<s&&(r+="*/",n+=2);continue}if(o==="'"){for(r+=o,n++;n<s;){if(e[n]==="'"&&e[n+1]==="'"){r+="''",n+=2;continue}if(r+=e[n],e[n]==="'"){n++;break}n++;}continue}if(o==='"'){for(r+=o,n++;n<s;){if(e[n]==='"'&&e[n+1]==='"'){r+='""',n+=2;continue}if(r+=e[n],e[n]==='"'){n++;break}n++;}continue}if(o==="$"){let l=e.indexOf("$",n+1);if(l!==-1){let c=e.slice(n,l+1);if(/^\$[A-Za-z_][A-Za-z0-9_]*\$$|^\$\$$/.test(c)){r+=c,n=l+1;let p=e.indexOf(c,n);p===-1?(r+=e.slice(n),n=s):(r+=e.slice(n,p+c.length),n=p+c.length);continue}}}if(o===";"){i(r),r="",n++;continue}r+=o,n++;}return i(r),t}function dg(e){let t="",r=0,n=e.length;for(;r<n;){let s=e[r],i=e[r+1];if(s==="-"&&i==="-"){for(;r<n&&e[r]!==`
|
|
62
62
|
`;)r++;continue}if(s==="/"&&i==="*"){for(r+=2;r<n&&!(e[r]==="*"&&e[r+1]==="/");)r++;r+=2;continue}t+=s,r++;}return t.trim()}function Gi(e){return (e??"").trim().toLowerCase()}function zi(e){return (e??"").replace(/\s+/g," ").replace(/"/g,"").trim().toLowerCase()}function Vi(e){if(e==null)return null;let t=e.trim();for(;t.startsWith("(")&&t.endsWith(")");)t=t.slice(1,-1).trim();return (t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"'))&&(t=t.slice(1,-1)),t}var _r=y(()=>{});function hg(e,t,r=void 0){let n=typeof t=="string"?vc(t):Xi(t);return Yn(e,n,r)}function Yn(e,t,r=void 0){let n=typeof t=="string"?t.split(/[.\[\]\"]+/).filter(s=>s):t;if(n.length===0)return e;try{let[s,...i]=n;return !s||!(s in e)?r:Yn(e[s],i,r)}catch{if(typeof r<"u")return r;throw new Error(`Invalid path: ${n.join(".")}`)}}function wg(e){return e===null}function me(e){return !Array.isArray(e)&&typeof e=="object"&&e!==null}function bg(e){return Object.prototype.toString.call(e)==="[object Object]"}function Ge(e){return typeof e=="string"}function Xe(e){return typeof e=="number"}function Sg(e){return typeof e=="number"&&Number.isInteger(e)}function Zi(e){return typeof e=="boolean"}function ot(e){return Array.isArray(e)}function Eg(e){return typeof e!="boolean"}function xg(e){return e!==void 0&&Eg(e)&&"type"in e}function ve(e){return e!==void 0&&me(e)&&$e in e}function _g(e){return ve(e)&&typeof e.toJSON()=="boolean"}function $g(e,t,r){if(!e)throw new yg(t,r)}function Tc(e){return Ge(e)?e.normalize("NFC"):e}function $r(e,t){let r=typeof e;if(r!==typeof t)return false;if(Array.isArray(e)){if(!Array.isArray(t))return false;let n=e.length;if(n!==t.length)return false;for(let s=0;s<n;s++)if(!$r(e[s],t[s]))return false;return true}if(r==="object"){if(!e||!t)return e===t;let n=Object.keys(e),s=Object.keys(t);if(n.length!==s.length)return false;for(let i of n)if(!$r(e[i],t[i]))return false;return true}return e===t}function vg(e,t){return t.reduce((r,n)=>(n in e&&(r[n]=e[n]),r),{})}function Ac(e){try{return structuredClone(e)}catch{return e}}function Tg(e,t,r={}){let n=t;try{n=structuredClone(t);}catch{n=JSON.parse(JSON.stringify(t));}let s={resolver:r.resolver||new eo(e),depth:r.depth||0,dropUnknown:r.dropUnknown??false};return s.resolver.hasRef(e,n)?s.resolver.resolve(e.$ref).coerce(n,{...s,depth:s.depth+1}):n}function Qn(e,t,r={}){return e.map(n=>n.validate(t,Xn(r)).valid?n:void 0).filter(Boolean)}function iy(e,t,r={}){let n={keywordPath:r.keywordPath||[],instancePath:r.instancePath||[],coerce:r.coerce||false,errors:r.errors||[],shortCircuit:r.shortCircuit||false,ignoreUnsupported:r.ignoreUnsupported||false,resolver:r.resolver||e.getResolver?.()||new eo(e),depth:r.depth?r.depth+1:0,skipClone:r.skipClone||false},s;if(r?.coerce&&e.coerce){let i=e.coerce(t,{resolver:n.resolver,depth:n.depth});s=n.skipClone?i:structuredClone(i);}else s=n.skipClone?t:structuredClone(t);if(r.ignoreUnsupported!==true){let i=["$defs"];for(let o of i)if(e[o])throw new Error(`${o} not implemented`)}if(n.resolver.hasRef(e,s)){let i=n.resolver.resolve(e.$ref).validate(s,{...n,errors:[]});i.valid||n.errors.push(...i.errors);}else {let i={keywordPath:n.keywordPath,instancePath:n.instancePath,coerce:n.coerce,errors:[],shortCircuit:n.shortCircuit,ignoreUnsupported:n.ignoreUnsupported,resolver:n.resolver,depth:n.depth};for(let o in e)if(o==="type"&&e.type!==void 0){if(s!==void 0){let a=Ki[o];if(a){i.errors=[];let l=a(e,s,i);if(!l.valid){if(r.shortCircuit)return l;n.errors.push(...l.errors);}}}}else if(o in Ki&&e[o]!==void 0){if(s===void 0)continue;let a=Ki[o];if(a){i.errors=[];let l=a(e,s,i);if(!l.valid){if(r.shortCircuit)return l;n.errors.push(...l.errors);}}}}return {valid:n.errors.length===0,errors:n.errors}}function Zn(e,t,r){return new class extends Ye{type=e}(t,r)}function Yi(e){return new oy(e)}function _c(e,t){return Array.isArray(e)?e.map(t):e!==void 0?[t(e)]:[]}function $c(e,t,r=n=>n){return Object.fromEntries(Object.entries(e).map(([n,s])=>[n,r(t(s,n),n)]))}function Gt(e){if(Zi(e))return Yi(e);let t=structuredClone(e);if(!me(t))throw new gg("non-object schemas cannot be converted to a schema",t);"properties"in t&&t.properties&&(t.properties=$c(t.properties,(i,o)=>{try{return Gt(i)}catch(a){throw new Error(`Couldn't schemaize property "${o}": ${String(a)}`)}},(i,o)=>"required"in t&&Array.isArray(t.required)&&t.required.includes(o)?i:i.optional()));let r=["patternProperties","dependentSchemas","$defs"];for(let i of r)i in t&&t[i]&&(t[i]=$c(t[i],Gt));let n=["additionalProperties","items","prefixItems","propertyNames","contains","not","if","then","else"];for(let i of n)i in t&&typeof t[i]<"u"&&(ot(t[i])?t[i]=_c(t[i],Gt):t[i]=Gt(t[i]));let s=["anyOf","oneOf","allOf"];for(let i of s)if(i in t){let{[i]:o}=t;t[i]=_c(o,Gt);}if(xg(t))switch(t.type){case "string":return Rc(t);case "number":return Pc(t);case "integer":return Nc(t);case "boolean":return Lc(t);case "object":{let{properties:i,...o}=t;return es(i,o)}case "array":{let{items:i,...o}=t;return Oc(i,o)}}return Cc(t)}function by(){return {type(e){let t=e.map(r=>Array.isArray(r)?new Set(r):new Set([r])).reduce((r,n)=>r?new Set([...r].filter(s=>n.has(s))):new Set(n));if(!t.size)throw new Error('Incompatible "type" in allOf');return t.size===1?[...t][0]:[...t]},enum(e){let t=e.map(r=>new Set(r)).reduce((r,n)=>new Set([...r].filter(s=>n.has(s))));if(!t.size)throw new Error('Incompatible "enum" in allOf');return [...t]},required(e){return [...new Set(e.flat())]},properties(e,t,r){return e.reduce((n,s)=>r(n,s),{})},patternProperties(e,t,r){return e.reduce((n,s)=>r(n,s),{})},$defs(e,t,r){return e.reduce((n,s)=>r(n,s),{})},definitions(e,t,r){return e.reduce((n,s)=>r(n,s),{})},...Object.fromEntries(yy.map(e=>[e,t=>Math.min(...t)])),...Object.fromEntries(wy.map(e=>[e,t=>Math.max(...t)]))}}function Sy(e){let t={...by(),...e.resolvers};function r(n,s){if(Array.isArray(n)&&Array.isArray(s))return [...new Set([...n,...s])];if(Qi(n)&&Qi(s)){let i={...n};for(let[o,a]of Object.entries(s))if(o in i){let l=t[o];i[o]=l?l([i[o],a],o,r):Ji(a);}else i[o]=Ji(a);return i}return Ji(s)}return r}function xy(e,t={}){let r=t.deep!==false,n=Sy(t);function s(i){if(Array.isArray(i))return i.map(s);if(!Qi(i))return i;if(Array.isArray(i.allOf)){let a=i.allOf.map(s);if(a.some(h=>h===false))return false;let l=a.filter(h=>h!==true);if(!l.length)return true;let c=l.reduce((h,d)=>n(h,d),{}),u=Ey(c);if(u!==null)return u;let p={...i};delete p.allOf;let f=n(c,r?s(p):p);return r?s(f):f}let o={};for(let[a,l]of Object.entries(i))o[a]=s(l);return o}return s(e)}var Xi,vc,Q,D,zt,Xn,Et,gg,yg,$e,eo,Ag,Cg,Rg,kg,Pg,Ng,Og,Lg,Ig,Dg,jg,Fg,Mg,Ug,Bg,qg,Hg,Wg,Gg,zg,Vg,Kg,Jg,Xg,Yg,Qg,Zg,ey,ty,ry,ny,xc,sy,Ki,Ye,vr,oy,Cc,ay,ly,es,cy,uy,py,fy,my,Rc,kc,Pc,Nc,dy,Oc,Lc,Jn,Ic,hy,gy,Qi,Ji,yy,wy,Ey,_y,Dc,$y,vy,Ty,jc,Fc=y(()=>{Xi=(e=[],t="")=>"/"+[t,...e.map(r=>String(r).replace(/\./g,"/"))].filter(Boolean).join("/"),vc=e=>e.split("/").slice(1);Q=(e={},t,r,n)=>({valid:false,errors:[...e.errors??[],{keywordLocation:Xi([...e.keywordPath??[],t]),instanceLocation:Xi(e.instancePath),error:typeof r=="string"?r:`Invalid value for ${t}`,data:n}]}),D=()=>({valid:true,errors:[]}),zt=(e,t,r)=>{let n=Array.isArray(t)?t:[t],s=r?Array.isArray(r)?r:[r]:[];return {...e,keywordPath:[...e.keywordPath??[],...n],instancePath:s?[...e.instancePath??[],...s]:e.instancePath}},Xn=(e={})=>({...e,errors:[]}),Et=class extends Error{constructor(e){super(`Expected ${e}`);}},gg=class extends Error{constructor(e,t){super(`${e??"Invalid raw schema"}: ${JSON.stringify(t)}`),this.schema=t;}},yg=class extends Error{constructor(e,t){super(`${e}, got: 'type "${typeof t}": ${JSON.stringify(t)}'`),this.value=t;}},$e=Symbol.for("jsonv-ts:schema");eo=class{constructor(e){this.root=e,this.cache=new Map;}cache;hasRef(e,t){return t!==void 0&&"$ref"in e&&Ge(e.$ref)}resolve(e){let t=this.cache.get(e);if(!t){if(t=hg(this.root,e),!ve(t))throw new Error(`ref not found: ${e}`);if("$ref"in t&&t.$ref===e)throw new Error(`ref loop: ${e}`);this.cache.set(e,t);}return t}};Ag=({type:e},t,r={})=>{if(e===void 0||t===void 0)return D();let n,s={string:Ge,number:Xe,integer:Sg,object:me,array:ot,boolean:Zi,null:wg};if(Array.isArray(e)){for(let i of e){if(!(i in s))throw new Et(`Unknown type: ${i}`);if(s[i](t))return D()}n=`Expected one of: ${e.join(", ")}`;}else {if(!(e in s))throw new Et(`Unknown type: ${e}`);s[e](t)||(n=`Expected ${e}`);}return n?Q(r,"type",n,t):D()},Cg=({const:e},t,r={})=>$r(e,t)?D():Q(r,"const",`Expected const: ${e}`,t),Rg=({enum:e=[]},t,r={})=>e.some(n=>$r(n,t))?D():Q(r,"enum",`Expected enum: ${JSON.stringify(e)}`,t);kg=({anyOf:e=[]},t,r={})=>Qn(e,t,r).length>0?D():Q(r,"anyOf","Expected at least one to match",t),Pg=({oneOf:e=[]},t,r={})=>Qn(e,t).length===1?D():Q(r,"oneOf","Expected exactly one to match",t),Ng=({allOf:e=[]},t,r={})=>Qn(e,t,r).length===e.length?D():Q(r,"allOf","Expected all to match",t),Og=({not:e},t,r={})=>t===void 0?D():ve(e)&&e.validate(t,r).valid?Q(r,"not","Expected not to match",t):D(),Lg=({if:e,then:t,else:r},n,s={})=>{if(e&&(t||r)){if(e.validate(n,Xn(s)).valid)return t?t.validate(n,Xn(s)):D();if(r)return r.validate(n,Xn(s))}return D()},Ig=({pattern:e=""},t,r={})=>{if(!Ge(t))return D();if(e instanceof RegExp){if(e.test(t))return D()}else if(new RegExp(e,"u").test(t))return D();return Q(r,"pattern",`Expected string matching pattern ${e}`,t)},Dg=({minLength:e=0},t,r={})=>Ge(t)?[...Tc(t)].length>=e?D():Q(r,"minLength",`Expected string with minimum length of ${e}`,t):D(),jg=({maxLength:e=0},t,r={})=>Ge(t)?[...Tc(t)].length<=e?D():Q(r,"maxLength",`Expected string with maximum length of ${e}`,t):D(),Fg=({multipleOf:e=0},t,r={})=>{if(!Xe(t))return D();if(!(Number.isFinite(t)&&Number.isFinite(e))||e<=0)throw new Et("number");let n=t/e,s=Number.EPSILON*Math.max(1,Math.abs(n));return Math.abs(n-Math.round(n))<=s?D():Q(r,"multipleOf",`Expected number being a multiple of ${e}`,t)},Mg=({maximum:e=0},t,r={})=>!Xe(t)||t<=e?D():Q(r,"maximum",`Expected number less than or equal to ${e}`,t),Ug=({exclusiveMaximum:e=0},t,r={})=>!Xe(t)||t<e?D():Q(r,"exclusiveMaximum",`Expected number less than ${e}`,t),Bg=({minimum:e=0},t,r={})=>!Xe(t)||t>=e?D():Q(r,"minimum",`Expected number greater than or equal to ${e}`,t),qg=({exclusiveMinimum:e=0},t,r={})=>!Xe(t)||t>e?D():Q(r,"exclusiveMinimum",`Expected number greater than ${e}`,t),Hg=({properties:e={}},t,r={})=>{if(!me(t))return D();for(let[n,s]of Object.entries(t)){let i=e[n];if(!ve(i))continue;let o=i.validate(s,zt(r,["properties",n],n));if(!o.valid)return o}return D()},Wg=({properties:e={},additionalProperties:t,patternProperties:r},n,s={})=>{if(!me(n))return D();if(!ve(t))throw new Et("additionalProperties must be a boolean or a managed schema");let i=Object.keys(e),o=me(r)?Object.keys(n).filter(l=>Object.keys(r).some(c=>new RegExp(c).test(l))):[],a=Object.keys(n).filter(l=>!i.includes(l)&&!o.includes(l));if(a.length>0){if(_g(t)){if(t.toJSON()===true)return D();let l=a.reduce((c,u)=>(c[u]=n[u],c),{});return Q(s,"additionalProperties","Additional properties are not allowed",l)}else if(ve(t))for(let l of a){let c=t.validate(n[l],zt(s,["additionalProperties"],l));if(!c.valid)return c}}return D()},Gg=({dependentRequired:e},t,r={})=>{if(!me(t))return D();let n=Object.keys(t).filter(s=>typeof t[s]!="function");if(me(e)){for(let[s,i]of Object.entries(e))if(n.includes(s)){for(let o of i)if(!n.includes(o))return Q(r,"dependentRequired",`Expected dependent required property ${o}`,t)}}return D()},zg=({required:e=[]},t,r={})=>{if(!me(t))return D();let n=Object.keys(t).filter(s=>typeof t[s]!="function");return e.every(s=>n.includes(s))?D():Q(r,"required",`Expected object with required properties ${e.join(", ")}`,t)},Vg=({dependentSchemas:e},t,r={})=>{if(!me(t))return D();let n=Object.keys(t).filter(s=>typeof t[s]!="function");if(me(e)){for(let[s,i]of Object.entries(e))if(n.includes(s)){let o=i.validate(t,r);if(!o.valid)return o}}return D()},Kg=({minProperties:e=0},t,r={})=>me(t)?Object.keys(t).length>=e?D():Q(r,"minProperties",`Expected object with at least ${e} properties`,t):D(),Jg=({maxProperties:e=0},t,r={})=>!me(t)||Object.keys(t).length<=e?D():Q(r,"maxProperties",`Expected object with at most ${e} properties`,t),Xg=({patternProperties:e={}},t,r={})=>{if(!me(t))return D();if(!me(e))throw new Et("patternProperties must be an object");for(let[n,s]of Object.entries(t))for(let[i,o]of Object.entries(e))if(new RegExp(i,"u").test(n)){let a=o.validate(s,zt(r,["patternProperties"],n));if(!a.valid)return a}return D()},Yg=({propertyNames:e},t,r={})=>{if(!me(t)||e===void 0)return D();if(!ve(e))throw new Et("propertyNames must be a managed schema");for(let n of Object.keys(t)){let s=e.validate(n,zt(r,["propertyNames"],n));if(!s.valid)return s}return D()},Qg=({items:e,prefixItems:t=[]},r,n={})=>{if(!ot(r)||e===void 0)return D();if(!ve(e))throw new Et("items must be a managed schema");for(let[s,i]of r.slice(t.length).entries()){let o=e.validate(i,zt(n,["items"],String(s)));if(!o.valid)return o}return D()},Zg=({minItems:e=0},t,r={})=>!ot(t)||t.length>=e?D():Q(r,"minItems",`Expected array with at least ${e} items`,t),ey=({maxItems:e=0},t,r={})=>!ot(t)||t.length<=e?D():Q(r,"maxItems",`Expected array with at most ${e} items`,t),ty=({uniqueItems:e=false},t,r={})=>{if(!ot(t)||!e)return D();for(let n=0;n<t.length;n++){let s=t[n];for(let i=0;i<t.length;i++){if(n===i)continue;let o=t[i];if($r(s,o))return Q(r,"uniqueItems",`Duplicated items at index ${n} and ${i}`,t)}}return D()},ry=({contains:e,minContains:t,maxContains:r},n,s={})=>{if(!ve(e))throw new Error("contains must be a managed schema");if(!ot(n))return D();let i=n.filter(o=>e.validate(o).valid).length;return i<(t??1)?Q(s,t?"minContains":"contains",`Expected array to contain at least ${t??1}, but found ${i}`,n):r!==void 0&&i>r?Q(s,"maxContains",`Expected array to contain at most ${r}, but found ${i}`,n):D()},ny=({prefixItems:e=[]},t,r={})=>{if(!ot(t))return D();for(let n=0;n<t.length;n++){let s=e[n]?.validate(t[n],zt(r,String(n),String(n)));if(s&&s?.valid!==true)return s}return D()},xc={email:e=>{if(e.length>318)return false;if(/^[a-z0-9!#$%&'*+/=?^_`{|}~-]{1,20}(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]{1,21}){0,2}@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,60}[a-z0-9])?){0,3}$/i.test(e))return true;if(!e.includes("@")||/(^\.|^"|\.@|\.\.)/.test(e))return false;let[t,r,...n]=e.split("@");return !t||!r||n.length!==0||t.length>64||r.length>253||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?false:r.split(".").every(s=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(s))},hostname:e=>e.length>(e.endsWith(".")?254:253)?false:/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*\.?$/i.test(e),date:e=>{if(e.length!==10)return false;if(e[5]==="0"&&e[6]==="2"){if(/^\d\d\d\d-02-(?:[012][1-8]|[12]0|[01]9)$/.test(e))return true;let t=e.match(/^(\d\d\d\d)-02-29$/);if(!t)return false;let r=Number(t[1]);return r%16===0||r%4===0&&r%25!==0}return e.endsWith("31")?/^\d\d\d\d-(?:0[13578]|1[02])-31$/.test(e):/^\d\d\d\d-(?:0[13-9]|1[012])-(?:[012][1-9]|[123]0)$/.test(e)},time:e=>{if(e.length>27||!/^(?:2[0-3]|[0-1]\d):[0-5]\d:(?:[0-5]\d|60)(?:\.\d+)?(?:z|[+-](?:2[0-3]|[0-1]\d)(?::?[0-5]\d)?)?$/i.test(e))return false;if(!/:60/.test(e))return true;let t=e.match(/([0-9.]+|[^0-9.])/g);if(!t)return false;let r=Number(t[0])*60+Number(t[2]);return t[5]==="+"?r+=1440-Number(t[6]||0)*60-Number(t[8]||0):t[5]==="-"&&(r+=Number(t[6]||0)*60+Number(t[8]||0)),r%1440===1439},"date-time":e=>{if(e.length>38)return false;let t=/^\d\d\d\d-(?:0[1-9]|1[0-2])-(?:[0-2]\d|3[01])[t\s](?:2[0-3]|[0-1]\d):[0-5]\d:(?:[0-5]\d|60)(?:\.\d+)?(?:z|[+-](?:2[0-3]|[0-1]\d)(?::?[0-5]\d)?)$/i,r=e[5]==="0"&&e[6]==="2";if(r&&e[8]==="3"||!t.test(e))return false;if(e[17]==="6"){let n=e.slice(11).match(/([0-9.]+|[^0-9.])/g);if(!n)return false;let s=Number(n[0])*60+Number(n[2]);if(n[5]==="+"?s+=1440-Number(n[6]||0)*60-Number(n[8]||0):n[5]==="-"&&(s+=Number(n[6]||0)*60+Number(n[8]||0)),s%1440!==1439)return false}if(r){if(/^\d\d\d\d-02-(?:[012][1-8]|[12]0|[01]9)/.test(e))return true;let n=e.match(/^(\d\d\d\d)-02-29/);if(!n)return false;let s=Number(n[1]??0);return s%16===0||s%4===0&&s%25!==0}return e[8]==="3"&&e[9]==="1"?/^\d\d\d\d-(?:0[13578]|1[02])-31/.test(e):/^\d\d\d\d-(?:0[13-9]|1[012])-(?:[012][1-9]|[123]0)/.test(e)},ipv4:e=>e.length<=15&&/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)$/.test(e),ipv6:e=>{if(e.length>45||e.length<2)return false;let t=0,r=0,n=0,s=false,i=false,o=0,a=true;for(let c=0;c<e.length;c++){let u=e.charCodeAt(c);if(c===1&&o===58&&u!==58)return false;if(u>=48&&u<=57){if(++n>4)return false}else if(u===46){if(t>6||r>=3||n===0||i)return false;r++,n=0;}else if(u===58){if(r>0||t>=7)return false;if(o===58){if(s)return false;s=true;}else c===0&&(a=false);t++,n=0,i=false;}else if(u>=97&&u<=102||u>=65&&u<=70){if(r>0||++n>4)return false;i=true;}else return false;o=u;}if(t<2||r>0&&(r!==3||n===0))return false;if(s&&e.length===2)return true;if(r>0&&!/(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/.test(e))return false;let l=r>0?6:7;return s?(a||n>0)&&t<l:t===l&&a&&n>0},uri:e=>/^[a-z][a-z0-9+\-.]*:(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/?(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i.test(e),"uri-reference":e=>/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/?(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?)?(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i.test(e),"uri-template":e=>/^(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2}|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i.test(e),"json-pointer":e=>/^(?:|\/(?:[^~]|~0|~1)*)$/.test(e),"relative-json-pointer":e=>/^(?:0|[1-9][0-9]*)(?:|#|\/(?:[^~]|~0|~1)*)$/.test(e),uuid:e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),duration:e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e)),regex:e=>{if(/[^\\]\\Z/.test(e))return false;try{return new RegExp(e,"u"),!0}catch{return false}},binary:()=>true,password:()=>true},sy=({format:e},t,r={})=>!Ge(t)||!e?D():xc[e]?xc[e](t)?D():Q(r,"format",`Expected format: ${e}`,t):D(),Ki={type:Ag,const:Cg,enum:Rg,allOf:Ng,anyOf:kg,oneOf:Pg,not:Og,minLength:Dg,maxLength:jg,pattern:Ig,format:sy,minimum:Bg,exclusiveMinimum:qg,maximum:Mg,exclusiveMaximum:Ug,multipleOf:Fg,required:zg,dependentRequired:Gg,dependentSchemas:Vg,minProperties:Kg,maxProperties:Jg,propertyNames:Yg,properties:Hg,patternProperties:Xg,additionalProperties:Wg,minItems:Zg,maxItems:ey,uniqueItems:ty,contains:ry,prefixItems:ny,items:Qg,if:Lg};Ye=class{"~standard";[$e];_resolver;type;$id;$ref;$schema;title;description;readOnly;writeOnly;$comment;examples;constructor(e,t){let{type:r,validate:n,coerce:s,template:i,...o}=e||{};Object.assign(this,{type:r},o),this[$e]={raw:e,optional:false,overrides:t},this["~standard"]={version:1,vendor:"jsonv-ts",validate:a=>{let l=this.validate(a);return l.valid?{value:a}:{issues:l.errors.map(c=>({message:c.error,path:vc(c.instanceLocation)}))}}};}template(e,t){let r=this,n=e;if(r.const!==void 0?n=r.const:n===void 0&&(r.default!==void 0&&(n=r.default),t?.withExtendedOptional&&r.enum!==void 0&&(n=r.enum[0])),t?.withOptional!==true&&n===void 0&&this.isOptional())return n;if(this[$e].raw?.template){let i=this[$e].raw.template(n,t);i!==void 0&&(n=i);}let s=this[$e].overrides?.template?.(n,t);return s!==void 0&&(n=s),n}validate(e,t){let r={keywordPath:t?.keywordPath||[],instancePath:t?.instancePath||[],coerce:t?.coerce||false,errors:t?.errors||[],shortCircuit:t?.shortCircuit||false,ignoreUnsupported:t?.ignoreUnsupported||false,resolver:t?.resolver||this.getResolver(),depth:t?.depth?t.depth+1:0,skipClone:t?.skipClone??true},n=this[$e].raw?.validate;if(n!==void 0){let s=n(e,r);if(!s.valid)return s}return iy(this,e,r)}coerce(e,t){let r={...t,resolver:t?.resolver||this.getResolver(),depth:t?.depth?t.depth+1:0,dropUnknown:t?.dropUnknown??false},n=this[$e].raw?.coerce;if(n!==void 0)return n(e,r);let s=this[$e].overrides?.coerce?.(e,r)??e;return Tg(this,s,r)}optional(){return this[$e].optional=true,this}isOptional(){return this[$e].optional}getResolver(){return this._resolver||(this._resolver=new eo(this)),this._resolver}children(e){return []}*walk({instancePath:e=[],keywordPath:t=[],data:r,maxDepth:n=Number.POSITIVE_INFINITY,...s}={}){let i=e.length===0&&r?Ac(r):r;if(s.includeSelf!==false&&(yield new vr(this,{instancePath:e,keywordPath:t,data:i,...s})),!(e.length>=n))for(let o of this.children(s)){let a=[...e,...o.instancePath];yield*o.schema.walk({...s,data:i,maxDepth:n,instancePath:a,keywordPath:[...t,...o.keywordPath]});}}*[Symbol.iterator](e){for(let t of this.walk(e))yield t;}toJSON(){let{toJSON:e,"~standard":t,_resolver:r,...n}=this;return JSON.parse(JSON.stringify(n))}},vr=class{constructor(e,t={}){this.schema=e,this.instancePath=t.instancePath||[],this.keywordPath=t.keywordPath||[],this.depth=this.instancePath.length;try{if(t.data!==void 0){let r=Yn(t.data,this.instancePath);e.validate(r).valid&&(this.data=r);}}catch{}}instancePath;keywordPath;data;depth;appendInstancePath(e){return this.instancePath=[...this.instancePath,...e],this}appendKeywordPath(e){return this.keywordPath=[...this.keywordPath,...e],this}setData(e){return this.data=e,this}};oy=class extends Ye{constructor(e){super(),this.bool=e;}toJSON(){return this.bool}validate(e,t){return this.bool?D():Q(t,"","Always fails",e)}};Cc=e=>Zn(e?.type,e),ay=(e,t)=>Zn(void 0,{...t,const:e}),ly=class extends Ye{type="object";properties;required;constructor(e,t){let r=[];for(let[s,i]of Object.entries(e||{}))$g(ve(i),"properties must be managed schemas",i),i[$e].optional||r.push(s);let n=t?.additionalProperties===false?Yi(false):t?.additionalProperties;r=r.length>0?r:void 0,super({...t,additionalProperties:n,properties:e,required:r},{template:(s,i)=>{let o=structuredClone(me(s)?s:{}),a={...o};if(this.properties)for(let[l,c]of Object.entries(this.properties)){let u=Yn(o,l);if(c.isOptional()&&i?.withOptional!==true&&u===void 0&&s===void 0)continue;let p=c.template(u,i);p!==void 0&&(a[l]=p);}if(!(Object.keys(a).length===0&&!i?.withExtendedOptional))return a},coerce:(s,i)=>{let o=Object.keys(this.properties),a=Ac(s),l=o.length>0&&Object.values(this.properties).every(u=>!u[$e].optional);if(bg(a)&&(i?.dropUnknown===true||l)&&(a=vg(a,o)),typeof a=="string"&&a.match(/^\{/)&&(a=JSON.parse(a)),typeof a!="object"||a===null)return;if(this.properties)for(let[u,p]of Object.entries(this.properties)){let f=a[u];f!==void 0&&(a[u]=p.coerce(f,i));}let c=this.additionalProperties;if(i?.dropUnknown!==true&&(!c||c.validate(null).valid)){let u=me(s)?s:{},p=Object.keys(u).filter(f=>!o.includes(f));for(let f of p)a[f]=c?c.coerce(u[f],i):u[f];}return a}}),this.properties=e,this.required=r;}strict(){return this.additionalProperties=Yi(false),this[$e].raw.additionalProperties=false,this}partial(){for(let[,e]of Object.entries(this.properties))e[$e].optional=true;return this.required=void 0,this}children(e){let t=[];for(let[r,n]of Object.entries(this.properties)){let s=new vr(n,e);s.appendInstancePath([r]),s.appendKeywordPath(["properties",r]),t.push(s);}return t}},es=(e,t)=>new ly(e,t),cy=(e,t)=>es(e,t).strict(),uy=(e,t)=>es(e,t).partial(),py=class extends Ye{type="object";additionalProperties;constructor(e,t){super({...t,additionalProperties:e},{template:(r,n)=>n?.withExtendedOptional&&(r===void 0||!me(r))?{}:r}),this.additionalProperties=e;}children(e){let t=[],r=new vr(this.additionalProperties,e);return r.appendKeywordPath(["additionalProperties"]),t.push(r),t}},fy=(e,t)=>new py(e,t),my=class extends Ye{type="string";constructor(e){super(e,{template:(t,r)=>r?.withExtendedOptional&&(t===void 0||!Ge(t))?"":t,coerce:t=>Xe(t)?String(t):t});}toJSON(){let{pattern:e,"~standard":t,_resolver:r,...n}=this;return JSON.parse(JSON.stringify({...n,pattern:e instanceof RegExp?e.source:e}))}},Rc=e=>new my(e),kc=(e,t,r)=>Zn(e,r,{template:(n,s)=>s?.withExtendedOptional&&(n===void 0||!Xe(n))?r?.minimum??0:n,coerce:n=>{if(Ge(n)){let s=t.parseFn(n);if(!Number.isNaN(s))return s}return n}}),Pc=e=>kc("number",{parseFn:Number},e),Nc=e=>kc("integer",{parseFn:Number.parseInt},e),dy=class extends Ye{constructor(e,t={}){super({...t,items:e},{template:r=>r===void 0||!Array.isArray(r)?[]:r,coerce:(r,n)=>{try{let s=typeof r=="string"?JSON.parse(r):r;if(!Array.isArray(s))return;if(ve(this.items))for(let[i,o]of s.entries())s[i]=this.items.coerce(o,n);return s}catch{}return r}}),this.items=e,this.items=e;}type="array";children(e){let t=[];if(this.items){let r=new vr(this.items,e);r.appendKeywordPath(["items"]),t.push(r);}return t}},Oc=(e,t)=>new dy(e,t),Lc=e=>Zn("boolean",e,{template:(t,r)=>r?.withExtendedOptional&&(t===void 0||!Zi(t))?false:t,coerce:t=>{if(Ge(t)&&["true","false","1","0"].includes(t))return t==="true"||t==="1";if(Xe(t)){if(t===1)return true;if(t===0)return false}return t}}),Jn=Symbol.for("unionType"),Ic=class extends Ye{[Jn];constructor(e,t,r){super({...r,[t]:e},{coerce:(n,s)=>{let i=r?.coerce;if(i!==void 0)return i.bind(this)(n,s);let o=Qn(e,n,{ignoreUnsupported:true,resolver:s?.resolver,coerce:true});return o.length>0?o[0].coerce(n,s):n}}),this[Jn]=t;}get schemas(){return this[this[Jn]]}children(e){let t=[];for(let[r,n]of this.schemas.entries()){let s=new vr(n,e);s.appendKeywordPath([this[Jn],r]),t.push(s);}return t}},hy=(e,t)=>new Ic(e,"anyOf",t),gy=(e,t)=>new Ic(e,"oneOf",t);Qi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ji=e=>typeof globalThis.structuredClone=="function"?globalThis.structuredClone(e):JSON.parse(JSON.stringify(e)),yy=["maximum","exclusiveMaximum","maxLength","maxItems","maxProperties"],wy=["minimum","exclusiveMinimum","minLength","minItems","minProperties"];Ey=e=>e===true||e===false?e:null;_y=(e,t)=>{let r=JSON.parse(JSON.stringify({...t,allOf:e}));return Gt(xy(r))},Dc=class extends Ye{$ref;constructor(e,t){if(!t&&!ve(e))throw new Error("Ref not set");if(ve(e)&&!e.$id)throw new Error("Ref must have an $id");let r=t??e?.$id;super({$ref:r},{coerce:(n,s)=>{let i=s?.resolver?.resolve(this.$ref);if(!ve(i))throw new Error(`Ref not found: ${this.$ref}`);return i.coerce(n,s)}}),this.$ref=r;}},$y=(e,t)=>new Dc(e,t),vy=e=>new Dc(void 0,e),Ty=e=>e(new Ye({$ref:"#",coerce:(t,r)=>{let n=r?.resolver?.resolve("#");if(!ve(n))throw new Error("Ref not found: #");return n.coerce(t,r)}})),jc={boolean:Lc,any:Cc,literal:ay,object:es,strictObject:cy,partialObject:uy,record:fy,string:Rc,number:Pc,integer:Nc,array:Oc,anyOf:hy,oneOf:gy,allOf:_y,ref:$y,refId:vy,recursive:Ty};});function Mc(e,t){if(typeof e!="string"){throw new Error("Email must be a string");}if(!jc.string({format:"email"}).validate(e).valid){throw new Error("Invalid email");}if(t?.domains?.length&&!t.domains.includes(e.split("@")[1])){throw new Error("Email domain not allowed");}return true}function Uc(e,{panic:t=true,length:r=8,numbers:n=0,special:s=0}={}){try{if(typeof e!="string"){if(t)throw new Error("Password must be a string");return !1}if(e.length<r){if(t)throw new Error(`Password must be at least ${r} characters long`);return !1}if((e.match(/[0-9]/g)?.length??0)<n){if(t)throw new Error(`Password must contain at least ${n} numbers`);return !1}if((e.match(/[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/g)?.length??0)<s){if(t)throw new Error(`Password must contain at least ${s} special characters`);return !1}return !0}catch(i){if(t)throw i;return false}}function M(e,t='"'){return `${t}${e}${t}`}function Bc(e,t,r){if(t instanceof RegExp)return t.test(e);if(typeof t=="string")switch(!r&&t.startsWith("/")&&(r="regex"),r){case "regex":return new RegExp(t).test(e);case "sql":return new RegExp(t.replace("%",".*").replace("_",".")).test(e);case "wildcard":return new RegExp(t.replace("*",".*")).test(e);default:return e.includes(t)}return false}var Tr=y(()=>{Fc();});function to(e){return typeof e=="number"?e:Number.parseInt(String(e),10)}var qc=y(()=>{});var Hc=y(()=>{});var at=y(()=>{gc();yc();wc();bc();Sc();_r();Tr();qc();Hc();});var ro,Wc=y(()=>{ro=(e,t,r)=>(n,s)=>{let i=-1;return o(0);async function o(a){if(a<=i)throw new Error("next() called multiple times");i=a;let l,c=false,u;if(e[a]?(u=e[a][0][0],n.req.routeIndex=a):u=a===e.length&&s||void 0,u)try{l=await u(n,()=>o(a+1));}catch(p){if(p instanceof Error&&t)n.error=p,l=await t(p,n),c=true;else throw p}else n.finalized===false&&r&&(l=await r(n));return l&&(n.finalized===false||c)&&(n.res=l),n}};});var Gc=y(()=>{});var zc,Vc=y(()=>{zc=Symbol();});async function Ay(e,t){let r=await e.formData();return r?Cy(r,t):{}}function Cy(e,t){let r=Object.create(null);return e.forEach((n,s)=>{t.all||s.endsWith("[]")?Ry(r,s,n):r[s]=n;}),t.dot&&Object.entries(r).forEach(([n,s])=>{n.includes(".")&&(ky(r,n,s),delete r[n]);}),r}var Kc,Ry,ky,Jc=y(()=>{no();Kc=async(e,t=Object.create(null))=>{let{all:r=false,dot:n=false}=t,i=(e instanceof ts?e.raw.headers:e.headers).get("Content-Type");return i?.startsWith("multipart/form-data")||i?.startsWith("application/x-www-form-urlencoded")?Ay(e,{all:r,dot:n}):{}};Ry=(e,t,r)=>{e[t]!==void 0?Array.isArray(e[t])?e[t].push(r):e[t]=[e[t],r]:t.endsWith("[]")?e[t]=[r]:e[t]=r;},ky=(e,t,r)=>{let n=e,s=t.split(".");s.forEach((i,o)=>{o===s.length-1?n[i]=r:((!n[i]||typeof n[i]!="object"||Array.isArray(n[i])||n[i]instanceof File)&&(n[i]=Object.create(null)),n=n[i]);});};});var io,Xc,Py,Ny,rs,Yc,ns,Oy,oo,Qc,xt,ss,so,Zc,eu,tu,ao,Vt=y(()=>{io=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},Xc=e=>{let{groups:t,path:r}=Py(e),n=io(r);return Ny(n,t)},Py=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let s=`@${n}`;return t.push([s,r]),s}),{groups:t,path:e}},Ny=(e,t)=>{for(let r=t.length-1;r>=0;r--){let[n]=t[r];for(let s=e.length-1;s>=0;s--)if(e[s].includes(n)){e[s]=e[s].replace(n,t[r][1]);break}}return e},rs={},Yc=(e,t)=>{if(e==="*")return "*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${e}#${t}`;return rs[n]||(r[2]?rs[n]=t&&t[0]!==":"&&t[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)]:rs[n]=[e,r[1],true]),rs[n]}return null},ns=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return t(r)}catch{return r}})}},Oy=e=>ns(e,decodeURI),oo=e=>{let t=e.url,r=t.indexOf("/",t.indexOf(":")+4),n=r;for(;n<t.length;n++){let s=t.charCodeAt(n);if(s===37){let i=t.indexOf("?",n),o=t.indexOf("#",n),a=i===-1?o===-1?void 0:o:o===-1?i:Math.min(i,o),l=t.slice(r,a);return Oy(l.includes("%25")?l.replace(/%25/g,"%2525"):l)}else if(s===63||s===35)break}return t.slice(r,n)},Qc=e=>{let t=oo(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},xt=(e,t,...r)=>(r.length&&(t=xt(t,...r)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),ss=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),r=[],n="";return t.forEach(s=>{if(s!==""&&!/\:/.test(s))n+="/"+s;else if(/\:/.test(s))if(/\?/.test(s)){r.length===0&&n===""?r.push("/"):r.push(n);let i=s.replace("?","");n+="/"+i,r.push(n);}else n+="/"+s;}),r.filter((s,i,o)=>o.indexOf(s)===i)},so=e=>/[%+]/.test(e)?(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),e.indexOf("%")!==-1?ns(e,ao):e):e,Zc=(e,t,r)=>{let n;if(!r&&t&&!/[%+]/.test(t)){let o=e.indexOf("?",8);if(o===-1)return;for(e.startsWith(t,o+1)||(o=e.indexOf(`&${t}`,o+1));o!==-1;){let a=e.charCodeAt(o+t.length+1);if(a===61){let l=o+t.length+2,c=e.indexOf("&",l);return so(e.slice(l,c===-1?void 0:c))}else if(a==38||isNaN(a))return "";o=e.indexOf(`&${t}`,o+1);}if(n=/[%+]/.test(e),!n)return}let s={};n??=/[%+]/.test(e);let i=e.indexOf("?",8);for(;i!==-1;){let o=e.indexOf("&",i+1),a=e.indexOf("=",i);a>o&&o!==-1&&(a=-1);let l=e.slice(i+1,a===-1?o===-1?void 0:o:a);if(n&&(l=so(l)),i=o,l==="")continue;let c;a===-1?c="":(c=e.slice(a+1,o===-1?void 0:o),n&&(c=so(c))),r?(s[l]&&Array.isArray(s[l])||(s[l]=[]),s[l].push(c)):s[l]??=c;}return t?s[t]:s},eu=Zc,tu=(e,t)=>Zc(e,t,true),ao=decodeURIComponent;});var ru,ts,no=y(()=>{Gc();Vc();Jc();Vt();ru=e=>ns(e,ao),ts=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(e,t="/",r=[[]]){this.raw=e,this.path=t,this.#t=r,this.#e={};}param(e){return e?this.#r(e):this.#i()}#r(e){let t=this.#t[0][this.routeIndex][1][e],r=this.#s(t);return r&&/\%/.test(r)?ru(r):r}#i(){let e={},t=Object.keys(this.#t[0][this.routeIndex][1]);for(let r of t){let n=this.#s(this.#t[0][this.routeIndex][1][r]);n!==void 0&&(e[r]=/\%/.test(n)?ru(n):n);}return e}#s(e){return this.#t[1]?this.#t[1][e]:e}query(e){return eu(this.url,e)}queries(e){return tu(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((r,n)=>{t[n]=r;}),t}async parseBody(e){return this.bodyCache.parsedBody??=await Kc(this,e)}#n=e=>{let{bodyCache:t,raw:r}=this,n=t[e];if(n)return n;let s=Object.keys(t)[0];return s?t[s].then(i=>(s==="json"&&(i=JSON.stringify(i)),new Response(i)[e]())):t[e]=r[e]()};json(){return this.#n("text").then(e=>JSON.parse(e))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(e,t){this.#e[e]=t;}valid(e){return this.#e[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[zc](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,e]])=>e)}get routePath(){return this.#t[0].map(([[,e]])=>e)[this.routeIndex].path}};});var nu,su,lo,co=y(()=>{nu={Stringify:1,BeforeStream:2,Stream:3},su=(e,t)=>{let r=new String(e);return r.isEscaped=true,r.callbacks=t,r},lo=async(e,t,r,n,s)=>{typeof e=="object"&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let i=e.callbacks;if(!i?.length)return Promise.resolve(e);s?s[0]+=e:s=[e];let o=Promise.all(i.map(a=>a({phase:t,buffer:s,context:n}))).then(a=>Promise.all(a.filter(Boolean).map(l=>lo(l,t,false,n,s))).then(()=>s[0]));return r?su(await o,i):o};});var Ly,uo,Ar,iu,ou=y(()=>{no();co();Ly="text/plain; charset=UTF-8",uo=(e,t)=>({"Content-Type":e,...t}),Ar=(e,t)=>new Response(e,t),iu=class{#e;#t;env={};#r;finalized=false;error;#i;#s;#n;#u;#l;#c;#a;#p;#f;constructor(e,t){this.#e=e,t&&(this.#s=t.executionCtx,this.env=t.env,this.#c=t.notFoundHandler,this.#f=t.path,this.#p=t.matchResult);}get req(){return this.#t??=new ts(this.#e,this.#f,this.#p),this.#t}get event(){if(this.#s&&"respondWith"in this.#s)return this.#s;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#s)return this.#s;throw Error("This context has no ExecutionContext")}get res(){return this.#n||=Ar(null,{headers:this.#a??=new Headers})}set res(e){if(this.#n&&e){e=Ar(e.body,e);for(let[t,r]of this.#n.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let n=this.#n.headers.getSetCookie();e.headers.delete("set-cookie");for(let s of n)e.headers.append("set-cookie",s);}else e.headers.set(t,r);}this.#n=e,this.finalized=true;}render=(...e)=>(this.#l??=t=>this.html(t),this.#l(...e));setLayout=e=>this.#u=e;getLayout=()=>this.#u;setRenderer=e=>{this.#l=e;};header=(e,t,r)=>{this.finalized&&(this.#n=Ar(this.#n.body,this.#n));let n=this.#n?this.#n.headers:this.#a??=new Headers;t===void 0?n.delete(e):r?.append?n.append(e,t):n.set(e,t);};status=e=>{this.#i=e;};set=(e,t)=>{this.#r??=new Map,this.#r.set(e,t);};get=e=>this.#r?this.#r.get(e):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#o(e,t,r){let n=this.#n?new Headers(this.#n.headers):this.#a??new Headers;if(typeof t=="object"&&"headers"in t){let i=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[o,a]of i)o.toLowerCase()==="set-cookie"?n.append(o,a):n.set(o,a);}if(r)for(let[i,o]of Object.entries(r))if(typeof o=="string")n.set(i,o);else {n.delete(i);for(let a of o)n.append(i,a);}let s=typeof t=="number"?t:t?.status??this.#i;return Ar(e,{status:s,headers:n})}newResponse=(...e)=>this.#o(...e);body=(e,t,r)=>this.#o(e,t,r);text=(e,t,r)=>!this.#a&&!this.#i&&!t&&!r&&!this.finalized?new Response(e):this.#o(e,t,uo(Ly,r));json=(e,t,r)=>this.#o(JSON.stringify(e),t,uo("application/json",r));html=(e,t,r)=>{let n=s=>this.#o(s,t,uo("text/html; charset=UTF-8",r));return typeof e=="object"?lo(e,nu.Stringify,false,{}).then(n):n(e)};redirect=(e,t)=>{let r=String(e);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,t??302)};notFound=()=>(this.#c??=()=>Ar(),this.#c(this))};});var te,au,lu,is,os,lt=y(()=>{te="ALL",au="all",lu=["get","post","put","delete","options","patch"],is="Can not add a route since the matcher is already built.",os=class extends Error{};});var Cr,po=y(()=>{Cr="__COMPOSED_HANDLER";});var Iy,cu,uu,fu=y(()=>{Wc();ou();lt();po();Vt();Iy=e=>e.text("404 Not Found",404),cu=(e,t)=>{if("getResponse"in e){let r=e.getResponse();return t.newResponse(r.body,r)}return console.error(e),t.text("Internal Server Error",500)},uu=class pu{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(t={}){[...lu,au].forEach(i=>{this[i]=(o,...a)=>(typeof o=="string"?this.#e=o:this.#i(i,this.#e,o),a.forEach(l=>{this.#i(i,this.#e,l);}),this);}),this.on=(i,o,...a)=>{for(let l of [o].flat()){this.#e=l;for(let c of [i].flat())a.map(u=>{this.#i(c.toUpperCase(),this.#e,u);});}return this},this.use=(i,...o)=>(typeof i=="string"?this.#e=i:(this.#e="*",o.unshift(i)),o.forEach(a=>{this.#i(te,this.#e,a);}),this);let{strict:n,...s}=t;Object.assign(this,s),this.getPath=n??true?t.getPath??oo:Qc;}#t(){let t=new pu({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=Iy;errorHandler=cu;route(t,r){let n=this.basePath(t);return r.routes.map(s=>{let i;r.errorHandler===cu?i=s.handler:(i=async(o,a)=>(await ro([],r.errorHandler)(o,()=>s.handler(o,a))).res,i[Cr]=s.handler),n.#i(s.method,s.path,i);}),this}basePath(t){let r=this.#t();return r._basePath=xt(this._basePath,t),r}onError=t=>(this.errorHandler=t,this);notFound=t=>(this.#r=t,this);mount(t,r,n){let s,i;n&&(typeof n=="function"?i=n:(i=n.optionHandler,n.replaceRequest===false?s=l=>l:s=n.replaceRequest));let o=i?l=>{let c=i(l);return Array.isArray(c)?c:[c]}:l=>{let c;try{c=l.executionCtx;}catch{}return [l.env,c]};s||=(()=>{let l=xt(this._basePath,t),c=l==="/"?0:l.length;return u=>{let p=new URL(u.url);return p.pathname=p.pathname.slice(c)||"/",new Request(p,u)}})();let a=async(l,c)=>{let u=await r(s(l.req.raw),...o(l));if(u)return u;await c();};return this.#i(te,xt(t,"*"),a),this}#i(t,r,n){t=t.toUpperCase(),r=xt(this._basePath,r);let s={basePath:this._basePath,path:r,method:t,handler:n};this.router.add(t,r,[n,s]),this.routes.push(s);}#s(t,r){if(t instanceof Error)return this.errorHandler(t,r);throw t}#n(t,r,n,s){if(s==="HEAD")return (async()=>new Response(null,await this.#n(t,r,n,"GET")))();let i=this.getPath(t,{env:n}),o=this.router.match(s,i),a=new iu(t,{path:i,matchResult:o,env:n,executionCtx:r,notFoundHandler:this.#r});if(o[0].length===1){let c;try{c=o[0][0][0][0](a,async()=>{a.res=await this.#r(a);});}catch(u){return this.#s(u,a)}return c instanceof Promise?c.then(u=>u||(a.finalized?a.res:this.#r(a))).catch(u=>this.#s(u,a)):c??this.#r(a)}let l=ro(o[0],this.errorHandler,this.#r);return (async()=>{try{let c=await l(a);if(!c.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return c.res}catch(c){return this.#s(c,a)}})()}fetch=(t,...r)=>this.#n(t,r[1],r[0],t.method);request=(t,r,n,s)=>t instanceof Request?this.fetch(r?new Request(t,r):t,n,s):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${xt("/",t)}`,r),n,s));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method));});}};});function fo(e,t){let r=this.buildAllMatchers(),n=((s,i)=>{let o=r[s]||r[te],a=o[2][i];if(a)return a;let l=i.match(o[0]);if(!l)return [[],as];let c=l.indexOf("",1);return [o[1][c],l]});return this.match=n,n(e,t)}var as,mo=y(()=>{lt();as=[];});function jy(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===Rr||e===kr?1:t===Rr||t===kr?-1:e===ls?1:t===ls?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var ls,Rr,kr,_t,Dy,mu,go=y(()=>{ls="[^/]+",Rr=".*",kr="(?:|/.*)",_t=Symbol(),Dy=new Set(".\\+*[^]$()");mu=class ho{#e;#t;#r=Object.create(null);insert(t,r,n,s,i){if(t.length===0){if(this.#e!==void 0)throw _t;if(i)return;this.#e=r;return}let[o,...a]=t,l=o==="*"?a.length===0?["","",Rr]:["","",ls]:o==="/*"?["","",kr]:o.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(l){let u=l[1],p=l[2]||ls;if(u&&l[2]&&(p===".*"||(p=p.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(p))))throw _t;if(c=this.#r[p],!c){if(Object.keys(this.#r).some(f=>f!==Rr&&f!==kr))throw _t;if(i)return;c=this.#r[p]=new ho,u!==""&&(c.#t=s.varIndex++);}!i&&u!==""&&n.push([u,c.#t]);}else if(c=this.#r[o],!c){if(Object.keys(this.#r).some(u=>u.length>1&&u!==Rr&&u!==kr))throw _t;if(i)return;c=this.#r[o]=new ho;}c.insert(a,r,n,s,i);}buildRegExpStr(){let r=Object.keys(this.#r).sort(jy).map(n=>{let s=this.#r[n];return (typeof s.#t=="number"?`(${n})@${s.#t}`:Dy.has(n)?`\\${n}`:n)+s.buildRegExpStr()});return typeof this.#e=="number"&&r.unshift(`#${this.#e}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};});var du,hu=y(()=>{go();du=class{#e={varIndex:0};#t=new mu;insert(e,t,r){let n=[],s=[];for(let o=0;;){let a=false;if(e=e.replace(/\{[^}]+\}/g,l=>{let c=`@\\${o}`;return s[o]=[c,l],o++,a=true,c}),!a)break}let i=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let o=s.length-1;o>=0;o--){let[a]=s[o];for(let l=i.length-1;l>=0;l--)if(i[l].indexOf(a)!==-1){i[l]=i[l].replace(a,s[o][1]);break}}return this.#t.insert(i,t,n,this.#e,r),n}buildRegExp(){let e=this.#t.buildRegExpStr();if(e==="")return [/^$/,[],[]];let t=0,r=[],n=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(s,i,o)=>i!==void 0?(r[++t]=Number(i),"$()"):(o!==void 0&&(n[Number(o)]=++t),"")),[new RegExp(`^${e}`),r,n]}};});function yu(e){return gu[e]??=new RegExp(e==="*"?"":`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(t,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function My(){gu=Object.create(null);}function Uy(e){let t=new du,r=[];if(e.length===0)return Fy;let n=e.map(c=>[!/\*|\/:/.test(c[0]),...c]).sort(([c,u],[p,f])=>c?1:p?-1:u.length-f.length),s=Object.create(null);for(let c=0,u=-1,p=n.length;c<p;c++){let[f,h,d]=n[c];f?s[h]=[d.map(([b])=>[b,Object.create(null)]),as]:u++;let m;try{m=t.insert(h,u,f);}catch(b){throw b===_t?new os(h):b}f||(r[u]=d.map(([b,g])=>{let S=Object.create(null);for(g-=1;g>=0;g--){let[A,$]=m[g];S[A]=$;}return [b,S]}));}let[i,o,a]=t.buildRegExp();for(let c=0,u=r.length;c<u;c++)for(let p=0,f=r[c].length;p<f;p++){let h=r[c][p]?.[1];if(!h)continue;let d=Object.keys(h);for(let m=0,b=d.length;m<b;m++)h[d[m]]=a[h[d[m]]];}let l=[];for(let c in o)l[c]=r[o[c]];return [i,l,s]}function Kt(e,t){if(e){for(let r of Object.keys(e).sort((n,s)=>s.length-n.length))if(yu(r).test(t))return [...e[r]]}}var Fy,gu,cs,yo=y(()=>{lt();Vt();mo();go();hu();Fy=[/^$/,[],Object.create(null)],gu=Object.create(null);cs=class{name="RegExpRouter";#e;#t;constructor(){this.#e={[te]:Object.create(null)},this.#t={[te]:Object.create(null)};}add(e,t,r){let n=this.#e,s=this.#t;if(!n||!s)throw new Error(is);n[e]||[n,s].forEach(a=>{a[e]=Object.create(null),Object.keys(a[te]).forEach(l=>{a[e][l]=[...a[te][l]];});}),t==="/*"&&(t="*");let i=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let a=yu(t);e===te?Object.keys(n).forEach(l=>{n[l][t]||=Kt(n[l],t)||Kt(n[te],t)||[];}):n[e][t]||=Kt(n[e],t)||Kt(n[te],t)||[],Object.keys(n).forEach(l=>{(e===te||e===l)&&Object.keys(n[l]).forEach(c=>{a.test(c)&&n[l][c].push([r,i]);});}),Object.keys(s).forEach(l=>{(e===te||e===l)&&Object.keys(s[l]).forEach(c=>a.test(c)&&s[l][c].push([r,i]));});return}let o=ss(t)||[t];for(let a=0,l=o.length;a<l;a++){let c=o[a];Object.keys(s).forEach(u=>{(e===te||e===u)&&(s[u][c]||=[...Kt(n[u],c)||Kt(n[te],c)||[]],s[u][c].push([r,i-l+a+1]));});}}match=fo;buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#t).concat(Object.keys(this.#e)).forEach(t=>{e[t]||=this.#r(t);}),this.#e=this.#t=void 0,My(),e}#r(e){let t=[],r=e===te;return [this.#e,this.#t].forEach(n=>{let s=n[e]?Object.keys(n[e]).map(i=>[i,n[e][i]]):[];s.length!==0?(r||=true,t.push(...s)):e!==te&&t.push(...Object.keys(n[te]).map(i=>[i,n[te][i]]));}),r?Uy(t):null}};});var wu=y(()=>{lt();mo();yo();});var bu=y(()=>{yo();wu();});var wo,Su=y(()=>{lt();wo=class{name="SmartRouter";#e=[];#t=[];constructor(e){this.#e=e.routers;}add(e,t,r){if(!this.#t)throw new Error(is);this.#t.push([e,t,r]);}match(e,t){if(!this.#t)throw new Error("Fatal error");let r=this.#e,n=this.#t,s=r.length,i=0,o;for(;i<s;i++){let a=r[i];try{for(let l=0,c=n.length;l<c;l++)a.add(...n[l]);o=a.match(e,t);}catch(l){if(l instanceof os)continue;throw l}this.match=a.match.bind(a),this.#e=[a],this.#t=void 0;break}if(i===s)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#t||this.#e.length!==1)throw new Error("No active router has been determined yet.");return this.#e[0]}};});var Eu=y(()=>{Su();});var Pr,By,xu,$u=y(()=>{lt();Vt();Pr=Object.create(null),By=e=>{for(let t in e)return true;return false},xu=class _u{#e;#t;#r;#i=0;#s=Pr;constructor(t,r,n){if(this.#t=n||Object.create(null),this.#e=[],t&&r){let s=Object.create(null);s[t]={handler:r,possibleKeys:[],score:0},this.#e=[s];}this.#r=[];}insert(t,r,n){this.#i=++this.#i;let s=this,i=Xc(r),o=[];for(let a=0,l=i.length;a<l;a++){let c=i[a],u=i[a+1],p=Yc(c,u),f=Array.isArray(p)?p[0]:c;if(f in s.#t){s=s.#t[f],p&&o.push(p[1]);continue}s.#t[f]=new _u,p&&(s.#r.push(p),o.push(p[1])),s=s.#t[f];}return s.#e.push({[t]:{handler:n,possibleKeys:o.filter((a,l,c)=>c.indexOf(a)===l),score:this.#i}}),s}#n(t,r,n,s,i){for(let o=0,a=r.#e.length;o<a;o++){let l=r.#e[o],c=l[n]||l[te],u={};if(c!==void 0&&(c.params=Object.create(null),t.push(c),s!==Pr||i&&i!==Pr))for(let p=0,f=c.possibleKeys.length;p<f;p++){let h=c.possibleKeys[p],d=u[c.score];c.params[h]=i?.[h]&&!d?i[h]:s[h]??i?.[h],u[c.score]=true;}}}search(t,r){let n=[];this.#s=Pr;let i=[this],o=io(r),a=[],l=o.length,c=null;for(let u=0;u<l;u++){let p=o[u],f=u===l-1,h=[];for(let m=0,b=i.length;m<b;m++){let g=i[m],S=g.#t[p];S&&(S.#s=g.#s,f?(S.#t["*"]&&this.#n(n,S.#t["*"],t,g.#s),this.#n(n,S,t,g.#s)):h.push(S));for(let A=0,$=g.#r.length;A<$;A++){let P=g.#r[A],N=g.#s===Pr?{}:{...g.#s};if(P==="*"){let I=g.#t["*"];I&&(this.#n(n,I,t,g.#s),I.#s=N,h.push(I));continue}let[v,_,L]=P;if(!p&&!(L instanceof RegExp))continue;let w=g.#t[v];if(L instanceof RegExp){if(c===null){c=new Array(l);let q=r[0]==="/"?1:0;for(let E=0;E<l;E++)c[E]=q,q+=o[E].length+1;}let I=r.substring(c[u]),T=L.exec(I);if(T){if(N[_]=T[0],this.#n(n,w,t,g.#s,N),By(w.#t)){w.#s=N;let q=T[0].match(/\//)?.length??0;(a[q]||=[]).push(w);}continue}}(L===true||L.test(p))&&(N[_]=p,f?(this.#n(n,w,t,N,g.#s),w.#t["*"]&&this.#n(n,w.#t["*"],t,N,g.#s)):(w.#s=N,h.push(w)));}}let d=a.shift();i=d?h.concat(d):h;}return n.length>1&&n.sort((u,p)=>u.score-p.score),[n.map(({handler:u,params:p})=>[u,p])]}};});var bo,vu=y(()=>{Vt();$u();bo=class{name="TrieRouter";#e;constructor(){this.#e=new xu;}add(e,t,r){let n=ss(t);if(n){for(let s=0,i=n.length;s<i;s++)this.#e.insert(e,n[s],r);return}this.#e.insert(e,t,r);}match(e,t){return this.#e.search(e,t)}};});var Tu=y(()=>{vu();});var So,Au=y(()=>{fu();bu();Eu();Tu();So=class extends uu{constructor(e={}){super(e),this.router=e.router??new wo({routers:[new cs,new bo]});}};});var Cu=y(()=>{Au();});function Eo(e){return !e||typeof e!="object"?false:e.code==="EADDRINUSE"}function Ru(e,t){return new Promise((r,n)=>{let s=o=>{e.off("listening",i),n(o);},i=()=>{e.off("error",s),r();};e.once("error",s),e.once("listening",i),e.listen(t);})}function xo(e){console.error(),console.error(Nr.default.red(`Cannot start server: Port ${Nr.default.bold(String(e))} is already in use.`)),console.error(Nr.default.red(`Stop the process using that port, or set a different ${Nr.default.bold("api.port")} in your config.`)),console.error(),process.exit(1);}var Nr,ku=y(()=>{Nr=ee(se());});var Pu,Nu=y(()=>{Pu=/^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;});var $o,Ou,qy,_o,vo=y(()=>{$o=(e,t=_o)=>{let r=/\.([a-zA-Z0-9]+?)$/,n=e.match(r);if(!n)return;let s=t[n[1]];return s&&s.startsWith("text")&&(s+="; charset=utf-8"),s},Ou=e=>{for(let t in _o)if(_o[t]===e)return t},qy={aac:"audio/aac",avi:"video/x-msvideo",avif:"image/avif",av1:"video/av1",bin:"application/octet-stream",bmp:"image/bmp",css:"text/css",csv:"text/csv",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gif:"image/gif",gz:"application/gzip",htm:"text/html",html:"text/html",ico:"image/x-icon",ics:"text/calendar",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript",json:"application/json",jsonld:"application/ld+json",map:"application/json",mid:"audio/x-midi",midi:"audio/x-midi",mjs:"text/javascript",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",pdf:"application/pdf",png:"image/png",rtf:"application/rtf",svg:"image/svg+xml",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain",wasm:"application/wasm",webm:"video/webm",weba:"audio/webm",webmanifest:"application/manifest+json",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xml:"application/xml",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2",gltf:"model/gltf+json",glb:"model/gltf-binary"},_o=qy;});var Lu,Iu=y(()=>{Lu=(...e)=>{let t=e.filter(s=>s!=="").join("/");t=t.replace(/(?<=\/)\/+/g,"");let r=t.split("/"),n=[];for(let s of r)s===".."&&n.length>0&&n.at(-1)!==".."?n.pop():s!=="."&&n.push(s);return n.join("/")||"."};});var Du,Hy,Wy,ju,Fu=y(()=>{Nu();vo();Iu();Du={br:".br",zstd:".zst",gzip:".gz"},Hy=Object.keys(Du),Wy="index.html",ju=e=>{let t=e.root??"./",r=e.path,n=e.join??Lu;return async(s,i)=>{if(s.finalized)return i();let o;if(e.path)o=e.path;else try{if(o=decodeURIComponent(s.req.path),/(?:^|[\/\\])\.\.(?:$|[\/\\])/.test(o))throw new Error}catch{return await e.onNotFound?.(s.req.path,s),i()}let a=n(t,!r&&e.rewriteRequestPath?e.rewriteRequestPath(o):o);e.isDir&&await e.isDir(a)&&(a=n(a,Wy));let l=e.getContent,c=await l(a,s);if(c instanceof Response)return s.newResponse(c.body,c);if(c){let u=e.mimes&&$o(a,e.mimes)||$o(a);if(s.header("Content-Type",u||"application/octet-stream"),e.precompressed&&(!u||Pu.test(u))){let p=new Set(s.req.header("Accept-Encoding")?.split(",").map(f=>f.trim()));for(let f of Hy){if(!p.has(f))continue;let h=await l(a+Du[f],s);if(h){c=h,s.header("Content-Encoding",f),s.header("Vary","Accept-Encoding",{append:true});break}}}return await e.onFound?.(a,s),s.body(c)}await e.onNotFound?.(a,s),await i();}};});var Mu,Uu=y(()=>{Fu();Mu=e=>async function(r,n){return ju({...e,getContent:async o=>{let a=Bun.file(o);return await a.exists()?a:null},join:join,isDir:async o=>{let a;try{a=(await stat(o)).isDirectory();}catch{}return a}})(r,n)};});var Bu=y(()=>{});var qu,Hu=y(()=>{Bu();qu=(e,t)=>{for(let[r,n]of Object.entries(t)){let s=new RegExp("/:"+r+"(?:{[^/]+})?\\??");e=e.replace(s,n?`/${n}`:"");}return e};});var Vy,Wu,Gu=y(()=>{Vy=1024,Wu=({concurrency:e,interval:t}={})=>{if(e||=Vy,e===1/0)return {run:async s=>s()};let r=new Set,n=async(s,i,o)=>{if(r.size>=e)return i||=new Promise(c=>o=c),setTimeout(()=>n(s,i,o)),i;let a={};r.add(a);let l=await s();return t?setTimeout(()=>r.delete(a),t):r.delete(a),o?(o(l),i):l};return {run:n}};});var zu,To,Vu=y(()=>{po();zu=e=>e.length>1,To=e=>e[Cr]?To(e[Cr]):e;});var Ku,Ky,Jy,Xy,Yy,Or,Ju,Ao,Co=y(()=>{lt();Vu();Ku=e=>e.split(/[\/\\]/).slice(0,-1).join("/"),Ky=e=>e.replace(/(\\)/g,"/").replace(/\/$/g,""),Jy=(e,t)=>{e.length===0||t?e.push(".."):e.pop();},Xy=(e,t)=>{e=e.replace(/^\.(?!.)/,""),e!==""&&t.push(e);},Yy=(e,t)=>{let r=false;for(let n of e)n===".."?(Jy(t,r),r=true):(Xy(n,t),r=false);},Or=(...e)=>{e=e.map(Ky);let t=[];return Yy(e.join("/").split("/"),t),(e[0][0]==="/"?"/":"")+t.join("/")},Ju=e=>e.routes.reduce((t,{method:r,handler:n,path:s})=>{let i=To(n);return ["GET",te].includes(r)&&!zu(i)&&t.push({path:s}),t},[]),Ao=e=>e.split("/").some(t=>t.startsWith(":")||t.includes("*"));});var Xu,us,Ro=y(()=>{Co();Xu="HONO_SSG_CONTEXT",us="x-hono-disable-ssg",(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[us]:"true"}})}catch{return null}})();});var Yu=y(()=>{co();});var ko,Po=y(()=>{Yu();ko=()=>({afterResponseHook:e=>e.status!==200?false:e});});var Qy,Zy,ew,tw,rw,nw,sw,iw,ow,aw,lw,Qu,cw,Zu,ep=y(()=>{Hu();Gu();vo();Ro();Po();Co();Qy=2,Zy="text/plain",ew="./static",tw=(e,t,r,n)=>{let s=sw(r,n);return e.endsWith(`.${s}`)?Or(t,e):e==="/"?Or(t,`index.${s}`):e.endsWith("/")?Or(t,e,`index.${s}`):Or(t,`${e}.${s}`)},rw=async e=>{let t=e.headers.get("Content-Type");try{return t?.includes("text")||t?.includes("json")?await e.text():await e.arrayBuffer()}catch(r){throw new Error(`Error processing response: ${r instanceof Error?r.message:"Unknown error"}`)}},nw={"text/html":"html","text/xml":"xml","application/xml":"xml","application/yaml":"yaml"},sw=(e,t)=>{let r=t||nw;return e in r?r[e]:Ou(e)||"html"},iw=e=>Array.isArray(e)?async t=>{let r=t;for(let n of e){let s=await n(r);if(s===false)return false;s instanceof Request&&(r=s);}return r}:e,ow=e=>Array.isArray(e)?async t=>{let r=t;for(let n of e){let s=await n(r);if(s===false)return false;s instanceof Response&&(r=s);}return r}:e,aw=(e,t,r)=>Array.isArray(e)?async n=>{for(let s of e)await s(n,t,r);}:e,lw=function*(e,t,r,n){let s="http://localhost",i=Wu({concurrency:n});for(let o of Ju(e)){let a=new URL(o.path,s).toString(),l=new Request(a);yield new Promise(async(c,u)=>{try{if(t){let f=await t(l);if(!f){c(void 0);return}l=f;}if(await i.run(()=>e.fetch(l)),!l.ssgParams){if(Ao(o.path)){c(void 0);return}l.ssgParams=[{}];}let p={method:l.method,headers:l.headers};c((function*(){for(let f of l.ssgParams)yield new Promise(async(h,d)=>{try{let m=qu(o.path,f),b=await i.run(()=>e.request(m,p,{[Xu]:!0}));if(b.headers.get(us)){h(void 0);return}if(r){let A=await r(b);if(!A){h(void 0);return}b=A;}let g=b.headers.get("Content-Type")?.split(";")[0]||Zy,S=await rw(b);h({routePath:m,mimeType:g,content:S});}catch(m){d(m);}});})());}catch(p){u(p);}});}},Qu=new Set,cw=async(e,t,r,n)=>{let s=await e;if(!s)return;let{routePath:i,content:o,mimeType:a}=s,l=tw(i,r,a,n),c=Ku(l);return Qu.has(c)||(await t.mkdir(c,{recursive:true}),Qu.add(c)),typeof o=="string"?await t.writeFile(l,o):o instanceof ArrayBuffer&&await t.writeFile(l,new Uint8Array(o)),l},Zu=async(e,t,r)=>{let n,s=[],i=[],o=r?.plugins||[ko()],a=[],l=[],c=[];r?.beforeRequestHook&&a.push(...Array.isArray(r.beforeRequestHook)?r.beforeRequestHook:[r.beforeRequestHook]),r?.afterResponseHook&&l.push(...Array.isArray(r.afterResponseHook)?r.afterResponseHook:[r.afterResponseHook]),r?.afterGenerateHook&&c.push(...Array.isArray(r.afterGenerateHook)?r.afterGenerateHook:[r.afterGenerateHook]);for(let u of o)u.beforeRequestHook&&a.push(...Array.isArray(u.beforeRequestHook)?u.beforeRequestHook:[u.beforeRequestHook]),u.afterResponseHook&&l.push(...Array.isArray(u.afterResponseHook)?u.afterResponseHook:[u.afterResponseHook]),u.afterGenerateHook&&c.push(...Array.isArray(u.afterGenerateHook)?u.afterGenerateHook:[u.afterGenerateHook]);try{let u=r?.dir??ew,p=r?.concurrency??Qy,f=iw(a.length>0?a:[b=>b]),h=ow(l.length>0?l:[b=>b]),d=lw(e,f,h,p);for(let b of d)s.push(b.then(g=>{if(g)for(let S of g)i.push(cw(S,t,u,r?.extensionMap).catch(A=>A));}));await Promise.all(s);let m=[];for(let b of i){let g=await b;if(typeof g=="string")m.push(g);else if(g)throw g}n={success:!0,files:m};}catch(u){let p=u instanceof Error?u:new Error(String(u));n={success:false,files:[],error:p};}return c.length>0&&await aw(c,t,r)(n,t,r),n};});var tp=y(()=>{ep();Ro();Po();});var uw,No,rp,np=y(()=>{tp();(({write:uw}=Bun)),No={writeFile:async(e,t)=>{await uw(e,t);},mkdir:async()=>{}},rp=async(e,t)=>Zu(e,No,t);});var sp,ip,op,ap=y(()=>{sp=class{#e;constructor(e){this.#e=e,this.raw=e.raw,this.url=e.url?new URL(e.url):null,this.protocol=e.protocol??null;}send(e,t){this.#e.send(e,t??{});}raw;binaryType="arraybuffer";get readyState(){return this.#e.readyState}url;protocol;close(e,t){this.#e.close(e,t);}},ip=e=>new MessageEvent("message",{data:e}),op=e=>((...t)=>{if(typeof t[0]=="function"){let[r,n]=t;return async function(i,o){let a=await r(i),l=await e(i,a,n);if(l)return l;await o();}}else {let[r,n,s]=t;return (async()=>{let i=await e(r,n,s);if(!i)throw new Error("Failed to upgrade WebSocket");return i})()}});});var Jt,ps=y(()=>{Jt=e=>"server"in e.env?e.env.server:e.env;});var Oo,Lo,Io,lp,cp=y(()=>{ap();ps();Oo=e=>new sp({send:(t,r)=>{e.send(t,r?.compress);},raw:e,readyState:e.readyState,url:e.data.url,protocol:e.data.protocol,close(t,r){e.close(t,r);}}),Lo=op((e,t)=>{let r=Jt(e);if(!r)throw new TypeError("env has to include the 2nd argument of fetch.");if(r.upgrade(e.req.raw,{data:{events:t,url:new URL(e.req.url),protocol:e.req.url}}))return new Response(null)}),Io={open(e){let t=e.data.events;t.onOpen&&t.onOpen(new Event("open"),Oo(e));},close(e,t,r){let n=e.data.events;n.onClose&&n.onClose(new CloseEvent("close",{code:t,reason:r}),Oo(e));},message(e,t){let r=e.data.events;if(r.onMessage){let n=typeof t=="string"?t:t.buffer;r.onMessage(ip(n),Oo(e));}}},lp=()=>({upgradeWebSocket:Lo,websocket:Io});});var up,pp=y(()=>{ps();up=e=>{let t=Jt(e);if(!t)throw new TypeError("env has to include the 2nd argument of fetch.");if(typeof t.requestIP!="function")throw new TypeError("server.requestIP is not a function.");let r=t.requestIP(e.req.raw);return r?{remote:{address:r.address,addressType:r.family==="IPv6"||r.family==="IPv4"?r.family:void 0,port:r.port}}:{remote:{}}};});var fp={};fe(fp,{bunFileSystemModule:()=>No,createBunWebSocket:()=>lp,getBunServer:()=>Jt,getConnInfo:()=>up,serveStatic:()=>Mu,toSSG:()=>rp,upgradeWebSocket:()=>Lo,websocket:()=>Io});var mp=y(()=>{Uu();np();cp();pp();ps();});async function fs(e,t={port:3e3}){let r=Wn(),n=t.port??3e3;if(xr()){let s=await Promise.resolve().then(()=>(mp(),fp)).then(o=>o.serveStatic),i;try{i=Bun.serve({fetch:hp(e,r,s).fetch,port:n});}catch(o){throw Eo(o)&&xo(n),o}return async()=>{await i.stop();}}else {let{createAdaptorServer:s}=await import('@hono/node-server'),i=await import('@hono/node-server/serve-static').then(a=>a.serveStatic),o=s({fetch:hp(e,r,i).fetch});try{await Ru(o,n);}catch(a){throw Eo(a)&&xo(n),a}return ()=>new Promise(a=>{o.close(()=>{a(void 0);});})}}function hp(e,t,r){return new So().use("/favicon.ico",r({path:He__default.join(t,"static","favicon.ico")})).use("/fonts/*",r({root:He__default.join(t,"static"),onNotFound:n=>{console.log("fonts not found",n,process.cwd());}})).use("/static/*",r({root:t,onNotFound(n){console.log("not found",n,process.cwd());}})).all("*",async n=>e.fetch(n.req.raw))}var Do=y(()=>{at();Cu();ku();we();});var Ze,jo=y(()=>{wt();Ze=class e{root;constructor(t,r){let n=r??e.projectDir();this.root=He__default.join(n,t??"");}ensureRoot(){Re(this.root);}static homeDir(){return He__default.join(pw.homedir(),".lite")}static projectDir(){return He__default.join(process.cwd(),"supabase")}deleteAll(t=false){try{In.rmSync(this.root,{recursive:!0});}catch(r){if(!t)throw r}this.ensureRoot();}delete(t,r=false){try{In.unlinkSync(He__default.join(this.root,t));}catch(n){if(!r)throw n}}write(t,r,n=false){try{this.ensureRoot(),In.writeFileSync(He__default.join(this.root,t),r);}catch(s){if(!n)throw s}}read(t,r=false){try{return In.readFileSync(He__default.join(this.root,t),"utf8")}catch(n){if(!r)throw n}}relativePath(t){return t?He__default.relative(process.cwd(),He__default.join(this.root,t)):this.root}path(t){return t?He__default.join(this.root,t):this.root}};});var Lr,Fo=y(()=>{Lr=process.env.SUPALITE_CLOUD_URL??(process.env.LOCAL?"http://localhost:2000":"https://www.lite.dev");});var hs,gp=y(()=>{wt();hs=class{root;constructor(t){this.root=t??He__default.join(pw.homedir(),".lite","auth"),Re(this.root);}async getItem(t){try{return In.readFileSync(He__default.join(this.root,t+".json"),"utf8")}catch{return null}}async setItem(t,r){In.writeFileSync(He__default.join(this.root,t+".json"),r);}async removeItem(t){try{In.unlinkSync(He__default.join(this.root,t+".json"));}catch{return}}};});var Xt,Uo=y(()=>{Fo();jo();gp();Xt=class{constructor(t){this.config=t;this.tempFs=new Ze(".temp",this.config.root),this.projectFs=new Ze("supabase",this.config.root),this.schemaFs=new Ze("schemas",this.config.root),this.authStorage=this.config.authStorage??new hs(He__default.join(Ze.homeDir(),"auth")),this._client=this.config.withSupabaseClient!==false?this.config.client??createClient(this.config.host??Lr,process.env.SUPALITE_CLOUD_ANON_KEY??"...",{auth:{storage:this.authStorage}}):void 0;}tempFs;projectFs;schemaFs;_client;authStorage;async fetch(t,r){if(!this.config.token)throw new Error("Not authenticated, sign in first.");let n=t instanceof URL?t:new URL(t,this.config.host??Lr);return await fetch(n,{...r,headers:{...r?.headers,Authorization:`Bearer ${this.config.token}`}})}};});var Yt,Bo=y(()=>{Uo();Yt=class extends Xt{constructor(r){super(r);this.config=r;}get client(){if(!this._client)throw new Error("Supabase client not initialized");return this._client}projectRef(){return this.tempFs.read("project-ref",true)}projectUrl(r){let n=new URL(this.config.host),s=n.hostname==="localhost"?"supalite.local":n.hostname,i=s.split(".").filter(a=>a!=="www"),o=i.length>=2?i.slice(-2).join("."):s;return `${n.protocol}//${r}.${o}${n.port?`:${n.port}`:""}`}};});function hw(e){let t=He.extname(e).toLowerCase();return {".html":"text/html",".css":"text/css",".js":"application/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".webp":"image/webp",".avif":"image/avif",".pdf":"application/pdf",".txt":"text/plain",".xml":"application/xml",".zip":"application/zip",".mp4":"video/mp4",".webm":"video/webm",".mp3":"audio/mpeg",".wav":"audio/wav",".woff":"font/woff",".woff2":"font/woff2"}[t]??"application/octet-stream"}var ys,yp=y(()=>{at();ys=class{driver=ce;basePath;constructor(t){this.basePath=He.resolve(t.basePath);}filePath(t,r){return He.join(this.basePath,t,r)}async ensureDir(t){await ce.mkdir(He.dirname(t),{recursive:true});}async getObject(t,r,n,s){let i=this.filePath(t,r),o=await ce.stat(i),a=`"${createHash("md5").update(`${i}:${o.mtimeMs}`).digest("hex")}"`;if(s?.ifNoneMatch===a)return {httpStatusCode:304,metadata:this.buildMetadata(o,a,r)};if(s?.ifModifiedSince){let f=new Date(s.ifModifiedSince);if(o.mtime<=f)return {httpStatusCode:304,metadata:this.buildMetadata(o,a,r)}}let l,c,u=o.size,p=200;if(s?.range){let f=s.range.match(/^bytes=(\d+)-(\d*)$/);if(f){let h=Number.parseInt(f[1],10),d=f[2]?Number.parseInt(f[2],10):o.size-1;u=d-h+1,c=`bytes ${h}-${d}/${o.size}`,p=206,l=(await ce.open(i,"r")).readableWebStream();}else l=(await ce.open(i,"r")).readableWebStream();}else l=(await ce.open(i,"r")).readableWebStream();return {httpStatusCode:p,metadata:{...this.buildMetadata(o,a,r),contentLength:u,contentRange:c},body:l}}async uploadObject(t,r,n,s,i,o){let a=this.filePath(t,r);await this.ensureDir(a);let l;if(s instanceof Uint8Array||Buffer.isBuffer(s))l=s;else {let p=[],f=s.getReader();for(;;){let{done:h,value:d}=await f.read();if(h)break;p.push(d);}l=Buffer.concat(p);}await ce.writeFile(a,l);let c=await ce.stat(a),u=`"${createHash("md5").update(l).digest("hex")}"`;return {cacheControl:o,contentLength:c.size,size:c.size,mimetype:i,lastModified:c.mtime,eTag:u}}async deleteObject(t,r,n){let s=this.filePath(t,r);await ce.unlink(s).catch(i=>{if(i.code!=="ENOENT")throw i});}async deleteObjects(t,r){for(let n of r)await this.deleteObject(t,n,void 0);}async copyObject(t,r,n,s,i){let o=this.filePath(t,r),a=this.filePath(t,s);await this.ensureDir(a),await ce.copyFile(o,a);let l=await ce.stat(a),c=await ce.readFile(a);return {httpStatusCode:200,eTag:`"${createHash("md5").update(c).digest("hex")}"`,lastModified:l.mtime}}async headObject(t,r,n){let s=this.filePath(t,r),i=await ce.stat(s),o=`"${createHash("md5").update(`${s}:${i.mtimeMs}`).digest("hex")}"`;return this.buildMetadata(i,o,r)}async privateAssetUrl(t,r,n){return `file://${this.filePath(t,r)}`}buildMetadata(t,r,n){return {cacheControl:"no-cache",contentLength:to(t.size),size:to(t.size),mimetype:hw(n),lastModified:t.mtime,eTag:r}}};});async function Ue(e,t,r){try{return await gw(e)}catch(n){throw n?.code==="ERR_MODULE_NOT_FOUND"||/Cannot find package/.test(String(n?.message))?new Error(`Driver '${t}' selected but '${r}' is not installed. Run: bun add ${r}`):n}}var gw,Qt=y(()=>{gw=new Function("spec","return import(spec)");});function wp(e,t={}){let r=He__default.resolve(t.cwd??process.cwd()),n=t.env??process.env,s=process.env.SUPABASE_ENV||"development",i=[`.env.${s}.local`,s==="test"?null:".env.local",`.env.${s}`,".env"].filter(a=>a!==null),o=bw(He__default.resolve(e),r);for(let a of o)for(let l of i){let c=He__default.join(a,l),u;try{u=In.readFileSync(c,"utf-8");}catch{continue}let p;try{p=parse(u);}catch(f){throw new Error(`Failed to parse ${c}: ${f.message}`)}for(let[f,h]of Object.entries(p))n[f]===void 0&&(n[f]=h);}}function bw(e,t){let r=[],n=e,s=He__default.parse(n).root;for(;r.push(n),!(n===t||n===s);){let i=He__default.dirname(n);if(i===n)break;n=i;}return r}var bp=y(()=>{});function Sp(e,t=process.env){return qo(e,t)}function qo(e,t){if(typeof e=="string"){let r=e.match(Sw);return r?t[r[1]]??"":e}if(Array.isArray(e))return e.map(r=>qo(r,t));if(e&&typeof e=="object"){let r={};for(let[n,s]of Object.entries(e))r[n]=qo(s,t);return r}return e}var Sw,Ep=y(()=>{Sw=/^env\((\w+)\)$/;});var Dr,xw,ws,_p=y(()=>{Bo();Wt();Dr=ee(se());Sr();qt();yp();Qt();bp();Ep();xw=["toml","json","ts","mts","js","mjs","cjs"],ws=class extends Yt{ref(){return this.projectRef()}setRef(t){return this.tempFs.write("project-ref",t),this}link(t){return this.setRef(t.id),t}unlink(){return this.tempFs.delete("project-ref"),this}url(){let t=this.ref();if(!t)throw new Error("No project linked");return this.projectUrl(t)}async getConfigPath(t){let r=He__default.relative(process.cwd(),_e.config_dir);if(!t)for(let n of xw){let s=He__default.join(r,`config.${n}`);if(await ce__default.access(s).then(()=>true).catch(()=>false)){t=s;break}}return t}async readConfig(t){let r=await this.getConfigPath(t);if(!r)return {};console.log(Dr.default.dim(`Using config file: ${Dr.default.cyan(`./${r}`)}`));let n=He__default.dirname(He__default.resolve(r));wp(n);let s=r.split(".").pop(),i;switch(s){case "toml":i=St(await ce__default.readFile(r,"utf-8"));break;case "json":i=JSON.parse(await ce__default.readFile(r,"utf-8"));break;case "ts":case "mts":case "js":case "mjs":case "cjs":try{i=(await import(He__default.join(process.cwd(),r))).default;break}catch(o){throw console.error("Failed to import config file",o),o}default:throw new Error(`Unsupported config file type: ${r}`)}return Sp(i)}async createConnection(){throw new Error("Not implemented")}async getConfig(t){let r=await this.readConfig(t);if("connection"in r)return {...r,connection:await r.connection};let n,s;switch(r.db?.driver){case "sqlite":s=r.db?.url??_e.default_db_url,n=await createConnection({url:s,ddlDialect:"sqlite"});break;case "pglite":{s=r.db?.url??He__default.join(process.cwd(),_e.default_db_dir);let{createPgliteConnection:i}=await Ue("@supabase/lite/pglite","pglite","@electric-sql/pglite");n=await i({url:s});break}case "postgres":{s=r.db?.url??"";let{createPostgresConnection:i}=await Ue("@supabase/lite/postgres","postgres","postgres");n=await i({url:s});break}default:s=r.db?.url??_e.default_db_url,n=await createConnection({url:s,ddlDialect:"postgres"});break}if(!n)throw new Error("Failed to create connection");return console.log(Dr.default.green(" \u279C"),"Database located at",Dr.default.cyan(s??"in-memory")),{...r,connection:n}}async createApp(t){let r=await this.getConfig(t),n=new App(r);return n.config.storage?.enabled&&process.env.EXPERIMENTAL_STORAGE==="1"&&!n._storageAdapter&&(n._storageAdapter=new ys({basePath:He__default.join(process.cwd(),_e.config_dir,".temp/storage")})),await n.init()}};});var bs,$p=y(()=>{Bo();bs=class extends Yt{url(t){return this.projectUrl(t)}async ping(){return (await this.fetch("/v1/system/ping")).ok}async list(){let t=await this.fetch("/v1/projects");if(!t.ok)throw new Error("Failed to list projects");let r=await t.json();if(!r||!r.data)throw new Error("Failed to list projects");return r.data}async get(t){if(t=t??this.projectRef(),!t)throw new Error("No project ref found");let r=await this.fetch(`/v1/projects/${t}`);if(!r.ok)throw new Error(`Failed to get project: ${r.status} ${r.statusText}`);let n=await r.json();if(!n||!n.id)throw new Error("Failed to get project");return n}async create(t={}){let r=await this.fetch("/v1/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok)throw new Error(`Failed to create project: ${r.status} ${r.statusText}`);let n=await r.json();if(!n.data||!n.data.id)throw new Error("Failed to create project");return n.data}async getConfig(t){let r=await this.fetch(`/v1/projects/${t}/config`);if(!r.ok)throw new Error(`Failed to get project config: ${r.status} ${r.statusText}`);let n=await r.json();if(!n)throw new Error("Failed to get project config");return n}async setConfig(t,r){let n=await this.fetch(`/v1/projects/${t}/config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!n.ok)throw new Error(`Failed to set project config: ${n.status} ${n.statusText}`);return true}async createApp(t){if(!this.config.host)throw new Error("No host specified");let{data:r,error:n}=await this.client.auth.getSession();if(n)throw n;if(!r?.session?.access_token)throw new Error("Not authenticated, sign in first.");let s=await this.getConfig(t);return await new App({...s.config,connection:cloud({projectRef:t,token:r.session.access_token,host:this.config.host})}).init()}};});var Ss,vp=y(()=>{Uo();_p();$p();Ss=class extends Xt{project;get client(){if(!this._client)throw new Error("Supabase client not initialized");return this._client}async getSession(){return await this.client.auth.getSession()}async getAccessToken(){let{data:t,error:r}=await this.getSession();if(r)throw r;return t?.session?.access_token}async requireSession(){let t=await this.getAccessToken();if(!t)throw new Error("Not authenticated, sign in first.");return t}async init(){let t={...this.config};return this.config.withSupabaseClient!==false&&(t.client=this.client,t.token=await this.getAccessToken()),this.project={local:new ws(t),remote:new bs(t)},this}};});async function V(e={}){return await new Ss({host:Lr,root:Ze.projectDir(),...e}).init()}var Te=y(()=>{jo();Fo();vp();});var Tp={};fe(Tp,{start:()=>vw});var jr,vw,Ap=y(()=>{Do();at();jr=ee(se());Wt();Te();we();qt();vw=e=>{e.command("start").option("--config <config>","Path to the config file").description("Start the development server").helpGroup("Local Development:").action(async t=>{await Y(t.config),await Vn(async()=>{let n=await(await V({withSupabaseClient:false})).project.local.createApp(t.config),s=n.config.api?.port??_e.default_api_port;await fs(n,{port:s});console.log(jr.default.green(" \u279C"),"Server running on ",jr.default.cyan(`http://localhost:${s}`));let o=Ln();o&&console.log(jr.default.yellow(` \u26A0 ${o}`)),await n.connection.ping();},r=>{console.log(),console.log(jr.default.green(`Ready in ${r.toFixed(2)}ms`));});});};});function Nw(e){let t=normalize(e);return t.length>1&&t[t.length-1]===sep&&(t=t.substring(0,t.length-1)),t}function Pp(e,t){return e.replace(Ow,t)}function Iw(e){return e==="/"||Lw.test(e)}function Wo(e,t){let{resolvePaths:r,normalizePath:n,pathSeparator:s}=t,i=process.platform==="win32"&&e.includes("/")||e.startsWith(".");if(r&&(e=resolve(e)),(n||i)&&(e=Nw(e)),e===".")return "";let o=e[e.length-1]!==s;return Pp(o?e+s:e,s)}function Np(e,t){return t+e}function Dw(e,t){return function(r,n){return n.startsWith(e)?n.slice(e.length)+r:Pp(relative(e,n),t.pathSeparator)+t.pathSeparator+r}}function jw(e){return e}function Fw(e,t,r){return t+e+r}function Mw(e,t){let{relativePaths:r,includeBasePath:n}=t;return r&&e?Dw(e,t):n?Np:jw}function Uw(e){return function(t,r){r.push(t.substring(e.length)||".");}}function Bw(e){return function(t,r,n){let s=t.substring(e.length)||".";n.every(i=>i(s,true))&&r.push(s);}}function Gw(e,t){let{includeDirs:r,filters:n,relativePaths:s}=t;return r?s?n&&n.length?Bw(e):Uw(e):n&&n.length?Hw:qw:Ww}function Yw(e){let{excludeFiles:t,filters:r,onlyCounts:n}=e;return t?Xw:r&&r.length?n?zw:Vw:n?Kw:Jw}function eb(e){return e.group?Zw:Qw}function nb(e){return e.group?tb:rb}function ob(e,t){return !e.resolveSymlinks||e.excludeSymlinks?null:t?ib:sb}function Op(e,t,r){if(r.options.useRealPaths)return ab(t,r);let n=dirname(e),s=1;for(;n!==r.root&&s<2;){let i=r.symlinks.get(n);!!i&&(i===t||i.startsWith(t)||t.startsWith(i))?s++:n=dirname(n);}return r.symlinks.set(e,t),s>1}function ab(e,t){return t.visited.includes(e+t.options.pathSeparator)}function Es(e,t,r,n){t(e&&!n?e:null,r);}function gb(e,t){let{onlyCounts:r,group:n,maxFiles:s}=e;return r?t?lb:fb:n?t?cb:hb:s?t?pb:db:t?ub:mb}function bb(e){return e?wb:yb}function _b(e,t){return new Promise((r,n)=>{Dp(e,t,(s,i)=>{if(s)return n(s);r(i);});})}function Dp(e,t,r){new Ip(e,t,r).start();}function $b(e,t){return new Ip(e,t).start()}var Cp,Ow,Lw,qw,Hw,Ww,zw,Vw,Kw,Jw,Xw,Qw,Zw,tb,rb,sb,ib,lb,cb,ub,pb,fb,mb,db,hb,Lp,yb,wb,Sb,Eb,xb,Ip,Rp,jp,Fp,Mp=y(()=>{Cp=createRequire(import.meta.url);Ow=/[\\/]/g;Lw=/^[a-z]:[\\/]$/i;qw=(e,t)=>{t.push(e||".");},Hw=(e,t,r)=>{let n=e||".";r.every(s=>s(n,true))&&t.push(n);},Ww=()=>{};zw=(e,t,r,n)=>{n.every(s=>s(e,false))&&r.files++;},Vw=(e,t,r,n)=>{n.every(s=>s(e,false))&&t.push(e);},Kw=(e,t,r,n)=>{r.files++;},Jw=(e,t)=>{t.push(e);},Xw=()=>{};Qw=e=>e,Zw=()=>[""].slice(0,0);tb=(e,t,r)=>{e.push({directory:t,files:r,dir:t});},rb=()=>{};sb=function(e,t,r){let{queue:n,fs:s,options:{suppressErrors:i}}=t;n.enqueue(),s.realpath(e,(o,a)=>{if(o)return n.dequeue(i?null:o,t);s.stat(a,(l,c)=>{if(l)return n.dequeue(i?null:l,t);if(c.isDirectory()&&Op(e,a,t))return n.dequeue(null,t);r(c,a),n.dequeue(null,t);});});},ib=function(e,t,r){let{queue:n,fs:s,options:{suppressErrors:i}}=t;n.enqueue();try{let o=s.realpathSync(e),a=s.statSync(o);if(a.isDirectory()&&Op(e,o,t))return;r(a,o);}catch(o){if(!i)throw o}};lb=e=>e.counts,cb=e=>e.groups,ub=e=>e.paths,pb=e=>e.paths.slice(0,e.options.maxFiles),fb=(e,t,r)=>(Es(t,r,e.counts,e.options.suppressErrors),null),mb=(e,t,r)=>(Es(t,r,e.paths,e.options.suppressErrors),null),db=(e,t,r)=>(Es(t,r,e.paths.slice(0,e.options.maxFiles),e.options.suppressErrors),null),hb=(e,t,r)=>(Es(t,r,e.groups,e.options.suppressErrors),null);Lp={withFileTypes:true},yb=(e,t,r,n,s)=>{if(e.queue.enqueue(),n<0)return e.queue.dequeue(null,e);let{fs:i}=e;e.visited.push(t),e.counts.directories++,i.readdir(t||".",Lp,(o,a=[])=>{s(a,r,n),e.queue.dequeue(e.options.suppressErrors?null:o,e);});},wb=(e,t,r,n,s)=>{let{fs:i}=e;if(n<0)return;e.visited.push(t),e.counts.directories++;let o=[];try{o=i.readdirSync(t||".",Lp);}catch(a){if(!e.options.suppressErrors)throw a}s(o,r,n);};Sb=class{count=0;constructor(e){this.onQueueEmpty=e;}enqueue(){return this.count++,this.count}dequeue(e,t){this.onQueueEmpty&&(--this.count<=0||e)&&(this.onQueueEmpty(e,t),e&&(t.controller.abort(),this.onQueueEmpty=void 0));}},Eb=class{_files=0;_directories=0;set files(e){this._files=e;}get files(){return this._files}set directories(e){this._directories=e;}get directories(){return this._directories}get dirs(){return this._directories}},xb=class{aborted=false;abort(){this.aborted=true;}},Ip=class{root;isSynchronous;state;joinPath;pushDirectory;pushFile;getArray;groupFiles;resolveSymlink;walkDirectory;callbackInvoker;constructor(e,t,r){this.isSynchronous=!r,this.callbackInvoker=gb(t,this.isSynchronous),this.root=Wo(e,t),this.state={root:Iw(this.root)?this.root:this.root.slice(0,-1),paths:[""].slice(0,0),groups:[],counts:new Eb,options:t,queue:new Sb((n,s)=>this.callbackInvoker(s,n,r)),symlinks:new Map,visited:[""].slice(0,0),controller:new xb,fs:t.fs||er},this.joinPath=Mw(this.root,t),this.pushDirectory=Gw(this.root,t),this.pushFile=Yw(t),this.getArray=eb(t),this.groupFiles=nb(t),this.resolveSymlink=ob(t,this.isSynchronous),this.walkDirectory=bb(this.isSynchronous);}start(){return this.pushDirectory(this.root,this.state.paths,this.state.options.filters),this.walkDirectory(this.state,this.root,this.root,this.state.options.maxDepth,this.walk),this.isSynchronous?this.callbackInvoker(this.state,null):null}walk=(e,t,r)=>{let{paths:n,options:{filters:s,resolveSymlinks:i,excludeSymlinks:o,exclude:a,maxFiles:l,signal:c,useRealPaths:u,pathSeparator:p},controller:f}=this.state;if(f.aborted||c&&c.aborted||l&&n.length>l)return;let h=this.getArray(this.state.paths);for(let d=0;d<e.length;++d){let m=e[d];if(m.isFile()||m.isSymbolicLink()&&!i&&!o){let b=this.joinPath(m.name,t);this.pushFile(b,h,this.state.counts,s);}else if(m.isDirectory()){let b=Fw(m.name,t,this.state.options.pathSeparator);if(a&&a(m.name,b))continue;this.pushDirectory(b,n,s),this.walkDirectory(this.state,b,b,r-1,this.walk);}else if(this.resolveSymlink&&m.isSymbolicLink()){let b=Np(m.name,t);this.resolveSymlink(b,this.state,(g,S)=>{if(g.isDirectory()){if(S=Wo(S,this.state.options),a&&a(m.name,u?S:b+p))return;this.walkDirectory(this.state,S,u?S:b+p,r-1,this.walk);}else {S=u?S:b;let A=basename(S),$=Wo(dirname(S),this.state.options);S=this.joinPath(A,$),this.pushFile(S,h,this.state.counts,s);}});}}this.groupFiles(this.state.groups,t,h);}};Rp=class{constructor(e,t){this.root=e,this.options=t;}withPromise(){return _b(this.root,this.options)}withCallback(e){Dp(this.root,this.options,e);}sync(){return $b(this.root,this.options)}},jp=null;try{Cp.resolve("picomatch"),jp=Cp("picomatch");}catch{}Fp=class{globCache={};options={maxDepth:1/0,suppressErrors:true,pathSeparator:sep,filters:[]};globFunction;constructor(e){this.options={...this.options,...e},this.globFunction=this.options.globFunction;}group(){return this.options.group=true,this}withPathSeparator(e){return this.options.pathSeparator=e,this}withBasePath(){return this.options.includeBasePath=true,this}withRelativePaths(){return this.options.relativePaths=true,this}withDirs(){return this.options.includeDirs=true,this}withMaxDepth(e){return this.options.maxDepth=e,this}withMaxFiles(e){return this.options.maxFiles=e,this}withFullPaths(){return this.options.resolvePaths=true,this.options.includeBasePath=true,this}withErrors(){return this.options.suppressErrors=false,this}withSymlinks({resolvePaths:e=true}={}){return this.options.resolveSymlinks=true,this.options.useRealPaths=e,this.withFullPaths()}withAbortSignal(e){return this.options.signal=e,this}normalize(){return this.options.normalizePath=true,this}filter(e){return this.options.filters.push(e),this}onlyDirs(){return this.options.excludeFiles=true,this.options.includeDirs=true,this}exclude(e){return this.options.exclude=e,this}onlyCounts(){return this.options.onlyCounts=true,this}crawl(e){return new Rp(e||".",this.options)}withGlobFunction(e){return this.globFunction=e,this}crawlWithOptions(e,t){return this.options={...this.options,...t},new Rp(e||".",this.options)}glob(...e){return this.globFunction?this.globWithOptions(e):this.globWithOptions(e,{dot:true})}globWithOptions(e,...t){let r=this.globFunction||jp;if(!r)throw new Error("Please specify a glob function to use glob matching.");var n=this.globCache[e.join("\0")];return n||(n=r(e,...t),this.globCache[e.join("\0")]=n),this.options.filters.push(s=>n(s)),this}};});var Fr=it((_C,Wp)=>{var Up="[^\\\\/]",vb="(?=.)",Bp="[^/]",zo="(?:\\/|$)",qp="(?:^|\\/)",Vo=`\\.{1,2}${zo}`,Tb="(?!\\.)",Ab=`(?!${qp}${Vo})`,Cb=`(?!\\.{0,1}${zo})`,Rb=`(?!${Vo})`,kb="[^.\\/]",Pb=`${Bp}*?`,Nb="/",Hp={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:vb,QMARK:Bp,END_ANCHOR:zo,DOTS_SLASH:Vo,NO_DOT:Tb,NO_DOTS:Ab,NO_DOT_SLASH:Cb,NO_DOTS_SLASH:Rb,QMARK_NO_DOT:kb,STAR:Pb,START_ANCHOR:qp,SEP:Nb},Ob={...Hp,SLASH_LITERAL:"[\\\\/]",QMARK:Up,STAR:`${Up}*?`,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:"\\"},Lb={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"};Wp.exports={MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:Lb,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars(e){return {"!":{type:"negate",open:"(?:(?!(?:",close:`))${e.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(e){return e===true?Ob:Hp}};});var Mr=it(Pe=>{var{REGEX_BACKSLASH:Ib,REGEX_REMOVE_BACKSLASH:Db,REGEX_SPECIAL_CHARS:jb,REGEX_SPECIAL_CHARS_GLOBAL:Fb}=Fr();Pe.isObject=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);Pe.hasRegexChars=e=>jb.test(e);Pe.isRegexChar=e=>e.length===1&&Pe.hasRegexChars(e);Pe.escapeRegex=e=>e.replace(Fb,"\\$1");Pe.toPosixSlashes=e=>e.replace(Ib,"/");Pe.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let e=navigator.platform.toLowerCase();return e==="win32"||e==="windows"}return typeof process<"u"&&process.platform?process.platform==="win32":false};Pe.removeBackslashes=e=>e.replace(Db,t=>t==="\\"?"":t);Pe.escapeLast=(e,t,r)=>{let n=e.lastIndexOf(t,r);return n===-1?e:e[n-1]==="\\"?Pe.escapeLast(e,t,n-1):`${e.slice(0,n)}\\${e.slice(n)}`};Pe.removePrefix=(e,t={})=>{let r=e;return r.startsWith("./")&&(r=r.slice(2),t.prefix="./"),r};Pe.wrapOutput=(e,t={},r={})=>{let n=r.contains?"":"^",s=r.contains?"":"$",i=`${n}(?:${e})${s}`;return t.negated===true&&(i=`(?:^(?!${i}).*$)`),i};Pe.basename=(e,{windows:t}={})=>{let r=e.split(t?/[\\/]/:"/"),n=r[r.length-1];return n===""?r[r.length-2]:n};});var Qp=it((vC,Yp)=>{var Gp=Mr(),{CHAR_ASTERISK:Ko,CHAR_AT:Mb,CHAR_BACKWARD_SLASH:Ur,CHAR_COMMA:Ub,CHAR_DOT:Jo,CHAR_EXCLAMATION_MARK:Xo,CHAR_FORWARD_SLASH:Xp,CHAR_LEFT_CURLY_BRACE:Yo,CHAR_LEFT_PARENTHESES:Qo,CHAR_LEFT_SQUARE_BRACKET:Bb,CHAR_PLUS:qb,CHAR_QUESTION_MARK:zp,CHAR_RIGHT_CURLY_BRACE:Hb,CHAR_RIGHT_PARENTHESES:Vp,CHAR_RIGHT_SQUARE_BRACKET:Wb}=Fr(),Kp=e=>e===Xp||e===Ur,Jp=e=>{e.isPrefix!==true&&(e.depth=e.isGlobstar?1/0:1);},Gb=(e,t)=>{let r=t||{},n=e.length-1,s=r.parts===true||r.scanToEnd===true,i=[],o=[],a=[],l=e,c=-1,u=0,p=0,f=false,h=false,d=false,m=false,b=false,g=false,S=false,A=false,$=false,P=false,N=0,v,_,L={value:"",depth:0,isGlob:false},w=()=>c>=n,I=()=>l.charCodeAt(c+1),T=()=>(v=_,l.charCodeAt(++c));for(;c<n;){_=T();let j;if(_===Ur){S=L.backslashes=true,_=T(),_===Yo&&(g=true);continue}if(g===true||_===Yo){for(N++;w()!==true&&(_=T());){if(_===Ur){S=L.backslashes=true,T();continue}if(_===Yo){N++;continue}if(g!==true&&_===Jo&&(_=T())===Jo){if(f=L.isBrace=true,d=L.isGlob=true,P=true,s===true)continue;break}if(g!==true&&_===Ub){if(f=L.isBrace=true,d=L.isGlob=true,P=true,s===true)continue;break}if(_===Hb&&(N--,N===0)){g=false,f=L.isBrace=true,P=true;break}}if(s===true)continue;break}if(_===Xp){if(i.push(c),o.push(L),L={value:"",depth:0,isGlob:false},P===true)continue;if(v===Jo&&c===u+1){u+=2;continue}p=c+1;continue}if(r.noext!==true&&(_===qb||_===Mb||_===Ko||_===zp||_===Xo)===true&&I()===Qo){if(d=L.isGlob=true,m=L.isExtglob=true,P=true,_===Xo&&c===u&&($=true),s===true){for(;w()!==true&&(_=T());){if(_===Ur){S=L.backslashes=true,_=T();continue}if(_===Vp){d=L.isGlob=true,P=true;break}}continue}break}if(_===Ko){if(v===Ko&&(b=L.isGlobstar=true),d=L.isGlob=true,P=true,s===true)continue;break}if(_===zp){if(d=L.isGlob=true,P=true,s===true)continue;break}if(_===Bb){for(;w()!==true&&(j=T());){if(j===Ur){S=L.backslashes=true,T();continue}if(j===Wb){h=L.isBracket=true,d=L.isGlob=true,P=true;break}}if(s===true)continue;break}if(r.nonegate!==true&&_===Xo&&c===u){A=L.negated=true,u++;continue}if(r.noparen!==true&&_===Qo){if(d=L.isGlob=true,s===true){for(;w()!==true&&(_=T());){if(_===Qo){S=L.backslashes=true,_=T();continue}if(_===Vp){P=true;break}}continue}break}if(d===true){if(P=true,s===true)continue;break}}r.noext===true&&(m=false,d=false);let q=l,E="",x="";u>0&&(E=l.slice(0,u),l=l.slice(u),p-=u),q&&d===true&&p>0?(q=l.slice(0,p),x=l.slice(p)):d===true?(q="",x=l):q=l,q&&q!==""&&q!=="/"&&q!==l&&Kp(q.charCodeAt(q.length-1))&&(q=q.slice(0,-1)),r.unescape===true&&(x&&(x=Gp.removeBackslashes(x)),q&&S===true&&(q=Gp.removeBackslashes(q)));let U={prefix:E,input:e,start:u,base:q,glob:x,isBrace:f,isBracket:h,isGlob:d,isExtglob:m,isGlobstar:b,negated:A,negatedExtglob:$};if(r.tokens===true&&(U.maxDepth=0,Kp(_)||o.push(L),U.tokens=o),r.parts===true||r.tokens===true){let j;for(let z=0;z<i.length;z++){let Me=j?j+1:u,Ce=i[z],st=e.slice(Me,Ce);r.tokens&&(z===0&&u!==0?(o[z].isPrefix=true,o[z].value=E):o[z].value=st,Jp(o[z]),U.maxDepth+=o[z].depth),(z!==0||st!=="")&&a.push(st),j=Ce;}if(j&&j+1<e.length){let z=e.slice(j+1);a.push(z),r.tokens&&(o[o.length-1].value=z,Jp(o[o.length-1]),U.maxDepth+=o[o.length-1].depth);}U.slashes=i,U.parts=a;}return U};Yp.exports=Gb;});var tf=it((TC,ef)=>{var xs=Fr(),ze=Mr(),{MAX_LENGTH:_s,POSIX_REGEX_SOURCE:zb,REGEX_NON_SPECIAL_CHARS:Vb,REGEX_SPECIAL_CHARS_BACKREF:Kb,REPLACEMENTS:Zp}=xs,Jb=(e,t)=>{if(typeof t.expandRange=="function")return t.expandRange(...e,t);e.sort();let r=`[${e.join("-")}]`;try{new RegExp(r);}catch{return e.map(s=>ze.escapeRegex(s)).join("..")}return r},Zt=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`,Zo=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a string");e=Zp[e]||e;let r={...t},n=typeof r.maxLength=="number"?Math.min(_s,r.maxLength):_s,s=e.length;if(s>n)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${n}`);let i={type:"bos",value:"",output:r.prepend||""},o=[i],a=r.capture?"":"?:",l=xs.globChars(r.windows),c=xs.extglobChars(l),{DOT_LITERAL:u,PLUS_LITERAL:p,SLASH_LITERAL:f,ONE_CHAR:h,DOTS_SLASH:d,NO_DOT:m,NO_DOT_SLASH:b,NO_DOTS_SLASH:g,QMARK:S,QMARK_NO_DOT:A,STAR:$,START_ANCHOR:P}=l,N=O=>`(${a}(?:(?!${P}${O.dot?d:u}).)*?)`,v=r.dot?"":m,_=r.dot?S:A,L=r.bash===true?N(r):$;r.capture&&(L=`(${L})`),typeof r.noext=="boolean"&&(r.noextglob=r.noext);let w={input:e,index:-1,start:0,dot:r.dot===true,consumed:"",output:"",prefix:"",backtrack:false,negated:false,brackets:0,braces:0,parens:0,quotes:0,globstar:false,tokens:o};e=ze.removePrefix(e,w),s=e.length;let I=[],T=[],q=[],E=i,x,U=()=>w.index===s-1,j=w.peek=(O=1)=>e[w.index+O],z=w.advance=()=>e[++w.index]||"",Me=()=>e.slice(w.index+1),Ce=(O="",re=0)=>{w.consumed+=O,w.index+=re;},st=O=>{w.output+=O.output!=null?O.output:O.value,Ce(O.value);},Lh=()=>{let O=1;for(;j()==="!"&&(j(2)!=="("||j(3)==="?");)z(),w.start++,O++;return O%2===0?false:(w.negated=true,w.start++,true)},Rn=O=>{w[O]++,q.push(O);},gt=O=>{w[O]--,q.pop();},G=O=>{if(E.type==="globstar"){let re=w.braces>0&&(O.type==="comma"||O.type==="brace"),C=O.extglob===true||I.length&&(O.type==="pipe"||O.type==="paren");O.type!=="slash"&&O.type!=="paren"&&!re&&!C&&(w.output=w.output.slice(0,-E.output.length),E.type="star",E.value="*",E.output=L,w.output+=E.output);}if(I.length&&O.type!=="paren"&&(I[I.length-1].inner+=O.value),(O.value||O.output)&&st(O),E&&E.type==="text"&&O.type==="text"){E.output=(E.output||E.value)+O.value,E.value+=O.value;return}O.prev=E,o.push(O),E=O;},kn=(O,re)=>{let C={...c[re],conditions:1,inner:""};C.prev=E,C.parens=w.parens,C.output=w.output;let W=(r.capture?"(":"")+C.open;Rn("parens"),G({type:O,value:re,output:w.output?"":h}),G({type:"paren",extglob:true,value:z(),output:W}),I.push(C);},Ih=O=>{let re=O.close+(r.capture?")":""),C;if(O.type==="negate"){let W=L;if(O.inner&&O.inner.length>1&&O.inner.includes("/")&&(W=N(r)),(W!==L||U()||/^\)+$/.test(Me()))&&(re=O.close=`)$))${W}`),O.inner.includes("*")&&(C=Me())&&/^\.[^\\/.]+$/.test(C)){let ae=Zo(C,{...t,fastpaths:false}).output;re=O.close=`)${ae})${W})`;}O.prev.type==="bos"&&(w.negatedExtglob=true);}G({type:"paren",extglob:true,value:x,output:re}),gt("parens");};if(r.fastpaths!==false&&!/(^[*!]|[/()[\]{}"])/.test(e)){let O=false,re=e.replace(Kb,(C,W,ae,xe,pe,Ai)=>xe==="\\"?(O=true,C):xe==="?"?W?W+xe+(pe?S.repeat(pe.length):""):Ai===0?_+(pe?S.repeat(pe.length):""):S.repeat(ae.length):xe==="."?u.repeat(ae.length):xe==="*"?W?W+xe+(pe?L:""):L:W?C:`\\${C}`);return O===true&&(r.unescape===true?re=re.replace(/\\/g,""):re=re.replace(/\\+/g,C=>C.length%2===0?"\\\\":C?"\\":"")),re===e&&r.contains===true?(w.output=e,w):(w.output=ze.wrapOutput(re,w,t),w)}for(;!U();){if(x=z(),x==="\0")continue;if(x==="\\"){let C=j();if(C==="/"&&r.bash!==true||C==="."||C===";")continue;if(!C){x+="\\",G({type:"text",value:x});continue}let W=/^\\+/.exec(Me()),ae=0;if(W&&W[0].length>2&&(ae=W[0].length,w.index+=ae,ae%2!==0&&(x+="\\")),r.unescape===true?x=z():x+=z(),w.brackets===0){G({type:"text",value:x});continue}}if(w.brackets>0&&(x!=="]"||E.value==="["||E.value==="[^")){if(r.posix!==false&&x===":"){let C=E.value.slice(1);if(C.includes("[")&&(E.posix=true,C.includes(":"))){let W=E.value.lastIndexOf("["),ae=E.value.slice(0,W),xe=E.value.slice(W+2),pe=zb[xe];if(pe){E.value=ae+pe,w.backtrack=true,z(),!i.output&&o.indexOf(E)===1&&(i.output=h);continue}}}(x==="["&&j()!==":"||x==="-"&&j()==="]")&&(x=`\\${x}`),x==="]"&&(E.value==="["||E.value==="[^")&&(x=`\\${x}`),r.posix===true&&x==="!"&&E.value==="["&&(x="^"),E.value+=x,st({value:x});continue}if(w.quotes===1&&x!=='"'){x=ze.escapeRegex(x),E.value+=x,st({value:x});continue}if(x==='"'){w.quotes=w.quotes===1?0:1,r.keepQuotes===true&&G({type:"text",value:x});continue}if(x==="("){Rn("parens"),G({type:"paren",value:x});continue}if(x===")"){if(w.parens===0&&r.strictBrackets===true)throw new SyntaxError(Zt("opening","("));let C=I[I.length-1];if(C&&w.parens===C.parens+1){Ih(I.pop());continue}G({type:"paren",value:x,output:w.parens?")":"\\)"}),gt("parens");continue}if(x==="["){if(r.nobracket===true||!Me().includes("]")){if(r.nobracket!==true&&r.strictBrackets===true)throw new SyntaxError(Zt("closing","]"));x=`\\${x}`;}else Rn("brackets");G({type:"bracket",value:x});continue}if(x==="]"){if(r.nobracket===true||E&&E.type==="bracket"&&E.value.length===1){G({type:"text",value:x,output:`\\${x}`});continue}if(w.brackets===0){if(r.strictBrackets===true)throw new SyntaxError(Zt("opening","["));G({type:"text",value:x,output:`\\${x}`});continue}gt("brackets");let C=E.value.slice(1);if(E.posix!==true&&C[0]==="^"&&!C.includes("/")&&(x=`/${x}`),E.value+=x,st({value:x}),r.literalBrackets===false||ze.hasRegexChars(C))continue;let W=ze.escapeRegex(E.value);if(w.output=w.output.slice(0,-E.value.length),r.literalBrackets===true){w.output+=W,E.value=W;continue}E.value=`(${a}${W}|${E.value})`,w.output+=E.value;continue}if(x==="{"&&r.nobrace!==true){Rn("braces");let C={type:"brace",value:x,output:"(",outputIndex:w.output.length,tokensIndex:w.tokens.length};T.push(C),G(C);continue}if(x==="}"){let C=T[T.length-1];if(r.nobrace===true||!C){G({type:"text",value:x,output:x});continue}let W=")";if(C.dots===true){let ae=o.slice(),xe=[];for(let pe=ae.length-1;pe>=0&&(o.pop(),ae[pe].type!=="brace");pe--)ae[pe].type!=="dots"&&xe.unshift(ae[pe].value);W=Jb(xe,r),w.backtrack=true;}if(C.comma!==true&&C.dots!==true){let ae=w.output.slice(0,C.outputIndex),xe=w.tokens.slice(C.tokensIndex);C.value=C.output="\\{",x=W="\\}",w.output=ae;for(let pe of xe)w.output+=pe.output||pe.value;}G({type:"brace",value:x,output:W}),gt("braces"),T.pop();continue}if(x==="|"){I.length>0&&I[I.length-1].conditions++,G({type:"text",value:x});continue}if(x===","){let C=x,W=T[T.length-1];W&&q[q.length-1]==="braces"&&(W.comma=true,C="|"),G({type:"comma",value:x,output:C});continue}if(x==="/"){if(E.type==="dot"&&w.index===w.start+1){w.start=w.index+1,w.consumed="",w.output="",o.pop(),E=i;continue}G({type:"slash",value:x,output:f});continue}if(x==="."){if(w.braces>0&&E.type==="dot"){E.value==="."&&(E.output=u);let C=T[T.length-1];E.type="dots",E.output+=x,E.value+=x,C.dots=true;continue}if(w.braces+w.parens===0&&E.type!=="bos"&&E.type!=="slash"){G({type:"text",value:x,output:u});continue}G({type:"dot",value:x,output:u});continue}if(x==="?"){if(!(E&&E.value==="(")&&r.noextglob!==true&&j()==="("&&j(2)!=="?"){kn("qmark",x);continue}if(E&&E.type==="paren"){let W=j(),ae=x;(E.value==="("&&!/[!=<:]/.test(W)||W==="<"&&!/<([!=]|\w+>)/.test(Me()))&&(ae=`\\${x}`),G({type:"text",value:x,output:ae});continue}if(r.dot!==true&&(E.type==="slash"||E.type==="bos")){G({type:"qmark",value:x,output:A});continue}G({type:"qmark",value:x,output:S});continue}if(x==="!"){if(r.noextglob!==true&&j()==="("&&(j(2)!=="?"||!/[!=<:]/.test(j(3)))){kn("negate",x);continue}if(r.nonegate!==true&&w.index===0){Lh();continue}}if(x==="+"){if(r.noextglob!==true&&j()==="("&&j(2)!=="?"){kn("plus",x);continue}if(E&&E.value==="("||r.regex===false){G({type:"plus",value:x,output:p});continue}if(E&&(E.type==="bracket"||E.type==="paren"||E.type==="brace")||w.parens>0){G({type:"plus",value:x});continue}G({type:"plus",value:p});continue}if(x==="@"){if(r.noextglob!==true&&j()==="("&&j(2)!=="?"){G({type:"at",extglob:true,value:x,output:""});continue}G({type:"text",value:x});continue}if(x!=="*"){(x==="$"||x==="^")&&(x=`\\${x}`);let C=Vb.exec(Me());C&&(x+=C[0],w.index+=C[0].length),G({type:"text",value:x});continue}if(E&&(E.type==="globstar"||E.star===true)){E.type="star",E.star=true,E.value+=x,E.output=L,w.backtrack=true,w.globstar=true,Ce(x);continue}let O=Me();if(r.noextglob!==true&&/^\([^?]/.test(O)){kn("star",x);continue}if(E.type==="star"){if(r.noglobstar===true){Ce(x);continue}let C=E.prev,W=C.prev,ae=C.type==="slash"||C.type==="bos",xe=W&&(W.type==="star"||W.type==="globstar");if(r.bash===true&&(!ae||O[0]&&O[0]!=="/")){G({type:"star",value:x,output:""});continue}let pe=w.braces>0&&(C.type==="comma"||C.type==="brace"),Ai=I.length&&(C.type==="pipe"||C.type==="paren");if(!ae&&C.type!=="paren"&&!pe&&!Ai){G({type:"star",value:x,output:""});continue}for(;O.slice(0,3)==="/**";){let Pn=e[w.index+4];if(Pn&&Pn!=="/")break;O=O.slice(3),Ce("/**",3);}if(C.type==="bos"&&U()){E.type="globstar",E.value+=x,E.output=N(r),w.output=E.output,w.globstar=true,Ce(x);continue}if(C.type==="slash"&&C.prev.type!=="bos"&&!xe&&U()){w.output=w.output.slice(0,-(C.output+E.output).length),C.output=`(?:${C.output}`,E.type="globstar",E.output=N(r)+(r.strictSlashes?")":"|$)"),E.value+=x,w.globstar=true,w.output+=C.output+E.output,Ce(x);continue}if(C.type==="slash"&&C.prev.type!=="bos"&&O[0]==="/"){let Pn=O[1]!==void 0?"|$":"";w.output=w.output.slice(0,-(C.output+E.output).length),C.output=`(?:${C.output}`,E.type="globstar",E.output=`${N(r)}${f}|${f}${Pn})`,E.value+=x,w.output+=C.output+E.output,w.globstar=true,Ce(x+z()),G({type:"slash",value:"/",output:""});continue}if(C.type==="bos"&&O[0]==="/"){E.type="globstar",E.value+=x,E.output=`(?:^|${f}|${N(r)}${f})`,w.output=E.output,w.globstar=true,Ce(x+z()),G({type:"slash",value:"/",output:""});continue}w.output=w.output.slice(0,-E.output.length),E.type="globstar",E.output=N(r),E.value+=x,w.output+=E.output,w.globstar=true,Ce(x);continue}let re={type:"star",value:x,output:L};if(r.bash===true){re.output=".*?",(E.type==="bos"||E.type==="slash")&&(re.output=v+re.output),G(re);continue}if(E&&(E.type==="bracket"||E.type==="paren")&&r.regex===true){re.output=x,G(re);continue}(w.index===w.start||E.type==="slash"||E.type==="dot")&&(E.type==="dot"?(w.output+=b,E.output+=b):r.dot===true?(w.output+=g,E.output+=g):(w.output+=v,E.output+=v),j()!=="*"&&(w.output+=h,E.output+=h)),G(re);}for(;w.brackets>0;){if(r.strictBrackets===true)throw new SyntaxError(Zt("closing","]"));w.output=ze.escapeLast(w.output,"["),gt("brackets");}for(;w.parens>0;){if(r.strictBrackets===true)throw new SyntaxError(Zt("closing",")"));w.output=ze.escapeLast(w.output,"("),gt("parens");}for(;w.braces>0;){if(r.strictBrackets===true)throw new SyntaxError(Zt("closing","}"));w.output=ze.escapeLast(w.output,"{"),gt("braces");}if(r.strictSlashes!==true&&(E.type==="star"||E.type==="bracket")&&G({type:"maybe_slash",value:"",output:`${f}?`}),w.backtrack===true){w.output="";for(let O of w.tokens)w.output+=O.output!=null?O.output:O.value,O.suffix&&(w.output+=O.suffix);}return w};Zo.fastpaths=(e,t)=>{let r={...t},n=typeof r.maxLength=="number"?Math.min(_s,r.maxLength):_s,s=e.length;if(s>n)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${n}`);e=Zp[e]||e;let{DOT_LITERAL:i,SLASH_LITERAL:o,ONE_CHAR:a,DOTS_SLASH:l,NO_DOT:c,NO_DOTS:u,NO_DOTS_SLASH:p,STAR:f,START_ANCHOR:h}=xs.globChars(r.windows),d=r.dot?u:c,m=r.dot?p:c,b=r.capture?"":"?:",g={negated:false,prefix:""},S=r.bash===true?".*?":f;r.capture&&(S=`(${S})`);let A=v=>v.noglobstar===true?S:`(${b}(?:(?!${h}${v.dot?l:i}).)*?)`,$=v=>{switch(v){case "*":return `${d}${a}${S}`;case ".*":return `${i}${a}${S}`;case "*.*":return `${d}${S}${i}${a}${S}`;case "*/*":return `${d}${S}${o}${a}${m}${S}`;case "**":return d+A(r);case "**/*":return `(?:${d}${A(r)}${o})?${m}${a}${S}`;case "**/*.*":return `(?:${d}${A(r)}${o})?${m}${S}${i}${a}${S}`;case "**/.*":return `(?:${d}${A(r)}${o})?${i}${a}${S}`;default:{let _=/^(.*?)\.(\w+)$/.exec(v);if(!_)return;let L=$(_[1]);return L?L+i+_[2]:void 0}}},P=ze.removePrefix(e,g),N=$(P);return N&&r.strictSlashes!==true&&(N+=`${o}?`),N};ef.exports=Zo;});var sf=it((AC,nf)=>{var Xb=Qp(),ea=tf(),rf=Mr(),Yb=Fr(),Qb=e=>e&&typeof e=="object"&&!Array.isArray(e),le=(e,t,r=false)=>{if(Array.isArray(e)){let u=e.map(f=>le(f,t,r));return f=>{for(let h of u){let d=h(f);if(d)return d}return false}}let n=Qb(e)&&e.tokens&&e.input;if(e===""||typeof e!="string"&&!n)throw new TypeError("Expected pattern to be a non-empty string");let s=t||{},i=s.windows,o=n?le.compileRe(e,t):le.makeRe(e,t,false,true),a=o.state;delete o.state;let l=()=>false;if(s.ignore){let u={...t,ignore:null,onMatch:null,onResult:null};l=le(s.ignore,u,r);}let c=(u,p=false)=>{let{isMatch:f,match:h,output:d}=le.test(u,o,t,{glob:e,posix:i}),m={glob:e,state:a,regex:o,posix:i,input:u,output:d,match:h,isMatch:f};return typeof s.onResult=="function"&&s.onResult(m),f===false?(m.isMatch=false,p?m:false):l(u)?(typeof s.onIgnore=="function"&&s.onIgnore(m),m.isMatch=false,p?m:false):(typeof s.onMatch=="function"&&s.onMatch(m),p?m:true)};return r&&(c.state=a),c};le.test=(e,t,r,{glob:n,posix:s}={})=>{if(typeof e!="string")throw new TypeError("Expected input to be a string");if(e==="")return {isMatch:false,output:""};let i=r||{},o=i.format||(s?rf.toPosixSlashes:null),a=e===n,l=a&&o?o(e):e;return a===false&&(l=o?o(e):e,a=l===n),(a===false||i.capture===true)&&(i.matchBase===true||i.basename===true?a=le.matchBase(e,t,r,s):a=t.exec(l)),{isMatch:!!a,match:a,output:l}};le.matchBase=(e,t,r)=>(t instanceof RegExp?t:le.makeRe(t,r)).test(rf.basename(e));le.isMatch=(e,t,r)=>le(t,r)(e);le.parse=(e,t)=>Array.isArray(e)?e.map(r=>le.parse(r,t)):ea(e,{...t,fastpaths:false});le.scan=(e,t)=>Xb(e,t);le.compileRe=(e,t,r=false,n=false)=>{if(r===true)return e.output;let s=t||{},i=s.contains?"":"^",o=s.contains?"":"$",a=`${i}(?:${e.output})${o}`;e&&e.negated===true&&(a=`^(?!${a}).*$`);let l=le.toRegex(a,t);return n===true&&(l.state=e),l};le.makeRe=(e,t={},r=false,n=false)=>{if(!e||typeof e!="string")throw new TypeError("Expected a non-empty string");let s={negated:false,fastpaths:true};return t.fastpaths!==false&&(e[0]==="."||e[0]==="*")&&(s.output=ea.fastpaths(e,t)),s.output||(s=ea(e,t)),le.compileRe(s,t,r,n)};le.toRegex=(e,t)=>{try{let r=t||{};return new RegExp(e,r.flags||(r.nocase?"i":""))}catch(r){if(t&&t.debug===true)throw r;return /$^/}};le.constants=Yb;nf.exports=le;});var cf=it((CC,lf)=>{var of=sf(),Zb=Mr();function af(e,t,r=false){return t&&(t.windows===null||t.windows===void 0)&&(t={...t,windows:Zb.isWindows()}),of(e,t,r)}Object.assign(af,of);lf.exports=af;});function nS(e,t={}){let r=e.length,n=Array(r),s=Array(r),i=!t.noglobstar;for(let o=0;o<r;o++){let a=mf(e[o]);n[o]=a;let l=a.length,c=Array(l);for(let u=0;u<l;u++)c[u]=(0, rr.default)(a[u],t);s[o]=c;}return o=>{let a=o.split("/");if(a[0]===".."&&rS.test(o))return true;for(let l=0;l<e.length;l++){let c=n[l],u=s[l],p=a.length,f=Math.min(p,c.length),h=0;for(;h<f;){let d=c[h];if(d.includes("/"))return true;if(!u[h](a[h]))break;if(i&&d==="**")return true;h++;}if(h===p)return true}return false}}function uf(e,t,r){if(e===t||t.startsWith(`${e}/`)){if(r){let s=iS(e)?e.length:e.length+1;return (i,o)=>i.slice(s,o?-1:void 0)||"."}let n=t.slice(e.length+1);return n?(s,i)=>{if(s===".")return n;let o=`${n}/${s}`;return i?o.slice(0,-1):o}:(s,i)=>i&&s!=="."?s.slice(0,-1):s}return r?n=>posix.relative(e,n)||".":n=>posix.relative(e,`${t}/${n}`)||"."}function oS(e,t){if(t.startsWith(`${e}/`)){let r=t.slice(e.length+1);return n=>`${r}/${n}`}return r=>{let n=posix.relative(e,`${t}/${r}`);return r.endsWith("/")&&n!==""?`${n}/`:n||"."}}function mf(e){var t;let r=rr.default.scan(e,aS);return !((t=r.parts)===null||t===void 0)&&t.length?r.parts:[e]}function mS(e,t){let r=rr.default.scan(e);return r.isGlob||r.negated}function tr(...e){console.log(`[tinyglobby ${new Date().toLocaleTimeString("es")}]`,...e);}function ta(e,t,r,n,s){let i=e;e.endsWith("/")&&(i=e.slice(0,-1)),!i.endsWith("*")&&t&&(i+="/**");let o=fS(r);pf.isAbsolute(i.replace(hS,""))?i=posix.relative(o,i):i=posix.normalize(i);let a=dS.exec(i),l=mf(i);if(a?.[0]){let u=(a[0].length+1)/3,p=0,f=o.split("/");for(;p<u&&l[p+u]===f[f.length+p-u];)i=i.slice(0,(u-p-1)*3)+i.slice((u-p)*3+l[p+u].length+1)||".",p++;let h=posix.join(r,a[0].slice(p*3));!h.startsWith(".")&&n.root.length>h.length&&(n.root=h,n.depthOffset=-u+p);}if(!s&&n.depthOffset>=0){var c;(c=n.commonPath)!==null&&c!==void 0||(n.commonPath=l);let u=[],p=Math.min(n.commonPath.length,l.length);for(let f=0;f<p;f++){let h=l[f];if(h==="**"&&!l[f+1]){u.pop();break}if(h!==n.commonPath[f]||mS(h)||f===l.length-1)break;u.push(h);}n.depthOffset=u.length,n.commonPath=u,n.root=u.length>0?posix.join(r,...u):r;}return i}function gS({patterns:e=["**/*"],ignore:t=[],expandDirectories:r=true},n,s){typeof e=="string"&&(e=[e]),typeof t=="string"&&(t=[t]);let i=[],o=[];for(let a of t)a&&(a[0]!=="!"||a[1]==="(")&&o.push(ta(a,r,n,s,true));for(let a of e)a&&(a[0]!=="!"||a[1]==="("?i.push(ta(a,r,n,s,false)):(a[1]!=="!"||a[2]==="(")&&o.push(ta(a.slice(1),r,n,s,true)));return {match:i,ignore:o}}function yS(e,t){for(let r=e.length-1;r>=0;r--){let n=e[r];e[r]=t(n);}return e}function wS(e){return e?e instanceof URL?fileURLToPath$1(e).replace($s,"/"):pf.resolve(e).replace($s,"/"):process.cwd().replace($s,"/")}function bS(e,t={}){let r=process.env.TINYGLOBBY_DEBUG?{...t,debug:true}:t,n=wS(r.cwd);if(r.debug&&tr("globbing with:",{patterns:e,options:r,cwd:n}),Array.isArray(e)&&e.length===0)return [{sync:()=>[],withPromise:async()=>[]},false];let s={root:n,commonPath:null,depthOffset:0},i=gS({...r,patterns:e},n,s);r.debug&&tr("internal processing patterns:",i);let o={dot:r.dot,nobrace:r.braceExpansion===false,nocase:r.caseSensitiveMatch===false,noextglob:r.extglob===false,noglobstar:r.globstar===false,posix:true},a=(0, rr.default)(i.match,{...o,ignore:i.ignore}),l=(0, rr.default)(i.ignore,o),c=nS(i.match,o),u=uf(n,s.root,r.absolute),p=r.absolute?u:uf(n,s.root,true),f={filters:[r.debug?(m,b)=>{let g=u(m,b),S=a(g);return S&&tr(`matched ${g}`),S}:(m,b)=>a(u(m,b))],exclude:r.debug?(m,b)=>{let g=p(b,true),S=g!=="."&&!c(g)||l(g);return tr(S?`skipped ${b}`:`crawling ${b}`),S}:(m,b)=>{let g=p(b,true);return g!=="."&&!c(g)||l(g)},fs:r.fs?{readdir:r.fs.readdir||er__default.readdir,readdirSync:r.fs.readdirSync||er__default.readdirSync,realpath:r.fs.realpath||er__default.realpath,realpathSync:r.fs.realpathSync||er__default.realpathSync,stat:r.fs.stat||er__default.stat,statSync:r.fs.statSync||er__default.statSync}:void 0,pathSeparator:"/",relativePaths:true,resolveSymlinks:true,signal:r.signal};r.deep!==void 0&&(f.maxDepth=Math.round(r.deep-s.depthOffset)),r.absolute&&(f.relativePaths=false,f.resolvePaths=true,f.includeBasePath=true),r.followSymbolicLinks===false&&(f.resolveSymlinks=false,f.excludeSymlinks=true),r.onlyDirectories?(f.excludeFiles=true,f.includeDirs=true):r.onlyFiles===false&&(f.includeDirs=true),s.root=s.root.replace($s,"");let h=s.root;r.debug&&tr("internal properties:",s);let d=n!==h&&!r.absolute&&oS(n,s.root);return [new Fp(f).crawl(h),d]}async function Br(e,t){if(e&&t?.patterns)throw new Error("Cannot pass patterns as both an argument and an option");let r=tS(e)||typeof e=="string",n=r?t:e,s=r?e:e.patterns,[i,o]=bS(s,n);return o?yS(await i.withPromise(),o):i.withPromise()}var rr,tS,ff,rS,sS,iS,aS,lS,cS,uS,pS,fS,dS,hS,$s,ra=y(()=>{Mp();rr=ee(cf()),tS=Array.isArray,ff=process.platform==="win32",rS=/^(\/?\.\.)+$/;sS=/^[A-Z]:\/$/i,iS=ff?e=>sS.test(e):e=>e==="/";aS={parts:true};lS=/(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g,cS=/(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g,uS=e=>e.replace(lS,"\\$&"),pS=e=>e.replace(cS,"\\$&"),fS=ff?pS:uS;dS=/^(\/?\.\.)+/,hS=/\\(?=[()[\]{}!*+?@|])/g,$s=/\\/g;});function hf(e){return e.config?.db?.driver==="sqlite"?"./sqlite-migrations/*.sql":"./migrations/*.sql"}function Tt(e){return He__default.posix.dirname(hf(e))}async function Ve(e){let t=He__default.join(process.cwd(),"supabase"),r=await Br([hf(e)],{cwd:t,absolute:true}),n=[];for(let s of r){let i=He__default.basename(s),o=SS.exec(i);if(!o)continue;let a=await ce__default.readFile(s,"utf-8");n.push({version:o[1],name:o[2]??null,filename:i,path:s,sql:a});}return n.sort((s,i)=>s.version.localeCompare(i.version))}async function vs(e){return (await Ve(e)).map(r=>r.sql).join(`
|
|
63
|
-
`)}function na(e=new Date){return e.getUTCFullYear().toString().padStart(4,"0")+(e.getUTCMonth()+1).toString().padStart(2,"0")+e.getUTCDate().toString().padStart(2,"0")+e.getUTCHours().toString().padStart(2,"0")+e.getUTCMinutes().toString().padStart(2,"0")+e.getUTCSeconds().toString().padStart(2,"0")}function sa(e,t=na()){let r=e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"");return r.length>0?`${t}_${r}.sql`:`${t}.sql`}async function gf(e,t,r){let n=He__default.join(process.cwd(),"supabase",Tt(e));Re(n);let s=sa(t,r?.ts),i=He__default.join(n,s);return await ce__default.writeFile(i,"",{flag:"wx"}),i}var SS,At=y(()=>{ra();wt();SS=/^(\d{14})(?:_([^.]+))?\.sql$/;});function Hr(e){if("String"in e)return e.String.sval}function Ct(e){return e.map(Hr).filter(t=>t!=null)}function Rt(e){return e==null?[]:e.List!==void 0?e.List.items||[]:Array.isArray(e)?e:[e]}function Ts(e){return QuoteUtils.quoteIdentifier(e)}function nr(e){return Object.keys(e)[0]}function yf(e){if("A_Const"in e){if(e.A_Const.ival)return e.A_Const.ival.ival;if(e.A_Const.fval)return e.A_Const.fval.fval;if(e.A_Const.sval)return e.A_Const.sval.sval;if(e.A_Const.boolval)return e.A_Const.boolval.boolval;if(e.A_Const.isnull)return null}}var kt=y(()=>{});function bf(e){let t=e.toLowerCase().trim();if(t.startsWith("_")||t.endsWith("[]"))return "TEXT";let r=_S[t];if(!r)throw new Pt(`Unsupported PostgreSQL type: "${e}"`);return r}function As(e){let t=e.toLowerCase();return ["serial","serial4","bigserial","serial8","smallserial","serial2"].includes(t)}function Cs(e){let t=e.toLowerCase();return ["varchar","character varying","char","character","bpchar"].includes(t)}function Rs(e){let t=e.toLowerCase();return ["numeric","decimal"].includes(t)}var Pt,B,_S,wf,$S,ks,sr=y(()=>{kt();Pt=class extends Error{},B=class extends Pt{constructor(r,n){super(n??`Unsupported node type: ${nr(r)}`);this.node=r;}},_S={int2:"INTEGER",smallint:"INTEGER",int4:"INTEGER",integer:"INTEGER",int:"INTEGER",int8:"INTEGER",bigint:"INTEGER",serial:"INTEGER",serial4:"INTEGER",bigserial:"INTEGER",serial8:"INTEGER",smallserial:"INTEGER",serial2:"INTEGER",float4:"REAL",real:"REAL",float8:"REAL","double precision":"REAL",numeric:"REAL",decimal:"REAL",text:"TEXT",varchar:"TEXT","character varying":"TEXT",char:"TEXT",character:"TEXT",bpchar:"TEXT",name:"TEXT",bytea:"BLOB",bool:"INTEGER",boolean:"INTEGER",date:"TEXT",time:"TEXT","time without time zone":"TEXT",timetz:"TEXT","time with time zone":"TEXT",timestamp:"TEXT","timestamp without time zone":"TEXT",timestamptz:"TEXT","timestamp with time zone":"TEXT",interval:"TEXT",json:"TEXT",jsonb:"TEXT",uuid:"TEXT",inet:"TEXT"},wf=["<",">","<=",">=","=","<>","!=","+","-","*","/","%","&","|","<<",">>","||","BETWEEN","NOT BETWEEN","IN","NOT IN","LIKE","NOT LIKE","IS NULL","IS NOT NULL","IS TRUE","IS NOT TRUE","IS FALSE","IS NOT FALSE","IS UNKNOWN","IS NOT UNKNOWN","AND","OR","NOT","->>"];$S={CreateEnumStmt:{react:"ignore"},CreateDomainStmt:{react:"warn"},CreateSeqStmt:{react:"error"},AlterSeqStmt:{react:"error"},CreateSchemaStmt:{react:"warn"},CreatePolicyStmt:{react:"ignore"},PartitionElem:{react:"error"},PartitionCmd:{react:"error"},VariableSetStmt:{react:"ignore"},CompositeTypeStmt:{react:"error"},AlterEnumStmt:{react:"error"},AlterObjectSchemaStmt:{react:"error"},AlterOwnerStmt:{react:"error"},AlterTypeStmt:{react:"error"},AlterFunctionStmt:{react:"error"},AlterDefaultPrivilegesStmt:{react:"error"},GrantStmt:{react:"error"},GrantRoleStmt:{react:"error"},CopyStmt:{react:"error"},CreateCastStmt:{react:"error"},AlterOpFamilyStmt:{react:"error"},AlterOperatorStmt:{react:"error"},TruncateStmt:{react:"error"},A_Indirection:{react:"error"},XmlExpr:{react:"error"},XmlSerialize:{react:"error"},RangeTableSample:{react:"error"},GroupingSet:{react:"error"}},ks=new Map(Object.entries($S));});var De,Wr,ia=y(()=>{kt();sr();De=class extends B{constructor(t,r){super(t,`Unsupported expression: ${r}`);}},Wr=class{deparse(t){if("A_Const"in t){let s=t.A_Const;if(s.boolval!==void 0)return s.boolval.boolval?{}:{$always:false}}let r=Object.keys(t)[0],n=this[r];if(!n)throw new De({[r]:t},`Unsupported expression: ${r}`);return n.call(this,t[r])}deparseValue(t){if("A_Const"in t)return this.A_Const(t.A_Const);if("ColumnRef"in t)return this.ColumnRef(t.ColumnRef);if("FuncCall"in t)return this.FuncCall(t.FuncCall);if("SubLink"in t)return this.SubLink(t.SubLink);if("TypeCast"in t)return this.TypeCast(t.TypeCast);if("A_Expr"in t){let n=this.isJwtAccessor(t.A_Expr);return n||this.A_Expr(t.A_Expr)}if("BoolExpr"in t)return this.BoolExpr(t.BoolExpr);let r=Object.keys(t)[0];throw new De({[r]:t},`deparseValue: ${r}`)}A_Expr(t){if(t.kind==="AEXPR_OP"){let r=t.name?.[0],n=r?Hr(r):void 0;if(!n)throw new De({A_Expr:t},"A_Expr missing operator");let s=this.isJwtAccessor(t);if(s)return {[s]:{}};let i=t.lexpr?this.deparseValue(t.lexpr):void 0,o=t.rexpr?this.deparseValue(t.rexpr):void 0,a=this.mapOperator(n);if(!a)throw new De({A_Expr:t},`Unsupported operator: ${n}`);let l=t.rexpr!=null&&"ColumnRef"in t.rexpr;if(typeof i=="string"&&i.startsWith("{{")&&l)return {[o]:{[a]:i}};let c=l&&typeof o=="string"?{$ref:o}:o;return {[i]:{[a]:c}}}if(t.kind==="AEXPR_LIKE"||t.kind==="AEXPR_ILIKE"){let r=t.lexpr?this.deparseValue(t.lexpr):void 0,n=t.rexpr?this.deparseValue(t.rexpr):void 0,i=(t.name?.[0]?Hr(t.name[0]):"~~")==="!~~"?"$notLike":"$like";return {[r]:{[i]:n}}}if(t.kind==="AEXPR_IN"){let r=t.lexpr?this.deparseValue(t.lexpr):void 0,n=t.rexpr&&"List"in t.rexpr&&t.rexpr.List.items?t.rexpr.List.items.map(s=>this.deparseValue(s)):[];return {[r]:{$in:n}}}throw new De({A_Expr:t},`A_Expr kind: ${t.kind}`)}BoolExpr(t){let r=t.args??[];switch(t.boolop){case "AND_EXPR":return {$and:r.map(n=>this.deparse(n))};case "OR_EXPR":return {$or:r.map(n=>this.deparse(n))};case "NOT_EXPR":return {$not:this.deparse(r[0])};default:throw new De({BoolExpr:t},`BoolExpr op: ${t.boolop}`)}}NullTest(t){let r=t.arg?this.deparseValue(t.arg):void 0;return t.nulltesttype==="IS_NULL"?{[r]:{$is:null}}:{[r]:{$isNot:null}}}SubLink(t){if(t.subLinkType==="ANY_SUBLINK"){let r=t.testexpr?this.deparseValue(t.testexpr):void 0,n=t.subselect?this.SelectStmt(t.subselect.SelectStmt):void 0;return {[r]:{$in:n}}}if(t.subLinkType==="EXISTS_SUBLINK")return {$exists:t.subselect?this.SelectStmt(t.subselect.SelectStmt):void 0};if(t.subLinkType==="EXPR_SUBLINK"){let r=t.subselect?t.subselect.SelectStmt:void 0;if(r?.fromClause?.length)return this.SelectStmt(r);if(r?.targetList?.[0]){let n=r.targetList[0],s="ResTarget"in n?n.ResTarget:void 0;if(s?.val){let i=this.deparseValue(s.val);return i}}}throw new De({SubLink:t},`SubLink type: ${t.subLinkType}`)}SelectStmt(t){let{from:r,schema:n,join:s}=this.deparseFromClause(t.fromClause??[]),i=[];for(let f of t.targetList??[]){let h="ResTarget"in f?f.ResTarget:void 0;if(h?.val){let d=this.deparseValue(h.val);Array.isArray(d)?i.push(...d.map(String)):d!=null&&d!==""&&i.push(String(d));}}let o=t.whereClause?this.deparse(t.whereClause):void 0,a=this.deparseSortClause(t.sortClause),l=this.deparseLimit(t.limitCount),c=this.deparseLimit(t.limitOffset),u=this.deparseGroupClause(t.groupClause),p={type:"query",from:r,select:i};return n&&(p.schema=n),Object.keys(s).length>0&&(p.join=s),o&&(p.where=o),a.length>0&&(p.order=a),l!==void 0&&(p.limit=l),c!==void 0&&(p.offset=c),u.length>0&&(p.group=u),p}FuncCall(t){let r=this.isAuthFunc(t.funcname??[]);if(r)return r;throw new De({FuncCall:t},`FuncCall: ${Ct(t.funcname??[]).join(".")}`)}ColumnRef(t){let r=Ct(t.fields??[]);return r.length===1?r[0]:r.join(".")}A_Const(t){if(t.boolval!==void 0)return t.boolval.boolval;if(t.ival!==void 0)return t.ival.ival??0;if(t.fval!==void 0)return parseFloat(t.fval.fval??"0");if(t.sval!==void 0)return t.sval.sval??"";if(t.isnull)return null;throw new De({A_Const:t},"A_Const: unknown variant")}TypeCast(t){if(!t.arg)throw new De({TypeCast:t},"TypeCast: missing arg");return this.deparseValue(t.arg)}BooleanTest(t){let r=t.arg?this.deparseValue(t.arg):void 0;return t.booltesttype==="IS_TRUE"?{[r]:{$eq:true}}:{[r]:{$eq:false}}}deparseFromClause(t){let r={};if(t.length===0)return {from:"",join:r};let n=t[0];if("RangeVar"in n){let s=n.RangeVar;return {from:s.relname??"",schema:s.schemaname,join:r}}if("JoinExpr"in n){let{from:s,schema:i}=this.walkJoinExpr(n.JoinExpr,r);return {from:s,schema:i,join:r}}return {from:"",join:r}}walkJoinExpr(t,r){let n={from:""};if(t.larg)if("RangeVar"in t.larg){let s=t.larg.RangeVar;n={from:s.relname??"",schema:s.schemaname};}else "JoinExpr"in t.larg&&(n=this.walkJoinExpr(t.larg.JoinExpr,r));if(t.rarg&&"RangeVar"in t.rarg){let s=t.rarg.RangeVar,i=s.relname??"",o=s.alias?.aliasname??i,a=t.jointype==="JOIN_LEFT"?"left":"inner",l={from:i,type:a};t.quals&&(l.on=this.deparse(t.quals));let c=o;if(c in r){let u=2;for(;`${c}_${u}`in r;)u++;c=`${c}_${u}`;}r[c]=l;}return n}deparseSortClause(t){if(!t)return [];let r=[];for(let n of t){if(!("SortBy"in n))continue;let s=n.SortBy;if(!s.node)continue;let i=String(this.deparseValue(s.node)),o=s.sortby_dir==="SORTBY_DESC"?"desc":"asc",a={column:i,direction:o};s.sortby_nulls==="SORTBY_NULLS_FIRST"?a.nullsFirst=true:s.sortby_nulls==="SORTBY_NULLS_LAST"&&(a.nullsFirst=false),r.push(a);}return r}deparseLimit(t){if(!t)return;let r=this.deparseValue(t);return typeof r=="number"?r:Number(r)}deparseGroupClause(t){return t?t.map(r=>String(this.deparseValue(r))):[]}isAuthFunc(t){let r=Ct(t);if(r.length===2&&r[0]==="auth"){if(r[1]==="uid")return "{{auth.uid}}";if(r[1]==="jwt")return "{{auth.jwt}}";if(r[1]==="role")return "{{auth.role}}";throw new Error(`Unsupported auth function: "${r.slice(1).join(".")}"`)}return null}isJwtAccessor(t){if(t.kind!=="AEXPR_OP")return null;let r=t.name?.[0]?Hr(t.name[0]):void 0;if(r!=="->"&&r!=="->>")return null;let n=t.rexpr&&"A_Const"in t.rexpr?t.rexpr.A_Const.sval?.sval:void 0;if(n===void 0)return null;if(t.lexpr&&"FuncCall"in t.lexpr)return this.isAuthFunc(t.lexpr.FuncCall.funcname??[])==="{{auth.jwt}}"?`{{auth.jwt.${n}}}`:null;if(t.lexpr&&"A_Expr"in t.lexpr){let s=this.isJwtAccessor(t.lexpr.A_Expr);if(s)return `${s.slice(0,-2)}.${n}}}`}return null}mapOperator(t){switch(t){case "=":return "$eq";case "<>":case "!=":return "$neq";case ">":return "$gt";case ">=":return "$gte";case "<":return "$lt";case "<=":return "$lte";case "~~":return "$like";case "!~~":return "$notLike";default:return}}};});var Gr,oa=y(()=>{Gr=class e{constructor(t){this.data=t;}appliesTo(t){return this.data.command==="ALL"||this.data.command===t}appliesToRole(t){return this.data.roles.length===0||this.data.roles.includes(t)}toJSON(){return this.data}static fromJSON(t){return new e(t)}};});var zr,aa=y(()=>{zr=class extends Error{constructor(r,n,s,i){super(`check constraint "${s}" violated for ${r}.${n}`);this.table=r;this.column=n;this.constraint=s;this.value=i;this.name="CheckConstraintError";}};});var he,et=y(()=>{aa();he=class{context;constructor(t){this.context=t;}get isShimBacked(){return false}checkConstraint(){return null}serialize(t){return t}deserialize(t){return t}validateStorage(t){return {status:"pass",message:null}}validationFail(t,r){return {status:"fail",message:t,action:r}}validationPass(){return {status:"pass",message:null}}isNullish(t){return t==null}toColumnDDL(t){let{includeNullable:r=true}=t??{},n=[],s=this.context.column;n.push(this.quoteIfNeeded(s)),n.push(this.sqliteType),this.context.isPrimaryKey&&n.push("PRIMARY KEY"),this.context.isSerial&&this.context.isPrimaryKey&&n.push("AUTOINCREMENT"),r&&!this.context.nullable&&!this.context.isPrimaryKey&&n.push("NOT NULL"),this.context.isUnique&&!this.context.isPrimaryKey&&n.push("UNIQUE"),this.context.defaultValue!==null&&n.push(`DEFAULT ${this.context.defaultValue}`);let i=this.checkConstraint();return i&&n.push(`CHECK (${i})`),n.join(" ")}checkError(t,r){return new zr(this.context.table,this.context.column,t,r)}quoteIfNeeded(t){return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)?t:`"${t}"`}};});var Nt,Ps=y(()=>{et();Nt=class extends he{get sqliteType(){return "INTEGER"}};});var Vr,la=y(()=>{Ps();Vr=class extends Nt{constructor(t){super({...t,isSerial:true});}};});function vS(e,t){let{precision:r,scale:n}=t,s=10**n,i=10**(r-n);return Math.abs(Math.round(e*s)-e*s)<1e-4&&Math.abs(e)<i}var Ot,Ns=y(()=>{et();Ot=class extends he{numericPrecision;constructor(t,r){super(t),this.numericPrecision=r;}get isShimBacked(){return this.numericPrecision!==void 0}get sqliteType(){return "REAL"}checkConstraint(){if(this.numericPrecision){let{precision:t,scale:r}=this.numericPrecision,n=this.context.column,s=10**r,i=10**(t-r);return `ABS(ROUND(${n} * ${s}) - ${n} * ${s}) < 0.0001 AND ABS(${n}) < ${i}`}return null}validateStorage(t){if(this.isNullish(t))return this.validationPass();if(typeof t!="number"||!Number.isFinite(t))return this.validationFail("Expected finite number.","Patch rows with finite numbers.");if(this.numericPrecision){let{precision:r,scale:n}=this.numericPrecision;if(!vS(t,this.numericPrecision))return this.validationFail(`Does not fit numeric(${r}, ${n}).`,"Patch rows within numeric precision.")}return this.validationPass()}};});var ie,je=y(()=>{et();ie=class extends he{lengthConstraint;constructor(t,r){super(t),this.lengthConstraint=r;}get isShimBacked(){return this.lengthConstraint!==void 0}get sqliteType(){return "TEXT"}checkConstraint(){return this.lengthConstraint!==void 0?`length(${this.context.column}) <= ${this.lengthConstraint}`:null}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"?this.validationFail("Expected text.","Patch rows with text values."):this.lengthConstraint!==void 0&&Array.from(t).length>this.lengthConstraint?this.validationFail(`Exceeds length ${this.lengthConstraint}.`,"Patch rows with shorter text."):this.validationPass()}};});var Kr,ca=y(()=>{et();Kr=class extends he{get sqliteType(){return "BLOB"}};});var Jr,ua=y(()=>{et();Jr=class extends he{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}checkConstraint(){return `${this.context.column} IN (0, 1)`}serialize(t){if(this.isNullish(t))return t;if(t===true||t===1)return 1;if(t===false||t===0)return 0;throw this.checkError("boolean_range",t)}deserialize(t){if(this.isNullish(t)||t===true||t===false)return t;if(typeof t=="number"&&Number.isFinite(t)){if(t===1)return true;if(t===0)return false}return t===1n?true:t===0n?false:t==="1"||t==="true"?true:t==="0"||t==="false"?false:t}validateStorage(t){return this.isNullish(t)?this.validationPass():t===1||t===0?this.validationPass():this.validationFail("Expected 0 or 1.","Patch rows with boolean values.")}};});function Sf(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var Xr,pa=y(()=>{et();Xr=class extends he{get isShimBacked(){return true}get sqliteType(){return "TEXT"}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR json_valid(${t})`}serialize(t){if(this.isNullish(t))return t;try{return JSON.stringify(t)}catch{throw this.checkError("json_valid",t)}}deserialize(t){if(this.isNullish(t))return t;if(typeof t=="string"){let r=Sf(t);return r.ok?r.value:t}return t}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"?this.validationFail("Expected JSON text.","Patch rows with JSON values."):Sf(t).ok?this.validationPass():this.validationFail("Invalid JSON text.","Patch rows with valid JSON.")}};});function TS(e){if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return false;let t=new Date(`${e}T00:00:00.000Z`);return !Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e}var Yr,fa=y(()=>{je();Yr=class extends ie{get isShimBacked(){return true}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR date(${t}) IS NOT NULL`}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!TS(t)?this.validationFail("Invalid date.","Patch rows with YYYY-MM-DD dates."):this.validationPass()}};});function AS(e){let t=e.match(/^(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?([+-](\d{2}):?(\d{2}))?$/);if(!t)return false;let r=Number(t[1]),n=Number(t[2]),s=t[3]===void 0?0:Number(t[3]),i=t[5]===void 0?null:Number(t[5]),o=t[6]===void 0?null:Number(t[6]),a=i===null||o!==null&&i<=15&&o<=59;return r<=24&&n<=59&&s<=59&&(r!==24||n===0&&s===0)&&a}var Qr,ma=y(()=>{je();Qr=class extends ie{get isShimBacked(){return true}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR time(${t}) IS NOT NULL`}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!AS(t)?this.validationFail("Invalid time.","Patch rows with HH:MM[:SS] times."):this.validationPass()}};});function CS(e){let t=e.match(/^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?(?:Z|([+-](\d{2}):?(\d{2})))?$/);if(!t)return false;let r=Number(t[1]),n=Number(t[2]),s=Number(t[3]),i=Number(t[4]),o=Number(t[5]),a=t[6]===void 0?0:Number(t[6]),l=t[8]===void 0?null:Number(t[8]),c=t[9]===void 0?null:Number(t[9]),u=new Date(Date.UTC(r,n-1,s)),p=u.getUTCFullYear()===r&&u.getUTCMonth()===n-1&&u.getUTCDate()===s,f=i<=24&&o<=59&&a<=59&&(i!==24||o===0&&a===0),h=l===null||c!==null&&l<=15&&c<=59;return p&&f&&h}var Zr,da=y(()=>{je();Zr=class extends ie{get isShimBacked(){return true}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR datetime(${t}) IS NOT NULL`}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!CS(t)?this.validationFail("Invalid timestamp.","Patch rows with ISO timestamps."):this.validationPass()}};});var en,ha=y(()=>{je();en=class extends ie{get isShimBacked(){return true}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||t.trim().length===0?this.validationFail("Expected interval text.","Patch rows with interval strings."):/^-?\d+(?:\.\d+)?$/.test(t.trim())?this.validationFail("Ambiguous numeric interval.","Patch rows with explicit interval strings."):this.validationPass()}};});var tn,ga=y(()=>{je();tn=class extends ie{enumValues;constructor(t,r){super(t),this.enumValues=r;}get isShimBacked(){return true}checkConstraint(){let t=this.context.column,r=this.enumValues.map(n=>`'${n.replace(/'/g,"''")}'`).join(", ");return `${t} IN (${r})`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string"||!this.enumValues.includes(t))throw this.checkError("enum_membership",t);return t}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!this.enumValues.includes(t)?this.validationFail("Invalid enum value.","Patch rows with declared enum values."):this.validationPass()}};});function Ef(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var ut,Os=y(()=>{et();ut=class extends he{elementField;constructor(t,r){super(t),this.elementField=r;}get sqliteType(){return "TEXT"}get isShimBacked(){return true}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR (json_valid(${t}) AND json_type(${t}) = 'array')`}serialize(t){if(this.isNullish(t))return t;if(!Array.isArray(t))throw this.checkError("array_type",t);return this.elementField?JSON.stringify(t.map(r=>this.elementField.serialize(r))):JSON.stringify(t)}deserialize(t){if(this.isNullish(t))return t;if(typeof t=="string"){let r=Ef(t);if(r.ok&&Array.isArray(r.value))return this.elementField?r.value.map(n=>this.elementField.deserialize(n)):r.value}return t}validateStorage(t){if(this.isNullish(t))return this.validationPass();if(typeof t!="string")return this.validationFail("Expected JSON array text.","Patch rows with array values.");let r=Ef(t);if(!r.ok)return this.validationFail("Invalid JSON array text.","Patch rows with array values.");if(!Array.isArray(r.value))return this.validationFail("Expected JSON array.","Patch rows with array values.");if(this.elementField)for(let n of r.value){let s=this.elementField.validateStorage(n);if(s.status==="fail")return this.validationFail(`Invalid ${this.elementField.context.pgTypeName} array element.`,s.action??"Patch rows with valid array elements.")}return this.validationPass()}};});function xf(e){return kS.test(e.toLowerCase())}var RS,kS,rn,ya=y(()=>{je();RS="????????-????-????-????-????????????",kS=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;rn=class extends ie{get isShimBacked(){return true}checkConstraint(){let t=this.quoteIfNeeded(this.context.column);return `${t} IS NULL OR ${t} GLOB '${RS}'`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string")throw this.checkError("uuid_format",t);let r=t.toLowerCase();if(!xf(r))throw this.checkError("uuid_format",t);return r}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!xf(t)?this.validationFail("Invalid UUID.","Patch rows with valid UUIDs."):this.validationPass()}};});function PS(e){let t=e.split("/");if(t.length>2)return null;let r=t[0];if(!r)return null;if(t.length===1)return {address:r,prefix:null};let n=t[1];return !n||!/^\d+$/.test(n)?null:{address:r,prefix:Number(n)}}function NS(e){let t=e.split(".");return t.length!==4?false:t.every(r=>{if(!/^\d+$/.test(r))return false;let n=Number(r);return n>=0&&n<=255})}function OS(e){if(!e.includes(":"))return false;try{return new URL(`http://[${e}]/`),!0}catch{return false}}function _f(e){let t=PS(e);return t?NS(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=32:OS(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=128:false:false}var nn,wa=y(()=>{je();nn=class extends ie{get isShimBacked(){return true}checkConstraint(){let t=this.quoteIfNeeded(this.context.column);return `${t} IS NULL OR (length(${t}) BETWEEN 3 AND 49 AND (instr(${t}, '.') > 0 OR instr(${t}, ':') > 0))`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string")throw this.checkError("inet_format",t);let r=t.trim();if(!_f(r))throw this.checkError("inet_format",t);return r}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!_f(t.trim())?this.validationFail("Invalid inet address.","Patch rows with valid inet strings."):this.validationPass()}};});var sn,ba=y(()=>{je();sn=class extends ie{serialize(t){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}deserialize(t){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}toColumnDDL(){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}};});function Lt(e,t){if(t?.isArray){let n=Lt(e,{...t,isArray:false});return new ut(e,n)}if(t?.enumValues)return new tn(e,t.enumValues);let r=e.pgTypeName.toLowerCase().trim();if(r.startsWith("_")||r.endsWith("[]")){let n=r.startsWith("_")?r.slice(1):r.slice(0,-2),s={...e,pgTypeName:n},i=Lt(s);return new ut(e,i)}return IS.has(r)?new Vr(e):LS.has(r)?new Nt(e):MS.has(r)?new Jr(e):US.has(r)?new Xr(e):WS.has(r)?new Yr(e):GS.has(r)?new Qr(e):zS.has(r)?new Zr(e):VS.has(r)?new en(e):FS.has(r)?new Kr(e):DS.has(r)?new Ot(e,t?.numericPrecision):BS.has(r)?new rn(e):qS.has(r)?new ie(e,63):HS.has(r)?new nn(e):jS.has(r)?new ie(e,t?.lengthConstraint):new sn(e)}var LS,IS,DS,jS,FS,MS,US,BS,qS,HS,WS,GS,zS,VS,Sa=y(()=>{Ps();la();Ns();je();ca();ua();pa();fa();ma();da();ha();ga();Os();ya();wa();ba();LS=new Set(["int2","smallint","int4","integer","int","int8","bigint"]),IS=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]),DS=new Set(["float4","real","float8","double precision","numeric","decimal"]),jS=new Set(["text","varchar","character varying","char","character","bpchar"]),FS=new Set(["bytea"]),MS=new Set(["bool","boolean"]),US=new Set(["json","jsonb"]),BS=new Set(["uuid"]),qS=new Set(["name"]),HS=new Set(["inet"]),WS=new Set(["date"]),GS=new Set(["time","timetz","time without time zone","time with time zone"]),zS=new Set(["timestamp","timestamptz","timestamp without time zone","timestamp with time zone"]),VS=new Set(["interval"]);});function Ea(e,t="auto"){let r=e.toLowerCase(),n=Ls[r];if(!n)return null;switch(t){case "translate":{if(!n.sqlite)throw new Error(`No SQLite translation for function "${e}"`);return {sqliteExpr:n.sqlite(),jsFn:null}}case "synthetic":{if(!n.js)throw new Error(`No JS implementation for function "${e}"`);return {sqliteExpr:null,jsFn:n.js}}case "auto":return n.js?{sqliteExpr:null,jsFn:n.js}:n.sqlite?{sqliteExpr:n.sqlite(),jsFn:null}:null}}var $f,Ls,xa=y(()=>{$f="lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))",Ls={gen_random_uuid:{sqlite:()=>$f,js:()=>crypto.randomUUID()},uuid_generate_v4:{sqlite:()=>$f,js:()=>crypto.randomUUID()},now:{sqlite:()=>"datetime('now')",js:()=>new Date().toISOString()},current_timestamp:{sqlite:()=>"datetime('now')",js:()=>new Date().toISOString()},current_date:{sqlite:()=>"date('now')",js:()=>new Date().toISOString().split("T")[0]},current_time:{sqlite:()=>"time('now')",js:()=>new Date().toISOString().split("T")[1].replace("Z","")},random:{sqlite:()=>"random()",js:()=>Math.random()},length:{sqlite:()=>"length",js:null},lower:{sqlite:()=>"lower",js:null},upper:{sqlite:()=>"upper",js:null},substr:{sqlite:()=>"substr",js:null},substring:{sqlite:()=>"substr",js:null},trim:{sqlite:()=>"trim",js:null},ltrim:{sqlite:()=>"ltrim",js:null},rtrim:{sqlite:()=>"rtrim",js:null},replace:{sqlite:()=>"replace",js:null},coalesce:{sqlite:()=>"coalesce",js:null},nullif:{sqlite:()=>"nullif",js:null},count:{sqlite:()=>"count",js:null},sum:{sqlite:()=>"sum",js:null},avg:{sqlite:()=>"avg",js:null},min:{sqlite:()=>"min",js:null},max:{sqlite:()=>"max",js:null},localtime:{sqlite:()=>"time('now', 'localtime')",js:null},localtimestamp:{sqlite:()=>"datetime('now', 'localtime')",js:null}};});var on,vf=y(()=>{on=class{table;schema;fields;constructor(t,r="public",n=new Map){this.table=t,this.schema=r,this.fields=n;}get(t){return this.fields.get(t)}has(t){return this.fields.has(t)}set(t,r){this.fields.set(t,r);}columns(){return Array.from(this.fields.keys())}all(){return Array.from(this.fields.values())}serializeRow(t){let r={};for(let[n,s]of Object.entries(t)){let i=this.fields.get(n);r[n]=i?i.serialize(s):s;}return r}deserializeRow(t){let r={};for(let[n,s]of Object.entries(t)){let i=this.fields.get(n);r[n]=i?i.deserialize(s):s;}return r}applyDefaults(t){let r={...t};for(let[n,s]of this.fields)!(n in r)&&s.context.defaultFn&&(r[n]=s.context.defaultFn());return r}};});var Tf=y(()=>{et();aa();Ps();la();Ns();je();ca();ua();pa();fa();ma();da();ha();ga();Os();ya();wa();ba();Sa();xa();vf();});var ka={};fe(ka,{_resetWarnedMissingToClauseForTests:()=>KS,collectComments:()=>Ra,collectEnums:()=>$a,collectPolicies:()=>Ta,collectSchema:()=>Aa,collectTableConstraints:()=>Ca,collectVariables:()=>va});function KS(){_a.clear();}function $a(e){let t=new Map;for(let r of e.stmts??[]){if(!r.stmt||!("CreateEnumStmt"in r.stmt))continue;let n=r.stmt.CreateEnumStmt,s=Ct(n.typeName??[]).join(".");if(!s||!n.vals)continue;let i=Ct(n.vals);t.set(s.toLowerCase(),i);}return t}function va(e){let t=new Map;for(let r of e.stmts??[]){if(!r.stmt||!("VariableSetStmt"in r.stmt))continue;let n=r.stmt.VariableSetStmt,s=n.name,i=yf(n.args?.[0]??{});t.set(s,{value:i,local:n.is_local});}return t}function Ta(e){let t=new Wr,r=new Set,n=[];for(let s of e.stmts??[])if(s.stmt){if("CreatePolicyStmt"in s.stmt){let i=s.stmt.CreatePolicyStmt,o=i.table?.relname??"",a=i.table?.schemaname,l={select:"SELECT",insert:"INSERT",update:"UPDATE",delete:"DELETE"},c=i.cmd_name?l[i.cmd_name]??"ALL":"ALL",u=i.permissive===true,p=[],f=false;for(let b of i.roles??[])if("RoleSpec"in b){let g=b.RoleSpec;g.roletype==="ROLESPEC_PUBLIC"?g.location===-1&&(f=true):g.roletype==="ROLESPEC_CSTRING"&&g.rolename&&p.push(g.rolename);}if(f){let b=a?`${a}.${o}`:o,g=i.policy_name??"",S=`${b}::${g}`;_a.has(S)||(_a.add(S),console.warn(`[supalite] policy "${g}" on "${b}" has no TO clause \u2014 applies to all roles (PUBLIC). For clarity, prefer an explicit \`TO <role>\` clause (e.g. \`TO authenticated\`).`));}let h=i.qual?t.deparse(i.qual):void 0,d=i.with_check?t.deparse(i.with_check):void 0,m=new Gr({name:i.policy_name??"",table:o,schema:a,command:c,permissive:u,roles:p,using:h,withCheck:d});n.push(m);}if("AlterTableStmt"in s.stmt){let i=s.stmt.AlterTableStmt;if((i.cmds??[]).some(l=>"AlterTableCmd"in l&&(l.AlterTableCmd.subtype==="AT_EnableRowSecurity"||l.AlterTableCmd.subtype==="AT_ForceRowSecurity"))){let l=i.relation?.relname??"";r.add(l);}}}return {policies:n,tables:r}}function Aa(e,t){let r=new Map;for(let n of e.stmts??[]){if(!n.stmt||!("CreateStmt"in n.stmt))continue;let s=n.stmt.CreateStmt,i=s.relation?.relname??"",o=s.relation?.schemaname??"public";if(!i)continue;let a=new on(i,o);for(let l of s.tableElts??[]){if(!("ColumnDef"in l))continue;let c=l.ColumnDef,u=c.colname;if(!u)continue;let p=c.typeName?.names?.map(T=>T.String?.sval||T.String?.str).filter(Boolean),f=p&&(p.length===2&&p[0]==="pg_catalog"?p[1]:p[0]);if(!f)continue;let h=!!c.typeName?.arrayBounds?.length,d=Array.isArray(c.typeName?.typmods)?c.typeName.typmods:[],m=T=>d[T]?.A_Const?.ival?.ival??d[T]?.A_Const?.val?.ival?.ival,b={isArray:h};if(Cs(f)&&d.length>0){let T=m(0);typeof T=="number"&&T>0&&(b.lengthConstraint=T);}if(Rs(f)&&d.length>=2){let T=m(0),q=m(1);typeof T=="number"&&typeof q=="number"&&T>0&&q>=0&&(b.numericPrecision={precision:T,scale:q});}let g=t.get(f.toLowerCase());g&&(b.enumValues=g);let S=Array.isArray(c.constraints)?c.constraints:[],A=S.some(T=>T.Constraint?.contype==="CONSTR_PRIMARY"),$=As(f)||S.some(T=>T.Constraint?.contype==="CONSTR_IDENTITY"),P=S.some(T=>T.Constraint?.contype==="CONSTR_NOTNULL"),N=S.find(T=>T.Constraint?.contype==="CONSTR_UNIQUE"),v=S.find(T=>T.Constraint?.contype==="CONSTR_GENERATED"),_=S.find(T=>T.Constraint?.contype==="CONSTR_FOREIGN"),L=S.find(T=>T.Constraint?.contype==="CONSTR_CHECK"),w;if(_){let T=_.Constraint,q=T.pktable?.relname,E=T.pktable?.schemaname,x=T.pk_attrs?.[0]?.String?.sval;q&&x&&(w={refSchema:E,refTable:q,refColumn:x,constraintName:T.conname||void 0});}let I={schema:o,table:i,column:u,pgTypeName:f,nullable:!P&&!A,defaultValue:null,defaultFn:null,isPrimaryKey:A,isUnique:!!N,isSerial:$,isGenerated:!!v,fkRef:w,hasCheck:!!L,checkConstraintName:L?.Constraint?.conname||void 0,uniqueConstraintName:N?.Constraint?.conname||void 0};a.set(u,Lt(I,b));}r.set(`${o}.${i}`,a);}return r}function Ca(e){let t=[];for(let r of e.stmts??[]){if(!r.stmt||!("CreateStmt"in r.stmt))continue;let n=r.stmt.CreateStmt,s=n.relation?.relname??"",i=n.relation?.schemaname??"public";if(s)for(let o of n.tableElts??[]){if("ColumnDef"in o)continue;let a=o;if(!a.Constraint)continue;let l=a.Constraint,c=l.contype;if(c==="CONSTR_UNIQUE"){let u=(l.keys??[]).map(p=>p.String?.sval??p.String?.str).filter(Boolean);if(u.length===0)continue;t.push({schema:i,table:s,kind:"unique",name:l.conname||void 0,columns:u});}else if(c==="CONSTR_CHECK")t.push({schema:i,table:s,kind:"check",name:l.conname||void 0,columns:[]});else if(c==="CONSTR_FOREIGN"){let u=(l.fk_attrs??[]).map(h=>h.String?.sval??h.String?.str).filter(Boolean),p=(l.pk_attrs??[]).map(h=>h.String?.sval??h.String?.str).filter(Boolean),f=l.pktable?.relname;if(!f)continue;t.push({schema:i,table:s,kind:"foreign_key",name:l.conname||void 0,columns:u,refSchema:l.pktable?.schemaname,refTable:f,refColumns:p});}}}return t}function Ra(e){let t=[];for(let r of e.stmts??[]){if(!r.stmt||!("CommentStmt"in r.stmt))continue;let n=r.stmt.CommentStmt,s=n.comment??"";if(!s)continue;let i=n.objtype,o=(n.object?.List?.items??n.object?.items??[]).map(a=>a.String?.sval??a.String?.str).filter(Boolean);if(o.length!==0){if(i==="OBJECT_TABLE"||i==="OBJECT_VIEW"){let[a,l]=o.length>=2?o:["public",o[0]];t.push({schema:a,table:l,text:s});}else if(i==="OBJECT_COLUMN"){let a="public",l,c;o.length>=3?[a,l,c]=o:[l,c]=o,t.push({schema:a,table:l,column:c,text:s});}}}return t}var _a,Pa=y(()=>{ia();kt();oa();Tf();sr();_a=new Set;});async function ln(e,t){let r=await e.connection.introspect(),n=Na(r);await Nf(e,{...t,dbHasTables:r.tables.length>0,dbFingerprint:n}),r.tables.length===0&&await Oa(e);let s=await e.connection.introspect();Lf(s,e);}async function YS(e){let t=await Br(e.config.db?.seed?.sql_paths??["./seed.sql"],{cwd:He__default.join(process.cwd(),"supabase"),absolute:true});return (await Promise.all(t.map(n=>ce__default.readFile(n,"utf-8")))).flatMap(n=>splitSqlStatements(n))}async function cn(e,t){let r=await YS(e);if(r.length===0)return 0;console.log(F.default.dim("Seeding database..."));try{return await e.connection.transaction(r),r.length}catch(n){let s=t?.recoveryHint??"Fix `supabase/seed.sql`, then run `bun run dev --recreate` to reset and reseed.";throw new Error(`Seed failed and was rolled back: ${String(n.message??n)}
|
|
63
|
+
`)}function na(e=new Date){return e.getUTCFullYear().toString().padStart(4,"0")+(e.getUTCMonth()+1).toString().padStart(2,"0")+e.getUTCDate().toString().padStart(2,"0")+e.getUTCHours().toString().padStart(2,"0")+e.getUTCMinutes().toString().padStart(2,"0")+e.getUTCSeconds().toString().padStart(2,"0")}function sa(e,t=na()){let r=e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"");return r.length>0?`${t}_${r}.sql`:`${t}.sql`}async function gf(e,t,r){let n=He__default.join(process.cwd(),"supabase",Tt(e));Re(n);let s=sa(t,r?.ts),i=He__default.join(n,s);return await ce__default.writeFile(i,"",{flag:"wx"}),i}var SS,At=y(()=>{ra();wt();SS=/^(\d{14})(?:_([^.]+))?\.sql$/;});function Hr(e){if("String"in e)return e.String.sval}function Ct(e){return e.map(Hr).filter(t=>t!=null)}function Rt(e){return e==null?[]:e.List!==void 0?e.List.items||[]:Array.isArray(e)?e:[e]}function Ts(e){return QuoteUtils.quoteIdentifier(e)}function nr(e){return Object.keys(e)[0]}function yf(e){if("A_Const"in e){if(e.A_Const.ival)return e.A_Const.ival.ival;if(e.A_Const.fval)return e.A_Const.fval.fval;if(e.A_Const.sval)return e.A_Const.sval.sval;if(e.A_Const.boolval)return e.A_Const.boolval.boolval;if(e.A_Const.isnull)return null}}var kt=y(()=>{});function bf(e){let t=e.toLowerCase().trim();if(t.startsWith("_")||t.endsWith("[]"))return "TEXT";let r=_S[t];if(!r)throw new Pt(`Unsupported PostgreSQL type: "${e}"`);return r}function As(e){let t=e.toLowerCase();return ["serial","serial4","bigserial","serial8","smallserial","serial2"].includes(t)}function Cs(e){let t=e.toLowerCase();return ["varchar","character varying","char","character","bpchar"].includes(t)}function Rs(e){let t=e.toLowerCase();return ["numeric","decimal"].includes(t)}var Pt,B,_S,wf,$S,ks,sr=y(()=>{kt();Pt=class extends Error{},B=class extends Pt{constructor(r,n){super(n??`Unsupported node type: ${nr(r)}`);this.node=r;}},_S={int2:"INTEGER",smallint:"INTEGER",int4:"INTEGER",integer:"INTEGER",int:"INTEGER",int8:"INTEGER",bigint:"INTEGER",serial:"INTEGER",serial4:"INTEGER",bigserial:"INTEGER",serial8:"INTEGER",smallserial:"INTEGER",serial2:"INTEGER",float4:"REAL",real:"REAL",float8:"REAL","double precision":"REAL",numeric:"REAL",decimal:"REAL",text:"TEXT",varchar:"TEXT","character varying":"TEXT",char:"TEXT",character:"TEXT",bpchar:"TEXT",name:"TEXT",bytea:"BLOB",bool:"INTEGER",boolean:"INTEGER",date:"TEXT",time:"TEXT","time without time zone":"TEXT",timetz:"TEXT","time with time zone":"TEXT",timestamp:"TEXT","timestamp without time zone":"TEXT",timestamptz:"TEXT","timestamp with time zone":"TEXT",interval:"TEXT",json:"TEXT",jsonb:"TEXT",uuid:"TEXT",inet:"TEXT"},wf=["<",">","<=",">=","=","<>","!=","+","-","*","/","%","&","|","<<",">>","||","BETWEEN","NOT BETWEEN","IN","NOT IN","LIKE","NOT LIKE","IS NULL","IS NOT NULL","IS TRUE","IS NOT TRUE","IS FALSE","IS NOT FALSE","IS UNKNOWN","IS NOT UNKNOWN","AND","OR","NOT","->>"];$S={CreateEnumStmt:{react:"ignore"},CreateDomainStmt:{react:"warn"},CreateSeqStmt:{react:"error"},AlterSeqStmt:{react:"error"},CreateSchemaStmt:{react:"warn"},CreatePolicyStmt:{react:"ignore"},PartitionElem:{react:"error"},PartitionCmd:{react:"error"},VariableSetStmt:{react:"ignore"},CompositeTypeStmt:{react:"error"},AlterEnumStmt:{react:"error"},AlterObjectSchemaStmt:{react:"error"},AlterOwnerStmt:{react:"error"},AlterTypeStmt:{react:"error"},AlterFunctionStmt:{react:"error"},AlterDefaultPrivilegesStmt:{react:"error"},GrantStmt:{react:"error"},GrantRoleStmt:{react:"error"},CopyStmt:{react:"error"},CreateCastStmt:{react:"error"},AlterOpFamilyStmt:{react:"error"},AlterOperatorStmt:{react:"error"},TruncateStmt:{react:"error"},A_Indirection:{react:"error"},XmlExpr:{react:"error"},XmlSerialize:{react:"error"},RangeTableSample:{react:"error"},GroupingSet:{react:"error"}},ks=new Map(Object.entries($S));});var De,Wr,ia=y(()=>{kt();sr();De=class extends B{constructor(t,r){super(t,`Unsupported expression: ${r}`);}},Wr=class{deparse(t){if("A_Const"in t){let s=t.A_Const;if(s.boolval!==void 0)return s.boolval.boolval?{}:{$always:false}}let r=Object.keys(t)[0],n=this[r];if(!n)throw new De({[r]:t},`Unsupported expression: ${r}`);return n.call(this,t[r])}deparseValue(t){if("A_Const"in t)return this.A_Const(t.A_Const);if("ColumnRef"in t)return this.ColumnRef(t.ColumnRef);if("FuncCall"in t)return this.FuncCall(t.FuncCall);if("SubLink"in t)return this.SubLink(t.SubLink);if("TypeCast"in t)return this.TypeCast(t.TypeCast);if("A_Expr"in t){let n=this.isJwtAccessor(t.A_Expr);return n||this.A_Expr(t.A_Expr)}if("BoolExpr"in t)return this.BoolExpr(t.BoolExpr);let r=Object.keys(t)[0];throw new De({[r]:t},`deparseValue: ${r}`)}A_Expr(t){if(t.kind==="AEXPR_OP"){let r=t.name?.[0],n=r?Hr(r):void 0;if(!n)throw new De({A_Expr:t},"A_Expr missing operator");let s=this.isJwtAccessor(t);if(s)return {[s]:{}};let i=t.lexpr?this.deparseValue(t.lexpr):void 0,o=t.rexpr?this.deparseValue(t.rexpr):void 0,a=this.mapOperator(n);if(!a)throw new De({A_Expr:t},`Unsupported operator: ${n}`);let l=t.rexpr!=null&&"ColumnRef"in t.rexpr;if(typeof i=="string"&&i.startsWith("{{")&&l)return {[o]:{[a]:i}};let c=l&&typeof o=="string"?{$ref:o}:o;return {[i]:{[a]:c}}}if(t.kind==="AEXPR_LIKE"||t.kind==="AEXPR_ILIKE"){let r=t.lexpr?this.deparseValue(t.lexpr):void 0,n=t.rexpr?this.deparseValue(t.rexpr):void 0,i=(t.name?.[0]?Hr(t.name[0]):"~~")==="!~~"?"$notLike":"$like";return {[r]:{[i]:n}}}if(t.kind==="AEXPR_IN"){let r=t.lexpr?this.deparseValue(t.lexpr):void 0,n=t.rexpr&&"List"in t.rexpr&&t.rexpr.List.items?t.rexpr.List.items.map(s=>this.deparseValue(s)):[];return {[r]:{$in:n}}}throw new De({A_Expr:t},`A_Expr kind: ${t.kind}`)}BoolExpr(t){let r=t.args??[];switch(t.boolop){case "AND_EXPR":return {$and:r.map(n=>this.deparse(n))};case "OR_EXPR":return {$or:r.map(n=>this.deparse(n))};case "NOT_EXPR":return {$not:this.deparse(r[0])};default:throw new De({BoolExpr:t},`BoolExpr op: ${t.boolop}`)}}NullTest(t){let r=t.arg?this.deparseValue(t.arg):void 0;return t.nulltesttype==="IS_NULL"?{[r]:{$is:null}}:{[r]:{$isNot:null}}}SubLink(t){if(t.subLinkType==="ANY_SUBLINK"){let r=t.testexpr?this.deparseValue(t.testexpr):void 0,n=t.subselect?this.SelectStmt(t.subselect.SelectStmt):void 0;return {[r]:{$in:n}}}if(t.subLinkType==="EXISTS_SUBLINK")return {$exists:t.subselect?this.SelectStmt(t.subselect.SelectStmt):void 0};if(t.subLinkType==="EXPR_SUBLINK"){let r=t.subselect?t.subselect.SelectStmt:void 0;if(r?.fromClause?.length)return this.SelectStmt(r);if(r?.targetList?.[0]){let n=r.targetList[0],s="ResTarget"in n?n.ResTarget:void 0;if(s?.val){let i=this.deparseValue(s.val);return i}}}throw new De({SubLink:t},`SubLink type: ${t.subLinkType}`)}SelectStmt(t){let{from:r,schema:n,join:s}=this.deparseFromClause(t.fromClause??[]),i=[];for(let f of t.targetList??[]){let h="ResTarget"in f?f.ResTarget:void 0;if(h?.val){let d=this.deparseValue(h.val);Array.isArray(d)?i.push(...d.map(String)):d!=null&&d!==""&&i.push(String(d));}}let o=t.whereClause?this.deparse(t.whereClause):void 0,a=this.deparseSortClause(t.sortClause),l=this.deparseLimit(t.limitCount),c=this.deparseLimit(t.limitOffset),u=this.deparseGroupClause(t.groupClause),p={type:"query",from:r,select:i};return n&&(p.schema=n),Object.keys(s).length>0&&(p.join=s),o&&(p.where=o),a.length>0&&(p.order=a),l!==void 0&&(p.limit=l),c!==void 0&&(p.offset=c),u.length>0&&(p.group=u),p}FuncCall(t){let r=this.isAuthFunc(t.funcname??[]);if(r)return r;throw new De({FuncCall:t},`FuncCall: ${Ct(t.funcname??[]).join(".")}`)}ColumnRef(t){let r=Ct(t.fields??[]);return r.length===1?r[0]:r.join(".")}A_Const(t){if(t.boolval!==void 0)return t.boolval.boolval;if(t.ival!==void 0)return t.ival.ival??0;if(t.fval!==void 0)return parseFloat(t.fval.fval??"0");if(t.sval!==void 0)return t.sval.sval??"";if(t.isnull)return null;throw new De({A_Const:t},"A_Const: unknown variant")}TypeCast(t){if(!t.arg)throw new De({TypeCast:t},"TypeCast: missing arg");return this.deparseValue(t.arg)}BooleanTest(t){let r=t.arg?this.deparseValue(t.arg):void 0;return t.booltesttype==="IS_TRUE"?{[r]:{$eq:true}}:{[r]:{$eq:false}}}deparseFromClause(t){let r={};if(t.length===0)return {from:"",join:r};let n=t[0];if("RangeVar"in n){let s=n.RangeVar;return {from:s.relname??"",schema:s.schemaname,join:r}}if("JoinExpr"in n){let{from:s,schema:i}=this.walkJoinExpr(n.JoinExpr,r);return {from:s,schema:i,join:r}}return {from:"",join:r}}walkJoinExpr(t,r){let n={from:""};if(t.larg)if("RangeVar"in t.larg){let s=t.larg.RangeVar;n={from:s.relname??"",schema:s.schemaname};}else "JoinExpr"in t.larg&&(n=this.walkJoinExpr(t.larg.JoinExpr,r));if(t.rarg&&"RangeVar"in t.rarg){let s=t.rarg.RangeVar,i=s.relname??"",o=s.alias?.aliasname??i,a=t.jointype==="JOIN_LEFT"?"left":"inner",l={from:i,type:a};t.quals&&(l.on=this.deparse(t.quals));let c=o;if(c in r){let u=2;for(;`${c}_${u}`in r;)u++;c=`${c}_${u}`;}r[c]=l;}return n}deparseSortClause(t){if(!t)return [];let r=[];for(let n of t){if(!("SortBy"in n))continue;let s=n.SortBy;if(!s.node)continue;let i=String(this.deparseValue(s.node)),o=s.sortby_dir==="SORTBY_DESC"?"desc":"asc",a={column:i,direction:o};s.sortby_nulls==="SORTBY_NULLS_FIRST"?a.nullsFirst=true:s.sortby_nulls==="SORTBY_NULLS_LAST"&&(a.nullsFirst=false),r.push(a);}return r}deparseLimit(t){if(!t)return;let r=this.deparseValue(t);return typeof r=="number"?r:Number(r)}deparseGroupClause(t){return t?t.map(r=>String(this.deparseValue(r))):[]}isAuthFunc(t){let r=Ct(t);if(r.length===2&&r[0]==="auth"){if(r[1]==="uid")return "{{auth.uid}}";if(r[1]==="jwt")return "{{auth.jwt}}";if(r[1]==="role")return "{{auth.role}}";throw new Error(`Unsupported auth function: "${r.slice(1).join(".")}"`)}return null}isJwtAccessor(t){if(t.kind!=="AEXPR_OP")return null;let r=t.name?.[0]?Hr(t.name[0]):void 0;if(r!=="->"&&r!=="->>")return null;let n=t.rexpr&&"A_Const"in t.rexpr?t.rexpr.A_Const.sval?.sval:void 0;if(n===void 0)return null;if(t.lexpr&&"FuncCall"in t.lexpr)return this.isAuthFunc(t.lexpr.FuncCall.funcname??[])==="{{auth.jwt}}"?`{{auth.jwt.${n}}}`:null;if(t.lexpr&&"A_Expr"in t.lexpr){let s=this.isJwtAccessor(t.lexpr.A_Expr);if(s)return `${s.slice(0,-2)}.${n}}}`}return null}mapOperator(t){switch(t){case "=":return "$eq";case "<>":case "!=":return "$neq";case ">":return "$gt";case ">=":return "$gte";case "<":return "$lt";case "<=":return "$lte";case "~~":return "$like";case "!~~":return "$notLike";default:return}}};});var Gr,oa=y(()=>{Gr=class e{constructor(t){this.data=t;}appliesTo(t){return this.data.command==="ALL"||this.data.command===t}appliesToRole(t){return this.data.roles.length===0||this.data.roles.includes(t)}toJSON(){return this.data}static fromJSON(t){return new e(t)}};});var zr,aa=y(()=>{zr=class extends Error{constructor(r,n,s,i){super(`check constraint "${s}" violated for ${r}.${n}`);this.table=r;this.column=n;this.constraint=s;this.value=i;this.name="CheckConstraintError";}};});var he,et=y(()=>{aa();he=class{context;constructor(t){this.context=t;}get isShimBacked(){return false}checkConstraint(){return null}serialize(t){return t}deserialize(t){return t}validateStorage(t){return {status:"pass",message:null}}validationFail(t,r){return {status:"fail",message:t,action:r}}validationPass(){return {status:"pass",message:null}}isNullish(t){return t==null}toColumnDDL(t){let{includeNullable:r=true}=t??{},n=[],s=this.context.column;n.push(this.quoteIfNeeded(s)),n.push(this.sqliteType),this.context.isPrimaryKey&&n.push("PRIMARY KEY"),this.context.isSerial&&this.context.isPrimaryKey&&n.push("AUTOINCREMENT"),r&&!this.context.nullable&&!this.context.isPrimaryKey&&n.push("NOT NULL"),this.context.isUnique&&!this.context.isPrimaryKey&&n.push("UNIQUE"),this.context.defaultValue!==null&&n.push(`DEFAULT ${this.context.defaultValue}`);let i=this.checkConstraint();return i&&n.push(`CHECK (${i})`),n.join(" ")}checkError(t,r){return new zr(this.context.table,this.context.column,t,r)}quoteIfNeeded(t){return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)?t:`"${t}"`}};});var Nt,Ps=y(()=>{et();Nt=class extends he{get sqliteType(){return "INTEGER"}};});var Vr,la=y(()=>{Ps();Vr=class extends Nt{constructor(t){super({...t,isSerial:true});}};});function vS(e,t){let{precision:r,scale:n}=t,s=10**n,i=10**(r-n);return Math.abs(Math.round(e*s)-e*s)<1e-4&&Math.abs(e)<i}var Ot,Ns=y(()=>{et();Ot=class extends he{numericPrecision;constructor(t,r){super(t),this.numericPrecision=r;}get isShimBacked(){return this.numericPrecision!==void 0}get sqliteType(){return "REAL"}checkConstraint(){if(this.numericPrecision){let{precision:t,scale:r}=this.numericPrecision,n=this.context.column,s=10**r,i=10**(t-r);return `ABS(ROUND(${n} * ${s}) - ${n} * ${s}) < 0.0001 AND ABS(${n}) < ${i}`}return null}validateStorage(t){if(this.isNullish(t))return this.validationPass();if(typeof t!="number"||!Number.isFinite(t))return this.validationFail("Expected finite number.","Patch rows with finite numbers.");if(this.numericPrecision){let{precision:r,scale:n}=this.numericPrecision;if(!vS(t,this.numericPrecision))return this.validationFail(`Does not fit numeric(${r}, ${n}).`,"Patch rows within numeric precision.")}return this.validationPass()}};});var ie,je=y(()=>{et();ie=class extends he{lengthConstraint;constructor(t,r){super(t),this.lengthConstraint=r;}get isShimBacked(){return this.lengthConstraint!==void 0}get sqliteType(){return "TEXT"}checkConstraint(){return this.lengthConstraint!==void 0?`length(${this.context.column}) <= ${this.lengthConstraint}`:null}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"?this.validationFail("Expected text.","Patch rows with text values."):this.lengthConstraint!==void 0&&Array.from(t).length>this.lengthConstraint?this.validationFail(`Exceeds length ${this.lengthConstraint}.`,"Patch rows with shorter text."):this.validationPass()}};});var Kr,ca=y(()=>{et();Kr=class extends he{get sqliteType(){return "BLOB"}};});var Jr,ua=y(()=>{et();Jr=class extends he{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}checkConstraint(){return `${this.context.column} IN (0, 1)`}serialize(t){if(this.isNullish(t))return t;if(t===true||t===1)return 1;if(t===false||t===0)return 0;throw this.checkError("boolean_range",t)}deserialize(t){if(this.isNullish(t)||t===true||t===false)return t;if(typeof t=="number"&&Number.isFinite(t)){if(t===1)return true;if(t===0)return false}return t===1n?true:t===0n?false:t==="1"||t==="true"?true:t==="0"||t==="false"?false:t}validateStorage(t){return this.isNullish(t)?this.validationPass():t===1||t===0?this.validationPass():this.validationFail("Expected 0 or 1.","Patch rows with boolean values.")}};});function Sf(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var Xr,pa=y(()=>{et();Xr=class extends he{get isShimBacked(){return true}get sqliteType(){return "TEXT"}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR json_valid(${t})`}serialize(t){if(this.isNullish(t))return t;try{return JSON.stringify(t)}catch{throw this.checkError("json_valid",t)}}deserialize(t){if(this.isNullish(t))return t;if(typeof t=="string"){let r=Sf(t);return r.ok?r.value:t}return t}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"?this.validationFail("Expected JSON text.","Patch rows with JSON values."):Sf(t).ok?this.validationPass():this.validationFail("Invalid JSON text.","Patch rows with valid JSON.")}};});function TS(e){if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return false;let t=new Date(`${e}T00:00:00.000Z`);return !Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e}var Yr,fa=y(()=>{je();Yr=class extends ie{get isShimBacked(){return true}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR date(${t}) IS NOT NULL`}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!TS(t)?this.validationFail("Invalid date.","Patch rows with YYYY-MM-DD dates."):this.validationPass()}};});function AS(e){let t=e.match(/^(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?([+-](\d{2}):?(\d{2}))?$/);if(!t)return false;let r=Number(t[1]),n=Number(t[2]),s=t[3]===void 0?0:Number(t[3]),i=t[5]===void 0?null:Number(t[5]),o=t[6]===void 0?null:Number(t[6]),a=i===null||o!==null&&i<=15&&o<=59;return r<=24&&n<=59&&s<=59&&(r!==24||n===0&&s===0)&&a}var Qr,ma=y(()=>{je();Qr=class extends ie{get isShimBacked(){return true}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR time(${t}) IS NOT NULL`}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!AS(t)?this.validationFail("Invalid time.","Patch rows with HH:MM[:SS] times."):this.validationPass()}};});function CS(e){let t=e.match(/^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?(?:Z|([+-](\d{2}):?(\d{2})))?$/);if(!t)return false;let r=Number(t[1]),n=Number(t[2]),s=Number(t[3]),i=Number(t[4]),o=Number(t[5]),a=t[6]===void 0?0:Number(t[6]),l=t[8]===void 0?null:Number(t[8]),c=t[9]===void 0?null:Number(t[9]),u=new Date(Date.UTC(r,n-1,s)),p=u.getUTCFullYear()===r&&u.getUTCMonth()===n-1&&u.getUTCDate()===s,f=i<=24&&o<=59&&a<=59&&(i!==24||o===0&&a===0),h=l===null||c!==null&&l<=15&&c<=59;return p&&f&&h}var Zr,da=y(()=>{je();Zr=class extends ie{get isShimBacked(){return true}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR datetime(${t}) IS NOT NULL`}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!CS(t)?this.validationFail("Invalid timestamp.","Patch rows with ISO timestamps."):this.validationPass()}};});var en,ha=y(()=>{je();en=class extends ie{get isShimBacked(){return true}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||t.trim().length===0?this.validationFail("Expected interval text.","Patch rows with interval strings."):/^-?\d+(?:\.\d+)?$/.test(t.trim())?this.validationFail("Ambiguous numeric interval.","Patch rows with explicit interval strings."):this.validationPass()}};});var tn,ga=y(()=>{je();tn=class extends ie{enumValues;constructor(t,r){super(t),this.enumValues=r;}get isShimBacked(){return true}checkConstraint(){let t=this.context.column,r=this.enumValues.map(n=>`'${n.replace(/'/g,"''")}'`).join(", ");return `${t} IN (${r})`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string"||!this.enumValues.includes(t))throw this.checkError("enum_membership",t);return t}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!this.enumValues.includes(t)?this.validationFail("Invalid enum value.","Patch rows with declared enum values."):this.validationPass()}};});function Ef(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var ut,Os=y(()=>{et();ut=class extends he{elementField;constructor(t,r){super(t),this.elementField=r;}get sqliteType(){return "TEXT"}get isShimBacked(){return true}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR (json_valid(${t}) AND json_type(${t}) = 'array')`}serialize(t){if(this.isNullish(t))return t;if(!Array.isArray(t))throw this.checkError("array_type",t);return this.elementField?JSON.stringify(t.map(r=>this.elementField.serialize(r))):JSON.stringify(t)}deserialize(t){if(this.isNullish(t))return t;if(typeof t=="string"){let r=Ef(t);if(r.ok&&Array.isArray(r.value))return this.elementField?r.value.map(n=>this.elementField.deserialize(n)):r.value}return t}validateStorage(t){if(this.isNullish(t))return this.validationPass();if(typeof t!="string")return this.validationFail("Expected JSON array text.","Patch rows with array values.");let r=Ef(t);if(!r.ok)return this.validationFail("Invalid JSON array text.","Patch rows with array values.");if(!Array.isArray(r.value))return this.validationFail("Expected JSON array.","Patch rows with array values.");if(this.elementField)for(let n of r.value){let s=this.elementField.validateStorage(n);if(s.status==="fail")return this.validationFail(`Invalid ${this.elementField.context.pgTypeName} array element.`,s.action??"Patch rows with valid array elements.")}return this.validationPass()}};});function xf(e){return kS.test(e.toLowerCase())}var RS,kS,rn,ya=y(()=>{je();RS="????????-????-????-????-????????????",kS=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;rn=class extends ie{get isShimBacked(){return true}checkConstraint(){let t=this.quoteIfNeeded(this.context.column);return `${t} IS NULL OR ${t} GLOB '${RS}'`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string")throw this.checkError("uuid_format",t);let r=t.toLowerCase();if(!xf(r))throw this.checkError("uuid_format",t);return r}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!xf(t)?this.validationFail("Invalid UUID.","Patch rows with valid UUIDs."):this.validationPass()}};});function PS(e){let t=e.split("/");if(t.length>2)return null;let r=t[0];if(!r)return null;if(t.length===1)return {address:r,prefix:null};let n=t[1];return !n||!/^\d+$/.test(n)?null:{address:r,prefix:Number(n)}}function NS(e){let t=e.split(".");return t.length!==4?false:t.every(r=>{if(!/^\d+$/.test(r))return false;let n=Number(r);return n>=0&&n<=255})}function OS(e){if(!e.includes(":"))return false;try{return new URL(`http://[${e}]/`),!0}catch{return false}}function _f(e){let t=PS(e);return t?NS(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=32:OS(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=128:false:false}var nn,wa=y(()=>{je();nn=class extends ie{get isShimBacked(){return true}checkConstraint(){let t=this.quoteIfNeeded(this.context.column);return `${t} IS NULL OR (length(${t}) BETWEEN 3 AND 49 AND (instr(${t}, '.') > 0 OR instr(${t}, ':') > 0))`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string")throw this.checkError("inet_format",t);let r=t.trim();if(!_f(r))throw this.checkError("inet_format",t);return r}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!_f(t.trim())?this.validationFail("Invalid inet address.","Patch rows with valid inet strings."):this.validationPass()}};});var sn,ba=y(()=>{je();sn=class extends ie{serialize(t){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}deserialize(t){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}toColumnDDL(){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}};});function Lt(e,t){if(t?.isArray){let n=Lt(e,{...t,isArray:false});return new ut(e,n)}if(t?.enumValues)return new tn(e,t.enumValues);let r=e.pgTypeName.toLowerCase().trim();if(r.startsWith("_")||r.endsWith("[]")){let n=r.startsWith("_")?r.slice(1):r.slice(0,-2),s={...e,pgTypeName:n},i=Lt(s);return new ut(e,i)}return IS.has(r)?new Vr(e):LS.has(r)?new Nt(e):MS.has(r)?new Jr(e):US.has(r)?new Xr(e):WS.has(r)?new Yr(e):GS.has(r)?new Qr(e):zS.has(r)?new Zr(e):VS.has(r)?new en(e):FS.has(r)?new Kr(e):DS.has(r)?new Ot(e,t?.numericPrecision):BS.has(r)?new rn(e):qS.has(r)?new ie(e,63):HS.has(r)?new nn(e):jS.has(r)?new ie(e,t?.lengthConstraint):new sn(e)}var LS,IS,DS,jS,FS,MS,US,BS,qS,HS,WS,GS,zS,VS,Sa=y(()=>{Ps();la();Ns();je();ca();ua();pa();fa();ma();da();ha();ga();Os();ya();wa();ba();LS=new Set(["int2","smallint","int4","integer","int","int8","bigint"]),IS=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]),DS=new Set(["float4","real","float8","double precision","numeric","decimal"]),jS=new Set(["text","varchar","character varying","char","character","bpchar"]),FS=new Set(["bytea"]),MS=new Set(["bool","boolean"]),US=new Set(["json","jsonb"]),BS=new Set(["uuid"]),qS=new Set(["name"]),HS=new Set(["inet"]),WS=new Set(["date"]),GS=new Set(["time","timetz","time without time zone","time with time zone"]),zS=new Set(["timestamp","timestamptz","timestamp without time zone","timestamp with time zone"]),VS=new Set(["interval"]);});function Ea(e,t="auto"){let r=e.toLowerCase(),n=Ls[r];if(!n)return null;switch(t){case "translate":{if(!n.sqlite)throw new Error(`No SQLite translation for function "${e}"`);return {sqliteExpr:n.sqlite(),jsFn:null}}case "synthetic":{if(!n.js)throw new Error(`No JS implementation for function "${e}"`);return {sqliteExpr:null,jsFn:n.js}}case "auto":return n.js?{sqliteExpr:null,jsFn:n.js}:n.sqlite?{sqliteExpr:n.sqlite(),jsFn:null}:null}}var $f,Ls,xa=y(()=>{$f="lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))",Ls={gen_random_uuid:{sqlite:()=>$f,js:()=>crypto.randomUUID()},uuid_generate_v4:{sqlite:()=>$f,js:()=>crypto.randomUUID()},now:{sqlite:()=>"datetime('now')",js:()=>new Date().toISOString()},current_timestamp:{sqlite:()=>"datetime('now')",js:()=>new Date().toISOString()},current_date:{sqlite:()=>"date('now')",js:()=>new Date().toISOString().split("T")[0]},current_time:{sqlite:()=>"time('now')",js:()=>new Date().toISOString().split("T")[1].replace("Z","")},random:{sqlite:()=>"random()",js:()=>Math.random()},length:{sqlite:()=>"length",js:null},lower:{sqlite:()=>"lower",js:null},upper:{sqlite:()=>"upper",js:null},substr:{sqlite:()=>"substr",js:null},substring:{sqlite:()=>"substr",js:null},trim:{sqlite:()=>"trim",js:null},ltrim:{sqlite:()=>"ltrim",js:null},rtrim:{sqlite:()=>"rtrim",js:null},replace:{sqlite:()=>"replace",js:null},coalesce:{sqlite:()=>"coalesce",js:null},nullif:{sqlite:()=>"nullif",js:null},count:{sqlite:()=>"count",js:null},sum:{sqlite:()=>"sum",js:null},avg:{sqlite:()=>"avg",js:null},min:{sqlite:()=>"min",js:null},max:{sqlite:()=>"max",js:null},localtime:{sqlite:()=>"time('now', 'localtime')",js:null},localtimestamp:{sqlite:()=>"datetime('now', 'localtime')",js:null}};});var on,vf=y(()=>{on=class{table;schema;fields;constructor(t,r="public",n=new Map){this.table=t,this.schema=r,this.fields=n;}get(t){return this.fields.get(t)}has(t){return this.fields.has(t)}set(t,r){this.fields.set(t,r);}columns(){return Array.from(this.fields.keys())}all(){return Array.from(this.fields.values())}serializeRow(t){let r={};for(let[n,s]of Object.entries(t)){let i=this.fields.get(n);r[n]=i?i.serialize(s):s;}return r}deserializeRow(t){let r={};for(let[n,s]of Object.entries(t)){let i=this.fields.get(n);r[n]=i?i.deserialize(s):s;}return r}applyDefaults(t){let r={...t};for(let[n,s]of this.fields)!(n in r)&&s.context.defaultFn&&(r[n]=s.context.defaultFn());return r}};});var Tf=y(()=>{et();aa();Ps();la();Ns();je();ca();ua();pa();fa();ma();da();ha();ga();Os();ya();wa();ba();Sa();xa();vf();});var ka={};fe(ka,{_resetWarnedMissingToClauseForTests:()=>KS,collectComments:()=>Ra,collectEnums:()=>$a,collectPolicies:()=>Ta,collectSchema:()=>Aa,collectTableConstraints:()=>Ca,collectVariables:()=>va});function KS(){_a.clear();}function $a(e){let t=new Map;for(let r of e.stmts??[]){if(!r.stmt||!("CreateEnumStmt"in r.stmt))continue;let n=r.stmt.CreateEnumStmt,s=Ct(n.typeName??[]).join(".");if(!s||!n.vals)continue;let i=Ct(n.vals);t.set(s.toLowerCase(),i);}return t}function va(e){let t=new Map;for(let r of e.stmts??[]){if(!r.stmt||!("VariableSetStmt"in r.stmt))continue;let n=r.stmt.VariableSetStmt,s=n.name,i=yf(n.args?.[0]??{});t.set(s,{value:i,local:n.is_local});}return t}function Ta(e){let t=new Wr,r=new Set,n=[];for(let s of e.stmts??[])if(s.stmt){if("CreatePolicyStmt"in s.stmt){let i=s.stmt.CreatePolicyStmt,o=i.table?.relname??"",a=i.table?.schemaname,l={select:"SELECT",insert:"INSERT",update:"UPDATE",delete:"DELETE"},c=i.cmd_name?l[i.cmd_name]??"ALL":"ALL",u=i.permissive===true,p=[],f=false;for(let b of i.roles??[])if("RoleSpec"in b){let g=b.RoleSpec;g.roletype==="ROLESPEC_PUBLIC"?g.location===-1&&(f=true):g.roletype==="ROLESPEC_CSTRING"&&g.rolename&&p.push(g.rolename);}let h=i.qual?t.deparse(i.qual):void 0,d=i.with_check?t.deparse(i.with_check):void 0;if(f){let b=a?`${a}.${o}`:o,g=i.policy_name??"",S=`${b}::${g}`;if(!_a.has(S)){_a.add(S);let A=JSON.stringify(h)+JSON.stringify(d);/\{\{auth\.(uid|jwt|role)/i.test(A)||console.warn(`[supalite] policy "${g}" on "${b}" has no TO clause \u2014 applies to all roles (PUBLIC). For clarity, prefer an explicit \`TO <role>\` clause (e.g. \`TO authenticated\`).`);}}let m=new Gr({name:i.policy_name??"",table:o,schema:a,command:c,permissive:u,roles:p,using:h,withCheck:d});n.push(m);}if("AlterTableStmt"in s.stmt){let i=s.stmt.AlterTableStmt;if((i.cmds??[]).some(l=>"AlterTableCmd"in l&&(l.AlterTableCmd.subtype==="AT_EnableRowSecurity"||l.AlterTableCmd.subtype==="AT_ForceRowSecurity"))){let l=i.relation?.relname??"";r.add(l);}}}return {policies:n,tables:r}}function Aa(e,t){let r=new Map;for(let n of e.stmts??[]){if(!n.stmt||!("CreateStmt"in n.stmt))continue;let s=n.stmt.CreateStmt,i=s.relation?.relname??"",o=s.relation?.schemaname??"public";if(!i)continue;let a=new on(i,o);for(let l of s.tableElts??[]){if(!("ColumnDef"in l))continue;let c=l.ColumnDef,u=c.colname;if(!u)continue;let p=c.typeName?.names?.map(T=>T.String?.sval||T.String?.str).filter(Boolean),f=p&&(p.length===2&&p[0]==="pg_catalog"?p[1]:p[0]);if(!f)continue;let h=!!c.typeName?.arrayBounds?.length,d=Array.isArray(c.typeName?.typmods)?c.typeName.typmods:[],m=T=>d[T]?.A_Const?.ival?.ival??d[T]?.A_Const?.val?.ival?.ival,b={isArray:h};if(Cs(f)&&d.length>0){let T=m(0);typeof T=="number"&&T>0&&(b.lengthConstraint=T);}if(Rs(f)&&d.length>=2){let T=m(0),q=m(1);typeof T=="number"&&typeof q=="number"&&T>0&&q>=0&&(b.numericPrecision={precision:T,scale:q});}let g=t.get(f.toLowerCase());g&&(b.enumValues=g);let S=Array.isArray(c.constraints)?c.constraints:[],A=S.some(T=>T.Constraint?.contype==="CONSTR_PRIMARY"),$=As(f)||S.some(T=>T.Constraint?.contype==="CONSTR_IDENTITY"),P=S.some(T=>T.Constraint?.contype==="CONSTR_NOTNULL"),N=S.find(T=>T.Constraint?.contype==="CONSTR_UNIQUE"),v=S.find(T=>T.Constraint?.contype==="CONSTR_GENERATED"),_=S.find(T=>T.Constraint?.contype==="CONSTR_FOREIGN"),L=S.find(T=>T.Constraint?.contype==="CONSTR_CHECK"),w;if(_){let T=_.Constraint,q=T.pktable?.relname,E=T.pktable?.schemaname,x=T.pk_attrs?.[0]?.String?.sval;q&&x&&(w={refSchema:E,refTable:q,refColumn:x,constraintName:T.conname||void 0});}let I={schema:o,table:i,column:u,pgTypeName:f,nullable:!P&&!A,defaultValue:null,defaultFn:null,isPrimaryKey:A,isUnique:!!N,isSerial:$,isGenerated:!!v,fkRef:w,hasCheck:!!L,checkConstraintName:L?.Constraint?.conname||void 0,uniqueConstraintName:N?.Constraint?.conname||void 0};a.set(u,Lt(I,b));}r.set(`${o}.${i}`,a);}return r}function Ca(e){let t=[];for(let r of e.stmts??[]){if(!r.stmt||!("CreateStmt"in r.stmt))continue;let n=r.stmt.CreateStmt,s=n.relation?.relname??"",i=n.relation?.schemaname??"public";if(s)for(let o of n.tableElts??[]){if("ColumnDef"in o)continue;let a=o;if(!a.Constraint)continue;let l=a.Constraint,c=l.contype;if(c==="CONSTR_UNIQUE"){let u=(l.keys??[]).map(p=>p.String?.sval??p.String?.str).filter(Boolean);if(u.length===0)continue;t.push({schema:i,table:s,kind:"unique",name:l.conname||void 0,columns:u});}else if(c==="CONSTR_CHECK")t.push({schema:i,table:s,kind:"check",name:l.conname||void 0,columns:[]});else if(c==="CONSTR_FOREIGN"){let u=(l.fk_attrs??[]).map(h=>h.String?.sval??h.String?.str).filter(Boolean),p=(l.pk_attrs??[]).map(h=>h.String?.sval??h.String?.str).filter(Boolean),f=l.pktable?.relname;if(!f)continue;t.push({schema:i,table:s,kind:"foreign_key",name:l.conname||void 0,columns:u,refSchema:l.pktable?.schemaname,refTable:f,refColumns:p});}}}return t}function Ra(e){let t=[];for(let r of e.stmts??[]){if(!r.stmt||!("CommentStmt"in r.stmt))continue;let n=r.stmt.CommentStmt,s=n.comment??"";if(!s)continue;let i=n.objtype,o=(n.object?.List?.items??n.object?.items??[]).map(a=>a.String?.sval??a.String?.str).filter(Boolean);if(o.length!==0){if(i==="OBJECT_TABLE"||i==="OBJECT_VIEW"){let[a,l]=o.length>=2?o:["public",o[0]];t.push({schema:a,table:l,text:s});}else if(i==="OBJECT_COLUMN"){let a="public",l,c;o.length>=3?[a,l,c]=o:[l,c]=o,t.push({schema:a,table:l,column:c,text:s});}}}return t}var _a,Pa=y(()=>{ia();kt();oa();Tf();sr();_a=new Set;});async function ln(e,t){let r=await e.connection.introspect(),n=Na(r);await Nf(e,{...t,dbHasTables:r.tables.length>0,dbFingerprint:n}),r.tables.length===0&&await Oa(e);let s=await e.connection.introspect();Lf(s,e);}async function YS(e){let t=await Br(e.config.db?.seed?.sql_paths??["./seed.sql"],{cwd:He__default.join(process.cwd(),"supabase"),absolute:true});return (await Promise.all(t.map(n=>ce__default.readFile(n,"utf-8")))).flatMap(n=>splitSqlStatements(n))}async function cn(e,t){let r=await YS(e);if(r.length===0)return 0;console.log(F.default.dim("Seeding database..."));try{return await e.connection.transaction(r),r.length}catch(n){let s=t?.recoveryHint??"Fix `supabase/seed.sql`, then run `bun run dev --recreate` to reset and reseed.";throw new Error(`Seed failed and was rolled back: ${String(n.message??n)}
|
|
64
64
|
${s}`)}}async function Oa(e){await cn(e);}async function ue(e){let t=await Br(e.config?.db?.migrations?.schema_paths??["./schemas/*.sql"],{cwd:He__default.join(process.cwd(),"supabase"),absolute:true}),r=await Promise.all(t.map(async n=>await ce__default.readFile(n,"utf-8"))).then(n=>n.map(s=>s.split(`
|
|
65
65
|
`).filter(i=>i.trim().length>0&&!i.trim().startsWith("--")).join(`
|
|
66
66
|
`)).join(`
|