@supabase/lite 0.8.1-next.2 → 0.9.1-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/FEATURES.md +176 -0
  2. package/LIMITATIONS.md +1 -0
  3. package/README.md +1 -0
  4. package/STATUS.md +7 -1
  5. package/dist/cli/index.js +86 -86
  6. package/dist/db/postgres/pglite/PgliteConnection.js +17 -17
  7. package/dist/index.d.ts +26 -2
  8. package/dist/index.js +55 -55
  9. package/dist/vite/index.d.ts +26 -2
  10. package/docs/auth/email.mdx +214 -0
  11. package/docs/auth/not-supported.mdx +57 -0
  12. package/docs/auth/overview.mdx +52 -0
  13. package/docs/auth/supported-flows.mdx +120 -0
  14. package/docs/cli/overview.mdx +112 -0
  15. package/docs/cli/telemetry.mdx +34 -0
  16. package/docs/compatibility.mdx +115 -0
  17. package/docs/database/backends.mdx +118 -0
  18. package/docs/database/data-api.mdx +90 -0
  19. package/docs/database/functions-triggers.mdx +93 -0
  20. package/docs/database/migrations.mdx +93 -0
  21. package/docs/database/overview.mdx +66 -0
  22. package/docs/database/postgres-sqlite-translation.mdx +130 -0
  23. package/docs/database/rls.mdx +159 -0
  24. package/docs/database/schemas.mdx +58 -0
  25. package/docs/index.mdx +49 -0
  26. package/docs/integrations/embedded.mdx +83 -0
  27. package/docs/integrations/frameworks.mdx +83 -0
  28. package/docs/integrations/vite.mdx +85 -0
  29. package/docs/llms.txt +52 -0
  30. package/docs/other/edge-functions.mdx +34 -0
  31. package/docs/other/realtime.mdx +22 -0
  32. package/docs/quickstart.mdx +150 -0
  33. package/docs/running.mdx +117 -0
  34. package/docs/storage/adapters.mdx +75 -0
  35. package/docs/storage/limitations.mdx +30 -0
  36. package/docs/storage/overview.mdx +82 -0
  37. package/docs/upgrade.mdx +108 -0
  38. package/package.json +4 -1
  39. package/skills/supalite/SKILL.md +5 -3
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import*as yt from'jsonv-ts';import {s}from'jsonv-ts';import {Deparser,QuoteUtils}from'pgsql-deparser';import {DeparserContext}from'pgsql-deparser/visitors/base.js';import {SqlFormatter}from'pgsql-deparser/utils/sql-formatter.js';import {jsonStringify,Connection,RelationNotFoundError,invariant,DataLossError,PlanStepType}from'@supabase/lite';import {Kysely,PostgresQueryCompiler,PostgresIntrospector,DummyDriver,PostgresAdapter,SqliteQueryCompiler,SqliteIntrospector,SqliteAdapter,sql,OperationNodeTransformer,SchemableIdentifierNode,JoinNode,TableNode,AliasNode,ListNode,UsingNode}from'kysely';import {jsonObjectFrom as jsonObjectFrom$1,jsonArrayFrom as jsonArrayFrom$1}from'kysely/helpers/postgres';import {jsonObjectFrom,jsonArrayFrom}from'kysely/helpers/sqlite';import {jwtVerify,createRemoteJWKSet,customFetch,errors,SignJWT}from'jose';import hh from'bcryptjs';import {v7}from'uuid';import {validator}from'jsonv-ts/hono';import {createClient}from'@supabase/supabase-js';try {
1
+ import*as yt from'jsonv-ts';import {s}from'jsonv-ts';import {Deparser,QuoteUtils}from'pgsql-deparser';import {DeparserContext}from'pgsql-deparser/visitors/base.js';import {SqlFormatter}from'pgsql-deparser/utils/sql-formatter.js';import {jsonStringify,Connection,RelationNotFoundError,invariant,DataLossError,PlanStepType}from'@supabase/lite';import {Kysely,PostgresQueryCompiler,PostgresIntrospector,DummyDriver,PostgresAdapter,SqliteQueryCompiler,SqliteIntrospector,SqliteAdapter,sql,OperationNodeTransformer,SchemableIdentifierNode,JoinNode,TableNode,AliasNode,ListNode,UsingNode}from'kysely';import {jsonObjectFrom as jsonObjectFrom$1,jsonArrayFrom as jsonArrayFrom$1}from'kysely/helpers/postgres';import {jsonObjectFrom,jsonArrayFrom}from'kysely/helpers/sqlite';import {jwtVerify,createRemoteJWKSet,customFetch,errors,SignJWT}from'jose';import yh from'bcryptjs';import {v7}from'uuid';import {validator}from'jsonv-ts/hono';import {createClient}from'@supabase/supabase-js';try {
2
2
  /**
3
3
  * Adding this to avoid warnings from node:sqlite being experimental
4
4
  */
@@ -9,37 +9,37 @@ import*as yt from'jsonv-ts';import {s}from'jsonv-ts';import {Deparser,QuoteUtils
9
9
  };
10
10
  } catch {}
11
11
 
12
- var bb=Object.create;var la=Object.defineProperty;var wb=Object.getOwnPropertyDescriptor;var Sb=Object.getOwnPropertyNames;var _b=Object.getPrototypeOf,Eb=Object.prototype.hasOwnProperty;var I=(t,e)=>()=>(t&&(e=t(t=0)),e);var Hu=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Zs=(t,e)=>{for(var n in e)la(t,n,{get:e[n],enumerable:true});},xb=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Sb(e))!Eb.call(t,s)&&s!==n&&la(t,s,{get:()=>e[s],enumerable:!(r=wb(e,s))||r.enumerable});return t};var ca=(t,e,n)=>(n=t!=null?bb(_b(t)):{},xb(la(n,"default",{value:t,enumerable:true}),t));var on,ki=I(()=>{on=class extends Error{constructor(n,r,s,i){super(`check constraint "${s}" violated for ${n}.${r}`);this.table=n;this.column=r;this.constraint=s;this.value=i;this.name="CheckConstraintError";}};});var ie,st=I(()=>{ki();ie=class{context;factoryExtra;constructor(e){this.context=e;}get isShimBacked(){return false}checkConstraint(){return null}serialize(e){return e}deserialize(e){return e}validateStorage(e){return {status:"pass",message:null}}validationFail(e,n){return {status:"fail",message:e,action:n}}validationPass(){return {status:"pass",message:null}}isNullish(e){return e==null}toColumnDDL(e){let{includeNullable:n=true}=e??{},r=[],s=this.context.column;r.push(this.quoteIfNeeded(s)),r.push(this.sqliteType),this.context.isPrimaryKey&&r.push("PRIMARY KEY"),this.context.isSerial&&this.context.isPrimaryKey&&r.push("AUTOINCREMENT"),n&&!this.context.nullable&&!this.context.isPrimaryKey&&r.push("NOT NULL"),this.context.isUnique&&!this.context.isPrimaryKey&&r.push("UNIQUE"),this.context.defaultValue!==null&&r.push(`DEFAULT ${this.context.defaultValue}`);let i=this.checkConstraint();return i&&r.push(`CHECK (${i})`),r.join(" ")}checkError(e,n){return new on(this.context.table,this.context.column,e,n)}quoteIfNeeded(e){return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)?e:`"${e}"`}};});function LO(t=10,e={}){let o="abcdefghijklmnopqrstuvwxyz"+(e.uppercase?"ABCDEFGHIJKLMNOPQRSTUVWXYZ":"")+(e.numbers?"0123456789":"")+(e.special?"!@#$%^&*()_+{}:\"<>?|[];',./`~":""),a="";for(let l=0;l<t;l++)a+=o[Math.floor(Math.random()*o.length)];return a}function FO(t,e){if(typeof t!="string"){if(e?.panic)throw new Error("Email must be a string");return false}if(!s.string({format:"email"}).validate(t).valid){if(e?.panic)throw new Error("Invalid email");return false}if(e?.domains?.length&&!e.domains.includes(t.split("@")[1])){if(e?.panic)throw new Error("Email domain not allowed");return false}return true}function UO(t,{panic:e=true,length:n=8,numbers:r=0,special:s=0}={}){try{if(typeof t!="string"){if(e)throw new Error("Password must be a string");return !1}if(t.length<n){if(e)throw new Error(`Password must be at least ${n} characters long`);return !1}if((t.match(/[0-9]/g)?.length??0)<r){if(e)throw new Error(`Password must contain at least ${r} numbers`);return !1}if((t.match(/[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/g)?.length??0)<s){if(e)throw new Error(`Password must contain at least ${s} special characters`);return !1}return !0}catch(i){if(e)throw i;return false}}function MO(t){return !t||t.length===0?t:t.charAt(0).toUpperCase()+t.slice(1)}function BO(t,e=" "){return !t||t.length===0?t:t.split(e).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(e)}function qO(t){return !t||t.length===0?t:t.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}function WS(t){return String(t).normalize("NFKD").replace(/[\u0300-\u036f]/g,"")}function HO(t){return WS(t).trim().toLowerCase().replace(/[^a-z0-9 -]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-")}function WO(t,e=50,n="..."){return t.length<=e?t:t.substring(0,e)+n}function N(t,e='"'){return `${e}${t}${e}`}function Ki(t,e,n){if(e instanceof RegExp)return e.test(t);if(typeof e=="string")switch(!n&&e.startsWith("/")&&(n="regex"),n){case "regex":return new RegExp(e).test(t);case "sql":return new RegExp(e.replace("%",".*").replace("_",".")).test(t);case "wildcard":return new RegExp(e.replace("*",".*")).test(t);default:return t.includes(e)}return false}function KO(t,e,n=/\{\{([\w-]+)\}\}/g){return t.replace(n,(r,s)=>s in e?e[s]:r)}function Jr(t,e,n=.33){if(e.length===0)return null;let r=rp(t),s=[];for(let l of e){let c=KS(r,rp(l));c>.1&&s.push([l,c]);}s.sort((l,c)=>c[1]-l[1]);let i=s.slice(0,50),o=null,a=n;for(let[l]of i){let c=Math.max(t.length,l.length),f=c===0?1:1-JS(t.toLowerCase(),l.toLowerCase())/c;f>a&&(a=f,o=l);}return o}function rp(t,e=2){let n=new Map,r=`-${t.toLowerCase()}-`;for(let s=0;s<=r.length-e;s++){let i=r.slice(s,s+e);n.set(i,(n.get(i)||0)+1);}return n}function KS(t,e){let n=0,r=0,s=0;for(let[i,o]of t){r+=o*o;let a=e.get(i);a!==void 0&&(n+=o*a);}for(let[,i]of e)s+=i*i;return r===0||s===0?0:n/(Math.sqrt(r)*Math.sqrt(s))}function JS(t,e){let n=t.length,r=e.length,s=Array.from({length:r+1},(i,o)=>o);for(let i=1;i<=n;i++){let o=s[0];s[0]=i;for(let a=1;a<=r;a++){let l=s[a];s[a]=t[i-1]===e[a-1]?o:1+Math.min(o,s[a],s[a-1]),o=l;}}return s[r]}var Fn=I(()=>{});var Cl=Hu((BP,Rl)=>{var eo=process||{},Cp=eo.argv||[],Zi=eo.env||{},H_=!(Zi.NO_COLOR||Cp.includes("--no-color"))&&(!!Zi.FORCE_COLOR||Cp.includes("--color")||eo.platform==="win32"||(eo.stdout||{}).isTTY&&Zi.TERM!=="dumb"||!!Zi.CI),W_=(t,e,n=t)=>r=>{let s=""+r,i=s.indexOf(e,t.length);return ~i?t+K_(s,e,n,i)+e:t+s+e},K_=(t,e,n,r)=>{let s="",i=0;do s+=t.substring(i,r)+n,i=r+e.length,r=t.indexOf(e,i);while(~r);return s+t.substring(i)},kp=(t=H_)=>{let e=t?W_:()=>String;return {isColorSupported:t,reset:e("\x1B[0m","\x1B[0m"),bold:e("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:e("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:e("\x1B[3m","\x1B[23m"),underline:e("\x1B[4m","\x1B[24m"),inverse:e("\x1B[7m","\x1B[27m"),hidden:e("\x1B[8m","\x1B[28m"),strikethrough:e("\x1B[9m","\x1B[29m"),black:e("\x1B[30m","\x1B[39m"),red:e("\x1B[31m","\x1B[39m"),green:e("\x1B[32m","\x1B[39m"),yellow:e("\x1B[33m","\x1B[39m"),blue:e("\x1B[34m","\x1B[39m"),magenta:e("\x1B[35m","\x1B[39m"),cyan:e("\x1B[36m","\x1B[39m"),white:e("\x1B[37m","\x1B[39m"),gray:e("\x1B[90m","\x1B[39m"),bgBlack:e("\x1B[40m","\x1B[49m"),bgRed:e("\x1B[41m","\x1B[49m"),bgGreen:e("\x1B[42m","\x1B[49m"),bgYellow:e("\x1B[43m","\x1B[49m"),bgBlue:e("\x1B[44m","\x1B[49m"),bgMagenta:e("\x1B[45m","\x1B[49m"),bgCyan:e("\x1B[46m","\x1B[49m"),bgWhite:e("\x1B[47m","\x1B[49m"),blackBright:e("\x1B[90m","\x1B[39m"),redBright:e("\x1B[91m","\x1B[39m"),greenBright:e("\x1B[92m","\x1B[39m"),yellowBright:e("\x1B[93m","\x1B[39m"),blueBright:e("\x1B[94m","\x1B[39m"),magentaBright:e("\x1B[95m","\x1B[39m"),cyanBright:e("\x1B[96m","\x1B[39m"),whiteBright:e("\x1B[97m","\x1B[39m"),bgBlackBright:e("\x1B[100m","\x1B[49m"),bgRedBright:e("\x1B[101m","\x1B[49m"),bgGreenBright:e("\x1B[102m","\x1B[49m"),bgYellowBright:e("\x1B[103m","\x1B[49m"),bgBlueBright:e("\x1B[104m","\x1B[49m"),bgMagentaBright:e("\x1B[105m","\x1B[49m"),bgCyanBright:e("\x1B[106m","\x1B[49m"),bgWhiteBright:e("\x1B[107m","\x1B[49m")}};Rl.exports=kp();Rl.exports.createColors=kp;});function qP(t){return ["string","number","boolean"].includes(typeof t)}function HP(t){return [true,false,0,1].includes(t)}function WP(t){return typeof t=="string"}var vp=I(()=>{});function JP(...t){return e=>t.reduce((n,r)=>r(n),e)}function GP(...t){return e=>e.map(n=>t.reduce((r,s)=>s(r),n))}var Ap=I(()=>{});function Op(t){return Object.prototype.toString.call(t)==="[object Object]"}function Pp(t){return t!==null&&typeof t=="object"}function VP(t,e){let n={};for(let r in t)t[r]!==e[r]&&(n[r]=e[r]);return n}function qt(t,e,n=void 0){let r=typeof e=="string"?e.split(/[.[\]"]+/).filter(s=>s):e;if(r.length===0)return t;try{let[s,...i]=r;return !s||!(s in t)?n:qt(t[s],i,n)}catch{if(typeof n<"u")return n;throw new Error(`Invalid path: ${r.join(".")}`)}}function J_(t,e,n){let r=e;if(typeof r=="string"){let o=a=>a[0]==='"'&&a.at(-1)==='"';r=r.split(/[.[\]]+/).filter(a=>a).map(a=>Number.isNaN(Number(a))?a:Number(a)).map(a=>typeof a=="string"&&o(a)?a.slice(1,-1):a);}if(r.length===0)throw new Error("The path must have at least one entry in it");let[s,...i]=r;return i.length===0?(t[s]=n,t):(s in t||(t[s]=typeof i[0]=="number"?[]:{}),J_(t[s],i,n),t)}function QP(t,e){return e.reduce((n,r)=>(r in t&&(n[r]=t[r]),n),{})}function YP(t,e){let n=new Set(e),r={};for(let[s,i]of Object.entries(t))n.has(s)||(r[s]=i);return r}function vl(t,...e){for(let n of e)for(let[r,s]of Object.entries(n))s!==void 0&&(!Op(s)&&!Array.isArray(s)||Array.isArray(s)&&!Array.isArray(t[r])?t[r]=s:Pp(t[r])?vl(t[r],s):t[r]=s);return t}function G_(t,e,n){for(let[r,s]of Object.entries(e)){let i=n(t[r],s,r,t,e);if(i!==void 0){t[r]=i;continue}s!==void 0&&(!Op(s)&&!Array.isArray(s)||Array.isArray(s)&&!Array.isArray(t[r])?t[r]=s:Pp(t[r])?G_(t[r],s,n):t[r]=s);}return t}function kl(t,e){let n=s=>{if(s!==Object(s))return "primitive";if(Array.isArray(s))return "array";if(s instanceof Map)return "map";if(s!=null&&[null,Object.prototype].includes(Object.getPrototypeOf(s)))return "plainObject";if(s instanceof Function)return "function";throw new Error(`deeply comparing an instance of type ${t.constructor?.name} is not supported.`)},r=n(t);if(r!==n(e))return false;if(r==="primitive")return t===e||Number.isNaN(t)&&Number.isNaN(e);if(r==="array")return t.length===e.length&&t.every((s,i)=>kl(s,e[i]));if(r==="map")return t.size===e.size&&[...t].every(([s,i])=>e.has(s)&&kl(i,e.get(s)));if(r==="plainObject"){let s=new Map(Object.entries(t)),i=new Map(Object.entries(e));return s.size===i.size&&[...s].every(([o,a])=>i.has(o)&&kl(a,i.get(o)))}else {if(r==="function")return t.toString()===e.toString();throw new Error("Unreachable")}}function $p(...t){let[e,n,r]=t;return JSON.stringify(e,(s,i)=>typeof i=="bigint"?Number.parseInt(i.toString(),10):i instanceof Map?Object.fromEntries(i.entries()):i instanceof Set?Array.from(i):n&&typeof n=="function"?n(s,i):i,r)}var Vr=I(()=>{});function ZP(t){let e=t instanceof Request?new URL(t.url).searchParams:t;return Object.fromEntries(e.entries())}function e$(t,e){let n=t instanceof Request?new URL(t.url).searchParams:t,r={};for(let[s,i]of n.entries())e(s,i)&&(r[s]=i);return r}var Ip=I(()=>{});function Np(){try{return !Al()&&global?.process?.release?.name==="node"}catch{return false}}function Al(){try{return typeof Bun<"u"}catch{return false}}function Dp(){try{return typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"}catch{return false}}function jp(t,e){if(!t)throw new Error(e)}function n$(t,e){try{return t(),!1}catch(n){if(e){if(n instanceof e)return true;throw n}return true}}async function r$(t,e){try{return await t,!1}catch(n){if(e){if(n instanceof e)return true;throw n}return true}}function s$(t,e){try{return t()}catch{return e}}async function i$(t,e){let n=performance.now();await t();let r=performance.now();e(r-n);}var o$,Ol=I(()=>{o$={Map:t=>t instanceof Map?t:new Map(typeof t=="object"&&t!==null?Object.entries(t):[]),Set:t=>t instanceof Set?t:new Set(Array.isArray(t)?t:[]),Array:t=>Array.isArray(t)?t:["string","number","boolean"].includes(typeof t)?[t]:[]};});function Qr(t,e={}){return t.split(`
12
+ var xb=Object.create;var fa=Object.defineProperty;var Tb=Object.getOwnPropertyDescriptor;var Rb=Object.getOwnPropertyNames;var Cb=Object.getPrototypeOf,kb=Object.prototype.hasOwnProperty;var I=(t,e)=>()=>(t&&(e=t(t=0)),e);var zu=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Zs=(t,e)=>{for(var n in e)fa(t,n,{get:e[n],enumerable:true});},vb=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Rb(e))!kb.call(t,s)&&s!==n&&fa(t,s,{get:()=>e[s],enumerable:!(r=Tb(e,s))||r.enumerable});return t};var da=(t,e,n)=>(n=t!=null?xb(Cb(t)):{},vb(fa(n,"default",{value:t,enumerable:true}),t));var on,Oi=I(()=>{on=class extends Error{constructor(n,r,s,i){super(`check constraint "${s}" violated for ${n}.${r}`);this.table=n;this.column=r;this.constraint=s;this.value=i;this.name="CheckConstraintError";}};});var ie,st=I(()=>{Oi();ie=class{context;factoryExtra;constructor(e){this.context=e;}get isShimBacked(){return false}checkConstraint(){return null}serialize(e){return e}deserialize(e){return e}validateStorage(e){return {status:"pass",message:null}}validationFail(e,n){return {status:"fail",message:e,action:n}}validationPass(){return {status:"pass",message:null}}isNullish(e){return e==null}toColumnDDL(e){let{includeNullable:n=true}=e??{},r=[],s=this.context.column;r.push(this.quoteIfNeeded(s)),r.push(this.sqliteType),this.context.isPrimaryKey&&r.push("PRIMARY KEY"),this.context.isSerial&&this.context.isPrimaryKey&&r.push("AUTOINCREMENT"),n&&!this.context.nullable&&!this.context.isPrimaryKey&&r.push("NOT NULL"),this.context.isUnique&&!this.context.isPrimaryKey&&r.push("UNIQUE"),this.context.defaultValue!==null&&r.push(`DEFAULT ${this.context.defaultValue}`);let i=this.checkConstraint();return i&&r.push(`CHECK (${i})`),r.join(" ")}checkError(e,n){return new on(this.context.table,this.context.column,e,n)}quoteIfNeeded(e){return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)?e:`"${e}"`}};});function WO(t=10,e={}){let o="abcdefghijklmnopqrstuvwxyz"+(e.uppercase?"ABCDEFGHIJKLMNOPQRSTUVWXYZ":"")+(e.numbers?"0123456789":"")+(e.special?"!@#$%^&*()_+{}:\"<>?|[];',./`~":""),a="";for(let l=0;l<t;l++)a+=o[Math.floor(Math.random()*o.length)];return a}function KO(t,e){if(typeof t!="string"){if(e?.panic)throw new Error("Email must be a string");return false}if(!s.string({format:"email"}).validate(t).valid){if(e?.panic)throw new Error("Invalid email");return false}if(e?.domains?.length&&!e.domains.includes(t.split("@")[1])){if(e?.panic)throw new Error("Email domain not allowed");return false}return true}function JO(t,{panic:e=true,length:n=8,numbers:r=0,special:s=0}={}){try{if(typeof t!="string"){if(e)throw new Error("Password must be a string");return !1}if(t.length<n){if(e)throw new Error(`Password must be at least ${n} characters long`);return !1}if((t.match(/[0-9]/g)?.length??0)<r){if(e)throw new Error(`Password must contain at least ${r} numbers`);return !1}if((t.match(/[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/g)?.length??0)<s){if(e)throw new Error(`Password must contain at least ${s} special characters`);return !1}return !0}catch(i){if(e)throw i;return false}}function GO(t){return !t||t.length===0?t:t.charAt(0).toUpperCase()+t.slice(1)}function zO(t,e=" "){return !t||t.length===0?t:t.split(e).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(e)}function VO(t){return !t||t.length===0?t:t.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}function VS(t){return String(t).normalize("NFKD").replace(/[\u0300-\u036f]/g,"")}function QO(t){return VS(t).trim().toLowerCase().replace(/[^a-z0-9 -]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-")}function XO(t,e=50,n="..."){return t.length<=e?t:t.substring(0,e)+n}function N(t,e='"'){return `${e}${t}${e}`}function zi(t,e,n){if(e instanceof RegExp)return e.test(t);if(typeof e=="string")switch(!n&&e.startsWith("/")&&(n="regex"),n){case "regex":return new RegExp(e).test(t);case "sql":return new RegExp(e.replace("%",".*").replace("_",".")).test(t);case "wildcard":return new RegExp(e.replace("*",".*")).test(t);default:return t.includes(e)}return false}function YO(t,e,n=/\{\{([\w-]+)\}\}/g){return t.replace(n,(r,s)=>s in e?e[s]:r)}function Jr(t,e,n=.33){if(e.length===0)return null;let r=ip(t),s=[];for(let l of e){let c=QS(r,ip(l));c>.1&&s.push([l,c]);}s.sort((l,c)=>c[1]-l[1]);let i=s.slice(0,50),o=null,a=n;for(let[l]of i){let c=Math.max(t.length,l.length),f=c===0?1:1-XS(t.toLowerCase(),l.toLowerCase())/c;f>a&&(a=f,o=l);}return o}function ip(t,e=2){let n=new Map,r=`-${t.toLowerCase()}-`;for(let s=0;s<=r.length-e;s++){let i=r.slice(s,s+e);n.set(i,(n.get(i)||0)+1);}return n}function QS(t,e){let n=0,r=0,s=0;for(let[i,o]of t){r+=o*o;let a=e.get(i);a!==void 0&&(n+=o*a);}for(let[,i]of e)s+=i*i;return r===0||s===0?0:n/(Math.sqrt(r)*Math.sqrt(s))}function XS(t,e){let n=t.length,r=e.length,s=Array.from({length:r+1},(i,o)=>o);for(let i=1;i<=n;i++){let o=s[0];s[0]=i;for(let a=1;a<=r;a++){let l=s[a];s[a]=t[i-1]===e[a-1]?o:1+Math.min(o,s[a],s[a-1]),o=l;}}return s[r]}var Fn=I(()=>{});var Al=zu((zP,vl)=>{var ro=process||{},vp=ro.argv||[],no=ro.env||{},z_=!(no.NO_COLOR||vp.includes("--no-color"))&&(!!no.FORCE_COLOR||vp.includes("--color")||ro.platform==="win32"||(ro.stdout||{}).isTTY&&no.TERM!=="dumb"||!!no.CI),V_=(t,e,n=t)=>r=>{let s=""+r,i=s.indexOf(e,t.length);return ~i?t+Q_(s,e,n,i)+e:t+s+e},Q_=(t,e,n,r)=>{let s="",i=0;do s+=t.substring(i,r)+n,i=r+e.length,r=t.indexOf(e,i);while(~r);return s+t.substring(i)},Ap=(t=z_)=>{let e=t?V_:()=>String;return {isColorSupported:t,reset:e("\x1B[0m","\x1B[0m"),bold:e("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:e("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:e("\x1B[3m","\x1B[23m"),underline:e("\x1B[4m","\x1B[24m"),inverse:e("\x1B[7m","\x1B[27m"),hidden:e("\x1B[8m","\x1B[28m"),strikethrough:e("\x1B[9m","\x1B[29m"),black:e("\x1B[30m","\x1B[39m"),red:e("\x1B[31m","\x1B[39m"),green:e("\x1B[32m","\x1B[39m"),yellow:e("\x1B[33m","\x1B[39m"),blue:e("\x1B[34m","\x1B[39m"),magenta:e("\x1B[35m","\x1B[39m"),cyan:e("\x1B[36m","\x1B[39m"),white:e("\x1B[37m","\x1B[39m"),gray:e("\x1B[90m","\x1B[39m"),bgBlack:e("\x1B[40m","\x1B[49m"),bgRed:e("\x1B[41m","\x1B[49m"),bgGreen:e("\x1B[42m","\x1B[49m"),bgYellow:e("\x1B[43m","\x1B[49m"),bgBlue:e("\x1B[44m","\x1B[49m"),bgMagenta:e("\x1B[45m","\x1B[49m"),bgCyan:e("\x1B[46m","\x1B[49m"),bgWhite:e("\x1B[47m","\x1B[49m"),blackBright:e("\x1B[90m","\x1B[39m"),redBright:e("\x1B[91m","\x1B[39m"),greenBright:e("\x1B[92m","\x1B[39m"),yellowBright:e("\x1B[93m","\x1B[39m"),blueBright:e("\x1B[94m","\x1B[39m"),magentaBright:e("\x1B[95m","\x1B[39m"),cyanBright:e("\x1B[96m","\x1B[39m"),whiteBright:e("\x1B[97m","\x1B[39m"),bgBlackBright:e("\x1B[100m","\x1B[49m"),bgRedBright:e("\x1B[101m","\x1B[49m"),bgGreenBright:e("\x1B[102m","\x1B[49m"),bgYellowBright:e("\x1B[103m","\x1B[49m"),bgBlueBright:e("\x1B[104m","\x1B[49m"),bgMagentaBright:e("\x1B[105m","\x1B[49m"),bgCyanBright:e("\x1B[106m","\x1B[49m"),bgWhiteBright:e("\x1B[107m","\x1B[49m")}};vl.exports=Ap();vl.exports.createColors=Ap;});function VP(t){return ["string","number","boolean"].includes(typeof t)}function QP(t){return [true,false,0,1].includes(t)}function XP(t){return typeof t=="string"}var Op=I(()=>{});function ZP(...t){return e=>t.reduce((n,r)=>r(n),e)}function e$(...t){return e=>e.map(n=>t.reduce((r,s)=>s(r),n))}var Pp=I(()=>{});function $p(t){return Object.prototype.toString.call(t)==="[object Object]"}function Ip(t){return t!==null&&typeof t=="object"}function n$(t,e){let n={};for(let r in t)t[r]!==e[r]&&(n[r]=e[r]);return n}function qt(t,e,n=void 0){let r=typeof e=="string"?e.split(/[.[\]"]+/).filter(s=>s):e;if(r.length===0)return t;try{let[s,...i]=r;return !s||!(s in t)?n:qt(t[s],i,n)}catch{if(typeof n<"u")return n;throw new Error(`Invalid path: ${r.join(".")}`)}}function X_(t,e,n){let r=e;if(typeof r=="string"){let o=a=>a[0]==='"'&&a.at(-1)==='"';r=r.split(/[.[\]]+/).filter(a=>a).map(a=>Number.isNaN(Number(a))?a:Number(a)).map(a=>typeof a=="string"&&o(a)?a.slice(1,-1):a);}if(r.length===0)throw new Error("The path must have at least one entry in it");let[s,...i]=r;return i.length===0?(t[s]=n,t):(s in t||(t[s]=typeof i[0]=="number"?[]:{}),X_(t[s],i,n),t)}function r$(t,e){return e.reduce((n,r)=>(r in t&&(n[r]=t[r]),n),{})}function s$(t,e){let n=new Set(e),r={};for(let[s,i]of Object.entries(t))n.has(s)||(r[s]=i);return r}function Pl(t,...e){for(let n of e)for(let[r,s]of Object.entries(n))s!==void 0&&(!$p(s)&&!Array.isArray(s)||Array.isArray(s)&&!Array.isArray(t[r])?t[r]=s:Ip(t[r])?Pl(t[r],s):t[r]=s);return t}function Y_(t,e,n){for(let[r,s]of Object.entries(e)){let i=n(t[r],s,r,t,e);if(i!==void 0){t[r]=i;continue}s!==void 0&&(!$p(s)&&!Array.isArray(s)||Array.isArray(s)&&!Array.isArray(t[r])?t[r]=s:Ip(t[r])?Y_(t[r],s,n):t[r]=s);}return t}function Ol(t,e){let n=s=>{if(s!==Object(s))return "primitive";if(Array.isArray(s))return "array";if(s instanceof Map)return "map";if(s!=null&&[null,Object.prototype].includes(Object.getPrototypeOf(s)))return "plainObject";if(s instanceof Function)return "function";throw new Error(`deeply comparing an instance of type ${t.constructor?.name} is not supported.`)},r=n(t);if(r!==n(e))return false;if(r==="primitive")return t===e||Number.isNaN(t)&&Number.isNaN(e);if(r==="array")return t.length===e.length&&t.every((s,i)=>Ol(s,e[i]));if(r==="map")return t.size===e.size&&[...t].every(([s,i])=>e.has(s)&&Ol(i,e.get(s)));if(r==="plainObject"){let s=new Map(Object.entries(t)),i=new Map(Object.entries(e));return s.size===i.size&&[...s].every(([o,a])=>i.has(o)&&Ol(a,i.get(o)))}else {if(r==="function")return t.toString()===e.toString();throw new Error("Unreachable")}}function Np(...t){let[e,n,r]=t;return JSON.stringify(e,(s,i)=>typeof i=="bigint"?Number.parseInt(i.toString(),10):i instanceof Map?Object.fromEntries(i.entries()):i instanceof Set?Array.from(i):n&&typeof n=="function"?n(s,i):i,r)}var Vr=I(()=>{});function o$(t){let e=t instanceof Request?new URL(t.url).searchParams:t;return Object.fromEntries(e.entries())}function a$(t,e){let n=t instanceof Request?new URL(t.url).searchParams:t,r={};for(let[s,i]of n.entries())e(s,i)&&(r[s]=i);return r}var Dp=I(()=>{});function jp(){try{return !$l()&&global?.process?.release?.name==="node"}catch{return false}}function $l(){try{return typeof Bun<"u"}catch{return false}}function Lp(){try{return typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"}catch{return false}}function Fp(t,e){if(!t)throw new Error(e)}function c$(t,e){try{return t(),!1}catch(n){if(e){if(n instanceof e)return true;throw n}return true}}async function u$(t,e){try{return await t,!1}catch(n){if(e){if(n instanceof e)return true;throw n}return true}}function f$(t,e){try{return t()}catch{return e}}async function d$(t,e){let n=performance.now();await t();let r=performance.now();e(r-n);}var p$,Il=I(()=>{p$={Map:t=>t instanceof Map?t:new Map(typeof t=="object"&&t!==null?Object.entries(t):[]),Set:t=>t instanceof Set?t:new Set(Array.isArray(t)?t:[]),Array:t=>Array.isArray(t)?t:["string","number","boolean"].includes(typeof t)?[t]:[]};});function Qr(t,e={}){return t.split(`
13
13
  `).map(n=>n.trim()).filter(n=>n.length>0).filter(n=>!n.startsWith(e.comments??"--")).join(`
14
- `)}function l$(t,e=true){return (e?Qr(t):t).split(";").filter(Boolean)}function Fp(t){let e=[],n="",r=0,s=t.length,i=false,o=false,a=0,l=/^create(\s+or\s+replace)?(\s+temp(orary)?)?$/i,c=u=>{Lp(u).length>0&&e.push(u.trim());},f=()=>{i=false,o=false,a=0;};for(;r<s;){let u=t[r],d=t[r+1];if(u==="-"&&d==="-"){for(;r<s&&t[r]!==`
15
- `;)n+=t[r],r++;continue}if(u==="/"&&d==="*"){for(n+="/*",r+=2;r<s&&!(t[r]==="*"&&t[r+1]==="/");)n+=t[r],r++;r<s&&(n+="*/",r+=2);continue}if(u==="'"){for(n+=u,r++;r<s;){if(t[r]==="'"&&t[r+1]==="'"){n+="''",r+=2;continue}if(n+=t[r],t[r]==="'"){r++;break}r++;}continue}if(u==='"'){for(n+=u,r++;r<s;){if(t[r]==='"'&&t[r+1]==='"'){n+='""',r+=2;continue}if(n+=t[r],t[r]==='"'){r++;break}r++;}continue}if(u==="$"){let p=t.indexOf("$",r+1);if(p!==-1){let g=t.slice(r,p+1);if(/^\$[A-Za-z_][A-Za-z0-9_]*\$$|^\$\$$/.test(g)){n+=g,r=p+1;let h=t.indexOf(g,r);h===-1?(n+=t.slice(r),r=s):(n+=t.slice(r,h+g.length),r=h+g.length);continue}}}if(/[A-Za-z_]/.test(u)){let p=r;for(;p<s&&/[A-Za-z0-9_]/.test(t[p]);)p++;let g=t.slice(r,p),m=g.toLowerCase();if(m==="trigger"&&l.test(Lp(n))?i=true:i&&m==="begin"?(o=true,a++):i&&o&&m==="case"?a++:i&&o&&m==="end"&&a>0&&a--,n+=g,r=p,i&&o&&a===0){let h=r;for(;h<s&&/\s/.test(t[h]);)h++;t[h]===";"&&(r=h+1),c(n),n="",f();}continue}if(u===";"){if(i&&o&&a>0){n+=u,r++;continue}c(n),n="",f(),r++;continue}n+=u,r++;}return c(n),e}function Lp(t){let e="",n=0,r=t.length;for(;n<r;){let s=t[n],i=t[n+1];if(s==="-"&&i==="-"){for(;n<r&&t[n]!==`
16
- `;)n++;continue}if(s==="/"&&i==="*"){for(n+=2;n<r&&!(t[n]==="*"&&t[n+1]==="/");)n++;n+=2;continue}e+=s,n++;}return e.trim()}function $l(t){return (t??"").trim().toLowerCase()}function Up(t,e){let n=e.toLowerCase();return t.startsWith("'")?n.includes("text")||n.includes("char")||n.includes("clob"):/^-?\d+$/.test(t)?n.includes("int"):n.includes("real")||n.includes("floa")||n.includes("doub")||n.includes("num")||n.includes("dec")}function to(t){let e=(t??"").replace(/\s+/g," ").replace(/"/g,"").trim().toLowerCase(),n;do n=e,e=e.replace(z_,(r,s,i)=>Up(s,i)?s:r);while(e!==n);do n=e,e=e.replace(V_,"$1");while(e!==n);return e}function X_(t,e,n){let r=0;for(let s=e;s<t.length;s++){let i=t[s];if(i==="'"){for(s++;s<t.length;){if(t[s]==="'"&&t[s+1]==="'"){s+=2;continue}if(t[s]==="'")break;s++;}continue}if(i==="("?r++:i===")"&&r--,r!==0)continue;let o=t[s-1];if(!(o&&/[a-z0-9_]/.test(o)))for(let a of n){if(t.slice(s,s+a.length)!==a)continue;let l=t[s+a.length];if(!(l&&/[a-z0-9_]/.test(l)))return {index:s,kw:a}}}return null}function Z_(t){let e=[],n=0;for(;;){let c=X_(t,n,Y_);if(!c)break;e.push(c),n=c.index+c.kw.length;}if(e.length===0)return {head:t,checks:[],uniques:[]};let r=t.slice(0,e[0].index).trim(),s=r.split(/\s+/)[0]??"",i=[],o=[],a=0;for(let c=0;c<e.length;c++){let f=e[c].index,u=c+1<e.length?e[c+1].index:t.length,d=t.slice(f,u).trim();e[c].kw==="check"?o.push(d):e[c].kw==="unique"&&!d.includes("(")?a++:i.push(d);}i.sort();let l=s?Array(a).fill(`unique (${s})`):[];return {head:[r,...i].join(" ").trim(),checks:o,uniques:l}}function Il(t){let e=to(t),n=e.indexOf("(");if(n===-1)return null;let r=Pl(e,n);if(r===-1)return null;let s=e.slice(n+1,r),i=e.slice(r+1).replace(/\s+/g," ").trim(),o=[];/\bstrict\b/.test(i)&&o.push("strict"),/\bwithout\s+rowid\b/.test(i)&&o.push("without rowid");let a=[],l=0,c="";for(let u=0;u<s.length;u++){let d=s[u];if(d==="'"){for(c+=d,u++;u<s.length;){if(s[u]==="'"&&s[u+1]==="'"){c+="''",u+=2;continue}if(c+=s[u],s[u]==="'")break;u++;}continue}if(d==="("?l++:d===")"&&l--,d===","&&l===0){a.push(c.trim()),c="";continue}c+=d;}c.trim().length>0&&a.push(c.trim());let f=[];for(let u of a){let d=u.replace(Q_,"");if(/^(primary key|unique|check|foreign key)\b/i.test(d)){f.push(d);continue}let{head:p,checks:g,uniques:m}=Z_(d);f.push(p,...g,...m);}return o.length>0&&f.push(`table options: ${o.join(", ")}`),f}function Pl(t,e){let n=0;for(let r=e;r<t.length;r++){let s=t[r];if(s==="'"){for(r++;r<t.length;){if(t[r]==="'"&&t[r+1]==="'"){r+=2;continue}if(t[r]==="'")break;r++;}continue}if(s==="(")n++;else if(s===")"&&(n--,n===0))return r}return -1}function eE(t){let e=0,n=-1;for(let r=0;r<t.length;r++){let s=t[r];if(s==="'"){for(r++;r<t.length;){if(t[r]==="'"&&t[r+1]==="'"){r+=2;continue}if(t[r]==="'")break;r++;}continue}s==="("?e++:s===")"?e--:e===0&&/^\s+as\s/i.test(t.slice(r))&&(n=r);}return n}function tE(t){return t.startsWith("'")&&t.endsWith("'")&&t.length>=2||/^-?\d+(\.\d+)?$/.test(t)}function Mp(t){let e=t.trim();for(;;){if(e.startsWith("(")&&Pl(e,0)===e.length-1){e=e.slice(1,-1).trim();continue}if(/^cast\s*\(/i.test(e)){let n=e.indexOf("(");if(Pl(e,n)===e.length-1){let r=e.slice(n+1,-1),s=eE(r);if(s!==-1){let i=r.slice(0,s).trim(),o=r.slice(s).replace(/^\s+as\s+/i,"").trim(),a=Mp(i);if(tE(a)&&Up(a,o)){e=a;continue}}}}break}return e}function Nl(t){if(t==null)return null;let e=Mp(t);if(e.startsWith("'")&&e.endsWith("'")&&e.length>=2){let n=e.slice(1,-1);/(?<!')'(?!')/.test(n)||(e=n);}else if(e.startsWith('"')&&e.endsWith('"')&&e.length>=2){let n=e.slice(1,-1);n.includes('"')||(e=n);}return e}var z_,V_,Q_,Y_,Un=I(()=>{z_=/\bcast\s*\(\s*('(?:[^']|'')*'|-?\d+(?:\.\d+)?)\s+as\s+([a-z][a-z0-9 ]*)\)/g,V_=/\(\s*('(?:[^']|'')*'|-?\d+(?:\.\d+)?)\s*\)/g;Q_=/\bconstraint\s+\S+\s+(?=(primary key|unique|check|foreign key|references)\b)/gi,Y_=["generated always as","not null","primary key","foreign key","references","default","unique","check","collate","null"];});function u$(t){return typeof t=="number"?t:Number.parseInt(String(t),10)}var Bp=I(()=>{});function d$(){return crypto.randomUUID()}var qp=I(()=>{});var Yr=I(()=>{vp();Ap();Vr();Ip();Ol();Un();Fn();Bp();qp();});var dn,no=I(()=>{st();dn=class extends ie{get sqliteType(){return "INTEGER"}};});var Xr,Dl=I(()=>{no();Xr=class extends dn{constructor(e){super({...e,isSerial:true});}};});function sE(t,e){let{precision:n,scale:r}=e,s=10**r,i=10**(n-r);return Math.abs(Math.round(t*s)-t*s)<1e-4&&Math.abs(t)<i}var Zr,jl=I(()=>{st();Zr=class extends ie{numericPrecision;constructor(e,n){super(e),this.numericPrecision=n;}get isShimBacked(){return this.numericPrecision!==void 0}get sqliteType(){return "REAL"}checkConstraint(){if(this.numericPrecision){let{precision:e,scale:n}=this.numericPrecision,r=this.context.column,s=10**n,i=10**(e-n);return `ABS(ROUND(${r} * ${s}) - ${r} * ${s}) < 0.0001 AND ABS(${r}) < ${i}`}return null}validateStorage(e){if(this.isNullish(e))return this.validationPass();if(typeof e!="number"||!Number.isFinite(e))return this.validationFail("Expected finite number.","Patch rows with finite numbers.");if(this.numericPrecision){let{precision:n,scale:r}=this.numericPrecision;if(!sE(e,this.numericPrecision))return this.validationFail(`Does not fit numeric(${n}, ${r}).`,"Patch rows within numeric precision.")}return this.validationPass()}};});var ae,Ze=I(()=>{st();ae=class extends ie{lengthConstraint;constructor(e,n){super(e),this.lengthConstraint=n;}get isShimBacked(){return this.lengthConstraint!==void 0}get sqliteType(){return "TEXT"}checkConstraint(){return this.lengthConstraint!==void 0?`length(${this.context.column}) <= ${this.lengthConstraint}`:null}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"?this.validationFail("Expected text.","Patch rows with text values."):this.lengthConstraint!==void 0&&Array.from(e).length>this.lengthConstraint?this.validationFail(`Exceeds length ${this.lengthConstraint}.`,"Patch rows with shorter text."):this.validationPass()}};});var es,Ll=I(()=>{st();es=class extends ie{get sqliteType(){return "BLOB"}};});var ts,Fl=I(()=>{st();ts=class extends ie{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}checkConstraint(){return `${this.context.column} IN (0, 1)`}serialize(e){if(this.isNullish(e))return e;if(e===true||e===1)return 1;if(e===false||e===0)return 0;throw this.checkError("boolean_range",e)}deserialize(e){if(this.isNullish(e)||e===true||e===false)return e;if(typeof e=="number"&&Number.isFinite(e)){if(e===1)return true;if(e===0)return false}return e===1n?true:e===0n?false:e==="1"||e==="true"?true:e==="0"||e==="false"?false:e}validateStorage(e){return this.isNullish(e)?this.validationPass():e===1||e===0?this.validationPass():this.validationFail("Expected 0 or 1.","Patch rows with boolean values.")}};});function Wp(t){try{return {ok:!0,value:JSON.parse(t)}}catch{return {ok:false}}}var ns,Ul=I(()=>{st();ns=class extends ie{get isShimBacked(){return true}get sqliteType(){return "TEXT"}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR json_valid(${e})`}serialize(e){if(this.isNullish(e))return e;try{return JSON.stringify(e)}catch{throw this.checkError("json_valid",e)}}deserialize(e){if(this.isNullish(e))return e;if(typeof e=="string"){let n=Wp(e);return n.ok?n.value:e}return e}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"?this.validationFail("Expected JSON text.","Patch rows with JSON values."):Wp(e).ok?this.validationPass():this.validationFail("Invalid JSON text.","Patch rows with valid JSON.")}};});function iE(t){if(!/^\d{4}-\d{2}-\d{2}$/.test(t))return false;let e=new Date(`${t}T00:00:00.000Z`);return !Number.isNaN(e.getTime())&&e.toISOString().slice(0,10)===t}var rs,Ml=I(()=>{Ze();rs=class extends ae{get isShimBacked(){return true}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR date(${e}) IS NOT NULL`}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!iE(e)?this.validationFail("Invalid date.","Patch rows with YYYY-MM-DD dates."):this.validationPass()}};});function oE(t){let e=t.match(/^(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?([+-](\d{2}):?(\d{2}))?$/);if(!e)return false;let n=Number(e[1]),r=Number(e[2]),s=e[3]===void 0?0:Number(e[3]),i=e[5]===void 0?null:Number(e[5]),o=e[6]===void 0?null:Number(e[6]),a=i===null||o!==null&&i<=15&&o<=59;return n<=24&&r<=59&&s<=59&&(n!==24||r===0&&s===0)&&a}var ss,Bl=I(()=>{Ze();ss=class extends ae{get isShimBacked(){return true}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR time(${e}) IS NOT NULL`}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!oE(e)?this.validationFail("Invalid time.","Patch rows with HH:MM[:SS] times."):this.validationPass()}};});function aE(t){let e=t.match(/^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?(?:Z|([+-](\d{2}):?(\d{2})))?$/);if(!e)return false;let n=Number(e[1]),r=Number(e[2]),s=Number(e[3]),i=Number(e[4]),o=Number(e[5]),a=e[6]===void 0?0:Number(e[6]),l=e[8]===void 0?null:Number(e[8]),c=e[9]===void 0?null:Number(e[9]),f=new Date(Date.UTC(n,r-1,s)),u=f.getUTCFullYear()===n&&f.getUTCMonth()===r-1&&f.getUTCDate()===s,d=i<=24&&o<=59&&a<=59&&(i!==24||o===0&&a===0),p=l===null||c!==null&&l<=15&&c<=59;return u&&d&&p}var is,ql=I(()=>{Ze();is=class extends ae{get isShimBacked(){return true}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR datetime(${e}) IS NOT NULL`}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!aE(e)?this.validationFail("Invalid timestamp.","Patch rows with ISO timestamps."):this.validationPass()}};});var os,Hl=I(()=>{Ze();os=class extends ae{get isShimBacked(){return true}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||e.trim().length===0?this.validationFail("Expected interval text.","Patch rows with interval strings."):/^-?\d+(?:\.\d+)?$/.test(e.trim())?this.validationFail("Ambiguous numeric interval.","Patch rows with explicit interval strings."):this.validationPass()}};});var as,Wl=I(()=>{Ze();as=class extends ae{enumValues;constructor(e,n){super(e),this.enumValues=n;}get isShimBacked(){return true}checkConstraint(){let e=this.context.column,n=this.enumValues.map(r=>`'${r.replace(/'/g,"''")}'`).join(", ");return `${e} IN (${n})`}serialize(e){if(this.isNullish(e))return e;if(typeof e!="string"||!this.enumValues.includes(e))throw this.checkError("enum_membership",e);return e}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!this.enumValues.includes(e)?this.validationFail("Invalid enum value.","Patch rows with declared enum values."):this.validationPass()}};});function Kp(t){try{return {ok:!0,value:JSON.parse(t)}}catch{return {ok:false}}}var Mn,Kl=I(()=>{st();Mn=class extends ie{elementField;constructor(e,n){super(e),this.elementField=n;}get sqliteType(){return "TEXT"}get isShimBacked(){return true}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR (json_valid(${e}) AND json_type(${e}) = 'array')`}serialize(e){if(this.isNullish(e))return e;if(!Array.isArray(e))throw this.checkError("array_type",e);return this.elementField?JSON.stringify(e.map(n=>this.elementField.serialize(n))):JSON.stringify(e)}deserialize(e){if(this.isNullish(e))return e;if(typeof e=="string"){let n=Kp(e);if(n.ok&&Array.isArray(n.value))return this.elementField?n.value.map(r=>this.elementField.deserialize(r)):n.value}return e}validateStorage(e){if(this.isNullish(e))return this.validationPass();if(typeof e!="string")return this.validationFail("Expected JSON array text.","Patch rows with array values.");let n=Kp(e);if(!n.ok)return this.validationFail("Invalid JSON array text.","Patch rows with array values.");if(!Array.isArray(n.value))return this.validationFail("Expected JSON array.","Patch rows with array values.");if(this.elementField)for(let r of n.value){let s=this.elementField.validateStorage(r);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 Jp(t){return cE.test(t.toLowerCase())}var lE,cE,ls,Jl=I(()=>{Ze();lE="????????-????-????-????-????????????",cE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;ls=class extends ae{get isShimBacked(){return true}checkConstraint(){let e=this.quoteIfNeeded(this.context.column);return `${e} IS NULL OR ${e} GLOB '${lE}'`}serialize(e){if(this.isNullish(e))return e;if(typeof e!="string")throw this.checkError("uuid_format",e);let n=e.toLowerCase();if(!Jp(n))throw this.checkError("uuid_format",e);return n}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!Jp(e)?this.validationFail("Invalid UUID.","Patch rows with valid UUIDs."):this.validationPass()}};});function uE(t){let e=t.split("/");if(e.length>2)return null;let n=e[0];if(!n)return null;if(e.length===1)return {address:n,prefix:null};let r=e[1];return !r||!/^\d+$/.test(r)?null:{address:n,prefix:Number(r)}}function fE(t){let e=t.split(".");return e.length!==4?false:e.every(n=>{if(!/^\d+$/.test(n))return false;let r=Number(n);return r>=0&&r<=255})}function dE(t){if(!t.includes(":"))return false;try{return new URL(`http://[${t}]/`),!0}catch{return false}}function Gp(t){let e=uE(t);return e?fE(e.address)?e.prefix===null||e.prefix>=0&&e.prefix<=32:dE(e.address)?e.prefix===null||e.prefix>=0&&e.prefix<=128:false:false}var cs,Gl=I(()=>{Ze();cs=class extends ae{get isShimBacked(){return true}checkConstraint(){let e=this.quoteIfNeeded(this.context.column);return `${e} IS NULL OR (length(${e}) BETWEEN 3 AND 49 AND (instr(${e}, '.') > 0 OR instr(${e}, ':') > 0))`}serialize(e){if(this.isNullish(e))return e;if(typeof e!="string")throw this.checkError("inet_format",e);let n=e.trim();if(!Gp(n))throw this.checkError("inet_format",e);return n}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!Gp(e.trim())?this.validationFail("Invalid inet address.","Patch rows with valid inet strings."):this.validationPass()}};});var us,zl=I(()=>{Ze();us=class extends ae{serialize(e){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}deserialize(e){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}toColumnDDL(){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}};});function We(t,e){let n=kE(t,e);if(e){let{enumValues:r,...s}=e;n.factoryExtra=s;}return n}function kE(t,e){if(e?.isArray){let r=We(t,{...e,isArray:false});return new Mn(t,r)}if(e?.enumValues)return new as(t,e.enumValues);let n=t.pgTypeName.toLowerCase().trim();if(n.startsWith("_")||n.endsWith("[]")){let r=n.startsWith("_")?n.slice(1):n.slice(0,-2),s={...t,pgTypeName:r},i=We(s);return new Mn(t,i)}return mE.has(n)?new Xr(t):pE.has(n)?new dn(t):bE.has(n)?new ts(t):wE.has(n)?new ns(t):xE.has(n)?new rs(t):TE.has(n)?new ss(t):RE.has(n)?new is(t):CE.has(n)?new os(t):yE.has(n)?new es(t):hE.has(n)?new Zr(t,e?.numericPrecision):SE.has(n)?new ls(t):_E.has(n)?new ae(t,63):EE.has(n)?new cs(t):gE.has(n)?new ae(t,e?.lengthConstraint):new us(t)}var pE,mE,hE,gE,yE,bE,wE,SE,_E,EE,xE,TE,RE,CE,ro=I(()=>{no();Dl();jl();Ze();Ll();Fl();Ul();Ml();Bl();ql();Hl();Wl();Kl();Jl();Gl();zl();pE=new Set(["int2","smallint","int4","integer","int","int8","bigint"]),mE=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]),hE=new Set(["float4","real","float8","double precision","numeric","decimal"]),gE=new Set(["text","varchar","character varying","char","character","bpchar"]),yE=new Set(["bytea"]),bE=new Set(["bool","boolean"]),wE=new Set(["json","jsonb"]),SE=new Set(["uuid"]),_E=new Set(["name"]),EE=new Set(["inet"]),xE=new Set(["date"]),TE=new Set(["time","timetz","time without time zone","time with time zone"]),RE=new Set(["timestamp","timestamptz","timestamp without time zone","timestamp with time zone"]),CE=new Set(["interval"]);});function Vl(t,e="auto"){let n=t.toLowerCase(),r=so[n];if(!r)return null;switch(e){case "translate":{if(!r.sqlite)throw new Error(`No SQLite translation for function "${t}"`);return {sqliteExpr:r.sqlite(),jsFn:null}}case "synthetic":{if(!r.js)throw new Error(`No JS implementation for function "${t}"`);return {sqliteExpr:null,jsFn:r.js}}case "auto":return r.js?{sqliteExpr:null,jsFn:r.js}:r.sqlite?{sqliteExpr:r.sqlite(),jsFn:null}:null}}var zp,so,Ql=I(()=>{zp="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)))",so={gen_random_uuid:{sqlite:()=>zp,js:()=>crypto.randomUUID()},uuid_generate_v4:{sqlite:()=>zp,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 at,Yl=I(()=>{at=class{table;schema;fields;constructor(e,n="public",r=new Map){this.table=e,this.schema=n,this.fields=r;}get(e){return this.fields.get(e)}has(e){return this.fields.has(e)}set(e,n){this.fields.set(e,n);}columns(){return Array.from(this.fields.keys())}all(){return Array.from(this.fields.values())}serializeRow(e){let n={};for(let[r,s]of Object.entries(e)){let i=this.fields.get(r);n[r]=i?i.serialize(s):s;}return n}deserializeRow(e){let n={};for(let[r,s]of Object.entries(e)){let i=this.fields.get(r);n[r]=i?i.deserialize(s):s;}return n}applyDefaults(e){let n={...e};for(let[r,s]of this.fields)!(r in n)&&s.context.defaultFn&&(n[r]=s.context.defaultFn());return n}};});var Xl=I(()=>{st();ki();no();Dl();jl();Ze();Ll();Fl();Ul();Ml();Bl();ql();Hl();Wl();Kl();Jl();Gl();zl();ro();Ql();Yl();});var Kh={};Zs(Kh,{AwsClient:()=>Dc,AwsV4Signer:()=>_o});async function _s(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?Nc.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},false,["sign"]);return crypto.subtle.sign("HMAC",n,Nc.encode(e))}async function qh(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?Nc.encode(t):t)}function Ic(t){let e=new Uint8Array(t),n="";for(let r=0;r<e.length;r++){let s=e[r];n+=Hh[s>>>4&15],n+=Hh[s&15];}return n}function Wh(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}function ST(t,e){let{hostname:n,pathname:r}=t;if(n.endsWith(".on.aws")){let a=n.match(/^[^.]{1,63}\.lambda-url\.([^.]{1,63})\.on\.aws$/);return a!=null?["lambda",a[1]||""]:["",""]}if(n.endsWith(".r2.cloudflarestorage.com"))return ["s3","auto"];if(n.endsWith(".backblazeb2.com")){let a=n.match(/^(?:[^.]{1,63}\.)?s3\.([^.]{1,63})\.backblazeb2\.com$/);return a!=null?["s3",a[1]||""]:["",""]}let s=n.replace("dualstack.","").match(/([^.]{1,63})\.(?:([^.]{0,63})\.)?amazonaws\.com(?:\.cn)?$/),i=s&&s[1]||"",o=s&&s[2];if(o==="us-gov")o="us-gov-west-1";else if(o==="s3"||o==="s3-accelerate")o="us-east-1",i="s3";else if(i==="iot")n.startsWith("iot.")?i="execute-api":n.startsWith("data.jobs.iot.")?i="iot-jobs-data":i=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(i==="autoscaling"){let a=(e.get("X-Amz-Target")||"").split(".")[0];a==="AnyScaleFrontendService"?i="application-autoscaling":a==="AnyScaleScalingPlannerFrontendService"&&(i="autoscaling-plans");}else o==null&&i.startsWith("s3-")?(o=i.slice(3).replace(/^fips-|^external-1/,""),i="s3"):i.endsWith("-fips")?i=i.slice(0,-5):o&&/-\d$/.test(i)&&!/-\d$/.test(o)&&([i,o]=[o,i]);return [bT[i]||i,o||""]}var Nc,bT,wT,Dc,_o,Hh,Jh=I(()=>{Nc=new TextEncoder,bT={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},wT=new Set(["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"]),Dc=class{constructor({accessKeyId:e,secretAccessKey:n,sessionToken:r,service:s,region:i,cache:o,retries:a,initRetryMs:l}){if(e==null)throw new TypeError("accessKeyId is a required option");if(n==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=n,this.sessionToken=r,this.service=s,this.region=i,this.cache=o||new Map,this.retries=a??10,this.initRetryMs=l||50;}async sign(e,n){if(e instanceof Request){let{method:i,url:o,headers:a,body:l}=e;n=Object.assign({method:i,url:o,headers:a},n),n.body==null&&a.has("Content-Type")&&(n.body=l!=null&&a.has("X-Amz-Content-Sha256")?l:await e.clone().arrayBuffer()),e=o;}let r=new _o(Object.assign({url:e.toString()},n,this,n&&n.aws)),s=Object.assign({},n,await r.sign());delete s.aws;try{return new Request(s.url.toString(),s)}catch(i){if(i instanceof TypeError)return new Request(s.url.toString(),Object.assign({duplex:"half"},s));throw i}}async fetch(e,n){for(let r=0;r<=this.retries;r++){let s=fetch(await this.sign(e,n));if(r===this.retries)return s;let i=await s;if(i.status<500&&i.status!==429)return i;await new Promise(o=>setTimeout(o,Math.random()*this.initRetryMs*Math.pow(2,r)));}throw new Error("An unknown error occurred, ensure retries is not negative")}},_o=class{constructor({method:e,url:n,headers:r,body:s,accessKeyId:i,secretAccessKey:o,sessionToken:a,service:l,region:c,cache:f,datetime:u,signQuery:d,appendSessionToken:p,allHeaders:g,singleEncode:m}){if(n==null)throw new TypeError("url is a required option");if(i==null)throw new TypeError("accessKeyId is a required option");if(o==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(s?"POST":"GET"),this.url=new URL(n),this.headers=new Headers(r||{}),this.body=s,this.accessKeyId=i,this.secretAccessKey=o,this.sessionToken=a;let h,y;(!l||!c)&&([h,y]=ST(this.url,this.headers)),this.service=l||h||"",this.region=c||y||"us-east-1",this.cache=f||new Map,this.datetime=u||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=d,this.appendSessionToken=p||this.service==="iotdevicegateway",this.headers.delete("Host"),this.service==="s3"&&!this.signQuery&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD");let w=this.signQuery?this.url.searchParams:this.headers;if(w.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&w.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(b=>g||!wT.has(b)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(b=>b+":"+(b==="host"?this.url.host:(this.headers.get(b)||"").replace(/\s+/g," "))).join(`
17
- `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!w.has("X-Amz-Expires")&&w.set("X-Amz-Expires","86400"),w.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),w.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),w.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "));}catch{this.encodedPath=this.url.pathname;}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");m||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=Wh(this.encodedPath);let S=new Set;this.encodedSearch=[...this.url.searchParams].filter(([b])=>{if(!b)return false;if(this.service==="s3"){if(S.has(b))return false;S.add(b);}return true}).map(b=>b.map(_=>Wh(encodeURIComponent(_)))).sort(([b,_],[E,x])=>b<E?-1:b>E?1:_<x?-1:_>x?1:0).map(b=>b.join("=")).join("&");}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return ["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),n=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(n);if(!r){let s=await _s("AWS4"+this.secretAccessKey,e),i=await _s(s,this.region),o=await _s(i,this.service);r=await _s(o,"aws4_request"),this.cache.set(n,r);}return Ic(await _s(r,await this.stringToSign()))}async stringToSign(){return ["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Ic(await qh(await this.canonicalString()))].join(`
14
+ `)}function h$(t,e=true){return (e?Qr(t):t).split(";").filter(Boolean)}function Mp(t){let e=[],n="",r=0,s=t.length,i=false,o=false,a=0,l=/^create(\s+or\s+replace)?(\s+temp(orary)?)?$/i,c=u=>{Up(u).length>0&&e.push(u.trim());},f=()=>{i=false,o=false,a=0;};for(;r<s;){let u=t[r],d=t[r+1];if(u==="-"&&d==="-"){for(;r<s&&t[r]!==`
15
+ `;)n+=t[r],r++;continue}if(u==="/"&&d==="*"){for(n+="/*",r+=2;r<s&&!(t[r]==="*"&&t[r+1]==="/");)n+=t[r],r++;r<s&&(n+="*/",r+=2);continue}if(u==="'"){for(n+=u,r++;r<s;){if(t[r]==="'"&&t[r+1]==="'"){n+="''",r+=2;continue}if(n+=t[r],t[r]==="'"){r++;break}r++;}continue}if(u==='"'){for(n+=u,r++;r<s;){if(t[r]==='"'&&t[r+1]==='"'){n+='""',r+=2;continue}if(n+=t[r],t[r]==='"'){r++;break}r++;}continue}if(u==="$"){let p=t.indexOf("$",r+1);if(p!==-1){let g=t.slice(r,p+1);if(/^\$[A-Za-z_][A-Za-z0-9_]*\$$|^\$\$$/.test(g)){n+=g,r=p+1;let h=t.indexOf(g,r);h===-1?(n+=t.slice(r),r=s):(n+=t.slice(r,h+g.length),r=h+g.length);continue}}}if(/[A-Za-z_]/.test(u)){let p=r;for(;p<s&&/[A-Za-z0-9_]/.test(t[p]);)p++;let g=t.slice(r,p),m=g.toLowerCase();if(m==="trigger"&&l.test(Up(n))?i=true:i&&m==="begin"?(o=true,a++):i&&o&&m==="case"?a++:i&&o&&m==="end"&&a>0&&a--,n+=g,r=p,i&&o&&a===0){let h=r;for(;h<s&&/\s/.test(t[h]);)h++;t[h]===";"&&(r=h+1),c(n),n="",f();}continue}if(u===";"){if(i&&o&&a>0){n+=u,r++;continue}c(n),n="",f(),r++;continue}n+=u,r++;}return c(n),e}function Up(t){let e="",n=0,r=t.length;for(;n<r;){let s=t[n],i=t[n+1];if(s==="-"&&i==="-"){for(;n<r&&t[n]!==`
16
+ `;)n++;continue}if(s==="/"&&i==="*"){for(n+=2;n<r&&!(t[n]==="*"&&t[n+1]==="/");)n++;n+=2;continue}e+=s,n++;}return e.trim()}function Dl(t){return (t??"").trim().toLowerCase()}function Bp(t,e){let n=e.toLowerCase();return t.startsWith("'")?n.includes("text")||n.includes("char")||n.includes("clob"):/^-?\d+$/.test(t)?n.includes("int"):n.includes("real")||n.includes("floa")||n.includes("doub")||n.includes("num")||n.includes("dec")}function so(t){let e=(t??"").replace(/\s+/g," ").replace(/"/g,"").trim().toLowerCase(),n;do n=e,e=e.replace(Z_,(r,s,i)=>Bp(s,i)?s:r);while(e!==n);do n=e,e=e.replace(eE,"$1");while(e!==n);return e}function rE(t,e,n){let r=0;for(let s=e;s<t.length;s++){let i=t[s];if(i==="'"){for(s++;s<t.length;){if(t[s]==="'"&&t[s+1]==="'"){s+=2;continue}if(t[s]==="'")break;s++;}continue}if(i==="("?r++:i===")"&&r--,r!==0)continue;let o=t[s-1];if(!(o&&/[a-z0-9_]/.test(o)))for(let a of n){if(t.slice(s,s+a.length)!==a)continue;let l=t[s+a.length];if(!(l&&/[a-z0-9_]/.test(l)))return {index:s,kw:a}}}return null}function sE(t){let e=[],n=0;for(;;){let c=rE(t,n,nE);if(!c)break;e.push(c),n=c.index+c.kw.length;}if(e.length===0)return {head:t,checks:[],uniques:[]};let r=t.slice(0,e[0].index).trim(),s=r.split(/\s+/)[0]??"",i=[],o=[],a=0;for(let c=0;c<e.length;c++){let f=e[c].index,u=c+1<e.length?e[c+1].index:t.length,d=t.slice(f,u).trim();e[c].kw==="check"?o.push(d):e[c].kw==="unique"&&!d.includes("(")?a++:i.push(d);}i.sort();let l=s?Array(a).fill(`unique (${s})`):[];return {head:[r,...i].join(" ").trim(),checks:o,uniques:l}}function jl(t){let e=so(t),n=e.indexOf("(");if(n===-1)return null;let r=Nl(e,n);if(r===-1)return null;let s=e.slice(n+1,r),i=e.slice(r+1).replace(/\s+/g," ").trim(),o=[];/\bstrict\b/.test(i)&&o.push("strict"),/\bwithout\s+rowid\b/.test(i)&&o.push("without rowid");let a=[],l=0,c="";for(let u=0;u<s.length;u++){let d=s[u];if(d==="'"){for(c+=d,u++;u<s.length;){if(s[u]==="'"&&s[u+1]==="'"){c+="''",u+=2;continue}if(c+=s[u],s[u]==="'")break;u++;}continue}if(d==="("?l++:d===")"&&l--,d===","&&l===0){a.push(c.trim()),c="";continue}c+=d;}c.trim().length>0&&a.push(c.trim());let f=[];for(let u of a){let d=u.replace(tE,"");if(/^(primary key|unique|check|foreign key)\b/i.test(d)){f.push(d);continue}let{head:p,checks:g,uniques:m}=sE(d);f.push(p,...g,...m);}return o.length>0&&f.push(`table options: ${o.join(", ")}`),f}function Nl(t,e){let n=0;for(let r=e;r<t.length;r++){let s=t[r];if(s==="'"){for(r++;r<t.length;){if(t[r]==="'"&&t[r+1]==="'"){r+=2;continue}if(t[r]==="'")break;r++;}continue}if(s==="(")n++;else if(s===")"&&(n--,n===0))return r}return -1}function iE(t){let e=0,n=-1;for(let r=0;r<t.length;r++){let s=t[r];if(s==="'"){for(r++;r<t.length;){if(t[r]==="'"&&t[r+1]==="'"){r+=2;continue}if(t[r]==="'")break;r++;}continue}s==="("?e++:s===")"?e--:e===0&&/^\s+as\s/i.test(t.slice(r))&&(n=r);}return n}function oE(t){return t.startsWith("'")&&t.endsWith("'")&&t.length>=2||/^-?\d+(\.\d+)?$/.test(t)}function qp(t){let e=t.trim();for(;;){if(e.startsWith("(")&&Nl(e,0)===e.length-1){e=e.slice(1,-1).trim();continue}if(/^cast\s*\(/i.test(e)){let n=e.indexOf("(");if(Nl(e,n)===e.length-1){let r=e.slice(n+1,-1),s=iE(r);if(s!==-1){let i=r.slice(0,s).trim(),o=r.slice(s).replace(/^\s+as\s+/i,"").trim(),a=qp(i);if(oE(a)&&Bp(a,o)){e=a;continue}}}}break}return e}function Ll(t){if(t==null)return null;let e=qp(t);if(e.startsWith("'")&&e.endsWith("'")&&e.length>=2){let n=e.slice(1,-1);/(?<!')'(?!')/.test(n)||(e=n);}else if(e.startsWith('"')&&e.endsWith('"')&&e.length>=2){let n=e.slice(1,-1);n.includes('"')||(e=n);}return e}var Z_,eE,tE,nE,Un=I(()=>{Z_=/\bcast\s*\(\s*('(?:[^']|'')*'|-?\d+(?:\.\d+)?)\s+as\s+([a-z][a-z0-9 ]*)\)/g,eE=/\(\s*('(?:[^']|'')*'|-?\d+(?:\.\d+)?)\s*\)/g;tE=/\bconstraint\s+\S+\s+(?=(primary key|unique|check|foreign key|references)\b)/gi,nE=["generated always as","not null","primary key","foreign key","references","default","unique","check","collate","null"];});function y$(t){return typeof t=="number"?t:Number.parseInt(String(t),10)}var Hp=I(()=>{});function w$(){return crypto.randomUUID()}var Wp=I(()=>{});var Xr=I(()=>{Op();Pp();Vr();Dp();Il();Un();Fn();Hp();Wp();});var dn,io=I(()=>{st();dn=class extends ie{get sqliteType(){return "INTEGER"}};});var Yr,Fl=I(()=>{io();Yr=class extends dn{constructor(e){super({...e,isSerial:true});}};});function cE(t,e){let{precision:n,scale:r}=e,s=10**r,i=10**(n-r);return Math.abs(Math.round(t*s)-t*s)<1e-4&&Math.abs(t)<i}var Zr,Ul=I(()=>{st();Zr=class extends ie{numericPrecision;constructor(e,n){super(e),this.numericPrecision=n;}get isShimBacked(){return this.numericPrecision!==void 0}get sqliteType(){return "REAL"}checkConstraint(){if(this.numericPrecision){let{precision:e,scale:n}=this.numericPrecision,r=this.context.column,s=10**n,i=10**(e-n);return `ABS(ROUND(${r} * ${s}) - ${r} * ${s}) < 0.0001 AND ABS(${r}) < ${i}`}return null}validateStorage(e){if(this.isNullish(e))return this.validationPass();if(typeof e!="number"||!Number.isFinite(e))return this.validationFail("Expected finite number.","Patch rows with finite numbers.");if(this.numericPrecision){let{precision:n,scale:r}=this.numericPrecision;if(!cE(e,this.numericPrecision))return this.validationFail(`Does not fit numeric(${n}, ${r}).`,"Patch rows within numeric precision.")}return this.validationPass()}};});var ae,Ze=I(()=>{st();ae=class extends ie{lengthConstraint;constructor(e,n){super(e),this.lengthConstraint=n;}get isShimBacked(){return this.lengthConstraint!==void 0}get sqliteType(){return "TEXT"}checkConstraint(){return this.lengthConstraint!==void 0?`length(${this.context.column}) <= ${this.lengthConstraint}`:null}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"?this.validationFail("Expected text.","Patch rows with text values."):this.lengthConstraint!==void 0&&Array.from(e).length>this.lengthConstraint?this.validationFail(`Exceeds length ${this.lengthConstraint}.`,"Patch rows with shorter text."):this.validationPass()}};});var es,Ml=I(()=>{st();es=class extends ie{get sqliteType(){return "BLOB"}};});var ts,Bl=I(()=>{st();ts=class extends ie{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}checkConstraint(){return `${this.context.column} IN (0, 1)`}serialize(e){if(this.isNullish(e))return e;if(e===true||e===1)return 1;if(e===false||e===0)return 0;throw this.checkError("boolean_range",e)}deserialize(e){if(this.isNullish(e)||e===true||e===false)return e;if(typeof e=="number"&&Number.isFinite(e)){if(e===1)return true;if(e===0)return false}return e===1n?true:e===0n?false:e==="1"||e==="true"?true:e==="0"||e==="false"?false:e}validateStorage(e){return this.isNullish(e)?this.validationPass():e===1||e===0?this.validationPass():this.validationFail("Expected 0 or 1.","Patch rows with boolean values.")}};});function Jp(t){try{return {ok:!0,value:JSON.parse(t)}}catch{return {ok:false}}}var ns,ql=I(()=>{st();ns=class extends ie{get isShimBacked(){return true}get sqliteType(){return "TEXT"}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR json_valid(${e})`}serialize(e){if(this.isNullish(e))return e;try{return JSON.stringify(e)}catch{throw this.checkError("json_valid",e)}}deserialize(e){if(this.isNullish(e))return e;if(typeof e=="string"){let n=Jp(e);return n.ok?n.value:e}return e}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"?this.validationFail("Expected JSON text.","Patch rows with JSON values."):Jp(e).ok?this.validationPass():this.validationFail("Invalid JSON text.","Patch rows with valid JSON.")}};});function uE(t){if(!/^\d{4}-\d{2}-\d{2}$/.test(t))return false;let e=new Date(`${t}T00:00:00.000Z`);return !Number.isNaN(e.getTime())&&e.toISOString().slice(0,10)===t}var rs,Hl=I(()=>{Ze();rs=class extends ae{get isShimBacked(){return true}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR date(${e}) IS NOT NULL`}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!uE(e)?this.validationFail("Invalid date.","Patch rows with YYYY-MM-DD dates."):this.validationPass()}};});function fE(t){let e=t.match(/^(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?([+-](\d{2}):?(\d{2}))?$/);if(!e)return false;let n=Number(e[1]),r=Number(e[2]),s=e[3]===void 0?0:Number(e[3]),i=e[5]===void 0?null:Number(e[5]),o=e[6]===void 0?null:Number(e[6]),a=i===null||o!==null&&i<=15&&o<=59;return n<=24&&r<=59&&s<=59&&(n!==24||r===0&&s===0)&&a}var ss,Wl=I(()=>{Ze();ss=class extends ae{get isShimBacked(){return true}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR time(${e}) IS NOT NULL`}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!fE(e)?this.validationFail("Invalid time.","Patch rows with HH:MM[:SS] times."):this.validationPass()}};});function dE(t){let e=t.match(/^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?(?:Z|([+-](\d{2}):?(\d{2})))?$/);if(!e)return false;let n=Number(e[1]),r=Number(e[2]),s=Number(e[3]),i=Number(e[4]),o=Number(e[5]),a=e[6]===void 0?0:Number(e[6]),l=e[8]===void 0?null:Number(e[8]),c=e[9]===void 0?null:Number(e[9]),f=new Date(Date.UTC(n,r-1,s)),u=f.getUTCFullYear()===n&&f.getUTCMonth()===r-1&&f.getUTCDate()===s,d=i<=24&&o<=59&&a<=59&&(i!==24||o===0&&a===0),p=l===null||c!==null&&l<=15&&c<=59;return u&&d&&p}var is,Kl=I(()=>{Ze();is=class extends ae{get isShimBacked(){return true}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR datetime(${e}) IS NOT NULL`}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!dE(e)?this.validationFail("Invalid timestamp.","Patch rows with ISO timestamps."):this.validationPass()}};});var os,Jl=I(()=>{Ze();os=class extends ae{get isShimBacked(){return true}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||e.trim().length===0?this.validationFail("Expected interval text.","Patch rows with interval strings."):/^-?\d+(?:\.\d+)?$/.test(e.trim())?this.validationFail("Ambiguous numeric interval.","Patch rows with explicit interval strings."):this.validationPass()}};});var as,Gl=I(()=>{Ze();as=class extends ae{enumValues;constructor(e,n){super(e),this.enumValues=n;}get isShimBacked(){return true}checkConstraint(){let e=this.context.column,n=this.enumValues.map(r=>`'${r.replace(/'/g,"''")}'`).join(", ");return `${e} IN (${n})`}serialize(e){if(this.isNullish(e))return e;if(typeof e!="string"||!this.enumValues.includes(e))throw this.checkError("enum_membership",e);return e}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!this.enumValues.includes(e)?this.validationFail("Invalid enum value.","Patch rows with declared enum values."):this.validationPass()}};});function Gp(t){try{return {ok:!0,value:JSON.parse(t)}}catch{return {ok:false}}}var Mn,zl=I(()=>{st();Mn=class extends ie{elementField;constructor(e,n){super(e),this.elementField=n;}get sqliteType(){return "TEXT"}get isShimBacked(){return true}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR (json_valid(${e}) AND json_type(${e}) = 'array')`}serialize(e){if(this.isNullish(e))return e;if(!Array.isArray(e))throw this.checkError("array_type",e);return this.elementField?JSON.stringify(e.map(n=>this.elementField.serialize(n))):JSON.stringify(e)}deserialize(e){if(this.isNullish(e))return e;if(typeof e=="string"){let n=Gp(e);if(n.ok&&Array.isArray(n.value))return this.elementField?n.value.map(r=>this.elementField.deserialize(r)):n.value}return e}validateStorage(e){if(this.isNullish(e))return this.validationPass();if(typeof e!="string")return this.validationFail("Expected JSON array text.","Patch rows with array values.");let n=Gp(e);if(!n.ok)return this.validationFail("Invalid JSON array text.","Patch rows with array values.");if(!Array.isArray(n.value))return this.validationFail("Expected JSON array.","Patch rows with array values.");if(this.elementField)for(let r of n.value){let s=this.elementField.validateStorage(r);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 zp(t){return mE.test(t.toLowerCase())}var pE,mE,ls,Vl=I(()=>{Ze();pE="????????-????-????-????-????????????",mE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;ls=class extends ae{get isShimBacked(){return true}checkConstraint(){let e=this.quoteIfNeeded(this.context.column);return `${e} IS NULL OR ${e} GLOB '${pE}'`}serialize(e){if(this.isNullish(e))return e;if(typeof e!="string")throw this.checkError("uuid_format",e);let n=e.toLowerCase();if(!zp(n))throw this.checkError("uuid_format",e);return n}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!zp(e)?this.validationFail("Invalid UUID.","Patch rows with valid UUIDs."):this.validationPass()}};});function hE(t){let e=t.split("/");if(e.length>2)return null;let n=e[0];if(!n)return null;if(e.length===1)return {address:n,prefix:null};let r=e[1];return !r||!/^\d+$/.test(r)?null:{address:n,prefix:Number(r)}}function gE(t){let e=t.split(".");return e.length!==4?false:e.every(n=>{if(!/^\d+$/.test(n))return false;let r=Number(n);return r>=0&&r<=255})}function yE(t){if(!t.includes(":"))return false;try{return new URL(`http://[${t}]/`),!0}catch{return false}}function Vp(t){let e=hE(t);return e?gE(e.address)?e.prefix===null||e.prefix>=0&&e.prefix<=32:yE(e.address)?e.prefix===null||e.prefix>=0&&e.prefix<=128:false:false}var cs,Ql=I(()=>{Ze();cs=class extends ae{get isShimBacked(){return true}checkConstraint(){let e=this.quoteIfNeeded(this.context.column);return `${e} IS NULL OR (length(${e}) BETWEEN 3 AND 49 AND (instr(${e}, '.') > 0 OR instr(${e}, ':') > 0))`}serialize(e){if(this.isNullish(e))return e;if(typeof e!="string")throw this.checkError("inet_format",e);let n=e.trim();if(!Vp(n))throw this.checkError("inet_format",e);return n}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!Vp(e.trim())?this.validationFail("Invalid inet address.","Patch rows with valid inet strings."):this.validationPass()}};});var us,Xl=I(()=>{Ze();us=class extends ae{serialize(e){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}deserialize(e){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}toColumnDDL(){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}};});function We(t,e){let n=$E(t,e);if(e){let{enumValues:r,...s}=e;n.factoryExtra=s;}return n}function $E(t,e){if(e?.isArray){let r=We(t,{...e,isArray:false});return new Mn(t,r)}if(e?.enumValues)return new as(t,e.enumValues);let n=t.pgTypeName.toLowerCase().trim();if(n.startsWith("_")||n.endsWith("[]")){let r=n.startsWith("_")?n.slice(1):n.slice(0,-2),s={...t,pgTypeName:r},i=We(s);return new Mn(t,i)}return wE.has(n)?new Yr(t):bE.has(n)?new dn(t):xE.has(n)?new ts(t):TE.has(n)?new ns(t):vE.has(n)?new rs(t):AE.has(n)?new ss(t):OE.has(n)?new is(t):PE.has(n)?new os(t):EE.has(n)?new es(t):SE.has(n)?new Zr(t,e?.numericPrecision):RE.has(n)?new ls(t):CE.has(n)?new ae(t,63):kE.has(n)?new cs(t):_E.has(n)?new ae(t,e?.lengthConstraint):new us(t)}var bE,wE,SE,_E,EE,xE,TE,RE,CE,kE,vE,AE,OE,PE,oo=I(()=>{io();Fl();Ul();Ze();Ml();Bl();ql();Hl();Wl();Kl();Jl();Gl();zl();Vl();Ql();Xl();bE=new Set(["int2","smallint","int4","integer","int","int8","bigint"]),wE=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]),SE=new Set(["float4","real","float8","double precision","numeric","decimal"]),_E=new Set(["text","varchar","character varying","char","character","bpchar"]),EE=new Set(["bytea"]),xE=new Set(["bool","boolean"]),TE=new Set(["json","jsonb"]),RE=new Set(["uuid"]),CE=new Set(["name"]),kE=new Set(["inet"]),vE=new Set(["date"]),AE=new Set(["time","timetz","time without time zone","time with time zone"]),OE=new Set(["timestamp","timestamptz","timestamp without time zone","timestamp with time zone"]),PE=new Set(["interval"]);});function Yl(t,e="auto"){let n=t.toLowerCase(),r=ao[n];if(!r)return null;switch(e){case "translate":{if(!r.sqlite)throw new Error(`No SQLite translation for function "${t}"`);return {sqliteExpr:r.sqlite(),jsFn:null}}case "synthetic":{if(!r.js)throw new Error(`No JS implementation for function "${t}"`);return {sqliteExpr:null,jsFn:r.js}}case "auto":return r.js?{sqliteExpr:null,jsFn:r.js}:r.sqlite?{sqliteExpr:r.sqlite(),jsFn:null}:null}}var Qp,ao,Zl=I(()=>{Qp="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)))",ao={gen_random_uuid:{sqlite:()=>Qp,js:()=>crypto.randomUUID()},uuid_generate_v4:{sqlite:()=>Qp,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 at,ec=I(()=>{at=class{table;schema;fields;constructor(e,n="public",r=new Map){this.table=e,this.schema=n,this.fields=r;}get(e){return this.fields.get(e)}has(e){return this.fields.has(e)}set(e,n){this.fields.set(e,n);}columns(){return Array.from(this.fields.keys())}all(){return Array.from(this.fields.values())}serializeRow(e){let n={};for(let[r,s]of Object.entries(e)){let i=this.fields.get(r);n[r]=i?i.serialize(s):s;}return n}deserializeRow(e){let n={};for(let[r,s]of Object.entries(e)){let i=this.fields.get(r);n[r]=i?i.deserialize(s):s;}return n}applyDefaults(e){let n={...e};for(let[r,s]of this.fields)!(r in n)&&s.context.defaultFn&&(n[r]=s.context.defaultFn());return n}};});var tc=I(()=>{st();Oi();io();Fl();Ul();Ze();Ml();Bl();ql();Hl();Wl();Kl();Jl();Gl();zl();Vl();Ql();Xl();oo();Zl();ec();});var Gh={};Zs(Gh,{AwsClient:()=>Fc,AwsV4Signer:()=>To});async function _s(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?Lc.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},false,["sign"]);return crypto.subtle.sign("HMAC",n,Lc.encode(e))}async function Wh(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?Lc.encode(t):t)}function jc(t){let e=new Uint8Array(t),n="";for(let r=0;r<e.length;r++){let s=e[r];n+=Kh[s>>>4&15],n+=Kh[s&15];}return n}function Jh(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}function RT(t,e){let{hostname:n,pathname:r}=t;if(n.endsWith(".on.aws")){let a=n.match(/^[^.]{1,63}\.lambda-url\.([^.]{1,63})\.on\.aws$/);return a!=null?["lambda",a[1]||""]:["",""]}if(n.endsWith(".r2.cloudflarestorage.com"))return ["s3","auto"];if(n.endsWith(".backblazeb2.com")){let a=n.match(/^(?:[^.]{1,63}\.)?s3\.([^.]{1,63})\.backblazeb2\.com$/);return a!=null?["s3",a[1]||""]:["",""]}let s=n.replace("dualstack.","").match(/([^.]{1,63})\.(?:([^.]{0,63})\.)?amazonaws\.com(?:\.cn)?$/),i=s&&s[1]||"",o=s&&s[2];if(o==="us-gov")o="us-gov-west-1";else if(o==="s3"||o==="s3-accelerate")o="us-east-1",i="s3";else if(i==="iot")n.startsWith("iot.")?i="execute-api":n.startsWith("data.jobs.iot.")?i="iot-jobs-data":i=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(i==="autoscaling"){let a=(e.get("X-Amz-Target")||"").split(".")[0];a==="AnyScaleFrontendService"?i="application-autoscaling":a==="AnyScaleScalingPlannerFrontendService"&&(i="autoscaling-plans");}else o==null&&i.startsWith("s3-")?(o=i.slice(3).replace(/^fips-|^external-1/,""),i="s3"):i.endsWith("-fips")?i=i.slice(0,-5):o&&/-\d$/.test(i)&&!/-\d$/.test(o)&&([i,o]=[o,i]);return [xT[i]||i,o||""]}var Lc,xT,TT,Fc,To,Kh,zh=I(()=>{Lc=new TextEncoder,xT={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},TT=new Set(["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"]),Fc=class{constructor({accessKeyId:e,secretAccessKey:n,sessionToken:r,service:s,region:i,cache:o,retries:a,initRetryMs:l}){if(e==null)throw new TypeError("accessKeyId is a required option");if(n==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=n,this.sessionToken=r,this.service=s,this.region=i,this.cache=o||new Map,this.retries=a??10,this.initRetryMs=l||50;}async sign(e,n){if(e instanceof Request){let{method:i,url:o,headers:a,body:l}=e;n=Object.assign({method:i,url:o,headers:a},n),n.body==null&&a.has("Content-Type")&&(n.body=l!=null&&a.has("X-Amz-Content-Sha256")?l:await e.clone().arrayBuffer()),e=o;}let r=new To(Object.assign({url:e.toString()},n,this,n&&n.aws)),s=Object.assign({},n,await r.sign());delete s.aws;try{return new Request(s.url.toString(),s)}catch(i){if(i instanceof TypeError)return new Request(s.url.toString(),Object.assign({duplex:"half"},s));throw i}}async fetch(e,n){for(let r=0;r<=this.retries;r++){let s=fetch(await this.sign(e,n));if(r===this.retries)return s;let i=await s;if(i.status<500&&i.status!==429)return i;await new Promise(o=>setTimeout(o,Math.random()*this.initRetryMs*Math.pow(2,r)));}throw new Error("An unknown error occurred, ensure retries is not negative")}},To=class{constructor({method:e,url:n,headers:r,body:s,accessKeyId:i,secretAccessKey:o,sessionToken:a,service:l,region:c,cache:f,datetime:u,signQuery:d,appendSessionToken:p,allHeaders:g,singleEncode:m}){if(n==null)throw new TypeError("url is a required option");if(i==null)throw new TypeError("accessKeyId is a required option");if(o==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(s?"POST":"GET"),this.url=new URL(n),this.headers=new Headers(r||{}),this.body=s,this.accessKeyId=i,this.secretAccessKey=o,this.sessionToken=a;let h,y;(!l||!c)&&([h,y]=RT(this.url,this.headers)),this.service=l||h||"",this.region=c||y||"us-east-1",this.cache=f||new Map,this.datetime=u||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=d,this.appendSessionToken=p||this.service==="iotdevicegateway",this.headers.delete("Host"),this.service==="s3"&&!this.signQuery&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD");let w=this.signQuery?this.url.searchParams:this.headers;if(w.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&w.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(b=>g||!TT.has(b)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(b=>b+":"+(b==="host"?this.url.host:(this.headers.get(b)||"").replace(/\s+/g," "))).join(`
17
+ `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!w.has("X-Amz-Expires")&&w.set("X-Amz-Expires","86400"),w.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),w.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),w.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "));}catch{this.encodedPath=this.url.pathname;}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");m||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=Jh(this.encodedPath);let S=new Set;this.encodedSearch=[...this.url.searchParams].filter(([b])=>{if(!b)return false;if(this.service==="s3"){if(S.has(b))return false;S.add(b);}return true}).map(b=>b.map(_=>Jh(encodeURIComponent(_)))).sort(([b,_],[E,x])=>b<E?-1:b>E?1:_<x?-1:_>x?1:0).map(b=>b.join("=")).join("&");}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return ["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),n=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(n);if(!r){let s=await _s("AWS4"+this.secretAccessKey,e),i=await _s(s,this.region),o=await _s(i,this.service);r=await _s(o,"aws4_request"),this.cache.set(n,r);}return jc(await _s(r,await this.stringToSign()))}async stringToSign(){return ["AWS4-HMAC-SHA256",this.datetime,this.credentialString,jc(await Wh(await this.canonicalString()))].join(`
18
18
  `)}async canonicalString(){return [this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
19
19
  `,this.signedHeaders,await this.hexBodyHash()].join(`
20
- `)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256")||(this.service==="s3"&&this.signQuery?"UNSIGNED-PAYLOAD":null);if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new Error("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Ic(await qh(this.body||""));}return e}};Hh=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];});var ey=Hu((LU,NR)=>{NR.exports={"dev/vite/main.tsx":{file:"assets/main-1bwWb_1q.js",name:"main",src:"dev/vite/main.tsx",isEntry:true,css:["assets/main-BDsRycsc.css"]}};});var ku,_y,Ey,Ho=I(()=>{ku=(p=>(p.DISABLE_FOREIGN_KEYS="disable_foreign_keys",p.ENABLE_FOREIGN_KEYS="enable_foreign_keys",p.BEGIN_TRANSACTION="begin_transaction",p.COMMIT_TRANSACTION="commit_transaction",p.CREATE_TABLE="create_table",p.ADD_COLUMN="add_column",p.DROP_COLUMN="drop_column",p.ADD_INDEX="add_index",p.DROP_INDEX="drop_index",p.DROP_TABLE="drop_table",p.RENAME_TABLE="rename_table",p.COPY_DATA="copy_data",p.CREATE_TRIGGER="create_trigger",p))(ku||{}),_y=class extends Error{constructor(n){super(`Migration would cause data loss:
20
+ `)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256")||(this.service==="s3"&&this.signQuery?"UNSIGNED-PAYLOAD":null);if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new Error("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=jc(await Wh(this.body||""));}return e}};Kh=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];});var sy=zu((zU,BR)=>{BR.exports={"dev/vite/main.tsx":{file:"assets/main-1bwWb_1q.js",name:"main",src:"dev/vite/main.tsx",isEntry:true,css:["assets/main-BDsRycsc.css"]}};});var Pu,Ry,Cy,Jo=I(()=>{Pu=(p=>(p.DISABLE_FOREIGN_KEYS="disable_foreign_keys",p.ENABLE_FOREIGN_KEYS="enable_foreign_keys",p.BEGIN_TRANSACTION="begin_transaction",p.COMMIT_TRANSACTION="commit_transaction",p.CREATE_TABLE="create_table",p.ADD_COLUMN="add_column",p.DROP_COLUMN="drop_column",p.ADD_INDEX="add_index",p.DROP_INDEX="drop_index",p.DROP_TABLE="drop_table",p.RENAME_TABLE="rename_table",p.COPY_DATA="copy_data",p.CREATE_TRIGGER="create_trigger",p))(Pu||{}),Ry=class extends Error{constructor(n){super(`Migration would cause data loss:
21
21
  ${n.map(r=>` - ${r.table}: ${r.reason}`).join(`
22
- `)}`);this.warnings=n;this.name="DataLossError";}},Ey=class extends Error{constructor(n,r,s){super(`Migration failed at step ${n}: ${s.message}
23
- SQL: ${r}`);this.stepIndex=n;this.sql=r;this.cause=s;this.name="MigrationError";}};});var Ge,Js=I(()=>{Ge=class t{constructor(e){this.data=e;}appliesTo(e){return this.data.command==="ALL"||this.data.command===e}appliesToRole(e){return this.data.roles.length===0||this.data.roles.includes(e)}toJSON(){return this.data}static fromJSON(e){return new t(e)}};});function OC(t,e){if(t.includes(Py)||e.includes(Py))return true;let n=Il(t),r=Il(e);return !n||!r?to(t)!==to(e):[...n].sort().join("\0")!==[...r].sort().join("\0")}var Py,cr,Pu=I(()=>{Un();Py="/* modified */";cr=class{makeIndexKey(e){return `${e.table}:${e.name}:${e.unique}:${e.columns.join(",")}`}makeForeignKeyKey(e){let n=(e.on_update??"NO ACTION").toUpperCase(),r=(e.on_delete??"NO ACTION").toUpperCase();return `${e.table}:${e.column}:${e.ref_table}:${e.ref_column}:${n}:${r}`}diff(e,n){let r=[],s=[],i=[],o=[],a=new Set(e.tables.map(m=>m.name)),l=new Set(n.tables.map(m=>m.name));for(let m of n.tables)a.has(m.name)||r.push({type:"added",name:m.name,sql:m.sql});for(let m of e.tables)l.has(m.name)||r.push({type:"removed",name:m.name});for(let m of e.tables){let h=n.tables.find(y=>y.name===m.name);h&&OC(m.sql,h.sql)&&r.push({type:"modified",name:m.name,sql:h.sql});}let c=e.tables.filter(m=>l.has(m.name));for(let m of c){let h=e.columns.filter(b=>b.table===m.name),y=n.columns.filter(b=>b.table===m.name),w=new Map(h.map(b=>[b.name,b])),S=new Map(y.map(b=>[b.name,b]));for(let[b,_]of S)w.has(b)||s.push({type:"added",table:m.name,name:b,column:_});for(let[b]of w)S.has(b)||s.push({type:"removed",table:m.name,name:b});for(let[b,_]of w){let E=S.get(b);if(!E)continue;let x={};$l(_.type)!==$l(E.type)&&(x.type={from:_.type,to:E.type}),!(_.is_primary_key&&E.is_primary_key)&&_.nullable!==E.nullable&&(x.nullable={from:_.nullable,to:E.nullable}),Nl(_.default_value)!==Nl(E.default_value)&&(x.default_value={from:_.default_value,to:E.default_value}),Object.keys(x).length>0&&s.push({type:"modified",table:m.name,name:b,changes:x});}}let f=new Map(e.indexes.map(m=>[this.makeIndexKey(m),m])),u=new Map(n.indexes.map(m=>[this.makeIndexKey(m),m]));for(let[m,h]of u)f.has(m)||i.push({type:"added",...h});for(let[m,h]of f)u.has(m)||i.push({type:"removed",...h});let d=new Map(e.foreign_keys.map(m=>[this.makeForeignKeyKey(m),m])),p=new Map(n.foreign_keys.map(m=>[this.makeForeignKeyKey(m),m]));for(let[m,h]of p)d.has(m)||o.push({type:"added",...h});for(let[m,h]of d)p.has(m)||o.push({type:"removed",...h});let g=r.length>0||s.length>0||i.length>0||o.length>0;return {tables:r,columns:s,indexes:i,foreign_keys:o,has_changes:g}}};});var PC,ur,$u=I(()=>{Ho();Fn();PC=["CURRENT_TIMESTAMP","CURRENT_TIME","CURRENT_DATE"],ur=class{plan(e,n,r,s){if(!e.has_changes)return {steps:[],warnings:[],unsafe:false};let i=[],o=[];i.push({sql:"PRAGMA foreign_keys=OFF;",description:"Disable foreign key checks",type:"disable_foreign_keys"}),i.push({sql:"BEGIN;",description:"Begin transaction",type:"begin_transaction"});for(let u of e.tables.filter(d=>d.type==="added")){i.push({sql:`${u.sql};`,description:`CREATE TABLE ${N(u.name)}`,type:"create_table"});let d=r.indexes.filter(p=>p.table===u.name);for(let p of d){let g=p.unique?"UNIQUE ":"",m=p.columns.map(h=>N(h)).join(", ");i.push({sql:`CREATE ${g}INDEX ${N(p.name)} ON ${N(u.name)} (${m});`,description:`Create index ${N(p.name)} on ${N(u.name)}`,type:"add_index"});}}let a=new Set(n.tables.map(u=>u.name)),l=new Set(r.tables.map(u=>u.name)),c=new Set(e.tables.filter(u=>u.type==="modified").map(u=>u.name)),f=[...a].filter(u=>l.has(u));for(let u of f){if(!(c.has(u)||e.columns.some(m=>m.table===u)||e.indexes.some(m=>m.table===u)||e.foreign_keys.some(m=>m.table===u)))continue;let{canAlter:p,addedCols:g}=this.canSimpleAlter(u,e,r);if(p){for(let y of g)i.push({sql:`ALTER TABLE ${N(u)} ADD COLUMN ${this.columnDef(y)};`,description:`Add column ${N(y.name)} to ${N(u)}`,type:"add_column"});let m=e.indexes.filter(y=>y.table===u&&y.type==="added"),h=e.indexes.filter(y=>y.table===u&&y.type==="removed");for(let y of h)i.push({sql:`DROP INDEX IF EXISTS ${N(y.name)};`,description:`Drop index ${N(y.name)}`,type:"drop_index"});for(let y of m){let w=y.unique?"UNIQUE ":"",S=y.columns.map(b=>N(b)).join(", ");i.push({sql:`CREATE ${w}INDEX ${N(y.name)} ON ${N(u)} (${S});`,description:`Create index ${N(y.name)} on ${N(u)}`,type:"add_index"});}}else {let m=this.rebuildTable(u,n,r,e);i.push(...m.steps),o.push(...m.warnings);}}for(let u of e.tables.filter(d=>d.type==="removed"))i.push({sql:`DROP TABLE ${N(u.name)};`,description:`Drop table ${N(u.name)}`,type:"drop_table"}),o.push({table:u.name,reason:"table will be dropped"});return i.push({sql:"COMMIT;",description:"Commit transaction",type:"commit_transaction"}),i.push({sql:"PRAGMA foreign_keys=ON;",description:"Re-enable foreign key checks",type:"enable_foreign_keys"}),{steps:i,warnings:o,unsafe:o.length>0}}rebuildTable(e,n,r,s){let i=[],o=[],a=r.tables.find(y=>y.name===e);if(!a)return {steps:i,warnings:o};let l=`_${e}_migrate_new`,c=a.sql.replace(new RegExp(`(CREATE\\s+TABLE\\s+)(?:"${e}"|${e})`,"i"),`$1${N(l)}`);i.push({sql:`${c};`,description:`Create temporary table ${N(l)}`,type:"create_table"});let f=n.columns.filter(y=>y.table===e).map(y=>y.name),u=r.columns.filter(y=>y.table===e).map(y=>y.name),d=f.filter(y=>u.includes(y));if(d.length>0){let y=d.map(w=>N(w)).join(", ");i.push({sql:`INSERT INTO ${N(l)} (${y})
22
+ `)}`);this.warnings=n;this.name="DataLossError";}},Cy=class extends Error{constructor(n,r,s){super(`Migration failed at step ${n}: ${s.message}
23
+ SQL: ${r}`);this.stepIndex=n;this.sql=r;this.cause=s;this.name="MigrationError";}};});var Ge,Js=I(()=>{Ge=class t{constructor(e){this.data=e;}appliesTo(e){return this.data.command==="ALL"||this.data.command===e}appliesToRole(e){return this.data.roles.length===0||this.data.roles.includes(e)}toJSON(){return this.data}static fromJSON(e){return new t(e)}};});function LC(t,e){if(t.includes(Dy)||e.includes(Dy))return true;let n=jl(t),r=jl(e);return !n||!r?so(t)!==so(e):[...n].sort().join("\0")!==[...r].sort().join("\0")}var Dy,cr,Du=I(()=>{Un();Dy="/* modified */";cr=class{makeIndexKey(e){return `${e.table}:${e.name}:${e.unique}:${e.columns.join(",")}`}makeForeignKeyKey(e){let n=(e.on_update??"NO ACTION").toUpperCase(),r=(e.on_delete??"NO ACTION").toUpperCase();return `${e.table}:${e.column}:${e.ref_table}:${e.ref_column}:${n}:${r}`}diff(e,n){let r=[],s=[],i=[],o=[],a=new Set(e.tables.map(m=>m.name)),l=new Set(n.tables.map(m=>m.name));for(let m of n.tables)a.has(m.name)||r.push({type:"added",name:m.name,sql:m.sql});for(let m of e.tables)l.has(m.name)||r.push({type:"removed",name:m.name});for(let m of e.tables){let h=n.tables.find(y=>y.name===m.name);h&&LC(m.sql,h.sql)&&r.push({type:"modified",name:m.name,sql:h.sql});}let c=e.tables.filter(m=>l.has(m.name));for(let m of c){let h=e.columns.filter(b=>b.table===m.name),y=n.columns.filter(b=>b.table===m.name),w=new Map(h.map(b=>[b.name,b])),S=new Map(y.map(b=>[b.name,b]));for(let[b,_]of S)w.has(b)||s.push({type:"added",table:m.name,name:b,column:_});for(let[b]of w)S.has(b)||s.push({type:"removed",table:m.name,name:b});for(let[b,_]of w){let E=S.get(b);if(!E)continue;let x={};Dl(_.type)!==Dl(E.type)&&(x.type={from:_.type,to:E.type}),!(_.is_primary_key&&E.is_primary_key)&&_.nullable!==E.nullable&&(x.nullable={from:_.nullable,to:E.nullable}),Ll(_.default_value)!==Ll(E.default_value)&&(x.default_value={from:_.default_value,to:E.default_value}),Object.keys(x).length>0&&s.push({type:"modified",table:m.name,name:b,changes:x});}}let f=new Map(e.indexes.map(m=>[this.makeIndexKey(m),m])),u=new Map(n.indexes.map(m=>[this.makeIndexKey(m),m]));for(let[m,h]of u)f.has(m)||i.push({type:"added",...h});for(let[m,h]of f)u.has(m)||i.push({type:"removed",...h});let d=new Map(e.foreign_keys.map(m=>[this.makeForeignKeyKey(m),m])),p=new Map(n.foreign_keys.map(m=>[this.makeForeignKeyKey(m),m]));for(let[m,h]of p)d.has(m)||o.push({type:"added",...h});for(let[m,h]of d)p.has(m)||o.push({type:"removed",...h});let g=r.length>0||s.length>0||i.length>0||o.length>0;return {tables:r,columns:s,indexes:i,foreign_keys:o,has_changes:g}}};});var FC,ur,ju=I(()=>{Jo();Fn();FC=["CURRENT_TIMESTAMP","CURRENT_TIME","CURRENT_DATE"],ur=class{plan(e,n,r,s){if(!e.has_changes)return {steps:[],warnings:[],unsafe:false};let i=[],o=[];i.push({sql:"PRAGMA foreign_keys=OFF;",description:"Disable foreign key checks",type:"disable_foreign_keys"}),i.push({sql:"BEGIN;",description:"Begin transaction",type:"begin_transaction"});for(let u of e.tables.filter(d=>d.type==="added")){i.push({sql:`${u.sql};`,description:`CREATE TABLE ${N(u.name)}`,type:"create_table"});let d=r.indexes.filter(p=>p.table===u.name);for(let p of d){let g=p.unique?"UNIQUE ":"",m=p.columns.map(h=>N(h)).join(", ");i.push({sql:`CREATE ${g}INDEX ${N(p.name)} ON ${N(u.name)} (${m});`,description:`Create index ${N(p.name)} on ${N(u.name)}`,type:"add_index"});}}let a=new Set(n.tables.map(u=>u.name)),l=new Set(r.tables.map(u=>u.name)),c=new Set(e.tables.filter(u=>u.type==="modified").map(u=>u.name)),f=[...a].filter(u=>l.has(u));for(let u of f){if(!(c.has(u)||e.columns.some(m=>m.table===u)||e.indexes.some(m=>m.table===u)||e.foreign_keys.some(m=>m.table===u)))continue;let{canAlter:p,addedCols:g}=this.canSimpleAlter(u,e,r);if(p){for(let y of g)i.push({sql:`ALTER TABLE ${N(u)} ADD COLUMN ${this.columnDef(y)};`,description:`Add column ${N(y.name)} to ${N(u)}`,type:"add_column"});let m=e.indexes.filter(y=>y.table===u&&y.type==="added"),h=e.indexes.filter(y=>y.table===u&&y.type==="removed");for(let y of h)i.push({sql:`DROP INDEX IF EXISTS ${N(y.name)};`,description:`Drop index ${N(y.name)}`,type:"drop_index"});for(let y of m){let w=y.unique?"UNIQUE ":"",S=y.columns.map(b=>N(b)).join(", ");i.push({sql:`CREATE ${w}INDEX ${N(y.name)} ON ${N(u)} (${S});`,description:`Create index ${N(y.name)} on ${N(u)}`,type:"add_index"});}}else {let m=this.rebuildTable(u,n,r,e);i.push(...m.steps),o.push(...m.warnings);}}for(let u of e.tables.filter(d=>d.type==="removed"))i.push({sql:`DROP TABLE ${N(u.name)};`,description:`Drop table ${N(u.name)}`,type:"drop_table"}),o.push({table:u.name,reason:"table will be dropped"});return i.push({sql:"COMMIT;",description:"Commit transaction",type:"commit_transaction"}),i.push({sql:"PRAGMA foreign_keys=ON;",description:"Re-enable foreign key checks",type:"enable_foreign_keys"}),{steps:i,warnings:o,unsafe:o.length>0}}rebuildTable(e,n,r,s){let i=[],o=[],a=r.tables.find(y=>y.name===e);if(!a)return {steps:i,warnings:o};let l=`_${e}_migrate_new`,c=a.sql.replace(new RegExp(`(CREATE\\s+TABLE\\s+)(?:"${e}"|${e})`,"i"),`$1${N(l)}`);i.push({sql:`${c};`,description:`Create temporary table ${N(l)}`,type:"create_table"});let f=n.columns.filter(y=>y.table===e).map(y=>y.name),u=r.columns.filter(y=>y.table===e).map(y=>y.name),d=f.filter(y=>u.includes(y));if(d.length>0){let y=d.map(w=>N(w)).join(", ");i.push({sql:`INSERT INTO ${N(l)} (${y})
24
24
  SELECT ${y}
25
- FROM ${N(e)};`,description:`Copy data from ${N(e)} to ${N(l)}`,type:"copy_data"});}i.push({sql:`DROP TABLE ${N(e)};`,description:`Drop old table ${N(e)}`,type:"drop_table"}),i.push({sql:`ALTER TABLE ${N(l)} RENAME TO ${N(e)};`,description:`Rename ${N(l)} to ${N(e)}`,type:"rename_table"});let p=r.indexes.filter(y=>y.table===e);for(let y of p){let w=y.unique?"UNIQUE ":"",S=y.columns.map(b=>N(b)).join(", ");i.push({sql:`CREATE ${w}INDEX ${N(y.name)} ON ${N(e)} (${S});`,description:`Recreate index ${N(y.name)} on ${N(e)}`,type:"add_index"});}let g=r.triggers?.filter(y=>y.table===e)??[];for(let y of g)i.push({sql:`${y.sql};`,description:`Recreate trigger ${N(y.name)} on ${N(e)}`,type:"create_trigger"});let m=s.columns.filter(y=>y.table===e&&y.type==="removed");for(let y of m)o.push({table:e,reason:`column "${y.name}" will be dropped`});let h=s.columns.filter(y=>y.table===e&&y.type==="modified");for(let y of h)y.changes?.type&&o.push({table:e,reason:`column "${y.name}" type changes from ${y.changes.type.from} to ${y.changes.type.to}`}),y.changes?.nullable&&!y.changes.nullable.to&&o.push({table:e,reason:`column "${y.name}" becomes NOT NULL`});return {steps:i,warnings:o}}canSimpleAlter(e,n,r){let s=n.columns.filter(u=>u.table===e),i=s.filter(u=>u.type==="added"),o=s.filter(u=>u.type==="removed"),a=s.filter(u=>u.type==="modified"),l=n.foreign_keys.some(u=>u.table===e);if(o.length>0||a.length>0||l)return {canAlter:false,addedCols:i};let c=r.tables.find(u=>u.name===e);return c&&/\bCHECK\s*\(/i.test(c.sql)?{canAlter:false,addedCols:i}:{canAlter:i.every(u=>{let d=u.column;return this.hasNonConstantDefault(d.default_value)?false:d.nullable||d.default_value!=null})&&i.length>0,addedCols:i}}hasNonConstantDefault(e){if(e==null)return false;let n=e.trim().toUpperCase();return PC.includes(n)}columnDef(e){let n=e.column,r=`${N(n.name)} ${n.type||"TEXT"}`;return n.nullable||(r+=" NOT NULL"),n.default_value!=null&&(r+=` DEFAULT ${n.default_value}`),r}};});async function dr(t){let{parse:e}=await import('pgsql-parser');return e(t)}var qy=I(()=>{});function zs(t){if("String"in t)return t.String.sval}function At(t){return t.map(zs).filter(e=>e!=null)}function zt(t){return t==null?[]:t.List!==void 0?t.List.items||[]:Array.isArray(t)?t:[t]}function Qo(t){return QuoteUtils.quoteIdentifier(t)}function pr(t){return Object.keys(t)[0]}function Hy(t){if("A_Const"in t){if(t.A_Const.ival)return t.A_Const.ival.ival;if(t.A_Const.fval)return t.A_Const.fval.fval;if(t.A_Const.sval)return t.A_Const.sval.sval;if(t.A_Const.boolval)return t.A_Const.boolval.boolval;if(t.A_Const.isnull)return null}}var _n=I(()=>{});function Ky(t){let e=t.toLowerCase().trim();if(e.startsWith("_")||e.endsWith("[]"))return "TEXT";let n=WC[e];if(!n)throw new En(`Unsupported PostgreSQL type: "${t}"`);return n}function Yo(t){let e=t.toLowerCase();return ["serial","serial4","bigserial","serial8","smallserial","serial2"].includes(e)}function Xo(t){let e=t.toLowerCase();return ["varchar","character varying","char","character","bpchar"].includes(e)}function Zo(t){let e=t.toLowerCase();return ["numeric","decimal"].includes(e)}var En,L,WC,Wy,KC,ea,mr=I(()=>{_n();En=class extends Error{},L=class extends En{constructor(n,r){super(r??`Unsupported node type: ${pr(n)}`);this.node=n;}},WC={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"},Wy=["<",">","<=",">=","=","<>","!=","+","-","*","/","%","&","|","<<",">>","||","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","->>"];KC={CreateEnumStmt:{react:"ignore"},CreateDomainStmt:{react:"warn"},CreateSeqStmt:{react:"ignore"},AlterSeqStmt:{react:"ignore"},CreateSchemaStmt:{react:"warn"},CreatePolicyStmt:{react:"ignore"},AlterPolicyStmt:{react:"ignore"},PartitionElem:{react:"error"},PartitionCmd:{react:"error"},VariableSetStmt:{react:"ignore"},CompositeTypeStmt:{react:"error"},AlterEnumStmt:{react:"error"},AlterObjectSchemaStmt:{react:"error"},AlterOwnerStmt:{react:"error"},AlterTypeStmt:{react:"error"},AlterFunctionStmt:{react:"error"},AlterDefaultPrivilegesStmt:{react:"error"},GrantStmt:{react:"error"},GrantRoleStmt:{react:"error"},CopyStmt:{react:"error"},CreateCastStmt:{react:"error"},AlterOpFamilyStmt:{react:"error"},AlterOperatorStmt:{react:"error"},TruncateStmt:{react:"error"},A_Indirection:{react:"error"},XmlExpr:{react:"error"},XmlSerialize:{react:"error"},RangeTableSample:{react:"error"},GroupingSet:{react:"error"}},ea=new Map(Object.entries(KC));});var ze,xn,ju=I(()=>{_n();mr();ze=class extends L{constructor(e,n){super(e,`Unsupported expression: ${n}`);}},xn=class{deparse(e){if("A_Const"in e){let s=e.A_Const;if(s.boolval!==void 0)return s.boolval.boolval?{}:{$always:false}}let n=Object.keys(e)[0],r=this[n];if(!r)throw new ze({[n]:e},`Unsupported expression: ${n}`);return r.call(this,e[n])}deparseValue(e){if("A_Const"in e)return this.A_Const(e.A_Const);if("ColumnRef"in e)return this.ColumnRef(e.ColumnRef);if("FuncCall"in e)return this.FuncCall(e.FuncCall);if("SubLink"in e)return this.SubLink(e.SubLink);if("TypeCast"in e)return this.TypeCast(e.TypeCast);if("A_Expr"in e){let r=this.isJwtAccessor(e.A_Expr);return r||this.A_Expr(e.A_Expr)}if("BoolExpr"in e)return this.BoolExpr(e.BoolExpr);let n=Object.keys(e)[0];throw new ze({[n]:e},`deparseValue: ${n}`)}A_Expr(e){if(e.kind==="AEXPR_OP"){let n=e.name?.[0],r=n?zs(n):void 0;if(!r)throw new ze({A_Expr:e},"A_Expr missing operator");let s=this.isJwtAccessor(e);if(s)return {[s]:{}};let i=e.lexpr?this.deparseValue(e.lexpr):void 0,o=e.rexpr?this.deparseValue(e.rexpr):void 0,a=this.mapOperator(r);if(!a)throw new ze({A_Expr:e},`Unsupported operator: ${r}`);let l=e.rexpr!=null&&"ColumnRef"in e.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(e.kind==="AEXPR_LIKE"||e.kind==="AEXPR_ILIKE"){let n=e.lexpr?this.deparseValue(e.lexpr):void 0,r=e.rexpr?this.deparseValue(e.rexpr):void 0,i=(e.name?.[0]?zs(e.name[0]):"~~")==="!~~"?"$notLike":"$like";return {[n]:{[i]:r}}}if(e.kind==="AEXPR_IN"){let n=e.lexpr?this.deparseValue(e.lexpr):void 0,r=e.rexpr&&"List"in e.rexpr&&e.rexpr.List.items?e.rexpr.List.items.map(s=>this.deparseValue(s)):[];return {[n]:{$in:r}}}throw new ze({A_Expr:e},`A_Expr kind: ${e.kind}`)}BoolExpr(e){let n=e.args??[];switch(e.boolop){case "AND_EXPR":return {$and:n.map(r=>this.deparse(r))};case "OR_EXPR":return {$or:n.map(r=>this.deparse(r))};case "NOT_EXPR":return {$not:this.deparse(n[0])};default:throw new ze({BoolExpr:e},`BoolExpr op: ${e.boolop}`)}}NullTest(e){let n=e.arg?this.deparseValue(e.arg):void 0;return e.nulltesttype==="IS_NULL"?{[n]:{$is:null}}:{[n]:{$isNot:null}}}SubLink(e){if(e.subLinkType==="ANY_SUBLINK"){let n=e.testexpr?this.deparseValue(e.testexpr):void 0,r=e.subselect?this.SelectStmt(e.subselect.SelectStmt):void 0;return {[n]:{$in:r}}}if(e.subLinkType==="EXISTS_SUBLINK")return {$exists:e.subselect?this.SelectStmt(e.subselect.SelectStmt):void 0};if(e.subLinkType==="EXPR_SUBLINK"){let n=e.subselect?e.subselect.SelectStmt:void 0;if(n?.fromClause?.length)return this.SelectStmt(n);if(n?.targetList?.[0]){let r=n.targetList[0],s="ResTarget"in r?r.ResTarget:void 0;if(s?.val){let i=this.deparseValue(s.val);return i}}}throw new ze({SubLink:e},`SubLink type: ${e.subLinkType}`)}SelectStmt(e){let{from:n,schema:r,join:s}=this.deparseFromClause(e.fromClause??[]),i=[];for(let d of e.targetList??[]){let p="ResTarget"in d?d.ResTarget:void 0;if(p?.val){let g=this.deparseValue(p.val);Array.isArray(g)?i.push(...g.map(String)):g!=null&&g!==""&&i.push(String(g));}}let o=e.whereClause?this.deparse(e.whereClause):void 0,a=this.deparseSortClause(e.sortClause),l=this.deparseLimit(e.limitCount),c=this.deparseLimit(e.limitOffset),f=this.deparseGroupClause(e.groupClause),u={type:"query",from:n,select:i};return r&&(u.schema=r),Object.keys(s).length>0&&(u.join=s),o&&(u.where=o),a.length>0&&(u.order=a),l!==void 0&&(u.limit=l),c!==void 0&&(u.offset=c),f.length>0&&(u.group=f),u}FuncCall(e){let n=this.isAuthFunc(e.funcname??[]);if(n)return n;throw new ze({FuncCall:e},`FuncCall: ${At(e.funcname??[]).join(".")}`)}ColumnRef(e){let n=At(e.fields??[]);return n.length===1?n[0]:n.join(".")}A_Const(e){if(e.boolval!==void 0)return e.boolval.boolval;if(e.ival!==void 0)return e.ival.ival??0;if(e.fval!==void 0)return parseFloat(e.fval.fval??"0");if(e.sval!==void 0)return e.sval.sval??"";if(e.isnull)return null;throw new ze({A_Const:e},"A_Const: unknown variant")}TypeCast(e){if(!e.arg)throw new ze({TypeCast:e},"TypeCast: missing arg");return this.deparseValue(e.arg)}BooleanTest(e){let n=e.arg?this.deparseValue(e.arg):void 0;return e.booltesttype==="IS_TRUE"?{[n]:{$eq:true}}:{[n]:{$eq:false}}}deparseFromClause(e){let n={};if(e.length===0)return {from:"",join:n};let r=e[0];if("RangeVar"in r){let s=r.RangeVar;return {from:s.relname??"",schema:s.schemaname,join:n}}if("JoinExpr"in r){let{from:s,schema:i}=this.walkJoinExpr(r.JoinExpr,n);return {from:s,schema:i,join:n}}return {from:"",join:n}}walkJoinExpr(e,n){let r={from:""};if(e.larg)if("RangeVar"in e.larg){let s=e.larg.RangeVar;r={from:s.relname??"",schema:s.schemaname};}else "JoinExpr"in e.larg&&(r=this.walkJoinExpr(e.larg.JoinExpr,n));if(e.rarg&&"RangeVar"in e.rarg){let s=e.rarg.RangeVar,i=s.relname??"",o=s.alias?.aliasname??i,a=e.jointype==="JOIN_LEFT"?"left":"inner",l={from:i,type:a};e.quals&&(l.on=this.deparse(e.quals));let c=o;if(c in n){let f=2;for(;`${c}_${f}`in n;)f++;c=`${c}_${f}`;}n[c]=l;}return r}deparseSortClause(e){if(!e)return [];let n=[];for(let r of e){if(!("SortBy"in r))continue;let s=r.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),n.push(a);}return n}deparseLimit(e){if(!e)return;let n=this.deparseValue(e);return typeof n=="number"?n:Number(n)}deparseGroupClause(e){return e?e.map(n=>String(this.deparseValue(n))):[]}isAuthFunc(e){let n=At(e);if(n.length===2&&n[0]==="auth"){if(n[1]==="uid")return "{{auth.uid}}";if(n[1]==="jwt")return "{{auth.jwt}}";if(n[1]==="role")return "{{auth.role}}";throw new Error(`Unsupported auth function: "${n.slice(1).join(".")}"`)}return null}isJwtAccessor(e){if(e.kind!=="AEXPR_OP")return null;let n=e.name?.[0]?zs(e.name[0]):void 0;if(n!=="->"&&n!=="->>")return null;let r=e.rexpr&&"A_Const"in e.rexpr?e.rexpr.A_Const.sval?.sval:void 0;if(r===void 0)return null;if(e.lexpr&&"FuncCall"in e.lexpr)return this.isAuthFunc(e.lexpr.FuncCall.funcname??[])==="{{auth.jwt}}"?`{{auth.jwt.${r}}}`:null;if(e.lexpr&&"A_Expr"in e.lexpr){let s=this.isJwtAccessor(e.lexpr.A_Expr);if(s)return `${s.slice(0,-2)}.${r}}}`}return null}mapOperator(e){switch(e){case "=":return "$eq";case "<>":case "!=":return "$neq";case ">":return "$gt";case ">=":return "$gte";case "<":return "$lt";case "<=":return "$lte";case "~~":return "$like";case "!~~":return "$notLike";default:return}}};});function Vy(t){let e=new Map;for(let n of t.stmts??[]){if(!n.stmt||!("CreateEnumStmt"in n.stmt))continue;let r=n.stmt.CreateEnumStmt,s=At(r.typeName??[]).join(".");if(!s||!r.vals)continue;let i=At(r.vals),o=s.toLowerCase();e.set(o,i),o.startsWith("public.")&&e.set(o.slice(7),i);}return e}function Vs(t,e){let n=e.toLowerCase(),r=t.get(n);return r||(n.startsWith("public.")?t.get(n.slice(7)):t.get(`public.${n}`))}function Qy(t){let e=new Map;for(let n of t.stmts??[]){if(!n.stmt||!("VariableSetStmt"in n.stmt))continue;let r=n.stmt.VariableSetStmt,s=r.name,i=Hy(r.args?.[0]??{});e.set(s,{value:i,local:r.is_local});}return e}function Gy(t){let e=[],n=false;for(let r of t??[])if("RoleSpec"in r){let s=r.RoleSpec;s.roletype==="ROLESPEC_PUBLIC"?s.location===-1&&(n=true):s.roletype==="ROLESPEC_CSTRING"&&s.rolename&&e.push(s.rolename);}return {roles:e,implicitPublic:n}}function ta(t,e){return t&&t.length>0?t:e}function Lu(t,e,n){return t.findIndex(r=>r.data.name===e.name&&r.data.table===e.table&&ta(r.data.schema,n)===ta(e.schema,n))}function Fu(t,e){return new Error(`policy "${t}" for table "${e}" does not exist`)}function zy(t,e,n,r){return t.data.table===e&&ta(t.data.schema,r)===ta(n,r)}function Yy(t,e={}){let n=e.defaultSchema||"public",r=e.validateMutations===true,s=new xn,i=new Set,o=[];for(let a of t.stmts??[])if(a.stmt){if("CreatePolicyStmt"in a.stmt){let l=a.stmt.CreatePolicyStmt,c=l.table?.relname??"",f=l.table?.schemaname,u={select:"SELECT",insert:"INSERT",update:"UPDATE",delete:"DELETE"},d=l.cmd_name?u[l.cmd_name]??"ALL":"ALL",p=l.permissive===true,{roles:g,implicitPublic:m}=Gy(l.roles),h=l.qual?s.deparse(l.qual):void 0,y=l.with_check?s.deparse(l.with_check):void 0;if(m){let S=f?`${f}.${c}`:c,b=l.policy_name??"",_=`${S}::${b}`;if(!Jy.has(_)){Jy.add(_);let E=JSON.stringify(h)+JSON.stringify(y);/\{\{auth\.(uid|jwt|role)/i.test(E)||console.warn(`[supalite] policy "${b}" on "${S}" has no TO clause \u2014 applies to all roles (PUBLIC). For clarity, prefer an explicit \`TO <role>\` clause (e.g. \`TO authenticated\`).`);}}let w=new Ge({name:l.policy_name??"",table:c,schema:f,command:d,permissive:p,roles:g,using:h,withCheck:y});o.push(w);}if("DropStmt"in a.stmt&&a.stmt.DropStmt.removeType==="OBJECT_POLICY"){let l=a.stmt.DropStmt,c=l.objects?.[0];if(c&&"List"in c){let f=At(c.List.items??[]),u=f[f.length-1],d=f[f.length-2],p=f.length>=3?f[f.length-3]:void 0;if(u&&d){let g=Lu(o,{name:u,table:d,schema:p},n);if(g!==-1)o.splice(g,1);else if(r&&!l.missing_ok)throw Fu(u,d)}}}if("AlterPolicyStmt"in a.stmt){let l=a.stmt.AlterPolicyStmt,c=l.policy_name??"",f=l.table?.relname??"",u=l.table?.schemaname,d=Lu(o,{name:c,table:f,schema:u},n);if(d===-1){if(r)throw Fu(c,f);continue}let p=o[d].data,g=l.roles?Gy(l.roles).roles:p.roles,m=l.qual?s.deparse(l.qual):p.using,h=l.with_check?s.deparse(l.with_check):p.withCheck;o[d]=new Ge({...p,roles:g,using:m,withCheck:h});}if("RenameStmt"in a.stmt&&a.stmt.RenameStmt.renameType==="OBJECT_POLICY"){let l=a.stmt.RenameStmt,c=l.subname??"",f=l.relation?.relname??"",u=l.relation?.schemaname,d=Lu(o,{name:c,table:f,schema:u},n);if(d===-1){if(r)throw Fu(c,f);continue}l.newname&&(o[d]=new Ge({...o[d].data,name:l.newname}));}if("RenameStmt"in a.stmt&&a.stmt.RenameStmt.renameType==="OBJECT_TABLE"){let l=a.stmt.RenameStmt,c=l.relation?.relname??"",f=l.newname??"",u=l.relation?.schemaname;if(c&&f&&c!==f){i.delete(c)&&i.add(f);for(let d=0;d<o.length;d++)zy(o[d],c,u,n)&&(o[d]=new Ge({...o[d].data,table:f}));}}if("DropStmt"in a.stmt&&a.stmt.DropStmt.removeType==="OBJECT_TABLE")for(let l of a.stmt.DropStmt.objects??[]){if(!("List"in l))continue;let c=At(l.List.items??[]),f=c[c.length-1],u=c.length>=2?c[c.length-2]:void 0;if(f){i.delete(f);for(let d=o.length-1;d>=0;d--)zy(o[d],f,u,n)&&o.splice(d,1);}}if("AlterTableStmt"in a.stmt){let l=a.stmt.AlterTableStmt,c=l.relation?.relname??"";for(let f of l.cmds??[]){if(!("AlterTableCmd"in f))continue;let u=f.AlterTableCmd.subtype;u==="AT_EnableRowSecurity"?i.add(c):u==="AT_DisableRowSecurity"&&i.delete(c);}}}return {policies:o,tables:i}}function Xy(t,e){let n=new Map;for(let r of t.stmts??[]){if(!r.stmt||!("CreateStmt"in r.stmt))continue;let s=r.stmt.CreateStmt,i=s.relation?.relname??"",o=s.relation?.schemaname??"public";if(!i)continue;let a=new at(i,o);for(let l of s.tableElts??[]){if(!("ColumnDef"in l))continue;let c=l.ColumnDef,f=c.colname;if(!f)continue;let u=c.typeName?.names?.map(R=>R.String?.sval||R.String?.str).filter(Boolean),d=u&&u.length>0?u.length===2&&u[0]==="pg_catalog"?u[1]:u.join("."):void 0;if(!d)continue;let p=!!c.typeName?.arrayBounds?.length,g=Array.isArray(c.typeName?.typmods)?c.typeName.typmods:[],m=R=>g[R]?.A_Const?.ival?.ival??g[R]?.A_Const?.val?.ival?.ival,h={isArray:p};if(Xo(d)&&g.length>0){let R=m(0);typeof R=="number"&&R>0&&(h.lengthConstraint=R);}if(Zo(d)&&g.length>=2){let R=m(0),U=m(1);typeof R=="number"&&typeof U=="number"&&R>0&&U>=0&&(h.numericPrecision={precision:R,scale:U});}let y=Vs(e,d);y&&(h.enumValues=y);let w=Array.isArray(c.constraints)?c.constraints:[],S=w.some(R=>R.Constraint?.contype==="CONSTR_PRIMARY"),b=Yo(d)||w.some(R=>R.Constraint?.contype==="CONSTR_IDENTITY"),_=w.some(R=>R.Constraint?.contype==="CONSTR_NOTNULL"),E=w.find(R=>R.Constraint?.contype==="CONSTR_UNIQUE"),x=w.find(R=>R.Constraint?.contype==="CONSTR_GENERATED"),O=w.find(R=>R.Constraint?.contype==="CONSTR_FOREIGN"),v=w.find(R=>R.Constraint?.contype==="CONSTR_CHECK"),P;if(O){let R=O.Constraint,U=R.pktable?.relname,J=R.pktable?.schemaname,F=R.pk_attrs?.[0]?.String?.sval;U&&F&&(P={refSchema:J,refTable:U,refColumn:F,constraintName:R.conname||void 0});}let C={schema:o,table:i,column:f,pgTypeName:d,nullable:!_&&!S,defaultValue:null,defaultFn:null,isPrimaryKey:S,isUnique:!!E,isSerial:b,isGenerated:!!x,fkRef:P,hasCheck:!!v,checkConstraintName:v?.Constraint?.conname||void 0,uniqueConstraintName:E?.Constraint?.conname||void 0};a.set(f,We(C,h));}n.set(`${o}.${i}`,a);}return n}function Zy(t){let e=[];for(let n of t.stmts??[]){if(!n.stmt||!("CreateStmt"in n.stmt))continue;let r=n.stmt.CreateStmt,s=r.relation?.relname??"",i=r.relation?.schemaname??"public";if(s)for(let o of r.tableElts??[]){if("ColumnDef"in o){let f=o.ColumnDef,u=f?.colname;if(!u)continue;for(let d of f.constraints??[]){let p=d?.Constraint;if(!p||p.contype!=="CONSTR_FOREIGN")continue;let g=p.pktable?.relname;if(!g)continue;let m=(p.pk_attrs??[]).map(h=>h.String?.sval??h.String?.str).filter(Boolean);e.push({schema:i,table:s,kind:"foreign_key",name:p.conname||void 0,columns:[u],refSchema:p.pktable?.schemaname,refTable:g,refColumns:m});}continue}let a=o;if(!a.Constraint)continue;let l=a.Constraint,c=l.contype;if(c==="CONSTR_UNIQUE"){let f=(l.keys??[]).map(u=>u.String?.sval??u.String?.str).filter(Boolean);if(f.length===0)continue;e.push({schema:i,table:s,kind:"unique",name:l.conname||void 0,columns:f});}else if(c==="CONSTR_CHECK")e.push({schema:i,table:s,kind:"check",name:l.conname||void 0,columns:[]});else if(c==="CONSTR_FOREIGN"){let f=(l.fk_attrs??[]).map(p=>p.String?.sval??p.String?.str).filter(Boolean),u=(l.pk_attrs??[]).map(p=>p.String?.sval??p.String?.str).filter(Boolean),d=l.pktable?.relname;if(!d)continue;e.push({schema:i,table:s,kind:"foreign_key",name:l.conname||void 0,columns:f,refSchema:l.pktable?.schemaname,refTable:d,refColumns:u});}}}return e}function eb(t){let e=[];for(let n of t.stmts??[]){if(!n.stmt||!("CommentStmt"in n.stmt))continue;let r=n.stmt.CommentStmt,s=r.comment??"";if(!s)continue;let i=r.objtype,o=(r.object?.List?.items??r.object?.items??[]).map(a=>a.String?.sval??a.String?.str).filter(Boolean);if(o.length!==0){if(i==="OBJECT_TABLE"||i==="OBJECT_VIEW"){let[a,l]=o.length>=2?o:["public",o[0]];e.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,e.push({schema:a,table:l,column:c,text:s});}}}return e}var Jy,Uu=I(()=>{ju();_n();Js();Xl();mr();Jy=new Set;});var na,tb=I(()=>{mr();_n();na=class{constructor(e){this.ast=e;this.result=[...this.walk(this.ast,[],{trackPaths:["returningList"]})];}result=[];*walk(e=this.ast,n=[],r={}){if(!e||typeof e!="object")return;let{trackPaths:s=[]}=r;if(Array.isArray(e)){for(let o=0;o<e.length;o++)yield*this.walk(e[o],n,r);return}let i=Object.keys(e);if(i.length===1&&i[0][0]>="A"&&i[0][0]<="Z"){let o=i[0];yield {node:e,path:n},yield*this.walk(e[o],[...n,o],r);}else for(let[o,a]of Object.entries(e))if(a&&typeof a=="object"){let l=s.includes(o)?[...n,o]:n;yield*this.walk(a,l,r);}}containsUnsupportedNode(){for(let{node:e}of this.result){let n=pr(e),r=ea.get(n);if(r&&r.react==="error")return true}}hasFuncCall(){for(let{node:e}of this.result)if("FuncCall"in e)return true;return false}getFuncCalls(){return Array.from(this.result).map(({node:e})=>e).filter(e=>"FuncCall"in e).map(e=>e.FuncCall)}getFuncCallNames(){return this.getFuncCalls().flatMap(e=>e.funcname?.map(n=>n.String?.sval||n.String?.str))}hasSqlValueFunction(){for(let{node:e}of this.result)if("SQLValueFunction"in e)return true;return false}getSqlValueFunctions(){return Array.from(this.result).map(({node:e})=>e).filter(e=>"SQLValueFunction"in e).map(e=>e.SQLValueFunction)}getSqlValueFunctionNames(){return this.getSqlValueFunctions().map(e=>e.op)}hasUnsafeStar(){let e=this.result.filter(({node:n})=>"A_Star"in n);if(e.length===0)return false;for(let{path:n}of e)if(!n.includes("SelectStmt")&&!n.includes("returningList"))return true;return false}getRelationDefinitions(){return this.result.filter(({node:n})=>"CreateStmt"in n).map(({node:n})=>n.CreateStmt).map(n=>({relation:{relname:n.relation?.relname??"",inh:n.relation?.inh,relpersistence:n.relation?.relpersistence},columns:n.tableElts?.map(r=>{let s=r.ColumnDef?.typeName?.names?.map(o=>"String"in o?o.String.sval:""),i=s?.some(o=>o.toLowerCase().includes("pg_catalog"));return {name:r.ColumnDef?.colname??"",is_local:r.ColumnDef?.is_local,pg_catalog:i,type:s?.filter(o=>!o.toLowerCase().includes("pg_catalog"))[0]??"",types:s,constraints:r.ColumnDef?.constraints}})}))}getRelationColumnTypes(){return {has_non_pg_catalog_types:this.getRelationDefinitions().some(e=>e.columns?.some(n=>!n.pg_catalog)),types:Array.from(new Set(this.getRelationDefinitions().flatMap(e=>e.columns?.map(n=>n.type))))}}};});var GC,zC,VC,QC,hr,ra,nb=I(()=>{mr();GC=["DECLARE","IF","ELSIF","ELSE","LOOP","WHILE","FOR","FOREACH","EXCEPTION","RAISE","PERFORM","EXECUTE","SELECT"],zC=/^NEW\.(\w+)\s*(?::=|=)\s*(.+)$/is,VC=/^RETURN\s+(NEW|OLD)$/i,QC=/^(INSERT|UPDATE|DELETE)\b/i,hr=class extends En{constructor(n,r,s){super(s??`Unsupported PL/pgSQL: ${n}`);this.hint=n;this.body=r;}},ra=class{parse(e){let n=this.extractBlock(e),r=this.splitStatements(n),s=[],i=null;for(let o of r){let a=o.trim();if(!a)continue;this.rejectUnsupported(a);let l=a.match(VC);if(l){i=l[1].toUpperCase(),s.push({type:"return",value:i});continue}let c=a.match(zC);if(c){s.push({type:"assignment",column:c[1],expression:c[2].trim()});continue}if(QC.test(a)){s.push({type:"dml",sql:a});continue}throw new hr(`"${a.substring(0,80)}" is not translatable to SQLite`,n)}if(!i)throw new En("Trigger function body must end with RETURN NEW or RETURN OLD");return {statements:s,returnValue:i}}extractBlock(e){let n=e.trim(),r=n.toUpperCase();if(/^\s*DECLARE\b/i.test(n))throw new hr('"DECLARE" is not translatable to SQLite',e);let s=r.indexOf("BEGIN"),i=r.lastIndexOf("END");if(s===-1||i===-1||i<=s)throw new hr("Expected BEGIN ... END block in trigger function body",e);return n.slice(s+5,i).trim()}splitStatements(e){let n=[],r="",s=0,i=false,o="";for(let l=0;l<e.length;l++){let c=e[l];if(i){r+=c,c===o&&(l+1<e.length&&e[l+1]===o?r+=e[++l]:i=false);continue}if(c==="'"||c==='"'){i=true,o=c,r+=c;continue}if(c==="("){s++,r+=c;continue}if(c===")"){s--,r+=c;continue}if(c===";"&&s===0){n.push(r.trim()),r="";continue}r+=c;}let a=r.trim();return a&&n.push(a),n}rejectUnsupported(e){let n=e.match(/^(\w+)/)?.[1]?.toUpperCase();if(n&&GC.includes(n))throw new hr(`"${n}" is not translatable to SQLite`,e)}};});function tk(t){let e=t?.GrantStmt??t;return e?.is_grant!==true?false:e.targtype==="ACL_TARGET_ALL_IN_SCHEMA"?e.objtype==="OBJECT_TABLE"||e.objtype==="OBJECT_SEQUENCE":e.targtype==="ACL_TARGET_OBJECT"&&ek.has(e.objtype)}var ek,sa,rb=I(()=>{mr();Uu();_n();_n();tb();Yr();nb();Ho();Pu();$u();Fn();ro();Ql();ek=new Set(["OBJECT_TABLE","OBJECT_VIEW","OBJECT_SEQUENCE","OBJECT_SCHEMA"]);sa=class extends Deparser{enums;schemaHandling;warnings=[];helper;config;triggerFunctions=new Map;plpgsqlParser=new ra;introspection;functionResolution;serialColumns;constructor(e,{enums:n,schemaHandling:r,introspection:s,serialColumns:i,...o}={}){super(e,o),this.schemaHandling=r??"default",this.enums=n??new Map,this.helper=new na(e),this.config=o,this.introspection=s,this.functionResolution=o?.functionResolution??"translate",this.serialColumns=i??new WeakSet;}visit(e,n){let r=pr(e);if(r==="GrantStmt"&&tk(e))return "";let s=ea.get(r);if(s){if(s.react==="error")throw new L({[r]:e},`Unsupported node type: ${r}`);return s.react==="warn"&&this.warnings.push({type:r,node:e}),""}return super.visit(e,n)}deparse(e,n){if(e==null)return null;if(!n){let r=new SqlFormatter;n=new DeparserContext({formatter:r});}return typeof e=="number"||e instanceof Number?e.toString():this.visit(e,n)}RawStmt(e,n){if(!e.stmt||e.stmt.CommentStmt)return "";let r=this.deparse(e.stmt,n);return !r||r.length===0?"":e.stmt_len?r+";":r}RangeVar(e,n){this.ensureRelation(e);let r=this.effectiveSchema(e.schemaname),s=e.relname,i=this.quoteBareIfNeeded(s);r&&(this.schemaHandling==="prefix"?i=`${r}__${s}`:i=`"${r}.${s}"`);let o=e.alias?" "+this.Alias(e.alias,n):"";return i+o}getRelationName(e){this.ensureRelation(e);let n=this.effectiveSchema(e.schemaname),r=e.relname;return n?this.schemaHandling==="prefix"?`${n}__${r}`:`${n}.${r}`:r}quoteBareIfNeeded(e){return /^[A-Za-z_][A-Za-z0-9_]*$/.test(e)?e:`"${e.replace(/"/g,'""')}"`}effectiveSchema(e){if(e){if(this.config.forceDefaultSchema||this.schemaHandling!=="default")return e;if(e!=="public")return e}}ensureRelation(e){let n=this.config.forceDefaultSchema;n&&(!e||typeof e!="object"||n.length===0||e.schemaname||(e.schemaname=n));}CreateStmt(e,n){if(e.inhRelations&&e.inhRelations.length>0)throw new L({CreateStmt:e},"Inheritance is not supported in SQLite");if(e.ofTypename!==void 0)throw new L({CreateStmt:e},"Typed tables (CREATE TABLE ... OF type_name) are not supported. Define columns directly in the CREATE TABLE statement instead.");if(e.options&&e.options.length>0&&(e.options=void 0),!e.tableElts||e.tableElts.length===0)throw new L({CreateStmt:e},"Empty tables are not supported in SQLite. Define at least one column.");return e.accessMethod&&(e.accessMethod=void 0),super.CreateStmt(e,n)+" STRICT"}TableLikeClause(e,n){throw new L({TableLikeClause:e},"CREATE TABLE ... (LIKE ...) is not supported in SQLite. Define the table columns explicitly instead.")}DefElem(e,n){if(["oids","fillfactor",/^autovacuum_/i,"toast_tuple_target","parallel_workers","user_catalog_table"].some(i=>Ki(e.defname??"",i)))return "";let s=super.DefElem(e,n);throw new L({DefElem:e},`DefElem "${e.defname}" (${s}) not supported`)}TypeName(e,n){if(!e.names)return "";let r=e.names.map(i=>i.String?i.String.sval||i.String.str:"").filter(Boolean);if(r.length===0)return "";let s=r.length===2&&r[0]==="pg_catalog"?r[1]:r.join(".");return e.arrayBounds&&e.arrayBounds.length>0||Vs(this.enums,s)?"TEXT":Ky(s)}ColumnDef(e,n){let r=[],s=e.colname;s&&r.push(this.quoteIfNeeded(s));let i=false,o=false,a=null,l=null,c=null,f=false;if(e.typeName){let u=e.typeName.names?.map(g=>g.String?.sval||g.String?.str).filter(Boolean);c=u&&u.length>0?u.length===2&&u[0]==="pg_catalog"?u[1]:u.join("."):null,i=!!(c&&Yo(c))||this.serialColumns.has(e),f=!!(e.typeName.arrayBounds&&e.typeName.arrayBounds.length>0);let d=Array.isArray(e.typeName.typmods)?e.typeName.typmods:[],p=g=>d[g]?.A_Const?.ival?.ival??d[g]?.A_Const?.val?.ival?.ival;if(c&&Xo(c)&&d.length>0){let g=p(0);typeof g=="number"&&g>0&&(a={maxLen:g});}if(c&&Zo(c)&&d.length>=2){let g=p(0),m=p(1);typeof g=="number"&&typeof m=="number"&&g>0&&m>=0&&(l={precision:g,scale:m});}if(e.constraints){let g=Array.isArray(e.constraints)?e.constraints:[];o=g.some(m=>m.Constraint?.contype==="CONSTR_PRIMARY"),g.some(m=>m.Constraint?.contype==="CONSTR_IDENTITY")&&(i=true);}r.push(this.TypeName(e.typeName,n));}if(e.constraints){let u=Array.isArray(e.constraints)?e.constraints:[],d=n.spawn("ColumnDef",{isColumnConstraint:true}),p=u.map(m=>this.visit(m,d));r.push(...p.filter(Boolean));let g=u.some(m=>m.Constraint?.contype==="CONSTR_CHECK");i&&o&&!g?r.push("AUTOINCREMENT"):i&&!o&&this.warnings.push({type:"ColumnDef",node:{ColumnDef:e},message:`Column "${s}" is serial/auto-increment but not the primary key; SQLite can't auto-increment a non-primary-key column, so it becomes a plain INTEGER (no auto-increment).`});}if(s&&c){let u={isArray:f};a&&(u.lengthConstraint=a.maxLen),l&&(u.numericPrecision=l);let d=Vs(this.enums,c);d&&(u.enumValues=d);let m=We({schema:"public",table:"",column:s,pgTypeName:c,nullable:true,defaultValue:null,defaultFn:null,isPrimaryKey:o,isUnique:false,isSerial:i},u).checkConstraint();m&&r.push(`CHECK (${m})`);}return r.join(" ")}Constraint(e,n){let r=e.contype;if(r==="CONSTR_IDENTITY"||r==="CONSTR_ATTR_DEFERRABLE"||r==="CONSTR_ATTR_NOT_DEFERRABLE"||r==="CONSTR_ATTR_DEFERRED"||r==="CONSTR_ATTR_IMMEDIATE")return "";if(r==="CONSTR_NULL")return "NULL";if(r==="CONSTR_NOTNULL")return "NOT NULL";if(r==="CONSTR_DEFAULT"&&e.raw_expr){let s=this.unwrapConstCast(e.raw_expr),i=this.visit(s,n);return i.includes("(")&&!i.startsWith("(")?`DEFAULT (${i})`:`DEFAULT ${i}`}if(r==="CONSTR_CHECK"&&e.raw_expr){let s=[];e.conname&&s.push("CONSTRAINT",Qo(e.conname)),s.push("CHECK");let i=this.visit(e.raw_expr,n);return s.push(`(${i})`),s.join(" ")}if(r==="CONSTR_PRIMARY")return e.keys&&e.keys.length>0?`PRIMARY KEY (${zt(e.keys).map(i=>this.visit(i,n)).join(", ")})`:"PRIMARY KEY";if(r==="CONSTR_UNIQUE")return e.keys&&e.keys.length>0?`UNIQUE (${zt(e.keys).map(i=>this.visit(i,n)).join(", ")})`:"UNIQUE";if(r==="CONSTR_FOREIGN")return super.Constraint(e,n).replace(/FOREIGN\s+KEY\s+REFERENCES/gi,"REFERENCES");if(r==="CONSTR_GENERATED"&&e.raw_expr)return `GENERATED ALWAYS AS (${this.visit(e.raw_expr,n)}) STORED`;if(r==="CONSTR_EXCLUSION")throw new L({Constraint:e},"EXCLUSION constraints are not supported in SQLite");return ""}FuncCall(e,n){let s=(e.funcname||[]).map(c=>c.String?.sval||c.String?.str).filter(Boolean);if(s.length===0)throw new Error("Function call has no name");let i=s[s.length-1].toLowerCase();if(i==="extract"&&e.args&&e.args.length>=2){let c=e.args[0];if((c?.A_Const?.sval?.sval||c?.String?.sval)==="epoch")return `strftime('%s', ${this.visit(e.args[1],n)})`}let a=(e.args??[]).map(c=>this.visit(c,n));if(e.agg_star)return `${i}(*)`;if(e.agg_distinct)return `${i}(DISTINCT ${a.join(", ")})`;let l=Vl(i,this.functionResolution);if(l){if(l.sqliteExpr!==null){let c=l.sqliteExpr;return c.includes("(")?c:`${c}(${a.join(", ")})`}if(l.jsFn!==null){let c=so[i];if(c?.sqlite){let f=c.sqlite();return f.includes("(")?f:`${f}(${a.join(", ")})`}}}throw new L({FuncCall:e},`Function call "${i}" not supported`)}SQLValueFunction(e,n){switch(e.op){case "SVFOP_CURRENT_TIMESTAMP":return "datetime('now')";case "SVFOP_CURRENT_DATE":return "date('now')";case "SVFOP_CURRENT_TIME":return "time('now')";default:throw new L({SQLValueFunction:e},`SQLValueFunction "${e.op}" not supported`)}}ResTarget(e,n){if(e.indirection&&e.indirection.length>0)throw new L({ResTarget:e},"Indirections are not supported in SQLite");let r=[];return n.update&&e.name?(r.push(this.quoteIfNeeded(e.name)),r.push("="),e.val&&r.push(this.deparse(e.val,n))):n.insertColumns&&e.name?r.push(this.quoteIfNeeded(e.name)):(e.val&&r.push(this.deparse(e.val,n)),e.name&&r.push(this.Alias({aliasname:e.name},n))),r.join(" ")}A_Expr(e,n){if(e.kind==="AEXPR_OP_ANY"&&(e.name?.[0]?.String?.sval||e.name?.[0]?.String?.str)==="="&&e.lexpr&&e.rexpr&&"A_ArrayExpr"in e.rexpr){let s=zt(e.rexpr.A_ArrayExpr.elements),i=this.tryFoldConstArrayElements(s,n);if(i!==void 0)return `${this.visit(e.lexpr,n)} IN (${i.join(", ")})`}if(["AEXPR_OP_ALL","AEXPR_OP_ANY"].includes(e.kind))throw new L({A_Expr:e},"ALL/ANY/SOME comparison operators are not supported. Use NOT EXISTS or IN instead");if(e.name&&e.name.length>0){if(e.name.length>1)throw new L({A_Expr:e},"Schema-qualified OPERATOR() syntax is not supported in SQLite");let r=e.name[0]?.String?.sval||e.name[0]?.String?.str;if(r){if(!e.lexpr||!e.rexpr)throw new L({A_Expr:e},"A_Expr missing left or right expression");if(!Wy.includes(r.toUpperCase()))throw new L({A_Expr:e},`Operator "${r}" is not supported in SQLite`);if(r==="~~"||r==="~~*"){let s=this.visit(e.lexpr,n),i=this.visit(e.rexpr,n);return `${s} LIKE ${i}`}if(r==="!~~"||r==="!~~*"){let s=this.visit(e.lexpr,n),i=this.visit(e.rexpr,n);return `${s} NOT LIKE ${i}`}if(r==="~"||r==="~*"){let s=this.visit(e.lexpr,n),i=this.visit(e.rexpr,n);return `${s} GLOB ${i}`}}}return super.A_Expr(e,n)}IndexStmt(e,n){let r=["CREATE"];e.unique&&r.push("UNIQUE"),r.push("INDEX"),e.if_not_exists&&r.push("IF NOT EXISTS"),e.idxname&&r.push(Qo(e.idxname)),r.push("ON"),e.relation&&r.push(this.RangeVar(e.relation,n));let s=(e.indexParams??[]).map(i=>"IndexElem"in i?this.IndexElem(i.IndexElem,n):this.visit(i,n)).filter(Boolean);return r.push(`(${s.join(", ")})`),r.join(" ")}IndexElem(e,n){let r=[];return e.name?r.push(Qo(e.name)):e.expr&&r.push(`(${this.visit(e.expr,n)})`),e.ordering==="SORTBY_ASC"&&r.push("ASC"),e.ordering==="SORTBY_DESC"&&r.push("DESC"),e.nulls_ordering==="SORTBY_NULLS_FIRST"&&r.push("NULLS FIRST"),e.nulls_ordering==="SORTBY_NULLS_LAST"&&r.push("NULLS LAST"),r.join(" ")}constFoldCategory(e){if(!e?.names||e.arrayBounds&&e.arrayBounds.length>0)return null;let n=e.names.map(c=>c.String?.sval||c.String?.str).filter(Boolean);if(n.length===0)return null;let r=n.length===2&&n[0]==="pg_catalog"?n[1]:n.join("."),s=r.toLowerCase().trim();return Vs(this.enums,r)?"text":new Set(["bool","boolean"]).has(s)?"boolean":new Set(["int2","smallint","int4","integer","int","int8","bigint","serial","serial4","bigserial","serial8","smallserial","serial2"]).has(s)?"integer":new Set(["float4","real","float8","double precision","numeric","decimal"]).has(s)?"real":new Set(["text","varchar","character varying","char","character","bpchar","name","uuid"]).has(s)?"text":null}isFoldableCast(e,n){if(e.isnull)return true;let r=this.constFoldCategory(n);return r?"sval"in e?r==="text":"ival"in e?r==="integer":"fval"in e?r==="real":"boolval"in e?r==="boolean":false:false}findUnderlyingConst(e){let n=e;for(;"TypeCast"in n;){let r=n.TypeCast;if(!r.arg)return null;n=r.arg;}return "A_Const"in n?n.A_Const:null}unwrapConstCast(e){let n=e;for(;"TypeCast"in n;){let r=n.TypeCast;if(r.typeName?.arrayBounds&&r.typeName.arrayBounds.length>0||!r.arg)break;if("A_Const"in r.arg){if(!this.isFoldableCast(r.arg.A_Const,r.typeName))break;n=r.arg;continue}if("TypeCast"in r.arg){let s=this.findUnderlyingConst(r.arg);if(!s||!this.isFoldableCast(s,r.typeName))break;n=r.arg;continue}break}return n}tryFoldConstArrayElements(e,n){let r=[];for(let s of e){let i=this.unwrapConstCast(s);if("A_Const"in i){r.push(this.visit(i,n));continue}if(this.findUnderlyingConst(s)===null)return;r.push(this.visit(i,n));}return r}TypeCast(e,n){if(!e.arg||!e.typeName)return super.TypeCast(e,n);if([...this.helper.walk(e)].filter(({node:o})=>"A_Star"in o).length>0)throw new L({TypeCast:e},"A.* in type casts are not supported in SQLite");if(e.typeName.arrayBounds&&e.typeName.arrayBounds.length>0){if("A_Const"in e.arg&&e.arg.A_Const.sval){let o=e.arg.A_Const.sval.sval;if(o.startsWith("{")&&o.endsWith("}")){let a=e.typeName.names?.map(u=>u.String?.sval).filter(Boolean)??[],l=a.length===2&&a[0]==="pg_catalog"?a[1]:a[0],f=["text","varchar","character varying","char","bpchar","name","uuid"].includes(l?.toLowerCase());try{let u=this.parsePgArrayLiteral(o,f);return `'${JSON.stringify(u).replace(/'/g,"''")}'`}catch{}}}return this.visit(e.arg,n)}let s=this.visit(e.arg,n),i=this.TypeName(e.typeName,n);return `CAST(${s} AS ${i})`}A_ArrayExpr(e,n){let r=zt(e.elements),s=this.tryExtractStaticArray(r);return s!==void 0?`'${JSON.stringify(s).replace(/'/g,"''")}'`:`json_array(${r.map(o=>this.visit(o,n)).join(", ")})`}tryExtractStaticArray(e){let n=[];for(let r of e)if("A_ArrayExpr"in r){let s=zt(r.A_ArrayExpr.elements),i=this.tryExtractStaticArray(s);if(i===void 0)return;n.push(i);}else if("A_Const"in r){let s=r.A_Const;if(s.isnull)n.push(null);else if(s.ival)n.push(s.ival.ival);else if(s.fval)n.push(parseFloat(s.fval.fval));else if(s.sval)n.push(s.sval.sval);else if("boolval"in s)n.push(s.boolval.boolval===true);else return}else return;return n}parsePgArrayLiteral(e,n){if(!e.startsWith("{")||!e.endsWith("}"))throw new Error("Not a PG array literal");let r=e.slice(1,-1);if(r.length===0)return [];let s=[],i=0;for(;i<r.length;)if(r[i]==="{"){let o=0,a=i;for(;a<r.length;){if(r[a]==="{")o++;else if(r[a]==="}"&&(o--,o===0))break;a++;}s.push(this.parsePgArrayLiteral(r.slice(i,a+1),n)),i=a+1,r[i]===","&&i++;}else if(r[i]==='"'){let o=i+1,a="";for(;o<r.length&&r[o]!=='"';)r[o]==="\\"&&o++,a+=r[o],o++;s.push(a),i=o+1,r[i]===","&&i++;}else {let o=i;for(;o<r.length&&r[o]!==","&&r[o]!=="}";)o++;if(o===i)throw new Error("Malformed PG array literal");let a=r.slice(i,o);if(a==="NULL")s.push(null);else if(n)s.push(a);else {let l=Number(a);s.push(isNaN(l)?a:l);}i=o,r[i]===","&&i++;}return s}BetweenExpr(e,n){return super.A_Expr(e,n)}AlterTableStmt(e,n){let r=e.cmds??[],s=["AT_EnableRowSecurity","AT_ForceRowSecurity","AT_ChangeOwner"],i=r.filter(f=>"AlterTableCmd"in f&&!s.includes(f.AlterTableCmd.subtype));if(i.length===0)return "";if(!["OBJECT_TABLE","OBJECT_INDEX","OBJECT_VIEW"].includes(e.objtype))throw new L({AlterTableStmt:e},`AlterTableStmt with objtype ${e.objtype} is not supported`);let o=["AT_AddColumn","AT_DropColumn"],a=["AT_AlterColumnType","AT_SetNotNull","AT_DropNotNull","AT_ColumnDefault","AT_AddConstraint","AT_DropConstraint"],l=[],c=[];for(let f of i){let u=f.AlterTableCmd.subtype;if(o.includes(u)){let d={...e,cmds:[f]};l.push(super.AlterTableStmt(d,n));}else if(a.includes(u))c.push(f.AlterTableCmd);else throw new L({AlterTableStmt:e},`AlterTableCmd with subtype ${u} is not supported in SQLite`)}if(c.length>0){let f=this.getRelationName(e.relation);l.push(this.generateRebuildSql(f,c));}return l.join(`;
26
- `)}AlterTableCmd(e,n){if(!["AT_AddColumn","AT_DropColumn"].includes(e.subtype))throw new L({AlterTableCmd:e},`AlterTableCmd with subtype ${e.subtype} is not supported`);if(e.subtype==="AT_AddColumn"&&e.def&&"ColumnDef"in e.def){let s=this.ColumnDef(e.def.ColumnDef,n),i=n.objtype==="OBJECT_TYPE"?"ADD ATTRIBUTE":"ADD COLUMN",o=e.missing_ok?" IF NOT EXISTS":"";return `${i}${o} ${s}`}return e.subtype==="AT_DropColumn"&&e.behavior?super.AlterTableCmd({...e,behavior:void 0},n):super.AlterTableCmd(e,n)}DefineStmt(e,n){if(e.kind==="OBJECT_AGGREGATE")throw new Error("AGGREGATE definitions are not supported in SQLite");return super.DefineStmt(e,n)}InsertStmt(e,n){if("selectStmt"in e){let s=(e.selectStmt?.SelectStmt?.valuesLists??[]).map(i=>i.List?.items?.map(o=>"SetToDefault"in o));if(s.length===1&&s[0]?.every(i=>i===true))return super.InsertStmt({...e,selectStmt:void 0,cols:void 0},n);if(s.some(i=>i.some(o=>o===true)))throw new L({InsertStmt:e},"Insert with partial DEFAULT values is not supported")}return super.InsertStmt(e,n)}SelectStmt(e,n){if(this.helper.hasUnsafeStar())throw new L({SelectStmt:e},"Row-wise comparison using .* is not supported in SQLite. Expand to explicit per-column comparisons instead.");if(e.intoClause)throw new L({SelectStmt:e},"SELECT ... INTO clause is not supported in SQLite");if(e.distinctClause){let s=zt(e.distinctClause);if(s.length>0&&Object.keys(s[0]).length>0)throw new L({SelectStmt:e},"DISTINCT ON clause is not supported in SQLite. Use window functions instead.")}if(e.limitOffset&&!e.limitCount)throw new L({SelectStmt:e},"OFFSET without LIMIT is not supported in SQLite");let r=super.SelectStmt(e,n);if(/^SELECT\s+FROM/.test(r))throw new L({SelectStmt:e},"SELECT without a target list is not supported in SQLite");return r}JoinExpr(e,n){return e.alias&&this.Alias(e.alias,n),super.JoinExpr(e,n)}A_Const(e,n){if(e.bsval!==void 0)throw new L({A_Const:e},"Bit string literals are not supported in SQLite");let r=super.A_Const(e,n);return typeof r=="string"&&r.startsWith("E'")?r.substring(2,r.length-1):r}SortBy(e,n){if(e.sortby_dir==="SORTBY_USING"){let r=zt(e.useOp),s=r[0]?.String?.sval;if(r.length>1||!["<",">"].includes(s??""))throw new L({SortBy:e},"Only `USING <` or `USING >` are supported.");e.sortby_dir=s==="<"?"SORTBY_DESC":"SORTBY_ASC",e.useOp=void 0;}return super.SortBy(e,n)}RangeSubselect(e,n){if(e.lateral)throw new L({RangeSubselect:e},"LATERAL subqueries are not supported in SQLite");return super.RangeSubselect(e,n)}SubLink(e,n){if(["ANY_SUBLINK","ALL_SUBLINK"].includes(e.subLinkType))throw new L({SubLink:e},"ANY/ALL/SOME subqueries are not supported. Use NOT EXISTS or IN instead");if(e.subLinkType==="ARRAY_SUBLINK")throw new L({SubLink:e},"ARRAY subqueries are not supported in SQLite");return super.SubLink(e,n)}LockingClause(e,n){return ""}UpdateStmt(e,n){if(n.parentNodeTypes.includes("SelectStmt"))throw new L({UpdateStmt:e},"UPDATE ... FROM (SELECT ...) is not supported in SQLite");return super.UpdateStmt(e,n)}Alias(e,n){if(e.colnames&&e.colnames.length>0)throw new L({Alias:e},"Aliasing with column names is not supported in SQLite");return `AS "${e.aliasname}"`}CreateFunctionStmt(e,n){let r=e.options??[],s=e.returnType?.names?.map(c=>c.String?.sval).filter(Boolean).join("."),i=r.find(c=>c.DefElem?.defname==="language")?.DefElem?.arg?.String?.sval;if(s!=="trigger"||i!=="plpgsql")throw new L({CreateFunctionStmt:e},"Only trigger functions with LANGUAGE plpgsql are supported");let o=e.funcname?.map(c=>c.String?.sval).filter(Boolean).pop();if(!o)throw new Error("Function has no name");let a=r.find(c=>c.DefElem?.defname==="as")?.DefElem?.arg?.List?.items?.[0]?.String?.sval;if(!a)throw new Error("Function has no body");let l=this.plpgsqlParser.parse(a);return this.triggerFunctions.set(o,l),""}CreateTrigStmt(e,n){let r=e.trigname,s=this.RangeVar(e.relation,n),i=e.funcname?.map(u=>u.String?.sval).filter(Boolean).pop();if(!i)throw new Error(`Trigger "${r}" has no function reference`);let o=this.triggerFunctions.get(i);if(!o)throw new L({CreateTrigStmt:e},`Trigger "${r}" references unknown function "${i}"`);let a=e.timing===2?"BEFORE":e.timing===64?"INSTEAD OF":"AFTER",l=[];if(e.events&4&&l.push("INSERT"),e.events&8&&l.push("DELETE"),e.events&16)if(e.columns?.length){let u=e.columns.map(d=>d.String?.sval).filter(Boolean);l.push(`UPDATE OF ${u.join(", ")}`);}else l.push("UPDATE");let c=l.join(" OR "),f=this.buildTriggerBody(o,s,n);return [`CREATE TRIGGER ${r}`,`${a} ${c} ON ${s}`,"FOR EACH ROW","BEGIN",...f.map(u=>` ${u};`),"END"].join(`
27
- `)}buildTriggerBody(e,n,r){let s=[],i=[];for(let o of e.statements)if(o.type!=="return"){if(o.type==="assignment"){i.push(o);continue}i.length>0&&(s.push(this.buildAssignmentUpdate(i,n,r)),i.length=0),o.type==="dml"&&s.push(this.translateDml(o.sql,r));}return i.length>0&&s.push(this.buildAssignmentUpdate(i,n,r)),s}buildAssignmentUpdate(e,n,r){let s=e.map(i=>{let o=this.translateExpression(i.expression,r);return `${i.column} = ${o}`});return `UPDATE ${n} SET ${s.join(", ")} WHERE rowid = NEW.rowid`}translateExpression(e,n){try{let r=`SELECT ${e}`,s=e.trim().toLowerCase();return s==="now()"||s==="current_timestamp"?"datetime('now')":e}catch{return e}}flattenTriggerTableRef(e,n){let r=this.effectiveSchema(e);return r?this.schemaHandling==="prefix"?`${r}__${n}`:`"${r}.${n}"`:this.quoteBareIfNeeded(n)}translateDml(e,n){let r=/^(\s*)(insert\s+into|update|delete\s+from)\s+(?:"([^"]+)"|(\w+))\s*\.\s*(?:"([^"]+)"|(\w+))/i;return e=e.replace(r,(s,i,o,a,l,c,f)=>`${i}${o} ${this.flattenTriggerTableRef(a??l,c??f)}`),e.replace(/\bnow\(\)/gi,"datetime('now')").replace(/\bcurrent_timestamp\b/gi,"datetime('now')").replace(/\bgen_random_uuid\(\)/gi,this.uuidExpression()).replace(/\buuid_generate_v4\(\)/gi,this.uuidExpression())}uuidExpression(){return "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)))"}NullTest(e,n){if(e.arg?.ColumnRef?.fields?.length>1)throw new L({NullTest:e},"row-level NULL tests are not supported in SQLite");return super.NullTest(e,n)}RenameStmt(e,n){if(!e.renameType)throw new Error("RenameStmt requires renameType");if(e.renameType==="OBJECT_POLICY")return "";let r=["OBJECT_TABLE","OBJECT_VIEW","OBJECT_COLUMN"];if(e.renameType==="OBJECT_COLUMN"&&(e.relationType==="OBJECT_FOREIGN_TABLE"||e.relationType==="OBJECT_VIEW"))throw new L({RenameStmt:e},`RenameStmt with relationType ${e.relationType} is not supported`);if(!r.includes(e.renameType))throw new L({RenameStmt:e},`RenameStmt with renameType ${e.renameType} is not supported in SQLite`);return super.RenameStmt(e,n)}DropStmt(e,n){let r=e.removeType;if(["OBJECT_TABLE","OBJECT_VIEW","OBJECT_INDEX","OBJECT_TRIGGER"].includes(r))return this.foldDropObjectSchemas(e),super.DropStmt(e,n);if(["OBJECT_POLICY"].includes(r))return "";throw new L({DropStmt:e},`DROP with removeType ${r} is not supported in SQLite`)}foldDropObjectSchemas(e){let n=e.removeType==="OBJECT_TRIGGER"?3:2;for(let r of e.objects??[]){let s=r?.List?.items;if(!Array.isArray(s)||s.length!==n)continue;let i=s[0]?.String?.sval,o=s[1]?.String?.sval;if(typeof i!="string"||typeof o!="string")continue;let a=this.effectiveSchema(i),l=a===void 0?o:this.schemaHandling==="prefix"?`${a}__${o}`:`${a}.${o}`;s.splice(0,2,{String:{sval:l}});}}generateRebuildSql(e,n){if(!this.introspection)throw new Error(`ALTER TABLE on "${e}" requires 12-step rebuild but no introspection was provided. Pass introspection in DeparseOptions to enable column type changes, NOT NULL, defaults, and constraint modifications.`);let r=this.buildDesiredSchema(this.introspection,e,n),s=new cr,i=new ur,o=s.diff(this.introspection,r);return o.has_changes?i.plan(o,this.introspection,r).steps.filter(l=>!["disable_foreign_keys","begin_transaction","commit_transaction","enable_foreign_keys"].includes(l.type)).map(l=>l.sql).join(`
28
- `):""}buildDesiredSchema(e,n,r){let s={...e,tables:e.tables.map(i=>({...i})),columns:e.columns.map(i=>({...i})),indexes:e.indexes.map(i=>({...i})),foreign_keys:e.foreign_keys.map(i=>({...i})),primary_keys:e.primary_keys.map(i=>({...i})),views:e.views.map(i=>({...i})),triggers:(e.triggers??[]).map(i=>({...i})),check_constraints:e.check_constraints.map(i=>({...i})),unique_constraints:(e.unique_constraints??[]).map(i=>({...i})),comments:(e.comments??[]).map(i=>({...i})),custom_types:e.custom_types.map(i=>({...i}))};for(let i of r){let o=s.columns.findIndex(a=>a.table===n&&a.name===i.name);switch(i.subtype){case "AT_AlterColumnType":{if(o===-1)break;let a=this.extractTypeName(i);a&&(s.columns[o]={...s.columns[o],type:a.toLowerCase()});break}case "AT_SetNotNull":{if(o===-1)break;s.columns[o]={...s.columns[o],nullable:false};break}case "AT_DropNotNull":{if(o===-1)break;s.columns[o]={...s.columns[o],nullable:true};break}case "AT_ColumnDefault":{if(o===-1)break;if(i.def){let a=this.extractDefaultValue(i);s.columns[o]={...s.columns[o],default_value:a};}else s.columns[o]={...s.columns[o],default_value:null};break}case "AT_AddConstraint":case "AT_DropConstraint":{let a=s.tables.findIndex(l=>l.name===n);a!==-1&&(s.tables[a]={...s.tables[a],sql:s.tables[a].sql+" /* modified */"});break}}}return this.rebuildTableSql(s,n),s}rebuildTableSql(e,n){let r=e.tables.findIndex(u=>u.name===n);if(r===-1)return;let s=e.columns.filter(u=>u.table===n),i=e.foreign_keys.filter(u=>u.table===n),o=e.check_constraints.filter(u=>u.table===n),a=s.map(u=>{let d=`${N(u.name)} ${u.type||"TEXT"}`;return u.is_primary_key&&(d+=" PRIMARY KEY"),u.nullable||(d+=" NOT NULL"),u.default_value!=null&&(d+=` DEFAULT ${u.default_value}`),d}),l=i.map(u=>`FOREIGN KEY (${N(u.column)}) REFERENCES ${N(u.ref_table)}(${N(u.ref_column)}) ON UPDATE ${u.on_update} ON DELETE ${u.on_delete}`),c=o.map(u=>`CHECK (${u.expression})`),f=[...a,...l,...c];e.tables[r]={...e.tables[r],sql:`CREATE TABLE ${N(n)} (${f.join(", ")}) STRICT`};}extractTypeName(e){let n=e.def?.ColumnDef;return n?.typeName?.TypeName?(n.typeName.TypeName.names??[]).map(s=>s.String?.sval).filter(Boolean).pop()??null:null}extractDefaultValue(e){if(!e.def)return null;let n=this.unwrapConstCast(e.def);if("A_Const"in n){let r=n.A_Const;return r.isnull?null:r.ival?String(r.ival.ival??0):r.fval?r.fval.fval:r.sval?`'${String(r.sval.sval).replace(/'/g,"''")}'`:"boolval"in r?r.boolval.boolval?"1":"0":null}return "Integer"in n?String(n.Integer.ival):"Float"in n?n.Float.fval:"String"in n?`'${n.String.sval}'`:null}};});function sb(t){return `${t?.schemaname??"public"}.${t?.relname??""}`}function nk(t){let e=t?.Constraint;if(!e||e.contype!=="CONSTR_DEFAULT")return false;let n=e.raw_expr?.FuncCall?.funcname;if(!Array.isArray(n))return false;let r=n.map(s=>s.String?.sval??s.String?.str).filter(Boolean);return r[r.length-1]?.toLowerCase()==="nextval"}function rk(t){return (Array.isArray(t.constraints)?t.constraints:[]).some(n=>n.Constraint?.contype==="CONSTR_IDENTITY")}function ib(t,e){let n=Array.isArray(t.constraints)?t.constraints:[],r=n.filter(s=>!nk(s));r.length!==n.length?(t.constraints=r,e.add(t)):rk(t)&&e.add(t);}function sk(t,e){let n=e?.Constraint;if(!n)return false;let r=n.contype;if(r!=="CONSTR_PRIMARY"&&r!=="CONSTR_UNIQUE"&&r!=="CONSTR_FOREIGN")return false;let s=t.tableElts??[];return r==="CONSTR_PRIMARY"&&ob(t,n)||r==="CONSTR_FOREIGN"&&ab(t,n)||(s.push(e),t.tableElts=s),true}function ob(t,e){let n=(e.keys??[]).map(i=>i.String?.sval??i.String?.str).filter(Boolean);if(n.length!==1)return false;let r=(t.tableElts??[]).find(i=>"ColumnDef"in i&&i.ColumnDef.colname===n[0]);if(!r)return false;let s=Array.isArray(r.ColumnDef.constraints)?r.ColumnDef.constraints:[];return r.ColumnDef.constraints=[...s.filter(i=>i.Constraint?.contype!=="CONSTR_NOTNULL"),{Constraint:{contype:"CONSTR_PRIMARY"}}],true}function ab(t,e){let n=(e.fk_attrs??[]).map(i=>i.String?.sval??i.String?.str).filter(Boolean);if(n.length!==1)return false;let r=(t.tableElts??[]).find(i=>"ColumnDef"in i&&i.ColumnDef.colname===n[0]);if(!r)return false;let s=Array.isArray(r.ColumnDef.constraints)?r.ColumnDef.constraints:[];return r.ColumnDef.constraints=[...s,{Constraint:e}],true}function ik(t){let e=t.tableElts??[],n=e.filter(r=>{let s=r?.Constraint;return !s||s.contype!=="CONSTR_PRIMARY"?true:!ob(t,s)});n.length!==e.length&&(t.tableElts=n);}function ok(t){let e=t.tableElts??[],n=e.filter(r=>{let s=r?.Constraint;return !s||s.contype!=="CONSTR_FOREIGN"?true:!ab(t,s)});n.length!==e.length&&(t.tableElts=n);}function lb(t){let e=new WeakSet,n=new Map;for(let r of t.stmts??[]){let s=r.stmt;if(!s||!("CreateStmt"in s))continue;let i=s.CreateStmt;n.set(sb(i.relation),i);for(let o of i.tableElts??[])"ColumnDef"in o&&ib(o.ColumnDef,e);ik(i),ok(i);}for(let r of t.stmts??[]){let s=r.stmt;if(!s||!("AlterTableStmt"in s))continue;let i=s.AlterTableStmt,o=n.get(sb(i.relation)),a=i.cmds??[],l=[];for(let c of a){let f=c.AlterTableCmd;f?.subtype==="AT_AddColumn"&&f.def&&"ColumnDef"in f.def&&ib(f.def.ColumnDef,e),!(o&&f?.subtype==="AT_AddConstraint"&&f.def&&sk(o,f.def))&&l.push(c);}i.cmds=l;}return e}var cb=I(()=>{});var db={};Zs(db,{Policy:()=>Ge,deparseDdl:()=>Mu,deparseExpression:()=>lk,deparsePostgresDdl:()=>ak,deparseSelect:()=>ck,parse:()=>dr,parseExpression:()=>fb,translatePostgresDdl:()=>ub});async function ub(t,e={}){let n=await dr(t);return Mu(n,e).ddl}async function ak(t,e={}){let n=await dr(t);return {ast:n,...Mu(n,e)}}function Mu(t,e={}){let n=lb(t),r=Vy(t),s=Xy(t,r),i=Qy(t),o=Zy(t),a=eb(t),l=new sa(t,{...e,enums:r,serialColumns:n}),{policies:c,tables:f}=Yy(t,{defaultSchema:e.defaultSchema,validateMutations:e.strict});if(e.strict)for(let u of c){if(!s.get(`${u.data.schema??"public"}.${u.data.table}`))throw new Error(`Policy "${u.data.name}" references unknown table "${u.data.table}"`);if(!f.has(u.data.table))throw new Error(`RLS is not enabled on table "${u.data.table}"`)}return {ddl:l.deparseQuery(),enums:r,rls:{tables:f,policies:c},schema:s,vars:i,tableConstraints:o,comments:a}}async function fb(t){let n=(await dr(`SELECT 1 WHERE ${t}`)).stmts?.[0]?.stmt;if(!n||!("SelectStmt"in n))throw new Error("expected SelectStmt");let r=n.SelectStmt.whereClause;if(!r)throw new Error("no whereClause");return r}async function lk(t){let e=await fb(t);return new xn().deparse(e)}async function ck(t){let n=(await dr(t)).stmts?.[0]?.stmt;if(!n||!("SelectStmt"in n))throw new Error("expected SelectStmt");return new xn().deparse(n)}var Bu=I(()=>{qy();rb();cb();ju();Uu();Js();});function Wu(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),n.push.apply(n,r);}return n}function Ku(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Wu(Object(n),true).forEach(function(r){Tb(t,r,n[r]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Wu(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r));});}return t}function Tb(t,e,n){return e=Rb(e),e in t?Object.defineProperty(t,e,{value:n,enumerable:true,configurable:true,writable:true}):t[e]=n,t}function Rb(t){var e=Cb(t,"string");return typeof e=="symbol"?e:String(e)}function Cb(t,e){if(typeof t!="object"||t===null)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return (e==="string"?String:Number)(t)}var kb=Ju({}),je=kb;function Ju(t){return e.withOptions=n=>Ju(Ku(Ku({},t),n)),e;function e(n,...r){let s=typeof n=="string"?[n]:n.raw,{alignValues:i=false,escapeSpecialCharacters:o=Array.isArray(n),trimWhitespace:a=true}=t,l="";for(let u=0;u<s.length;u++){let d=s[u];if(o&&(d=d.replace(/\\\n[ \t]*/g,"").replace(/\\`/g,"`").replace(/\\\$/g,"$").replace(/\\\{/g,"{")),l+=d,u<r.length){let p=i?vb(r[u],l):r[u];l+=p;}}let c=l.split(`
25
+ FROM ${N(e)};`,description:`Copy data from ${N(e)} to ${N(l)}`,type:"copy_data"});}i.push({sql:`DROP TABLE ${N(e)};`,description:`Drop old table ${N(e)}`,type:"drop_table"}),i.push({sql:`ALTER TABLE ${N(l)} RENAME TO ${N(e)};`,description:`Rename ${N(l)} to ${N(e)}`,type:"rename_table"});let p=r.indexes.filter(y=>y.table===e);for(let y of p){let w=y.unique?"UNIQUE ":"",S=y.columns.map(b=>N(b)).join(", ");i.push({sql:`CREATE ${w}INDEX ${N(y.name)} ON ${N(e)} (${S});`,description:`Recreate index ${N(y.name)} on ${N(e)}`,type:"add_index"});}let g=r.triggers?.filter(y=>y.table===e)??[];for(let y of g)i.push({sql:`${y.sql};`,description:`Recreate trigger ${N(y.name)} on ${N(e)}`,type:"create_trigger"});let m=s.columns.filter(y=>y.table===e&&y.type==="removed");for(let y of m)o.push({table:e,reason:`column "${y.name}" will be dropped`});let h=s.columns.filter(y=>y.table===e&&y.type==="modified");for(let y of h)y.changes?.type&&o.push({table:e,reason:`column "${y.name}" type changes from ${y.changes.type.from} to ${y.changes.type.to}`}),y.changes?.nullable&&!y.changes.nullable.to&&o.push({table:e,reason:`column "${y.name}" becomes NOT NULL`});return {steps:i,warnings:o}}canSimpleAlter(e,n,r){let s=n.columns.filter(u=>u.table===e),i=s.filter(u=>u.type==="added"),o=s.filter(u=>u.type==="removed"),a=s.filter(u=>u.type==="modified"),l=n.foreign_keys.some(u=>u.table===e);if(o.length>0||a.length>0||l)return {canAlter:false,addedCols:i};let c=r.tables.find(u=>u.name===e);return c&&/\bCHECK\s*\(/i.test(c.sql)?{canAlter:false,addedCols:i}:{canAlter:i.every(u=>{let d=u.column;return this.hasNonConstantDefault(d.default_value)?false:d.nullable||d.default_value!=null})&&i.length>0,addedCols:i}}hasNonConstantDefault(e){if(e==null)return false;let n=e.trim().toUpperCase();return FC.includes(n)}columnDef(e){let n=e.column,r=`${N(n.name)} ${n.type||"TEXT"}`;return n.nullable||(r+=" NOT NULL"),n.default_value!=null&&(r+=` DEFAULT ${n.default_value}`),r}};});async function dr(t){let{parse:e}=await import('pgsql-parser');return e(t)}var Jy=I(()=>{});function zs(t){if("String"in t)return t.String.sval}function At(t){return t.map(zs).filter(e=>e!=null)}function zt(t){return t==null?[]:t.List!==void 0?t.List.items||[]:Array.isArray(t)?t:[t]}function Zo(t){return QuoteUtils.quoteIdentifier(t)}function pr(t){return Object.keys(t)[0]}function Gy(t){if("A_Const"in t){if(t.A_Const.ival)return t.A_Const.ival.ival;if(t.A_Const.fval)return t.A_Const.fval.fval;if(t.A_Const.sval)return t.A_Const.sval.sval;if(t.A_Const.boolval)return t.A_Const.boolval.boolval;if(t.A_Const.isnull)return null}}var _n=I(()=>{});function Vy(t){let e=t.toLowerCase().trim();if(e.startsWith("_")||e.endsWith("[]"))return "TEXT";let n=XC[e];if(!n)throw new En(`Unsupported PostgreSQL type: "${t}"`);return n}function ea(t){let e=t.toLowerCase();return ["serial","serial4","bigserial","serial8","smallserial","serial2"].includes(e)}function ta(t){let e=t.toLowerCase();return ["varchar","character varying","char","character","bpchar"].includes(e)}function na(t){let e=t.toLowerCase();return ["numeric","decimal"].includes(e)}var En,D,XC,zy,YC,ra,mr=I(()=>{_n();En=class extends Error{},D=class extends En{constructor(n,r){super(r??`Unsupported node type: ${pr(n)}`);this.node=n;}},XC={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"},zy=["<",">","<=",">=","=","<>","!=","+","-","*","/","%","&","|","<<",">>","||","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","->>"];YC={CreateEnumStmt:{react:"ignore"},CreateDomainStmt:{react:"warn"},CreateSeqStmt:{react:"ignore"},AlterSeqStmt:{react:"ignore"},CreateSchemaStmt:{react:"warn"},CreatePolicyStmt:{react:"ignore"},AlterPolicyStmt:{react:"ignore"},PartitionElem:{react:"error"},PartitionCmd:{react:"error"},VariableSetStmt:{react:"ignore"},CompositeTypeStmt:{react:"error"},AlterEnumStmt:{react:"error"},AlterObjectSchemaStmt:{react:"error"},AlterOwnerStmt:{react:"error"},AlterTypeStmt:{react:"error"},AlterFunctionStmt:{react:"error"},AlterDefaultPrivilegesStmt:{react:"error"},GrantStmt:{react:"error"},GrantRoleStmt:{react:"error"},CopyStmt:{react:"error"},CreateCastStmt:{react:"error"},AlterOpFamilyStmt:{react:"error"},AlterOperatorStmt:{react:"error"},TruncateStmt:{react:"error"},A_Indirection:{react:"error"},XmlExpr:{react:"error"},XmlSerialize:{react:"error"},RangeTableSample:{react:"error"},GroupingSet:{react:"error"}},ra=new Map(Object.entries(YC));});var ze,xn,Mu=I(()=>{_n();mr();ze=class extends D{constructor(e,n){super(e,`Unsupported expression: ${n}`);}},xn=class{deparse(e){if("A_Const"in e){let s=e.A_Const;if(s.boolval!==void 0)return s.boolval.boolval?{}:{$always:false}}let n=Object.keys(e)[0],r=this[n];if(!r)throw new ze({[n]:e},`Unsupported expression: ${n}`);return r.call(this,e[n])}deparseValue(e){if("A_Const"in e)return this.A_Const(e.A_Const);if("ColumnRef"in e)return this.ColumnRef(e.ColumnRef);if("FuncCall"in e)return this.FuncCall(e.FuncCall);if("SubLink"in e)return this.SubLink(e.SubLink);if("TypeCast"in e)return this.TypeCast(e.TypeCast);if("A_Expr"in e){let r=this.isJwtAccessor(e.A_Expr);return r||this.A_Expr(e.A_Expr)}if("BoolExpr"in e)return this.BoolExpr(e.BoolExpr);let n=Object.keys(e)[0];throw new ze({[n]:e},`deparseValue: ${n}`)}A_Expr(e){if(e.kind==="AEXPR_OP"){let n=e.name?.[0],r=n?zs(n):void 0;if(!r)throw new ze({A_Expr:e},"A_Expr missing operator");let s=this.isJwtAccessor(e);if(s)return {[s]:{}};let i=e.lexpr?this.deparseValue(e.lexpr):void 0,o=e.rexpr?this.deparseValue(e.rexpr):void 0,a=this.mapOperator(r);if(!a)throw new ze({A_Expr:e},`Unsupported operator: ${r}`);let l=e.rexpr!=null&&"ColumnRef"in e.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(e.kind==="AEXPR_LIKE"||e.kind==="AEXPR_ILIKE"){let n=e.lexpr?this.deparseValue(e.lexpr):void 0,r=e.rexpr?this.deparseValue(e.rexpr):void 0,i=(e.name?.[0]?zs(e.name[0]):"~~")==="!~~"?"$notLike":"$like";return {[n]:{[i]:r}}}if(e.kind==="AEXPR_IN"){let n=e.lexpr?this.deparseValue(e.lexpr):void 0,r=e.rexpr&&"List"in e.rexpr&&e.rexpr.List.items?e.rexpr.List.items.map(s=>this.deparseValue(s)):[];return {[n]:{$in:r}}}throw new ze({A_Expr:e},`A_Expr kind: ${e.kind}`)}BoolExpr(e){let n=e.args??[];switch(e.boolop){case "AND_EXPR":return {$and:n.map(r=>this.deparse(r))};case "OR_EXPR":return {$or:n.map(r=>this.deparse(r))};case "NOT_EXPR":return {$not:this.deparse(n[0])};default:throw new ze({BoolExpr:e},`BoolExpr op: ${e.boolop}`)}}NullTest(e){let n=e.arg?this.deparseValue(e.arg):void 0;return e.nulltesttype==="IS_NULL"?{[n]:{$is:null}}:{[n]:{$isNot:null}}}SubLink(e){if(e.subLinkType==="ANY_SUBLINK"){let n=e.testexpr?this.deparseValue(e.testexpr):void 0,r=e.subselect?this.SelectStmt(e.subselect.SelectStmt):void 0;return {[n]:{$in:r}}}if(e.subLinkType==="EXISTS_SUBLINK")return {$exists:e.subselect?this.SelectStmt(e.subselect.SelectStmt):void 0};if(e.subLinkType==="EXPR_SUBLINK"){let n=e.subselect?e.subselect.SelectStmt:void 0;if(n?.fromClause?.length)return this.SelectStmt(n);if(n?.targetList?.[0]){let r=n.targetList[0],s="ResTarget"in r?r.ResTarget:void 0;if(s?.val){let i=this.deparseValue(s.val);return i}}}throw new ze({SubLink:e},`SubLink type: ${e.subLinkType}`)}SelectStmt(e){let{from:n,schema:r,join:s}=this.deparseFromClause(e.fromClause??[]),i=[];for(let d of e.targetList??[]){let p="ResTarget"in d?d.ResTarget:void 0;if(p?.val){let g=this.deparseValue(p.val);Array.isArray(g)?i.push(...g.map(String)):g!=null&&g!==""&&i.push(String(g));}}let o=e.whereClause?this.deparse(e.whereClause):void 0,a=this.deparseSortClause(e.sortClause),l=this.deparseLimit(e.limitCount),c=this.deparseLimit(e.limitOffset),f=this.deparseGroupClause(e.groupClause),u={type:"query",from:n,select:i};return r&&(u.schema=r),Object.keys(s).length>0&&(u.join=s),o&&(u.where=o),a.length>0&&(u.order=a),l!==void 0&&(u.limit=l),c!==void 0&&(u.offset=c),f.length>0&&(u.group=f),u}FuncCall(e){let n=this.isAuthFunc(e.funcname??[]);if(n)return n;throw new ze({FuncCall:e},`FuncCall: ${At(e.funcname??[]).join(".")}`)}ColumnRef(e){let n=At(e.fields??[]);return n.length===1?n[0]:n.join(".")}A_Const(e){if(e.boolval!==void 0)return e.boolval.boolval;if(e.ival!==void 0)return e.ival.ival??0;if(e.fval!==void 0)return parseFloat(e.fval.fval??"0");if(e.sval!==void 0)return e.sval.sval??"";if(e.isnull)return null;throw new ze({A_Const:e},"A_Const: unknown variant")}TypeCast(e){if(!e.arg)throw new ze({TypeCast:e},"TypeCast: missing arg");return this.deparseValue(e.arg)}BooleanTest(e){let n=e.arg?this.deparseValue(e.arg):void 0;return e.booltesttype==="IS_TRUE"?{[n]:{$eq:true}}:{[n]:{$eq:false}}}deparseFromClause(e){let n={};if(e.length===0)return {from:"",join:n};let r=e[0];if("RangeVar"in r){let s=r.RangeVar;return {from:s.relname??"",schema:s.schemaname,join:n}}if("JoinExpr"in r){let{from:s,schema:i}=this.walkJoinExpr(r.JoinExpr,n);return {from:s,schema:i,join:n}}return {from:"",join:n}}walkJoinExpr(e,n){let r={from:""};if(e.larg)if("RangeVar"in e.larg){let s=e.larg.RangeVar;r={from:s.relname??"",schema:s.schemaname};}else "JoinExpr"in e.larg&&(r=this.walkJoinExpr(e.larg.JoinExpr,n));if(e.rarg&&"RangeVar"in e.rarg){let s=e.rarg.RangeVar,i=s.relname??"",o=s.alias?.aliasname??i,a=e.jointype==="JOIN_LEFT"?"left":"inner",l={from:i,type:a};e.quals&&(l.on=this.deparse(e.quals));let c=o;if(c in n){let f=2;for(;`${c}_${f}`in n;)f++;c=`${c}_${f}`;}n[c]=l;}return r}deparseSortClause(e){if(!e)return [];let n=[];for(let r of e){if(!("SortBy"in r))continue;let s=r.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),n.push(a);}return n}deparseLimit(e){if(!e)return;let n=this.deparseValue(e);return typeof n=="number"?n:Number(n)}deparseGroupClause(e){return e?e.map(n=>String(this.deparseValue(n))):[]}isAuthFunc(e){let n=At(e);if(n.length===2&&n[0]==="auth"){if(n[1]==="uid")return "{{auth.uid}}";if(n[1]==="jwt")return "{{auth.jwt}}";if(n[1]==="role")return "{{auth.role}}";throw new Error(`Unsupported auth function: "${n.slice(1).join(".")}"`)}return null}isJwtAccessor(e){if(e.kind!=="AEXPR_OP")return null;let n=e.name?.[0]?zs(e.name[0]):void 0;if(n!=="->"&&n!=="->>")return null;let r=e.rexpr&&"A_Const"in e.rexpr?e.rexpr.A_Const.sval?.sval:void 0;if(r===void 0)return null;if(e.lexpr&&"FuncCall"in e.lexpr)return this.isAuthFunc(e.lexpr.FuncCall.funcname??[])==="{{auth.jwt}}"?`{{auth.jwt.${r}}}`:null;if(e.lexpr&&"A_Expr"in e.lexpr){let s=this.isJwtAccessor(e.lexpr.A_Expr);if(s)return `${s.slice(0,-2)}.${r}}}`}return null}mapOperator(e){switch(e){case "=":return "$eq";case "<>":case "!=":return "$neq";case ">":return "$gt";case ">=":return "$gte";case "<":return "$lt";case "<=":return "$lte";case "~~":return "$like";case "!~~":return "$notLike";default:return}}};});function Zy(t){let e=new Map;for(let n of t.stmts??[]){if(!n.stmt||!("CreateEnumStmt"in n.stmt))continue;let r=n.stmt.CreateEnumStmt,s=At(r.typeName??[]).join(".");if(!s||!r.vals)continue;let i=At(r.vals),o=s.toLowerCase();e.set(o,i),o.startsWith("public.")&&e.set(o.slice(7),i);}return e}function Vs(t,e){let n=e.toLowerCase(),r=t.get(n);return r||(n.startsWith("public.")?t.get(n.slice(7)):t.get(`public.${n}`))}function eb(t){let e=new Map;for(let n of t.stmts??[]){if(!n.stmt||!("VariableSetStmt"in n.stmt))continue;let r=n.stmt.VariableSetStmt,s=r.name,i=Gy(r.args?.[0]??{});e.set(s,{value:i,local:r.is_local});}return e}function Xy(t){let e=[],n=false;for(let r of t??[])if("RoleSpec"in r){let s=r.RoleSpec;s.roletype==="ROLESPEC_PUBLIC"?s.location===-1&&(n=true):s.roletype==="ROLESPEC_CSTRING"&&s.rolename&&e.push(s.rolename);}return {roles:e,implicitPublic:n}}function sa(t,e){return t&&t.length>0?t:e}function Bu(t,e,n){return t.findIndex(r=>r.data.name===e.name&&r.data.table===e.table&&sa(r.data.schema,n)===sa(e.schema,n))}function qu(t,e){return new Error(`policy "${t}" for table "${e}" does not exist`)}function Yy(t,e,n,r){return t.data.table===e&&sa(t.data.schema,r)===sa(n,r)}function tb(t,e={}){let n=e.defaultSchema||"public",r=e.validateMutations===true,s=new xn,i=new Set,o=[];for(let a of t.stmts??[])if(a.stmt){if("CreatePolicyStmt"in a.stmt){let l=a.stmt.CreatePolicyStmt,c=l.table?.relname??"",f=l.table?.schemaname,u={select:"SELECT",insert:"INSERT",update:"UPDATE",delete:"DELETE"},d=l.cmd_name?u[l.cmd_name]??"ALL":"ALL",p=l.permissive===true,{roles:g,implicitPublic:m}=Xy(l.roles),h=l.qual?s.deparse(l.qual):void 0,y=l.with_check?s.deparse(l.with_check):void 0;if(m){let S=f?`${f}.${c}`:c,b=l.policy_name??"",_=`${S}::${b}`;if(!Qy.has(_)){Qy.add(_);let E=JSON.stringify(h)+JSON.stringify(y);/\{\{auth\.(uid|jwt|role)/i.test(E)||console.warn(`[supalite] policy "${b}" on "${S}" has no TO clause \u2014 applies to all roles (PUBLIC). For clarity, prefer an explicit \`TO <role>\` clause (e.g. \`TO authenticated\`).`);}}let w=new Ge({name:l.policy_name??"",table:c,schema:f,command:d,permissive:p,roles:g,using:h,withCheck:y});o.push(w);}if("DropStmt"in a.stmt&&a.stmt.DropStmt.removeType==="OBJECT_POLICY"){let l=a.stmt.DropStmt,c=l.objects?.[0];if(c&&"List"in c){let f=At(c.List.items??[]),u=f[f.length-1],d=f[f.length-2],p=f.length>=3?f[f.length-3]:void 0;if(u&&d){let g=Bu(o,{name:u,table:d,schema:p},n);if(g!==-1)o.splice(g,1);else if(r&&!l.missing_ok)throw qu(u,d)}}}if("AlterPolicyStmt"in a.stmt){let l=a.stmt.AlterPolicyStmt,c=l.policy_name??"",f=l.table?.relname??"",u=l.table?.schemaname,d=Bu(o,{name:c,table:f,schema:u},n);if(d===-1){if(r)throw qu(c,f);continue}let p=o[d].data,g=l.roles?Xy(l.roles).roles:p.roles,m=l.qual?s.deparse(l.qual):p.using,h=l.with_check?s.deparse(l.with_check):p.withCheck;o[d]=new Ge({...p,roles:g,using:m,withCheck:h});}if("RenameStmt"in a.stmt&&a.stmt.RenameStmt.renameType==="OBJECT_POLICY"){let l=a.stmt.RenameStmt,c=l.subname??"",f=l.relation?.relname??"",u=l.relation?.schemaname,d=Bu(o,{name:c,table:f,schema:u},n);if(d===-1){if(r)throw qu(c,f);continue}l.newname&&(o[d]=new Ge({...o[d].data,name:l.newname}));}if("RenameStmt"in a.stmt&&a.stmt.RenameStmt.renameType==="OBJECT_TABLE"){let l=a.stmt.RenameStmt,c=l.relation?.relname??"",f=l.newname??"",u=l.relation?.schemaname;if(c&&f&&c!==f){i.delete(c)&&i.add(f);for(let d=0;d<o.length;d++)Yy(o[d],c,u,n)&&(o[d]=new Ge({...o[d].data,table:f}));}}if("DropStmt"in a.stmt&&a.stmt.DropStmt.removeType==="OBJECT_TABLE")for(let l of a.stmt.DropStmt.objects??[]){if(!("List"in l))continue;let c=At(l.List.items??[]),f=c[c.length-1],u=c.length>=2?c[c.length-2]:void 0;if(f){i.delete(f);for(let d=o.length-1;d>=0;d--)Yy(o[d],f,u,n)&&o.splice(d,1);}}if("AlterTableStmt"in a.stmt){let l=a.stmt.AlterTableStmt,c=l.relation?.relname??"";for(let f of l.cmds??[]){if(!("AlterTableCmd"in f))continue;let u=f.AlterTableCmd.subtype;u==="AT_EnableRowSecurity"?i.add(c):u==="AT_DisableRowSecurity"&&i.delete(c);}}}return {policies:o,tables:i}}function nb(t,e){let n=new Map;for(let r of t.stmts??[]){if(!r.stmt||!("CreateStmt"in r.stmt))continue;let s=r.stmt.CreateStmt,i=s.relation?.relname??"",o=s.relation?.schemaname??"public";if(!i)continue;let a=new at(i,o);for(let l of s.tableElts??[]){if(!("ColumnDef"in l))continue;let c=l.ColumnDef,f=c.colname;if(!f)continue;let u=c.typeName?.names?.map(R=>R.String?.sval||R.String?.str).filter(Boolean),d=u&&u.length>0?u.length===2&&u[0]==="pg_catalog"?u[1]:u.join("."):void 0;if(!d)continue;let p=!!c.typeName?.arrayBounds?.length,g=Array.isArray(c.typeName?.typmods)?c.typeName.typmods:[],m=R=>g[R]?.A_Const?.ival?.ival??g[R]?.A_Const?.val?.ival?.ival,h={isArray:p};if(ta(d)&&g.length>0){let R=m(0);typeof R=="number"&&R>0&&(h.lengthConstraint=R);}if(na(d)&&g.length>=2){let R=m(0),U=m(1);typeof R=="number"&&typeof U=="number"&&R>0&&U>=0&&(h.numericPrecision={precision:R,scale:U});}let y=Vs(e,d);y&&(h.enumValues=y);let w=Array.isArray(c.constraints)?c.constraints:[],S=w.some(R=>R.Constraint?.contype==="CONSTR_PRIMARY"),b=ea(d)||w.some(R=>R.Constraint?.contype==="CONSTR_IDENTITY"),_=w.some(R=>R.Constraint?.contype==="CONSTR_NOTNULL"),E=w.find(R=>R.Constraint?.contype==="CONSTR_UNIQUE"),x=w.find(R=>R.Constraint?.contype==="CONSTR_GENERATED"),O=w.find(R=>R.Constraint?.contype==="CONSTR_FOREIGN"),v=w.find(R=>R.Constraint?.contype==="CONSTR_CHECK"),P;if(O){let R=O.Constraint,U=R.pktable?.relname,J=R.pktable?.schemaname,F=R.pk_attrs?.[0]?.String?.sval;U&&F&&(P={refSchema:J,refTable:U,refColumn:F,constraintName:R.conname||void 0});}let C={schema:o,table:i,column:f,pgTypeName:d,nullable:!_&&!S,defaultValue:null,defaultFn:null,isPrimaryKey:S,isUnique:!!E,isSerial:b,isGenerated:!!x,fkRef:P,hasCheck:!!v,checkConstraintName:v?.Constraint?.conname||void 0,uniqueConstraintName:E?.Constraint?.conname||void 0};a.set(f,We(C,h));}n.set(`${o}.${i}`,a);}return n}function rb(t){let e=[];for(let n of t.stmts??[]){if(!n.stmt||!("CreateStmt"in n.stmt))continue;let r=n.stmt.CreateStmt,s=r.relation?.relname??"",i=r.relation?.schemaname??"public";if(s)for(let o of r.tableElts??[]){if("ColumnDef"in o){let f=o.ColumnDef,u=f?.colname;if(!u)continue;for(let d of f.constraints??[]){let p=d?.Constraint;if(!p||p.contype!=="CONSTR_FOREIGN")continue;let g=p.pktable?.relname;if(!g)continue;let m=(p.pk_attrs??[]).map(h=>h.String?.sval??h.String?.str).filter(Boolean);e.push({schema:i,table:s,kind:"foreign_key",name:p.conname||void 0,columns:[u],refSchema:p.pktable?.schemaname,refTable:g,refColumns:m});}continue}let a=o;if(!a.Constraint)continue;let l=a.Constraint,c=l.contype;if(c==="CONSTR_UNIQUE"){let f=(l.keys??[]).map(u=>u.String?.sval??u.String?.str).filter(Boolean);if(f.length===0)continue;e.push({schema:i,table:s,kind:"unique",name:l.conname||void 0,columns:f});}else if(c==="CONSTR_CHECK")e.push({schema:i,table:s,kind:"check",name:l.conname||void 0,columns:[]});else if(c==="CONSTR_FOREIGN"){let f=(l.fk_attrs??[]).map(p=>p.String?.sval??p.String?.str).filter(Boolean),u=(l.pk_attrs??[]).map(p=>p.String?.sval??p.String?.str).filter(Boolean),d=l.pktable?.relname;if(!d)continue;e.push({schema:i,table:s,kind:"foreign_key",name:l.conname||void 0,columns:f,refSchema:l.pktable?.schemaname,refTable:d,refColumns:u});}}}return e}function sb(t){let e=[];for(let n of t.stmts??[]){if(!n.stmt||!("CommentStmt"in n.stmt))continue;let r=n.stmt.CommentStmt,s=r.comment??"";if(!s)continue;let i=r.objtype,o=(r.object?.List?.items??r.object?.items??[]).map(a=>a.String?.sval??a.String?.str).filter(Boolean);if(o.length!==0){if(i==="OBJECT_TABLE"||i==="OBJECT_VIEW"){let[a,l]=o.length>=2?o:["public",o[0]];e.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,e.push({schema:a,table:l,column:c,text:s});}}}return e}var Qy,Hu=I(()=>{Mu();_n();Js();tc();mr();Qy=new Set;});var ia,ib=I(()=>{mr();_n();ia=class{constructor(e){this.ast=e;this.result=[...this.walk(this.ast,[],{trackPaths:["returningList"]})];}result=[];*walk(e=this.ast,n=[],r={}){if(!e||typeof e!="object")return;let{trackPaths:s=[]}=r;if(Array.isArray(e)){for(let o=0;o<e.length;o++)yield*this.walk(e[o],n,r);return}let i=Object.keys(e);if(i.length===1&&i[0][0]>="A"&&i[0][0]<="Z"){let o=i[0];yield {node:e,path:n},yield*this.walk(e[o],[...n,o],r);}else for(let[o,a]of Object.entries(e))if(a&&typeof a=="object"){let l=s.includes(o)?[...n,o]:n;yield*this.walk(a,l,r);}}containsUnsupportedNode(){for(let{node:e}of this.result){let n=pr(e),r=ra.get(n);if(r&&r.react==="error")return true}}hasFuncCall(){for(let{node:e}of this.result)if("FuncCall"in e)return true;return false}getFuncCalls(){return Array.from(this.result).map(({node:e})=>e).filter(e=>"FuncCall"in e).map(e=>e.FuncCall)}getFuncCallNames(){return this.getFuncCalls().flatMap(e=>e.funcname?.map(n=>n.String?.sval||n.String?.str))}hasSqlValueFunction(){for(let{node:e}of this.result)if("SQLValueFunction"in e)return true;return false}getSqlValueFunctions(){return Array.from(this.result).map(({node:e})=>e).filter(e=>"SQLValueFunction"in e).map(e=>e.SQLValueFunction)}getSqlValueFunctionNames(){return this.getSqlValueFunctions().map(e=>e.op)}hasUnsafeStar(){let e=this.result.filter(({node:n})=>"A_Star"in n);if(e.length===0)return false;for(let{path:n}of e)if(!n.includes("SelectStmt")&&!n.includes("returningList"))return true;return false}getRelationDefinitions(){return this.result.filter(({node:n})=>"CreateStmt"in n).map(({node:n})=>n.CreateStmt).map(n=>({relation:{relname:n.relation?.relname??"",inh:n.relation?.inh,relpersistence:n.relation?.relpersistence},columns:n.tableElts?.map(r=>{let s=r.ColumnDef?.typeName?.names?.map(o=>"String"in o?o.String.sval:""),i=s?.some(o=>o.toLowerCase().includes("pg_catalog"));return {name:r.ColumnDef?.colname??"",is_local:r.ColumnDef?.is_local,pg_catalog:i,type:s?.filter(o=>!o.toLowerCase().includes("pg_catalog"))[0]??"",types:s,constraints:r.ColumnDef?.constraints}})}))}getRelationColumnTypes(){return {has_non_pg_catalog_types:this.getRelationDefinitions().some(e=>e.columns?.some(n=>!n.pg_catalog)),types:Array.from(new Set(this.getRelationDefinitions().flatMap(e=>e.columns?.map(n=>n.type))))}}};});var ek,tk,nk,rk,hr,oa,ob=I(()=>{mr();ek=["DECLARE","IF","ELSIF","ELSE","LOOP","WHILE","FOR","FOREACH","EXCEPTION","RAISE","PERFORM","EXECUTE","SELECT"],tk=/^NEW\.(\w+)\s*(?::=|=)\s*(.+)$/is,nk=/^RETURN\s+(NEW|OLD)$/i,rk=/^(INSERT|UPDATE|DELETE)\b/i,hr=class extends En{constructor(n,r,s){super(s??`Unsupported PL/pgSQL: ${n}`);this.hint=n;this.body=r;}},oa=class{parse(e){let n=this.extractBlock(e),r=this.splitStatements(n),s=[],i=null;for(let o of r){let a=o.trim();if(!a)continue;this.rejectUnsupported(a);let l=a.match(nk);if(l){i=l[1].toUpperCase(),s.push({type:"return",value:i});continue}let c=a.match(tk);if(c){s.push({type:"assignment",column:c[1],expression:c[2].trim()});continue}if(rk.test(a)){s.push({type:"dml",sql:a});continue}throw new hr(`"${a.substring(0,80)}" is not translatable to SQLite`,n)}if(!i)throw new En("Trigger function body must end with RETURN NEW or RETURN OLD");return {statements:s,returnValue:i}}extractBlock(e){let n=e.trim(),r=n.toUpperCase();if(/^\s*DECLARE\b/i.test(n))throw new hr('"DECLARE" is not translatable to SQLite',e);let s=r.indexOf("BEGIN"),i=r.lastIndexOf("END");if(s===-1||i===-1||i<=s)throw new hr("Expected BEGIN ... END block in trigger function body",e);return n.slice(s+5,i).trim()}splitStatements(e){let n=[],r="",s=0,i=false,o="";for(let l=0;l<e.length;l++){let c=e[l];if(i){r+=c,c===o&&(l+1<e.length&&e[l+1]===o?r+=e[++l]:i=false);continue}if(c==="'"||c==='"'){i=true,o=c,r+=c;continue}if(c==="("){s++,r+=c;continue}if(c===")"){s--,r+=c;continue}if(c===";"&&s===0){n.push(r.trim()),r="";continue}r+=c;}let a=r.trim();return a&&n.push(a),n}rejectUnsupported(e){let n=e.match(/^(\w+)/)?.[1]?.toUpperCase();if(n&&ek.includes(n))throw new hr(`"${n}" is not translatable to SQLite`,e)}};});function lk(t){let e=t?.GrantStmt??t;return e?.is_grant!==true?false:e.targtype==="ACL_TARGET_ALL_IN_SCHEMA"?e.objtype==="OBJECT_TABLE"||e.objtype==="OBJECT_SEQUENCE":e.targtype==="ACL_TARGET_OBJECT"&&ak.has(e.objtype)}function ab(t){return t?.String?.sval}var ak,Wu,aa,lb=I(()=>{mr();Hu();_n();_n();ib();Xr();ob();Jo();Du();ju();Fn();oo();Zl();ak=new Set(["OBJECT_TABLE","OBJECT_VIEW","OBJECT_SEQUENCE","OBJECT_SCHEMA"]);Wu=new Set(["plpgsql","pgcrypto","uuid-ossp"]);aa=class extends Deparser{enums;schemaHandling;warnings=[];helper;config;triggerFunctions=new Map;plpgsqlParser=new oa;introspection;functionResolution;serialColumns;constructor(e,{enums:n,schemaHandling:r,introspection:s,serialColumns:i,...o}={}){super(e,o),this.schemaHandling=r??"default",this.enums=n??new Map,this.helper=new ia(e),this.config=o,this.introspection=s,this.functionResolution=o?.functionResolution??"translate",this.serialColumns=i??new WeakSet;}visit(e,n){let r=pr(e);if(r==="GrantStmt"&&lk(e))return "";let s=e.AlterObjectSchemaStmt;if(r==="AlterObjectSchemaStmt"&&s?.objectType==="OBJECT_EXTENSION"){let o=ab(s.object);if(o&&Wu.has(o))return "";throw new D({[r]:e},"ALTER EXTENSION is not supported in SQLite")}if(r==="AlterExtensionStmt"||r==="AlterExtensionContentsStmt")throw new D({[r]:e},"ALTER EXTENSION is not supported in SQLite");let i=ra.get(r);if(i){if(i.react==="error")throw new D({[r]:e},`Unsupported node type: ${r}`);return i.react==="warn"&&this.warnings.push({type:r,node:e}),""}return super.visit(e,n)}CreateExtensionStmt(e,n){let r=e.extname??"";if(Wu.has(r))return "";throw new D({CreateExtensionStmt:e},`CREATE EXTENSION ${JSON.stringify(r)} is not supported in SQLite`)}deparse(e,n){if(e==null)return null;if(!n){let r=new SqlFormatter;n=new DeparserContext({formatter:r});}return typeof e=="number"||e instanceof Number?e.toString():this.visit(e,n)}RawStmt(e,n){if(!e.stmt||e.stmt.CommentStmt)return "";let r=this.deparse(e.stmt,n);return !r||r.length===0?"":e.stmt_len?r+";":r}RangeVar(e,n){this.ensureRelation(e);let r=this.effectiveSchema(e.schemaname),s=e.relname,i=this.quoteBareIfNeeded(s);r&&(this.schemaHandling==="prefix"?i=`${r}__${s}`:i=`"${r}.${s}"`);let o=e.alias?" "+this.Alias(e.alias,n):"";return i+o}getRelationName(e){this.ensureRelation(e);let n=this.effectiveSchema(e.schemaname),r=e.relname;return n?this.schemaHandling==="prefix"?`${n}__${r}`:`${n}.${r}`:r}quoteBareIfNeeded(e){return /^[A-Za-z_][A-Za-z0-9_]*$/.test(e)?e:`"${e.replace(/"/g,'""')}"`}effectiveSchema(e){if(e){if(this.config.forceDefaultSchema||this.schemaHandling!=="default")return e;if(e!=="public")return e}}ensureRelation(e){let n=this.config.forceDefaultSchema;n&&(!e||typeof e!="object"||n.length===0||e.schemaname||(e.schemaname=n));}CreateStmt(e,n){if(e.inhRelations&&e.inhRelations.length>0)throw new D({CreateStmt:e},"Inheritance is not supported in SQLite");if(e.ofTypename!==void 0)throw new D({CreateStmt:e},"Typed tables (CREATE TABLE ... OF type_name) are not supported. Define columns directly in the CREATE TABLE statement instead.");if(e.options&&e.options.length>0&&(e.options=void 0),!e.tableElts||e.tableElts.length===0)throw new D({CreateStmt:e},"Empty tables are not supported in SQLite. Define at least one column.");return e.accessMethod&&(e.accessMethod=void 0),super.CreateStmt(e,n)+" STRICT"}TableLikeClause(e,n){throw new D({TableLikeClause:e},"CREATE TABLE ... (LIKE ...) is not supported in SQLite. Define the table columns explicitly instead.")}DefElem(e,n){if(["oids","fillfactor",/^autovacuum_/i,"toast_tuple_target","parallel_workers","user_catalog_table"].some(i=>zi(e.defname??"",i)))return "";let s=super.DefElem(e,n);throw new D({DefElem:e},`DefElem "${e.defname}" (${s}) not supported`)}TypeName(e,n){if(!e.names)return "";let r=e.names.map(i=>i.String?i.String.sval||i.String.str:"").filter(Boolean);if(r.length===0)return "";let s=r.length===2&&r[0]==="pg_catalog"?r[1]:r.join(".");return e.arrayBounds&&e.arrayBounds.length>0||Vs(this.enums,s)?"TEXT":Vy(s)}ColumnDef(e,n){let r=[],s=e.colname;s&&r.push(this.quoteIfNeeded(s));let i=false,o=false,a=null,l=null,c=null,f=false;if(e.typeName){let u=e.typeName.names?.map(g=>g.String?.sval||g.String?.str).filter(Boolean);c=u&&u.length>0?u.length===2&&u[0]==="pg_catalog"?u[1]:u.join("."):null,i=!!(c&&ea(c))||this.serialColumns.has(e),f=!!(e.typeName.arrayBounds&&e.typeName.arrayBounds.length>0);let d=Array.isArray(e.typeName.typmods)?e.typeName.typmods:[],p=g=>d[g]?.A_Const?.ival?.ival??d[g]?.A_Const?.val?.ival?.ival;if(c&&ta(c)&&d.length>0){let g=p(0);typeof g=="number"&&g>0&&(a={maxLen:g});}if(c&&na(c)&&d.length>=2){let g=p(0),m=p(1);typeof g=="number"&&typeof m=="number"&&g>0&&m>=0&&(l={precision:g,scale:m});}if(e.constraints){let g=Array.isArray(e.constraints)?e.constraints:[];o=g.some(m=>m.Constraint?.contype==="CONSTR_PRIMARY"),g.some(m=>m.Constraint?.contype==="CONSTR_IDENTITY")&&(i=true);}r.push(this.TypeName(e.typeName,n));}if(e.constraints){let u=Array.isArray(e.constraints)?e.constraints:[],d=n.spawn("ColumnDef",{isColumnConstraint:true}),p=u.map(m=>this.visit(m,d));r.push(...p.filter(Boolean));let g=u.some(m=>m.Constraint?.contype==="CONSTR_CHECK");i&&o&&!g?r.push("AUTOINCREMENT"):i&&!o&&this.warnings.push({type:"ColumnDef",node:{ColumnDef:e},message:`Column "${s}" is serial/auto-increment but not the primary key; SQLite can't auto-increment a non-primary-key column, so it becomes a plain INTEGER (no auto-increment).`});}if(s&&c){let u={isArray:f};a&&(u.lengthConstraint=a.maxLen),l&&(u.numericPrecision=l);let d=Vs(this.enums,c);d&&(u.enumValues=d);let m=We({schema:"public",table:"",column:s,pgTypeName:c,nullable:true,defaultValue:null,defaultFn:null,isPrimaryKey:o,isUnique:false,isSerial:i},u).checkConstraint();m&&r.push(`CHECK (${m})`);}return r.join(" ")}Constraint(e,n){let r=e.contype;if(r==="CONSTR_IDENTITY"||r==="CONSTR_ATTR_DEFERRABLE"||r==="CONSTR_ATTR_NOT_DEFERRABLE"||r==="CONSTR_ATTR_DEFERRED"||r==="CONSTR_ATTR_IMMEDIATE")return "";if(r==="CONSTR_NULL")return "NULL";if(r==="CONSTR_NOTNULL")return "NOT NULL";if(r==="CONSTR_DEFAULT"&&e.raw_expr){let s=this.unwrapConstCast(e.raw_expr),i=this.visit(s,n);return i.includes("(")&&!i.startsWith("(")?`DEFAULT (${i})`:`DEFAULT ${i}`}if(r==="CONSTR_CHECK"&&e.raw_expr){let s=[];e.conname&&s.push("CONSTRAINT",Zo(e.conname)),s.push("CHECK");let i=this.visit(e.raw_expr,n);return s.push(`(${i})`),s.join(" ")}if(r==="CONSTR_PRIMARY")return e.keys&&e.keys.length>0?`PRIMARY KEY (${zt(e.keys).map(i=>this.visit(i,n)).join(", ")})`:"PRIMARY KEY";if(r==="CONSTR_UNIQUE")return e.keys&&e.keys.length>0?`UNIQUE (${zt(e.keys).map(i=>this.visit(i,n)).join(", ")})`:"UNIQUE";if(r==="CONSTR_FOREIGN")return super.Constraint(e,n).replace(/FOREIGN\s+KEY\s+REFERENCES/gi,"REFERENCES");if(r==="CONSTR_GENERATED"&&e.raw_expr)return `GENERATED ALWAYS AS (${this.visit(e.raw_expr,n)}) STORED`;if(r==="CONSTR_EXCLUSION")throw new D({Constraint:e},"EXCLUSION constraints are not supported in SQLite");return ""}FuncCall(e,n){let s=(e.funcname||[]).map(c=>c.String?.sval||c.String?.str).filter(Boolean);if(s.length===0)throw new Error("Function call has no name");let i=s[s.length-1].toLowerCase();if(i==="extract"&&e.args&&e.args.length>=2){let c=e.args[0];if((c?.A_Const?.sval?.sval||c?.String?.sval)==="epoch")return `strftime('%s', ${this.visit(e.args[1],n)})`}let a=(e.args??[]).map(c=>this.visit(c,n));if(e.agg_star)return `${i}(*)`;if(e.agg_distinct)return `${i}(DISTINCT ${a.join(", ")})`;let l=Yl(i,this.functionResolution);if(l){if(l.sqliteExpr!==null){let c=l.sqliteExpr;return c.includes("(")?c:`${c}(${a.join(", ")})`}if(l.jsFn!==null){let c=ao[i];if(c?.sqlite){let f=c.sqlite();return f.includes("(")?f:`${f}(${a.join(", ")})`}}}throw new D({FuncCall:e},`Function call "${i}" not supported`)}SQLValueFunction(e,n){switch(e.op){case "SVFOP_CURRENT_TIMESTAMP":return "datetime('now')";case "SVFOP_CURRENT_DATE":return "date('now')";case "SVFOP_CURRENT_TIME":return "time('now')";default:throw new D({SQLValueFunction:e},`SQLValueFunction "${e.op}" not supported`)}}ResTarget(e,n){if(e.indirection&&e.indirection.length>0)throw new D({ResTarget:e},"Indirections are not supported in SQLite");let r=[];return n.update&&e.name?(r.push(this.quoteIfNeeded(e.name)),r.push("="),e.val&&r.push(this.deparse(e.val,n))):n.insertColumns&&e.name?r.push(this.quoteIfNeeded(e.name)):(e.val&&r.push(this.deparse(e.val,n)),e.name&&r.push(this.Alias({aliasname:e.name},n))),r.join(" ")}A_Expr(e,n){if(e.kind==="AEXPR_OP_ANY"&&(e.name?.[0]?.String?.sval||e.name?.[0]?.String?.str)==="="&&e.lexpr&&e.rexpr&&"A_ArrayExpr"in e.rexpr){let s=zt(e.rexpr.A_ArrayExpr.elements),i=this.tryFoldConstArrayElements(s,n);if(i!==void 0)return `${this.visit(e.lexpr,n)} IN (${i.join(", ")})`}if(["AEXPR_OP_ALL","AEXPR_OP_ANY"].includes(e.kind))throw new D({A_Expr:e},"ALL/ANY/SOME comparison operators are not supported. Use NOT EXISTS or IN instead");if(e.name&&e.name.length>0){if(e.name.length>1)throw new D({A_Expr:e},"Schema-qualified OPERATOR() syntax is not supported in SQLite");let r=e.name[0]?.String?.sval||e.name[0]?.String?.str;if(r){if(!e.lexpr||!e.rexpr)throw new D({A_Expr:e},"A_Expr missing left or right expression");if(!zy.includes(r.toUpperCase()))throw new D({A_Expr:e},`Operator "${r}" is not supported in SQLite`);if(r==="~~"||r==="~~*"){let s=this.visit(e.lexpr,n),i=this.visit(e.rexpr,n);return `${s} LIKE ${i}`}if(r==="!~~"||r==="!~~*"){let s=this.visit(e.lexpr,n),i=this.visit(e.rexpr,n);return `${s} NOT LIKE ${i}`}if(r==="~"||r==="~*"){let s=this.visit(e.lexpr,n),i=this.visit(e.rexpr,n);return `${s} GLOB ${i}`}}}return super.A_Expr(e,n)}IndexStmt(e,n){let r=["CREATE"];e.unique&&r.push("UNIQUE"),r.push("INDEX"),e.if_not_exists&&r.push("IF NOT EXISTS"),e.idxname&&r.push(Zo(e.idxname)),r.push("ON"),e.relation&&r.push(this.RangeVar(e.relation,n));let s=(e.indexParams??[]).map(i=>"IndexElem"in i?this.IndexElem(i.IndexElem,n):this.visit(i,n)).filter(Boolean);return r.push(`(${s.join(", ")})`),r.join(" ")}IndexElem(e,n){let r=[];return e.name?r.push(Zo(e.name)):e.expr&&r.push(`(${this.visit(e.expr,n)})`),e.ordering==="SORTBY_ASC"&&r.push("ASC"),e.ordering==="SORTBY_DESC"&&r.push("DESC"),e.nulls_ordering==="SORTBY_NULLS_FIRST"&&r.push("NULLS FIRST"),e.nulls_ordering==="SORTBY_NULLS_LAST"&&r.push("NULLS LAST"),r.join(" ")}constFoldCategory(e){if(!e?.names||e.arrayBounds&&e.arrayBounds.length>0)return null;let n=e.names.map(c=>c.String?.sval||c.String?.str).filter(Boolean);if(n.length===0)return null;let r=n.length===2&&n[0]==="pg_catalog"?n[1]:n.join("."),s=r.toLowerCase().trim();return Vs(this.enums,r)?"text":new Set(["bool","boolean"]).has(s)?"boolean":new Set(["int2","smallint","int4","integer","int","int8","bigint","serial","serial4","bigserial","serial8","smallserial","serial2"]).has(s)?"integer":new Set(["float4","real","float8","double precision","numeric","decimal"]).has(s)?"real":new Set(["text","varchar","character varying","char","character","bpchar","name","uuid"]).has(s)?"text":null}isFoldableCast(e,n){if(e.isnull)return true;let r=this.constFoldCategory(n);return r?"sval"in e?r==="text":"ival"in e?r==="integer":"fval"in e?r==="real":"boolval"in e?r==="boolean":false:false}findUnderlyingConst(e){let n=e;for(;"TypeCast"in n;){let r=n.TypeCast;if(!r.arg)return null;n=r.arg;}return "A_Const"in n?n.A_Const:null}unwrapConstCast(e){let n=e;for(;"TypeCast"in n;){let r=n.TypeCast;if(r.typeName?.arrayBounds&&r.typeName.arrayBounds.length>0||!r.arg)break;if("A_Const"in r.arg){if(!this.isFoldableCast(r.arg.A_Const,r.typeName))break;n=r.arg;continue}if("TypeCast"in r.arg){let s=this.findUnderlyingConst(r.arg);if(!s||!this.isFoldableCast(s,r.typeName))break;n=r.arg;continue}break}return n}tryFoldConstArrayElements(e,n){let r=[];for(let s of e){let i=this.unwrapConstCast(s);if("A_Const"in i){r.push(this.visit(i,n));continue}if(this.findUnderlyingConst(s)===null)return;r.push(this.visit(i,n));}return r}TypeCast(e,n){if(!e.arg||!e.typeName)return super.TypeCast(e,n);if([...this.helper.walk(e)].filter(({node:o})=>"A_Star"in o).length>0)throw new D({TypeCast:e},"A.* in type casts are not supported in SQLite");if(e.typeName.arrayBounds&&e.typeName.arrayBounds.length>0){if("A_Const"in e.arg&&e.arg.A_Const.sval){let o=e.arg.A_Const.sval.sval;if(o.startsWith("{")&&o.endsWith("}")){let a=e.typeName.names?.map(u=>u.String?.sval).filter(Boolean)??[],l=a.length===2&&a[0]==="pg_catalog"?a[1]:a[0],f=["text","varchar","character varying","char","bpchar","name","uuid"].includes(l?.toLowerCase());try{let u=this.parsePgArrayLiteral(o,f);return `'${JSON.stringify(u).replace(/'/g,"''")}'`}catch{}}}return this.visit(e.arg,n)}let s=this.visit(e.arg,n),i=this.TypeName(e.typeName,n);return `CAST(${s} AS ${i})`}A_ArrayExpr(e,n){let r=zt(e.elements),s=this.tryExtractStaticArray(r);return s!==void 0?`'${JSON.stringify(s).replace(/'/g,"''")}'`:`json_array(${r.map(o=>this.visit(o,n)).join(", ")})`}tryExtractStaticArray(e){let n=[];for(let r of e)if("A_ArrayExpr"in r){let s=zt(r.A_ArrayExpr.elements),i=this.tryExtractStaticArray(s);if(i===void 0)return;n.push(i);}else if("A_Const"in r){let s=r.A_Const;if(s.isnull)n.push(null);else if(s.ival)n.push(s.ival.ival);else if(s.fval)n.push(parseFloat(s.fval.fval));else if(s.sval)n.push(s.sval.sval);else if("boolval"in s)n.push(s.boolval.boolval===true);else return}else return;return n}parsePgArrayLiteral(e,n){if(!e.startsWith("{")||!e.endsWith("}"))throw new Error("Not a PG array literal");let r=e.slice(1,-1);if(r.length===0)return [];let s=[],i=0;for(;i<r.length;)if(r[i]==="{"){let o=0,a=i;for(;a<r.length;){if(r[a]==="{")o++;else if(r[a]==="}"&&(o--,o===0))break;a++;}s.push(this.parsePgArrayLiteral(r.slice(i,a+1),n)),i=a+1,r[i]===","&&i++;}else if(r[i]==='"'){let o=i+1,a="";for(;o<r.length&&r[o]!=='"';)r[o]==="\\"&&o++,a+=r[o],o++;s.push(a),i=o+1,r[i]===","&&i++;}else {let o=i;for(;o<r.length&&r[o]!==","&&r[o]!=="}";)o++;if(o===i)throw new Error("Malformed PG array literal");let a=r.slice(i,o);if(a==="NULL")s.push(null);else if(n)s.push(a);else {let l=Number(a);s.push(isNaN(l)?a:l);}i=o,r[i]===","&&i++;}return s}BetweenExpr(e,n){return super.A_Expr(e,n)}AlterTableStmt(e,n){let r=e.cmds??[],s=["AT_EnableRowSecurity","AT_ForceRowSecurity","AT_ChangeOwner"],i=r.filter(f=>"AlterTableCmd"in f&&!s.includes(f.AlterTableCmd.subtype));if(i.length===0)return "";if(!["OBJECT_TABLE","OBJECT_INDEX","OBJECT_VIEW"].includes(e.objtype))throw new D({AlterTableStmt:e},`AlterTableStmt with objtype ${e.objtype} is not supported`);let o=["AT_AddColumn","AT_DropColumn"],a=["AT_AlterColumnType","AT_SetNotNull","AT_DropNotNull","AT_ColumnDefault","AT_AddConstraint","AT_DropConstraint"],l=[],c=[];for(let f of i){let u=f.AlterTableCmd.subtype;if(o.includes(u)){let d={...e,cmds:[f]};l.push(super.AlterTableStmt(d,n));}else if(a.includes(u))c.push(f.AlterTableCmd);else throw new D({AlterTableStmt:e},`AlterTableCmd with subtype ${u} is not supported in SQLite`)}if(c.length>0){let f=this.getRelationName(e.relation);l.push(this.generateRebuildSql(f,c));}return l.join(`;
26
+ `)}AlterTableCmd(e,n){if(!["AT_AddColumn","AT_DropColumn"].includes(e.subtype))throw new D({AlterTableCmd:e},`AlterTableCmd with subtype ${e.subtype} is not supported`);if(e.subtype==="AT_AddColumn"&&e.def&&"ColumnDef"in e.def){let s=this.ColumnDef(e.def.ColumnDef,n),i=n.objtype==="OBJECT_TYPE"?"ADD ATTRIBUTE":"ADD COLUMN",o=e.missing_ok?" IF NOT EXISTS":"";return `${i}${o} ${s}`}return e.subtype==="AT_DropColumn"&&e.behavior?super.AlterTableCmd({...e,behavior:void 0},n):super.AlterTableCmd(e,n)}DefineStmt(e,n){if(e.kind==="OBJECT_AGGREGATE")throw new Error("AGGREGATE definitions are not supported in SQLite");return super.DefineStmt(e,n)}InsertStmt(e,n){if("selectStmt"in e){let s=(e.selectStmt?.SelectStmt?.valuesLists??[]).map(i=>i.List?.items?.map(o=>"SetToDefault"in o));if(s.length===1&&s[0]?.every(i=>i===true))return super.InsertStmt({...e,selectStmt:void 0,cols:void 0},n);if(s.some(i=>i.some(o=>o===true)))throw new D({InsertStmt:e},"Insert with partial DEFAULT values is not supported")}return super.InsertStmt(e,n)}SelectStmt(e,n){if(this.helper.hasUnsafeStar())throw new D({SelectStmt:e},"Row-wise comparison using .* is not supported in SQLite. Expand to explicit per-column comparisons instead.");if(e.intoClause)throw new D({SelectStmt:e},"SELECT ... INTO clause is not supported in SQLite");if(e.distinctClause){let s=zt(e.distinctClause);if(s.length>0&&Object.keys(s[0]).length>0)throw new D({SelectStmt:e},"DISTINCT ON clause is not supported in SQLite. Use window functions instead.")}if(e.limitOffset&&!e.limitCount)throw new D({SelectStmt:e},"OFFSET without LIMIT is not supported in SQLite");let r=super.SelectStmt(e,n);if(/^SELECT\s+FROM/.test(r))throw new D({SelectStmt:e},"SELECT without a target list is not supported in SQLite");return r}JoinExpr(e,n){return e.alias&&this.Alias(e.alias,n),super.JoinExpr(e,n)}A_Const(e,n){if(e.bsval!==void 0)throw new D({A_Const:e},"Bit string literals are not supported in SQLite");let r=super.A_Const(e,n);return typeof r=="string"&&r.startsWith("E'")?r.substring(2,r.length-1):r}SortBy(e,n){if(e.sortby_dir==="SORTBY_USING"){let r=zt(e.useOp),s=r[0]?.String?.sval;if(r.length>1||!["<",">"].includes(s??""))throw new D({SortBy:e},"Only `USING <` or `USING >` are supported.");e.sortby_dir=s==="<"?"SORTBY_DESC":"SORTBY_ASC",e.useOp=void 0;}return super.SortBy(e,n)}RangeSubselect(e,n){if(e.lateral)throw new D({RangeSubselect:e},"LATERAL subqueries are not supported in SQLite");return super.RangeSubselect(e,n)}SubLink(e,n){if(["ANY_SUBLINK","ALL_SUBLINK"].includes(e.subLinkType))throw new D({SubLink:e},"ANY/ALL/SOME subqueries are not supported. Use NOT EXISTS or IN instead");if(e.subLinkType==="ARRAY_SUBLINK")throw new D({SubLink:e},"ARRAY subqueries are not supported in SQLite");return super.SubLink(e,n)}LockingClause(e,n){return ""}UpdateStmt(e,n){if(n.parentNodeTypes.includes("SelectStmt"))throw new D({UpdateStmt:e},"UPDATE ... FROM (SELECT ...) is not supported in SQLite");return super.UpdateStmt(e,n)}Alias(e,n){if(e.colnames&&e.colnames.length>0)throw new D({Alias:e},"Aliasing with column names is not supported in SQLite");return `AS "${e.aliasname}"`}CreateFunctionStmt(e,n){let r=e.options??[],s=e.returnType?.names?.map(c=>c.String?.sval).filter(Boolean).join("."),i=r.find(c=>c.DefElem?.defname==="language")?.DefElem?.arg?.String?.sval;if(s!=="trigger"||i!=="plpgsql")throw new D({CreateFunctionStmt:e},"Only trigger functions with LANGUAGE plpgsql are supported");let o=e.funcname?.map(c=>c.String?.sval).filter(Boolean).pop();if(!o)throw new Error("Function has no name");let a=r.find(c=>c.DefElem?.defname==="as")?.DefElem?.arg?.List?.items?.[0]?.String?.sval;if(!a)throw new Error("Function has no body");let l=this.plpgsqlParser.parse(a);return this.triggerFunctions.set(o,l),""}CreateTrigStmt(e,n){let r=e.trigname,s=this.RangeVar(e.relation,n),i=e.funcname?.map(u=>u.String?.sval).filter(Boolean).pop();if(!i)throw new Error(`Trigger "${r}" has no function reference`);let o=this.triggerFunctions.get(i);if(!o)throw new D({CreateTrigStmt:e},`Trigger "${r}" references unknown function "${i}"`);let a=e.timing===2?"BEFORE":e.timing===64?"INSTEAD OF":"AFTER",l=[];if(e.events&4&&l.push("INSERT"),e.events&8&&l.push("DELETE"),e.events&16)if(e.columns?.length){let u=e.columns.map(d=>d.String?.sval).filter(Boolean);l.push(`UPDATE OF ${u.join(", ")}`);}else l.push("UPDATE");let c=l.join(" OR "),f=this.buildTriggerBody(o,s,n);return [`CREATE TRIGGER ${r}`,`${a} ${c} ON ${s}`,"FOR EACH ROW","BEGIN",...f.map(u=>` ${u};`),"END"].join(`
27
+ `)}buildTriggerBody(e,n,r){let s=[],i=[];for(let o of e.statements)if(o.type!=="return"){if(o.type==="assignment"){i.push(o);continue}i.length>0&&(s.push(this.buildAssignmentUpdate(i,n,r)),i.length=0),o.type==="dml"&&s.push(this.translateDml(o.sql,r));}return i.length>0&&s.push(this.buildAssignmentUpdate(i,n,r)),s}buildAssignmentUpdate(e,n,r){let s=e.map(i=>{let o=this.translateExpression(i.expression,r);return `${i.column} = ${o}`});return `UPDATE ${n} SET ${s.join(", ")} WHERE rowid = NEW.rowid`}translateExpression(e,n){try{let r=`SELECT ${e}`,s=e.trim().toLowerCase();return s==="now()"||s==="current_timestamp"?"datetime('now')":e}catch{return e}}flattenTriggerTableRef(e,n){let r=this.effectiveSchema(e);return r?this.schemaHandling==="prefix"?`${r}__${n}`:`"${r}.${n}"`:this.quoteBareIfNeeded(n)}translateDml(e,n){let r=/^(\s*)(insert\s+into|update|delete\s+from)\s+(?:"([^"]+)"|(\w+))\s*\.\s*(?:"([^"]+)"|(\w+))/i;return e=e.replace(r,(s,i,o,a,l,c,f)=>`${i}${o} ${this.flattenTriggerTableRef(a??l,c??f)}`),e.replace(/\bnow\(\)/gi,"datetime('now')").replace(/\bcurrent_timestamp\b/gi,"datetime('now')").replace(/\bgen_random_uuid\(\)/gi,this.uuidExpression()).replace(/\buuid_generate_v4\(\)/gi,this.uuidExpression())}uuidExpression(){return "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)))"}NullTest(e,n){if(e.arg?.ColumnRef?.fields?.length>1)throw new D({NullTest:e},"row-level NULL tests are not supported in SQLite");return super.NullTest(e,n)}RenameStmt(e,n){if(!e.renameType)throw new Error("RenameStmt requires renameType");if(e.renameType==="OBJECT_POLICY")return "";let r=["OBJECT_TABLE","OBJECT_VIEW","OBJECT_COLUMN"];if(e.renameType==="OBJECT_COLUMN"&&(e.relationType==="OBJECT_FOREIGN_TABLE"||e.relationType==="OBJECT_VIEW"))throw new D({RenameStmt:e},`RenameStmt with relationType ${e.relationType} is not supported`);if(!r.includes(e.renameType))throw new D({RenameStmt:e},`RenameStmt with renameType ${e.renameType} is not supported in SQLite`);return super.RenameStmt(e,n)}DropStmt(e,n){let r=e.removeType;if(r==="OBJECT_EXTENSION"){let o=e.objects?.map(ab)??[];if(o.length>0&&o.every(a=>a&&Wu.has(a)))return "";throw new D({DropStmt:e},"DROP EXTENSION is not supported in SQLite")}if(["OBJECT_TABLE","OBJECT_VIEW","OBJECT_INDEX","OBJECT_TRIGGER"].includes(r))return this.foldDropObjectSchemas(e),super.DropStmt(e,n);if(["OBJECT_POLICY"].includes(r))return "";throw new D({DropStmt:e},`DROP with removeType ${r} is not supported in SQLite`)}foldDropObjectSchemas(e){let n=e.removeType==="OBJECT_TRIGGER"?3:2;for(let r of e.objects??[]){let s=r?.List?.items;if(!Array.isArray(s)||s.length!==n)continue;let i=s[0]?.String?.sval,o=s[1]?.String?.sval;if(typeof i!="string"||typeof o!="string")continue;let a=this.effectiveSchema(i),l=a===void 0?o:this.schemaHandling==="prefix"?`${a}__${o}`:`${a}.${o}`;s.splice(0,2,{String:{sval:l}});}}generateRebuildSql(e,n){if(!this.introspection)throw new Error(`ALTER TABLE on "${e}" requires 12-step rebuild but no introspection was provided. Pass introspection in DeparseOptions to enable column type changes, NOT NULL, defaults, and constraint modifications.`);let r=this.buildDesiredSchema(this.introspection,e,n),s=new cr,i=new ur,o=s.diff(this.introspection,r);return o.has_changes?i.plan(o,this.introspection,r).steps.filter(l=>!["disable_foreign_keys","begin_transaction","commit_transaction","enable_foreign_keys"].includes(l.type)).map(l=>l.sql).join(`
28
+ `):""}buildDesiredSchema(e,n,r){let s={...e,tables:e.tables.map(i=>({...i})),columns:e.columns.map(i=>({...i})),indexes:e.indexes.map(i=>({...i})),foreign_keys:e.foreign_keys.map(i=>({...i})),primary_keys:e.primary_keys.map(i=>({...i})),views:e.views.map(i=>({...i})),triggers:(e.triggers??[]).map(i=>({...i})),check_constraints:e.check_constraints.map(i=>({...i})),unique_constraints:(e.unique_constraints??[]).map(i=>({...i})),comments:(e.comments??[]).map(i=>({...i})),custom_types:e.custom_types.map(i=>({...i}))};for(let i of r){let o=s.columns.findIndex(a=>a.table===n&&a.name===i.name);switch(i.subtype){case "AT_AlterColumnType":{if(o===-1)break;let a=this.extractTypeName(i);a&&(s.columns[o]={...s.columns[o],type:a.toLowerCase()});break}case "AT_SetNotNull":{if(o===-1)break;s.columns[o]={...s.columns[o],nullable:false};break}case "AT_DropNotNull":{if(o===-1)break;s.columns[o]={...s.columns[o],nullable:true};break}case "AT_ColumnDefault":{if(o===-1)break;if(i.def){let a=this.extractDefaultValue(i);s.columns[o]={...s.columns[o],default_value:a};}else s.columns[o]={...s.columns[o],default_value:null};break}case "AT_AddConstraint":case "AT_DropConstraint":{let a=s.tables.findIndex(l=>l.name===n);a!==-1&&(s.tables[a]={...s.tables[a],sql:s.tables[a].sql+" /* modified */"});break}}}return this.rebuildTableSql(s,n),s}rebuildTableSql(e,n){let r=e.tables.findIndex(u=>u.name===n);if(r===-1)return;let s=e.columns.filter(u=>u.table===n),i=e.foreign_keys.filter(u=>u.table===n),o=e.check_constraints.filter(u=>u.table===n),a=s.map(u=>{let d=`${N(u.name)} ${u.type||"TEXT"}`;return u.is_primary_key&&(d+=" PRIMARY KEY"),u.nullable||(d+=" NOT NULL"),u.default_value!=null&&(d+=` DEFAULT ${u.default_value}`),d}),l=i.map(u=>`FOREIGN KEY (${N(u.column)}) REFERENCES ${N(u.ref_table)}(${N(u.ref_column)}) ON UPDATE ${u.on_update} ON DELETE ${u.on_delete}`),c=o.map(u=>`CHECK (${u.expression})`),f=[...a,...l,...c];e.tables[r]={...e.tables[r],sql:`CREATE TABLE ${N(n)} (${f.join(", ")}) STRICT`};}extractTypeName(e){let n=e.def?.ColumnDef;return n?.typeName?.TypeName?(n.typeName.TypeName.names??[]).map(s=>s.String?.sval).filter(Boolean).pop()??null:null}extractDefaultValue(e){if(!e.def)return null;let n=this.unwrapConstCast(e.def);if("A_Const"in n){let r=n.A_Const;return r.isnull?null:r.ival?String(r.ival.ival??0):r.fval?r.fval.fval:r.sval?`'${String(r.sval.sval).replace(/'/g,"''")}'`:"boolval"in r?r.boolval.boolval?"1":"0":null}return "Integer"in n?String(n.Integer.ival):"Float"in n?n.Float.fval:"String"in n?`'${n.String.sval}'`:null}};});function cb(t){return `${t?.schemaname??"public"}.${t?.relname??""}`}function ck(t){let e=t?.Constraint;if(!e||e.contype!=="CONSTR_DEFAULT")return false;let n=e.raw_expr?.FuncCall?.funcname;if(!Array.isArray(n))return false;let r=n.map(s=>s.String?.sval??s.String?.str).filter(Boolean);return r[r.length-1]?.toLowerCase()==="nextval"}function uk(t){return (Array.isArray(t.constraints)?t.constraints:[]).some(n=>n.Constraint?.contype==="CONSTR_IDENTITY")}function ub(t,e){let n=Array.isArray(t.constraints)?t.constraints:[],r=n.filter(s=>!ck(s));r.length!==n.length?(t.constraints=r,e.add(t)):uk(t)&&e.add(t);}function fk(t,e){let n=e?.Constraint;if(!n)return false;let r=n.contype;if(r!=="CONSTR_PRIMARY"&&r!=="CONSTR_UNIQUE"&&r!=="CONSTR_FOREIGN")return false;let s=t.tableElts??[];return r==="CONSTR_PRIMARY"&&fb(t,n)||r==="CONSTR_FOREIGN"&&db(t,n)||(s.push(e),t.tableElts=s),true}function fb(t,e){let n=(e.keys??[]).map(i=>i.String?.sval??i.String?.str).filter(Boolean);if(n.length!==1)return false;let r=(t.tableElts??[]).find(i=>"ColumnDef"in i&&i.ColumnDef.colname===n[0]);if(!r)return false;let s=Array.isArray(r.ColumnDef.constraints)?r.ColumnDef.constraints:[];return r.ColumnDef.constraints=[...s.filter(i=>i.Constraint?.contype!=="CONSTR_NOTNULL"),{Constraint:{contype:"CONSTR_PRIMARY"}}],true}function db(t,e){let n=(e.fk_attrs??[]).map(i=>i.String?.sval??i.String?.str).filter(Boolean);if(n.length!==1)return false;let r=(t.tableElts??[]).find(i=>"ColumnDef"in i&&i.ColumnDef.colname===n[0]);if(!r)return false;let s=Array.isArray(r.ColumnDef.constraints)?r.ColumnDef.constraints:[];return r.ColumnDef.constraints=[...s,{Constraint:e}],true}function dk(t){let e=t.tableElts??[],n=e.filter(r=>{let s=r?.Constraint;return !s||s.contype!=="CONSTR_PRIMARY"?true:!fb(t,s)});n.length!==e.length&&(t.tableElts=n);}function pk(t){let e=t.tableElts??[],n=e.filter(r=>{let s=r?.Constraint;return !s||s.contype!=="CONSTR_FOREIGN"?true:!db(t,s)});n.length!==e.length&&(t.tableElts=n);}function pb(t){let e=new WeakSet,n=new Map;for(let r of t.stmts??[]){let s=r.stmt;if(!s||!("CreateStmt"in s))continue;let i=s.CreateStmt;n.set(cb(i.relation),i);for(let o of i.tableElts??[])"ColumnDef"in o&&ub(o.ColumnDef,e);dk(i),pk(i);}for(let r of t.stmts??[]){let s=r.stmt;if(!s||!("AlterTableStmt"in s))continue;let i=s.AlterTableStmt,o=n.get(cb(i.relation)),a=i.cmds??[],l=[];for(let c of a){let f=c.AlterTableCmd;f?.subtype==="AT_AddColumn"&&f.def&&"ColumnDef"in f.def&&ub(f.def.ColumnDef,e),!(o&&f?.subtype==="AT_AddConstraint"&&f.def&&fk(o,f.def))&&l.push(c);}i.cmds=l;}return e}var mb=I(()=>{});var yb={};Zs(yb,{Policy:()=>Ge,deparseDdl:()=>Ku,deparseExpression:()=>hk,deparsePostgresDdl:()=>mk,deparseSelect:()=>gk,parse:()=>dr,parseExpression:()=>gb,translatePostgresDdl:()=>hb});async function hb(t,e={}){let n=await dr(t);return Ku(n,e).ddl}async function mk(t,e={}){let n=await dr(t);return {ast:n,...Ku(n,e)}}function Ku(t,e={}){let n=pb(t),r=Zy(t),s=nb(t,r),i=eb(t),o=rb(t),a=sb(t),l=new aa(t,{...e,enums:r,serialColumns:n}),{policies:c,tables:f}=tb(t,{defaultSchema:e.defaultSchema,validateMutations:e.strict});if(e.strict)for(let u of c){if(!s.get(`${u.data.schema??"public"}.${u.data.table}`))throw new Error(`Policy "${u.data.name}" references unknown table "${u.data.table}"`);if(!f.has(u.data.table))throw new Error(`RLS is not enabled on table "${u.data.table}"`)}return {ddl:l.deparseQuery(),enums:r,rls:{tables:f,policies:c},schema:s,vars:i,tableConstraints:o,comments:a}}async function gb(t){let n=(await dr(`SELECT 1 WHERE ${t}`)).stmts?.[0]?.stmt;if(!n||!("SelectStmt"in n))throw new Error("expected SelectStmt");let r=n.SelectStmt.whereClause;if(!r)throw new Error("no whereClause");return r}async function hk(t){let e=await gb(t);return new xn().deparse(e)}async function gk(t){let n=(await dr(t)).stmts?.[0]?.stmt;if(!n||!("SelectStmt"in n))throw new Error("expected SelectStmt");return new xn().deparse(n)}var Ju=I(()=>{Jy();lb();mb();Mu();Hu();Js();});function Vu(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),n.push.apply(n,r);}return n}function Qu(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Vu(Object(n),true).forEach(function(r){Ab(t,r,n[r]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Vu(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r));});}return t}function Ab(t,e,n){return e=Ob(e),e in t?Object.defineProperty(t,e,{value:n,enumerable:true,configurable:true,writable:true}):t[e]=n,t}function Ob(t){var e=Pb(t,"string");return typeof e=="symbol"?e:String(e)}function Pb(t,e){if(typeof t!="object"||t===null)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return (e==="string"?String:Number)(t)}var $b=Xu({}),je=$b;function Xu(t){return e.withOptions=n=>Xu(Qu(Qu({},t),n)),e;function e(n,...r){let s=typeof n=="string"?[n]:n.raw,{alignValues:i=false,escapeSpecialCharacters:o=Array.isArray(n),trimWhitespace:a=true}=t,l="";for(let u=0;u<s.length;u++){let d=s[u];if(o&&(d=d.replace(/\\\n[ \t]*/g,"").replace(/\\`/g,"`").replace(/\\\$/g,"$").replace(/\\\{/g,"{")),l+=d,u<r.length){let p=i?Ib(r[u],l):r[u];l+=p;}}let c=l.split(`
29
29
  `),f=null;for(let u of c){let d=u.match(/^(\s+)\S+/);if(d){let p=d[1].length;f?f=Math.min(f,p):f=p;}}if(f!==null){let u=f;l=c.map(d=>d[0]===" "||d[0]===" "?d.slice(u):d).join(`
30
30
  `);}return a&&(l=l.trim()),o&&(l=l.replace(/\\n/g,`
31
- `).replace(/\\t/g," ").replace(/\\r/g,"\r").replace(/\\v/g,"\v").replace(/\\b/g,"\b").replace(/\\f/g,"\f").replace(/\\0/g,"\0").replace(/\\x([\da-fA-F]{2})/g,(u,d)=>String.fromCharCode(parseInt(d,16))).replace(/\\u\{([\da-fA-F]{1,6})\}/g,(u,d)=>String.fromCodePoint(parseInt(d,16))).replace(/\\u([\da-fA-F]{4})/g,(u,d)=>String.fromCharCode(parseInt(d,16)))),typeof Bun<"u"&&(l=l.replace(/\\u(?:\{([\da-fA-F]{1,6})\}|([\da-fA-F]{4}))/g,(u,d,p)=>{var g;let m=(g=d??p)!==null&&g!==void 0?g:"";return String.fromCodePoint(parseInt(m,16))})),l}}function vb(t,e){if(typeof t!="string"||!t.includes(`
31
+ `).replace(/\\t/g," ").replace(/\\r/g,"\r").replace(/\\v/g,"\v").replace(/\\b/g,"\b").replace(/\\f/g,"\f").replace(/\\0/g,"\0").replace(/\\x([\da-fA-F]{2})/g,(u,d)=>String.fromCharCode(parseInt(d,16))).replace(/\\u\{([\da-fA-F]{1,6})\}/g,(u,d)=>String.fromCodePoint(parseInt(d,16))).replace(/\\u([\da-fA-F]{4})/g,(u,d)=>String.fromCharCode(parseInt(d,16)))),typeof Bun<"u"&&(l=l.replace(/\\u(?:\{([\da-fA-F]{1,6})\}|([\da-fA-F]{4}))/g,(u,d,p)=>{var g;let m=(g=d??p)!==null&&g!==void 0?g:"";return String.fromCodePoint(parseInt(m,16))})),l}}function Ib(t,e){if(typeof t!="string"||!t.includes(`
32
32
  `))return t;let r=e.slice(e.lastIndexOf(`
33
33
  `)+1).match(/^(\s+)/);if(r){let s=r[1];return t.replace(/\n/g,`
34
- ${s}`)}return t}var Gu=[{name:"Self-hosted Logflare Configuration",link:"https://supabase.com/docs/reference/self-hosting-analytics/list-endpoints#getting-started"}],ei=["analytics"],zu=s.strictObject({enabled:s.boolean({default:false,description:"Enable the local Logflare service.",tags:ei,links:Gu}),port:s.number({default:54327,description:"Port to the local Logflare service.",tags:ei}),vector_port:s.number({default:54328,description:"Port to the local syslog ingest service.",tags:ei}),backend:s.string({enum:["postgres","bigquery"],default:"postgres",description:je`
34
+ ${s}`)}return t}var Yu=[{name:"Self-hosted Logflare Configuration",link:"https://supabase.com/docs/reference/self-hosting-analytics/list-endpoints#getting-started"}],ei=["analytics"],Zu=s.strictObject({enabled:s.boolean({default:false,description:"Enable the local Logflare service.",tags:ei,links:Yu}),port:s.number({default:54327,description:"Port to the local Logflare service.",tags:ei}),vector_port:s.number({default:54328,description:"Port to the local syslog ingest service.",tags:ei}),backend:s.string({enum:["postgres","bigquery"],default:"postgres",description:je`
35
35
  Configure one of the supported backends:
36
36
 
37
37
  - \`postgres\`
38
- - \`bigquery\``,tags:ei,links:Gu})}).partial();var Ab=Symbol.for("lite-only"),Pt=t=>(Object.defineProperty(t,Ab,{value:true,enumerable:false,writable:false,configurable:false}),t);var nt=[{name:"PostgREST configuration",link:"https://postgrest.org/en/stable/configuration.html"}],Be=["api"],Vu=s.strictObject({enabled:s.boolean({default:true,description:"Enable the local PostgREST service.",tags:Be,links:nt}),port:s.number({default:54321,description:"Port to use for the API URL.",tags:Be,links:nt}),schemas:s.array(s.string({description:"Schemas to expose in your API. Tables, views and functions in this schema will get API endpoints. `public` and `storage` are always included.",tags:Be,links:nt}),{default:["public","storage","graphql_public"]}),extra_search_path:s.array(s.string({description:"Extra schemas to add to the search_path of every request. public is always included.",tags:Be,links:nt}),{default:["public","extensions"]}),max_rows:s.number({default:1e3,description:"The maximum number of rows returned from a view, table, or stored procedure. Limits payload size for accidental or malicious requests.",tags:Be,links:nt}),pg_safe_update:s.boolean({default:false,description:"Require a WHERE clause on UPDATE and DELETE requests. Equivalent to pg_safe_update extension.",tags:Be,links:nt}),plan_enabled:Pt(s.boolean({default:false,description:"Enable the EXPLAIN plan feature via `Accept: application/vnd.pgrst.plan`. Disabled by default to match PostgREST's `db-plan-enabled` setting.",tags:Be,links:nt})),aggregates_enabled:Pt(s.boolean({default:false,description:"Enable aggregate functions (count(), sum(), avg(), min(), max()) in select. Disabled by default to match PostgREST's `db-aggregates-enabled` setting.",tags:Be,links:nt})),limited_mutations_enabled:Pt(s.boolean({default:false,description:"Honor `?limit`, `?offset`, and `?order` on UPDATE/DELETE via subquery. Disabled by default to match PostgREST's silent-ignore behavior.",tags:Be,links:nt})),anonymous_enabled:Pt(s.boolean({default:true,description:"Allow requests without an Authorization header. When false, unauthenticated requests receive 401 PGRST302 'Anonymous access is disabled'. Mirrors PostgREST's `db-anon-role`.",tags:Be,links:nt})),tls:s.strictObject({enabled:s.boolean({default:false,description:"Enable TLS for the local PostgREST service.",tags:Be})}).partial(),external_url:s.string({default:"http://127.0.0.1:54321",description:"External URL for accessing the API server.",tags:Be})}).partial();var Vt=["auth"],Qt={auth:{name:"Auth Server configuration",link:"https://supabase.com/docs/reference/auth"}},br=(t,e)=>s.strictObject({subject:s.string({default:e,description:`The subject of the ${t} email.`}),content_path:s.string({description:`The path to the content of the ${t} email.`})}).partial(),Qu=s.strictObject({enable_signup:s.boolean({default:true,description:"Allow/disallow new user signups via email to your project.",tags:Vt,links:[Qt.auth]}),double_confirm_changes:s.boolean({default:true,description:"If enabled, a user will be required to confirm any email change on both the old, and new email addresses. If disabled, only the new email is required to confirm.",tags:Vt,links:[Qt.auth]}),enable_confirmations:s.boolean({default:false,description:"If enabled, users need to confirm their email address before signing in.",tags:Vt,links:[Qt.auth]}),secure_password_change:s.boolean({default:false,description:"If enabled, users will need to reauthenticate or have logged in recently to change their password.",tags:Vt,links:[Qt.auth]}),max_frequency:s.string({default:"1s",description:"Controls the minimum amount of time that must pass before sending another signup confirmation or password reset email.",tags:Vt,links:[Qt.auth]}),smtp:s.strictObject({enabled:s.boolean({default:false,description:"Enable sending emails through a custom SMTP server."}),host:s.string({description:"Hostname or IP address of the SMTP server."}),port:s.number({description:"Port number of the SMTP server."}),user:s.string({description:"Username for authenticating with the SMTP server."}),pass:s.string({description:"Password for authenticating with the SMTP server."}),admin_email:s.string({description:"Email used as the sender for emails sent from the application."}),sender_name:s.string({description:"Display name used as the sender for emails sent from the application."})}).partial(),template:s.strictObject({invite:br("invite","You have been invited"),confirmation:br("confirmation","Confirm Your Signup"),recovery:br("recovery","Reset Your Password"),magic_link:br("magic link","Your Magic Link"),email_change:br("email change","Confirm Email Change")}).partial(),otp_length:s.number({default:6,description:"Number of characters used in the email OTP.",tags:Vt,links:[Qt.auth]}),otp_expiry:s.number({default:3600,description:"Number of seconds before the email OTP expires (defaults to 1 hour).",tags:Vt,links:[Qt.auth]})}).partial();var ti=["auth"],ua=(t,e)=>({name:t,link:`https://supabase.com/docs/guides/auth/auth-hooks/${e}`}),wr=(t,e)=>s.strictObject({enabled:s.boolean({default:false,description:`Enable/disable the ${t.toLowerCase()}.`,tags:ti,links:[ua(t,e)]}),uri:s.string({description:"The URI of the postgres function or HTTP endpoint to call.",tags:ti,links:[ua(t,e)]}),secrets:s.array(s.string({description:"A secret to pass to the function or endpoint.",tags:ti}),{description:"The secrets to pass to the postgres function or HTTP endpoint.",tags:ti,links:[ua(t,e)]})}).partial(),Yu=s.strictObject({mfa_verification_attempt:wr("MFA Verification Hook","mfa-verification-hook"),password_verification_attempt:wr("Password Verification Hook","password-verification-hook"),custom_access_token:wr("Custom Access Token Hook","custom-access-token-hook"),send_sms:wr("Send SMS Hook","send-sms-hook"),send_email:wr("Send Email Hook","send-email-hook")}).partial();var $t=["auth"],It={mfa:{name:"Multi-Factor Authentication",link:"https://supabase.com/docs/guides/auth/auth-mfa"},totp:{name:"Multi-Factor Authentication (TOTP)",link:"https://supabase.com/docs/guides/auth/auth-mfa/totp"},phone:{name:"Multi-Factor Authentication (Phone)",link:"https://supabase.com/docs/guides/auth/auth-mfa/phone"}},Xu=s.strictObject({totp:s.strictObject({enroll_enabled:s.boolean({default:true,description:"Allow/disallow TOTP enrollment for users.",tags:$t,links:[It.totp]}),verify_enabled:s.boolean({default:true,description:"Allow/disallow TOTP verification for users.",tags:$t,links:[It.totp]})}).partial(),phone:s.strictObject({enroll_enabled:s.boolean({default:false,description:"Allow/disallow phone enrollment for users.",tags:$t,links:[It.phone]}),verify_enabled:s.boolean({default:false,description:"Allow/disallow phone verification for users.",tags:$t,links:[It.phone]}),otp_length:s.number({default:6,description:"The length of the OTP code.",tags:$t,links:[It.phone]}),template:s.string({default:"Your code is {{ .Code }}",description:"The template to use for the phone message.",tags:$t,links:[It.phone]}),max_frequency:s.string({default:"60s",description:"The maximum frequency of the phone messages.",tags:$t,links:[It.phone]})}).partial(),max_enrolled_factors:s.number({default:10,description:"The maximum number of MFA factors a user can enroll in.",tags:$t,links:[It.mfa]})}).partial();var fa=class extends yt.StringSchema{},gt=t=>new fa(t);var Yt=["auth"],me=t=>{let e=[{name:`Login with ${t.name}`,link:`https://supabase.com/docs/guides/auth/social-login/auth-${t.id}`}];return s.strictObject({enabled:s.boolean({default:false,description:`Use the ${t.name} OAuth provider.`,tags:Yt,links:e}),client_id:s.string({description:`Client ID for the ${t.name} OAuth provider.`,tags:Yt,links:e}),secret:gt({default:`env(SUPABASE_AUTH_EXTERNAL_${t.id.toUpperCase()}_SECRET)`,description:je`
38
+ - \`bigquery\``,tags:ei,links:Yu})}).partial();var Nb=Symbol.for("lite-only"),Pt=t=>(Object.defineProperty(t,Nb,{value:true,enumerable:false,writable:false,configurable:false}),t);var nt=[{name:"PostgREST configuration",link:"https://postgrest.org/en/stable/configuration.html"}],Be=["api"],ef=s.strictObject({enabled:s.boolean({default:true,description:"Enable the local PostgREST service.",tags:Be,links:nt}),port:s.number({default:54321,description:"Port to use for the API URL.",tags:Be,links:nt}),schemas:s.array(s.string({description:"Schemas to expose in your API. Tables, views and functions in this schema will get API endpoints. `public` and `storage` are always included.",tags:Be,links:nt}),{default:["public","storage","graphql_public"]}),extra_search_path:s.array(s.string({description:"Extra schemas to add to the search_path of every request. public is always included.",tags:Be,links:nt}),{default:["public","extensions"]}),max_rows:s.number({default:1e3,description:"The maximum number of rows returned from a view, table, or stored procedure. Limits payload size for accidental or malicious requests.",tags:Be,links:nt}),pg_safe_update:s.boolean({default:false,description:"Require a WHERE clause on UPDATE and DELETE requests. Equivalent to pg_safe_update extension.",tags:Be,links:nt}),plan_enabled:Pt(s.boolean({default:false,description:"Enable the EXPLAIN plan feature via `Accept: application/vnd.pgrst.plan`. Disabled by default to match PostgREST's `db-plan-enabled` setting.",tags:Be,links:nt})),aggregates_enabled:Pt(s.boolean({default:false,description:"Enable aggregate functions (count(), sum(), avg(), min(), max()) in select. Disabled by default to match PostgREST's `db-aggregates-enabled` setting.",tags:Be,links:nt})),limited_mutations_enabled:Pt(s.boolean({default:false,description:"Honor `?limit`, `?offset`, and `?order` on UPDATE/DELETE via subquery. Disabled by default to match PostgREST's silent-ignore behavior.",tags:Be,links:nt})),anonymous_enabled:Pt(s.boolean({default:true,description:"Allow requests without an Authorization header. When false, unauthenticated requests receive 401 PGRST302 'Anonymous access is disabled'. Mirrors PostgREST's `db-anon-role`.",tags:Be,links:nt})),tls:s.strictObject({enabled:s.boolean({default:false,description:"Enable TLS for the local PostgREST service.",tags:Be})}).partial(),external_url:s.string({default:"http://127.0.0.1:54321",description:"External URL for accessing the API server.",tags:Be})}).partial();var Vt=["auth"],Qt={auth:{name:"Auth Server configuration",link:"https://supabase.com/docs/reference/auth"}},br=(t,e)=>s.strictObject({subject:s.string({default:e,description:`The subject of the ${t} email.`}),content_path:s.string({description:`The path to the content of the ${t} email.`})}).partial(),tf=s.strictObject({enable_signup:s.boolean({default:true,description:"Allow/disallow new user signups via email to your project.",tags:Vt,links:[Qt.auth]}),double_confirm_changes:s.boolean({default:true,description:"If enabled, a user will be required to confirm any email change on both the old, and new email addresses. If disabled, only the new email is required to confirm.",tags:Vt,links:[Qt.auth]}),enable_confirmations:s.boolean({default:false,description:"If enabled, users need to confirm their email address before signing in.",tags:Vt,links:[Qt.auth]}),secure_password_change:s.boolean({default:false,description:"If enabled, users will need to reauthenticate or have logged in recently to change their password.",tags:Vt,links:[Qt.auth]}),max_frequency:s.string({default:"1s",description:"Controls the minimum amount of time that must pass before sending another signup confirmation or password reset email.",tags:Vt,links:[Qt.auth]}),smtp:s.strictObject({enabled:s.boolean({default:false,description:"Enable sending emails through a custom SMTP server."}),host:s.string({description:"Hostname or IP address of the SMTP server."}),port:s.number({description:"Port number of the SMTP server."}),user:s.string({description:"Username for authenticating with the SMTP server."}),pass:s.string({description:"Password for authenticating with the SMTP server."}),admin_email:s.string({description:"Email used as the sender for emails sent from the application."}),sender_name:s.string({description:"Display name used as the sender for emails sent from the application."})}).partial(),template:s.strictObject({invite:br("invite","You have been invited"),confirmation:br("confirmation","Confirm Your Signup"),recovery:br("recovery","Reset Your Password"),magic_link:br("magic link","Your Magic Link"),email_change:br("email change","Confirm Email Change")}).partial(),otp_length:s.number({default:6,description:"Number of characters used in the email OTP.",tags:Vt,links:[Qt.auth]}),otp_expiry:s.number({default:3600,description:"Number of seconds before the email OTP expires (defaults to 1 hour).",tags:Vt,links:[Qt.auth]})}).partial();var ti=["auth"],pa=(t,e)=>({name:t,link:`https://supabase.com/docs/guides/auth/auth-hooks/${e}`}),wr=(t,e)=>s.strictObject({enabled:s.boolean({default:false,description:`Enable/disable the ${t.toLowerCase()}.`,tags:ti,links:[pa(t,e)]}),uri:s.string({description:"The URI of the postgres function or HTTP endpoint to call.",tags:ti,links:[pa(t,e)]}),secrets:s.array(s.string({description:"A secret to pass to the function or endpoint.",tags:ti}),{description:"The secrets to pass to the postgres function or HTTP endpoint.",tags:ti,links:[pa(t,e)]})}).partial(),nf=s.strictObject({mfa_verification_attempt:wr("MFA Verification Hook","mfa-verification-hook"),password_verification_attempt:wr("Password Verification Hook","password-verification-hook"),custom_access_token:wr("Custom Access Token Hook","custom-access-token-hook"),send_sms:wr("Send SMS Hook","send-sms-hook"),send_email:wr("Send Email Hook","send-email-hook")}).partial();var $t=["auth"],It={mfa:{name:"Multi-Factor Authentication",link:"https://supabase.com/docs/guides/auth/auth-mfa"},totp:{name:"Multi-Factor Authentication (TOTP)",link:"https://supabase.com/docs/guides/auth/auth-mfa/totp"},phone:{name:"Multi-Factor Authentication (Phone)",link:"https://supabase.com/docs/guides/auth/auth-mfa/phone"}},rf=s.strictObject({totp:s.strictObject({enroll_enabled:s.boolean({default:true,description:"Allow/disallow TOTP enrollment for users.",tags:$t,links:[It.totp]}),verify_enabled:s.boolean({default:true,description:"Allow/disallow TOTP verification for users.",tags:$t,links:[It.totp]})}).partial(),phone:s.strictObject({enroll_enabled:s.boolean({default:false,description:"Allow/disallow phone enrollment for users.",tags:$t,links:[It.phone]}),verify_enabled:s.boolean({default:false,description:"Allow/disallow phone verification for users.",tags:$t,links:[It.phone]}),otp_length:s.number({default:6,description:"The length of the OTP code.",tags:$t,links:[It.phone]}),template:s.string({default:"Your code is {{ .Code }}",description:"The template to use for the phone message.",tags:$t,links:[It.phone]}),max_frequency:s.string({default:"60s",description:"The maximum frequency of the phone messages.",tags:$t,links:[It.phone]})}).partial(),max_enrolled_factors:s.number({default:10,description:"The maximum number of MFA factors a user can enroll in.",tags:$t,links:[It.mfa]})}).partial();var ma=class extends yt.StringSchema{},gt=t=>new ma(t);var Xt=["auth"],me=t=>{let e=[{name:`Login with ${t.name}`,link:`https://supabase.com/docs/guides/auth/social-login/auth-${t.id}`}];return s.strictObject({enabled:s.boolean({default:false,description:`Use the ${t.name} OAuth provider.`,tags:Xt,links:e}),client_id:s.string({description:`Client ID for the ${t.name} OAuth provider.`,tags:Xt,links:e}),secret:gt({default:`env(SUPABASE_AUTH_EXTERNAL_${t.id.toUpperCase()}_SECRET)`,description:je`
39
39
  Client secret for the ${t.name} OAuth provider.
40
40
 
41
41
  DO NOT commit your OAuth provider secret to git. Use environment variable substitution instead.
42
- `,tags:Yt,links:e}),url:s.string({description:"The base URL used for constructing the URLs to request authorization and access tokens.",...t.url,tags:Yt,links:e}),redirect_uri:s.string({description:`The URI the ${t.name} OAuth2 provider will redirect to with the code and state values.`,tags:Yt,links:e}),skip_nonce_check:s.boolean({default:false,description:"If true, the nonce check will be skipped.",tags:Yt,links:e}),email_optional:s.boolean({default:false,description:"If true, an email address is not required to sign in with this provider.",tags:Yt,links:e})}).partial()},ef=s.strictObject({apple:me({id:"apple",name:"Apple"}),azure:me({id:"azure",name:"Azure"}),bitbucket:me({id:"bitbucket",name:"Bitbucket"}),discord:me({id:"discord",name:"Discord"}),facebook:me({id:"facebook",name:"Facebook"}),github:me({id:"github",name:"GitHub"}),gitlab:me({id:"gitlab",name:"Gitlab",url:{default:"https://gitlab.com"}}),google:me({id:"google",name:"Google"}),kakao:me({id:"kakao",name:"Kakao"}),keycloak:me({id:"keycloak",name:"Keycloak",url:{examples:["https://keycloak.example.com/realms/myrealm"]}}),linkedin:me({id:"linkedin",name:"LinkedIn"}),notion:me({id:"notion",name:"Notion"}),twitch:me({id:"twitch",name:"Twitch"}),twitter:me({id:"twitter",name:"Twitter"}),slack:me({id:"slack",name:"Slack"}),spotify:me({id:"spotify",name:"Spotify"}),workos:me({id:"workos",name:"WorkOS"}),zoom:me({id:"zoom",name:"Zoom"})}).partial();var da=["auth"],pa=[{name:"User sessions",link:"https://supabase.com/docs/guides/auth/sessions"}],tf=s.strictObject({timebox:s.string({description:"The timebox for the user session.",tags:da,links:pa}),inactivity_timeout:s.string({description:"The inactivity timeout for the user session.",tags:da,links:pa}),single_per_user:s.boolean({default:false,description:"Limit each user to one active refreshable session.",tags:da,links:pa})}).partial();var se=["auth"],oe={auth:{name:"Auth Server configuration",link:"https://supabase.com/docs/reference/auth"},phoneLogin:t=>({name:`Enabling Phone Login (${t})`,link:`https://supabase.com/docs/guides/auth/phone-login?showSmsProvider=${t}#enabling-phone-login`})},nf=s.strictObject({enable_signup:s.boolean({default:true,description:"Allow/disallow new user signups via SMS to your project.",tags:se,links:[oe.auth]}),enable_confirmations:s.boolean({default:false,description:"If enabled, users need to confirm their phone number before signing in.",tags:se,links:[oe.auth]}),template:s.string({default:"Your code is {{ .Code }}",description:"The template to use for the SMS message.",tags:se,links:[oe.auth]}),max_frequency:s.string({default:"60s",description:"Controls the minimum amount of time that must pass before sending another sms otp.",tags:se}),twilio:s.strictObject({enabled:s.boolean({default:false,description:"Enable/disable Twilio provider for phone login.",tags:se,links:[oe.phoneLogin("Twilio")]}),account_sid:s.string({description:"The account SID for the Twilio API.",tags:se,links:[oe.phoneLogin("Twilio")]}),message_service_sid:s.string({description:"The message service SID for the Twilio API.",tags:se,links:[oe.phoneLogin("Twilio")]}),auth_token:s.string({description:"The auth token for the Twilio API.",tags:se,links:[oe.phoneLogin("Twilio")]})}).partial(),twilio_verify:s.strictObject({enabled:s.boolean({default:false,description:"Enable/disable Twilio Verify provider for phone verification.",tags:se,links:[oe.phoneLogin("Twilio")]}),account_sid:s.string({description:"The account SID for the Twilio API.",tags:se,links:[oe.phoneLogin("Twilio")]}),message_service_sid:s.string({description:"The message service SID for the Twilio API.",tags:se,links:[oe.phoneLogin("Twilio")]}),auth_token:s.string({description:"The auth token for the Twilio API.",tags:se,links:[oe.phoneLogin("Twilio")]})}).partial(),messagebird:s.strictObject({enabled:s.boolean({default:false,description:"Enable/disable MessageBird provider for phone login.",tags:se,links:[oe.phoneLogin("MessageBird")]}),originator:s.string({description:"The originator of the SMS message.",tags:se,links:[oe.phoneLogin("MessageBird")]}),api_key:s.string({description:"The API key for the MessageBird API.",tags:se,links:[oe.phoneLogin("MessageBird")]})}).partial(),textlocal:s.strictObject({enabled:s.boolean({default:false,description:"Enable/disable Textlocal provider for phone login.",tags:se,links:[oe.phoneLogin("Textlocal%2520(Community%2520Supported)")]}),sender:s.string({description:"The sender of the SMS message.",tags:se,links:[oe.phoneLogin("Textlocal%2520(Community%2520Supported)")]}),api_key:s.string({description:"The API key for the Textlocal API.",tags:se,links:[oe.phoneLogin("Textlocal%2520(Community%2520Supported)")]})}).partial(),vonage:s.strictObject({enabled:s.boolean({default:false,description:"Enable/disable Vonage provider for phone login.",tags:se,links:[oe.phoneLogin("Vonage")]}),from:s.string({description:"The sender of the SMS message.",tags:se,links:[oe.phoneLogin("Vonage")]}),api_key:s.string({description:"The API key for the Vonage API.",tags:se,links:[oe.phoneLogin("Vonage")]}),api_secret:s.string({description:"The API secret for the Vonage API.",tags:se,links:[oe.phoneLogin("Vonage")]})}).partial(),test_otp:s.record(s.string(),{description:"Use pre-defined map of phone number to OTP for testing.",tags:se,links:[oe.auth]})}).partial();var Ce=["auth"],Ie={auth:{name:"Auth Server configuration",link:"https://supabase.com/docs/reference/auth"}},rf=["letters_digits","lower_upper_letters_digits","lower_upper_letters_digits_symbols"],sf=s.strictObject({enabled:s.boolean({default:true,description:"Enable the local GoTrue service.",tags:Ce,links:[Ie.auth]}),jwt_secret:s.string({default:"unsafe-secret-change-me",description:"The secret used to sign JWT tokens.",tags:Ce,links:[Ie.auth]}),publishable_key:s.string({description:"The `sb_publishable_*` API key clients use to authenticate as `anon`.",tags:Ce,links:[Ie.auth]}),secret_key:s.string({description:"The `sb_secret_*` API key clients use to authenticate as `service_role`.",tags:Ce,links:[Ie.auth]}),site_url:s.string({default:"http://localhost:3000",description:"The base URL of your website. Used as an allow-list for redirects and for constructing URLs used in emails.",tags:Ce,links:[Ie.auth]}),additional_redirect_urls:s.array(s.string({description:"A URL that auth providers are permitted to redirect to.",tags:Ce}),{default:["https://localhost:3000"],description:"A list of _exact_ URLs that auth providers are permitted to redirect to post authentication.",tags:Ce,links:[Ie.auth]}),jwt_expiry:s.number({default:3600,description:"How long tokens are valid for, in seconds. Defaults to 3600 (1 hour), maximum 604,800 seconds (one week).",tags:Ce,links:[Ie.auth]}),enable_refresh_token_rotation:s.boolean({default:true,description:"If disabled, the refresh token will never expire.",tags:Ce,links:[Ie.auth]}),refresh_token_reuse_interval:s.number({default:10,description:"Allows refresh tokens to be reused after expiry, up to the specified interval in seconds. Requires enable_refresh_token_rotation = true.",tags:Ce,links:[Ie.auth]}),enable_manual_linking:s.boolean({default:false,description:"Allow/disallow testing manual linking of accounts.",tags:Ce,links:[Ie.auth]}),enable_signup:s.boolean({default:true,description:"Allow/disallow new user signups to your project.",tags:Ce,links:[Ie.auth]}),enable_anonymous_sign_ins:s.boolean({default:false,description:"Allow/disallow anonymous sign-ins to your project.",tags:Ce,links:[Ie.auth]}),minimum_password_length:s.number({default:6,description:"Passwords shorter than this value will be rejected as weak. Minimum 6, recommended 8 or more.",tags:Ce,links:[Ie.auth]}),password_requirements:s.string({description:`Passwords that do not meet the following requirements will be rejected as weak. Supported values are: ${rf.join(", ")}`,enum:["",...rf],tags:Ce,links:[Ie.auth]}),hook:Yu,mfa:Xu,sessions:tf,email:Qu,sms:nf,external:ef}).partial();var Xt={postgres:{name:"PostgreSQL configuration",link:"https://postgrest.org/en/stable/configuration.html"},pgbouncer:t=>({name:"PgBouncer Configuration",link:`https://www.pgbouncer.org/config.html${t?`#${t}`:""}`})},ke=["database"],of=s.object({driver:Pt(s.string({enum:["sqlite","sqlite-postgres","pglite","postgres"],default:"sqlite-postgres",description:"The database driver to use.",tags:ke})),url:Pt(s.string({description:"Path to the database file/directory (Supalite only).",tags:ke})),port:s.number({default:54322,description:"Port to use for the local database URL.",tags:ke,links:[Xt.postgres]}),shadow_port:s.number({default:54320,description:"Port to use for the local shadow database.",tags:ke}),major_version:s.number({default:15,description:"The database major version to use. This has to be the same as your remote database's. Run `SHOW server_version;` on the remote database to check.",tags:ke,links:[Xt.postgres]}),pooler:s.object({enabled:s.boolean({default:false,description:"Enable the local PgBouncer service.",tags:ke,links:[Xt.pgbouncer()]}),port:s.number({default:54329,description:"Port to use for the local connection pooler.",tags:ke,links:[Xt.pgbouncer("listen_port")]}),pool_mode:s.string({enum:["transaction","session"],default:"transaction",description:"Specifies when a server connection can be reused by other clients. Configure one of the supported pooler modes: `transaction`, `session`.",tags:ke,links:[Xt.pgbouncer("pool_mode")]}),default_pool_size:s.number({default:20,description:"How many server connections to allow per user/database pair.",tags:ke,links:[Xt.pgbouncer("default_pool_size")]}),max_client_conn:s.number({default:100,description:"Maximum number of client connections allowed.",tags:ke,links:[Xt.pgbouncer("max_client_conn")]})}).partial(),seed:s.strictObject({enabled:s.boolean({default:true,description:"Enable seeding the database with SQL files.",tags:ke}),sql_paths:s.array(s.string({description:"Path to a SQL file to seed the database with.",tags:ke}),{default:["./seed.sql"],description:"Paths to SQL files to seed the database with. Supports glob patterns relative to supabase directory.",examples:[["./seeds/*.sql","../project-src/seeds/*-load-testing.sql"]],tags:ke})}).partial(),migrations:s.strictObject({enabled:s.boolean({default:true,description:"Enable migrations.",tags:ke}),schema_paths:s.array(s.string({description:"Path to a SQL file to seed the database with.",tags:ke}),{default:["./schemas/schema.sql"]})}).partial()}).partial();var ma=["edge-functions"],af=s.strictObject({enabled:s.boolean({default:true,description:"Enable the local Edge Runtime service.",tags:ma}),policy:s.string({enum:["oneshot","per_worker"],default:"oneshot",description:"Configure the supported request policy. Use `oneshot` for hot reload, or `per_worker` for load testing.",tags:ma}),inspector_port:s.number({default:8083,description:"Port to run the Edge Functions inspector on.",tags:ma})}).partial();var Sr=["experimental"],cf=s.strictObject({orioledb_version:s.string({description:"Postgres storage engine to use OrioleDB (S3)",tags:Sr}),s3_host:gt({description:"S3 bucket URL.",examples:["<bucket_name>.s3-<region>.amazonaws.com"],default:"env(S3_HOST)",tags:Sr}),s3_region:gt({description:"S3 bucket region.",examples:["us-east-1"],default:"env(S3_REGION)",tags:Sr}),s3_access_key:gt({description:"S3 access key.",default:"env(S3_ACCESS_KEY)",tags:Sr}),s3_secret_key:gt({description:"S3 secret key.",default:"env(S3_SECRET_KEY)",tags:Sr})}).partial();var si=["functions"],ii=[{name:"`supabase functions` CLI subcommands",link:"https://supabase.com/docs/reference/cli/supabase-functions"}],Ob=yt.strictObject({enabled:yt.boolean({default:true,description:je`
42
+ `,tags:Xt,links:e}),url:s.string({description:"The base URL used for constructing the URLs to request authorization and access tokens.",...t.url,tags:Xt,links:e}),redirect_uri:s.string({description:`The URI the ${t.name} OAuth2 provider will redirect to with the code and state values.`,tags:Xt,links:e}),skip_nonce_check:s.boolean({default:false,description:"If true, the nonce check will be skipped.",tags:Xt,links:e}),email_optional:s.boolean({default:false,description:"If true, an email address is not required to sign in with this provider.",tags:Xt,links:e})}).partial()},of=s.strictObject({apple:me({id:"apple",name:"Apple"}),azure:me({id:"azure",name:"Azure"}),bitbucket:me({id:"bitbucket",name:"Bitbucket"}),discord:me({id:"discord",name:"Discord"}),facebook:me({id:"facebook",name:"Facebook"}),github:me({id:"github",name:"GitHub"}),gitlab:me({id:"gitlab",name:"Gitlab",url:{default:"https://gitlab.com"}}),google:me({id:"google",name:"Google"}),kakao:me({id:"kakao",name:"Kakao"}),keycloak:me({id:"keycloak",name:"Keycloak",url:{examples:["https://keycloak.example.com/realms/myrealm"]}}),linkedin:me({id:"linkedin",name:"LinkedIn"}),notion:me({id:"notion",name:"Notion"}),twitch:me({id:"twitch",name:"Twitch"}),twitter:me({id:"twitter",name:"Twitter"}),slack:me({id:"slack",name:"Slack"}),spotify:me({id:"spotify",name:"Spotify"}),workos:me({id:"workos",name:"WorkOS"}),zoom:me({id:"zoom",name:"Zoom"})}).partial();var ha=["auth"],ga=[{name:"User sessions",link:"https://supabase.com/docs/guides/auth/sessions"}],af=s.strictObject({timebox:s.string({description:"The timebox for the user session.",tags:ha,links:ga}),inactivity_timeout:s.string({description:"The inactivity timeout for the user session.",tags:ha,links:ga}),single_per_user:s.boolean({default:false,description:"Limit each user to one active refreshable session.",tags:ha,links:ga})}).partial();var se=["auth"],oe={auth:{name:"Auth Server configuration",link:"https://supabase.com/docs/reference/auth"},phoneLogin:t=>({name:`Enabling Phone Login (${t})`,link:`https://supabase.com/docs/guides/auth/phone-login?showSmsProvider=${t}#enabling-phone-login`})},lf=s.strictObject({enable_signup:s.boolean({default:true,description:"Allow/disallow new user signups via SMS to your project.",tags:se,links:[oe.auth]}),enable_confirmations:s.boolean({default:false,description:"If enabled, users need to confirm their phone number before signing in.",tags:se,links:[oe.auth]}),template:s.string({default:"Your code is {{ .Code }}",description:"The template to use for the SMS message.",tags:se,links:[oe.auth]}),max_frequency:s.string({default:"60s",description:"Controls the minimum amount of time that must pass before sending another sms otp.",tags:se}),twilio:s.strictObject({enabled:s.boolean({default:false,description:"Enable/disable Twilio provider for phone login.",tags:se,links:[oe.phoneLogin("Twilio")]}),account_sid:s.string({description:"The account SID for the Twilio API.",tags:se,links:[oe.phoneLogin("Twilio")]}),message_service_sid:s.string({description:"The message service SID for the Twilio API.",tags:se,links:[oe.phoneLogin("Twilio")]}),auth_token:s.string({description:"The auth token for the Twilio API.",tags:se,links:[oe.phoneLogin("Twilio")]})}).partial(),twilio_verify:s.strictObject({enabled:s.boolean({default:false,description:"Enable/disable Twilio Verify provider for phone verification.",tags:se,links:[oe.phoneLogin("Twilio")]}),account_sid:s.string({description:"The account SID for the Twilio API.",tags:se,links:[oe.phoneLogin("Twilio")]}),message_service_sid:s.string({description:"The message service SID for the Twilio API.",tags:se,links:[oe.phoneLogin("Twilio")]}),auth_token:s.string({description:"The auth token for the Twilio API.",tags:se,links:[oe.phoneLogin("Twilio")]})}).partial(),messagebird:s.strictObject({enabled:s.boolean({default:false,description:"Enable/disable MessageBird provider for phone login.",tags:se,links:[oe.phoneLogin("MessageBird")]}),originator:s.string({description:"The originator of the SMS message.",tags:se,links:[oe.phoneLogin("MessageBird")]}),api_key:s.string({description:"The API key for the MessageBird API.",tags:se,links:[oe.phoneLogin("MessageBird")]})}).partial(),textlocal:s.strictObject({enabled:s.boolean({default:false,description:"Enable/disable Textlocal provider for phone login.",tags:se,links:[oe.phoneLogin("Textlocal%2520(Community%2520Supported)")]}),sender:s.string({description:"The sender of the SMS message.",tags:se,links:[oe.phoneLogin("Textlocal%2520(Community%2520Supported)")]}),api_key:s.string({description:"The API key for the Textlocal API.",tags:se,links:[oe.phoneLogin("Textlocal%2520(Community%2520Supported)")]})}).partial(),vonage:s.strictObject({enabled:s.boolean({default:false,description:"Enable/disable Vonage provider for phone login.",tags:se,links:[oe.phoneLogin("Vonage")]}),from:s.string({description:"The sender of the SMS message.",tags:se,links:[oe.phoneLogin("Vonage")]}),api_key:s.string({description:"The API key for the Vonage API.",tags:se,links:[oe.phoneLogin("Vonage")]}),api_secret:s.string({description:"The API secret for the Vonage API.",tags:se,links:[oe.phoneLogin("Vonage")]})}).partial(),test_otp:s.record(s.string(),{description:"Use pre-defined map of phone number to OTP for testing.",tags:se,links:[oe.auth]})}).partial();var Ce=["auth"],Ie={auth:{name:"Auth Server configuration",link:"https://supabase.com/docs/reference/auth"}},cf=["letters_digits","lower_upper_letters_digits","lower_upper_letters_digits_symbols"],uf=s.strictObject({enabled:s.boolean({default:true,description:"Enable the local GoTrue service.",tags:Ce,links:[Ie.auth]}),jwt_secret:s.string({default:"unsafe-secret-change-me",description:"The secret used to sign JWT tokens.",tags:Ce,links:[Ie.auth]}),publishable_key:s.string({description:"The `sb_publishable_*` API key clients use to authenticate as `anon`.",tags:Ce,links:[Ie.auth]}),secret_key:s.string({description:"The `sb_secret_*` API key clients use to authenticate as `service_role`.",tags:Ce,links:[Ie.auth]}),site_url:s.string({default:"http://localhost:3000",description:"The base URL of your website. Used as an allow-list for redirects and for constructing URLs used in emails.",tags:Ce,links:[Ie.auth]}),additional_redirect_urls:s.array(s.string({description:"A URL that auth providers are permitted to redirect to.",tags:Ce}),{default:["https://localhost:3000"],description:"A list of _exact_ URLs that auth providers are permitted to redirect to post authentication.",tags:Ce,links:[Ie.auth]}),jwt_expiry:s.number({default:3600,description:"How long tokens are valid for, in seconds. Defaults to 3600 (1 hour), maximum 604,800 seconds (one week).",tags:Ce,links:[Ie.auth]}),enable_refresh_token_rotation:s.boolean({default:true,description:"If disabled, the refresh token will never expire.",tags:Ce,links:[Ie.auth]}),refresh_token_reuse_interval:s.number({default:10,description:"Allows refresh tokens to be reused after expiry, up to the specified interval in seconds. Requires enable_refresh_token_rotation = true.",tags:Ce,links:[Ie.auth]}),enable_manual_linking:s.boolean({default:false,description:"Allow/disallow testing manual linking of accounts.",tags:Ce,links:[Ie.auth]}),enable_signup:s.boolean({default:true,description:"Allow/disallow new user signups to your project.",tags:Ce,links:[Ie.auth]}),enable_anonymous_sign_ins:s.boolean({default:false,description:"Allow/disallow anonymous sign-ins to your project.",tags:Ce,links:[Ie.auth]}),minimum_password_length:s.number({default:6,description:"Passwords shorter than this value will be rejected as weak. Minimum 6, recommended 8 or more.",tags:Ce,links:[Ie.auth]}),password_requirements:s.string({description:`Passwords that do not meet the following requirements will be rejected as weak. Supported values are: ${cf.join(", ")}`,enum:["",...cf],tags:Ce,links:[Ie.auth]}),hook:nf,mfa:rf,sessions:af,email:tf,sms:lf,external:of}).partial();var Yt={postgres:{name:"PostgreSQL configuration",link:"https://postgrest.org/en/stable/configuration.html"},pgbouncer:t=>({name:"PgBouncer Configuration",link:`https://www.pgbouncer.org/config.html${t?`#${t}`:""}`})},ke=["database"],ff=s.object({driver:Pt(s.string({enum:["sqlite","sqlite-postgres","pglite","postgres"],default:"sqlite-postgres",description:"The database driver to use.",tags:ke})),url:Pt(s.string({description:"Path to the database file/directory (Supalite only).",tags:ke})),port:s.number({default:54322,description:"Port to use for the local database URL.",tags:ke,links:[Yt.postgres]}),shadow_port:s.number({default:54320,description:"Port to use for the local shadow database.",tags:ke}),major_version:s.number({default:15,description:"The database major version to use. This has to be the same as your remote database's. Run `SHOW server_version;` on the remote database to check.",tags:ke,links:[Yt.postgres]}),pooler:s.object({enabled:s.boolean({default:false,description:"Enable the local PgBouncer service.",tags:ke,links:[Yt.pgbouncer()]}),port:s.number({default:54329,description:"Port to use for the local connection pooler.",tags:ke,links:[Yt.pgbouncer("listen_port")]}),pool_mode:s.string({enum:["transaction","session"],default:"transaction",description:"Specifies when a server connection can be reused by other clients. Configure one of the supported pooler modes: `transaction`, `session`.",tags:ke,links:[Yt.pgbouncer("pool_mode")]}),default_pool_size:s.number({default:20,description:"How many server connections to allow per user/database pair.",tags:ke,links:[Yt.pgbouncer("default_pool_size")]}),max_client_conn:s.number({default:100,description:"Maximum number of client connections allowed.",tags:ke,links:[Yt.pgbouncer("max_client_conn")]})}).partial(),seed:s.strictObject({enabled:s.boolean({default:true,description:"Enable seeding the database with SQL files.",tags:ke}),sql_paths:s.array(s.string({description:"Path to a SQL file to seed the database with.",tags:ke}),{default:["./seed.sql"],description:"Paths to SQL files to seed the database with. Supports glob patterns relative to supabase directory.",examples:[["./seeds/*.sql","../project-src/seeds/*-load-testing.sql"]],tags:ke})}).partial(),migrations:s.strictObject({enabled:s.boolean({default:true,description:"Enable migrations.",tags:ke}),schema_paths:s.array(s.string({description:"Path to a SQL file to seed the database with.",tags:ke}),{default:["./schemas/schema.sql"]})}).partial()}).partial();var ya=["edge-functions"],df=s.strictObject({enabled:s.boolean({default:true,description:"Enable the local Edge Runtime service.",tags:ya}),policy:s.string({enum:["oneshot","per_worker"],default:"oneshot",description:"Configure the supported request policy. Use `oneshot` for hot reload, or `per_worker` for load testing.",tags:ya}),inspector_port:s.number({default:8083,description:"Port to run the Edge Functions inspector on.",tags:ya})}).partial();var Sr=["experimental"],mf=s.strictObject({orioledb_version:s.string({description:"Postgres storage engine to use OrioleDB (S3)",tags:Sr}),s3_host:gt({description:"S3 bucket URL.",examples:["<bucket_name>.s3-<region>.amazonaws.com"],default:"env(S3_HOST)",tags:Sr}),s3_region:gt({description:"S3 bucket region.",examples:["us-east-1"],default:"env(S3_REGION)",tags:Sr}),s3_access_key:gt({description:"S3 access key.",default:"env(S3_ACCESS_KEY)",tags:Sr}),s3_secret_key:gt({description:"S3 secret key.",default:"env(S3_SECRET_KEY)",tags:Sr})}).partial();var si=["functions"],ii=[{name:"`supabase functions` CLI subcommands",link:"https://supabase.com/docs/reference/cli/supabase-functions"}],Db=yt.strictObject({enabled:yt.boolean({default:true,description:je`
43
43
  Controls whether a function is deployed or served. When set to false,
44
44
  the function will be skipped during deployment and won't be served locally.
45
45
  This is useful for disabling demo functions or temporarily disabling a function
@@ -56,7 +56,7 @@ ${s}`)}return t}var Gu=[{name:"Self-hosted Logflare Configuration",link:"https:/
56
56
  Specify the entrypoint path to the Function (defaults to "functions/slug/index.ts").
57
57
 
58
58
  Both \`.js\` and \`.ts\` file extensions are supported.
59
- `,tags:si,links:ii})}).partial(),uf=yt.strictObject({},{patternProperties:{"^[a-zA-Z0-9_-]+$":Ob}});var oi=[{name:"Inbucket documentation",link:"https://www.inbucket.org"}],ai=["local"],ff=s.strictObject({enabled:s.boolean({default:true,description:"Enable the local InBucket service.",tags:ai,links:oi}),port:s.number({default:54324,description:je`
59
+ `,tags:si,links:ii})}).partial(),hf=yt.strictObject({},{patternProperties:{"^[a-zA-Z0-9_-]+$":Db}});var oi=[{name:"Inbucket documentation",link:"https://www.inbucket.org"}],ai=["local"],gf=s.strictObject({enabled:s.boolean({default:true,description:"Enable the local InBucket service.",tags:ai,links:oi}),port:s.number({default:54324,description:je`
60
60
  Port to use for the email testing server web interface.
61
61
 
62
62
  Emails sent with the local dev setup are not actually sent - rather, they are monitored, and you can view the emails that would have been sent from the web interface.
@@ -72,21 +72,21 @@ ${s}`)}return t}var Gu=[{name:"Self-hosted Logflare Configuration",link:"https:/
72
72
  Emails sent with the local dev setup are not actually sent - rather, they are monitored, and you can view the emails that would have been sent from the web interface.
73
73
 
74
74
  If set, you can access the POP3 server from this port.
75
- `,tags:ai,links:oi})}).partial();var Pb=[{name:"Supabase Realtime",link:"https://supabase.com/docs/guides/realtime"}],ha=["realtime"],df=s.strictObject({enabled:s.boolean({default:true,description:"Enable the local Realtime service.",tags:ha,links:Pb}),ip_version:s.string({enum:["IPv4","IPv6"],default:"IPv4",description:"Bind realtime via either IPv4 or IPv6.",tags:ha,links:[{name:"Supabase Realtime Configuration",link:"https://supabase.com/docs/guides/realtime/self-hosting"}]}),max_header_length:s.number({default:4096,description:"Maximum length of the HTTP header.",tags:ha})}).partial();var ci=[{name:"Storage server configuration",link:"https://supabase.com/docs/guides/self-hosting/storage/config"}],Dt=["storage"],$b=s.strictObject({public:s.boolean({default:false,description:"Enable public access to the bucket."}),file_size_limit:s.string({default:"50MiB",description:"The maximum file size allowed for the bucket.",examples:["5MB","500KB"],tags:Dt,links:ci}),allowed_mime_types:s.array(s.string({description:"A MIME type allowed for the bucket.",tags:Dt}),{examples:[["image/png","image/jpeg"]],description:"The list of allowed MIME types for the bucket.",tags:Dt}),objects_path:s.string({description:"The path to the objects in the bucket.",tags:Dt})}).partial(),pf=s.strictObject({enabled:s.boolean({default:true,description:"Enable the local Storage service.",tags:Dt,links:ci}),file_size_limit:s.string({default:"50MiB",description:"The maximum file size allowed.",examples:["5MB","500KB"],tags:Dt,links:ci}),image_transformation:s.strictObject({enabled:s.boolean({default:true,description:"Enable image transformation.",tags:Dt,links:ci})}).partial(),buckets:s.record($b,{description:"Storage buckets configuration.",tags:Dt})}).partial();var ga={studio:{name:"Supabase Studio",link:"https://supabase.com/docs/guides/studio"},config:{name:"Supabase Studio Configuration",link:"https://supabase.com/docs/guides/self-hosting/studio"}},fi=["studio"],mf=s.strictObject({enabled:s.boolean({default:true,description:"Enable the local Supabase Studio dashboard.",tags:fi,links:[ga.studio]}),port:s.number({default:54323,description:"Port to use for Supabase Studio.",tags:fi}),api_url:s.string({default:"http://localhost",description:"External URL of the API server that frontend connects to.",tags:fi,links:[ga.config]}),openai_api_key:gt({default:"env(OPENAI_API_KEY)",description:"OpenAI API key to use for Supabase AI in the Supabase Studio.",tags:fi,links:[ga.config]})}).partial();var pi=yt.strictObject({project_id:yt.string({description:"A string used to distinguish different Supabase projects on the same host. Defaults to the working directory name when running `supabase init`.",tags:["general"]}),analytics:zu,api:Vu,auth:sf,db:of,edge_runtime:af,functions:uf,inbucket:ff,realtime:df,storage:pf,studio:mf,experimental:cf}).partial();var ya=(t,e,n)=>(r,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,f;if(t[a]?(f=t[a][0][0],r.req.routeIndex=a):f=a===t.length&&s||void 0,f)try{l=await f(r,()=>o(a+1));}catch(u){if(u instanceof Error&&e)r.error=u,l=await e(u,r),c=true;else throw u}else r.finalized===false&&n&&(l=await n(r));return l&&(r.finalized===false||c)&&(r.res=l),r}};var hf=Symbol();var gf=async(t,e=Object.create(null))=>{let{all:n=false,dot:r=false}=e,i=(t instanceof mi?t.raw.headers:t.headers).get("Content-Type");return i?.startsWith("multipart/form-data")||i?.startsWith("application/x-www-form-urlencoded")?Ib(t,{all:n,dot:r}):{}};async function Ib(t,e){let n=await t.formData();return n?Nb(n,e):{}}function Nb(t,e){let n=Object.create(null);return t.forEach((r,s)=>{e.all||s.endsWith("[]")?Db(n,s,r):n[s]=r;}),e.dot&&Object.entries(n).forEach(([r,s])=>{r.includes(".")&&(jb(n,r,s),delete n[r]);}),n}var Db=(t,e,n)=>{t[e]!==void 0?Array.isArray(t[e])?t[e].push(n):t[e]=[t[e],n]:e.endsWith("[]")?t[e]=[n]:t[e]=n;},jb=(t,e,n)=>{let r=t,s=e.split(".");s.forEach((i,o)=>{o===s.length-1?r[i]=n:((!r[i]||typeof r[i]!="object"||Array.isArray(r[i])||r[i]instanceof File)&&(r[i]=Object.create(null)),r=r[i]);});};var wa=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},yf=t=>{let{groups:e,path:n}=Lb(t),r=wa(n);return Fb(r,e)},Lb=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(n,r)=>{let s=`@${r}`;return e.push([s,n]),s}),{groups:e,path:t}},Fb=(t,e)=>{for(let n=e.length-1;n>=0;n--){let[r]=e[n];for(let s=t.length-1;s>=0;s--)if(t[s].includes(r)){t[s]=t[s].replace(r,e[n][1]);break}}return t},hi={},bf=(t,e)=>{if(t==="*")return "*";let n=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${t}#${e}`;return hi[r]||(n[2]?hi[r]=e&&e[0]!==":"&&e[0]!=="*"?[r,n[1],new RegExp(`^${n[2]}(?=/${e})`)]:[t,n[1],new RegExp(`^${n[2]}$`)]:hi[r]=[t,n[1],true]),hi[r]}return null},gi=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,n=>{try{return e(n)}catch{return n}})}},Ub=t=>gi(t,decodeURI),Sa=t=>{let e=t.url,n=e.indexOf("/",e.indexOf(":")+4),r=n;for(;r<e.length;r++){let s=e.charCodeAt(r);if(s===37){let i=e.indexOf("?",r),o=e.indexOf("#",r),a=i===-1?o===-1?void 0:o:o===-1?i:Math.min(i,o),l=e.slice(n,a);return Ub(l.includes("%25")?l.replace(/%25/g,"%2525"):l)}else if(s===63||s===35)break}return e.slice(n,r)};var wf=t=>{let e=Sa(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},Zt=(t,e,...n)=>(n.length&&(e=Zt(e,...n)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),yi=t=>{if(t.charCodeAt(t.length-1)!==63||!t.includes(":"))return null;let e=t.split("/"),n=[],r="";return e.forEach(s=>{if(s!==""&&!/\:/.test(s))r+="/"+s;else if(/\:/.test(s))if(/\?/.test(s)){n.length===0&&r===""?n.push("/"):n.push(r);let i=s.replace("?","");r+="/"+i,n.push(r);}else r+="/"+s;}),n.filter((s,i,o)=>o.indexOf(s)===i)},ba=t=>/[%+]/.test(t)?(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),t.indexOf("%")!==-1?gi(t,_a):t):t,Sf=(t,e,n)=>{let r;if(!n&&e&&!/[%+]/.test(e)){let o=t.indexOf("?",8);if(o===-1)return;for(t.startsWith(e,o+1)||(o=t.indexOf(`&${e}`,o+1));o!==-1;){let a=t.charCodeAt(o+e.length+1);if(a===61){let l=o+e.length+2,c=t.indexOf("&",l);return ba(t.slice(l,c===-1?void 0:c))}else if(a==38||isNaN(a))return "";o=t.indexOf(`&${e}`,o+1);}if(r=/[%+]/.test(t),!r)return}let s={};r??=/[%+]/.test(t);let i=t.indexOf("?",8);for(;i!==-1;){let o=t.indexOf("&",i+1),a=t.indexOf("=",i);a>o&&o!==-1&&(a=-1);let l=t.slice(i+1,a===-1?o===-1?void 0:o:a);if(r&&(l=ba(l)),i=o,l==="")continue;let c;a===-1?c="":(c=t.slice(a+1,o===-1?void 0:o),r&&(c=ba(c))),n?(s[l]&&Array.isArray(s[l])||(s[l]=[]),s[l].push(c)):s[l]??=c;}return e?s[e]:s},_f=Sf,Ef=(t,e)=>Sf(t,e,true),_a=decodeURIComponent;var xf=t=>gi(t,_a),mi=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(t,e="/",n=[[]]){this.raw=t,this.path=e,this.#e=n,this.#t={};}param(t){return t?this.#n(t):this.#i()}#n(t){let e=this.#e[0][this.routeIndex][1][t],n=this.#r(e);return n&&/\%/.test(n)?xf(n):n}#i(){let t={},e=Object.keys(this.#e[0][this.routeIndex][1]);for(let n of e){let r=this.#r(this.#e[0][this.routeIndex][1][n]);r!==void 0&&(t[n]=/\%/.test(r)?xf(r):r);}return t}#r(t){return this.#e[1]?this.#e[1][t]:t}query(t){return _f(this.url,t)}queries(t){return Ef(this.url,t)}header(t){if(t)return this.raw.headers.get(t)??void 0;let e={};return this.raw.headers.forEach((n,r)=>{e[r]=n;}),e}async parseBody(t){return this.bodyCache.parsedBody??=await gf(this,t)}#s=t=>{let{bodyCache:e,raw:n}=this,r=e[t];if(r)return r;let s=Object.keys(e)[0];return s?e[s].then(i=>(s==="json"&&(i=JSON.stringify(i)),new Response(i)[t]())):e[t]=n[t]()};json(){return this.#s("text").then(t=>JSON.parse(t))}text(){return this.#s("text")}arrayBuffer(){return this.#s("arrayBuffer")}blob(){return this.#s("blob")}formData(){return this.#s("formData")}addValidatedData(t,e){this.#t[t]=e;}valid(t){return this.#t[t]}get url(){return this.raw.url}get method(){return this.raw.method}get[hf](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,t]])=>t)}get routePath(){return this.#e[0].map(([[,t]])=>t)[this.routeIndex].path}};var Ye={Stringify:1},X=(t,e)=>{let n=new String(t);return n.isEscaped=true,n.callbacks=e,n},Mb=/[&<>'"]/,bi=async(t,e)=>{let n="";e||=[];let r=await Promise.all(t);for(let s=r.length-1;n+=r[s],s--,!(s<0);s--){let i=r[s];typeof i=="object"&&e.push(...i.callbacks||[]);let o=i.isEscaped;if(i=await(typeof i=="object"?i.toString():i),typeof i=="object"&&e.push(...i.callbacks||[]),i.isEscaped??o)n+=i;else {let a=[n];bt(i,a),n=a[0];}}return X(n,e)},bt=(t,e)=>{let n=t.search(Mb);if(n===-1){e[0]+=t;return}let r,s,i=0;for(s=n;s<t.length;s++){switch(t.charCodeAt(s)){case 34:r="&quot;";break;case 39:r="&#39;";break;case 38:r="&amp;";break;case 60:r="&lt;";break;case 62:r="&gt;";break;default:continue}e[0]+=t.substring(i,s)+r,i=s+1;}e[0]+=t.substring(i,s);},Ea=t=>{let e=t.callbacks;if(!e?.length)return t;let n=[t],r={};return e.forEach(s=>s({phase:Ye.Stringify,buffer:n,context:r})),n[0]},en=async(t,e,n,r,s)=>{typeof t=="object"&&!(t instanceof String)&&(t instanceof Promise||(t=t.toString()),t instanceof Promise&&(t=await t));let i=t.callbacks;if(!i?.length)return Promise.resolve(t);s?s[0]+=t:s=[t];let o=Promise.all(i.map(a=>a({phase:e,buffer:s,context:r}))).then(a=>Promise.all(a.filter(Boolean).map(l=>en(l,e,false,r,s))).then(()=>s[0]));return n?X(await o,i):o};var Bb="text/plain; charset=UTF-8",xa=(t,e)=>({"Content-Type":t,...e}),Er=(t,e)=>new Response(t,e),Tf=class{#t;#e;env={};#n;finalized=false;error;#i;#r;#s;#u;#l;#c;#a;#f;#d;constructor(t,e){this.#t=t,e&&(this.#r=e.executionCtx,this.env=e.env,this.#c=e.notFoundHandler,this.#d=e.path,this.#f=e.matchResult);}get req(){return this.#e??=new mi(this.#t,this.#d,this.#f),this.#e}get event(){if(this.#r&&"respondWith"in this.#r)return this.#r;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#r)return this.#r;throw Error("This context has no ExecutionContext")}get res(){return this.#s||=Er(null,{headers:this.#a??=new Headers})}set res(t){if(this.#s&&t){t=Er(t.body,t);for(let[e,n]of this.#s.headers.entries())if(e!=="content-type")if(e==="set-cookie"){let r=this.#s.headers.getSetCookie();t.headers.delete("set-cookie");for(let s of r)t.headers.append("set-cookie",s);}else t.headers.set(e,n);}this.#s=t,this.finalized=true;}render=(...t)=>(this.#l??=e=>this.html(e),this.#l(...t));setLayout=t=>this.#u=t;getLayout=()=>this.#u;setRenderer=t=>{this.#l=t;};header=(t,e,n)=>{this.finalized&&(this.#s=Er(this.#s.body,this.#s));let r=this.#s?this.#s.headers:this.#a??=new Headers;e===void 0?r.delete(t):n?.append?r.append(t,e):r.set(t,e);};status=t=>{this.#i=t;};set=(t,e)=>{this.#n??=new Map,this.#n.set(t,e);};get=t=>this.#n?this.#n.get(t):void 0;get var(){return this.#n?Object.fromEntries(this.#n):{}}#o(t,e,n){let r=this.#s?new Headers(this.#s.headers):this.#a??new Headers;if(typeof e=="object"&&"headers"in e){let i=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(let[o,a]of i)o.toLowerCase()==="set-cookie"?r.append(o,a):r.set(o,a);}if(n)for(let[i,o]of Object.entries(n))if(typeof o=="string")r.set(i,o);else {r.delete(i);for(let a of o)r.append(i,a);}let s=typeof e=="number"?e:e?.status??this.#i;return Er(t,{status:s,headers:r})}newResponse=(...t)=>this.#o(...t);body=(t,e,n)=>this.#o(t,e,n);text=(t,e,n)=>!this.#a&&!this.#i&&!e&&!n&&!this.finalized?new Response(t):this.#o(t,e,xa(Bb,n));json=(t,e,n)=>this.#o(JSON.stringify(t),e,xa("application/json",n));html=(t,e,n)=>{let r=s=>this.#o(s,e,xa("text/html; charset=UTF-8",n));return typeof t=="object"?en(t,Ye.Stringify,false,{}).then(r):r(t)};redirect=(t,e)=>{let n=String(t);return this.header("Location",/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,e??302)};notFound=()=>(this.#c??=()=>Er(),this.#c(this))};var ne="ALL",Rf="all",Cf=["get","post","put","delete","options","patch"],wi="Can not add a route since the matcher is already built.",Si=class extends Error{};var kf="__COMPOSED_HANDLER";var qb=t=>t.text("404 Not Found",404),vf=(t,e)=>{if("getResponse"in t){let n=t.getResponse();return e.newResponse(n.body,n)}return console.error(t),e.text("Internal Server Error",500)},Af=class Of{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(e={}){[...Cf,Rf].forEach(i=>{this[i]=(o,...a)=>(typeof o=="string"?this.#t=o:this.#i(i,this.#t,o),a.forEach(l=>{this.#i(i,this.#t,l);}),this);}),this.on=(i,o,...a)=>{for(let l of [o].flat()){this.#t=l;for(let c of [i].flat())a.map(f=>{this.#i(c.toUpperCase(),this.#t,f);});}return this},this.use=(i,...o)=>(typeof i=="string"?this.#t=i:(this.#t="*",o.unshift(i)),o.forEach(a=>{this.#i(ne,this.#t,a);}),this);let{strict:r,...s}=e;Object.assign(this,s),this.getPath=r??true?e.getPath??Sa:wf;}#e(){let e=new Of({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#n=this.#n,e.routes=this.routes,e}#n=qb;errorHandler=vf;route(e,n){let r=this.basePath(e);return n.routes.map(s=>{let i;n.errorHandler===vf?i=s.handler:(i=async(o,a)=>(await ya([],n.errorHandler)(o,()=>s.handler(o,a))).res,i[kf]=s.handler),r.#i(s.method,s.path,i);}),this}basePath(e){let n=this.#e();return n._basePath=Zt(this._basePath,e),n}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#n=e,this);mount(e,n,r){let s,i;r&&(typeof r=="function"?i=r:(i=r.optionHandler,r.replaceRequest===false?s=l=>l:s=r.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=Zt(this._basePath,e),c=l==="/"?0:l.length;return f=>{let u=new URL(f.url);return u.pathname=u.pathname.slice(c)||"/",new Request(u,f)}})();let a=async(l,c)=>{let f=await n(s(l.req.raw),...o(l));if(f)return f;await c();};return this.#i(ne,Zt(e,"*"),a),this}#i(e,n,r){e=e.toUpperCase(),n=Zt(this._basePath,n);let s={basePath:this._basePath,path:n,method:e,handler:r};this.router.add(e,n,[r,s]),this.routes.push(s);}#r(e,n){if(e instanceof Error)return this.errorHandler(e,n);throw e}#s(e,n,r,s){if(s==="HEAD")return (async()=>new Response(null,await this.#s(e,n,r,"GET")))();let i=this.getPath(e,{env:r}),o=this.router.match(s,i),a=new Tf(e,{path:i,matchResult:o,env:r,executionCtx:n,notFoundHandler:this.#n});if(o[0].length===1){let c;try{c=o[0][0][0][0](a,async()=>{a.res=await this.#n(a);});}catch(f){return this.#r(f,a)}return c instanceof Promise?c.then(f=>f||(a.finalized?a.res:this.#n(a))).catch(f=>this.#r(f,a)):c??this.#n(a)}let l=ya(o[0],this.errorHandler,this.#n);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.#r(c,a)}})()}fetch=(e,...n)=>this.#s(e,n[1],n[0],e.method);request=(e,n,r,s)=>e instanceof Request?this.fetch(n?new Request(e,n):e,r,s):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${Zt("/",e)}`,n),r,s));fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.#s(e.request,e,void 0,e.request.method));});}};var _i=[];function Ta(t,e){let n=this.buildAllMatchers(),r=((s,i)=>{let o=n[s]||n[ne],a=o[2][i];if(a)return a;let l=i.match(o[0]);if(!l)return [[],_i];let c=l.indexOf("",1);return [o[1][c],l]});return this.match=r,r(t,e)}var Ei="[^/]+",xr=".*",Tr="(?:|/.*)",tn=Symbol(),Hb=new Set(".\\+*[^]$()");function Wb(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1||t===xr||t===Tr?1:e===xr||e===Tr?-1:t===Ei?1:e===Ei?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var Pf=class Ra{#t;#e;#n=Object.create(null);insert(e,n,r,s,i){if(e.length===0){if(this.#t!==void 0)throw tn;if(i)return;this.#t=n;return}let[o,...a]=e,l=o==="*"?a.length===0?["","",xr]:["","",Ei]:o==="/*"?["","",Tr]:o.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(l){let f=l[1],u=l[2]||Ei;if(f&&l[2]&&(u===".*"||(u=u.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(u))))throw tn;if(c=this.#n[u],!c){if(Object.keys(this.#n).some(d=>d!==xr&&d!==Tr))throw tn;if(i)return;c=this.#n[u]=new Ra,f!==""&&(c.#e=s.varIndex++);}!i&&f!==""&&r.push([f,c.#e]);}else if(c=this.#n[o],!c){if(Object.keys(this.#n).some(f=>f.length>1&&f!==xr&&f!==Tr))throw tn;if(i)return;c=this.#n[o]=new Ra;}c.insert(a,n,r,s,i);}buildRegExpStr(){let n=Object.keys(this.#n).sort(Wb).map(r=>{let s=this.#n[r];return (typeof s.#e=="number"?`(${r})@${s.#e}`:Hb.has(r)?`\\${r}`:r)+s.buildRegExpStr()});return typeof this.#t=="number"&&n.unshift(`#${this.#t}`),n.length===0?"":n.length===1?n[0]:"(?:"+n.join("|")+")"}};var $f=class{#t={varIndex:0};#e=new Pf;insert(t,e,n){let r=[],s=[];for(let o=0;;){let a=false;if(t=t.replace(/\{[^}]+\}/g,l=>{let c=`@\\${o}`;return s[o]=[c,l],o++,a=true,c}),!a)break}let i=t.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.#e.insert(i,e,r,this.#t,n),r}buildRegExp(){let t=this.#e.buildRegExpStr();if(t==="")return [/^$/,[],[]];let e=0,n=[],r=[];return t=t.replace(/#(\d+)|@(\d+)|\.\*\$/g,(s,i,o)=>i!==void 0?(n[++e]=Number(i),"$()"):(o!==void 0&&(r[Number(o)]=++e),"")),[new RegExp(`^${t}`),n,r]}};var Kb=[/^$/,[],Object.create(null)],If=Object.create(null);function Nf(t){return If[t]??=new RegExp(t==="*"?"":`^${t.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,n)=>n?`\\${n}`:"(?:|/.*)")}$`)}function Jb(){If=Object.create(null);}function Gb(t){let e=new $f,n=[];if(t.length===0)return Kb;let r=t.map(c=>[!/\*|\/:/.test(c[0]),...c]).sort(([c,f],[u,d])=>c?1:u?-1:f.length-d.length),s=Object.create(null);for(let c=0,f=-1,u=r.length;c<u;c++){let[d,p,g]=r[c];d?s[p]=[g.map(([h])=>[h,Object.create(null)]),_i]:f++;let m;try{m=e.insert(p,f,d);}catch(h){throw h===tn?new Si(p):h}d||(n[f]=g.map(([h,y])=>{let w=Object.create(null);for(y-=1;y>=0;y--){let[S,b]=m[y];w[S]=b;}return [h,w]}));}let[i,o,a]=e.buildRegExp();for(let c=0,f=n.length;c<f;c++)for(let u=0,d=n[c].length;u<d;u++){let p=n[c][u]?.[1];if(!p)continue;let g=Object.keys(p);for(let m=0,h=g.length;m<h;m++)p[g[m]]=a[p[g[m]]];}let l=[];for(let c in o)l[c]=n[o[c]];return [i,l,s]}function Cn(t,e){if(t){for(let n of Object.keys(t).sort((r,s)=>s.length-r.length))if(Nf(n).test(e))return [...t[n]]}}var xi=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[ne]:Object.create(null)},this.#e={[ne]:Object.create(null)};}add(t,e,n){let r=this.#t,s=this.#e;if(!r||!s)throw new Error(wi);r[t]||[r,s].forEach(a=>{a[t]=Object.create(null),Object.keys(a[ne]).forEach(l=>{a[t][l]=[...a[ne][l]];});}),e==="/*"&&(e="*");let i=(e.match(/\/:/g)||[]).length;if(/\*$/.test(e)){let a=Nf(e);t===ne?Object.keys(r).forEach(l=>{r[l][e]||=Cn(r[l],e)||Cn(r[ne],e)||[];}):r[t][e]||=Cn(r[t],e)||Cn(r[ne],e)||[],Object.keys(r).forEach(l=>{(t===ne||t===l)&&Object.keys(r[l]).forEach(c=>{a.test(c)&&r[l][c].push([n,i]);});}),Object.keys(s).forEach(l=>{(t===ne||t===l)&&Object.keys(s[l]).forEach(c=>a.test(c)&&s[l][c].push([n,i]));});return}let o=yi(e)||[e];for(let a=0,l=o.length;a<l;a++){let c=o[a];Object.keys(s).forEach(f=>{(t===ne||t===f)&&(s[f][c]||=[...Cn(r[f],c)||Cn(r[ne],c)||[]],s[f][c].push([n,i-l+a+1]));});}}match=Ta;buildAllMatchers(){let t=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#t)).forEach(e=>{t[e]||=this.#n(e);}),this.#t=this.#e=void 0,Jb(),t}#n(t){let e=[],n=t===ne;return [this.#t,this.#e].forEach(r=>{let s=r[t]?Object.keys(r[t]).map(i=>[i,r[t][i]]):[];s.length!==0?(n||=true,e.push(...s)):t!==ne&&e.push(...Object.keys(r[ne]).map(i=>[i,r[ne][i]]));}),n?Gb(e):null}};var Ca=class{name="SmartRouter";#t=[];#e=[];constructor(t){this.#t=t.routers;}add(t,e,n){if(!this.#e)throw new Error(wi);this.#e.push([t,e,n]);}match(t,e){if(!this.#e)throw new Error("Fatal error");let n=this.#t,r=this.#e,s=n.length,i=0,o;for(;i<s;i++){let a=n[i];try{for(let l=0,c=r.length;l<c;l++)a.add(...r[l]);o=a.match(t,e);}catch(l){if(l instanceof Si)continue;throw l}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(i===s)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};var Rr=Object.create(null),zb=t=>{for(let e in t)return true;return false},Df=class jf{#t;#e;#n;#i=0;#r=Rr;constructor(e,n,r){if(this.#e=r||Object.create(null),this.#t=[],e&&n){let s=Object.create(null);s[e]={handler:n,possibleKeys:[],score:0},this.#t=[s];}this.#n=[];}insert(e,n,r){this.#i=++this.#i;let s=this,i=yf(n),o=[];for(let a=0,l=i.length;a<l;a++){let c=i[a],f=i[a+1],u=bf(c,f),d=Array.isArray(u)?u[0]:c;if(d in s.#e){s=s.#e[d],u&&o.push(u[1]);continue}s.#e[d]=new jf,u&&(s.#n.push(u),o.push(u[1])),s=s.#e[d];}return s.#t.push({[e]:{handler:r,possibleKeys:o.filter((a,l,c)=>c.indexOf(a)===l),score:this.#i}}),s}#s(e,n,r,s,i){for(let o=0,a=n.#t.length;o<a;o++){let l=n.#t[o],c=l[r]||l[ne],f={};if(c!==void 0&&(c.params=Object.create(null),e.push(c),s!==Rr||i&&i!==Rr))for(let u=0,d=c.possibleKeys.length;u<d;u++){let p=c.possibleKeys[u],g=f[c.score];c.params[p]=i?.[p]&&!g?i[p]:s[p]??i?.[p],f[c.score]=true;}}}search(e,n){let r=[];this.#r=Rr;let i=[this],o=wa(n),a=[],l=o.length,c=null;for(let f=0;f<l;f++){let u=o[f],d=f===l-1,p=[];for(let m=0,h=i.length;m<h;m++){let y=i[m],w=y.#e[u];w&&(w.#r=y.#r,d?(w.#e["*"]&&this.#s(r,w.#e["*"],e,y.#r),this.#s(r,w,e,y.#r)):p.push(w));for(let S=0,b=y.#n.length;S<b;S++){let _=y.#n[S],E=y.#r===Rr?{}:{...y.#r};if(_==="*"){let C=y.#e["*"];C&&(this.#s(r,C,e,y.#r),C.#r=E,p.push(C));continue}let[x,O,v]=_;if(!u&&!(v instanceof RegExp))continue;let P=y.#e[x];if(v instanceof RegExp){if(c===null){c=new Array(l);let U=n[0]==="/"?1:0;for(let J=0;J<l;J++)c[J]=U,U+=o[J].length+1;}let C=n.substring(c[f]),R=v.exec(C);if(R){if(E[O]=R[0],this.#s(r,P,e,y.#r,E),zb(P.#e)){P.#r=E;let U=R[0].match(/\//)?.length??0;(a[U]||=[]).push(P);}continue}}(v===true||v.test(u))&&(E[O]=u,d?(this.#s(r,P,e,E,y.#r),P.#e["*"]&&this.#s(r,P.#e["*"],e,E,y.#r)):(P.#r=E,p.push(P)));}}let g=a.shift();i=g?p.concat(g):p;}return r.length>1&&r.sort((f,u)=>f.score-u.score),[r.map(({handler:f,params:u})=>[f,u])]}};var ka=class{name="TrieRouter";#t;constructor(){this.#t=new Df;}add(t,e,n){let r=yi(e);if(r){for(let s=0,i=r.length;s<i;s++)this.#t.insert(t,r[s],n);return}this.#t.insert(t,e,n);}match(t,e){return this.#t.search(t,e)}};var _e=class extends Af{constructor(t={}){super(t),this.router=t.router??new Ca({routers:[new xi,new ka]});}};var Lf=t=>{let n={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...t},r=(i=>typeof i=="string"?i==="*"?()=>i:o=>i===o?o:null:typeof i=="function"?i:o=>i.includes(o)?o:null)(n.origin),s=(i=>typeof i=="function"?i:Array.isArray(i)?()=>i:()=>[])(n.allowMethods);return async function(o,a){function l(f,u){o.res.headers.set(f,u);}let c=await r(o.req.header("origin")||"",o);if(c&&l("Access-Control-Allow-Origin",c),n.credentials&&l("Access-Control-Allow-Credentials","true"),n.exposeHeaders?.length&&l("Access-Control-Expose-Headers",n.exposeHeaders.join(",")),o.req.method==="OPTIONS"){n.origin!=="*"&&l("Vary","Origin"),n.maxAge!=null&&l("Access-Control-Max-Age",n.maxAge.toString());let f=await s(o.req.header("origin")||"",o);f.length&&l("Access-Control-Allow-Methods",f.join(","));let u=n.allowHeaders;if(!u?.length){let d=o.req.header("Access-Control-Request-Headers");d&&(u=d.split(/\s*,\s*/));}return u?.length&&(l("Access-Control-Allow-Headers",u.join(",")),o.res.headers.append("Vary","Access-Control-Request-Headers")),o.res.headers.delete("Content-Length"),o.res.headers.delete("Content-Type"),new Response(null,{headers:o.res.headers,status:204,statusText:"No Content"})}await a(),n.origin!=="*"&&o.header("Vary","Origin",{append:true});}};var kn=Symbol("lite-internal-request"),Ff=Symbol("lite-peer-address");var Vb=["/rest/v1","/storage/v1"],Qb=new Set(["localhost","127.0.0.1","::1","[::1]"]);function Yb(t){let e=t.trim().toLowerCase();if(e.startsWith("[")){let r=e.indexOf("]");return r===-1?e:e.slice(0,r+1)}let n=e.indexOf(":");return n===-1?e:e.slice(0,n)}function Xb(t){let e=t.trim().toLowerCase();return e.startsWith("[")&&e.endsWith("]")&&(e=e.slice(1,-1)),e=e.split("%")[0],e==="::1"?true:(e.startsWith("::ffff:")&&(e=e.slice(7)),e==="localhost"||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(e))}function Zb(t){let e=t.req.header("Origin");if(!e)return true;try{return new URL(e).origin.toLowerCase()===new URL(t.req.url).origin.toLowerCase()}catch{return false}}function ew(t){let e=t.req.header("Host")??new URL(t.req.url).host;if(!Qb.has(Yb(e)))return false;let n=t.req.raw[Ff];return typeof n=="string"&&n.length>0?Xb(n):true}function tw(t){return t.req.header("apikey")!==void 0||t.req.query("apikey")!==void 0||t.req.header("Authorization")!==void 0}function va(t){return Zb(t)&&ew(t)}function nw(t){return t.req.method==="OPTIONS"||!Vb.some(e=>t.req.path.startsWith(e))||tw(t)?false:va(t)}function Uf(t){return async(e,n)=>nw(e)?(e.set("admin",true),e.set("apiKeyType","secret"),e.set("ignoreAuthorization",true),e.set("jwt",{role:"service_role"}),n()):t(e,n)}var qf=t=>JSON.parse(jsonStringify(t)),Mf="[redacted]";function Bf(t){let e=qf(t);return e?.auth&&typeof e.auth=="object"&&("secret_key"in e.auth&&(e.auth.secret_key=Mf),"jwt_secret"in e.auth&&(e.auth.jwt_secret=Mf)),e}var Hf=new _e().get("/ping",t=>t.json({message:"pong"})).get("/config",t=>t.json(Bf(t.var.app.config))).get("/info",t=>t.json({connection:qf(t.var.app.connection.config),config:Bf(t.var.app.config),admin:t.var.app.adminMode&&va(t)})).get("/introspect",async t=>{let e=await t.var.app.connection.introspect();return t.json(e)});var ve=class extends Error{code;details;hint;httpStatus;constructor(e){super(e.message),this.name="EmbedError",this.code=e.code,this.details=e.details,this.hint=e.hint,this.httpStatus=e.httpStatus;}},He=class extends Error{constructor(n,r=n){super(n);this.details=r;this.name="SelectParseError";}},jt=class extends Error{constructor(n,r=n){super(n);this.details=r;this.name="QueryParamParseError";}},vn=class extends Error{constructor(n="Invalid path specified in request URL",r=null){super(n);this.details=r;this.name="RouteValidationError";}},An=class extends Error{constructor(n){super(`invalid input syntax for type integer: "${n}"`);this.rawValue=n;this.name="SqliteIntegerCastError";}code="22P02"},fe=class extends Error{constructor(n,r,s){super(n);this.details=r;this.position=s;this.name="OrderParseError";}};var sw="/rest/v1";function Aa(t,e=sw){let n=new URL(t.url),r=decodeURIComponent(n.pathname);r.startsWith(e)&&(r=r.slice(e.length)),r=r.replace(/^\/+|\/+$/g,"");let s=r.split("/");if(s[0]==="rpc"&&s[1])return {function:s[1],isRpc:true};if(s.length>1)throw new vn;return {from:s[0]||void 0,isRpc:false}}function Oa(t){let e=t.method.toUpperCase(),n;e==="GET"||e==="HEAD"?n=t.headers.get("Accept-Profile")??void 0:n=t.headers.get("Content-Profile")??void 0;let r=[],s=[],i=t.headers.get("Prefer");i&&s.push(i);for(let a of s){let l=a.split(",").map(c=>c.trim()).filter(Boolean);for(let c of l){let f=c.indexOf("=");if(f===-1)continue;let u=c.slice(0,f).trim(),d=c.slice(f+1).trim();u==="max-affected"?r.push({key:"max-affected",value:Number(d)}):r.push({key:u,value:d});}}let o=t.headers.get("Accept")??"application/json";return {schema:n,preferTokens:r,accept:o}}var Wf=new Set(["count","sum","avg","min","max"]);function W(t){return t.input[t.pos]??""}function q(t,e=1){t.pos+=e;}function Oe(t){return t.pos>=t.input.length}function Ae(t,e){return t.input.startsWith(e,t.pos)}function $a(t){return /^[a-zA-Z0-9_]$/.test(t)}function z(t){for(;!Oe(t)&&/\s/.test(W(t));)q(t);}function Na(t){let n=new URL(t.url).searchParams.get("select");if(n==null)return {select:[],join:{},embeddedAliases:new Set};if(n==="")return {select:[],join:{},embeddedAliases:new Set};if(n.trim()==="")throw new He("failed to parse select parameter");let r={},s=new Set;try{let i={input:n,pos:0},o=zf(i,r,s);if(z(i),iw(i),!Oe(i))throw new Error(`Unexpected input at position ${i.pos}: "${i.input.slice(i.pos)}"`);return {select:o,join:r,embeddedAliases:s}}catch(i){if(ow(n))return {select:[],join:{},embeddedAliases:new Set};throw i}}function iw(t){let e=t.pos-1;for(;e>=0&&/\s/.test(t.input[e]??"");)e--;if(t.input[e]!==")")return;let n=t.pos;for(;W(t)==="'";)q(t);t.pos!==n&&z(t);}function ow(t){if(/^\s/.test(t))return false;let e=t.trimStart();if(e==="")return false;if(aw(e)||e.startsWith("::")||e.startsWith("->"))return true;let n=e[0]??"";return new Set([".",":","!","@","#","%","`","[","-","(","'","~"]).has(n)}function aw(t){return t.startsWith("...")?!/^\.{3}\s*(?:"[^"]+"|[a-zA-Z_][a-zA-Z0-9_$ -]*)\s*(?:![a-zA-Z_][a-zA-Z0-9_]*)*\s*\(/.test(t):false}function zf(t,e,n){let r=[];if(z(t),Oe(t)||W(t)===")"||W(t)===","&&(q(t),z(t),Oe(t)||W(t)===")"))return r;for(r.push(Kf(t,e,n));!Oe(t)&&(z(t),W(t)===",");)q(t),z(t),r.push(Kf(t,e,n));return r}function Kf(t,e,n){if(z(t),W(t)==="*")return q(t),fw(t),Ae(t,".count()")&&q(t,8),"*";if(Ae(t,"..."))return q(t,3),z(t),lw(t,e,n);let r=Xe(t,{allowSpaces:true,allowDollar:true});return z(t),Ae(t,"::")?Ia(r,void 0,t,e,n):W(t)===":"?(q(t),z(t),cw(r,t,e,n)):Ia(r,void 0,t,e,n)}function lw(t,e,n){let r=Xe(t);z(t);let{hint:s,innerJoin:i}=Vf(t);if(z(t),W(t)!=="(")throw new Error(`Expected "(" for spread embed at position ${t.pos}`);let{subSelect:o,subJoin:a}=Qf(t),l=r,c={};i&&(c.type="inner"),s&&(c.hint=s),e[l]=c,n.add(l);let f={spread:true,select:o};return Object.keys(a).length>0&&(f.join=a),{[l]:f}}function cw(t,e,n,r){let s=Xe(e,{allowSpaces:true,allowDollar:true});return z(e),Ia(s,t,e,n,r)}function Ia(t,e,n,r,s){return z(n),t==="count"&&(Oe(n)||W(n)===","||W(n)===")"||W(n)==="("||Ae(n,"::"))?pw(e,n):W(n)==="!"||W(n)==="("?uw(t,e,n,r,s):mw(t,e,n)}function uw(t,e,n,r,s){let{hint:i,innerJoin:o}=Vf(n);if(z(n),W(n)!=="(")throw new He("failed to parse select parameter");let{subSelect:a,subJoin:l}=Qf(n),c=e??t,f={};e&&(f.from=t),o&&(f.type="inner"),i&&(f.hint=i),r[c]=f,s.add(c),e&&t!==c&&s.add(t);let u={select:a};return Object.keys(l).length>0&&(u.join=l),{[c]:u}}function Vf(t){if(z(t),W(t)!=="!")return {};q(t);let e=Xe(t);if(e==="inner")return {innerJoin:true};if(e==="left")return {};let n=e;if(z(t),W(t)==="!"){q(t);let r=Xe(t);if(r==="inner")return {hint:n,innerJoin:true};if(r==="left")return {hint:n};throw new Error(`Expected "inner" or "left" after hint, got "${r}" at position ${t.pos}`)}return {hint:n}}function fw(t){for(;W(t)==="*";)q(t);for(;W(t)==="!";){let e=t.pos;if(q(t),!dw(t)){t.pos=e;return}}}function dw(t){let e=t.pos;try{return Xe(t),!0}catch{return t.pos=e,false}}function Qf(t,e,n){if(W(t)!=="(")throw new Error(`Expected "(" at position ${t.pos}`);q(t),z(t);let r={},s=new Set;if(W(t)===")")return q(t),{subSelect:[],subJoin:r};let i=zf(t,r,s);if(z(t),W(t)!==")")throw new Error(`Expected ")" at position ${t.pos}`);return q(t),{subSelect:i,subJoin:r}}function pw(t,e){z(e);let n=true;if(W(e)==="("){n=false,q(e);let o=e.pos;for(;!Oe(e)&&W(e)!==")";)q(e);if(Oe(e))throw new He("expected closing paren for count()");let a=e.input.slice(o,e.pos).trim();if(q(e),a!=="")throw new He("expected null arg for count()")}z(e);let r;Ae(e,"::")&&(q(e,2),r=kr(e));let s=t??"count",i={aggregate:"count"};return n&&(i.bareCount=true),r&&(i.cast=r),{[s]:i}}function mw(t,e,n){z(n);let r,s,i=false,o;if(Ae(n,"->")){let{path:f,lastProp:u,lastIsText:d,invalidTextTraversalKey:p}=hw(n);r=f,s=u||void 0,i=d,o=p;}z(n);let a,l;if(Ae(n,"::")){q(n,2);let f=kr(n);if(z(n),W(n)==="."&&!Oe(n)){let u=n.input[n.pos+1]??"";if($a(u)){let d=n.pos;q(n);let p=Xe(n);if(Wf.has(p)&&Ae(n,"()"))return a=f,q(n,2),z(n),Ae(n,"::")&&(q(n,2),l=kr(n),Pa(n)),Jf(t,e,r,s,i,o,a,p,l);n.pos=d;}}l=f,Pa(n);}let c;if(W(n)==="."&&!Oe(n)){let f=n.input[n.pos+1]??"";if($a(f)){let u=n.pos;q(n);let d=Xe(n);Wf.has(d)&&Ae(n,"()")?(c=d,q(n,2),z(n),Ae(n,"::")&&(q(n,2),l=kr(n),Pa(n))):n.pos=u;}}return Jf(t,e,r,s,i,o,a,c,l)}function Pa(t){for(z(t);Ae(t,"::");)q(t,2),kr(t),z(t);}function kr(t){z(t);let e=[Xe(t)];for(;!Oe(t);){let n=t.pos;if(z(t),t.pos===n)break;let r=W(t);if(!(r==='"'||/^[a-zA-Z0-9_]$/.test(r))){t.pos=n;break}e.push(Xe(t));}return e.join(" ")}function Jf(t,e,n,r,s,i,o,a,l){let c=e??(a||void 0)??r;if(!c&&!o&&!l&&!a&&!n)return t;let f=c??t,u={};return t!==f&&(u.column=t),a&&!u.column&&t===f&&(u.column=t),n&&(u.column||(u.column=t),u.path=n,s&&(u.pathText=true),i&&(u.invalidJsonTextTraversalKey=i)),o&&(u.preCast=o),a&&(u.aggregate=a),l&&(u.cast=l),{[f]:u}}function hw(t){let e=[],n="",r=false,s;for(;Ae(t,"->");){let o=r;q(t,2);let a=false;W(t)===">"&&(q(t),a=true);let l=gw(t);e.push(l),o&&s===void 0&&(s=l),/^-?\d+$/.test(l)||(n=l),r=a;}return {path:"$."+e.join("."),lastProp:n,lastIsText:r,invalidTextTraversalKey:s}}function gw(t){return yw(t)}var Gf=new Set(["(",".",">","<"]);function Cr(t,e,n){throw new He(`"failed to parse select parameter (${t.input})" (line 1, column ${e})`,n)}function yw(t){z(t);let e=t.pos;if(W(t)==='"')return Xe(t);let n="";for(;!Oe(t)&&!(Ae(t,"->")||Ae(t,"::"));){let s=W(t);if(s===","||s==="."||s===":"||/\s/.test(s))break;n+=s,q(t);}n===""&&Cr(t,e+1,"unexpected end of input");let r=n[0]??"";Gf.has(r)&&Cr(t,e+1,`unexpected "${r}" expecting "-", digit or any non reserved character different from: .,>()`);for(let s=1;s<n.length;s++){let i=n[s];Gf.has(i)&&Cr(t,e+s+1,`unexpected "${i}" expecting "-", digit or any non reserved character different from: .,>()`);}if(n.includes("--")){let s=n.indexOf("--"),i=s===0&&n.length>1?e+2:e+s+1;Cr(t,i,'unexpected "-" expecting digit');}if(n.endsWith("-")&&Cr(t,e+n.length,'unexpected "-" expecting digit'),/^-\d+\D/.test(n))throw new He("failed to parse select parameter");return n}function Xe(t,e={}){if(z(t),W(t)==='"'){q(t);let r="";for(;!Oe(t)&&W(t)!=='"';)r+=W(t),q(t);if(Oe(t))throw new Error(`Missing closing quote at position ${t.pos}`);return q(t),r}let n="";for(;!Oe(t);){let r=W(t);if($a(r))n+=r,q(t);else if(e.allowDollar&&r==="$")n+=r,q(t);else if(e.allowSpaces&&r===" ")n+=r,q(t);else if(r==="-"&&n.length>0){if((t.input[t.pos+1]??"")===">")break;n+=r,q(t);}else break}if(e.allowSpaces&&(n=n.trimEnd()),n==="")throw new Error(`Expected identifier at position ${t.pos}`);if(n.includes("--")||n.endsWith("-"))throw new He("failed to parse select parameter");return n}var bw=new Set(["application/json","text/csv","application/x-www-form-urlencoded"]);function ww(t){return t.split(";")[0]?.trim().toLowerCase()??""}var vr=class extends Error{mediaType;constructor(e){super(`Content-Type not acceptable: ${e}`),this.name="ContentTypeNotAcceptableError",this.mediaType=e;}};async function Da(t){let e=t.method.toUpperCase();if(e==="GET"||e==="HEAD")return {};let n=await t.text(),r=t.headers.get("Content-Type")??"",s=ww(r);if(!n&&r.includes("text/csv"))throw new On('parse error (not enough input) at ""');if(!n)return {};if(s&&!bw.has(s))throw new vr(s);if(r.includes("application/json")||s===""||s==="application/json")try{let i=JSON.parse(n);return Array.isArray(i)?{values:i}:{values:i}}catch{throw new Error(`Invalid JSON body: ${n.slice(0,100)}`)}if(r.includes("text/csv"))return {values:Sw(n)};if(r.includes("application/x-www-form-urlencoded")){let i=new URLSearchParams(n),o={};for(let[a,l]of i)o[a]=l;return {values:o}}return {raw:n}}function Sw(t){let e=t.replace(/\r\n/g,`
75
+ `,tags:ai,links:oi})}).partial();var jb=[{name:"Supabase Realtime",link:"https://supabase.com/docs/guides/realtime"}],ba=["realtime"],yf=s.strictObject({enabled:s.boolean({default:true,description:"Enable the local Realtime service.",tags:ba,links:jb}),ip_version:s.string({enum:["IPv4","IPv6"],default:"IPv4",description:"Bind realtime via either IPv4 or IPv6.",tags:ba,links:[{name:"Supabase Realtime Configuration",link:"https://supabase.com/docs/guides/realtime/self-hosting"}]}),max_header_length:s.number({default:4096,description:"Maximum length of the HTTP header.",tags:ba})}).partial();var ci=[{name:"Storage server configuration",link:"https://supabase.com/docs/guides/self-hosting/storage/config"}],Dt=["storage"],Lb=s.strictObject({public:s.boolean({default:false,description:"Enable public access to the bucket."}),file_size_limit:s.string({default:"50MiB",description:"The maximum file size allowed for the bucket.",examples:["5MB","500KB"],tags:Dt,links:ci}),allowed_mime_types:s.array(s.string({description:"A MIME type allowed for the bucket.",tags:Dt}),{examples:[["image/png","image/jpeg"]],description:"The list of allowed MIME types for the bucket.",tags:Dt}),objects_path:s.string({description:"The path to the objects in the bucket.",tags:Dt})}).partial(),bf=s.strictObject({enabled:s.boolean({default:true,description:"Enable the local Storage service.",tags:Dt,links:ci}),file_size_limit:s.string({default:"50MiB",description:"The maximum file size allowed.",examples:["5MB","500KB"],tags:Dt,links:ci}),image_transformation:s.strictObject({enabled:s.boolean({default:true,description:"Enable image transformation.",tags:Dt,links:ci})}).partial(),buckets:s.record(Lb,{description:"Storage buckets configuration.",tags:Dt})}).partial();var wa={studio:{name:"Supabase Studio",link:"https://supabase.com/docs/guides/studio"},config:{name:"Supabase Studio Configuration",link:"https://supabase.com/docs/guides/self-hosting/studio"}},fi=["studio"],wf=s.strictObject({enabled:s.boolean({default:true,description:"Enable the local Supabase Studio dashboard.",tags:fi,links:[wa.studio]}),port:s.number({default:54323,description:"Port to use for Supabase Studio.",tags:fi}),api_url:s.string({default:"http://localhost",description:"External URL of the API server that frontend connects to.",tags:fi,links:[wa.config]}),openai_api_key:gt({default:"env(OPENAI_API_KEY)",description:"OpenAI API key to use for Supabase AI in the Supabase Studio.",tags:fi,links:[wa.config]})}).partial();var pi=yt.strictObject({project_id:yt.string({description:"A string used to distinguish different Supabase projects on the same host. Defaults to the working directory name when running `supabase init`.",tags:["general"]}),analytics:Zu,api:ef,auth:uf,db:ff,edge_runtime:df,functions:hf,inbucket:gf,realtime:yf,storage:bf,studio:wf,experimental:mf}).partial();var Sa=(t,e,n)=>(r,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,f;if(t[a]?(f=t[a][0][0],r.req.routeIndex=a):f=a===t.length&&s||void 0,f)try{l=await f(r,()=>o(a+1));}catch(u){if(u instanceof Error&&e)r.error=u,l=await e(u,r),c=true;else throw u}else r.finalized===false&&n&&(l=await n(r));return l&&(r.finalized===false||c)&&(r.res=l),r}};var mi=Symbol();var Sf=async(t,e=Object.create(null))=>{let{all:n=false,dot:r=false}=e,i=(t instanceof hi?t.raw.headers:t.headers).get("Content-Type");return i?.startsWith("multipart/form-data")||i?.startsWith("application/x-www-form-urlencoded")?Fb(t,{all:n,dot:r}):{}};async function Fb(t,e){let n=await t.formData();return n?Ub(n,e):{}}function Ub(t,e){let n=Object.create(null);return t.forEach((r,s)=>{e.all||s.endsWith("[]")?Mb(n,s,r):n[s]=r;}),e.dot&&Object.entries(n).forEach(([r,s])=>{r.includes(".")&&(Bb(n,r,s),delete n[r]);}),n}var Mb=(t,e,n)=>{t[e]!==void 0?Array.isArray(t[e])?t[e].push(n):t[e]=[t[e],n]:e.endsWith("[]")?t[e]=[n]:t[e]=n;},Bb=(t,e,n)=>{let r=t,s=e.split(".");s.forEach((i,o)=>{o===s.length-1?r[i]=n:((!r[i]||typeof r[i]!="object"||Array.isArray(r[i])||r[i]instanceof File)&&(r[i]=Object.create(null)),r=r[i]);});};var Ea=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},yi=t=>{let{groups:e,path:n}=qb(t),r=Ea(n);return Hb(r,e)},qb=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(n,r)=>{let s=`@${r}`;return e.push([s,n]),s}),{groups:e,path:t}},Hb=(t,e)=>{for(let n=e.length-1;n>=0;n--){let[r]=e[n];for(let s=t.length-1;s>=0;s--)if(t[s].includes(r)){t[s]=t[s].replace(r,e[n][1]);break}}return t},gi={},bi=(t,e)=>{if(t==="*")return "*";let n=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${t}#${e}`;return gi[r]||(n[2]?gi[r]=e&&e[0]!==":"&&e[0]!=="*"?[r,n[1],new RegExp(`^${n[2]}(?=/${e})`)]:[t,n[1],new RegExp(`^${n[2]}$`)]:gi[r]=[t,n[1],true]),gi[r]}return null},wi=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,n=>{try{return e(n)}catch{return n}})}},Wb=t=>wi(t,decodeURI),xa=t=>{let e=t.url,n=e.indexOf("/",e.indexOf(":")+4),r=n;for(;r<e.length;r++){let s=e.charCodeAt(r);if(s===37){let i=e.indexOf("?",r),o=e.indexOf("#",r),a=i===-1?o===-1?void 0:o:o===-1?i:Math.min(i,o),l=e.slice(n,a);return Wb(l.includes("%25")?l.replace(/%25/g,"%2525"):l)}else if(s===63||s===35)break}return e.slice(n,r)};var _f=t=>{let e=xa(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},Zt=(t,e,...n)=>(n.length&&(e=Zt(e,...n)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),Si=t=>{if(t.charCodeAt(t.length-1)!==63||!t.includes(":"))return null;let e=t.split("/"),n=[],r="";return e.forEach(s=>{if(s!==""&&!/\:/.test(s))r+="/"+s;else if(/\:/.test(s))if(/\?/.test(s)){n.length===0&&r===""?n.push("/"):n.push(r);let i=s.replace("?","");r+="/"+i,n.push(r);}else r+="/"+s;}),n.filter((s,i,o)=>o.indexOf(s)===i)},_a=t=>/[%+]/.test(t)?(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),t.indexOf("%")!==-1?wi(t,Ta):t):t,Ef=(t,e,n)=>{let r;if(!n&&e&&!/[%+]/.test(e)){let o=t.indexOf("?",8);if(o===-1)return;for(t.startsWith(e,o+1)||(o=t.indexOf(`&${e}`,o+1));o!==-1;){let a=t.charCodeAt(o+e.length+1);if(a===61){let l=o+e.length+2,c=t.indexOf("&",l);return _a(t.slice(l,c===-1?void 0:c))}else if(a==38||isNaN(a))return "";o=t.indexOf(`&${e}`,o+1);}if(r=/[%+]/.test(t),!r)return}let s={};r??=/[%+]/.test(t);let i=t.indexOf("?",8);for(;i!==-1;){let o=t.indexOf("&",i+1),a=t.indexOf("=",i);a>o&&o!==-1&&(a=-1);let l=t.slice(i+1,a===-1?o===-1?void 0:o:a);if(r&&(l=_a(l)),i=o,l==="")continue;let c;a===-1?c="":(c=t.slice(a+1,o===-1?void 0:o),r&&(c=_a(c))),n?(s[l]&&Array.isArray(s[l])||(s[l]=[]),s[l].push(c)):s[l]??=c;}return e?s[e]:s},xf=Ef,Tf=(t,e)=>Ef(t,e,true),Ta=decodeURIComponent;var Rf=t=>wi(t,Ta),hi=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(t,e="/",n=[[]]){this.raw=t,this.path=e,this.#e=n,this.#t={};}param(t){return t?this.#n(t):this.#i()}#n(t){let e=this.#e[0][this.routeIndex][1][t],n=this.#r(e);return n&&/\%/.test(n)?Rf(n):n}#i(){let t={},e=Object.keys(this.#e[0][this.routeIndex][1]);for(let n of e){let r=this.#r(this.#e[0][this.routeIndex][1][n]);r!==void 0&&(t[n]=/\%/.test(r)?Rf(r):r);}return t}#r(t){return this.#e[1]?this.#e[1][t]:t}query(t){return xf(this.url,t)}queries(t){return Tf(this.url,t)}header(t){if(t)return this.raw.headers.get(t)??void 0;let e={};return this.raw.headers.forEach((n,r)=>{e[r]=n;}),e}async parseBody(t){return this.bodyCache.parsedBody??=await Sf(this,t)}#s=t=>{let{bodyCache:e,raw:n}=this,r=e[t];if(r)return r;let s=Object.keys(e)[0];return s?e[s].then(i=>(s==="json"&&(i=JSON.stringify(i)),new Response(i)[t]())):e[t]=n[t]()};json(){return this.#s("text").then(t=>JSON.parse(t))}text(){return this.#s("text")}arrayBuffer(){return this.#s("arrayBuffer")}blob(){return this.#s("blob")}formData(){return this.#s("formData")}addValidatedData(t,e){this.#t[t]=e;}valid(t){return this.#t[t]}get url(){return this.raw.url}get method(){return this.raw.method}get[mi](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,t]])=>t)}get routePath(){return this.#e[0].map(([[,t]])=>t)[this.routeIndex].path}};var Xe={Stringify:1},Y=(t,e)=>{let n=new String(t);return n.isEscaped=true,n.callbacks=e,n},Kb=/[&<>'"]/,_i=async(t,e)=>{let n="";e||=[];let r=await Promise.all(t);for(let s=r.length-1;n+=r[s],s--,!(s<0);s--){let i=r[s];typeof i=="object"&&e.push(...i.callbacks||[]);let o=i.isEscaped;if(i=await(typeof i=="object"?i.toString():i),typeof i=="object"&&e.push(...i.callbacks||[]),i.isEscaped??o)n+=i;else {let a=[n];bt(i,a),n=a[0];}}return Y(n,e)},bt=(t,e)=>{let n=t.search(Kb);if(n===-1){e[0]+=t;return}let r,s,i=0;for(s=n;s<t.length;s++){switch(t.charCodeAt(s)){case 34:r="&quot;";break;case 39:r="&#39;";break;case 38:r="&amp;";break;case 60:r="&lt;";break;case 62:r="&gt;";break;default:continue}e[0]+=t.substring(i,s)+r,i=s+1;}e[0]+=t.substring(i,s);},Ra=t=>{let e=t.callbacks;if(!e?.length)return t;let n=[t],r={};return e.forEach(s=>s({phase:Xe.Stringify,buffer:n,context:r})),n[0]},en=async(t,e,n,r,s)=>{typeof t=="object"&&!(t instanceof String)&&(t instanceof Promise||(t=t.toString()),t instanceof Promise&&(t=await t));let i=t.callbacks;if(!i?.length)return Promise.resolve(t);s?s[0]+=t:s=[t];let o=Promise.all(i.map(a=>a({phase:e,buffer:s,context:r}))).then(a=>Promise.all(a.filter(Boolean).map(l=>en(l,e,false,r,s))).then(()=>s[0]));return n?Y(await o,i):o};var Jb="text/plain; charset=UTF-8",Ca=(t,e)=>({"Content-Type":t,...e}),Er=(t,e)=>new Response(t,e),Cf=class{#t;#e;env={};#n;finalized=false;error;#i;#r;#s;#u;#l;#c;#a;#f;#d;constructor(t,e){this.#t=t,e&&(this.#r=e.executionCtx,this.env=e.env,this.#c=e.notFoundHandler,this.#d=e.path,this.#f=e.matchResult);}get req(){return this.#e??=new hi(this.#t,this.#d,this.#f),this.#e}get event(){if(this.#r&&"respondWith"in this.#r)return this.#r;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#r)return this.#r;throw Error("This context has no ExecutionContext")}get res(){return this.#s||=Er(null,{headers:this.#a??=new Headers})}set res(t){if(this.#s&&t){t=Er(t.body,t);for(let[e,n]of this.#s.headers.entries())if(e!=="content-type")if(e==="set-cookie"){let r=this.#s.headers.getSetCookie();t.headers.delete("set-cookie");for(let s of r)t.headers.append("set-cookie",s);}else t.headers.set(e,n);}this.#s=t,this.finalized=true;}render=(...t)=>(this.#l??=e=>this.html(e),this.#l(...t));setLayout=t=>this.#u=t;getLayout=()=>this.#u;setRenderer=t=>{this.#l=t;};header=(t,e,n)=>{this.finalized&&(this.#s=Er(this.#s.body,this.#s));let r=this.#s?this.#s.headers:this.#a??=new Headers;e===void 0?r.delete(t):n?.append?r.append(t,e):r.set(t,e);};status=t=>{this.#i=t;};set=(t,e)=>{this.#n??=new Map,this.#n.set(t,e);};get=t=>this.#n?this.#n.get(t):void 0;get var(){return this.#n?Object.fromEntries(this.#n):{}}#o(t,e,n){let r=this.#s?new Headers(this.#s.headers):this.#a??new Headers;if(typeof e=="object"&&"headers"in e){let i=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(let[o,a]of i)o.toLowerCase()==="set-cookie"?r.append(o,a):r.set(o,a);}if(n)for(let[i,o]of Object.entries(n))if(typeof o=="string")r.set(i,o);else {r.delete(i);for(let a of o)r.append(i,a);}let s=typeof e=="number"?e:e?.status??this.#i;return Er(t,{status:s,headers:r})}newResponse=(...t)=>this.#o(...t);body=(t,e,n)=>this.#o(t,e,n);text=(t,e,n)=>!this.#a&&!this.#i&&!e&&!n&&!this.finalized?new Response(t):this.#o(t,e,Ca(Jb,n));json=(t,e,n)=>this.#o(JSON.stringify(t),e,Ca("application/json",n));html=(t,e,n)=>{let r=s=>this.#o(s,e,Ca("text/html; charset=UTF-8",n));return typeof t=="object"?en(t,Xe.Stringify,false,{}).then(r):r(t)};redirect=(t,e)=>{let n=String(t);return this.header("Location",/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,e??302)};notFound=()=>(this.#c??=()=>Er(),this.#c(this))};var ne="ALL",kf="all",vf=["get","post","put","delete","options","patch"],Ei="Can not add a route since the matcher is already built.",xi=class extends Error{};var Af="__COMPOSED_HANDLER";var Gb=t=>t.text("404 Not Found",404),Of=(t,e)=>{if("getResponse"in t){let n=t.getResponse();return e.newResponse(n.body,n)}return console.error(t),e.text("Internal Server Error",500)},Pf=class $f{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(e={}){[...vf,kf].forEach(i=>{this[i]=(o,...a)=>(typeof o=="string"?this.#t=o:this.#i(i,this.#t,o),a.forEach(l=>{this.#i(i,this.#t,l);}),this);}),this.on=(i,o,...a)=>{for(let l of [o].flat()){this.#t=l;for(let c of [i].flat())a.map(f=>{this.#i(c.toUpperCase(),this.#t,f);});}return this},this.use=(i,...o)=>(typeof i=="string"?this.#t=i:(this.#t="*",o.unshift(i)),o.forEach(a=>{this.#i(ne,this.#t,a);}),this);let{strict:r,...s}=e;Object.assign(this,s),this.getPath=r??true?e.getPath??xa:_f;}#e(){let e=new $f({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#n=this.#n,e.routes=this.routes,e}#n=Gb;errorHandler=Of;route(e,n){let r=this.basePath(e);return n.routes.map(s=>{let i;n.errorHandler===Of?i=s.handler:(i=async(o,a)=>(await Sa([],n.errorHandler)(o,()=>s.handler(o,a))).res,i[Af]=s.handler),r.#i(s.method,s.path,i);}),this}basePath(e){let n=this.#e();return n._basePath=Zt(this._basePath,e),n}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#n=e,this);mount(e,n,r){let s,i;r&&(typeof r=="function"?i=r:(i=r.optionHandler,r.replaceRequest===false?s=l=>l:s=r.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=Zt(this._basePath,e),c=l==="/"?0:l.length;return f=>{let u=new URL(f.url);return u.pathname=u.pathname.slice(c)||"/",new Request(u,f)}})();let a=async(l,c)=>{let f=await n(s(l.req.raw),...o(l));if(f)return f;await c();};return this.#i(ne,Zt(e,"*"),a),this}#i(e,n,r){e=e.toUpperCase(),n=Zt(this._basePath,n);let s={basePath:this._basePath,path:n,method:e,handler:r};this.router.add(e,n,[r,s]),this.routes.push(s);}#r(e,n){if(e instanceof Error)return this.errorHandler(e,n);throw e}#s(e,n,r,s){if(s==="HEAD")return (async()=>new Response(null,await this.#s(e,n,r,"GET")))();let i=this.getPath(e,{env:r}),o=this.router.match(s,i),a=new Cf(e,{path:i,matchResult:o,env:r,executionCtx:n,notFoundHandler:this.#n});if(o[0].length===1){let c;try{c=o[0][0][0][0](a,async()=>{a.res=await this.#n(a);});}catch(f){return this.#r(f,a)}return c instanceof Promise?c.then(f=>f||(a.finalized?a.res:this.#n(a))).catch(f=>this.#r(f,a)):c??this.#n(a)}let l=Sa(o[0],this.errorHandler,this.#n);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.#r(c,a)}})()}fetch=(e,...n)=>this.#s(e,n[1],n[0],e.method);request=(e,n,r,s)=>e instanceof Request?this.fetch(n?new Request(e,n):e,r,s):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${Zt("/",e)}`,n),r,s));fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.#s(e.request,e,void 0,e.request.method));});}};var Ti=[];function ka(t,e){let n=this.buildAllMatchers(),r=((s,i)=>{let o=n[s]||n[ne],a=o[2][i];if(a)return a;let l=i.match(o[0]);if(!l)return [[],Ti];let c=l.indexOf("",1);return [o[1][c],l]});return this.match=r,r(t,e)}var Ri="[^/]+",xr=".*",Tr="(?:|/.*)",tn=Symbol(),zb=new Set(".\\+*[^]$()");function Vb(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1||t===xr||t===Tr?1:e===xr||e===Tr?-1:t===Ri?1:e===Ri?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var If=class va{#t;#e;#n=Object.create(null);insert(e,n,r,s,i){if(e.length===0){if(this.#t!==void 0)throw tn;if(i)return;this.#t=n;return}let[o,...a]=e,l=o==="*"?a.length===0?["","",xr]:["","",Ri]:o==="/*"?["","",Tr]:o.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(l){let f=l[1],u=l[2]||Ri;if(f&&l[2]&&(u===".*"||(u=u.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(u))))throw tn;if(c=this.#n[u],!c){if(Object.keys(this.#n).some(d=>d!==xr&&d!==Tr))throw tn;if(i)return;c=this.#n[u]=new va,f!==""&&(c.#e=s.varIndex++);}!i&&f!==""&&r.push([f,c.#e]);}else if(c=this.#n[o],!c){if(Object.keys(this.#n).some(f=>f.length>1&&f!==xr&&f!==Tr))throw tn;if(i)return;c=this.#n[o]=new va;}c.insert(a,n,r,s,i);}buildRegExpStr(){let n=Object.keys(this.#n).sort(Vb).map(r=>{let s=this.#n[r];return (typeof s.#e=="number"?`(${r})@${s.#e}`:zb.has(r)?`\\${r}`:r)+s.buildRegExpStr()});return typeof this.#t=="number"&&n.unshift(`#${this.#t}`),n.length===0?"":n.length===1?n[0]:"(?:"+n.join("|")+")"}};var Nf=class{#t={varIndex:0};#e=new If;insert(t,e,n){let r=[],s=[];for(let o=0;;){let a=false;if(t=t.replace(/\{[^}]+\}/g,l=>{let c=`@\\${o}`;return s[o]=[c,l],o++,a=true,c}),!a)break}let i=t.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.#e.insert(i,e,r,this.#t,n),r}buildRegExp(){let t=this.#e.buildRegExpStr();if(t==="")return [/^$/,[],[]];let e=0,n=[],r=[];return t=t.replace(/#(\d+)|@(\d+)|\.\*\$/g,(s,i,o)=>i!==void 0?(n[++e]=Number(i),"$()"):(o!==void 0&&(r[Number(o)]=++e),"")),[new RegExp(`^${t}`),n,r]}};var Qb=[/^$/,[],Object.create(null)],Df=Object.create(null);function jf(t){return Df[t]??=new RegExp(t==="*"?"":`^${t.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,n)=>n?`\\${n}`:"(?:|/.*)")}$`)}function Xb(){Df=Object.create(null);}function Yb(t){let e=new Nf,n=[];if(t.length===0)return Qb;let r=t.map(c=>[!/\*|\/:/.test(c[0]),...c]).sort(([c,f],[u,d])=>c?1:u?-1:f.length-d.length),s=Object.create(null);for(let c=0,f=-1,u=r.length;c<u;c++){let[d,p,g]=r[c];d?s[p]=[g.map(([h])=>[h,Object.create(null)]),Ti]:f++;let m;try{m=e.insert(p,f,d);}catch(h){throw h===tn?new xi(p):h}d||(n[f]=g.map(([h,y])=>{let w=Object.create(null);for(y-=1;y>=0;y--){let[S,b]=m[y];w[S]=b;}return [h,w]}));}let[i,o,a]=e.buildRegExp();for(let c=0,f=n.length;c<f;c++)for(let u=0,d=n[c].length;u<d;u++){let p=n[c][u]?.[1];if(!p)continue;let g=Object.keys(p);for(let m=0,h=g.length;m<h;m++)p[g[m]]=a[p[g[m]]];}let l=[];for(let c in o)l[c]=n[o[c]];return [i,l,s]}function Cn(t,e){if(t){for(let n of Object.keys(t).sort((r,s)=>s.length-r.length))if(jf(n).test(e))return [...t[n]]}}var Ci=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[ne]:Object.create(null)},this.#e={[ne]:Object.create(null)};}add(t,e,n){let r=this.#t,s=this.#e;if(!r||!s)throw new Error(Ei);r[t]||[r,s].forEach(a=>{a[t]=Object.create(null),Object.keys(a[ne]).forEach(l=>{a[t][l]=[...a[ne][l]];});}),e==="/*"&&(e="*");let i=(e.match(/\/:/g)||[]).length;if(/\*$/.test(e)){let a=jf(e);t===ne?Object.keys(r).forEach(l=>{r[l][e]||=Cn(r[l],e)||Cn(r[ne],e)||[];}):r[t][e]||=Cn(r[t],e)||Cn(r[ne],e)||[],Object.keys(r).forEach(l=>{(t===ne||t===l)&&Object.keys(r[l]).forEach(c=>{a.test(c)&&r[l][c].push([n,i]);});}),Object.keys(s).forEach(l=>{(t===ne||t===l)&&Object.keys(s[l]).forEach(c=>a.test(c)&&s[l][c].push([n,i]));});return}let o=Si(e)||[e];for(let a=0,l=o.length;a<l;a++){let c=o[a];Object.keys(s).forEach(f=>{(t===ne||t===f)&&(s[f][c]||=[...Cn(r[f],c)||Cn(r[ne],c)||[]],s[f][c].push([n,i-l+a+1]));});}}match=ka;buildAllMatchers(){let t=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#t)).forEach(e=>{t[e]||=this.#n(e);}),this.#t=this.#e=void 0,Xb(),t}#n(t){let e=[],n=t===ne;return [this.#t,this.#e].forEach(r=>{let s=r[t]?Object.keys(r[t]).map(i=>[i,r[t][i]]):[];s.length!==0?(n||=true,e.push(...s)):t!==ne&&e.push(...Object.keys(r[ne]).map(i=>[i,r[ne][i]]));}),n?Yb(e):null}};var Aa=class{name="SmartRouter";#t=[];#e=[];constructor(t){this.#t=t.routers;}add(t,e,n){if(!this.#e)throw new Error(Ei);this.#e.push([t,e,n]);}match(t,e){if(!this.#e)throw new Error("Fatal error");let n=this.#t,r=this.#e,s=n.length,i=0,o;for(;i<s;i++){let a=n[i];try{for(let l=0,c=r.length;l<c;l++)a.add(...r[l]);o=a.match(t,e);}catch(l){if(l instanceof xi)continue;throw l}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(i===s)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};var Rr=Object.create(null),Zb=t=>{for(let e in t)return true;return false},Lf=class Ff{#t;#e;#n;#i=0;#r=Rr;constructor(e,n,r){if(this.#e=r||Object.create(null),this.#t=[],e&&n){let s=Object.create(null);s[e]={handler:n,possibleKeys:[],score:0},this.#t=[s];}this.#n=[];}insert(e,n,r){this.#i=++this.#i;let s=this,i=yi(n),o=[];for(let a=0,l=i.length;a<l;a++){let c=i[a],f=i[a+1],u=bi(c,f),d=Array.isArray(u)?u[0]:c;if(d in s.#e){s=s.#e[d],u&&o.push(u[1]);continue}s.#e[d]=new Ff,u&&(s.#n.push(u),o.push(u[1])),s=s.#e[d];}return s.#t.push({[e]:{handler:r,possibleKeys:o.filter((a,l,c)=>c.indexOf(a)===l),score:this.#i}}),s}#s(e,n,r,s,i){for(let o=0,a=n.#t.length;o<a;o++){let l=n.#t[o],c=l[r]||l[ne],f={};if(c!==void 0&&(c.params=Object.create(null),e.push(c),s!==Rr||i&&i!==Rr))for(let u=0,d=c.possibleKeys.length;u<d;u++){let p=c.possibleKeys[u],g=f[c.score];c.params[p]=i?.[p]&&!g?i[p]:s[p]??i?.[p],f[c.score]=true;}}}search(e,n){let r=[];this.#r=Rr;let i=[this],o=Ea(n),a=[],l=o.length,c=null;for(let f=0;f<l;f++){let u=o[f],d=f===l-1,p=[];for(let m=0,h=i.length;m<h;m++){let y=i[m],w=y.#e[u];w&&(w.#r=y.#r,d?(w.#e["*"]&&this.#s(r,w.#e["*"],e,y.#r),this.#s(r,w,e,y.#r)):p.push(w));for(let S=0,b=y.#n.length;S<b;S++){let _=y.#n[S],E=y.#r===Rr?{}:{...y.#r};if(_==="*"){let C=y.#e["*"];C&&(this.#s(r,C,e,y.#r),C.#r=E,p.push(C));continue}let[x,O,v]=_;if(!u&&!(v instanceof RegExp))continue;let P=y.#e[x];if(v instanceof RegExp){if(c===null){c=new Array(l);let U=n[0]==="/"?1:0;for(let J=0;J<l;J++)c[J]=U,U+=o[J].length+1;}let C=n.substring(c[f]),R=v.exec(C);if(R){if(E[O]=R[0],this.#s(r,P,e,y.#r,E),Zb(P.#e)){P.#r=E;let U=R[0].match(/\//)?.length??0;(a[U]||=[]).push(P);}continue}}(v===true||v.test(u))&&(E[O]=u,d?(this.#s(r,P,e,E,y.#r),P.#e["*"]&&this.#s(r,P.#e["*"],e,E,y.#r)):(P.#r=E,p.push(P)));}}let g=a.shift();i=g?p.concat(g):p;}return r.length>1&&r.sort((f,u)=>f.score-u.score),[r.map(({handler:f,params:u})=>[f,u])]}};var Oa=class{name="TrieRouter";#t;constructor(){this.#t=new Lf;}add(t,e,n){let r=Si(e);if(r){for(let s=0,i=r.length;s<i;s++)this.#t.insert(t,r[s],n);return}this.#t.insert(t,e,n);}match(t,e){return this.#t.search(t,e)}};var _e=class extends Pf{constructor(t={}){super(t),this.router=t.router??new Aa({routers:[new Ci,new Oa]});}};var Uf=t=>{let n={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...t},r=(i=>typeof i=="string"?i==="*"?()=>i:o=>i===o?o:null:typeof i=="function"?i:o=>i.includes(o)?o:null)(n.origin),s=(i=>typeof i=="function"?i:Array.isArray(i)?()=>i:()=>[])(n.allowMethods);return async function(o,a){function l(f,u){o.res.headers.set(f,u);}let c=await r(o.req.header("origin")||"",o);if(c&&l("Access-Control-Allow-Origin",c),n.credentials&&l("Access-Control-Allow-Credentials","true"),n.exposeHeaders?.length&&l("Access-Control-Expose-Headers",n.exposeHeaders.join(",")),o.req.method==="OPTIONS"){n.origin!=="*"&&l("Vary","Origin"),n.maxAge!=null&&l("Access-Control-Max-Age",n.maxAge.toString());let f=await s(o.req.header("origin")||"",o);f.length&&l("Access-Control-Allow-Methods",f.join(","));let u=n.allowHeaders;if(!u?.length){let d=o.req.header("Access-Control-Request-Headers");d&&(u=d.split(/\s*,\s*/));}return u?.length&&(l("Access-Control-Allow-Headers",u.join(",")),o.res.headers.append("Vary","Access-Control-Request-Headers")),o.res.headers.delete("Content-Length"),o.res.headers.delete("Content-Type"),new Response(null,{headers:o.res.headers,status:204,statusText:"No Content"})}await a(),n.origin!=="*"&&o.header("Vary","Origin",{append:true});}};var kn=Symbol("lite-internal-request"),Mf=Symbol("lite-peer-address");var ew=["/rest/v1","/storage/v1"],tw=new Set(["localhost","127.0.0.1","::1","[::1]"]);function nw(t){let e=t.trim().toLowerCase();if(e.startsWith("[")){let r=e.indexOf("]");return r===-1?e:e.slice(0,r+1)}let n=e.indexOf(":");return n===-1?e:e.slice(0,n)}function rw(t){let e=t.trim().toLowerCase();return e.startsWith("[")&&e.endsWith("]")&&(e=e.slice(1,-1)),e=e.split("%")[0],e==="::1"?true:(e.startsWith("::ffff:")&&(e=e.slice(7)),e==="localhost"||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(e))}function sw(t){let e=t.req.header("Origin");if(!e)return true;try{return new URL(e).origin.toLowerCase()===new URL(t.req.url).origin.toLowerCase()}catch{return false}}function iw(t){let e=t.req.header("Host")??new URL(t.req.url).host;if(!tw.has(nw(e)))return false;let n=t.req.raw[Mf];return typeof n=="string"&&n.length>0?rw(n):true}function ow(t){return t.req.header("apikey")!==void 0||t.req.query("apikey")!==void 0||t.req.header("Authorization")!==void 0}function Pa(t){return sw(t)&&iw(t)}function aw(t){return t.req.method==="OPTIONS"||!ew.some(e=>t.req.path.startsWith(e))||ow(t)?false:Pa(t)}function Bf(t){return async(e,n)=>aw(e)?(e.set("admin",true),e.set("apiKeyType","secret"),e.set("ignoreAuthorization",true),e.set("jwt",{role:"service_role"}),n()):t(e,n)}var Wf=t=>JSON.parse(jsonStringify(t)),qf="[redacted]";function Hf(t){let e=Wf(t);return e?.auth&&typeof e.auth=="object"&&("secret_key"in e.auth&&(e.auth.secret_key=qf),"jwt_secret"in e.auth&&(e.auth.jwt_secret=qf)),e}var Kf=new _e().get("/ping",t=>t.json({message:"pong"})).get("/config",t=>t.json(Hf(t.var.app.config))).get("/info",t=>t.json({connection:Wf(t.var.app.connection.config),config:Hf(t.var.app.config),admin:t.var.app.adminMode&&Pa(t)})).get("/introspect",async t=>{let e=await t.var.app.connection.introspect();return t.json(e)});var ve=class extends Error{code;details;hint;httpStatus;constructor(e){super(e.message),this.name="EmbedError",this.code=e.code,this.details=e.details,this.hint=e.hint,this.httpStatus=e.httpStatus;}},He=class extends Error{constructor(n,r=n){super(n);this.details=r;this.name="SelectParseError";}},jt=class extends Error{constructor(n,r=n){super(n);this.details=r;this.name="QueryParamParseError";}},vn=class extends Error{constructor(n="Invalid path specified in request URL",r=null){super(n);this.details=r;this.name="RouteValidationError";}},An=class extends Error{constructor(n){super(`invalid input syntax for type integer: "${n}"`);this.rawValue=n;this.name="SqliteIntegerCastError";}code="22P02"},fe=class extends Error{constructor(n,r,s){super(n);this.details=r;this.position=s;this.name="OrderParseError";}};var cw="/rest/v1";function $a(t,e=cw){let n=new URL(t.url),r=decodeURIComponent(n.pathname);r.startsWith(e)&&(r=r.slice(e.length)),r=r.replace(/^\/+|\/+$/g,"");let s=r.split("/");if(s[0]==="rpc"&&s[1])return {function:s[1],isRpc:true};if(s.length>1)throw new vn;return {from:s[0]||void 0,isRpc:false}}function Ia(t){let e=t.method.toUpperCase(),n;e==="GET"||e==="HEAD"?n=t.headers.get("Accept-Profile")??void 0:n=t.headers.get("Content-Profile")??void 0;let r=[],s=[],i=t.headers.get("Prefer");i&&s.push(i);for(let a of s){let l=a.split(",").map(c=>c.trim()).filter(Boolean);for(let c of l){let f=c.indexOf("=");if(f===-1)continue;let u=c.slice(0,f).trim(),d=c.slice(f+1).trim();u==="max-affected"?r.push({key:"max-affected",value:Number(d)}):r.push({key:u,value:d});}}let o=t.headers.get("Accept")??"application/json";return {schema:n,preferTokens:r,accept:o}}var Jf=new Set(["count","sum","avg","min","max"]);function W(t){return t.input[t.pos]??""}function q(t,e=1){t.pos+=e;}function Oe(t){return t.pos>=t.input.length}function Ae(t,e){return t.input.startsWith(e,t.pos)}function Da(t){return /^[a-zA-Z0-9_]$/.test(t)}function z(t){for(;!Oe(t)&&/\s/.test(W(t));)q(t);}function La(t){let n=new URL(t.url).searchParams.get("select");if(n==null)return {select:[],join:{},embeddedAliases:new Set};if(n==="")return {select:[],join:{},embeddedAliases:new Set};if(n.trim()==="")throw new He("failed to parse select parameter");let r={},s=new Set;try{let i={input:n,pos:0},o=Qf(i,r,s);if(z(i),uw(i),!Oe(i))throw new Error(`Unexpected input at position ${i.pos}: "${i.input.slice(i.pos)}"`);return {select:o,join:r,embeddedAliases:s}}catch(i){if(fw(n))return {select:[],join:{},embeddedAliases:new Set};throw i}}function uw(t){let e=t.pos-1;for(;e>=0&&/\s/.test(t.input[e]??"");)e--;if(t.input[e]!==")")return;let n=t.pos;for(;W(t)==="'";)q(t);t.pos!==n&&z(t);}function fw(t){if(/^\s/.test(t))return false;let e=t.trimStart();if(e==="")return false;if(dw(e)||e.startsWith("::")||e.startsWith("->"))return true;let n=e[0]??"";return new Set([".",":","!","@","#","%","`","[","-","(","'","~"]).has(n)}function dw(t){return t.startsWith("...")?!/^\.{3}\s*(?:"[^"]+"|[a-zA-Z_][a-zA-Z0-9_$ -]*)\s*(?:![a-zA-Z_][a-zA-Z0-9_]*)*\s*\(/.test(t):false}function Qf(t,e,n){let r=[];if(z(t),Oe(t)||W(t)===")"||W(t)===","&&(q(t),z(t),Oe(t)||W(t)===")"))return r;for(r.push(Gf(t,e,n));!Oe(t)&&(z(t),W(t)===",");)q(t),z(t),r.push(Gf(t,e,n));return r}function Gf(t,e,n){if(z(t),W(t)==="*")return q(t),gw(t),Ae(t,".count()")&&q(t,8),"*";if(Ae(t,"..."))return q(t,3),z(t),pw(t,e,n);let r=Ye(t,{allowSpaces:true,allowDollar:true});return z(t),Ae(t,"::")?ja(r,void 0,t,e,n):W(t)===":"?(q(t),z(t),mw(r,t,e,n)):ja(r,void 0,t,e,n)}function pw(t,e,n){let r=Ye(t);z(t);let{hint:s,innerJoin:i}=Xf(t);if(z(t),W(t)!=="(")throw new Error(`Expected "(" for spread embed at position ${t.pos}`);let{subSelect:o,subJoin:a}=Yf(t),l=r,c={};i&&(c.type="inner"),s&&(c.hint=s),e[l]=c,n.add(l);let f={spread:true,select:o};return Object.keys(a).length>0&&(f.join=a),{[l]:f}}function mw(t,e,n,r){let s=Ye(e,{allowSpaces:true,allowDollar:true});return z(e),ja(s,t,e,n,r)}function ja(t,e,n,r,s){return z(n),t==="count"&&(Oe(n)||W(n)===","||W(n)===")"||W(n)==="("||Ae(n,"::"))?bw(e,n):W(n)==="!"||W(n)==="("?hw(t,e,n,r,s):ww(t,e,n)}function hw(t,e,n,r,s){let{hint:i,innerJoin:o}=Xf(n);if(z(n),W(n)!=="(")throw new He("failed to parse select parameter");let{subSelect:a,subJoin:l}=Yf(n),c=e??t,f={};e&&(f.from=t),o&&(f.type="inner"),i&&(f.hint=i),r[c]=f,s.add(c),e&&t!==c&&s.add(t);let u={select:a};return Object.keys(l).length>0&&(u.join=l),{[c]:u}}function Xf(t){if(z(t),W(t)!=="!")return {};q(t);let e=Ye(t);if(e==="inner")return {innerJoin:true};if(e==="left")return {};let n=e;if(z(t),W(t)==="!"){q(t);let r=Ye(t);if(r==="inner")return {hint:n,innerJoin:true};if(r==="left")return {hint:n};throw new Error(`Expected "inner" or "left" after hint, got "${r}" at position ${t.pos}`)}return {hint:n}}function gw(t){for(;W(t)==="*";)q(t);for(;W(t)==="!";){let e=t.pos;if(q(t),!yw(t)){t.pos=e;return}}}function yw(t){let e=t.pos;try{return Ye(t),!0}catch{return t.pos=e,false}}function Yf(t,e,n){if(W(t)!=="(")throw new Error(`Expected "(" at position ${t.pos}`);q(t),z(t);let r={},s=new Set;if(W(t)===")")return q(t),{subSelect:[],subJoin:r};let i=Qf(t,r,s);if(z(t),W(t)!==")")throw new Error(`Expected ")" at position ${t.pos}`);return q(t),{subSelect:i,subJoin:r}}function bw(t,e){z(e);let n=true;if(W(e)==="("){n=false,q(e);let o=e.pos;for(;!Oe(e)&&W(e)!==")";)q(e);if(Oe(e))throw new He("expected closing paren for count()");let a=e.input.slice(o,e.pos).trim();if(q(e),a!=="")throw new He("expected null arg for count()")}z(e);let r;Ae(e,"::")&&(q(e,2),r=kr(e));let s=t??"count",i={aggregate:"count"};return n&&(i.bareCount=true),r&&(i.cast=r),{[s]:i}}function ww(t,e,n){z(n);let r,s,i=false,o;if(Ae(n,"->")){let{path:f,lastProp:u,lastIsText:d,invalidTextTraversalKey:p}=Sw(n);r=f,s=u||void 0,i=d,o=p;}z(n);let a,l;if(Ae(n,"::")){q(n,2);let f=kr(n);if(z(n),W(n)==="."&&!Oe(n)){let u=n.input[n.pos+1]??"";if(Da(u)){let d=n.pos;q(n);let p=Ye(n);if(Jf.has(p)&&Ae(n,"()"))return a=f,q(n,2),z(n),Ae(n,"::")&&(q(n,2),l=kr(n),Na(n)),zf(t,e,r,s,i,o,a,p,l);n.pos=d;}}l=f,Na(n);}let c;if(W(n)==="."&&!Oe(n)){let f=n.input[n.pos+1]??"";if(Da(f)){let u=n.pos;q(n);let d=Ye(n);Jf.has(d)&&Ae(n,"()")?(c=d,q(n,2),z(n),Ae(n,"::")&&(q(n,2),l=kr(n),Na(n))):n.pos=u;}}return zf(t,e,r,s,i,o,a,c,l)}function Na(t){for(z(t);Ae(t,"::");)q(t,2),kr(t),z(t);}function kr(t){z(t);let e=[Ye(t)];for(;!Oe(t);){let n=t.pos;if(z(t),t.pos===n)break;let r=W(t);if(!(r==='"'||/^[a-zA-Z0-9_]$/.test(r))){t.pos=n;break}e.push(Ye(t));}return e.join(" ")}function zf(t,e,n,r,s,i,o,a,l){let c=e??(a||void 0)??r;if(!c&&!o&&!l&&!a&&!n)return t;let f=c??t,u={};return t!==f&&(u.column=t),a&&!u.column&&t===f&&(u.column=t),n&&(u.column||(u.column=t),u.path=n,s&&(u.pathText=true),i&&(u.invalidJsonTextTraversalKey=i)),o&&(u.preCast=o),a&&(u.aggregate=a),l&&(u.cast=l),{[f]:u}}function Sw(t){let e=[],n="",r=false,s;for(;Ae(t,"->");){let o=r;q(t,2);let a=false;W(t)===">"&&(q(t),a=true);let l=_w(t);e.push(l),o&&s===void 0&&(s=l),/^-?\d+$/.test(l)||(n=l),r=a;}return {path:"$."+e.join("."),lastProp:n,lastIsText:r,invalidTextTraversalKey:s}}function _w(t){return Ew(t)}var Vf=new Set(["(",".",">","<"]);function Cr(t,e,n){throw new He(`"failed to parse select parameter (${t.input})" (line 1, column ${e})`,n)}function Ew(t){z(t);let e=t.pos;if(W(t)==='"')return Ye(t);let n="";for(;!Oe(t)&&!(Ae(t,"->")||Ae(t,"::"));){let s=W(t);if(s===","||s==="."||s===":"||/\s/.test(s))break;n+=s,q(t);}n===""&&Cr(t,e+1,"unexpected end of input");let r=n[0]??"";Vf.has(r)&&Cr(t,e+1,`unexpected "${r}" expecting "-", digit or any non reserved character different from: .,>()`);for(let s=1;s<n.length;s++){let i=n[s];Vf.has(i)&&Cr(t,e+s+1,`unexpected "${i}" expecting "-", digit or any non reserved character different from: .,>()`);}if(n.includes("--")){let s=n.indexOf("--"),i=s===0&&n.length>1?e+2:e+s+1;Cr(t,i,'unexpected "-" expecting digit');}if(n.endsWith("-")&&Cr(t,e+n.length,'unexpected "-" expecting digit'),/^-\d+\D/.test(n))throw new He("failed to parse select parameter");return n}function Ye(t,e={}){if(z(t),W(t)==='"'){q(t);let r="";for(;!Oe(t)&&W(t)!=='"';)r+=W(t),q(t);if(Oe(t))throw new Error(`Missing closing quote at position ${t.pos}`);return q(t),r}let n="";for(;!Oe(t);){let r=W(t);if(Da(r))n+=r,q(t);else if(e.allowDollar&&r==="$")n+=r,q(t);else if(e.allowSpaces&&r===" ")n+=r,q(t);else if(r==="-"&&n.length>0){if((t.input[t.pos+1]??"")===">")break;n+=r,q(t);}else break}if(e.allowSpaces&&(n=n.trimEnd()),n==="")throw new Error(`Expected identifier at position ${t.pos}`);if(n.includes("--")||n.endsWith("-"))throw new He("failed to parse select parameter");return n}var xw=new Set(["application/json","text/csv","application/x-www-form-urlencoded"]);function Tw(t){return t.split(";")[0]?.trim().toLowerCase()??""}var vr=class extends Error{mediaType;constructor(e){super(`Content-Type not acceptable: ${e}`),this.name="ContentTypeNotAcceptableError",this.mediaType=e;}};async function Fa(t){let e=t.method.toUpperCase();if(e==="GET"||e==="HEAD")return {};let n=await t.text(),r=t.headers.get("Content-Type")??"",s=Tw(r);if(!n&&r.includes("text/csv"))throw new On('parse error (not enough input) at ""');if(!n)return {};if(s&&!xw.has(s))throw new vr(s);if(r.includes("application/json")||s===""||s==="application/json")try{let i=JSON.parse(n);return Array.isArray(i)?{values:i}:{values:i}}catch{throw new Error(`Invalid JSON body: ${n.slice(0,100)}`)}if(r.includes("text/csv"))return {values:Rw(n)};if(r.includes("application/x-www-form-urlencoded")){let i=new URLSearchParams(n),o={};for(let[a,l]of i)o[a]=l;return {values:o}}return {raw:n}}function Rw(t){let e=t.replace(/\r\n/g,`
76
76
  `).replace(/\r/g,`
77
- `),n=_w(e);if(n.length===0)throw new On("parse error (not enough input)");let r=n[0];if(n.length===1)return [];let s=[];for(let i=1;i<n.length;i++){let o=n[i],a={};for(let l=0;l<r.length;l++){let c=l<o.length?o[l]:"";a[r[l]]=c===""?null:c;}s.push(a);}return s}function _w(t){let e=[],n=0,r=t.length;for(;n<r&&!(n===r-1&&t[n]===`
78
- `);){let{row:s,nextPos:i}=Ew(t,n);e.push(s),n=i;}return e}function Ew(t,e){let n=[],r=e,s=t.length;for(;r<=s;){if(r===s||t[r]===`
77
+ `),n=Cw(e);if(n.length===0)throw new On("parse error (not enough input)");let r=n[0];if(n.length===1)return [];let s=[];for(let i=1;i<n.length;i++){let o=n[i],a={};for(let l=0;l<r.length;l++){let c=l<o.length?o[l]:"";a[r[l]]=c===""?null:c;}s.push(a);}return s}function Cw(t){let e=[],n=0,r=t.length;for(;n<r&&!(n===r-1&&t[n]===`
78
+ `);){let{row:s,nextPos:i}=kw(t,n);e.push(s),n=i;}return e}function kw(t,e){let n=[],r=e,s=t.length;for(;r<=s;){if(r===s||t[r]===`
79
79
  `)return n.length,{row:n,nextPos:r+1};if(t[r]==='"'){let i="";for(r++;r<s;)if(t[r]==='"')if(r+1<s&&t[r+1]==='"')i+='"',r+=2;else {r++;break}else i+=t[r],r++;n.push(i),r<s&&t[r]===","&&r++;}else {let i="";for(;r<s&&t[r]!==","&&t[r]!==`
80
- `;)i+=t[r],r++;n.push(i),r<s&&t[r]===","&&r++;}}return {row:n,nextPos:r}}var On=class extends Error{constructor(e){super(e),this.name="CsvParseError";}};function ja(t){let e=new URL(t.url),n=new Map;for(let[r,s]of e.searchParams.entries()){let i=n.get(r)??[];i.push(s),n.set(r,i);}return n}function La(t,e,n){let r=e.toUpperCase();if(t.isRpc)return "rpc";switch(r){case "GET":case "HEAD":return "query";case "POST":return n.preferTokens.find(i=>i.key==="resolution"&&(i.value==="merge-duplicates"||i.value==="ignore-duplicates"))?"upsert":"insert";case "PATCH":return "update";case "PUT":return "put";case "DELETE":return "delete";default:return "query"}}var Xf=new Set(["eq","neq","gt","gte","lt","lte","like","ilike","match","imatch","is","isdistinct","in","cs","cd","ov","sl","sr","nxl","nxr","adj","fts","plfts","phfts","wfts","not"]),Yf={eq:"$eq",neq:"$neq",gt:"$gt",gte:"$gte",lt:"$lt",lte:"$lte",like:"$like",ilike:"$ilike",match:"$regex",imatch:"$iregex",is:"$is",isdistinct:"$isDistinct",in:"$in",cs:"$contains",cd:"$containedBy",ov:"$overlaps",sl:"$rangeLt",sr:"$rangeGt",nxl:"$rangeGte",nxr:"$rangeLte",adj:"$rangeAdjacent"},xw={any:"Any",all:"All"},Tw=new Set(["eq","gt","gte","lt","lte","like","ilike","match","imatch"]),Rw={fts:void 0,plfts:"plain",phfts:"phrase",wfts:"websearch"};function Ti(t){let e=t.match(/^(\w+)\((any|all)\)$/);if(e){let[,s,i]=e;if(!Tw.has(s))return null;let o=Yf[s];return o?{astOp:o+xw[i]}:null}let n=t.match(/^(p[lh]fts|wfts|fts)(?:\(([^)]+)\))?$/);if(n){let[,s,i]=n;return i!==void 0&&!/^[A-Za-z_][A-Za-z0-9_ ]*(?:\.[A-Za-z_][A-Za-z0-9_]*)?$/.test(i)?null:{astOp:"$textSearch",ftsType:Rw[s],ftsConfig:i}}let r=Yf[t];return r?{astOp:r}:null}function Ar(t){let e=t.indexOf(".");if(e===-1)return false;let r=t.substring(0,e).replace(/\((any|all)\)$/,"").replace(/^(p[lh]fts|wfts|fts)\([^)]+\)$/,"$1");return Xf.has(r)}var nn=new Set(["select","order","limit","offset","on_conflict","columns","apikey"]);function Or(t){if(t.startsWith("(")&&t.endsWith(")")&&(t=t.slice(1,-1)),t.trim()==="")return [];let e=[],n=0;for(;n<t.length;){if(t[n]==='"'){n++;let r="";for(;n<t.length&&t[n]!=='"';)t[n]==="\\"&&n+1<t.length&&n++,r+=t[n],n++;n<t.length&&n++,e.push(r);}else {let r="";for(;n<t.length&&t[n]!==",";)r+=t[n],n++;e.push(rt(r,{preserveWhitespace:true}));}n<t.length&&t[n]===","&&(n++,n===t.length&&e.push(""));}return e}function rn(t){if(t.startsWith("{")&&t.endsWith("}")&&(t=t.slice(1,-1)),t==="")return [];let e=[],n=0;for(;n<t.length;){if(t[n]==='"'){n++;let r="";for(;n<t.length&&t[n]!=='"';)t[n]==="\\"&&n+1<t.length&&n++,r+=t[n],n++;n<t.length&&n++,e.push(r);}else {let r="";for(;n<t.length&&t[n]!==",";)r+=t[n],n++;e.push(rt(r));}n<t.length&&t[n]===","&&n++;}return e}var Pn=Symbol.for("postgrest:not_null"),sn=Symbol.for("postgrest:unknown");function rt(t,e){let n=e?.preserveWhitespace===true,r=t.trim();if(r.startsWith('"')&&r.endsWith('"')&&r.length>=2)return r.slice(1,-1);let s=r.toLowerCase();if(s==="null")return null;if(s==="not_null")return Pn;if(s==="true")return true;if(s==="false")return false;if(s==="unknown")return null;if(/^-?0\d+$/.test(r)||/^[0-9A-Fa-f]+$/.test(r)&&/[A-Fa-f]/.test(r))return r;if(r!==""&&!Number.isNaN(Number(r))&&Number.isFinite(Number(r)))return Number(r);if(r.startsWith("{")&&r.endsWith("}"))try{let i=JSON.parse(r);if(typeof i=="object"&&!Array.isArray(i))return i}catch{}return n?r===""?"":t:r}function Ir(t,e,n,r){let s={},i={};for(let[o,a]of t){if(nn.has(o))continue;let c=o.startsWith('"')?-1:o.indexOf(".");if(c>0&&!o.slice(0,c).includes("->")){let f=o.slice(0,c),u=o.slice(c+1);if(e.has(f)){if(u==="order"||u==="limit"||u==="offset")continue;if(u.includes(".")){let d=u.lastIndexOf("."),p=u.slice(d+1);if(p==="order"||p==="limit"||p==="offset")continue}i[f]||(i[f]={}),Aw(u,a,i[f]);continue}if(o!=="not.or"&&o!=="not.and")throw kw(f)}if(e.has(o)&&!a.every(Cw)&&!r?.has(o)){let f=n?`${n}.${o}`:o,u=new Error(`column ${f} does not exist`);throw u.code="42703",u}Ua(o,a,s);}return {where:s,embeddedWheres:i}}function Cw(t){return /^(not\.)?is\.(null|true|false|distinct\.)/.test(t.trim())}function kw(t){return new ve({httpStatus:400,code:"PGRST108",message:`'${t}' is not an embedded resource in this request`,details:null,hint:`Verify that '${t}' is included in the 'select' query parameter.`})}function Ua(t,e,n){if(t==="or"||t==="and"){if(e.every(o=>!o.includes("("))){for(let o of e)vw(t,o,n);return}let s=e.map(o=>ed(o)),i=s.length===1?s[0]:s.flat();n[`$${t}`]=i;return}if(t==="not.or"||t==="not.and"){let s=t.slice(4),i=e.map(a=>ed(a)),o=i.length===1?i[0]:i.flat();n.$not={[`$${s}`]:o};return}let r=td(Nw(t),{stopAtSpace:false});nd(r);for(let s of e){let i=Ma(s);n[r]?Object.assign(n[r],i):n[r]=i;}}function vw(t,e,n){let r=e.indexOf("."),s=r===-1?e:e.slice(0,r),i=`${t}${s}`,o=r===-1?"":e.slice(r+1),a=Ma(o);n[i]?Object.assign(n[i],a):n[i]=a;}function Aw(t,e,n){let r=Ow(t);if(!r){Ua(t,e,n);return}let s={};Ua(r.filterKey,e,s);for(let[i,o]of Object.entries(s))n[`${r.path}.${i}`]=o;}function Ow(t){for(let e of ["not.or","not.and","or","and"]){let n=`.${e}`;if(t.endsWith(n)){let r=t.slice(0,-n.length);if((e==="or"||e==="and")&&r==="not")continue;if(r)return {path:r,filterKey:e}}}}function Ma(t){let e=t,n=false;e.startsWith("not.")&&(n=true,e=e.slice(4));let r=e.indexOf("."),s,i;r===-1?(s=e,i=""):(s=e.slice(0,r),i=e.slice(r+1));let o=Ti(s);if(!o){let u=s.match(/^(p[lh]fts|wfts|fts)\(\)$/);throw u?new Error(`"failed to parse filter (${t})" (line 1, column ${u[1].length+2})`):new Error(`"failed to parse filter (${t})" (line 1, column 1)`)}let{astOp:a,ftsType:l,ftsConfig:c}=o;if(n&&a==="$in")return {$notIn:Fa(a,i)};if(n&&a==="$is")return {$isNot:Fa(a,i)};let f=a==="$textSearch"?$w(i,l,c):Fa(a,i);return n?{$not:{[a]:f}}:{[a]:f}}function Fa(t,e){if(t==="$in"||t==="$notIn"){if(!e.startsWith("(")||!e.endsWith(")")){let n=t==="$in"?"in":"not.in";throw new Error(`"failed to parse filter (${n}.${e})" (line 1, column ${n.length+e.length+2})`)}return Or(e)}if(t.endsWith("Any")||t.endsWith("All")){if(e.startsWith("{"))return rn(e);if(!Pw(t))throw Object.assign(new Error(`malformed array literal: "${e}"`),{code:"22P02",detail:'Array value must start with "{" or dimension information.'});return Or(e)}if(t==="$contains"||t==="$containedBy"||t==="$overlaps"){if(e.startsWith("{")){try{let n=JSON.parse(e);if(typeof n=="object"&&!Array.isArray(n))return n}catch{}return rn(e)}return e.startsWith("[")||e.startsWith("(")?e:rt(e)}if(t.startsWith("$range"))return e;if(t==="$is"){let n=e.toLowerCase().trim(),s=["not_null","unknown","null","true","false"].find(i=>n===i||n.startsWith(i));if(!s)throw new Error(`"failed to parse filter (is.${e})" (line 1, column ${2+e.length})`);return s==="unknown"?sn:s==="not_null"?Pn:s==="null"?null:s==="true"?true:s==="false"?false:rt(e)}if(t==="$like"||t==="$ilike"||t==="$likeAny"||t==="$ilikeAny"||t==="$likeAll"||t==="$ilikeAll"){let n=e.replace(/\*/g,"%");return t.endsWith("Any")||t.endsWith("All")?n.startsWith("{")?rn(n):Or(n):n}if(t==="$isDistinct")return e.startsWith("{")?rn(e):e;if((t==="$eq"||t==="$neq")&&e.startsWith("{")&&e.endsWith("}")){try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null&&!Array.isArray(n))return n}catch{}return rn(e)}return rt(e)}function Pw(t){return t==="$likeAny"||t==="$ilikeAny"||t==="$likeAll"||t==="$ilikeAll"}function $w(t,e,n){let r={query:t};return e&&(r.type=e),n&&(r.config=n),r}function Iw(t){let e=t.match(/^\(\(or\([^)]*\),/);if(e)return e[0].length+8;let n=t.match(/^\(or\([^)]*\),/);return n?n[0].length+8:t.length+2}function Zf(t){return new Error(`"failed to parse logic tree (${t})" (line 1, column ${Iw(t)})`)}function ed(t){if(!t.startsWith("(")||!t.endsWith(")"))throw new Error(`"failed to parse logic tree (${t})" (line 1, column ${t.length+3})`);let e=t.slice(1,-1);for(;e.endsWith(")");){let n=0;for(let r of e)r==="("?n++:r===")"&&n--;if(n<0)e=e.slice(0,e.length+n);else break}if(e.trim()==="")throw Zf(t);try{return Pr(e).map(r=>$r(r))}catch{throw Zf(t)}}function Pr(t){let e=[],n=0,r=0,s=false,i="";for(let o of t)if(o==='"'&&!s?s=true:o==='"'&&s&&(s=false),s||(o==="("?n++:o===")"?n--:o==="{"?r++:o==="}"&&r--),o===","&&n===0&&r===0&&!s){if(i.trim()==="")throw new Error("empty logical expression");e.push(i.trim()),i="";}else i+=o;if(i.trim())e.push(i.trim());else if(t.trim().endsWith(","))throw new Error("empty logical expression");return e}function $r(t){let e=t.trim(),n=e.match(/^and\s*\((.*)\)$/s);if(n)return {$and:Pr(n[1]).map(d=>$r(d))};let r=e.match(/^or\s*\((.*)\)$/s);if(r)return {$or:Pr(r[1]).map(d=>$r(d))};let s=e.match(/^not\.and\s*\((.*)\)$/s);if(s)return {$not:{$and:Pr(s[1]).map(d=>$r(d))}};let i=e.match(/^not\.or\s*\((.*)\)$/s);if(i)return {$not:{$or:Pr(i[1]).map(d=>$r(d))}};if(/^(?:and|or|not)=/.test(e))throw new Error(`Invalid filter expression: "${t}"`);if(e.startsWith("not("))throw new Error(`Invalid filter expression: "${t}"`);let o=t;if(o.startsWith("not.")){let p=o.slice(4).split(".")[0];if(!(p.length>0&&Ti(p)!==null))throw new Error(`Invalid filter expression: "${t}"`)}let l=o.indexOf(".");if(l===-1)throw new Error(`Invalid filter expression: "${t}"`);let c=td(o.slice(0,l),{stopAtSpace:true});nd(c);let f=o.slice(l+1),u=Ma(f);return {[c]:u}}function td(t,e){let r=(e.stopAtSpace?/[!@/\\~[\]()\t ]/:/[!@/\\~[\]()\t]/).exec(t),s=r?t.slice(0,r.index):t,i=s.indexOf("::");i!==-1&&(s=s.slice(0,i));let o=s.indexOf("=");o!==-1&&(s=s.slice(0,o));let a=s.indexOf(":");return a!==-1&&(s=s.slice(0,a)),s}function Nw(t){return t.length>=2&&t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1).replace(/""/g,'"'):t}function nd(t){if(t===""||t==="*"||t.startsWith(".")||t.includes("--")||t.endsWith("-"))throw new Error(`Invalid filter expression: "${t}"`);if(/->>?-\d+[A-Za-z]/.test(t))throw new Error(`Invalid filter expression: "${t}"`)}function Dw(t){let e=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\(([^)]+)\)$/);return e?{embed:e[1],column:e[2]}:null}function rd(t){if(t===void 0)return;let e=t.trim();if(!/^[+-]?\d+$/.test(e))return;let n=Number(e);return Number.isFinite(n)?n:void 0}function Ba(t,e){let n=rd(t),r=rd(e);return r!==void 0&&r<0&&(n!==void 0&&n>=0&&(n=Math.max(0,n+r)),r=void 0),{limit:n,offset:r}}function Ha(t,e){let n={embeddedTransforms:{}},r,s,i={},o={},a={},l={};for(let[d,p]of t){let g=p[0],m=d.indexOf(".");if(m>0){let h=d.slice(0,m),y=d.slice(m+1);if(e.has(h)){if(y==="order"||y==="limit"||y==="offset"){n.embeddedTransforms[h]||(n.embeddedTransforms[h]={}),y==="order"?n.embeddedTransforms[h].order=qa(g):y==="limit"?i[h]=g:y==="offset"&&(o[h]=g);continue}if(y.includes(".")){let w=y.lastIndexOf("."),S=y.slice(w+1);if(S==="order"||S==="limit"||S==="offset"){n.embeddedTransforms[h]||(n.embeddedTransforms[h]={});let b=n.embeddedTransforms[h],_=y.slice(0,w);b._nested||(b._nested={});let E=b._nested;E[_]||(E[_]={});let x=E[_];S==="order"?x.order=qa(g):S==="limit"?(a[h]||(a[h]={}),a[h][_]=g):S==="offset"&&(l[h]||(l[h]={}),l[h][_]=g);continue}}}}d==="order"?n.order=qa(g):d==="limit"?r=g:d==="offset"&&(s=g);}if(n.order){for(let d of n.order)if(d.embed&&!e.has(d.embed))throw new ve({httpStatus:400,code:"PGRST108",message:`'${d.embed}' is not an embedded resource in this request`,details:null,hint:`Verify that '${d.embed}' is included in the 'select' query parameter.`})}let c=Ba(r,s);c.limit!==void 0&&(n.limit=c.limit),c.offset!==void 0&&(n.offset=c.offset);let f=new Set([...Object.keys(i),...Object.keys(o)]);for(let d of f){let p=Ba(i[d],o[d]);n.embeddedTransforms[d]||(n.embeddedTransforms[d]={}),p.limit!==void 0&&(n.embeddedTransforms[d].limit=p.limit),p.offset!==void 0&&(n.embeddedTransforms[d].offset=p.offset);}let u=new Set([...Object.keys(a),...Object.keys(l)]);for(let d of u){let p=new Set([...Object.keys(a[d]??{}),...Object.keys(l[d]??{})]);for(let g of p){let m=Ba(a[d]?.[g],l[d]?.[g]),h=n.embeddedTransforms[d]?._nested?.[g];h&&(m.limit!==void 0&&(h.limit=m.limit),m.offset!==void 0&&(h.offset=m.offset));}}return n}function qa(t){return jw(t).map(({entry:e,start:n},r)=>{let s=r===0?e.trim():e.trimEnd(),i=r===0?n+e.length-e.trimStart().length:n;return Lw(s,t,i)})}function jw(t){let e=[],n=0,r=0;for(let s=0;s<t.length;s++){let i=t[s];i==="("?n++:i===")"?n=Math.max(0,n-1):i===","&&n===0&&(e.push({entry:t.slice(r,s),start:r}),r=s+1);}return e.push({entry:t.slice(r),start:r}),e}function Lw(t,e,n){let r=t.split("."),s={column:r[0].replace(/\s+$/,"")},i=r[0];if(!i)throw new fe(`failed to parse order (${e})`,'unexpected end of input expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input',1);let o=i.indexOf("::");if(o!==-1)throw new fe(`failed to parse order (${e})`,`unexpected ':' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+o+1);let a=i.indexOf("--");if(a!==-1)throw new fe(`failed to parse order (${e})`,`unexpected '-' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+a+2);let l=i.search(/[@#%]/);if(l!==-1)throw new fe(`failed to parse order (${e})`,`unexpected '${i[l]}' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+l+1);if(i.endsWith("-"))throw new fe(`failed to parse order (${e})`,`unexpected '-' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+i.length);let c=i.indexOf(":");if(c!==-1)throw new fe(`failed to parse order (${e})`,`unexpected ':' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+c+1);let f=Dw(i);if(f){if(f.column.includes(","))throw new fe(`failed to parse order (${e})`,`unexpected ',' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+i.indexOf(",",f.embed.length)+1);s.column=f.column,s.embed=f.embed;}else if(i.includes("(")||i.includes(")")){let g=i.search(/[()]/);throw new fe(`failed to parse order (${e})`,`unexpected '${i[g]}' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+g+1)}let u=n+i.length+1,d=false,p=false;for(let g=1;g<r.length;g++){let m=r[g];if(m==="asc"||m==="desc"){if(d)throw new fe(`failed to parse order (${e})`,`unexpected '${m[0]}' expecting "," or end of input`,u+1);if(p)throw new fe(`failed to parse order (${e})`,`unexpected '${m[0]}' expecting "," or end of input`,u+1);s.direction=m,d=true,u+=m.length+1;}else if(m==="nullsfirst"||m==="nullslast"){if(p)throw new fe(`failed to parse order (${e})`,`unexpected '${m[0]}' expecting "," or end of input`,u+1);s.nullsFirst=m==="nullsfirst",p=true,u+=m.length+1;}else {let h=["asc","desc","nullsfirst","nullslast"],y=null;for(let w of h)if(m.startsWith(w)&&m.length>w.length){y=w;break}if(y){let w=m[y.length],S=u+y.length;throw new fe(`failed to parse order (${e})`,`unexpected '${w}' expecting "," or end of input`,S+1)}throw new fe(`failed to parse order (${e})`,`unexpected '${m[0]}' expecting "," or end of input`,u+1)}}return s}function Wa(t,e,n){let r={};for(let i of t.preferTokens)switch(i.key){case "count":r.count===void 0&&(r.count=i.value);break;case "missing":r.missing===void 0&&(r.missing=i.value);break;case "handling":r.handling===void 0&&(r.handling=i.value);break;case "tx":r.tx===void 0&&(r.tx=i.value,i.value==="rollback"&&(r.rollback=true));break;case "max-affected":r.maxAffected===void 0&&(r.maxAffected=i.value);break;case "timezone":r.timezone===void 0&&(r.timezone=i.value);break;case "return":r.return===void 0&&(r.return=i.value);break}n.toUpperCase()==="HEAD"&&(r.head=true),t.accept.includes("application/vnd.pgrst.object")&&(r.cardinality="one"),t.accept.includes("application/vnd.pgrst.plan")&&(r.explain=Mw(t.accept));let s=e.get("columns");if(s){let i=s[0];r.columns=Fw("columns",i);}return r}function Fw(t,e){let n=e.split(",").map(r=>Uw(r));if(n.length===0||n.some(r=>r===""||r==="*"||r.includes("--")||r.endsWith("-")))throw new jt(`"failed to parse ${t} parameter (${e})" (line 1, column 1)`,"unexpected input");return n}function Uw(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e.replace(/@.*$/,"")}function Mw(t){let e={},n=t.match(/options=([^;]+)/);if(n){let r=n[1].split("|").map(s=>s.trim());e.analyze=r.includes("analyze"),e.verbose=r.includes("verbose"),e.settings=r.includes("settings"),e.buffers=r.includes("buffers"),e.wal=r.includes("wal");}return e}function Ka(t,e,n,r){if(!t.isRpc)return {};if(e.toUpperCase()==="POST"){let a={httpMethod:"POST"};return r.values?(Array.isArray(r.values)?(a.args=r.values,a.paramsType="positional"):(a.args=r.values,a.paramsType="named"),a.inputType="json"):r.raw!==void 0&&(a.args={_raw:r.raw},a.inputType="text"),a}let i={};for(let[a,l]of n){if(nn.has(a))continue;let c=l.filter(f=>!Ar(f));c.length!==0&&(c.length>1?i[a]=c.map(f=>rt(f)):i[a]=rt(c[0]));}let o={httpMethod:"GET",paramsType:"named",inputType:"json"};return Object.keys(i).length>0&&(o.args=i),o}function Ja(t,e){let n=t.get("on_conflict"),r=n===void 0?void 0:Bw(n[0]),i=e.preferTokens.find(o=>o.key==="resolution")?.value==="ignore-duplicates";return {onConflict:r?.length?r:void 0,ignoreDuplicates:i}}function Bw(t){let e=t.split(",").map(n=>n.trim());if(e.length===0||e.some(n=>n===""||n.includes("--")||n.endsWith("-")))throw new jt(`"failed to parse on_conflict parameter (${t})" (line 1, column 1)`,"unexpected input");return e.map(n=>n.replace(/[!@/\\~[\]()\t ].*$/,""))}async function Ri(t,e){let n=e?.basePath,r=e?.parseRoute??(C=>Aa(C,n)),s=e?.parseHeaders??Oa,i=e?.parseSelect??Na,o=e?.parseBody??Da,a=e?.parseQueryParams??ja,l=e?.resolveType??La,c=e?.resolveFilters??Ir,f=e?.resolveTransforms??Ha,u=e?.resolveMeta??Wa,d=e?.resolveRpcParams??Ka,p=e?.resolveUpsertParams??Ja,[g,m,h,y,w]=await Promise.all([r(t),s(t),i(t),o(t),a(t)]),S=t.method,b=l(g,S,m),_=w;if(g.isRpc&&S.toUpperCase()==="GET"){_=new Map;for(let[C,R]of w){if(nn.has(C)){_.set(C,R);continue}let U=R.filter(J=>Ar(J));U.length>0&&_.set(C,U);}}let E=c(_,h.embeddedAliases,g.isRpc?void 0:g.from,e?.parentColumns),x=f(w,h.embeddedAliases),O=u(m,w,S),v=d(g,S,w,y),P=b==="upsert"||b==="put"?p(w,m):void 0;return qw(b,g,m,h,y,E,x,O,v,P)}function qw(t,e,n,r,s,i,o,a,l,c){let f={type:t};return e.isRpc?f.function=e.function:f.from=e.from,n.schema&&(f.schema=n.schema),Object.keys(r.join).length>0&&(f.join=r.join),r.select.length>0&&(f.select=sd(r.select,i.embeddedWheres,o.embeddedTransforms,r.join)),Object.keys(i.where).length>0&&(f.where=i.where),(t==="insert"||t==="update"||t==="upsert"||t==="put")&&s.values!==void 0&&(f.values=s.values),t==="rpc"&&(l.args!==void 0&&(f.args=l.args),l.httpMethod&&(f.httpMethod=l.httpMethod),l.paramsType&&(f.paramsType=l.paramsType),l.inputType&&(f.inputType=l.inputType)),(t==="upsert"||t==="put")&&c&&(c.onConflict&&(f.onConflict=c.onConflict),f.ignoreDuplicates=c.ignoreDuplicates),a.return==="representation"&&(t==="insert"||t==="update"||t==="delete"||t==="upsert"||t==="put")&&(!f.select||f.select.length===0)&&(f.select=["*"]),o.order&&(f.order=o.order),o.limit!==void 0&&(f.limit=o.limit),o.offset!==void 0&&(f.offset=o.offset),Object.keys(a).length>0&&(f.$meta=a),f}function Hw(t,e,n){return t.map(r=>{if(typeof r=="string"||!(e in r))return r;let s=r[e];return s.select?{[e]:{...s,where:{...s.where??{},...n}}}:r})}function sd(t,e,n,r,s){return t.map(i=>{if(typeof i=="string")return i;let o=Object.keys(i)[0],a=i[o];if(!a.select)return i;let l={...a},c=r?.[o]?.from,f=e[o]||c&&e[c],u=n[o]||c&&n[c];if(f&&s!==o){let d={},p={};for(let[g,m]of Object.entries(f)){let h=g.indexOf(".");if(h>0){let y=g.slice(0,h),w=g.slice(h+1);if(l.join?.[y]||l.select?.some(_=>typeof _=="object"&&y in _&&"select"in(_[y]??{}))){p[y]||(p[y]={}),p[y][w]=m;continue}}d[g]=m;}Object.keys(d).length>0&&(l.where=d);for(let[g,m]of Object.entries(p))l.select=Hw(l.select??[],g,m);}if(u){let d=u;if(d.order&&(l.order=d.order),d.limit!==void 0&&(l.limit=d.limit),d.offset!==void 0&&(l.offset=d.offset),d._nested)for(let[p,g]of Object.entries(d._nested))n[p]=g;}return l.select&&(l.select=sd(l.select,e,n,l.join,o)),{[o]:l}})}function Ci(t){return t!=null&&typeof t=="object"&&"$ref"in t}st();var Ga=class extends ie{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}serialize(e){if(this.isNullish(e))return e;if(typeof e=="number"&&Number.isFinite(e))return Math.trunc(e);if(typeof e=="string")return $n(e);throw this.checkError("color_range",e)}deserialize(e){if(this.isNullish(e))return "";if(typeof e=="number"&&Number.isFinite(e))return id(e);if(typeof e=="string"&&e.startsWith("#"))return e;if(typeof e=="string"||typeof e=="bigint"){let n=Number(e);if(Number.isFinite(n))return id(n)}return e}},za=class extends ie{get isShimBacked(){return true}get sqliteType(){return "TEXT"}serialize(e){return this.isNullish(e)?e:typeof e=="string"?e.replace(/Z$/,"+00:00"):e}deserialize(e){if(this.isNullish(e)||typeof e!="string")return e;let n=e.trim();if(/^\d{4}-\d{2}-\d{2}T/.test(n))return n.replace(/\+00:00$/,"Z");if(/^\d{4}-\d{2}-\d{2}$/.test(n))return `${n}T00:00:00Z`;if(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/.test(n)){let r=n.replace(" ","T");return /(?:Z|[+-]\d{2}:\d{2})$/.test(r)?r.replace(/\+00:00$/,"Z"):`${r}Z`}return n.replace(/\+00:00$/,"Z")}},Va=class extends ie{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}serialize(e){if(this.isNullish(e))return e;if(typeof e=="number"&&Number.isFinite(e))return Math.trunc(e);if(typeof e=="string"){let n=Date.parse(e);if(Number.isFinite(n))return Math.trunc(n/1e3)}return e}deserialize(e){if(this.isNullish(e))return e;if(typeof e=="number"&&Number.isFinite(e))return Math.trunc(e);if(typeof e=="bigint")return Number(e);if(e instanceof Date&&Number.isFinite(e.getTime()))return Math.trunc(e.getTime()/1e3);if(typeof e=="string"){let n=e.trim();if(/^\d+$/.test(n))return Number(n);let r=Date.parse(n);if(Number.isFinite(r))return Math.trunc(r/1e3)}return e}},Qa=class extends ie{get isShimBacked(){return true}get sqliteType(){return "TEXT"}serialize(e){return this.isNullish(e)?e:typeof e=="number"&&Number.isFinite(e)?e.toFixed(2):e}deserialize(e){return e}},Ya=class extends ie{get isShimBacked(){return true}get sqliteType(){return "TEXT"}deserialize(e){if(this.isNullish(e))return e;let n=null;if(typeof e=="string")n=e;else if(e instanceof Uint8Array)n=Buffer.from(e).toString("base64");else if(e&&typeof e=="object"&&!Array.isArray(e)){let s=Object.values(e);n=Buffer.from(s).toString("base64");}if(n===null)return e;n=n.replace(/\s/g,"");let r=(4-n.length%4)%4;return r===0?n:n+"=".repeat(r)}};function $n(t){let e=t.trim(),r=(e.startsWith("#")?e.slice(1):e).padStart(8,"0");return Number.parseInt(r,16)>>>0}function id(t){return `#${(Math.trunc(t)&16777215).toString(16).toUpperCase().padStart(6,"0")}`}function ad(t,e){return e==="postgres"||e==="pglite"?sql`('"' || upper('#' || lpad(to_hex((${t})::bigint & 16777215), 6, '0')) || '"')`:sql`('"' || upper(printf('#%06X', (${t}) & 16777215)) || '"')`}var Ww=new Set(["color","isodate","isodatetext","unixtz","monetary","monetarytext","bytea_b64"]),Kw=new Set(["bool","boolean"]),ld=new Map;function Le(t){if(!t)return false;let e=t.toLowerCase().trim();return Ww.has(e)||ld.has(e)}function Ne(t,e){return (t??e).toLowerCase().trim()}function Xa(t,e){let n=Ne(t.pg_type,t.type);return Le(n)||!e?n:Jw(t.table,t.name,e)??n}function Jw(t,e,n){let r=n.views.find(i=>i.name===t);if(!r?.sql)return;let s=[new RegExp(`CAST\\s*\\(.+?\\s+AS\\s+([\\w.]+)\\)\\s+AS\\s+${e}\\b`,"is"),new RegExp(`::\\s*(?:[\\w.]+\\.)?([\\w]+)\\s+AS\\s+${e}\\b`,"i")];for(let i of s){let o=r.sql.match(i);if(!o)continue;let a=o[1].split(".").pop().toLowerCase();if(Le(a)||Kw.has(a))return a}}function Za(t){if(typeof t=="string"&&t.trim()==="Z")throw Object.assign(new Error('invalid input syntax for type timestamp with time zone: "Z"'),{code:"22007",detail:null,hint:null})}function cd(t){return Array.isArray(t)?t.map(e=>od(e)):od(t)}function od(t){if(typeof t=="number"&&Number.isFinite(t))return Math.trunc(t);if(typeof t=="string"){let e=t.trim();return $n(e.startsWith("#")?e:`#${e}`)}return t}function vi(t,e){let n=e.toLowerCase().trim();return n==="color"?sql`to_json('#' || lpad(upper(to_hex((${t})::bigint & 16777215)), 6, '0'))`:n==="unixtz"?sql`to_json(EXTRACT(EPOCH FROM ${t})::bigint)`:n==="monetary"||n==="monetarytext"?sql`to_json((${t})::text)`:n==="bytea_b64"?sql`to_json(encode((${t})::bytea, 'base64'))`:n==="isodate"||n==="isodatetext"?sql`to_json(to_char((${t}) AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"'))`:null}function ud(t,e){let n=e.toLowerCase().trim();if(n==="unixtz"){let r=typeof t=="number"?t:typeof t=="string"?Number(t):NaN;if(Number.isFinite(r)){let s=new Date(r*1e3);if(Number.isFinite(s.getTime()))return s.toISOString()}return t}if(n==="bytea_b64"){if(typeof t=="string")try{let r=t.replace(/=+$/,"");for(;r.length%4!==0;)r+="=";let s=atob(r),i="";for(let o=0;o<s.length;o++)i+=s.charCodeAt(o).toString(16).padStart(2,"0");return `\\x${i}`}catch{return t}return t}return n==="monetary"||n==="monetarytext"?typeof t=="number"?String(t):t:(n==="isodate"||n==="isodatetext")&&typeof t=="string"?t.replace(/Z$/,"+00:00"):t}function Nr(t,e,n,r,s,i){if(r!=="postgres"||!e||!s?.columns)return t;let o=i??"public",a=s.columns.find(c=>c.table===e&&c.name===n&&(c.schema??"public")===o);if(!a)return t;let l=Ne(a.pg_type,a.type);return Le(l)?vi(t,l)??t:t}function fd(t,e,n,r){if(!t||!n?.columns)return false;let s=r??"public",i=n.columns.find(o=>o.table===t&&o.name===e&&(o.schema??"public")===s);return i?Le(Ne(i.pg_type,i.type)):false}function Dr(t,e,n){if(!t||!e?.columns)return false;let r=n??"public";return e.columns.some(s=>s.table!==t||(s.schema??"public")!==r?false:Le(Ne(s.pg_type,s.type)))}function el(t,e,n){let r=n??"public";return e.columns.filter(s=>s.table===t&&(s.schema??"public")===r).sort((s,i)=>s.ordinal_position-i.ordinal_position).map(s=>{let i=Ne(s.pg_type,s.type),o=Le(i);return {name:s.name,isDomain:o,domainTypeName:o?i:null}})}function dd(t){let e=t.pgTypeName.toLowerCase().trim(),n=ld.get(e);if(n)return n(t);switch(e){case "color":return new Ga(t);case "isodate":case "isodatetext":return new za(t);case "unixtz":return new Va(t);case "monetary":case "monetarytext":return new Qa(t);case "bytea_b64":return new Ya(t);default:return null}}var Gw=/^[a-zA-Z_][a-zA-Z0-9_.]*$/,zw=/[;'"\\/*\-#]/,Vw=/['\\;(]/,wt=class extends Error{constructor(n,r){super(`Unsafe ${r}: "${n}"`);this.value=n;this.context=r;this.name="SanitizeError";}};function Pe(t,e){if(!Gw.test(t))throw new wt(t,e)}function ln(t,e){if(zw.test(t))throw new wt(t,e);let n=0;for(let r of t)if(r==="("?n++:r===")"&&n--,n<0)throw new wt(t,e);if(n!==0)throw new wt(t,e)}function In(t,e){if(Vw.test(t))throw new wt(t,e)}function cn(t){let e=t.indexOf("->");if(e===-1)return {col:t,parts:[]};let n=t.slice(0,e),r=t.slice(e),s=[];for(;r.length>0;){let i;if(r.startsWith("->>"))i="->>",r=r.slice(3);else if(r.startsWith("->"))i="->",r=r.slice(2);else break;let o=r.indexOf("->"),a=o===-1?r:r.slice(0,o);s.push({op:i,key:a}),r=o===-1?"":r.slice(o);}return {col:n,parts:s}}function jr(t,e){return t.map(n=>{let r=/^-?\d+$/.test(n.key);return r||In(n.key,e),r?`${n.op}${n.key}`:`${n.op}'${n.key}'`}).join("")}function k(t){return typeof t=="string"?sql.ref(t):t}function Qw(t){return `"${t.replace(/"/g,'""')}"`}function tl(t){return sql.raw(Qw(t))}function nl(t,e,n=e.currentTable,r=e.currentSchema){if(!n||!e.introspection?.columns)return;let s=e.introspection.columns.filter(i=>i.table===n&&i.name===t);if(s.length!==0)return s.find(i=>!r||i.schema===r)??s.find(i=>["","public"].includes(i.schema??""))??s[0]}function Ai(t,e,n=e.currentTable,r=e.currentSchema){return nl(t,e,n,r)!==void 0}function de(t,e,n=e.currentTable){return Ai(t,e,n)?tl(t):sql.ref(t)}function St(t,e,n,r=n.currentTable){let s=Ai(e,n,r)?tl(e):sql.ref(e);return sql`${sql.ref(t)}.${s}`}function Yw(t){return (t?.pg_type??t?.type??"").toLowerCase()}function pd(t,e,n=e.currentTable){if(e.dialect!=="postgres")return false;let r=Yw(nl(t,e,n));return r.endsWith("[]")||r.startsWith("_")||r==="array"}function md(t){let e=[];for(let n of t){if(!/^\d+$/.test(n))return;e.push(`[${Number(n)+1}]`);}return e.join("")}function Lt(t,e,n=e.currentTable){if(e.dialect!=="postgres")return false;let r=e.currentSchema??e.introspection?.default_schema,s=nl(t,e,n,r),i=s?.pg_type??s?.type;return i?e.introspection?.custom_types?.some(o=>o.kind==="composite"&&o.type===i&&(!s?.udt_schema||!o.schema||o.schema===s.udt_schema))??false:false}function hd(t,e){let n=t;for(let r of e)n=sql`(${n}).${tl(r)}`;return n}function gd(t,e,n,r=n.currentTable,s=false){let i=e.replace(/^\$\./,"").split(".").filter(Boolean);if(i.length===0)return de(t,n,r);if(pd(t,n,r)){let l=md(i);if(l)return sql`${de(t,n,r)}${sql.raw(l)}`}if(Lt(t,n,r))return hd(de(t,n,r),i);let o=i.map((l,c)=>({op:c===i.length-1&&s?"->>":"->",key:l})),a=jr(o,"JSON path key");return sql`${de(t,n,r)}${sql.raw(a)}`}function Lr(t,e,n=e.currentTable,r){let{col:s,parts:i}=cn(t),o=r?St(r,s,e,n):de(s,e,n);if(i.length===0)return o;if(pd(s,e,n)){let c=md(i.map(f=>f.key));if(c)return sql`${o}${sql.raw(c)}`}if(Lt(s,e,n))return hd(o,i.map(c=>c.key));let a=e.dialect==="sqlite"?i.map((c,f)=>f===i.length-1?{...c,op:"->>"}:c):i,l=jr(a,"JSON path key");return sql`${o}${sql.raw(l)}`}var Oi={$eq:(t,e,n)=>sql`${k(e)} = ${n}`,$neq:(t,e,n)=>sql`${k(e)} != ${n}`,$gt:(t,e,n)=>sql`${k(e)} > ${n}`,$gte:(t,e,n)=>sql`${k(e)} >= ${n}`,$lt:(t,e,n)=>sql`${k(e)} < ${n}`,$lte:(t,e,n)=>sql`${k(e)} <= ${n}`,$like:(t,e,n)=>sql`${k(e)} like ${n}`,$is:(t,e,n)=>{let r=k(e);return n===Pn?sql`${r} IS NOT NULL`:n===sn?sql`${r} IS UNKNOWN`:n===null?sql`${r} IS NULL`:n===true?sql`${r} IS TRUE`:n===false?sql`${r} IS FALSE`:sql`${r} IS NULL`},$isNot:(t,e,n)=>{let r=k(e);return n===Pn?sql`${r} IS NULL`:n===sn?sql`${r} IS NOT UNKNOWN`:n===null?sql`${r} IS NOT NULL`:n===true?sql`${r} IS NOT TRUE`:n===false?sql`${r} IS NOT FALSE`:sql`${r} IS NOT NULL`},$in:(t,e,n)=>{if(Array.isArray(n)&&n.length===0)return sql`false`;let r=k(e);return Array.isArray(n)?sql`${r} in (${sql.join(n.map(s=>sql`${s}`))})`:sql`${r} in ${n}`},$notIn:(t,e,n)=>{if(Array.isArray(n)&&n.length===0)return sql`true`;let r=k(e);return Array.isArray(n)?sql`${r} not in (${sql.join(n.map(s=>sql`${s}`))})`:sql`${r} not in ${n}`},$isDistinct:(t,e,n)=>sql`${k(e)} is distinct from ${n}`},Pi={$eq:"=",$neq:"!=",$gt:">",$gte:">=",$lt:"<",$lte:"<="};function yd(t){let e=t.replace(/^setof\s+/i,"").trim();return (e.includes(".")?e.slice(e.lastIndexOf(".")+1):e).replace(/^"|"$/g,"").trim()}function rl(t,e,n){let r=t.replace(/^setof\s+/i,"").trim(),s=r.lastIndexOf(".");if(s>=0){let i=r.slice(0,s).replace(/^"|"$/g,"").trim(),o=r.slice(s+1).replace(/^"|"$/g,"").trim();return i===n&&o===e}return r.replace(/^"|"$/g,"").trim()===e}function Ii(t,e,n,r){let s=r??t?.default_schema??"public";return !!t?.columns?.some(i=>i.table===e&&i.name===n&&i.schema===s)}function $i(t,e,n){return !!(t?.tables?.some(r=>r.name===e&&r.schema===n)||t?.views?.some(r=>r.name===e&&r.schema===n))}function Ft(t,e,n,r,s){if(r!=="postgres")return null;let i=t?.functions;if(!i)return null;let o=s??t?.default_schema??"public";for(let a of i){if(a.name!==n||a.schema!==o||a.has_variadic||a.arg_types.length!==1||!rl(a.arg_types[0],e,a.schema)||!$i(t,e,a.schema)||a.return_typtype!=="c")continue;let l=yd(a.return_type);if(rl(a.return_type,l,a.schema)&&$i(t,l,a.schema))return {fnName:a.name,schema:a.schema,targetTable:l,toOne:!a.return_is_setof||a.return_rows===1}}return null}function Fr(t,e,n){let r=t.schema?`${t.schema}.${t.fnName}`:t.fnName;return Pe(r,"computed relationship function reference"),sql`${sql.raw(r)}(${sql.ref(e)})`.as(n)}function Ni(t,e,n,r,s){if(r!=="postgres")return null;let i=t?.functions;if(!i)return null;let o=s??t?.default_schema??"public";for(let a of i)if(a.name===n&&a.schema===o&&!(a.has_variadic||a.arg_types.length!==1)&&rl(a.arg_types[0],e,a.schema)&&$i(t,e,a.schema)&&!(a.return_typtype==="c"&&$i(t,yd(a.return_type),a.schema)))return {fnName:a.name,schema:a.schema};return null}function Di(t,e){let n=t.schema?`${t.schema}.${t.fnName}`:t.fnName;return Pe(n,"computed column function reference"),sql`${sql.raw(n)}(${sql.ref(e)})`}var Xw=new Set(["$like","$ilike","$likeAny","$ilikeAny","$likeAll","$ilikeAll"]);function sl(t){return t!=null&&typeof t=="object"&&t.type==="query"}function un(t,e){if(e.dialect==="postgres"&&e.currentTable&&!t.includes("->")&&!Ii(e.introspection,e.currentTable,t,e.currentSchema)){let r=Ni(e.introspection,e.currentTable,t,e.dialect,e.currentSchema);if(r)return Di(r,e.currentTableAlias??e.currentTable)}return de(t,e)}function ji(t,e){let n=e.db;return t.schema&&(n=n.withSchema(t.schema)),ol(t,e,n)}function Zw(t){return t.includes("->")}function Ed(t,e){let{col:n,parts:r}=cn(t);return r.length===0?de(t,e):Lr(t,e)}function Ee(t,e,n){let r=[];for(let[s,i]of Object.entries(e)){if(s==="$always"){i===false&&r.push(sql`0 = 1`);continue}if(s==="$or"){let o=i;r.push(t.or(o.map(a=>Ee(t,a,n))));}else if(s==="$and"){let o=i;r.push(t.and(o.map(a=>Ee(t,a,n))));}else if(s==="$not")r.push(t.not(Ee(t,i,n)));else if(s==="$exists"){let o=i;r.push(t.exists(ji(o,n)));}else {let o=i,a=Zw(s);for(let[l,c]of Object.entries(o)){if(Ci(c)){let f=Pi[l];if(!f)throw new Error(`Unsupported ref operator: ${l}`);r.push(sql`${a?Ed(s,n):un(s,n)} ${sql.raw(f)} ${de(c.$ref,n)}`);continue}if(l==="$not"){let f=c;for(let[u,d]of Object.entries(f))if(a)r.push(t.not(_d(s,u,d,n)));else {let p=bd(s,u,d,n);if(p){r.push(t.not(p));continue}let g=Sd(s,u,d,n);if(g){r.push(t.not(g));continue}let m=wd(s,u,d,n);if(m){r.push(t.not(m));continue}let h=n.operators[u];if(!h)throw new Error(`Unsupported operator: ${u}`);r.push(t.not(h(t,un(s,n),d)));}}else if(sl(c)){let f=ji(c,n),u=n.operators[l];if(!u)throw new Error(`Unsupported operator: ${l}`);r.push(u(t,un(s,n),f));}else if(a)r.push(_d(s,l,c,n));else {let f=bd(s,l,c,n);if(f){r.push(f);continue}let u=tS(s,l,c,n);if(u){r.push(u);continue}rS(s,l,n);let d=il(s,c,n),p=Sd(s,l,d,n);if(p){r.push(p);continue}let g=wd(s,l,d,n);if(g){r.push(g);continue}let m=n.operators[l];if(!m)throw new Error(`Unsupported operator: ${l}`);r.push(m(t,un(s,n),d));}}}}return r.length===1?r[0]:t.and(r)}function bd(t,e,n,r){if(e!=="$is"&&e!=="$isNot"||n!==sn)return null;let s=Dn(t,r);if(!s)return null;let i=xd(s.pg_type??s.type);if(i==="boolean")return r.dialect!=="sqlite"?null:e==="$is"?sql`${de(t,r)} IS NULL`:sql`${de(t,r)} IS NOT NULL`;throw Object.assign(new Error(`argument of IS UNKNOWN must be type boolean, not type ${i}`),{code:"42804",detail:null})}function Dn(t,e){if(!e.introspection?.columns||!e.currentTable)return null;let n=t.includes("->")?cn(t).col:t,r=e.introspection.columns.filter(i=>i.table===e.currentTable&&i.name===n);if(r.length===0)return null;let s=e.currentSchema;return r.find(i=>!s||i.schema===s)??r.find(i=>["","public"].includes(i.schema??""))??r[0]}var eS={$contains:{sym:"@>",cast:"ltree"},$containedBy:{sym:"<@",cast:"ltree"},$regex:{sym:"~",cast:"lquery"},$iregex:{sym:"~*",cast:"lquery"}};function wd(t,e,n,r){if(r.dialect!=="postgres")return null;let s=eS[e];if(!s)return null;let i=Dn(t,r);if(!i||Ne(i.pg_type,i.type)!=="ltree")return null;let o=`"${(i.udt_schema??"public").replace(/"/g,'""')}"`;return sql`${un(t,r)} OPERATOR(${sql.raw(`${o}.${s.sym}`)}) ${n}::${sql.raw(`${o}.${s.cast}`)}`}function Sd(t,e,n,r){if(r.dialect!=="postgres"||e!=="$textSearch")return null;let s=Dn(t,r);if(!s||Ne(s.pg_type,s.type)==="tsvector")return null;let i=n,o=i.config,a="to_tsquery";i.type==="plain"?a="plainto_tsquery":i.type==="phrase"?a="phraseto_tsquery":i.type==="websearch"&&(a="websearch_to_tsquery");let l=o?sql`to_tsvector(${sql.literal(o)}, ${un(t,r)})`:sql`to_tsvector(${un(t,r)})`,c=o?sql`${sql.raw(a)}(${sql.literal(o)}, ${i.query})`:sql`${sql.raw(a)}(${i.query})`;return sql`${l} @@ ${c}`}function xd(t){switch(t.toLowerCase()){case "bool":return "boolean";case "int8":case "bigserial":case "serial8":return "bigint";case "int4":case "serial":case "serial4":return "integer";case "int2":return "smallint";default:return t.toLowerCase()}}function tS(t,e,n,r){if(r.dialect!=="postgres"||e!=="$eq"&&e!=="$neq"||typeof n!="string"||!/^\s*[[{]/.test(n))return null;let s=Dn(t,r),i=xd(s?.pg_type??s?.type??"");if(i!=="json"&&i!=="jsonb")return null;let o=de(t,r),a=sql`cast(${sql.raw(nS(n))} as ${sql.raw(i)})`;return e==="$eq"?sql`${o} = ${a}`:sql`${o} != ${a}`}function nS(t){return `'${t.replace(/'/g,"''")}'`}function rS(t,e,n){if(!Xw.has(e))return;let r=Dn(t,n);if(!r||Ne(r.pg_type,r.type)!=="color")return;let i=e.includes("ilike")?"~~*":"~~";throw Object.assign(new Error(`operator does not exist: color ${i} unknown`),{code:"42883",detail:null,hint:"No operator matches the given name and argument types. You might need to add explicit type casts."})}function il(t,e,n){if(!n?.currentTable)return e;let r=Dn(t,n);if(!r)return e;let s=Ne(r.pg_type,r.type);if(s==="color")return cd(e);if(s==="isodate"||s==="isodatetext")if(Array.isArray(e))for(let i of e)Za(i);else Za(e);return e}function _d(t,e,n,r){let s=r?Ed(t,r):k(t),o={$eq:"=",$neq:"!=",$gt:">",$gte:">=",$lt:"<",$lte:"<=",$like:"like",$ilike:"ilike"}[e];if(o)return sql`${s} ${sql.raw(o)} ${n}`;if(e==="$is")return n===null?sql`${s} IS NULL`:n===true?sql`${s} IS TRUE`:n===false?sql`${s} IS FALSE`:sql`${s} IS NULL`;if(e==="$isNot")return n===null?sql`${s} IS NOT NULL`:n===true?sql`${s} IS NOT TRUE`:n===false?sql`${s} IS NOT FALSE`:sql`${s} IS NOT NULL`;if(e==="$in"){if(r&&sl(n))return sql`${s} in ${ji(n,r)}`;let a=il(t,n,r);return a.length===0?sql`false`:sql`${s} in (${sql.join(a.map(l=>sql`${l}`))})`}if(e==="$notIn"){if(r&&sl(n))return sql`${s} not in ${ji(n,r)}`;let a=il(t,n,r);return a.length===0?sql`true`:sql`${s} not in (${sql.join(a.map(l=>sql`${l}`))})`}return sql`${s} = ${n}`}function Ur(t,e){let n={};for(let[r,s]of Object.entries(t))r==="$or"||r==="$and"?n[r]=s.map(i=>Ur(i,e)):r==="$not"?n[r]=Ur(s,e):r.startsWith("$")||r.includes(".")?n[r]=s:n[`${e}.${r}`]=s;return n}function it(t){let e=t.leftCols??[t.leftCol],n=t.rightCols??[t.rightCol];return e.map((r,s)=>({leftCol:r,rightCol:n[s]??t.rightCol}))}function al(t,e){return `${t}_${e}_fkey`}function Li(t,e){return e===al(t.table,t.column)}function Td(t){let e=new Map;for(let n of t){let r=n.foreign_key_group??n.foreign_key_name,s=e.get(r);s?s.push(n):e.set(r,[n]);}return [...e.values()]}function Rd(t,e,n){return {leftCol:`${t}.${n.column}`,rightCol:`${e}.${n.ref_column}`,type:"m2o"}}function Cd(t,e,n){return {leftCol:`${e}.${n.column}`,rightCol:`${t}.${n.ref_column}`,type:"o2m"}}function sS(t,e,n){switch(t.kind){case "constraint":case "pg_autogen":case "ref_column":return t.direction==="m2o"?Rd(e,n,t.fk):Cd(e,n,t.fk);case "parent_column":return Rd(e,n,t.fk);case "target_column":return Cd(e,n,t.fk);case "junction_table":return {type:"m2m",junctionTable:t.junctionTable,junctionToParentCols:t.toParent.map(r=>r.column),parentCols:t.toParent.map(r=>r.ref_column),junctionToTargetCols:t.toTarget.map(r=>r.column),targetCols:t.toTarget.map(r=>r.ref_column)}}}function kd(t,e,n,r){let s=r.find(o=>o.foreign_key_name===t&&o.table===e&&o.ref_table===n);if(s)return {kind:"constraint",fk:s,direction:"m2o"};let i=r.find(o=>o.foreign_key_name===t&&o.table===n&&o.ref_table===e);return i?{kind:"constraint",fk:i,direction:"o2m"}:null}function vd(t,e,n,r){let s=r.find(o=>o.table===e&&o.ref_table===n&&Li(o,t));if(s)return {kind:"pg_autogen",fk:s,direction:"m2o"};let i=r.find(o=>o.table===n&&o.ref_table===e&&Li(o,t));return i?{kind:"pg_autogen",fk:i,direction:"o2m"}:null}function Ad(t,e,n,r){let s=r.find(i=>i.table===e&&i.column===t&&i.ref_table===n);return s?{kind:"parent_column",fk:s}:null}function Od(t,e,n,r){let s=r.find(i=>i.table===n&&i.column===t&&i.ref_table===e);return s?{kind:"target_column",fk:s}:null}function Pd(t,e,n,r){let s=r.filter(a=>a.table===t),i=Td(s.filter(a=>a.ref_table===e)),o=Td(s.filter(a=>a.ref_table===n));return i.length===0||o.length===0?null:{kind:"junction_table",junctionTable:t,toParent:i[0],toTarget:o[0]}}function $d(t,e,n,r){let s=r.find(i=>i.table===n&&i.ref_column===t&&i.ref_table===e);return s?{kind:"ref_column",fk:s,direction:"o2m"}:null}function Id(t,e,n,r){let s=r.find(i=>i.table===e&&i.ref_column===t&&i.ref_table===n);return s?{kind:"ref_column",fk:s,direction:"m2o"}:null}var iS=[kd,vd,Ad,Od,Pd,$d,Id];function Nd(t,e,n,r,s={}){let i=s.preferSelfReferenceTargetColumn&&e===n?[kd,vd,Od,Ad,Pd,$d,Id]:iS;for(let o of i){let a=o(t,e,n,r);if(a)return sS(a,e,n)}return null}function Fi(t,e,n,r){t=t.innerJoin(e.junctionTable,s=>{let i=s;for(let o=0;o<e.junctionToTargetCols.length;o++)i=i.onRef(`${e.junctionTable}.${e.junctionToTargetCols[o]}`,"=",`${n}.${e.targetCols[o]}`);return i});for(let s=0;s<e.junctionToParentCols.length;s++)t=t.whereRef(`${e.junctionTable}.${e.junctionToParentCols[s]}`,"=",`${r}.${e.parentCols[s]}`);return t}function Mr(t,e,n,r){if(e.type==="m2m")return Fi(t,e,n,r);for(let{leftCol:s,rightCol:i}of it(e))t=t.whereRef(s,"=",i);return t}function Br(t){return t.foreign_key_name?.endsWith("_fkey")||t.foreign_key_name&&!t.foreign_key_name.startsWith("fk_")?t.foreign_key_name:al(t.table,t.column)}function jn(t,e,n,r,s,i){if(!n||!e||!i.introspection?.foreign_keys)return {qb:t,remainingWhere:e};if(Object.keys(e).length===0||!Ld(e,n))return {qb:t,remainingWhere:e};let o=e;return t=t.where(a=>{let l=Dd(a,e,n,r,s,i);return o=l.remainingWhere,l.expression??sql`1 = 1`}),Object.keys(o).length===Object.keys(e).length?{qb:t,remainingWhere:e}:{qb:t,remainingWhere:o}}function Dd(t,e,n,r,s,i){let o=[],a={};for(let[c,f]of Object.entries(e)){if((c==="$or"||c==="$and")&&Array.isArray(f)){let d=f.map(p=>Dd(t,p,n,r,s,i));if(d.length>0&&d.every(p=>p.fullyHandled&&p.expression)){o.push(c==="$or"?t.or(d.map(p=>p.expression)):t.and(d.map(p=>p.expression)));continue}a[c]=f;continue}let u=oS(t,c,f,n,r,s,i);u?o.push(u):a[c]=f;}let l=o.length===0?null:o.length===1?o[0]:t.and(o);return {expression:l,remainingWhere:a,fullyHandled:l!==null&&Object.keys(a).length===0}}function oS(t,e,n,r,s,i,o){let a=n;if(!a||typeof a!="object")return null;let l="$is"in a&&a.$is===null,c="$isNot"in a&&a.$isNot===null;if(!l&&!c)return null;let f=jd(r,e);if(!f)return null;let u=s?.[e],d=Ft(o.introspection,i,u?.from||e,o.dialect,o.currentSchema);if(d){let w=t.selectFrom(Fr(d,i,d.targetTable)).select(sql`1`.as("_"));if(f.where&&Object.keys(f.where).length>0){let b=jn(w,f.where,f.select,f.join,d.targetTable,o);if(w=b.qb,Object.keys(b.remainingWhere).length>0){let _=Ur(b.remainingWhere,d.targetTable);w=w.where(E=>Ee(E,_,o));}}let S=t.exists(w);return c?S:t.not(S)}let p=xe(i,e,u,o.introspection),{targetTable:g,fkRel:m}=p;if(!m)return null;let h=t.selectFrom(g).select(sql`1`.as("_"));if(u?.on?h=h.where(w=>Ee(w,u.on,o)):h=Mr(h,m,g,i),f.where&&Object.keys(f.where).length>0){let w=jn(h,f.where,f.select,f.join,g,o);if(h=w.qb,Object.keys(w.remainingWhere).length>0){let S=Ur(w.remainingWhere,g);h=h.where(b=>Ee(b,S,o));}}let y=t.exists(h);return c?y:t.not(y)}function jd(t,e){for(let n of t){if(typeof n=="string")continue;let r=n[e];if(r&&re(r))return r}return null}function Ld(t,e){for(let[n,r]of Object.entries(t)){if((n==="$or"||n==="$and")&&Array.isArray(r)){if(r.some(a=>Ld(a,e)))return true;continue}let s=r;if(!s||typeof s!="object")continue;let i="$is"in s&&s.$is===null,o="$isNot"in s&&s.$isNot===null;if((i||o)&&jd(e,n))return true}return false}function re(t){return "select"in t||"spread"in t||"join"in t}function dl(t){if(typeof t=="string")return null;let[e,n]=Object.entries(t)[0]??[];return !e||n===void 0?null:{alias:e,def:n}}function Hr(t){return dl(t)?.def??null}function aS(t,e,n,r){if(t?.hint)return t.hint;if(!n||!r?.foreign_keys)return;let s=t?.from;return s&&s!==e&&r.foreign_keys.some(a=>a.table===n&&a.column===s)?s:r.foreign_keys.some(o=>o.table===n&&o.column===e)?e:void 0}function Fd(t){return t.includes(".")?t.slice(t.lastIndexOf(".")+1):t}function qi(t,e,n,r,s,i=false,o,a){let l=o??s,c=n.dialect==="postgres";if(!e||e.length===0)return c&&l&&(Dr(l,n.introspection,Fe(n))||Mi(l,n))?Ud(t,l,n,new Set,false,s):t.selectAll();for(let f of e)if(typeof f=="string")if(f==="*")if(c&&l&&(Dr(l,n.introspection,Fe(n))||Mi(l,n))){let u=new Set;for(let d of e){if(d===f)break;if(typeof d=="string"&&d!=="*")u.add(d.includes(".")?d.split(".").pop():d);else if(typeof d!="string")for(let[p]of Object.entries(d))u.add(p);}t=Ud(t,l,n,u,i,s);}else t=i&&s?t.selectAll(s):t.selectAll();else if(/^-?\d+(?:\.\d+)?$/.test(f))t=t.select(sql.lit(Number(f)).as("_lit"));else if(wS(f,n,s)){let u=i&&s?St(s,f,n,s):de(f,n,s);t=t.select(sql`json(${u})`.as(f));}else if(c&&l&&s&&!f.includes(".")&&!Ii(n.introspection,l,f,n.currentSchema)){let u=Ni(n.introspection,l,f,n.dialect,n.currentSchema);t=u?t.select(Di(u,s).as(f)):t.select(f);}else if(c&&s&&l&&fd(l,Fd(f),n.introspection,Fe(n))){let u=Fd(f),d=f.includes(".")?sql.ref(f):i?St(s,f,n,s):sql.ref(f);t=t.select(Nr(d,l,u,n.dialect,n.introspection,Fe(n)).as(u));}else t=i&&s&&!f.includes(".")?t.select(St(s,f,n,s).as(f)):!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(f)&&Ai(f,n,s)?t.select(de(f,n,s).as(f)):t.select(f);else for(let[u,d]of Object.entries(f))re(d)?t=qS(t,u,d,n,r,l,a):t=pS(t,u,d,n,s,i,l);return t}function Fe(t){return t.currentSchema??t.introspection?.default_schema??"public"}function Mi(t,e){if(!t||e.dialect!=="postgres"||!e.introspection?.columns)return false;let n=Fe(e);return e.introspection.columns.some(r=>r.table===t&&(r.schema??"public")===n&&Lt(r.name,e,t))}function Ud(t,e,n,r,s=false,i=e){if(!n.introspection)return s?t.selectAll(i):t.selectAll();let o=el(e,n.introspection,Fe(n));if(o.length===0)return s?t.selectAll(i):t.selectAll();for(let{name:a,isDomain:l,domainTypeName:c}of o){if(r.has(a))continue;let f=s?sql`${sql.ref(i)}.${sql.ref(a)}`:sql.ref(a);if(l&&c){let u=vi(f,c);t=t.select((u??f).as(a));}else Lt(a,n,e)?t=t.select(sql`to_jsonb(${f})`.as(a)):t=s?t.select(f.as(a)):t.select(a);}return t}function Wr(t,e,n){let r=n?.dialect==="postgres",s=n?.currentTable;if(!e||e.length===0)return r&&s&&(Dr(s,n.introspection,Fe(n))||Mi(s,n))?Md(t,s,n):t;for(let i of e)if(typeof i=="string")if(i==="*")if(r&&s&&(Dr(s,n.introspection,Fe(n))||Mi(s,n))){let o=new Set;for(let a of e){if(a===i)break;if(typeof a=="string"&&a!=="*")o.add(a.includes(".")?a.split(".").pop():a);else if(typeof a!="string")for(let[l]of Object.entries(a))o.add(l);}t=Md(t,s,n,o);}else t=t.returningAll();else if(r&&s&&Lt(i,n,s))t=t.returning(sql`to_jsonb(${sql.ref(i)})`.as(i));else if(r&&s){let o=sql.ref(i),a=Nr(o,s,i,n.dialect,n.introspection,Fe(n));t=a!==o?t.returning(a.as(i)):t.returning(i);}else t=t.returning(i);else for(let[o,a]of Object.entries(i)){if(re(a))continue;let l=a.column||o;if(r&&s&&!a.cast&&!a.path&&!a.aggregate&&Lt(l,n,s))t=t.returning(sql`to_jsonb(${sql.ref(l)})`.as(o));else if(r&&s&&!a.cast&&!a.path&&!a.aggregate){let c=sql.ref(l),f=Nr(c,s,l,n.dialect,n.introspection,Fe(n));t=f!==c?t.returning(f.as(o)):t.returning(l);}else t=t.returning(l);}return t}function Md(t,e,n,r){if(!n.introspection)return t.returningAll();let s=el(e,n.introspection,Fe(n));if(s.length===0)return t.returningAll();for(let{name:i,isDomain:o,domainTypeName:a}of s)if(!r?.has(i))if(o&&a){let l=sql.ref(i),c=vi(l,a);c?t=t.returning(c.as(i)):t=t.returning(i);}else Lt(i,n,e)?t=t.returning(sql`to_jsonb(${sql.ref(i)})`.as(i)):t=t.returning(i);return t}function Kr(t,e,n,r,s,i=false,o){let a;if(n.aggregate==="count"&&!n.column&&!n.path)a=t.fn.countAll();else {let l=n.column||e;if(n.invalidJsonTextTraversalKey&&r.dialect==="postgres")throw Object.assign(new Error(`operator does not exist: text -> ${cS(n.invalidJsonTextTraversalKey)}`),{code:"42883",detail:null,hint:"No operator matches the given name and argument types. You might need to add explicit type casts."});if(n.path)a=gd(l,n.path,r,s,n.pathText===true);else {let c=s&&i?St(s,l,r,s):de(l,r,s);a=r.dialect==="postgres"&&!n.cast&&!n.preCast&&!n.aggregate?Nr(c,o??s??r.currentTable,l,r.dialect,r.introspection,Fe(r)):c;}n.preCast&&(ln(n.preCast,"pre-cast type"),a=sql`cast(${a} as ${sql.raw(n.preCast)})`),n.aggregate&&(a=sql`${sql.raw(n.aggregate)}(${a})`);}return n.cast&&(ln(n.cast,"cast type"),r.dialect==="sqlite"&&n.pathText===true&&lS(n.cast)||(n.cast.trim().toLowerCase()==="text"&&n.column&&dS(r,s,n.column)?a=ad(a,r.dialect):a=r.dialect==="sqlite"&&(uS(n.cast)||fS(n.cast))?sql`json(${a})`:sql`cast(${a} as ${sql.raw(n.cast)})`)),a}function lS(t){let e=t.trim().toLowerCase();return e==="integer"||e==="int"||e==="int2"||e==="int4"||e==="int8"||e==="bigint"||e==="smallint"}function cS(t){return /^-?\d+$/.test(t)?"integer":"unknown"}function uS(t){let e=t.trim().toLowerCase();return e==="json"||e==="jsonb"}function fS(t){let e=t.trim().toLowerCase();return e.startsWith("_")||e.endsWith("[]")}function dS(t,e,n){let r=e??t.currentTable;if(!r||!t.introspection?.columns)return false;let s=t.introspection.columns.filter(o=>o.table===r&&o.name===n);if(s.length===0)return false;let i=s.find(o=>o.schema===Fe(t))??s.find(o=>o.schema==="public")??s[0];return Ne(i.pg_type,i.type)==="color"}function pS(t,e,n,r,s,i=false,o){return t.select(a=>Kr(a,e,n,r,s,i,o).as(e))}function mS(t){if(!t)return false;for(let e of t)if(typeof e!="string"){for(let n of Object.values(e))if(!re(n)&&n.aggregate)return true}return false}function hS(t){if(!t)return false;for(let e of t)if(typeof e!="string"){for(let n of Object.values(e))if(re(n)&&n.spread&&pl(n.select))return true}return false}function Bd(t){if(!t)return false;for(let e of t)if(typeof e!="string"){for(let n of Object.values(e))if(re(n)&&n.spread)return true}return false}function gS(t){return mS(t)||hS(t)}function pl(t){if(!t)return false;for(let e of t)if(typeof e!="string")for(let n of Object.values(e)){if(re(n)){if(pl(n.select))return true;continue}if(n.aggregate)return true}return false}function ml(t){if(!t)return false;for(let e of t)if(typeof e!="string")for(let n of Object.values(e)){if(re(n)){if(n.spread)continue;if(ml(n.select))return true;continue}if(n.aggregate&&!n.bareCount)return true}return false}function hl(t,e,n,r,s,i=false,o){if(!gS(e))return t;let a=[];for(let l of e){if(typeof l=="string"){if(l==="*")continue;a.push(de(l,n,r));continue}for(let[c,f]of Object.entries(l))re(f)||f.aggregate||a.push(u=>Kr(u,c,f,n,r,i,o));}return yS(a,e,n,r,s),a.length===0?t:t.groupBy(a)}function yS(t,e,n,r,s){if(!(!e||!r||!n.introspection?.foreign_keys)){for(let i of e)if(typeof i!="string")for(let[o,a]of Object.entries(i)){if(!re(a)||!a.spread)continue;let l=a,c=s?.[o],f=xe(r,o,c,n.introspection);if(!f.fkRel||!_t(f))continue;let u=f.targetTable;f.fkRel;let p=Wi(l.select,u,n.introspection)??l.select??[],g=`_spread_${o}`;for(let m of p){if(typeof m=="string"){m!=="*"&&t.push(`${g}.${m}`);continue}let[h,y]=Object.entries(m)[0];re(y)||y.aggregate||t.push(w=>Kr(w,h,y,n,g,true));}}}}function Jd(t,e,n,r,s){if(!t||!e||!r||!s.introspection?.foreign_keys)return t;let i=new Set;for(let o of e)if(typeof o!="string")for(let[a,l]of Object.entries(o)){if(!re(l)||!l.spread)continue;let c=n?.[a],f=xe(r,a,c,s.introspection);f.fkRel&&_t(f)&&i.add(a);}return i.size===0?t:t.map(o=>o.embed&&i.has(o.embed)?{...o,embed:`_spread_${o.embed}`}:o)}function Gd(t,e,n,r){if(!t||!n||!r.introspection?.foreign_keys)return false;for(let s of t)if(typeof s!="string")for(let[i,o]of Object.entries(s)){if(!re(o)||!o.spread)continue;let a=e?.[i],l=xe(n,i,a,r.introspection);if(l.fkRel&&_t(l))return true}return false}function Ln(t){let e=new Map;for(let n of t){let r=n.foreign_key_group??n.foreign_key_name,s=e.get(r);s?s.push(n):e.set(r,[n]);}return [...e.values()]}function qr(t,e,n,r){let s=r==="m2o"?n.map(o=>`${t}.${o.column}`):n.map(o=>`${e}.${o.column}`),i=r==="m2o"?n.map(o=>`${e}.${o.ref_column}`):n.map(o=>`${t}.${o.ref_column}`);return {leftCol:s[0],rightCol:i[0],leftCols:s,rightCols:i,type:r,fk:n[0]}}function gl(t,e,n,r,s=n){let i=s===n?n:`${n} as ${s}`;return e.type==="m2o"?t.leftJoin(i,o=>{let a=o;for(let{leftCol:l,rightCol:c}of it(e)){let[,f]=l.split("."),[,u]=c.split(".");a=a.onRef(`${s}.${u}`,"=",`${r}.${f}`);}return a}):t.leftJoin(i,o=>{let a=o;for(let{leftCol:l,rightCol:c}of it(e)){let[,f]=l.split("."),[,u]=c.split(".");a=a.onRef(`${s}.${f}`,"=",`${r}.${u}`);}return a})}function Hi(t,e,n,r,s){let i=new Set;if(!e||!r.introspection?.foreign_keys)return {sub:t,joined:i};for(let o of e){if(!o.embed||i.has(o.embed))continue;Pe(o.embed,"order embed alias");let a=s?.[o.embed],l=xe(n,o.embed,a,r.introspection);if(l.targetTable!==o.embed&&Pe(l.targetTable,"order embed target"),!l.fkRel||!_t(l)||l.fkRel.type==="m2m")continue;let{targetTable:c,fkRel:f}=l;t=gl(t,f,c,n,o.embed),i.add(o.embed),i.add(c);}return {sub:t,joined:i}}function bS(t){return t&&t.map(e=>e.embed&&e.nullsFirst===void 0?{...e,nullsFirst:e.direction==="desc"}:e)}function Bi(t,e,n){let r=n.includes(".")?n.split(".").pop():n,s=t.introspection?.columns?.find(o=>o.table===e&&o.name===r),i=(s?.pg_type||s?.type||"").toLowerCase();return i==="json"||i==="jsonb"}function wS(t,e,n){return e.dialect==="sqlite"&&n!==void 0&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)&&Bi(e,n,t)}function SS(t,e){if(!t)return false;let n=e.includes(".")?e.split(".").pop():e;return t.some(r=>r.column.includes("->")?r.column.slice(0,r.column.indexOf("->"))===n:false)}function zd(t,e,n,r){return Bi(t,e,n)||SS(r,n)}function _S(t,e,n){if(!t)return null;let r=[];for(let s of t){if(typeof s=="string"){if(s==="*")return null;let l=s.includes(".")?s.split(".").pop():s;r.push({alias:l,asJson:Bi(n,e,l)});continue}let[i,o]=Object.entries(s)[0];if(!i||!o)continue;if(re(o))return null;let a=Bi(n,e,o.column||i);r.push({alias:i,asJson:a});}return r}function ES(t,e,n,r){let s=_S(e,n,r);if(!s||s.length===0)return r.jsonObjectFrom(t);let i=s.flatMap(o=>[sql.lit(o.alias),o.asJson?sql`json(${sql.ref(`obj.${o.alias}`)})`:sql.ref(`obj.${o.alias}`)]);return sql`(select json_object(${sql.join(i)}) from ${t} as obj)`}function Vd(t){if(!t||t.length===0)return false;for(let e of t){if(typeof e=="string")return true;let n=dl(e);if(n&&(!re(n.def)||Vd(n.def.select)))return true}return false}function Qd(t,e,n){return n?n.indexes?.some(i=>i.table===t&&i.unique&&i.columns.length===1&&i.columns[0]===e)||n.unique_constraints?.some(i=>i.table===t&&i.columns.length===1&&i.columns[0]===e)?true:n.primary_keys?.some(i=>i.table===t&&i.columns.length===1&&i.columns[0]===e)??false:false}function xS(t,e,n,r){if(t.type==="m2m")return "many-to-many";if(t.type==="m2o"&&r&&t.fk)return Qd(e,t.fk.column,r)?"one-to-one":"many-to-one";if(t.type==="o2m"&&r&&t.fk){let s={leftCol:`${n}.${t.fk.column}`,rightCol:`${e}.${t.fk.ref_column}`,type:"o2m"};if(ep(r,e,n,void 0,s))return "one-to-one"}return "one-to-many"}function TS(t,e,n){if(!t?.views?.length)return [];let r=n??t.tables?.find(s=>s.name===e)?.schema??t.foreign_keys?.find(s=>s.table===e)?.schema;return t.views.filter(s=>s.name!==e&&s.sql&&RS(s.sql)===e&&(!r||s.schema===r)).map(s=>s.name)}function RS(t){let e=t.match(/\bfrom\s+((?:"[^"]+"|`[^`]+`|\[[^\]]+\]|[\w$]+)(?:\s*\.\s*(?:"[^"]+"|`[^`]+`|\[[^\]]+\]|[\w$]+))?)/i);if(!e)return;let n=e[1].split(/\s*\.\s*/);return n[n.length-1].replace(/^["`[]|["`\]]$/g,"")}function CS(t,e){let n=new Set(e?.views?.map(s=>s.name)??[]),r=t.filter(s=>s.type==="m2m"&&!n.has(s.junctionTable));for(let s of r){if(s.type!=="m2m")continue;let i=s.parentFkGroup?.[0]?.schema;for(let o of TS(e,s.junctionTable,i))t.push({...s,junctionTable:o});}}function kS(t){if(t.type!=="m2m")return null;let e=t.parentFkGroup?.[0]?.foreign_key_name??"",n=t.targetFkGroup?.[0]?.foreign_key_name??"";return `${t.junctionTable}:${e}:${n}`}function qd(t){return t.type!=="m2m"?0:[...t.parentFkGroup??[],...t.targetFkGroup??[]].filter(n=>n.foreign_key_group).length}function vS(t){let e=[],n=new Map;for(let r of t){let s=kS(r);if(!s){e.push(r);continue}let i=n.get(s);if(i===void 0){n.set(s,e.length),e.push(r);continue}qd(r)<qd(e[i])&&(e[i]=r);}return e}function cl(t,e){if(t.type==="m2m")return t.junctionTable;if(t.fk)return Br(t.fk)}function ul(t,e,n,r){if(t.type==="m2m"&&t.parentFkGroup?.[0]&&t.targetFkGroup?.[0]){let a=t.parentFkGroup[0],l=t.targetFkGroup[0];return `${t.junctionTable} using ${Br(a)}(${a.column}) and ${Br(l)}(${l.column})`}if(t.type==="m2m"||!t.fk)return "";let s=Br(t.fk);if(t.type==="o2m"){let a=Ui(t.rightCols??[t.rightCol]),l=Ui(t.leftCols??[t.leftCol]);return `${s} using ${e}(${a}) and ${n}(${l})`}let i=Ui(t.leftCols??[t.leftCol]),o=Ui(t.rightCols??[t.rightCol]);return `${s} using ${e}(${i}) and ${n}(${o})`}function Ui(t){return t.map(e=>e.split(".").at(-1)??e).join(", ")}function AS(t,e,n){if(!t||!e)return null;let r=t.partitions?.find(o=>o.name===e&&(!n||o.schema===n));if(r)return `Perhaps you meant '${r.parent}' instead of '${e}'.`;let s=[];for(let o of t.tables??[])s.push(o.name);for(let o of t.views??[])s.push(o.name);let i=s.find(o=>o.length===e.length+1&&o.startsWith(e));return i?`Perhaps you meant '${i}' instead of '${e}'.`:null}function yl(t,e,n,r){let s=t?.foreign_keys?.find(o=>o.table===e||o.ref_table===e)?.schema||"test",i=r?` using the hint '${r}'`:"";throw new ve({httpStatus:400,code:"PGRST200",message:`Could not find a relationship between '${e}' and '${n}' in the schema cache`,details:`Searched for a foreign key relationship between '${e}' and '${n}'${i} in the schema '${s}', but no matches were found.`,hint:AS(t,n,s)})}function OS(t,e,n,r,s=false){if(!t||!t.foreign_keys)return null;let i=t.foreign_keys.filter(h=>h.is_visible!==false);if(r){let h=Nd(r,e,n,i,{preferSelfReferenceTargetColumn:s});if(h)return h;yl(t,e,n,r);}if(e===n){let h=Ln(i.filter(y=>y.table===n&&y.ref_table===e))[0];if(h)return qr(e,n,h,"o2m")}let o=i.filter(h=>h.table===e&&h.ref_table===n),a=Ln(o),l=i.filter(h=>h.table===n&&h.ref_table===e),c=Ln(l),f=[],u=Ln(i.filter(h=>h.ref_table===e));for(let h of u){let y=h[0].table;if(y===e||y===n)continue;let w=i.filter(S=>S.table===y&&S.ref_table===n);if(w.length!==0)for(let S of Ln(w))f.push({type:"m2m",junctionTable:y,junctionToParentCols:h.map(b=>b.column),parentCols:h.map(b=>b.ref_column),junctionToTargetCols:S.map(b=>b.column),targetCols:S.map(b=>b.ref_column),fk:h[0],parentFkGroup:h,targetFkGroup:S});}if(a.length+c.length+f.length===0)return null;let p=[...f];CS(p,t),p=vS(p);let g=e!==n&&a.length>0&&c.length>0;if(a.length>1||c.length>1||a.length===0&&c.length===0&&p.length>1||g||a.length>0&&p.length>1){let h=[...a.map(E=>qr(e,n,E,"m2o")),...c.map(E=>qr(e,n,E,"o2m")),...p],y={o2m:0,m2o:1,m2m:2},w=[...h].sort((E,x)=>{let O=y[E.type]??3,v=y[x.type]??3;if(O!==v)return O-v;let P=cl(E)??"",C=cl(x)??"",R=P.localeCompare(C);return R!==0?R:ul(E,e,n).localeCompare(ul(x,e,n))}),S=w.map(E=>({cardinality:xS(E,e,n,t),embedding:`${e} with ${n}`,relationship:ul(E,e,n)})),_=w.map(E=>cl(E)).filter(Boolean).map(E=>`'${n}!${E}'`).join(", ");throw new ve({httpStatus:300,code:"PGRST201",message:`Could not embed because more than one relationship was found for '${e}' and '${n}'`,details:S,hint:_?`Try changing '${n}' to one of the following: ${_}. Find the desired relationship in the 'details' key.`:null})}return a.length===1?qr(e,n,a[0],"m2o"):c.length===1?qr(e,n,c[0],"o2m"):f.length===1?f[0]:null}function PS(t,e,n){if(!n?.foreign_keys)return {targetTable:t};let r=n.foreign_keys,s=r.find(l=>l.table===e&&l.column===t);if(s)return {targetTable:s.ref_table,resolvedFkHint:t};let i=r.find(l=>(l.foreign_key_name===t||Li(l,t))&&(l.table===e||l.ref_table===e));if(i)return {targetTable:i.table===e?i.ref_table:i.table,resolvedFkHint:t};let o=r.find(l=>l.ref_table===e&&l.ref_column===t);return o?{targetTable:o.table,resolvedFkHint:t}:n.tables?.some(l=>l.name===t)||n.views?.some(l=>l.name===t)?{targetTable:t}:{targetTable:t}}function $S(t,e,n,r,s){if(!t)return "o2m";if(t.type==="m2m")return "m2m";if(t.type==="m2o"){let i=t.leftCol.split(".")[1];return Qd(e,i,s)?"o2o":"m2o"}return ep(s,e,n,r,t)?"o2o":"o2m"}function xe(t,e,n,r){let s=n?.from||e,{targetTable:i,resolvedFkHint:o}=PS(s,t,r),a=aS(n,e,t,r)??o,l=t===i&&!!(n?.hint&&n.from&&n.from!==e),c=r?.foreign_keys&&t?OS(r,t,i,a,l):null,f=$S(c,t,i,a,r);return {targetTable:i,fkRel:c,cardinality:f,displayHint:a}}function _t(t){return t.cardinality==="m2o"||t.cardinality==="o2o"}function Yd(t,e,n,r){if(!(!t||!n||!r.introspection?.foreign_keys))for(let s of t){if(!s.embed)continue;let i=e?.[s.embed],o=xe(n,s.embed,i,r.introspection);if(o.fkRel&&!_t(o))throw new ve({httpStatus:400,code:"PGRST118",message:`A related order on '${s.embed}' is not possible`,details:`'${n}' and '${s.embed}' do not form a many-to-one or one-to-one relationship`,hint:null})}}function Hd(t,e,n,r,s){let i=e.join??r;if(!e.select||!i)return t;for(let o of e.select){if(typeof o=="string")continue;let a=Object.keys(o)[0],l=o[a];if(!re(l)||!l.select)continue;let c=i[a];if(c?.type!=="inner")continue;let f=Ft(s.introspection,n,c?.from||a,s.dialect,s.currentSchema),u=f?f.targetTable:xe(n,a,c,s.introspection).targetTable;t=t.where(d=>Xd(d,l,u,n,c,l.join??i,s));}return t}function Xd(t,e,n,r,s,i,o){let a=r?Ft(o.introspection,r,s?.from??n,o.dialect,o.currentSchema):null;if(a){let u=t.selectFrom(Fr(a,r,a.targetTable)).select(sql`1`.as("_"));return e.where&&Object.keys(e.where).length>0&&(u=u.where(d=>Ee(d,e.where,{...o,currentTable:a.targetTable}))),r&&(u=Hd(u,e,a.targetTable,i,o)),t.exists(u)}let c=(r?xe(r,s?.from??n,s,o.introspection):null)?.fkRel??null,f=t.selectFrom(n).select(sql`1`.as("_"));if(s?.on)f=f.where(u=>Ee(u,s.on,o));else if(c&&c.type==="m2m")f=Fi(f,c,n,r);else if(c)for(let{leftCol:u,rightCol:d}of it(c))f=f.whereRef(u,"=",d);else r&&(f=f.whereRef(`${n}.${r}_id`,"=",`${r}.id`));return e.where&&Object.keys(e.where).length>0&&(f=f.where(u=>Ee(u,e.where,{...o,currentTable:n}))),r&&(f=Hd(f,e,n,i,o)),t.exists(f)}function Wd(t,e,n,r,s,i){let o=s?.[e],a=i?Ft(r.introspection,i,o?.from||e,r.dialect,r.currentSchema):null,l=a?a.targetTable:i?xe(i,e,o,r.introspection).targetTable:o?.from||e;return t.where(c=>Xd(c,n,l,i,o,s,r))}function Zd(t,e,n){if(!n||t.type!=="o2m")return false;let r=t.leftCol.split(".")[1];return n.indexes?.some(o=>o.table===e&&o.unique&&o.columns.length===1&&o.columns[0]===r)||n.unique_constraints?.some(o=>o.table===e&&o.columns.length===1&&o.columns[0]===r)?true:n.primary_keys?.some(o=>o.table===e&&o.columns.length===1&&o.columns[0]===r)??false}function ep(t,e,n,r,s){if(!t?.foreign_keys||!s||s.type!=="o2m")return false;if(Zd(s,n,t))return true;let o=t.foreign_keys.filter(u=>u.is_visible!==false).filter(u=>u.table===n&&u.ref_table===e);if(r){let u=o.filter(d=>d.foreign_key_name===r);u.length>0&&(o=u);}let a=Ln(o);if(a.length!==1)return false;let l=[...a[0].map(u=>u.column)].sort(),c=t.primary_keys?.find(u=>u.table===n);if(!c?.columns?.length)return false;let f=[...c.columns].sort();return l.length===f.length&&l.every((u,d)=>u===f[d])}function IS(t,e){return t&&t.map(n=>typeof n!="string"||n==="*"||n.includes(".")||/^-?\d+(?:\.\d+)?$/.test(n)?n:`${e}.${n}`)}function Mt(t){if(typeof t=="string")return {colAlias:t,colName:t};let e=Object.keys(t)[0],n=t[e];return {colAlias:e,colName:n?.column||e}}function NS(t,e,n,r,s,i){if(!n.select||!i)return t;let o=s?.[e],a=xe(i,e,o,r.introspection),{targetTable:l,fkRel:c}=a,f=Wi(n.select,l,r.introspection)??n.select;if(!r.introspection?.foreign_keys)return BS(t,f,l,i,c);if(!c)throw new ve({httpStatus:400,code:"PGRST120",message:"Could not embed because the relationship is not a one-to-one or many-to-one",details:null,hint:null});if(!_t(a)){if(pl(n.select))throw new ve({httpStatus:400,code:"PGRST127",message:"Feature not implemented",details:"Aggregates are not implemented for one-to-many or many-to-many spreads.",hint:null});return MS(t,f,n,c,l,i,r)}let u=`_spread_${e}`;if(c.type!=="m2o"&&c.type!=="o2m")throw new ve({httpStatus:400,code:"PGRST120",message:"Could not embed because the relationship is not a one-to-one or many-to-one",details:null,hint:null});let d=it(c).map(({leftCol:m,rightCol:h},y)=>{let[w,S]=m.split("."),[,b]=h.split(".");return {targetSideCol:w===l?S:b,parentSideCol:w===i?S:b,joinKey:`__spread_join_key_${y}`}}),p=[],g=new Set;for(let m of f){if(typeof m=="string"&&m==="*")continue;let h;if(typeof m!="string"){let S=Hr(m);if(!S||re(S))continue;h=S;}let{colAlias:y,colName:w}=Mt(m);p.push({src:w,out:y,def:h}),g.add(w);}t=t.leftJoin(m=>{let h=m.selectFrom(l);for(let{targetSideCol:y,joinKey:w}of d)h=h.select(`${l}.${y} as ${w}`);for(let y of g)h=h.select(`${l}.${y} as ${y}`);return h.as(u)},m=>{let h=m;for(let{joinKey:y,parentSideCol:w}of d)h=h.onRef(`${u}.${y}`,"=",`${i}.${w}`);return h});for(let{out:m,def:h}of p)h?t=t.select(y=>Kr(y,m,h,r,u,true).as(m)):t=t.select(`${u}.${m}`);return t}function DS(t,e,n,r){for(let s of t){if(typeof s=="string")continue;let i=Hr(s);if(!i||!re(i))continue;let{colAlias:o}=Mt(s),a=e.join?.[o],l=xe(n,o,a,r.introspection),c=l.targetTable,f=l.fkRel;if(!f||f.type!=="o2m"||!Zd(f,c,r.introspection))continue;let u=r.introspection?.primary_keys?.find(d=>d.table===c);if(u?.columns?.length)return {nestedTargetTable:c,fkRel:f,pkColumns:u.columns}}return null}function jS(t,e){let n=e.frames[0],{fkRel:r,fromTable:s,parentTable:i,embed:o}=n,a=t.selectFrom(s);if(a=Mr(a,r,s,i),o.where&&Object.keys(o.where).length>0){let c=e.frames.length>1?e.config:{...e.config,currentTable:s};a=a.where(f=>Ee(f,o.where,c));}let l=Hi(a,o.order,s,e.config,o.join);return a=l.sub,o.order&&(a=Ut(a,bS(o.order),void 0,e.config,s)),o.limit!==void 0&&(a=a.limit(o.limit)),o.offset!==void 0&&(a=a.offset(o.offset)),e.tieBreaker&&e.frames.length===1&&(a=gl(a,e.tieBreaker.fkRel,e.tieBreaker.nestedTargetTable,s),a=Ut(a,e.tieBreaker.pkColumns.map(c=>({column:c,embed:e.tieBreaker.nestedTargetTable})),void 0,e.config)),{inner:a,joinedToOne:l.joined}}function LS(t,e,n,r){if(e.frames[0].embed.order||!n.fkRel||n.fkRel.type!=="o2m")return t;let s=e.config.introspection?.primary_keys?.find(i=>i.table===n.fromTable);return s?.columns?.length?Ut(t,s.columns.map(i=>({column:i,embed:n.fromTable})),void 0,e.config):t}function FS(t,e,n){if(n&&re(n)&&!n.spread)return true;let r=t.frames[t.frames.length-1],s=r.embedRel;if(t.frames.length>1&&s&&!_t(s))return true;let{colName:i}=Mt(e);return zd(t.config,r.fromTable,i,t.frames[0].embed.order)}function US(t,e,n,r){let s=Hr(n),{colAlias:i,colName:o}=Mt(n),l=e.frames[r].fromTable;if(r===0&&s&&re(s)&&!s.spread){let c=e.frames[0].embed.join?.[i];return t.select(f=>tp(f,i,s,e.config,c,l).as("value"))}if(s&&!re(s)){let c=r>0?{...s,column:`${l}.${o}`}:s,f=r>0?i:o;return t.select(u=>Kr(u,f,c,e.config,r>0?void 0:l).as("value"))}return t.select(`${l}.${o} as value`)}function fl(t,e,n,r,s){if(r===e.frames.length-1)return US(t,e,n,r);let o=e.frames[r],a=e.frames[r+1];if(!a.fkRel)return t.where(sql`1 = 0`).select(sql`null`.as("value"));let l=a.embedRel;if(!l)return t.where(sql`1 = 0`).select(sql`null`.as("value"));if(_t(l))return s.has(a.fromTable)||(t=gl(t,a.fkRel,a.fromTable,o.fromTable),s.add(a.fromTable)),t=LS(t,e,a),fl(t,e,n,r+1,s);let{colName:c}=Mt(n);return t.select(f=>{let u=f.selectFrom(a.fromTable);return u=Mr(u,a.fkRel,a.fromTable,o.fromTable),u=fl(u,e,n,r+1,new Set),e.config.jsonScalarArrayFrom(u,"value",zd(e.config,a.fromTable,c,e.frames[0].embed.order)).as("value")})}function Kd(t,e,n){let{colAlias:r}=Mt(n),s=Hr(n);return t.select(i=>{let{inner:o,joinedToOne:a}=jS(i,e),l=e.frames[e.frames.length-1];if(e.frames.length>1&&!l.fkRel){let f=o.where(sql`1 = 0`).select(sql`null`.as("value"));return e.config.jsonScalarArrayFrom(f).as(r)}let c=fl(o,e,n,0,a);return e.config.jsonScalarArrayFrom(c,"value",FS(e,n,s)).as(r)})}function MS(t,e,n,r,s,i,o){let a=n.order?null:DS(e,n,s,o),l={frames:[{embed:n,fkRel:r,fromTable:s,parentTable:i}],config:o,tieBreaker:a};for(let c of e){if(typeof c=="string"&&c==="*")continue;let f=Hr(c),u=f!==null&&re(f)&&f.spread,{colAlias:d}=Mt(c);if(u){let p=f,g=n.join?.[d],m=xe(s,d,g,o.introspection),h=Wi(p.select,m.targetTable,o.introspection)??p.select??[],y={...l,frames:[...l.frames,{embed:p,fkRel:m.fkRel,fromTable:m.targetTable,parentTable:s,embedRel:m}]};for(let w of h)typeof w=="string"&&w==="*"||(t=Kd(t,y,w));continue}t=Kd(t,l,c);}return t}function BS(t,e,n,r,s){for(let i of e){if(typeof i=="string"&&i==="*")continue;let{colAlias:o,colName:a}=Mt(i);t=t.select(l=>{let c=l.selectFrom(n).select(`${n}.${a}`);if(s&&s.type!=="m2m")for(let{leftCol:f,rightCol:u}of it(s))c=c.whereRef(f,"=",u);else c=c.whereRef(`${n}.${r}_id`,"=",`${r}.id`);return c=c.limit(1),c.as(o)});}return t}function Wi(t,e,n){if(!t||!n?.columns||!t.some(i=>i==="*"))return t;let r=n.columns.filter(i=>i.table===e).sort((i,o)=>i.ordinal_position-o.ordinal_position).map(i=>i.name);if(r.length===0)return t;let s=[];for(let i of t)if(i==="*")for(let o of r)s.push(o);else s.push(i);return s}function qS(t,e,n,r,s,i,o){let a=s?.[e];if(!Vd(n.select)){if(a?.type==="inner"&&i)return Wd(t,e,n,r,s,i);if(i&&!a?.on&&r.introspection?.foreign_keys&&!Ft(r.introspection,i,a?.from||e,r.dialect,r.currentSchema)){let l=xe(i,e,a,r.introspection);l.fkRel||yl(r.introspection,i,l.targetTable,l.displayHint);}return t}return a?.type==="inner"&&i&&(t=Wd(t,e,n,r,s,i)),n.spread&&i?NS(t,e,n,r,s,i):t.select(l=>tp(l,e,n,r,a,i,o).as(e))}function tp(t,e,n,r,s,i,o){let a=i?Ft(r.introspection,i,s?.from||e,r.dialect,r.currentSchema):null,l=a||!i?{targetTable:a?.targetTable??(s?.from||e),fkRel:null,cardinality:"o2m",displayHint:void 0}:xe(i,e,s,r.introspection),c=l.targetTable,{displayHint:f,fkRel:u}=l,d=i===c,p=d?o?`${c}_nested`:`${c}_self`:c,g=d?`${c} as ${p}`:c,m=a?t.selectFrom(Fr(a,o??i,p)):t.selectFrom(g),h=i&&!s?.on&&!a?u:null,y=h?.type==="m2m",w=Wi(n.select,c,r.introspection),S=y?IS(w,p):w;if(m=qi(m,S,r,n.join,p,y||Bd(S),d?c:p,d?p:void 0),n.where&&Object.keys(n.where).length>0){let x=jn(m,n.where,n.select,n.join,c,r);m=x.qb,Object.keys(x.remainingWhere).length>0&&(m=m.where(O=>Ee(O,x.remainingWhere,{...r,currentTable:c,currentTableAlias:p})));}let b=l.cardinality==="m2m"?"m2m":l.cardinality==="m2o"?"m2o":"o2m";if(s?.on)m=m.where(x=>Ee(x,s.on,r));else if(i&&!a){let x=h;if(x&&x.type==="m2m")b="m2m",m=Fi(m,x,p,i);else if(x?.type==="m2o"){for(let{leftCol:O,rightCol:v}of it(x)){let[,P]=O.split("."),[,C]=v.split("."),R=o?`${o}.${P}`:`${i}.${P}`;m=m.whereRef(`${p}.${C}`,"=",R);}b="m2o";}else if(x){for(let{leftCol:O,rightCol:v}of it(x)){let[,P]=O.split("."),[,C]=v.split("."),R=d?`${p}.${P}`:O,U=o?`${o}.${C}`:d?v.replace(`${c}.`,`${i}.`):v;m=m.whereRef(R,"=",U);}b=x.type;}else r.introspection?.foreign_keys?yl(r.introspection,i,c,f):m=m.whereRef(`${p}.${i}_id`,"=",`${i}.id`);}m=hl(m,S,r,p,void 0,y||Bd(S),d?c:p),n.order?.some(x=>x.embed)&&(m=Hi(m,n.order,c,r,n.join).sub),m=Ut(m,n.order,void 0,r,c),b==="m2m"&&!n.order&&h?.type==="m2m"&&r.dialect==="sqlite"&&(m=m.orderBy(`${h.junctionTable}.${r.rowIdColumn}`,"asc")),n.limit!==void 0&&(m=m.limit(n.limit)),n.offset!==void 0&&(m=m.offset(n.offset)),a?.toOne&&(m=m.limit(1));let _=n.spread?true:a?a.toOne:b==="m2o"||l.cardinality==="o2o";return _&&r.dialect==="sqlite"?ES(m,S,c,r):(_?r.jsonObjectFrom:r.jsonArrayFrom)(m)}function np(t,e,n,r){if(!t||!r.introspection?.foreign_keys)return false;for(let s of t){let i=dl(s);if(!i||!re(i.def))continue;let{alias:o,def:a}=i;if(!a.spread)continue;let l=e?.[o],c=xe(n,o,l,r.introspection);if(c.fkRel&&!_t(c))return true}return false}Fn();function bl(t){return t.startsWith("pg_catalog.")?t.slice(11):t}function GS(t,e,n){let r=n.arg_types.map((s,i)=>`${n.arg_names[i]??""} => ${bl(s)}`);return `${t}.${e}(${r.join(", ")})`}function zS(t){return [...t].sort((e,n)=>{let r=e.arg_types.length-n.arg_types.length;if(r!==0)return r;let s=e.arg_types.map(bl).join(","),i=n.arg_types.map(bl).join(",");return s<i?-1:s>i?1:0})}function sp(t,e,n){return {message:`Could not choose the best candidate function between: ${zS(n).map(i=>GS(t,e,i)).join(", ")}`,details:null,hint:"Try renaming the parameters or the function itself in the database so function overloading can be resolved"}}function op(t,e){let n=t??[],{schema:r,fnName:s,method:i,providedNames:o,inputType:a,paramsType:l}=e,c=n.filter(u=>u.schema===r&&u.name===s);if(c.length===0)return null;if(!(l==="positional"&&o.length===0)){let u=Bt(n,{schema:r,fnName:s,providedNames:o});if(u.length>1)return sp(r,s,c);if(u.length===1)return null}if(i==="POST"&&a!=="text"){let u=c.filter(d=>!d.has_variadic&&d.arg_types.length===1&&d.arg_names.length===0&&(d.arg_types[0]==="json"||d.arg_types[0]==="jsonb"));if(u.length>1)return sp(r,s,u)}return null}function fn(t){let e=t.args;if(e==null)return [];if(Array.isArray(e)){let n=e[0];return n&&typeof n=="object"&&!Array.isArray(n)?Object.keys(n):[]}return typeof e=="object"?"_raw"in e?[]:Object.keys(e):[]}function ap(t){if(!t)return;let e=t.toLowerCase();if(e.includes("application/octet-stream"))return "bytea";if(e.includes("xml"))return "xml";if(e.includes("text/plain"))return "text"}function VS(t,e){let n=new Set(t.arg_names.filter(i=>i!=="")),r=new Set(e);for(let i of e)if(!n.has(i))return false;let s=t.arg_types.length-(t.arg_defaults||0)-(t.has_variadic?1:0);for(let i=0;i<s;i++){let o=t.arg_names[i];if(!o||!r.has(o))return false}return true}function Bt(t,e){let{schema:n,fnName:r,providedNames:s}=e;return t.filter(i=>i.schema===n&&i.name===r&&VS(i,s))}function Ji(t,e){let n=t??[],r=e.paramsType==="positional"&&e.providedNames.length===0&&e.method==="POST"&&e.inputType!=="text",s;if(r)s=[];else if(e.paramsType==="positional"){let i=e.argCount??0;s=n.filter(o=>o.schema===e.schema&&o.name===e.fnName&&o.arg_types.length===i);}else s=Bt(n,{schema:e.schema,fnName:e.fnName,providedNames:e.providedNames});if(s.length===1)return s[0];if(s.length===0&&e.method==="POST"&&e.inputType!=="text"){let i=n.filter(o=>o.schema===e.schema&&o.name===e.fnName&&!o.has_variadic&&o.arg_types.length===1&&o.arg_names.length===0&&(o.arg_types[0]==="json"||o.arg_types[0]==="jsonb"));if(i.length===1)return i[0]}return null}function Gi(t,e){let n=Ji(t,e);if(!n)return null;let r=n.has_out_args||n.return_typtype==="c"||n.return_typtype==="p",s=n.return_type.toLowerCase()==="void"&&!n.has_out_args;return {return_is_setof:n.return_is_setof,return_type:n.return_type,returns_object:r,returns_void:s,volatility:n.volatility}}function lp(t,e){let n=Ji(t?.functions,e);if(!n||n.return_typtype!=="c")return null;let r=n.return_type.replace(/^setof\s+/i,"").trim(),s=(r.includes(".")?r.slice(r.lastIndexOf(".")+1):r).replace(/^"|"$/g,""),i=[...t?.tables??[],...t?.views??[]];return i.find(a=>a.name===s&&a.schema===e.schema)??i.find(a=>a.name===s)?s:null}function QS(t){return [...t].sort().join(", ")}function YS(t){if(t.arg_types.length===0)return null;let e=t.arg_names.filter(n=>n!=="");return e.length!==t.arg_types.length?null:{arity:t.arg_types.length,sig:QS(e)}}function XS(t,e,n,r){let s=r.filter(d=>d.schema===t),i=()=>{let d=[...new Set(s.map(p=>p.name))].filter(p=>p!==e);return Jr(e,d)},o=d=>`Perhaps you meant to call the function ${t}.${d}`,a=d=>`Perhaps you meant to call the function ${t}.${e}(${d})`,l=s.filter(d=>d.name===e).map(YS).filter(d=>d!==null);if(l.length===0){let d=i();return d?o(d):null}if(s.filter(d=>d.name===e).length>1){let d=l.filter(p=>p.arity===n.length);return d.length===1?a(d[0].sig):null}return l[0].sig.split(", ").every(d=>n.includes(d)||Jr(d,n)!==null)?a(l[0].sig):null}function ip(t,e){let{schema:n,fnName:r,method:s,providedNames:i,inputType:o,rawKind:a}=t,l=[...i].sort(),c=s==="POST",f=c&&o==="text",u;f?u=`with a single unnamed ${a??"text"} parameter`:c?u=l.length===0?"without parameters or with a single unnamed json/jsonb parameter":`with ${l.length===1?"parameter":"parameters"} ${l.join(", ")} or with a single unnamed json/jsonb parameter`:u=l.length===0?"without parameters":`with ${l.length===1?"parameter":"parameters"} ${l.join(", ")}`;let d=`Searched for the function ${n}.${r} ${u}, but no matches were found in the schema cache.`,p;l.length>0?p=`${n}.${r}(${l.join(", ")})`:f?p=`${n}.${r}`:p=`${n}.${r} without parameters`;let g=`Could not find the function ${p} in the schema cache`,m=XS(n,r,i,e);return {message:g,details:d,hint:m}}function wl(t,e){let n=t??[],r=n.filter(s=>s.schema===e.schema&&s.name===e.fnName);return r.length===0?ip(e,n):e.paramsType==="positional"&&e.providedNames.length===0||Bt(n,{schema:e.schema,fnName:e.fnName,providedNames:e.providedNames}).length>0||e.method==="POST"&&e.inputType!=="text"&&r.some(i=>!i.has_variadic&&i.arg_types.length===1&&i.arg_names.length===0&&(i.arg_types[0]==="json"||i.arg_types[0]==="jsonb"))||e.inputType==="text"?null:ip(e,n)}function ZS(t,e,n){return t.schema?.get(`${e??"public"}.${n}`)}function _l(t,e,n,r,s={}){if(!t)return t;let i=ZS(e,n,r),o=a=>{let l=e_(a,i,e,n,r),c=s.applyDefaults&&i?i.applyDefaults(l):l;return i?i.serializeRow(c):t_(c,e,n,r)};return Array.isArray(t)?t.map(a=>o(a)):o(t)}function e_(t,e,n,r,s){let i={};for(let[o,a]of Object.entries(t)){let l=e?.get(o)?.context.pgTypeName??pp(n,r,s,o)??void 0;i[o]=n_(a,l,n.dialect);}return i}function t_(t,e,n,r){if(e.dialect!=="sqlite")return t;let s={};for(let[i,o]of Object.entries(t)){let a=pp(e,n,r,i);s[i]=r_(a)?Vi(o):o;}return s}function pp(t,e,n,r){let i=(t.introspection?.columns??[]).filter(l=>l.table===n&&l.name===r);if(i.length===0)return;let o=e??t.introspection?.default_schema??"public",a=i.find(l=>l.schema===o)??i.find(l=>l.schema==="public")??i[0];return Ne(a.pg_type,a.type)}function n_(t,e,n){if(t==null)return t;let r=e?.toLowerCase().trim();if(n!=="sqlite"&&r&&Le(r)){if(r==="color"){if(typeof t=="string"){let i=t.trim();return $n(i.startsWith("#")?i:`#${i}`)}return t}return ud(t,r)}if(typeof t!="string")return t;if(r==="color"){let i=t.trim();return $n(i.startsWith("#")?i:`#${i}`)}if(n!=="sqlite"){let i=Gr(e);return i==="boolean"?cp(t):i==="integer"?zi(t,true):i==="number"?zi(t,false):i==="json"?Sl(t):i==="array"?up(t):t}if(r==="color")return $n(t);if(r==="isodate"||r==="isodatetext")return t.replace(/Z$/,"+00:00");if(r==="unixtz"){let i=Date.parse(t);if(Number.isFinite(i))return Math.trunc(i/1e3)}if(r==="monetary"||r==="monetarytext"){let i=Number(t);return Number.isFinite(i)?i.toFixed(2):t}let s=Gr(e);return s==="boolean"?cp(t):s==="integer"?zi(t,true):s==="number"?zi(t,false):s==="json"?Sl(t):s==="array"?up(t):t}function Gr(t){if(!t)return;let e=t.toLowerCase().trim();if(e.startsWith("_")||e.endsWith("[]"))return "array";if(e==="bool"||e==="boolean")return "boolean";if(["int2","smallint","int4","integer","int","int8","bigint"].includes(e))return "integer";if(["float4","real","float8","double precision","numeric","decimal"].includes(e))return "number";if(e==="json"||e==="jsonb")return "json"}function cp(t){let e=t.trim().toLowerCase();return ["true","t","1","yes","y","on"].includes(e)?true:["false","f","0","no","n","off"].includes(e)?false:t}function zi(t,e){let n=t.trim();if(n==="")return t;let r=Number(n);return !Number.isFinite(r)||e&&!Number.isInteger(r)?t:r}function Sl(t){let e=t.trim();if(e==="")return t;try{return JSON.parse(e)}catch{return t}}function up(t){let e=Sl(t);return Array.isArray(e)?e:t}function r_(t){let e=Gr(t);return e==="json"||e==="array"}var s_=new Set(["text","character","character varying","bpchar","varchar","name","citext"]);function fp(t){let e=t.toLowerCase().trim(),n=e.endsWith("[]")?e.slice(0,-2).trim():e;return !s_.has(n)}function Vi(t){return t==null||typeof t=="string"?t:JSON.stringify(t)}function mp(t,e){let n=e.db;switch(t.schema&&(n=n.withSchema(t.schema),e={...e,currentSchema:t.schema}),t.type){case "query":return ol(t,e,n);case "insert":return o_(t,e,n);case "update":return a_(t,e,n);case "delete":return l_(t,e,n);case "upsert":case "put":return c_(t,e,n);case "rpc":return f_(t,e,n);default:throw t&&"type"in t?(console.error(t),new Error(`Unsupported AST type: ${t.type}`)):new Error("Invalid AST")}}function Ut(t,e,n,r,s){if(!e)return t;for(let i of e){let o=i.embed?(Pe(i.embed,"order embed alias"),i.column.includes("->")?r?Lr(i.column,r,s,i.embed):dp(i.column,i.embed):(Pe(i.column,"order embed column"),r?St(i.embed,i.column,r,s):sql`${sql.ref(i.embed)}.${sql.ref(i.column)}`)):i.column.includes("->")?r?Lr(i.column,r,s,n):dp(i.column,void 0,n):n?r?St(n,i.column,r,s):sql`${sql.ref(n)}.${sql.ref(i.column)}`:r?de(i.column,r,s):i.column,a=i.nullsFirst!==void 0?i.nullsFirst:r?.dialect==="sqlite"?i.direction==="desc":void 0;a!==void 0?t=t.orderBy(o,l=>{let c=i.direction==="desc"?l.desc():l.asc();return a?c.nullsFirst():c.nullsLast()}):t=t.orderBy(o,i.direction||"asc");}return t}function dp(t,e,n){let{col:r,parts:s}=cn(t);if(s.length===0)return sql.ref(t);e&&Pe(r,"order embed column");let i=jr(s,"ORDER BY JSON path key");return e?sql`${sql.ref(e)}.${sql.ref(r)}${sql.raw(i)}`:n?sql`${sql.ref(n)}.${sql.ref(r)}${sql.raw(i)}`:sql`${sql.ref(r)}${sql.raw(i)}`}function zr(t,e,n,r,s){return !e||Object.keys(e).length===0?t:t.where(i=>Ee(i,e,{...n,currentTable:r,currentSchema:s}))}function ol(t,e,n){let r=n.selectFrom(t.from);return hp(r,t,e,t.from)}function hp(t,e,n,r){t=i_(t,e.join,e.select);let s=e.order?.some(f=>f.embed)===true;t=qi(t,e.select,n,e.join,r,s||Gd(e.select,e.join,r,n));let i=e.where??{},{qb:o,remainingWhere:a}=jn(t,i,e.select,e.join,r,n);t=o,t=zr(t,a,n,r,e.schema),t=hl(t,e.select,n,r,e.join),Yd(e.order,e.join,r,n),s&&(t=Hi(t,e.order,r,n,e.join).sub);let l=np(e.select,e.join,r,n)?r:void 0,c=Jd(e.order,e.select,e.join,r,n);return t=Ut(t,c,l,n,r),e.limit!==void 0&&(t=t.limit(e.limit)),e.offset!==void 0&&(t=t.offset(e.offset)),t}function i_(t,e,n){if(!e)return t;let r=new Set;if(n){for(let s of n)if(typeof s!="string")for(let i of Object.keys(s))r.add(i);}for(let[s,i]of Object.entries(e)){if(!i.on||r.has(s))continue;let o=i.from||s,a=i.type==="left"?"leftJoin":"innerJoin";t=t[a](`${o} as ${s}`,l=>gp(l,i.on));}return t}function gp(t,e){for(let[n,r]of Object.entries(e))if(n==="$and")for(let s of r)t=gp(t,s);else {let s=r;for(let[i,o]of Object.entries(s)){let a=Pi[i];if(!a)throw new Error(`Unsupported join operator: ${i}`);Ci(o)?t=t.onRef(n,a,o.$ref):t=t.on(n,a,o);}}return t}function o_(t,e,n){let r=n.insertInto(t.from);if(t.values){let i=_l(t.values,e,t.schema,t.from,{applyDefaults:true});r=r.values(i);}let s=t.from?{...e,currentTable:t.from}:e;return r=Wr(r,t.select,s),r}function a_(t,e,n){let r=n.updateTable(t.from);if(t.values){let i=t.values;Array.isArray(i)&&(i=i.length>0?i[0]:i);let o=_l(i,e,t.schema,t.from);r=r.set(o);}t.limit!==void 0||t.offset!==void 0?r=yp(r,t,e,n):r=zr(r,t.where??{},e,t.from,t.schema);let s=t.from?{...e,currentTable:t.from}:e;return r=Wr(r,t.select,s),r}function l_(t,e,n){let r=n.deleteFrom(t.from);t.limit!==void 0||t.offset!==void 0?r=yp(r,t,e,n):r=zr(r,t.where??{},e,t.from,t.schema);let s=t.from?{...e,currentTable:t.from}:e;return r=Wr(r,t.select,s),r}function yp(t,e,n,r){let i=n.introspection?.primary_keys.find(l=>l.table===e.from)?.columns??[],o=r.selectFrom(e.from),a=n.rowIdColumn;if(i.length>0)for(let l of i)o=o.select(l);else o=o.select(sql.ref(a).as("__rowid"));if(o=zr(o,e.where??{},n,e.from,e.schema),o=Ut(o,e.order,void 0,n,e.from),e.limit!==void 0&&(o=o.limit(e.limit)),e.offset!==void 0&&(o=o.offset(e.offset)),i.length===1)return t.where(i[0],"in",o);if(i.length>1){let l="__ltd_target",c=r.selectFrom(o.as(l)).select(sql`1`.as("_"));for(let f of i)c=c.whereRef(`${l}.${f}`,"=",`${e.from}.${f}`);return t.where(f=>f.exists(c))}else return t.where(sql.ref(a),"in",o)}function c_(t,e,n){let r=t.values,s=_l(r,e,t.schema,t.from,{applyDefaults:true}),i=n.insertInto(t.from).values(s);t.onConflict&&(i=i.onConflict(a=>{let l=t.onConflict.length===1?a.column(t.onConflict[0]):a.columns(t.onConflict);if(t.ignoreDuplicates)return l.doNothing();let c=Array.isArray(s)?s[0]:s,f=Object.keys(c).filter(u=>!t.onConflict.includes(u));return f.length===0?l.doUpdateSet({[t.onConflict[0]]:sql.ref(`excluded.${t.onConflict[0]}`)}):l.doUpdateSet(u=>{let d={};for(let p of f)d[p]=u.ref(`excluded.${p}`);return d})}));let o=t.from?{...e,currentTable:t.from}:e;return i=Wr(i,t.select,o),i}function u_(t,e,n){let r=n.introspection?.functions;if(!r)return null;let s=t.schema??n.introspection?.default_schema??"public",i=Array.isArray(t.args)?fn(t):Object.keys(t.args);if(Bt(r,{schema:s,fnName:e,providedNames:i}).length>0)return null;let o=r.filter(a=>a.schema===s&&a.name===e&&!a.has_variadic&&a.arg_types.length===1&&a.arg_names.length===0&&(a.arg_types[0]==="json"||a.arg_types[0]==="jsonb"));return o.length===1?o[0].arg_types[0]:null}function f_(t,e,n){let r=t.function;Pe(r,"RPC function name");let s=t.schema??e.introspection?.default_schema,i;r.includes(".")?s!==void 0?(Pe(s,"RPC schema"),i=`"${s}"."${r}"`):i=r:(i=s?`${s}.${r}`:r,Pe(i,"RPC function reference"));let o,l=e.dialect==="postgres"&&t.httpMethod==="POST"&&t.inputType!=="text"&&t.args!=null?u_(t,r,e):null;if(l)o=sql`${sql.raw(i)}(${Vi(t.args)}::${sql.raw(l)})`;else if(t.args&&!Array.isArray(t.args)&&Object.keys(t.args).length>0){let u=Object.entries(t.args),d=null,p=null,g=null;if(e.dialect==="postgres"&&e.introspection?.functions){let y=u.map(([S])=>S),w=Bt(e.introspection.functions,{schema:t.schema??e.introspection?.default_schema??"public",fnName:r,providedNames:y});if(w.length===1){let S=w[0];d=new Map;for(let b=0;b<S.arg_names.length;b++)d.set(S.arg_names[b],S.arg_types[b]);if(S.has_variadic&&S.arg_names.length>0){p=S.arg_names[S.arg_names.length-1];let b=S.arg_types[S.arg_types.length-1];g=b.endsWith("[]")?b.slice(0,-2):b;}}}let m=t.httpMethod==="GET",h=u.map(([y,w])=>{if(Pe(y,"RPC param key"),d){let b=d.get(y);if(b){if(y===p&&g){ln(g,"RPC variadic elem type"),Pe(y,"RPC variadic param key");let _=Array.isArray(w)?w:[w];return sql`VARIADIC ${sql.raw(y)} := ${_}::${sql.raw(g+"[]")}`}if(fp(b)){ln(b,"RPC arg type");let _=m&&Array.isArray(w)?w[w.length-1]:w,E=Gr(b),x=E==="json"||E==="array"&&!Array.isArray(_)?Vi(_):_;return sql`${sql.raw(y)} := ${x}::${sql.raw(b)}`}}}let S=m&&Array.isArray(w)?w[w.length-1]:w;return sql`${sql.raw(y)} := ${S}`});o=sql`${sql.raw(i)}(${sql.join(h)})`;}else if(Array.isArray(t.args)&&t.args.length>0){let u=null;if(e.dialect==="postgres"&&e.introspection?.functions){let p=e.introspection.functions,g=t.schema??e.introspection?.default_schema??"public",h=t.args.length,y=p.filter(w=>w.schema===g&&w.name===r&&w.arg_types.length===h);y.length===1&&(u=y[0].arg_types);}let d=t.args.map((p,g)=>{if(u){let m=u[g];if(m&&fp(m)){ln(m,"RPC positional arg type");let h=Gr(m),y=h==="json"||h==="array"&&!Array.isArray(p)?Vi(p):p;return sql`${y}::${sql.raw(m)}`}}return sql`${p}`});o=sql`${sql.raw(i)}(${sql.join(d)})`;}else o=sql`${sql.raw(i)}()`;let c=!!t.join&&Object.keys(t.join).length>0;if(e.dialect==="postgres"&&c){let u=lp(e.introspection,{schema:t.schema??e.introspection?.default_schema??"public",fnName:r,providedNames:fn(t),paramsType:t.paramsType,argCount:Array.isArray(t.args)?t.args.length:void 0,method:t.httpMethod,inputType:t.inputType});if(u)return hp(n.selectFrom(o.as(u)),t,e,u)}let f=n.selectFrom(o.as(r));return f=qi(f,t.select,e),f=zr(f,t.where??{},e,t.from,t.schema),f=Ut(f,t.order,void 0,e,t.from),t.limit!==void 0&&(f=f.limit(t.limit)),t.offset!==void 0&&(f=f.offset(t.offset)),f}var w_=new Kysely({dialect:{createAdapter:()=>new PostgresAdapter,createDriver:()=>new DummyDriver,createIntrospector:t=>new PostgresIntrospector(t),createQueryCompiler:()=>new PostgresQueryCompiler}}),S_={$ilike:(t,e,n)=>sql`${k(e)} ilike ${n}`,$regex:(t,e,n)=>sql`${k(e)} ~ ${n}`,$iregex:(t,e,n)=>sql`${k(e)} ~* ${n}`,$contains:(t,e,n)=>sql`${k(e)} @> ${n}`,$containedBy:(t,e,n)=>sql`${k(e)} <@ ${n}`,$overlaps:(t,e,n)=>sql`${k(e)} && ${n}`,$rangeLt:(t,e,n)=>sql`${k(e)} << ${n}`,$rangeGt:(t,e,n)=>sql`${k(e)} >> ${n}`,$rangeGte:(t,e,n)=>sql`${k(e)} &> ${n}`,$rangeLte:(t,e,n)=>sql`${k(e)} &< ${n}`,$rangeAdjacent:(t,e,n)=>sql`${k(e)} -|- ${n}`,$textSearch:(t,e,n)=>{let r=n,s=r.config||"english",i="to_tsquery";return r.type==="plain"?i="plainto_tsquery":r.type==="phrase"?i="phraseto_tsquery":r.type==="websearch"&&(i="websearch_to_tsquery"),sql`${k(e)} @@ ${sql.raw(i)}(${sql.literal(s)}, ${r.query})`},$eqAny:(t,e,n)=>sql`${k(e)} = any(${n})`,$neqAny:(t,e,n)=>sql`${k(e)} != any(${n})`,$gtAny:(t,e,n)=>sql`${k(e)} > any(${n})`,$gteAny:(t,e,n)=>sql`${k(e)} >= any(${n})`,$ltAny:(t,e,n)=>sql`${k(e)} < any(${n})`,$lteAny:(t,e,n)=>sql`${k(e)} <= any(${n})`,$likeAny:(t,e,n)=>sql`${k(e)} like any(${n})`,$ilikeAny:(t,e,n)=>sql`${k(e)} ilike any(${n})`,$eqAll:(t,e,n)=>sql`${k(e)} = all(${n})`,$neqAll:(t,e,n)=>sql`${k(e)} != all(${n})`,$gtAll:(t,e,n)=>sql`${k(e)} > all(${n})`,$gteAll:(t,e,n)=>sql`${k(e)} >= all(${n})`,$ltAll:(t,e,n)=>sql`${k(e)} < all(${n})`,$lteAll:(t,e,n)=>sql`${k(e)} <= all(${n})`,$likeAll:(t,e,n)=>sql`${k(e)} like all(${n})`,$ilikeAll:(t,e,n)=>sql`${k(e)} ilike all(${n})`,$regexAny:(t,e,n)=>sql`${k(e)} ~ any(${n})`,$iregexAny:(t,e,n)=>sql`${k(e)} ~* any(${n})`,$regexAll:(t,e,n)=>sql`${k(e)} ~ all(${n})`,$iregexAll:(t,e,n)=>sql`${k(e)} ~* all(${n})`};function __(t,e){let n=e.replace(/^\$\./,"").split(".");if(n.length===0)return sql.ref(t);let r=n.map((s,i)=>{let o=i===n.length-1?"->>":"->",a=/^-?\d+$/.test(s);return a||In(s,"JSON path key"),a?`${o}${s}`:`${o}'${s}'`}).join("");return sql`${sql.ref(t)}${sql.raw(r)}`}function E_(t,e="value",n=false){let r=sql.ref(e);return sql`(select coalesce(json_agg(${r}), '[]'::json) from ${t} as _agg)`}var bp={db:w_,operators:{...Oi,...S_},jsonArrayFrom:jsonArrayFrom$1,jsonObjectFrom:jsonObjectFrom$1,jsonScalarArrayFrom:E_,jsonPath:__,rowIdColumn:"ctid"};var x_=/[.*+?[\]{}()|]/;function Qi(t){let e="";for(let n of t)n==="\\"||n==="*"||n==="?"||n==="["?e+=`[${n}]`:e+=n;return e}function wp(t){return t==="\\"||t==="*"||t==="?"||t==="["?`[${t}]`:t}function El(t){let e="";for(let n=0;n<t.length;){let r=t[n];if(r==="\\"){if(n+1>=t.length){e+="[\\\\]",n+=1;continue}e+=wp(t[n+1]),n+=2;continue}if(r==="%"){e+="*",n+=1;continue}if(r==="_"){e+="?",n+=1;continue}e+=wp(r),n+=1;}return e}function Yi(t){return t?x_.test(t)?/^[A-Za-z0-9_\-\\%]+$/.test(t):true:false}function Sp(t){if(t.startsWith("^")&&t.endsWith("$")&&t.length>=2){let e=t.slice(1,-1);return Yi(e)?{mode:"exact",text:Qi(e)}:null}if(t.startsWith("^")){let e=t.slice(1);return Yi(e)?{mode:"prefix",text:Qi(e)}:null}if(t.endsWith("$")){let e=t.slice(0,-1);return Yi(e)?{mode:"suffix",text:Qi(e)}:null}return Yi(t)?{mode:"contains",text:Qi(t)}:null}function _p(t,e){switch(t){case "exact":return e;case "prefix":return `${e}*`;case "suffix":return `*${e}`;case "contains":return `*${e}*`}}function Ep(t,e){switch(t){case "exact":return e;case "prefix":return `${e}%`;case "suffix":return `%${e}`;case "contains":return `%${e}%`}}var P_=new Kysely({dialect:{createAdapter:()=>new SqliteAdapter,createDriver:()=>new DummyDriver,createIntrospector:t=>new SqliteIntrospector(t),createQueryCompiler:()=>new SqliteQueryCompiler}});function $_(t,e){let n=e.replace(/^\$\./,"").split(".");if(n.length===0)return sql.ref(t);let r=n.map((s,i)=>{let o=i===n.length-1?"->>":"->",a=/^-?\d+$/.test(s);return a||In(s,"JSON path key"),a?`${o}${s}`:`${o}'${s}'`}).join("");return sql`${sql.ref(t)}${sql.raw(r)}`}function I_(t,e){let n=k(t);if(e.length===0)return sql`(${n} is not null)`;let r=sql.join(e.map(s=>sql`${s}`));return sql`(${n} is not null and (select count(distinct value) from json_each(${n}) where value in (${r})) = ${sql.lit(e.length)})`}function N_(t,e){let n=k(t),r=Object.keys(e);if(r.length===0)return sql`${n} is not null`;let s=r.map(i=>(In(i,"JSON object key"),sql`json_extract(${n}, ${sql.raw(`'$.${i}'`)}) = ${e[i]}`));return sql`(${n} is not null and ${sql.join(s,sql` and `)})`}var D_=new Set(["a","an","and","are","as","at","be","by","for","from","in","is","it","of","on","or","that","the","to","was","with"]);function j_(t){let e=t.toLowerCase().replace(/'/g,"''");return e.endsWith("s")&&!e.endsWith("ss")&&e.length>3&&(e=e.slice(0,-1)),e.length===7?e.slice(0,4):e.length>6?e.slice(0,6):e}function xp(t,e,n){let r=j_(e);if(!r)return sql`1 = 1`;let i=n!=null&&n!=="english"&&n!=="simple"&&r.length>=5?`%'${r}%':%`:`%'${r}':%`;return sql`lower(${t}) like ${i}`}function L_(t){try{return decodeURIComponent(t.replace(/\+/g," "))}catch{return t}}function xl(t,e){let n=k(t),r=L_(e.query).trim();if(!r)return sql`1 = 1`;if(e.type==="websearch"){let o=r.split(/\s+or\s+/i).map(l=>l.trim()).filter(Boolean);if(o.length>1){let l=o.map(c=>xl(t,{...e,query:c,type:"plain",config:e.config}));return sql`(${sql.join(l,sql` or `)})`}let a=r.split(/\s+and\s+/i).map(l=>l.trim()).filter(Boolean);if(a.length>1){let l=a.map(c=>xl(t,{...e,query:c,type:"plain",config:e.config}));return sql`(${sql.join(l,sql` and `)})`}}if(r.includes("|")&&e.type!=="phrase"&&e.type!=="plain"){let o=r.split("|").map(a=>a.trim()).filter(Boolean);return o.length===0?sql`1 = 1`:sql`(${sql.join(o.map(a=>xp(n,a,e.config)),sql` or `)})`}let s=r.split(/\s+/).map(o=>o.trim()).filter(Boolean);if((e.type==="phrase"||e.type==="plain")&&(s=s.filter(o=>!D_.has(o.toLowerCase()))),s.length===0)return sql`1 = 1`;let i=sql` and `;return sql`(${sql.join(s.map(o=>xp(n,o,e.config)),i)})`}function Tl(t,e){return sql`${k(t)} GLOB ${e}`}function F_(t,e){let n=k(t);return sql`json(${n}) = json(${JSON.stringify(e)})`}function U_(t,e){let n=k(t);return Array.isArray(e)||e!==null&&typeof e=="object"?sql`json(${n}) is distinct from json(${JSON.stringify(e)})`:sql`${n} is distinct from ${e}`}function Tp(t,e,n){if(typeof e!="string")throw new Error(`$${n?"iregex":"regex"} on sqlite requires a string value`);let r=Sp(e);if(!r)throw new Error(`Unsupported operator: $${n?"iregex":"regex"}`);if(n){let i=Ep(r.mode,r.text),o=k(t);return sql`lower(${o}) like lower(${i}) escape '\\'`}let s=_p(r.mode,r.text);return Tl(t,s)}function Xi(t,e,n,r){if(!Array.isArray(e))throw new Error(`$${n}${r} on sqlite requires an array value`);if(e.length===0)return r==="any"?sql`false`:sql`true`;let s=k(t),i=e.map(o=>n==="ilike"?sql`lower(${s}) like lower(${o})`:Tl(t,typeof o=="string"?El(o):o));return sql`(${sql.join(i,r==="any"?sql` or `:sql` and `)})`}var M_={$eq:(t,e,n)=>Array.isArray(n)||n!==null&&typeof n=="object"?F_(e,n):sql`${k(e)} = ${n}`,$neq:(t,e,n)=>Array.isArray(n)||n!==null&&typeof n=="object"?sql`json(${k(e)}) != json(${JSON.stringify(n)})`:sql`${k(e)} != ${n}`,$textSearch:(t,e,n)=>xl(e,n),$like:(t,e,n)=>{if(typeof n!="string")throw new Error("$like on sqlite requires a string value");return Tl(e,El(n))},$regex:(t,e,n)=>Tp(e,n,false),$iregex:(t,e,n)=>Tp(e,n,true),$ilike:(t,e,n)=>sql`lower(${k(e)}) like lower(${n})`,$likeAny:(t,e,n)=>Xi(e,n,"like","any"),$ilikeAny:(t,e,n)=>Xi(e,n,"ilike","any"),$likeAll:(t,e,n)=>Xi(e,n,"like","all"),$ilikeAll:(t,e,n)=>Xi(e,n,"ilike","all"),$isDistinct:(t,e,n)=>U_(e,n),$contains:(t,e,n)=>{if(Array.isArray(n))return I_(e,n);if(n!==null&&typeof n=="object")return N_(e,n);throw new Error("$contains on sqlite requires an array or object value")},$containedBy:(t,e,n)=>{if(!Array.isArray(n))throw new Error("$containedBy on sqlite requires an array value");let r=k(e),s=n.length===0?sql`${r} is not null and not exists (select 1 from json_each(${r}))`:sql`${r} is not null and not exists (select 1 from json_each(${r}) where value not in (${sql.join(n.map(i=>sql`${i}`))}))`;return sql`(case when ${r} is null then null else (${s}) end)`},$overlaps:(t,e,n)=>{if(!Array.isArray(n))throw new Error("$overlaps on sqlite requires an array value");let r=k(e);if(n.length===0)return sql`1 = 0`;let s=sql.join(n.map(i=>sql`${i}`));return sql`(${r} is not null and exists (select 1 from json_each(${r}) where value in (${s})))`}};function B_(t,e="value",n=false){let r=sql.ref(e),s=n?sql`json_group_array(json(${r}))`:sql`json_group_array(${r})`;return sql`(select coalesce(${s}, json('[]')) from ${t} as _agg)`}var Rp={db:P_,operators:{...Oi,...M_},jsonArrayFrom:jsonArrayFrom,jsonObjectFrom:jsonObjectFrom,jsonScalarArrayFrom:B_,jsonPath:$_,rowIdColumn:"rowid"};function q_(t){switch(t){case "postgres":return bp;case "sqlite":return Rp;default:throw new Error(`Unsupported dialect: ${t}`)}}function te(t,e="postgres",n){let r=q_(e),s=n&&"introspection"in n?n:{db:n,introspection:void 0};return mp(t,{...r,dialect:e,db:s.db??r.db,introspection:s.introspection,schema:s.schema})}var cc=ca(Cl());Yr();function T(t,e,n,r,s){let i=JSON.stringify({code:e,details:r,hint:s,message:n}),o=new TextEncoder().encode(i);return new Response(o,{status:t,headers:{"Content-Type":"application/json; charset=utf-8","Content-Length":String(o.byteLength)}})}function ot(t){return T(t.status,t.code,t.message,t.details??null,t.hint??null)}async function Hp(t,e){if(!t||!t.startsWith("Bearer "))return e.anonymousEnabled?{kind:"ok",payload:null}:{kind:"error",response:ot({status:401,code:"PGRST302",message:"Anonymous access is disabled"})};let n=t.slice(7).trim(),r=n.split(".");if(r.length!==3||r.some(s=>s.length===0))return e.anonymousEnabled?{kind:"ok",payload:null}:{kind:"error",response:ot({status:401,code:"PGRST301",message:`Expected 3 parts in JWT; got ${Math.max(1,r.filter(s=>s.length>0).length)}`})};if(!e.jwtSecret)return {kind:"error",response:ot({status:500,code:"PGRST300",message:"Server lacks JWT secret"})};try{let s=new TextEncoder().encode(e.jwtSecret),{payload:i}=await jwtVerify(n,s,{algorithms:["HS256"]});return typeof i.iat=="number"&&i.iat>Math.floor(Date.now()/1e3)?{kind:"error",response:ot({status:401,code:"PGRST303",message:"JWT issued at future"})}:{kind:"ok",payload:i}}catch(s){return s instanceof errors.JWTExpired?{kind:"error",response:ot({status:401,code:"PGRST303",message:"JWT expired"})}:{kind:"error",response:ot({status:401,code:"PGRST301",message:"No suitable key or wrong key type",details:"None of the keys was able to decode the JWT"})}}}Xl();function vE(t,e,n,r){if(n){let i=t.get(`${n}.${e}`);if(i)return i}let s=t.get(`${r}.${e}`);if(s)return s;for(let[i,o]of t)if(i.endsWith(`.${e}`))return o}function AE(t,e){let n=t.schema||"public",r=Xa(t,e);return {schema:n,table:t.table,column:t.name,pgTypeName:r,nullable:t.nullable,defaultValue:t.default_value??null,isPrimaryKey:t.is_primary_key,isUnique:false,isSerial:!!t.is_identity,isGenerated:t.is_generated}}function Vp(t,e){let n=AE(t,e);return Le(n.pgTypeName)?dd(n)??We(n):We(n)}function OE(t,e="sqlite"){let n=new Map;for(let r of t.columns){let s=r.schema||"public",i=`${s}.${r.table}`,o=n.get(i);o||(o=new at(r.table,s),n.set(i,o)),o.set(r.name,Vp(r,t));}return n}function PE(t,e){for(let n of e.columns){if(!Le(Xa(n,e)))continue;let r=n.schema||"public",s=`${r}.${n.table}`,i=t.get(s);i||(i=new at(n.table,r),t.set(s,i)),i.set(n.name,Vp(n,e));}return t}function Qp(t,e,n){if(n==="sqlite")return OE(e,n);if(n==="postgres"||n==="pglite"){let r=t&&t.size>0?t:new Map;return PE(new Map(r),e)}return t&&t.size>0?t:new Map}function Yp(t,e){let n=t.config?.translation?.schemas;return e.schema??n?.defaultSchema??"public"}function Xp(t,e,n,r){return !n||!e?.from?t:t.map(s=>Zl(s,e.select,e.from,e.schema,e.join,n,r))}function Zl(t,e,n,r,s,i,o){let a=vE(i,n,r,o),l=IE(e,s),c={};for(let[f,u]of Object.entries(t)){let d=l.get(f);if(d&&"embed"in d){let m=d.embed;c[f]=$E(u,m,r,i,o);continue}let p=d?.sourceColumn??f,g=a?.get(p);c[f]=g?.isShimBacked?g.deserialize(u):u;}return c}function $E(t,e,n,r,s){return Array.isArray(t)?t.map(i=>i&&typeof i=="object"?Zl(i,e.select,e.table,n,e.join,r,s):i):t&&typeof t=="object"?Zl(t,e.select,e.table,n,e.join,r,s):t}function IE(t,e){let n=new Map;if(!t)return n;for(let r of t){if(typeof r=="string"){if(r==="*")continue;n.set(r,{sourceColumn:r});continue}if(!(!r||typeof r!="object"))for(let[s,i]of Object.entries(r))if(NE(i)){let o=e?.[s]?.from??s;n.set(s,{embed:{table:o,select:i.select,join:i.join}});}else {let o=i;if(o.cast||o.path||o.aggregate)continue;n.set(s,{sourceColumn:o.column??s});}}return n}function NE(t){return t!=null&&typeof t=="object"&&("select"in t||"where"in t||"order"in t||"limit"in t||"offset"in t||"spread"in t||"join"in t)}var Bn=class extends Error{constructor(n,r){super(`Could not find the table '${[n,r].filter(Boolean).join(".")}' in the schema cache`);this.schema=n;this.relation=r;}},ec=class{constructor(e){this.config=e;}kysely;introspection;async translateDdl(e){return e}async clearSchemaCache(){this.introspection=void 0,await this.deleteCachedIntrospection();}async readCachedIntrospection(e){if(typeof this.introspection=="object"&&e?.useCache===true)return this.introspection;if(e?.useCache!==true||!this.config.schemaCache)return;let n=await this.config.schemaCache?.get(this.schemaCacheKey());if(n)try{return this.introspection=JSON.parse(n),this.introspection}catch{await this.deleteCachedIntrospection();return}}async writeCachedIntrospection(e,n){this.introspection=e,n?.useDriver===true&&await this.config.schemaCache?.set(this.schemaCacheKey(),JSON.stringify(e));}async deleteCachedIntrospection(){await this.config.schemaCache?.delete(this.schemaCacheKey());}schemaCacheKey(){return ["@supabase/lite","schema-cache",this.dialect,this.config.introspection?.name??"",this.config.url??""].join(":")}async exec(e,...n){try{return sql(e,...n??[]).execute(this.kysely)}catch(r){throw console.error(r),new Error(`Failed to execute query: ${e}`)}}async ping(){try{let e=await this.exec("SELECT 1");return e&&Array.isArray(e.rows)&&e.rows.length===1}catch{return false}}async transaction(e,n){throw new Error("This Connection does not support transactions")}async runInTransaction(e){return this.kysely.transaction().execute(n=>e(n))}createMigrator(e){throw new Error("This Connection does not support migrations")}async onPostgrestAST(e,n){return e}deserializeRow(e){return e}normalizeDbError(e){return e}async withContext(e,n,r){return n(this.kysely)}get supportsRpc(){return false}async viewOptionsMetadata(e,n){return null}};function Et(t){return JSON.stringify(t,(e,n)=>typeof n=="bigint"?Number.parseInt(n.toString(),10):n)}var Zp=/application\/vnd\.pgrst\.plan(?:\+(json|text))?/i;function em(t){let e=t.match(Zp);if(!e)return null;let n=e[1]?.toLowerCase()==="json"?"json":"text",r=t.match(/;\s*options=([^;]+)/i),s=r?`; options=${r[1].trim()}`:"";return {format:n,optionsSegment:s}}function tm(t){return Zp.test(t)}function nm(t){return /;\s*nulls\s*=\s*stripped/i.test(t)}function pn(t){if(Array.isArray(t))return t.map(e=>pn(e));if(t!==null&&typeof t=="object"){let e={};for(let[n,r]of Object.entries(t))r!==null&&(e[n]=pn(r));return e}return t}function io(t,e){if(!e||e.length===0)return t;let n=(r,s)=>{for(let i of e){if(i.embed)continue;let o=r[i.column],a=s[i.column],l=o==null,c=a==null;if(l&&c)continue;if(l)return i.nullsFirst?-1:1;if(c)return i.nullsFirst?1:-1;let f;if(typeof o=="number"&&typeof a=="number"?f=o-a:f=String(o).localeCompare(String(a)),f!==0)return i.direction==="desc"?-f:f}return 0};return [...t].sort(n)}function jE(t,e){return !e||e.length===0?t:t.map(n=>ic(n,e))}function rm(t,e,n){if(!e||e.length===0||t.length===0)return t;let r=jE(t,e);return r=FE(r,e),r=UE(r,e),r=ME(r,e),n==="sqlite"&&(r=BE(r,e),r=LE(r,e)),r}function LE(t,e){if(!e||e.length===0)return t;let n=qE(e);return n.size===0?t:t.map(r=>{if(!Hn(r))return r;let s={...r};for(let i of n){let o=s[i];o!==null&&typeof o=="object"&&(s[i]=JSON.stringify(o));}return s})}function FE(t,e){return !e||e.length===0?t:t.map(n=>nc(n,e))}function UE(t,e){return !e||e.length===0?t:t.map(n=>rc(n,e))}function ME(t,e){return !e||e.length===0?t:t.map(n=>sc(n,e))}function BE(t,e){return !e||e.length===0?t:t.map(n=>tc(n,e))}function qE(t){let e=new Set;for(let n of t){if(typeof n=="string")continue;let[r,s]=Object.entries(n)[0]??[];if(!r||!s)continue;let i=s;i.path&&i.pathText&&!sm(i.cast)&&e.add(r);}return e}function sm(t){let e=t?.trim().toLowerCase();return e==="json"||e==="jsonb"}function HE(t){let e=t?.trim().toLowerCase();return e==="integer"||e==="int"||e==="int2"||e==="int4"||e==="int8"||e==="bigint"||e==="smallint"}function tc(t,e){if(Array.isArray(t))return t.map(r=>tc(r,e));if(!Hn(t))return t;let n={...t};for(let r of e){if(typeof r=="string")continue;let[s,i]=Object.entries(r)[0]??[];if(!s||!i)continue;if(fs(i)){s in n&&i.select&&(n[s]=tc(n[s],i.select));continue}let o=i;if(!o.path||o.pathText!==true||!HE(o.cast)||!(s in n))continue;let a=n[s];if(a==null)continue;let l=String(a);if(!/^-?\d+$/.test(l))throw new An(l);n[s]=Number.parseInt(l,10);}return n}function ic(t,e){if(Array.isArray(t))return t.map(r=>ic(r,e));if(!Hn(t))return t;let n={...t};for(let r of e){if(typeof r=="string")continue;let[s,i]=Object.entries(r)[0]??[];!s||!i||!fs(i)||s in n&&(n[s]=KE(n[s],i.select));}return n}function nc(t,e){if(Array.isArray(t))return t.map(r=>nc(r,e));if(!Hn(t))return t;let n={...t};for(let r of e){if(typeof r=="string")continue;let[s,i]=Object.entries(r)[0]??[];if(!s||!i)continue;if(fs(i)){s in n&&i.select&&(n[s]=nc(n[s],i.select));continue}let o=i;o.aggregate==="avg"&&o.cast!=="text"&&s in n&&(n[s]=WE(n[s]));}return n}function rc(t,e){if(Array.isArray(t))return t.map(r=>rc(r,e));if(!Hn(t))return t;let n={...t};for(let r of e){if(typeof r=="string")continue;let[s,i]=Object.entries(r)[0]??[];if(!s||!i)continue;if(fs(i)){s in n&&i.select&&(n[s]=rc(n[s],i.select));continue}sm(i.cast)&&s in n&&(n[s]=im(n[s]));}return n}function sc(t,e){if(Array.isArray(t))return t.map(r=>sc(r,e));if(!Hn(t))return t;let n={...t};for(let r of e){if(typeof r=="string")continue;let[s,i]=Object.entries(r)[0]??[];if(!s||!i)continue;if(fs(i)){s in n&&i.select&&(n[s]=sc(n[s],i.select));continue}let o=i;o.path&&!o.pathText&&s in n&&(n[s]=im(n[s]));}return n}function WE(t){if(typeof t!="string")return t;let e=t.trim();if(!/^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i.test(e))return t;let n=Number(e);return !Number.isFinite(n)||e.replace(/^[+-]/,"").replace(/e[+-]?\d+$/i,"").replace(".","").replace(/^0+/,"").replace(/0+$/,"").length>15?t:n}function KE(t,e){let n=JE(t);return !e||e.length===0?n:ic(n,e)}function JE(t){if(typeof t!="string")return t;let e=t[0];if(e!=="["&&e!=="{")return t;try{return JSON.parse(t)}catch{return t}}function im(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}function Hn(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function fs(t){return t!==null&&typeof t=="object"&&("select"in t||"spread"in t||"join"in t)}var GE=new Set(["*/*","application/*","application/json","application/vnd.pgrst.object","application/vnd.pgrst.object+json","application/vnd.pgrst.array","application/vnd.pgrst.array+json","application/octet-stream","text/csv"]);function om(t){let e=em(t);return e?`application/vnd.pgrst.plan+${e.format}; for="application/json"${e.optionsSegment}`:t}function am(t,e){let n=t.split(",").map(r=>r.split(";")[0].trim().toLowerCase()).filter(Boolean);if(n.length===0)return true;for(let r of n)if(GE.has(r)||e&&r.startsWith("application/vnd.pgrst.plan"))return true;return false}function lm(t,e){let n=em(t)??{format:"text",optionsSegment:""},r=`application/vnd.pgrst.plan+${n.format}; for="application/json"${n.optionsSegment}; charset=utf-8`,s=n.format==="json"?Et({sql:e.sql,parameters:[...e.parameters]}):e.sql;return new Response(s,{status:200,headers:{"Content-Type":r}})}function lt(t,e,n){let r=t+e-1,s=n!==void 0?`${n}`:"*";return `${t}-${r}/${s}`}function cm(t,e){let n=e.startsWith("?")?e.slice(1):e;if(!n)return;let s=[...new URLSearchParams(n).entries()].sort(([o],[a])=>o.localeCompare(a)),i=new URLSearchParams(s).toString();return i?`${t}?${i}`:t}async function qn(t,e,n,r){if(e.type==="rpc"){let f={...e,order:void 0,limit:void 0,offset:void 0},u=te(f,n,{db:t,introspection:r}),{sql:d,parameters:p}=u.compile(),g=`SELECT count(*) as __count FROM (${d}) AS __inner_count`,m=await t.executeQuery({sql:g,parameters:p,query:{kind:"RawNode"}});return Number(m.rows?.[0]?.__count??0)}let s=e.join&&Object.values(e.join).some(f=>f.type==="inner"),i=zE(e);if(s||i){let f={...e,type:"query",order:void 0,limit:void 0,offset:void 0},u=te(f,n,{db:t,introspection:r}),{sql:d,parameters:p}=u.compile(),g=`SELECT count(*) as __count FROM (${d}) AS __inner_count`,h=(await t.executeQuery({sql:g,parameters:p,query:{kind:"RawNode"}})).rows?.[0];return Number(h?.__count??0)}let o={...e,type:"query",select:[{__count:{aggregate:"count"}}],order:void 0,limit:void 0,offset:void 0,join:void 0},l=await te(o,n,{db:t,introspection:r}).execute(),c=Array.isArray(l)?l[0]:l;return Number(c?.__count??0)}async function oc(t,e,n,r){if(e.$meta?.count!=="planned"&&e.$meta?.count!=="estimated"||n!=="postgres"||e.type==="rpc")return qn(t,e,n,r);let s={...e,type:"query",order:void 0,limit:void 0,offset:void 0},o=te(s,n,{db:t,introspection:r}).compile(),c=(await t.executeQuery({sql:`EXPLAIN (FORMAT JSON) ${o.sql}`,parameters:o.parameters,query:{kind:"RawNode"}})).rows?.[0]?.["QUERY PLAN"],f=Array.isArray(c)&&c[0]&&typeof c[0]=="object"?c[0].Plan:void 0,u=f&&typeof f=="object"?Number(f["Plan Rows"]):Number.NaN;return Number.isFinite(u)?u:qn(t,e,n,r)}function zE(t){if(t.type!=="query"||!t.where||!t.select)return false;let e=VE(t.select);return e.size===0?false:um(t.where,e)}function um(t,e){for(let[n,r]of Object.entries(t)){if((n==="$or"||n==="$and")&&Array.isArray(r)){if(r.some(i=>i&&typeof i=="object"&&um(i,e)))return true;continue}if(!e.has(n)||!r||typeof r!="object")continue;let s=r;if(s.$is===null||s.$isNot===null)return true}return false}function VE(t){let e=new Set;for(let n of t){if(typeof n=="string")continue;let[r,s]=Object.entries(n)[0]??[];r&&s&&typeof s=="object"&&"select"in s&&e.add(r);}return e}function ac(t){return t?.count==="exact"||t?.count==="planned"||t?.count==="estimated"}function Ht(t,e,n){return ac(e)?`*/${n??0}`:t.type==="update"&&n!==0?lt(0,n??1,void 0):"*/*"}function fm(t,e,n,r){return e&&(t.type==="insert"||t.type==="upsert"||t.type==="delete")?r!==void 0?`*/${r}`:"*/*":lt(n,1,r)}var QE=/[",\n\r ]/;function dm(t){if(t==null)return "";let e;return typeof t=="string"?e=t:typeof t=="number"||typeof t=="boolean"?e=String(t):typeof t=="bigint"?e=t.toString():e=JSON.stringify(t),QE.test(e)?`"${e.replace(/"/g,'""')}"`:e}function oo(t,e){let n=t.length>0?Object.keys(t[0]):[];if(n.length===0)return "";let r=[n.map(s=>dm(s)).join(",")];for(let s of t)r.push(n.map(i=>dm(s[i])).join(","));return r.join(`
81
- `)}function pm(t){return t.split(",").map(n=>n.split(";")[0].trim().toLowerCase()).includes("text/csv")}function gm(t){return t==null?[]:Array.isArray(t)?t.map(e=>ds(e)?new Set(Object.keys(e)):new Set):ds(t)?[new Set(Object.keys(t))]:[]}function ym(t,e,n){return !e?.length||!n?.length||t.length===0?t:t.map((r,s)=>{let i=n[s]??n[0],o={...r};for(let a of e)i.has(a)||(o[a]=null);return o})}function bm(t,e){if(t.type!=="upsert"&&t.type!=="put")return {ast:t};if(t.type==="put"){if(t.limit!==void 0||t.offset!==void 0)return T(400,"PGRST114","limit/offset querystring parameters are not allowed for PUT",null,null);let r=mm(t,e),s=YE(t.where,r);if(!s)return T(405,"PGRST105","Filters must include all and only primary key columns with 'eq' operators",null,null);if(Array.isArray(t.values)&&t.values.length===0)return {ast:t,emptyPayload:true};if(!ds(t.values))return T(400,"PGRST102","Empty or invalid json",null,null);for(let i of r)if(!ZE(t.values[i],s[i]))return T(400,"PGRST115","Payload values do not match URL in primary key column(s)",null,null);return t.onConflict=r,t.ignoreDuplicates=false,{ast:t,preflight:{mode:"put",conflictColumns:r}}}let n=t.onConflict?.length?t.onConflict:mm(t,e);return n.length===0?(t.onConflict=void 0,{ast:t}):(t.onConflict=n,{ast:t,appliedResolution:t.ignoreDuplicates?"ignore-duplicates":"merge-duplicates",preflight:t.ignoreDuplicates?void 0:{mode:"merge-duplicates",conflictColumns:n}})}function wm(t,e){let n=t.$meta,r={"Content-Type":"application/json; charset=utf-8"},s=ps(n,e.appliedResolution),i=n?.count==="exact"||n?.count==="planned"||n?.count==="estimated"?"*/0":"*/*",o=t.type==="upsert"?200:et(t,n?.return==="representation"?"representation":"no-return",e.appliedResolution,false);return n?.return==="representation"?(r["Content-Range"]=i,r["Content-Length"]="2",s&&(r["Preference-Applied"]=s),new Response("[]",{status:o,headers:r})):(r["Content-Range"]=i,s&&(r["Preference-Applied"]=s),new Response(null,{status:o,headers:r}))}function mm(t,e){if(!t.from)return [];let n=t.schema??"public",r=e.primary_keys.find(s=>s.table===t.from&&s.schema===n);return r?r.columns:e.primary_keys.find(s=>s.table===t.from)?.columns??[]}function YE(t,e){if(!t||e.length===0)return null;let n=Object.keys(t);if(n.length!==e.length)return null;let r={};for(let s of n){if(s.startsWith("$")||!e.includes(s))return null;let i=XE(t[s]);if(!i.ok)return null;r[s]=i.value;}return r}function XE(t){if(!ds(t))return {ok:false};let e=Object.keys(t);return e.length!==1||e[0]!=="$eq"?{ok:false}:{ok:true,value:t.$eq}}function ZE(t,e){return Object.is(t,e)?true:t!==null&&e!==null&&t!==void 0&&e!==void 0&&typeof t!="object"&&typeof e!="object"?String(t)===String(e):Et(t)===Et(e)}function ps(t,e){let n=[];return e&&n.push(`resolution=${e}`),t?.missing&&n.push(`missing=${t.missing}`),t?.return&&n.push(`return=${t.return}`),t?.count&&t.count!=="none"&&n.push(`count=${t.count}`),t?.tx&&n.push(`tx=${t.tx}`),n.length>0?n.join(", "):void 0}function et(t,e,n,r){switch(t.type){case "insert":return 201;case "upsert":return !n||n==="ignore-duplicates"?201:r===false?200:201;case "put":return e==="representation"?r?201:200:204;case "update":case "delete":return e==="representation"?200:204;default:return 200}}async function Sm(t,e,n,r,s){if(e.type==="insert")return true;if(!s.preflight||!e.from)return;if(s.preflight.mode==="put")return !await hm(t,e.from,e.schema,e.where??{},n,r);let i=Array.isArray(e.values)?e.values:e.values?[e.values]:[];for(let o of i){if(!ds(o))continue;let a=ex(s.preflight.conflictColumns,o);if(!a||!await hm(t,e.from,e.schema,a,n,r))return true}return false}function ex(t,e){let n={};for(let r of t){if(!(r in e))return;n[r]={$eq:e[r]};}return n}async function hm(t,e,n,r,s,i){return await qn(t,{type:"query",from:e,schema:n,where:r},s,i)>0}function ds(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function tx(t){return "select"in t||"spread"in t||"join"in t}function _m(t,e){if(t){for(let n of t)if(typeof n!="string")for(let r of Object.values(n))tx(r)&&((r.limit===void 0||r.limit>e)&&(r.limit=e),_m(r.select,e));}}var nx={count:new Set(["exact","planned","estimated"]),resolution:new Set(["merge-duplicates","ignore-duplicates"]),return:new Set(["minimal","headers-only","representation"]),tx:new Set(["commit","rollback"]),missing:new Set(["default","null"]),handling:new Set(["strict","lenient"]),"max-affected":"number",timezone:"string",params:new Set(["single-object","multiple-objects"])};function rx(t,e){if(!t)return [];let n=t.split(",").map(i=>i.trim()).filter(Boolean);if(n.find(i=>i.startsWith("handling="))!=="handling=strict")return [];let s=e?new Set(e):void 0;return n.filter(i=>!sx(i,s))}function sx(t,e){let n=t.indexOf("=");if(n===-1)return false;let r=t.slice(0,n).trim(),s=t.slice(n+1).trim();if(r==="timezone")return e?e.has(s):s.length>0;let i=nx[r];return i?i==="string"?s.length>0:i==="number"?/^-?\d+$/.test(s):i.has(s):false}function ix(t){if(!t.from||!t.order)return null;let e=t.order.find(n=>/^\s+/.test(n.column));return e?T(400,"42703",`column ${t.from}.${e.column.trim()} does not exist`,null,null):null}function Em(t){let e=t.ast,{dialect:n,introspection:r,apiConfig:s,acceptHeader:i,preferHeader:o,httpMethod:a,rangeHeader:l}=t,c=s??{};if(c?.aggregates_enabled!==true&&ml(e.select))return T(400,"PGRST123","Use of aggregate functions is not allowed",null,null);let f=c?.plan_enabled===true;if(!t.allowRawMedia&&!am(i,f))return T(406,"PGRST107",`None of these media types are available: ${om(i)}`,null,null);let u=nm(i),d=pm(i),p=rx(o,r.timezones);if(p.length>0)return T(400,"PGRST122","Invalid preferences given with handling=strict",`Invalid preferences: ${p.join(", ")}`,null);let g=ix(e);if(g)return g;if(n==="sqlite"&&e.from){let b=e.schema??"",_=r.tables.some(x=>x.name===e.from&&(x.schema??"")===b),E=r.views.some(x=>x.name===e.from&&(x.schema??"")===b);if(!_&&!E)throw new Bn(e.schema,e.from)}let m=e.$meta,h=e.type==="update"||e.type==="delete"||e.type==="insert"||e.type==="upsert"||e.type==="put",y={ast:e};if(h&&m?.return!=="representation"&&(e.select=void 0),(e.type==="put"||e.type==="upsert")&&(e.limit!==void 0||e.offset!==void 0))return T(400,"PGRST114","limit/offset querystring parameters are not allowed for PUT",null,null);if((e.type==="update"||e.type==="delete"||e.type==="insert")&&c?.limited_mutations_enabled!==true&&(e.limit=void 0,e.offset=void 0),c?.pg_safe_update&&h){let b=e.where&&Object.keys(e.where).length>0;if(e.type==="update"&&!b)return T(400,"21000","UPDATE requires a WHERE clause",null,null);if(e.type==="delete"&&!b)return T(400,"21000","DELETE requires a WHERE clause",null,null)}if(h&&(e.type==="insert"||e.type==="update"||e.type==="upsert"||e.type==="put")){if((e.type==="update"||e.type==="insert"||e.type==="upsert"||e.type==="put")&&(e.values===void 0||e.values===null))return T(400,"PGRST102","Empty or invalid json",null,null);if(e.type==="update"&&e.values&&typeof e.values=="object"&&!Array.isArray(e.values)&&Object.keys(e.values).length===0){let b=m?.return==="representation"?200:204,_=ps(m,y.appliedResolution),E={"Content-Type":"application/json; charset=utf-8","Content-Range":Ht(e,m,0)};if(_&&(E["Preference-Applied"]=_),m?.return==="representation"){let x=new TextEncoder().encode("[]");return E["Content-Length"]=String(x.byteLength),new Response(x,{status:b,headers:E})}return new Response(null,{status:b,headers:E})}if(e.type==="put"&&Array.isArray(e.values)&&(e.values.length===0?y.emptyPayload=true:e.values=e.values[0]),Array.isArray(e.values)){if(m?.cardinality==="one"&&(e.type==="insert"||e.type==="upsert")&&e.values.length>1)return T(406,"PGRST116","Cannot coerce the result to a single JSON object",`The result contains ${e.values.length} rows`,null);if(e.values.length>0&&e.values.some(b=>typeof b!="object"||b===null||Array.isArray(b)))return m?.columns?T(400,"22023","argument of jsonb_to_recordset must be an array of objects",null,null):T(400,"PGRST102","All object keys must match",null,null);if(!m?.columns&&e.values.length>1){let b=Object.keys(e.values[0]).sort().join(",");for(let _=1;_<e.values.length;_++)if(Object.keys(e.values[_]).sort().join(",")!==b)return T(400,"PGRST102","All object keys must match",null,null)}}if(m?.columns&&e.from){y.bodyKeySets=gm(e.values);let b=r.columns.filter(E=>E.table===e.from).map(E=>E.name);for(let E of m.columns){if(E==="")return T(400,"PGRST100",'"failed to parse columns parameter ()" (line 1, column 1)',"unexpected end of input",null);if(!b.includes(E))return T(400,"PGRST204",`Could not find the '${E}' column of '${e.from}' in the schema cache`,null,null)}let _=new Set(m.columns);if(e.values)if(Array.isArray(e.values))e.values=e.values.map(E=>{let x={};for(let O of _)O in E&&(x[O]=E[O]);return x});else {let E={};for(let x of _)x in e.values&&(E[x]=e.values[x]);e.values=E;}}if(!m?.columns&&e.values&&e.from&&(e.type==="insert"||e.type==="update"||e.type==="upsert"||e.type==="put")){let b=r.columns.filter(_=>_.table===e.from).map(_=>_.name);if(b.length>0){let _=Array.isArray(e.values)?e.values.length>0?Object.keys(e.values[0]):[]:Object.keys(e.values);for(let E of _)if(!b.includes(E))return T(400,"PGRST204",`Could not find the '${E}' column of '${e.from}' in the schema cache`,null,null)}}if(e.values&&e.from&&(e.type==="insert"||e.type==="update"||e.type==="upsert"||e.type==="put")){let b=e.schema??"public",_=new Set(r.columns.filter(E=>E.table===e.from&&(E.schema||"public")===b&&E.is_generated===true).map(E=>E.name));if(_.size>0){let E=Array.isArray(e.values)?e.values:[e.values];for(let x of E)if(!(!x||typeof x!="object")){for(let O of Object.keys(x))if(_.has(O))return T(400,"428C9",`cannot insert a non-DEFAULT value into column "${O}"`,`Column "${O}" is a generated column.`,null)}}}}let w=bm(e,r);if(w instanceof Response)return w;let S=y.bodyKeySets;if(y=w,y.bodyKeySets=S,e=y.ast,h&&((e.type==="insert"||e.type==="upsert")&&Array.isArray(e.values)&&e.values.length===0||y.emptyPayload))return m?.cardinality==="one"?T(406,"PGRST116","Cannot coerce the result to a single JSON object","The result contains 0 rows",null):wm(e,y);if(l&&(a==="GET"||a==="HEAD")){let b=l.match(/^(\d+)-(\d*)$/);if(b){let _=parseInt(b[1],10);if(b[2]!==""){let E=parseInt(b[2],10);if(_>E)return T(416,"PGRST103","Requested range not satisfiable","The lower boundary must be lower than or equal to the upper boundary in the Range header.",null);e.offset=_,e.limit=E-_+1;}else e.offset=_;}}if(e.limit!==void 0&&e.limit<0||e.limit===0&&e.offset!==void 0&&e.offset>0)return T(416,"PGRST103","Requested range not satisfiable","Limit should be greater than or equal to zero.",null);if(e.offset!==void 0&&e.offset<0&&(e.offset=0),!h){let b=c?.max_rows;b!==void 0&&b>0&&((e.limit===void 0||e.limit>b)&&(e.limit=b),_m(e.select,b));}return {ast:e,meta:m,mutationPlan:y,isMutation:h,stripNullsResponse:u,csvResponse:d,planEnabled:f}}var Wn=class extends Error{constructor(n){super(`new row violates row-level security policy for table "${n.data.table}"`);this.policy=n;this.name="PolicyViolation";}};ki();Vr();Fn();function xm(t){if(t.from)return t.from}function Cm(t,e){let{connection:n,introspection:r,vars:s,ast:i}=e;if(t instanceof fe){let a=`"${t.message}" (line 1, column ${t.position})`;return T(400,"PGRST100",a,t.details,null)}if(t instanceof He)return T(400,"PGRST100",t.message,t.details,null);if(t instanceof An)return T(400,t.code,t.message,null,null);if(t instanceof jt)return T(400,"PGRST100",t.message,t.details,null);if(t instanceof vn)return T(404,"PGRST125",t.message,t.details,null);if(t instanceof ve)return T(t.httpStatus,t.code,t.message,t.details,t.hint);if(t instanceof On)return T(400,"PGRST102",t.message,null,null);if(t instanceof vr)return T(400,"PGRST102",t.message,null,null);if(t instanceof Error&&t.message.startsWith("Invalid JSON body"))return T(400,"PGRST102","Empty or invalid json",null,null);if(t instanceof wt)return T(400,"PGRST100",t.message,t.message,null);if(t instanceof on)return T(400,"23514",t.message,`check constraint "${t.constraint}" violated`,null);if(t instanceof Wn){let l=qt(s,"auth.role","anon")==="anon"?401:403;return ot({status:l,code:"PGRST301",message:t.message})}let o=n.normalizeDbError(t);if(console.error(o),o instanceof Bn){let a=o.schema||"public",l=[...r.tables.filter(d=>(d.schema||"public")===a).map(d=>d.name),...r.views.filter(d=>(d.schema||"public")===a).map(d=>d.name)],c=l.length>0?l:[...r.tables.map(d=>d.name),...r.views.map(d=>d.name)],f=Jr(o.relation,c),u=f?`Perhaps you meant the table '${a}.${f}'`:null;return ot({status:404,code:"PGRST205",message:o.message,hint:u})}if(typeof o?.code=="string"){if(o.code==="PGRST")return ax(o);let a=/^PT(\d{3})$/.exec(o.code);if(a){let l=Number(a[1]);return T(l>=200&&l<=599?l:500,o.code,o.message,o.detail??null,o.hint??null)}if(o.code.startsWith("PT"))return T(500,o.code,o.message,o.detail??null,o.hint??null)}if(o?.code==="42501"){let l=qt(s,"auth.role","anon")==="anon"?401:403;return T(l,"42501",o.message,o.detail??null,o.hint??null)}if(o?.code==="42P01")return T(404,"PGRST205","Could not find the relation in the schema cache",o.message,null);if(o?.code==="23505"||o?.code==="23503")return T(409,o.code,o.message,o.detail??null,null);if(o?.code==="25006")return T(405,"25006",o.message,o.detail??null,o.hint??null);if(typeof o?.code=="string"){let a=o.code.slice(0,2);if(o.code==="42883"){let l=o.message;return l=l.replace(/^operator does not exist: [\w.]+\.([\w]+) /,"operator does not exist: $1 "),T(404,o.code,l,o.detail??null,o.hint??null)}if(o.code==="42P17")return T(500,o.code,o.message,o.detail??null,o.hint??null);if(a==="42"||a==="22"||a==="21"||o.code==="23502"){let l=o.message,c=i?xm(i):void 0;if(o.code==="42703"&&c){let f=i?.onConflict;l=l.replace(/^column "([^"]+)" does not exist$/,(u,d)=>f?.includes(d)?u:`column ${c}.${d} does not exist`);}return T(400,o.code,l,o.detail??null,o.hint??null)}if(a==="55"||a==="53")return T(500,o.code,o.message,o.detail??null,o.hint??null)}return o?.message?.includes("Unknown operator")?T(400,"PGRST100",o.message,null,null):o instanceof Error&&(o.message.includes("Expected identifier")||o.message.includes("Invalid filter")||o.message.includes("Unexpected input")||o.message.includes("Unsupported operator")||o.message.includes("failed to parse filter")||o.message.includes("failed to parse logic tree")||/^Expected .* at position \d+$/.test(o.message)||o.message.startsWith('Expected "(" for spread embed'))?T(400,"PGRST100",o.message,o.message,null):T(500,"SUP",String(o),null,null)}var lc=`Could not parse JSON in the "RAISE SQLSTATE 'PGRST'" error`,ox="MESSAGE must be a JSON object with obligatory keys: 'code', 'message' and optional keys: 'details', 'hint'.",Tm="DETAIL must be a JSON object with obligatory keys: 'status', 'headers' and optional key: 'status_text'.";function Rm(t){if(typeof t!="string")return null;try{let e=JSON.parse(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function ax(t){let e=typeof t.message=="string"?t.message:"",n=Rm(e);if(!n||typeof n.code!="string"||typeof n.message!="string")return T(500,"PGRST121",lc,`Invalid JSON value for MESSAGE: '${e}'`,ox);let r=t.detail;if(r==null||r==="")return T(500,"PGRST121",lc,"DETAIL is missing in the RAISE statement",Tm);let s=Rm(r),i=s?.headers,o=!!i&&typeof i=="object"&&!Array.isArray(i);if(!s||typeof s.status!="number"||!o)return T(500,"PGRST121",lc,`Invalid JSON value for DETAIL: '${r}'`,Tm);let a=JSON.stringify({code:n.code,details:n.details??null,hint:n.hint??null,message:n.message}),l=new TextEncoder().encode(a),c={"Content-Type":"application/json; charset=utf-8","Content-Length":String(l.byteLength)};for(let[u,d]of Object.entries(i))typeof d=="string"&&(c[u]=d);let f={status:s.status,headers:c};typeof s.status_text=="string"&&(f.statusText=s.status_text);try{return new Response(l,f)}catch{return new Response(l,{status:500,headers:{"Content-Type":"application/json; charset=utf-8","Content-Length":String(l.byteLength)}})}}var cx="response.status guc must be a valid status code",Kn="response.headers guc must be a JSON array composed of objects with a single key and a string value";async function km(t,e){let n=(await sql`
80
+ `;)i+=t[r],r++;n.push(i),r<s&&t[r]===","&&r++;}}return {row:n,nextPos:r}}var On=class extends Error{constructor(e){super(e),this.name="CsvParseError";}};function Ua(t){let e=new URL(t.url),n=new Map;for(let[r,s]of e.searchParams.entries()){let i=n.get(r)??[];i.push(s),n.set(r,i);}return n}function Ma(t,e,n){let r=e.toUpperCase();if(t.isRpc)return "rpc";switch(r){case "GET":case "HEAD":return "query";case "POST":return n.preferTokens.find(i=>i.key==="resolution"&&(i.value==="merge-duplicates"||i.value==="ignore-duplicates"))?"upsert":"insert";case "PATCH":return "update";case "PUT":return "put";case "DELETE":return "delete";default:return "query"}}var ed=new Set(["eq","neq","gt","gte","lt","lte","like","ilike","match","imatch","is","isdistinct","in","cs","cd","ov","sl","sr","nxl","nxr","adj","fts","plfts","phfts","wfts","not"]),Zf={eq:"$eq",neq:"$neq",gt:"$gt",gte:"$gte",lt:"$lt",lte:"$lte",like:"$like",ilike:"$ilike",match:"$regex",imatch:"$iregex",is:"$is",isdistinct:"$isDistinct",in:"$in",cs:"$contains",cd:"$containedBy",ov:"$overlaps",sl:"$rangeLt",sr:"$rangeGt",nxl:"$rangeGte",nxr:"$rangeLte",adj:"$rangeAdjacent"},vw={any:"Any",all:"All"},Aw=new Set(["eq","gt","gte","lt","lte","like","ilike","match","imatch"]),Ow={fts:void 0,plfts:"plain",phfts:"phrase",wfts:"websearch"};function ki(t){let e=t.match(/^(\w+)\((any|all)\)$/);if(e){let[,s,i]=e;if(!Aw.has(s))return null;let o=Zf[s];return o?{astOp:o+vw[i]}:null}let n=t.match(/^(p[lh]fts|wfts|fts)(?:\(([^)]+)\))?$/);if(n){let[,s,i]=n;return i!==void 0&&!/^[A-Za-z_][A-Za-z0-9_ ]*(?:\.[A-Za-z_][A-Za-z0-9_]*)?$/.test(i)?null:{astOp:"$textSearch",ftsType:Ow[s],ftsConfig:i}}let r=Zf[t];return r?{astOp:r}:null}function Ar(t){let e=t.indexOf(".");if(e===-1)return false;let r=t.substring(0,e).replace(/\((any|all)\)$/,"").replace(/^(p[lh]fts|wfts|fts)\([^)]+\)$/,"$1");return ed.has(r)}var nn=new Set(["select","order","limit","offset","on_conflict","columns","apikey"]);function Or(t){if(t.startsWith("(")&&t.endsWith(")")&&(t=t.slice(1,-1)),t.trim()==="")return [];let e=[],n=0;for(;n<t.length;){if(t[n]==='"'){n++;let r="";for(;n<t.length&&t[n]!=='"';)t[n]==="\\"&&n+1<t.length&&n++,r+=t[n],n++;n<t.length&&n++,e.push(r);}else {let r="";for(;n<t.length&&t[n]!==",";)r+=t[n],n++;e.push(rt(r,{preserveWhitespace:true}));}n<t.length&&t[n]===","&&(n++,n===t.length&&e.push(""));}return e}function rn(t){if(t.startsWith("{")&&t.endsWith("}")&&(t=t.slice(1,-1)),t==="")return [];let e=[],n=0;for(;n<t.length;){if(t[n]==='"'){n++;let r="";for(;n<t.length&&t[n]!=='"';)t[n]==="\\"&&n+1<t.length&&n++,r+=t[n],n++;n<t.length&&n++,e.push(r);}else {let r="";for(;n<t.length&&t[n]!==",";)r+=t[n],n++;e.push(rt(r));}n<t.length&&t[n]===","&&n++;}return e}var Pn=Symbol.for("postgrest:not_null"),sn=Symbol.for("postgrest:unknown");function rt(t,e){let n=e?.preserveWhitespace===true,r=t.trim();if(r.startsWith('"')&&r.endsWith('"')&&r.length>=2)return r.slice(1,-1);let s=r.toLowerCase();if(s==="null")return null;if(s==="not_null")return Pn;if(s==="true")return true;if(s==="false")return false;if(s==="unknown")return null;if(/^-?0\d+$/.test(r)||/^[0-9A-Fa-f]+$/.test(r)&&/[A-Fa-f]/.test(r))return r;if(r!==""&&!Number.isNaN(Number(r))&&Number.isFinite(Number(r)))return Number(r);if(r.startsWith("{")&&r.endsWith("}"))try{let i=JSON.parse(r);if(typeof i=="object"&&!Array.isArray(i))return i}catch{}return n?r===""?"":t:r}function Ir(t,e,n,r){let s={},i={};for(let[o,a]of t){if(nn.has(o))continue;let c=o.startsWith('"')?-1:o.indexOf(".");if(c>0&&!o.slice(0,c).includes("->")){let f=o.slice(0,c),u=o.slice(c+1);if(e.has(f)){if(u==="order"||u==="limit"||u==="offset")continue;if(u.includes(".")){let d=u.lastIndexOf("."),p=u.slice(d+1);if(p==="order"||p==="limit"||p==="offset")continue}i[f]||(i[f]={}),Nw(u,a,i[f]);continue}if(o!=="not.or"&&o!=="not.and")throw $w(f)}if(e.has(o)&&!a.every(Pw)&&!r?.has(o)){let f=n?`${n}.${o}`:o,u=new Error(`column ${f} does not exist`);throw u.code="42703",u}qa(o,a,s);}return {where:s,embeddedWheres:i}}function Pw(t){return /^(not\.)?is\.(null|true|false|distinct\.)/.test(t.trim())}function $w(t){return new ve({httpStatus:400,code:"PGRST108",message:`'${t}' is not an embedded resource in this request`,details:null,hint:`Verify that '${t}' is included in the 'select' query parameter.`})}function qa(t,e,n){if(t==="or"||t==="and"){if(e.every(o=>!o.includes("("))){for(let o of e)Iw(t,o,n);return}let s=e.map(o=>nd(o)),i=s.length===1?s[0]:s.flat();n[`$${t}`]=i;return}if(t==="not.or"||t==="not.and"){let s=t.slice(4),i=e.map(a=>nd(a)),o=i.length===1?i[0]:i.flat();n.$not={[`$${s}`]:o};return}let r=rd(Uw(t),{stopAtSpace:false});sd(r);for(let s of e){let i=Ha(s);n[r]?Object.assign(n[r],i):n[r]=i;}}function Iw(t,e,n){let r=e.indexOf("."),s=r===-1?e:e.slice(0,r),i=`${t}${s}`,o=r===-1?"":e.slice(r+1),a=Ha(o);n[i]?Object.assign(n[i],a):n[i]=a;}function Nw(t,e,n){let r=Dw(t);if(!r){qa(t,e,n);return}let s={};qa(r.filterKey,e,s);for(let[i,o]of Object.entries(s))n[`${r.path}.${i}`]=o;}function Dw(t){for(let e of ["not.or","not.and","or","and"]){let n=`.${e}`;if(t.endsWith(n)){let r=t.slice(0,-n.length);if((e==="or"||e==="and")&&r==="not")continue;if(r)return {path:r,filterKey:e}}}}function Ha(t){let e=t,n=false;e.startsWith("not.")&&(n=true,e=e.slice(4));let r=e.indexOf("."),s,i;r===-1?(s=e,i=""):(s=e.slice(0,r),i=e.slice(r+1));let o=ki(s);if(!o){let u=s.match(/^(p[lh]fts|wfts|fts)\(\)$/);throw u?new Error(`"failed to parse filter (${t})" (line 1, column ${u[1].length+2})`):new Error(`"failed to parse filter (${t})" (line 1, column 1)`)}let{astOp:a,ftsType:l,ftsConfig:c}=o;if(n&&a==="$in")return {$notIn:Ba(a,i)};if(n&&a==="$is")return {$isNot:Ba(a,i)};let f=a==="$textSearch"?Lw(i,l,c):Ba(a,i);return n?{$not:{[a]:f}}:{[a]:f}}function Ba(t,e){if(t==="$in"||t==="$notIn"){if(!e.startsWith("(")||!e.endsWith(")")){let n=t==="$in"?"in":"not.in";throw new Error(`"failed to parse filter (${n}.${e})" (line 1, column ${n.length+e.length+2})`)}return Or(e)}if(t.endsWith("Any")||t.endsWith("All")){if(e.startsWith("{"))return rn(e);if(!jw(t))throw Object.assign(new Error(`malformed array literal: "${e}"`),{code:"22P02",detail:'Array value must start with "{" or dimension information.'});return Or(e)}if(t==="$contains"||t==="$containedBy"||t==="$overlaps"){if(e.startsWith("{")){try{let n=JSON.parse(e);if(typeof n=="object"&&!Array.isArray(n))return n}catch{}return rn(e)}return e.startsWith("[")||e.startsWith("(")?e:rt(e)}if(t.startsWith("$range"))return e;if(t==="$is"){let n=e.toLowerCase().trim(),s=["not_null","unknown","null","true","false"].find(i=>n===i||n.startsWith(i));if(!s)throw new Error(`"failed to parse filter (is.${e})" (line 1, column ${2+e.length})`);return s==="unknown"?sn:s==="not_null"?Pn:s==="null"?null:s==="true"?true:s==="false"?false:rt(e)}if(t==="$like"||t==="$ilike"||t==="$likeAny"||t==="$ilikeAny"||t==="$likeAll"||t==="$ilikeAll"){let n=e.replace(/\*/g,"%");return t.endsWith("Any")||t.endsWith("All")?n.startsWith("{")?rn(n):Or(n):n}if(t==="$isDistinct")return e.startsWith("{")?rn(e):e;if((t==="$eq"||t==="$neq")&&e.startsWith("{")&&e.endsWith("}")){try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null&&!Array.isArray(n))return n}catch{}return rn(e)}return rt(e)}function jw(t){return t==="$likeAny"||t==="$ilikeAny"||t==="$likeAll"||t==="$ilikeAll"}function Lw(t,e,n){let r={query:t};return e&&(r.type=e),n&&(r.config=n),r}function Fw(t){let e=t.match(/^\(\(or\([^)]*\),/);if(e)return e[0].length+8;let n=t.match(/^\(or\([^)]*\),/);return n?n[0].length+8:t.length+2}function td(t){return new Error(`"failed to parse logic tree (${t})" (line 1, column ${Fw(t)})`)}function nd(t){if(!t.startsWith("(")||!t.endsWith(")"))throw new Error(`"failed to parse logic tree (${t})" (line 1, column ${t.length+3})`);let e=t.slice(1,-1);for(;e.endsWith(")");){let n=0;for(let r of e)r==="("?n++:r===")"&&n--;if(n<0)e=e.slice(0,e.length+n);else break}if(e.trim()==="")throw td(t);try{return Pr(e).map(r=>$r(r))}catch{throw td(t)}}function Pr(t){let e=[],n=0,r=0,s=false,i="";for(let o of t)if(o==='"'&&!s?s=true:o==='"'&&s&&(s=false),s||(o==="("?n++:o===")"?n--:o==="{"?r++:o==="}"&&r--),o===","&&n===0&&r===0&&!s){if(i.trim()==="")throw new Error("empty logical expression");e.push(i.trim()),i="";}else i+=o;if(i.trim())e.push(i.trim());else if(t.trim().endsWith(","))throw new Error("empty logical expression");return e}function $r(t){let e=t.trim(),n=e.match(/^and\s*\((.*)\)$/s);if(n)return {$and:Pr(n[1]).map(d=>$r(d))};let r=e.match(/^or\s*\((.*)\)$/s);if(r)return {$or:Pr(r[1]).map(d=>$r(d))};let s=e.match(/^not\.and\s*\((.*)\)$/s);if(s)return {$not:{$and:Pr(s[1]).map(d=>$r(d))}};let i=e.match(/^not\.or\s*\((.*)\)$/s);if(i)return {$not:{$or:Pr(i[1]).map(d=>$r(d))}};if(/^(?:and|or|not)=/.test(e))throw new Error(`Invalid filter expression: "${t}"`);if(e.startsWith("not("))throw new Error(`Invalid filter expression: "${t}"`);let o=t;if(o.startsWith("not.")){let p=o.slice(4).split(".")[0];if(!(p.length>0&&ki(p)!==null))throw new Error(`Invalid filter expression: "${t}"`)}let l=o.indexOf(".");if(l===-1)throw new Error(`Invalid filter expression: "${t}"`);let c=rd(o.slice(0,l),{stopAtSpace:true});sd(c);let f=o.slice(l+1),u=Ha(f);return {[c]:u}}function rd(t,e){let r=(e.stopAtSpace?/[!@/\\~[\]()\t ]/:/[!@/\\~[\]()\t]/).exec(t),s=r?t.slice(0,r.index):t,i=s.indexOf("::");i!==-1&&(s=s.slice(0,i));let o=s.indexOf("=");o!==-1&&(s=s.slice(0,o));let a=s.indexOf(":");return a!==-1&&(s=s.slice(0,a)),s}function Uw(t){return t.length>=2&&t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1).replace(/""/g,'"'):t}function sd(t){if(t===""||t==="*"||t.startsWith(".")||t.includes("--")||t.endsWith("-"))throw new Error(`Invalid filter expression: "${t}"`);if(/->>?-\d+[A-Za-z]/.test(t))throw new Error(`Invalid filter expression: "${t}"`)}function Mw(t){let e=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\(([^)]+)\)$/);return e?{embed:e[1],column:e[2]}:null}function id(t){if(t===void 0)return;let e=t.trim();if(!/^[+-]?\d+$/.test(e))return;let n=Number(e);return Number.isFinite(n)?n:void 0}function Wa(t,e){let n=id(t),r=id(e);return r!==void 0&&r<0&&(n!==void 0&&n>=0&&(n=Math.max(0,n+r)),r=void 0),{limit:n,offset:r}}function Ja(t,e){let n={embeddedTransforms:{}},r,s,i={},o={},a={},l={};for(let[d,p]of t){let g=p[0],m=d.indexOf(".");if(m>0){let h=d.slice(0,m),y=d.slice(m+1);if(e.has(h)){if(y==="order"||y==="limit"||y==="offset"){n.embeddedTransforms[h]||(n.embeddedTransforms[h]={}),y==="order"?n.embeddedTransforms[h].order=Ka(g):y==="limit"?i[h]=g:y==="offset"&&(o[h]=g);continue}if(y.includes(".")){let w=y.lastIndexOf("."),S=y.slice(w+1);if(S==="order"||S==="limit"||S==="offset"){n.embeddedTransforms[h]||(n.embeddedTransforms[h]={});let b=n.embeddedTransforms[h],_=y.slice(0,w);b._nested||(b._nested={});let E=b._nested;E[_]||(E[_]={});let x=E[_];S==="order"?x.order=Ka(g):S==="limit"?(a[h]||(a[h]={}),a[h][_]=g):S==="offset"&&(l[h]||(l[h]={}),l[h][_]=g);continue}}}}d==="order"?n.order=Ka(g):d==="limit"?r=g:d==="offset"&&(s=g);}if(n.order){for(let d of n.order)if(d.embed&&!e.has(d.embed))throw new ve({httpStatus:400,code:"PGRST108",message:`'${d.embed}' is not an embedded resource in this request`,details:null,hint:`Verify that '${d.embed}' is included in the 'select' query parameter.`})}let c=Wa(r,s);c.limit!==void 0&&(n.limit=c.limit),c.offset!==void 0&&(n.offset=c.offset);let f=new Set([...Object.keys(i),...Object.keys(o)]);for(let d of f){let p=Wa(i[d],o[d]);n.embeddedTransforms[d]||(n.embeddedTransforms[d]={}),p.limit!==void 0&&(n.embeddedTransforms[d].limit=p.limit),p.offset!==void 0&&(n.embeddedTransforms[d].offset=p.offset);}let u=new Set([...Object.keys(a),...Object.keys(l)]);for(let d of u){let p=new Set([...Object.keys(a[d]??{}),...Object.keys(l[d]??{})]);for(let g of p){let m=Wa(a[d]?.[g],l[d]?.[g]),h=n.embeddedTransforms[d]?._nested?.[g];h&&(m.limit!==void 0&&(h.limit=m.limit),m.offset!==void 0&&(h.offset=m.offset));}}return n}function Ka(t){return Bw(t).map(({entry:e,start:n},r)=>{let s=r===0?e.trim():e.trimEnd(),i=r===0?n+e.length-e.trimStart().length:n;return qw(s,t,i)})}function Bw(t){let e=[],n=0,r=0;for(let s=0;s<t.length;s++){let i=t[s];i==="("?n++:i===")"?n=Math.max(0,n-1):i===","&&n===0&&(e.push({entry:t.slice(r,s),start:r}),r=s+1);}return e.push({entry:t.slice(r),start:r}),e}function qw(t,e,n){let r=t.split("."),s={column:r[0].replace(/\s+$/,"")},i=r[0];if(!i)throw new fe(`failed to parse order (${e})`,'unexpected end of input expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input',1);let o=i.indexOf("::");if(o!==-1)throw new fe(`failed to parse order (${e})`,`unexpected ':' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+o+1);let a=i.indexOf("--");if(a!==-1)throw new fe(`failed to parse order (${e})`,`unexpected '-' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+a+2);let l=i.search(/[@#%]/);if(l!==-1)throw new fe(`failed to parse order (${e})`,`unexpected '${i[l]}' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+l+1);if(i.endsWith("-"))throw new fe(`failed to parse order (${e})`,`unexpected '-' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+i.length);let c=i.indexOf(":");if(c!==-1)throw new fe(`failed to parse order (${e})`,`unexpected ':' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+c+1);let f=Mw(i);if(f){if(f.column.includes(","))throw new fe(`failed to parse order (${e})`,`unexpected ',' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+i.indexOf(",",f.embed.length)+1);s.column=f.column,s.embed=f.embed;}else if(i.includes("(")||i.includes(")")){let g=i.search(/[()]/);throw new fe(`failed to parse order (${e})`,`unexpected '${i[g]}' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+g+1)}let u=n+i.length+1,d=false,p=false;for(let g=1;g<r.length;g++){let m=r[g];if(m==="asc"||m==="desc"){if(d)throw new fe(`failed to parse order (${e})`,`unexpected '${m[0]}' expecting "," or end of input`,u+1);if(p)throw new fe(`failed to parse order (${e})`,`unexpected '${m[0]}' expecting "," or end of input`,u+1);s.direction=m,d=true,u+=m.length+1;}else if(m==="nullsfirst"||m==="nullslast"){if(p)throw new fe(`failed to parse order (${e})`,`unexpected '${m[0]}' expecting "," or end of input`,u+1);s.nullsFirst=m==="nullsfirst",p=true,u+=m.length+1;}else {let h=["asc","desc","nullsfirst","nullslast"],y=null;for(let w of h)if(m.startsWith(w)&&m.length>w.length){y=w;break}if(y){let w=m[y.length],S=u+y.length;throw new fe(`failed to parse order (${e})`,`unexpected '${w}' expecting "," or end of input`,S+1)}throw new fe(`failed to parse order (${e})`,`unexpected '${m[0]}' expecting "," or end of input`,u+1)}}return s}function Ga(t,e,n){let r={};for(let i of t.preferTokens)switch(i.key){case "count":r.count===void 0&&(r.count=i.value);break;case "missing":r.missing===void 0&&(r.missing=i.value);break;case "handling":r.handling===void 0&&(r.handling=i.value);break;case "tx":r.tx===void 0&&(r.tx=i.value,i.value==="rollback"&&(r.rollback=true));break;case "max-affected":r.maxAffected===void 0&&(r.maxAffected=i.value);break;case "timezone":r.timezone===void 0&&(r.timezone=i.value);break;case "return":r.return===void 0&&(r.return=i.value);break}n.toUpperCase()==="HEAD"&&(r.head=true),t.accept.includes("application/vnd.pgrst.object")&&(r.cardinality="one"),t.accept.includes("application/vnd.pgrst.plan")&&(r.explain=Kw(t.accept));let s=e.get("columns");if(s){let i=s[0];r.columns=Hw("columns",i);}return r}function Hw(t,e){let n=e.split(",").map(r=>Ww(r));if(n.length===0||n.some(r=>r===""||r==="*"||r.includes("--")||r.endsWith("-")))throw new jt(`"failed to parse ${t} parameter (${e})" (line 1, column 1)`,"unexpected input");return n}function Ww(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e.replace(/@.*$/,"")}function Kw(t){let e={},n=t.match(/options=([^;]+)/);if(n){let r=n[1].split("|").map(s=>s.trim());e.analyze=r.includes("analyze"),e.verbose=r.includes("verbose"),e.settings=r.includes("settings"),e.buffers=r.includes("buffers"),e.wal=r.includes("wal");}return e}function za(t,e,n,r){if(!t.isRpc)return {};if(e.toUpperCase()==="POST"){let a={httpMethod:"POST"};return r.values?(Array.isArray(r.values)?(a.args=r.values,a.paramsType="positional"):(a.args=r.values,a.paramsType="named"),a.inputType="json"):r.raw!==void 0&&(a.args={_raw:r.raw},a.inputType="text"),a}let i={};for(let[a,l]of n){if(nn.has(a))continue;let c=l.filter(f=>!Ar(f));c.length!==0&&(c.length>1?i[a]=c.map(f=>rt(f)):i[a]=rt(c[0]));}let o={httpMethod:"GET",paramsType:"named",inputType:"json"};return Object.keys(i).length>0&&(o.args=i),o}function Va(t,e){let n=t.get("on_conflict"),r=n===void 0?void 0:Jw(n[0]),i=e.preferTokens.find(o=>o.key==="resolution")?.value==="ignore-duplicates";return {onConflict:r?.length?r:void 0,ignoreDuplicates:i}}function Jw(t){let e=t.split(",").map(n=>n.trim());if(e.length===0||e.some(n=>n===""||n.includes("--")||n.endsWith("-")))throw new jt(`"failed to parse on_conflict parameter (${t})" (line 1, column 1)`,"unexpected input");return e.map(n=>n.replace(/[!@/\\~[\]()\t ].*$/,""))}async function vi(t,e){let n=e?.basePath,r=e?.parseRoute??(C=>$a(C,n)),s=e?.parseHeaders??Ia,i=e?.parseSelect??La,o=e?.parseBody??Fa,a=e?.parseQueryParams??Ua,l=e?.resolveType??Ma,c=e?.resolveFilters??Ir,f=e?.resolveTransforms??Ja,u=e?.resolveMeta??Ga,d=e?.resolveRpcParams??za,p=e?.resolveUpsertParams??Va,[g,m,h,y,w]=await Promise.all([r(t),s(t),i(t),o(t),a(t)]),S=t.method,b=l(g,S,m),_=w;if(g.isRpc&&S.toUpperCase()==="GET"){_=new Map;for(let[C,R]of w){if(nn.has(C)){_.set(C,R);continue}let U=R.filter(J=>Ar(J));U.length>0&&_.set(C,U);}}let E=c(_,h.embeddedAliases,g.isRpc?void 0:g.from,e?.parentColumns),x=f(w,h.embeddedAliases),O=u(m,w,S),v=d(g,S,w,y),P=b==="upsert"||b==="put"?p(w,m):void 0;return Gw(b,g,m,h,y,E,x,O,v,P)}function Gw(t,e,n,r,s,i,o,a,l,c){let f={type:t};return e.isRpc?f.function=e.function:f.from=e.from,n.schema&&(f.schema=n.schema),Object.keys(r.join).length>0&&(f.join=r.join),r.select.length>0&&(f.select=od(r.select,i.embeddedWheres,o.embeddedTransforms,r.join)),Object.keys(i.where).length>0&&(f.where=i.where),(t==="insert"||t==="update"||t==="upsert"||t==="put")&&s.values!==void 0&&(f.values=s.values),t==="rpc"&&(l.args!==void 0&&(f.args=l.args),l.httpMethod&&(f.httpMethod=l.httpMethod),l.paramsType&&(f.paramsType=l.paramsType),l.inputType&&(f.inputType=l.inputType)),(t==="upsert"||t==="put")&&c&&(c.onConflict&&(f.onConflict=c.onConflict),f.ignoreDuplicates=c.ignoreDuplicates),a.return==="representation"&&(t==="insert"||t==="update"||t==="delete"||t==="upsert"||t==="put")&&(!f.select||f.select.length===0)&&(f.select=["*"]),o.order&&(f.order=o.order),o.limit!==void 0&&(f.limit=o.limit),o.offset!==void 0&&(f.offset=o.offset),Object.keys(a).length>0&&(f.$meta=a),f}function zw(t,e,n){return t.map(r=>{if(typeof r=="string"||!(e in r))return r;let s=r[e];return s.select?{[e]:{...s,where:{...s.where??{},...n}}}:r})}function od(t,e,n,r,s){return t.map(i=>{if(typeof i=="string")return i;let o=Object.keys(i)[0],a=i[o];if(!a.select)return i;let l={...a},c=r?.[o]?.from,f=e[o]||c&&e[c],u=n[o]||c&&n[c];if(f&&s!==o){let d={},p={};for(let[g,m]of Object.entries(f)){let h=g.indexOf(".");if(h>0){let y=g.slice(0,h),w=g.slice(h+1);if(l.join?.[y]||l.select?.some(_=>typeof _=="object"&&y in _&&"select"in(_[y]??{}))){p[y]||(p[y]={}),p[y][w]=m;continue}}d[g]=m;}Object.keys(d).length>0&&(l.where=d);for(let[g,m]of Object.entries(p))l.select=zw(l.select??[],g,m);}if(u){let d=u;if(d.order&&(l.order=d.order),d.limit!==void 0&&(l.limit=d.limit),d.offset!==void 0&&(l.offset=d.offset),d._nested)for(let[p,g]of Object.entries(d._nested))n[p]=g;}return l.select&&(l.select=od(l.select,e,n,l.join,o)),{[o]:l}})}function Ai(t){return t!=null&&typeof t=="object"&&"$ref"in t}st();var Qa=class extends ie{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}serialize(e){if(this.isNullish(e))return e;if(typeof e=="number"&&Number.isFinite(e))return Math.trunc(e);if(typeof e=="string")return $n(e);throw this.checkError("color_range",e)}deserialize(e){if(this.isNullish(e))return "";if(typeof e=="number"&&Number.isFinite(e))return ad(e);if(typeof e=="string"&&e.startsWith("#"))return e;if(typeof e=="string"||typeof e=="bigint"){let n=Number(e);if(Number.isFinite(n))return ad(n)}return e}},Xa=class extends ie{get isShimBacked(){return true}get sqliteType(){return "TEXT"}serialize(e){return this.isNullish(e)?e:typeof e=="string"?e.replace(/Z$/,"+00:00"):e}deserialize(e){if(this.isNullish(e)||typeof e!="string")return e;let n=e.trim();if(/^\d{4}-\d{2}-\d{2}T/.test(n))return n.replace(/\+00:00$/,"Z");if(/^\d{4}-\d{2}-\d{2}$/.test(n))return `${n}T00:00:00Z`;if(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/.test(n)){let r=n.replace(" ","T");return /(?:Z|[+-]\d{2}:\d{2})$/.test(r)?r.replace(/\+00:00$/,"Z"):`${r}Z`}return n.replace(/\+00:00$/,"Z")}},Ya=class extends ie{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}serialize(e){if(this.isNullish(e))return e;if(typeof e=="number"&&Number.isFinite(e))return Math.trunc(e);if(typeof e=="string"){let n=Date.parse(e);if(Number.isFinite(n))return Math.trunc(n/1e3)}return e}deserialize(e){if(this.isNullish(e))return e;if(typeof e=="number"&&Number.isFinite(e))return Math.trunc(e);if(typeof e=="bigint")return Number(e);if(e instanceof Date&&Number.isFinite(e.getTime()))return Math.trunc(e.getTime()/1e3);if(typeof e=="string"){let n=e.trim();if(/^\d+$/.test(n))return Number(n);let r=Date.parse(n);if(Number.isFinite(r))return Math.trunc(r/1e3)}return e}},Za=class extends ie{get isShimBacked(){return true}get sqliteType(){return "TEXT"}serialize(e){return this.isNullish(e)?e:typeof e=="number"&&Number.isFinite(e)?e.toFixed(2):e}deserialize(e){return e}},el=class extends ie{get isShimBacked(){return true}get sqliteType(){return "TEXT"}deserialize(e){if(this.isNullish(e))return e;let n=null;if(typeof e=="string")n=e;else if(e instanceof Uint8Array)n=Buffer.from(e).toString("base64");else if(e&&typeof e=="object"&&!Array.isArray(e)){let s=Object.values(e);n=Buffer.from(s).toString("base64");}if(n===null)return e;n=n.replace(/\s/g,"");let r=(4-n.length%4)%4;return r===0?n:n+"=".repeat(r)}};function $n(t){let e=t.trim(),r=(e.startsWith("#")?e.slice(1):e).padStart(8,"0");return Number.parseInt(r,16)>>>0}function ad(t){return `#${(Math.trunc(t)&16777215).toString(16).toUpperCase().padStart(6,"0")}`}function cd(t,e){return e==="postgres"||e==="pglite"?sql`('"' || upper('#' || lpad(to_hex((${t})::bigint & 16777215), 6, '0')) || '"')`:sql`('"' || upper(printf('#%06X', (${t}) & 16777215)) || '"')`}var Vw=new Set(["color","isodate","isodatetext","unixtz","monetary","monetarytext","bytea_b64"]),Qw=new Set(["bool","boolean"]),ud=new Map;function Le(t){if(!t)return false;let e=t.toLowerCase().trim();return Vw.has(e)||ud.has(e)}function Ne(t,e){return (t??e).toLowerCase().trim()}function tl(t,e){let n=Ne(t.pg_type,t.type);return Le(n)||!e?n:Xw(t.table,t.name,e)??n}function Xw(t,e,n){let r=n.views.find(i=>i.name===t);if(!r?.sql)return;let s=[new RegExp(`CAST\\s*\\(.+?\\s+AS\\s+([\\w.]+)\\)\\s+AS\\s+${e}\\b`,"is"),new RegExp(`::\\s*(?:[\\w.]+\\.)?([\\w]+)\\s+AS\\s+${e}\\b`,"i")];for(let i of s){let o=r.sql.match(i);if(!o)continue;let a=o[1].split(".").pop().toLowerCase();if(Le(a)||Qw.has(a))return a}}function nl(t){if(typeof t=="string"&&t.trim()==="Z")throw Object.assign(new Error('invalid input syntax for type timestamp with time zone: "Z"'),{code:"22007",detail:null,hint:null})}function fd(t){return Array.isArray(t)?t.map(e=>ld(e)):ld(t)}function ld(t){if(typeof t=="number"&&Number.isFinite(t))return Math.trunc(t);if(typeof t=="string"){let e=t.trim();return $n(e.startsWith("#")?e:`#${e}`)}return t}function Pi(t,e){let n=e.toLowerCase().trim();return n==="color"?sql`to_json('#' || lpad(upper(to_hex((${t})::bigint & 16777215)), 6, '0'))`:n==="unixtz"?sql`to_json(EXTRACT(EPOCH FROM ${t})::bigint)`:n==="monetary"||n==="monetarytext"?sql`to_json((${t})::text)`:n==="bytea_b64"?sql`to_json(encode((${t})::bytea, 'base64'))`:n==="isodate"||n==="isodatetext"?sql`to_json(to_char((${t}) AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"'))`:null}function dd(t,e){let n=e.toLowerCase().trim();if(n==="unixtz"){let r=typeof t=="number"?t:typeof t=="string"?Number(t):NaN;if(Number.isFinite(r)){let s=new Date(r*1e3);if(Number.isFinite(s.getTime()))return s.toISOString()}return t}if(n==="bytea_b64"){if(typeof t=="string")try{let r=t.replace(/=+$/,"");for(;r.length%4!==0;)r+="=";let s=atob(r),i="";for(let o=0;o<s.length;o++)i+=s.charCodeAt(o).toString(16).padStart(2,"0");return `\\x${i}`}catch{return t}return t}return n==="monetary"||n==="monetarytext"?typeof t=="number"?String(t):t:(n==="isodate"||n==="isodatetext")&&typeof t=="string"?t.replace(/Z$/,"+00:00"):t}function Nr(t,e,n,r,s,i){if(r!=="postgres"||!e||!s?.columns)return t;let o=i??"public",a=s.columns.find(c=>c.table===e&&c.name===n&&(c.schema??"public")===o);if(!a)return t;let l=Ne(a.pg_type,a.type);return Le(l)?Pi(t,l)??t:t}function pd(t,e,n,r){if(!t||!n?.columns)return false;let s=r??"public",i=n.columns.find(o=>o.table===t&&o.name===e&&(o.schema??"public")===s);return i?Le(Ne(i.pg_type,i.type)):false}function Dr(t,e,n){if(!t||!e?.columns)return false;let r=n??"public";return e.columns.some(s=>s.table!==t||(s.schema??"public")!==r?false:Le(Ne(s.pg_type,s.type)))}function rl(t,e,n){let r=n??"public";return e.columns.filter(s=>s.table===t&&(s.schema??"public")===r).sort((s,i)=>s.ordinal_position-i.ordinal_position).map(s=>{let i=Ne(s.pg_type,s.type),o=Le(i);return {name:s.name,isDomain:o,domainTypeName:o?i:null}})}function md(t){let e=t.pgTypeName.toLowerCase().trim(),n=ud.get(e);if(n)return n(t);switch(e){case "color":return new Qa(t);case "isodate":case "isodatetext":return new Xa(t);case "unixtz":return new Ya(t);case "monetary":case "monetarytext":return new Za(t);case "bytea_b64":return new el(t);default:return null}}var Yw=/^[a-zA-Z_][a-zA-Z0-9_.]*$/,Zw=/[;'"\\/*\-#]/,eS=/['\\;(]/,wt=class extends Error{constructor(n,r){super(`Unsafe ${r}: "${n}"`);this.value=n;this.context=r;this.name="SanitizeError";}};function Pe(t,e){if(!Yw.test(t))throw new wt(t,e)}function ln(t,e){if(Zw.test(t))throw new wt(t,e);let n=0;for(let r of t)if(r==="("?n++:r===")"&&n--,n<0)throw new wt(t,e);if(n!==0)throw new wt(t,e)}function In(t,e){if(eS.test(t))throw new wt(t,e)}function cn(t){let e=t.indexOf("->");if(e===-1)return {col:t,parts:[]};let n=t.slice(0,e),r=t.slice(e),s=[];for(;r.length>0;){let i;if(r.startsWith("->>"))i="->>",r=r.slice(3);else if(r.startsWith("->"))i="->",r=r.slice(2);else break;let o=r.indexOf("->"),a=o===-1?r:r.slice(0,o);s.push({op:i,key:a}),r=o===-1?"":r.slice(o);}return {col:n,parts:s}}function jr(t,e){return t.map(n=>{let r=/^-?\d+$/.test(n.key);return r||In(n.key,e),r?`${n.op}${n.key}`:`${n.op}'${n.key}'`}).join("")}function k(t){return typeof t=="string"?sql.ref(t):t}function tS(t){return `"${t.replace(/"/g,'""')}"`}function sl(t){return sql.raw(tS(t))}function il(t,e,n=e.currentTable,r=e.currentSchema){if(!n||!e.introspection?.columns)return;let s=e.introspection.columns.filter(i=>i.table===n&&i.name===t);if(s.length!==0)return s.find(i=>!r||i.schema===r)??s.find(i=>["","public"].includes(i.schema??""))??s[0]}function $i(t,e,n=e.currentTable,r=e.currentSchema){return il(t,e,n,r)!==void 0}function de(t,e,n=e.currentTable){return $i(t,e,n)?sl(t):sql.ref(t)}function St(t,e,n,r=n.currentTable){let s=$i(e,n,r)?sl(e):sql.ref(e);return sql`${sql.ref(t)}.${s}`}function nS(t){return (t?.pg_type??t?.type??"").toLowerCase()}function hd(t,e,n=e.currentTable){if(e.dialect!=="postgres")return false;let r=nS(il(t,e,n));return r.endsWith("[]")||r.startsWith("_")||r==="array"}function gd(t){let e=[];for(let n of t){if(!/^\d+$/.test(n))return;e.push(`[${Number(n)+1}]`);}return e.join("")}function Lt(t,e,n=e.currentTable){if(e.dialect!=="postgres")return false;let r=e.currentSchema??e.introspection?.default_schema,s=il(t,e,n,r),i=s?.pg_type??s?.type;return i?e.introspection?.custom_types?.some(o=>o.kind==="composite"&&o.type===i&&(!s?.udt_schema||!o.schema||o.schema===s.udt_schema))??false:false}function yd(t,e){let n=t;for(let r of e)n=sql`(${n}).${sl(r)}`;return n}function bd(t,e,n,r=n.currentTable,s=false){let i=e.replace(/^\$\./,"").split(".").filter(Boolean);if(i.length===0)return de(t,n,r);if(hd(t,n,r)){let l=gd(i);if(l)return sql`${de(t,n,r)}${sql.raw(l)}`}if(Lt(t,n,r))return yd(de(t,n,r),i);let o=i.map((l,c)=>({op:c===i.length-1&&s?"->>":"->",key:l})),a=jr(o,"JSON path key");return sql`${de(t,n,r)}${sql.raw(a)}`}function Lr(t,e,n=e.currentTable,r){let{col:s,parts:i}=cn(t),o=r?St(r,s,e,n):de(s,e,n);if(i.length===0)return o;if(hd(s,e,n)){let c=gd(i.map(f=>f.key));if(c)return sql`${o}${sql.raw(c)}`}if(Lt(s,e,n))return yd(o,i.map(c=>c.key));let a=e.dialect==="sqlite"?i.map((c,f)=>f===i.length-1?{...c,op:"->>"}:c):i,l=jr(a,"JSON path key");return sql`${o}${sql.raw(l)}`}var Ii={$eq:(t,e,n)=>sql`${k(e)} = ${n}`,$neq:(t,e,n)=>sql`${k(e)} != ${n}`,$gt:(t,e,n)=>sql`${k(e)} > ${n}`,$gte:(t,e,n)=>sql`${k(e)} >= ${n}`,$lt:(t,e,n)=>sql`${k(e)} < ${n}`,$lte:(t,e,n)=>sql`${k(e)} <= ${n}`,$like:(t,e,n)=>sql`${k(e)} like ${n}`,$is:(t,e,n)=>{let r=k(e);return n===Pn?sql`${r} IS NOT NULL`:n===sn?sql`${r} IS UNKNOWN`:n===null?sql`${r} IS NULL`:n===true?sql`${r} IS TRUE`:n===false?sql`${r} IS FALSE`:sql`${r} IS NULL`},$isNot:(t,e,n)=>{let r=k(e);return n===Pn?sql`${r} IS NULL`:n===sn?sql`${r} IS NOT UNKNOWN`:n===null?sql`${r} IS NOT NULL`:n===true?sql`${r} IS NOT TRUE`:n===false?sql`${r} IS NOT FALSE`:sql`${r} IS NOT NULL`},$in:(t,e,n)=>{if(Array.isArray(n)&&n.length===0)return sql`false`;let r=k(e);return Array.isArray(n)?sql`${r} in (${sql.join(n.map(s=>sql`${s}`))})`:sql`${r} in ${n}`},$notIn:(t,e,n)=>{if(Array.isArray(n)&&n.length===0)return sql`true`;let r=k(e);return Array.isArray(n)?sql`${r} not in (${sql.join(n.map(s=>sql`${s}`))})`:sql`${r} not in ${n}`},$isDistinct:(t,e,n)=>sql`${k(e)} is distinct from ${n}`},Ni={$eq:"=",$neq:"!=",$gt:">",$gte:">=",$lt:"<",$lte:"<="};function wd(t){let e=t.replace(/^setof\s+/i,"").trim();return (e.includes(".")?e.slice(e.lastIndexOf(".")+1):e).replace(/^"|"$/g,"").trim()}function ol(t,e,n){let r=t.replace(/^setof\s+/i,"").trim(),s=r.lastIndexOf(".");if(s>=0){let i=r.slice(0,s).replace(/^"|"$/g,"").trim(),o=r.slice(s+1).replace(/^"|"$/g,"").trim();return i===n&&o===e}return r.replace(/^"|"$/g,"").trim()===e}function ji(t,e,n,r){let s=r??t?.default_schema??"public";return !!t?.columns?.some(i=>i.table===e&&i.name===n&&i.schema===s)}function Di(t,e,n){return !!(t?.tables?.some(r=>r.name===e&&r.schema===n)||t?.views?.some(r=>r.name===e&&r.schema===n))}function Ft(t,e,n,r,s){if(r!=="postgres")return null;let i=t?.functions;if(!i)return null;let o=s??t?.default_schema??"public";for(let a of i){if(a.name!==n||a.schema!==o||a.has_variadic||a.arg_types.length!==1||!ol(a.arg_types[0],e,a.schema)||!Di(t,e,a.schema)||a.return_typtype!=="c")continue;let l=wd(a.return_type);if(ol(a.return_type,l,a.schema)&&Di(t,l,a.schema))return {fnName:a.name,schema:a.schema,targetTable:l,toOne:!a.return_is_setof||a.return_rows===1}}return null}function Fr(t,e,n){let r=t.schema?`${t.schema}.${t.fnName}`:t.fnName;return Pe(r,"computed relationship function reference"),sql`${sql.raw(r)}(${sql.ref(e)})`.as(n)}function Li(t,e,n,r,s){if(r!=="postgres")return null;let i=t?.functions;if(!i)return null;let o=s??t?.default_schema??"public";for(let a of i)if(a.name===n&&a.schema===o&&!(a.has_variadic||a.arg_types.length!==1)&&ol(a.arg_types[0],e,a.schema)&&Di(t,e,a.schema)&&!(a.return_typtype==="c"&&Di(t,wd(a.return_type),a.schema)))return {fnName:a.name,schema:a.schema};return null}function Fi(t,e){let n=t.schema?`${t.schema}.${t.fnName}`:t.fnName;return Pe(n,"computed column function reference"),sql`${sql.raw(n)}(${sql.ref(e)})`}var rS=new Set(["$like","$ilike","$likeAny","$ilikeAny","$likeAll","$ilikeAll"]);function al(t){return t!=null&&typeof t=="object"&&t.type==="query"}function un(t,e){if(e.dialect==="postgres"&&e.currentTable&&!t.includes("->")&&!ji(e.introspection,e.currentTable,t,e.currentSchema)){let r=Li(e.introspection,e.currentTable,t,e.dialect,e.currentSchema);if(r)return Fi(r,e.currentTableAlias??e.currentTable)}return de(t,e)}function Ui(t,e){let n=e.db;return t.schema&&(n=n.withSchema(t.schema)),cl(t,e,n)}function sS(t){return t.includes("->")}function Td(t,e){let{col:n,parts:r}=cn(t);return r.length===0?de(t,e):Lr(t,e)}function Ee(t,e,n){let r=[];for(let[s,i]of Object.entries(e)){if(s==="$always"){i===false&&r.push(sql`0 = 1`);continue}if(s==="$or"){let o=i;r.push(t.or(o.map(a=>Ee(t,a,n))));}else if(s==="$and"){let o=i;r.push(t.and(o.map(a=>Ee(t,a,n))));}else if(s==="$not")r.push(t.not(Ee(t,i,n)));else if(s==="$exists"){let o=i;r.push(t.exists(Ui(o,n)));}else {let o=i,a=sS(s);for(let[l,c]of Object.entries(o)){if(Ai(c)){let f=Ni[l];if(!f)throw new Error(`Unsupported ref operator: ${l}`);r.push(sql`${a?Td(s,n):un(s,n)} ${sql.raw(f)} ${de(c.$ref,n)}`);continue}if(l==="$not"){let f=c;for(let[u,d]of Object.entries(f))if(a)r.push(t.not(xd(s,u,d,n)));else {let p=Sd(s,u,d,n);if(p){r.push(t.not(p));continue}let g=Ed(s,u,d,n);if(g){r.push(t.not(g));continue}let m=_d(s,u,d,n);if(m){r.push(t.not(m));continue}let h=n.operators[u];if(!h)throw new Error(`Unsupported operator: ${u}`);r.push(t.not(h(t,un(s,n),d)));}}else if(al(c)){let f=Ui(c,n),u=n.operators[l];if(!u)throw new Error(`Unsupported operator: ${l}`);r.push(u(t,un(s,n),f));}else if(a)r.push(xd(s,l,c,n));else {let f=Sd(s,l,c,n);if(f){r.push(f);continue}let u=oS(s,l,c,n);if(u){r.push(u);continue}lS(s,l,n);let d=ll(s,c,n),p=Ed(s,l,d,n);if(p){r.push(p);continue}let g=_d(s,l,d,n);if(g){r.push(g);continue}let m=n.operators[l];if(!m)throw new Error(`Unsupported operator: ${l}`);r.push(m(t,un(s,n),d));}}}}return r.length===1?r[0]:t.and(r)}function Sd(t,e,n,r){if(e!=="$is"&&e!=="$isNot"||n!==sn)return null;let s=Dn(t,r);if(!s)return null;let i=Rd(s.pg_type??s.type);if(i==="boolean")return r.dialect!=="sqlite"?null:e==="$is"?sql`${de(t,r)} IS NULL`:sql`${de(t,r)} IS NOT NULL`;throw Object.assign(new Error(`argument of IS UNKNOWN must be type boolean, not type ${i}`),{code:"42804",detail:null})}function Dn(t,e){if(!e.introspection?.columns||!e.currentTable)return null;let n=t.includes("->")?cn(t).col:t,r=e.introspection.columns.filter(i=>i.table===e.currentTable&&i.name===n);if(r.length===0)return null;let s=e.currentSchema;return r.find(i=>!s||i.schema===s)??r.find(i=>["","public"].includes(i.schema??""))??r[0]}var iS={$contains:{sym:"@>",cast:"ltree"},$containedBy:{sym:"<@",cast:"ltree"},$regex:{sym:"~",cast:"lquery"},$iregex:{sym:"~*",cast:"lquery"}};function _d(t,e,n,r){if(r.dialect!=="postgres")return null;let s=iS[e];if(!s)return null;let i=Dn(t,r);if(!i||Ne(i.pg_type,i.type)!=="ltree")return null;let o=`"${(i.udt_schema??"public").replace(/"/g,'""')}"`;return sql`${un(t,r)} OPERATOR(${sql.raw(`${o}.${s.sym}`)}) ${n}::${sql.raw(`${o}.${s.cast}`)}`}function Ed(t,e,n,r){if(r.dialect!=="postgres"||e!=="$textSearch")return null;let s=Dn(t,r);if(!s||Ne(s.pg_type,s.type)==="tsvector")return null;let i=n,o=i.config,a="to_tsquery";i.type==="plain"?a="plainto_tsquery":i.type==="phrase"?a="phraseto_tsquery":i.type==="websearch"&&(a="websearch_to_tsquery");let l=o?sql`to_tsvector(${sql.literal(o)}, ${un(t,r)})`:sql`to_tsvector(${un(t,r)})`,c=o?sql`${sql.raw(a)}(${sql.literal(o)}, ${i.query})`:sql`${sql.raw(a)}(${i.query})`;return sql`${l} @@ ${c}`}function Rd(t){switch(t.toLowerCase()){case "bool":return "boolean";case "int8":case "bigserial":case "serial8":return "bigint";case "int4":case "serial":case "serial4":return "integer";case "int2":return "smallint";default:return t.toLowerCase()}}function oS(t,e,n,r){if(r.dialect!=="postgres"||e!=="$eq"&&e!=="$neq"||typeof n!="string"||!/^\s*[[{]/.test(n))return null;let s=Dn(t,r),i=Rd(s?.pg_type??s?.type??"");if(i!=="json"&&i!=="jsonb")return null;let o=de(t,r),a=sql`cast(${sql.raw(aS(n))} as ${sql.raw(i)})`;return e==="$eq"?sql`${o} = ${a}`:sql`${o} != ${a}`}function aS(t){return `'${t.replace(/'/g,"''")}'`}function lS(t,e,n){if(!rS.has(e))return;let r=Dn(t,n);if(!r||Ne(r.pg_type,r.type)!=="color")return;let i=e.includes("ilike")?"~~*":"~~";throw Object.assign(new Error(`operator does not exist: color ${i} unknown`),{code:"42883",detail:null,hint:"No operator matches the given name and argument types. You might need to add explicit type casts."})}function ll(t,e,n){if(!n?.currentTable)return e;let r=Dn(t,n);if(!r)return e;let s=Ne(r.pg_type,r.type);if(s==="color")return fd(e);if(s==="isodate"||s==="isodatetext")if(Array.isArray(e))for(let i of e)nl(i);else nl(e);return e}function xd(t,e,n,r){let s=r?Td(t,r):k(t),o={$eq:"=",$neq:"!=",$gt:">",$gte:">=",$lt:"<",$lte:"<=",$like:"like",$ilike:"ilike"}[e];if(o)return sql`${s} ${sql.raw(o)} ${n}`;if(e==="$is")return n===null?sql`${s} IS NULL`:n===true?sql`${s} IS TRUE`:n===false?sql`${s} IS FALSE`:sql`${s} IS NULL`;if(e==="$isNot")return n===null?sql`${s} IS NOT NULL`:n===true?sql`${s} IS NOT TRUE`:n===false?sql`${s} IS NOT FALSE`:sql`${s} IS NOT NULL`;if(e==="$in"){if(r&&al(n))return sql`${s} in ${Ui(n,r)}`;let a=ll(t,n,r);return a.length===0?sql`false`:sql`${s} in (${sql.join(a.map(l=>sql`${l}`))})`}if(e==="$notIn"){if(r&&al(n))return sql`${s} not in ${Ui(n,r)}`;let a=ll(t,n,r);return a.length===0?sql`true`:sql`${s} not in (${sql.join(a.map(l=>sql`${l}`))})`}return sql`${s} = ${n}`}function Ur(t,e){let n={};for(let[r,s]of Object.entries(t))r==="$or"||r==="$and"?n[r]=s.map(i=>Ur(i,e)):r==="$not"?n[r]=Ur(s,e):r.startsWith("$")||r.includes(".")?n[r]=s:n[`${e}.${r}`]=s;return n}function it(t){let e=t.leftCols??[t.leftCol],n=t.rightCols??[t.rightCol];return e.map((r,s)=>({leftCol:r,rightCol:n[s]??t.rightCol}))}function ul(t,e){return `${t}_${e}_fkey`}function Mi(t,e){return e===ul(t.table,t.column)}function Cd(t){let e=new Map;for(let n of t){let r=n.foreign_key_group??n.foreign_key_name,s=e.get(r);s?s.push(n):e.set(r,[n]);}return [...e.values()]}function kd(t,e,n){return {leftCol:`${t}.${n.column}`,rightCol:`${e}.${n.ref_column}`,type:"m2o"}}function vd(t,e,n){return {leftCol:`${e}.${n.column}`,rightCol:`${t}.${n.ref_column}`,type:"o2m"}}function cS(t,e,n){switch(t.kind){case "constraint":case "pg_autogen":case "ref_column":return t.direction==="m2o"?kd(e,n,t.fk):vd(e,n,t.fk);case "parent_column":return kd(e,n,t.fk);case "target_column":return vd(e,n,t.fk);case "junction_table":return {type:"m2m",junctionTable:t.junctionTable,junctionToParentCols:t.toParent.map(r=>r.column),parentCols:t.toParent.map(r=>r.ref_column),junctionToTargetCols:t.toTarget.map(r=>r.column),targetCols:t.toTarget.map(r=>r.ref_column)}}}function Ad(t,e,n,r){let s=r.find(o=>o.foreign_key_name===t&&o.table===e&&o.ref_table===n);if(s)return {kind:"constraint",fk:s,direction:"m2o"};let i=r.find(o=>o.foreign_key_name===t&&o.table===n&&o.ref_table===e);return i?{kind:"constraint",fk:i,direction:"o2m"}:null}function Od(t,e,n,r){let s=r.find(o=>o.table===e&&o.ref_table===n&&Mi(o,t));if(s)return {kind:"pg_autogen",fk:s,direction:"m2o"};let i=r.find(o=>o.table===n&&o.ref_table===e&&Mi(o,t));return i?{kind:"pg_autogen",fk:i,direction:"o2m"}:null}function Pd(t,e,n,r){let s=r.find(i=>i.table===e&&i.column===t&&i.ref_table===n);return s?{kind:"parent_column",fk:s}:null}function $d(t,e,n,r){let s=r.find(i=>i.table===n&&i.column===t&&i.ref_table===e);return s?{kind:"target_column",fk:s}:null}function Id(t,e,n,r){let s=r.filter(a=>a.table===t),i=Cd(s.filter(a=>a.ref_table===e)),o=Cd(s.filter(a=>a.ref_table===n));return i.length===0||o.length===0?null:{kind:"junction_table",junctionTable:t,toParent:i[0],toTarget:o[0]}}function Nd(t,e,n,r){let s=r.find(i=>i.table===n&&i.ref_column===t&&i.ref_table===e);return s?{kind:"ref_column",fk:s,direction:"o2m"}:null}function Dd(t,e,n,r){let s=r.find(i=>i.table===e&&i.ref_column===t&&i.ref_table===n);return s?{kind:"ref_column",fk:s,direction:"m2o"}:null}var uS=[Ad,Od,Pd,$d,Id,Nd,Dd];function jd(t,e,n,r,s={}){let i=s.preferSelfReferenceTargetColumn&&e===n?[Ad,Od,$d,Pd,Id,Nd,Dd]:uS;for(let o of i){let a=o(t,e,n,r);if(a)return cS(a,e,n)}return null}function Bi(t,e,n,r){t=t.innerJoin(e.junctionTable,s=>{let i=s;for(let o=0;o<e.junctionToTargetCols.length;o++)i=i.onRef(`${e.junctionTable}.${e.junctionToTargetCols[o]}`,"=",`${n}.${e.targetCols[o]}`);return i});for(let s=0;s<e.junctionToParentCols.length;s++)t=t.whereRef(`${e.junctionTable}.${e.junctionToParentCols[s]}`,"=",`${r}.${e.parentCols[s]}`);return t}function Mr(t,e,n,r){if(e.type==="m2m")return Bi(t,e,n,r);for(let{leftCol:s,rightCol:i}of it(e))t=t.whereRef(s,"=",i);return t}function Br(t){return t.foreign_key_name?.endsWith("_fkey")||t.foreign_key_name&&!t.foreign_key_name.startsWith("fk_")?t.foreign_key_name:ul(t.table,t.column)}function jn(t,e,n,r,s,i){if(!n||!e||!i.introspection?.foreign_keys)return {qb:t,remainingWhere:e};if(Object.keys(e).length===0||!Ud(e,n))return {qb:t,remainingWhere:e};let o=e;return t=t.where(a=>{let l=Ld(a,e,n,r,s,i);return o=l.remainingWhere,l.expression??sql`1 = 1`}),Object.keys(o).length===Object.keys(e).length?{qb:t,remainingWhere:e}:{qb:t,remainingWhere:o}}function Ld(t,e,n,r,s,i){let o=[],a={};for(let[c,f]of Object.entries(e)){if((c==="$or"||c==="$and")&&Array.isArray(f)){let d=f.map(p=>Ld(t,p,n,r,s,i));if(d.length>0&&d.every(p=>p.fullyHandled&&p.expression)){o.push(c==="$or"?t.or(d.map(p=>p.expression)):t.and(d.map(p=>p.expression)));continue}a[c]=f;continue}let u=fS(t,c,f,n,r,s,i);u?o.push(u):a[c]=f;}let l=o.length===0?null:o.length===1?o[0]:t.and(o);return {expression:l,remainingWhere:a,fullyHandled:l!==null&&Object.keys(a).length===0}}function fS(t,e,n,r,s,i,o){let a=n;if(!a||typeof a!="object")return null;let l="$is"in a&&a.$is===null,c="$isNot"in a&&a.$isNot===null;if(!l&&!c)return null;let f=Fd(r,e);if(!f)return null;let u=s?.[e],d=Ft(o.introspection,i,u?.from||e,o.dialect,o.currentSchema);if(d){let w=t.selectFrom(Fr(d,i,d.targetTable)).select(sql`1`.as("_"));if(f.where&&Object.keys(f.where).length>0){let b=jn(w,f.where,f.select,f.join,d.targetTable,o);if(w=b.qb,Object.keys(b.remainingWhere).length>0){let _=Ur(b.remainingWhere,d.targetTable);w=w.where(E=>Ee(E,_,o));}}let S=t.exists(w);return c?S:t.not(S)}let p=xe(i,e,u,o.introspection),{targetTable:g,fkRel:m}=p;if(!m)return null;let h=t.selectFrom(g).select(sql`1`.as("_"));if(u?.on?h=h.where(w=>Ee(w,u.on,o)):h=Mr(h,m,g,i),f.where&&Object.keys(f.where).length>0){let w=jn(h,f.where,f.select,f.join,g,o);if(h=w.qb,Object.keys(w.remainingWhere).length>0){let S=Ur(w.remainingWhere,g);h=h.where(b=>Ee(b,S,o));}}let y=t.exists(h);return c?y:t.not(y)}function Fd(t,e){for(let n of t){if(typeof n=="string")continue;let r=n[e];if(r&&re(r))return r}return null}function Ud(t,e){for(let[n,r]of Object.entries(t)){if((n==="$or"||n==="$and")&&Array.isArray(r)){if(r.some(a=>Ud(a,e)))return true;continue}let s=r;if(!s||typeof s!="object")continue;let i="$is"in s&&s.$is===null,o="$isNot"in s&&s.$isNot===null;if((i||o)&&Fd(e,n))return true}return false}function re(t){return "select"in t||"spread"in t||"join"in t}function hl(t){if(typeof t=="string")return null;let[e,n]=Object.entries(t)[0]??[];return !e||n===void 0?null:{alias:e,def:n}}function Hr(t){return hl(t)?.def??null}function dS(t,e,n,r){if(t?.hint)return t.hint;if(!n||!r?.foreign_keys)return;let s=t?.from;return s&&s!==e&&r.foreign_keys.some(a=>a.table===n&&a.column===s)?s:r.foreign_keys.some(o=>o.table===n&&o.column===e)?e:void 0}function Md(t){return t.includes(".")?t.slice(t.lastIndexOf(".")+1):t}function Ki(t,e,n,r,s,i=false,o,a){let l=o??s,c=n.dialect==="postgres";if(!e||e.length===0)return c&&l&&(Dr(l,n.introspection,Fe(n))||Hi(l,n))?Bd(t,l,n,new Set,false,s):t.selectAll();for(let f of e)if(typeof f=="string")if(f==="*")if(c&&l&&(Dr(l,n.introspection,Fe(n))||Hi(l,n))){let u=new Set;for(let d of e){if(d===f)break;if(typeof d=="string"&&d!=="*")u.add(d.includes(".")?d.split(".").pop():d);else if(typeof d!="string")for(let[p]of Object.entries(d))u.add(p);}t=Bd(t,l,n,u,i,s);}else t=i&&s?t.selectAll(s):t.selectAll();else if(/^-?\d+(?:\.\d+)?$/.test(f))t=t.select(sql.lit(Number(f)).as("_lit"));else if(TS(f,n,s)){let u=i&&s?St(s,f,n,s):de(f,n,s);t=t.select(sql`json(${u})`.as(f));}else if(c&&l&&s&&!f.includes(".")&&!ji(n.introspection,l,f,n.currentSchema)){let u=Li(n.introspection,l,f,n.dialect,n.currentSchema);t=u?t.select(Fi(u,s).as(f)):t.select(f);}else if(c&&s&&l&&pd(l,Md(f),n.introspection,Fe(n))){let u=Md(f),d=f.includes(".")?sql.ref(f):i?St(s,f,n,s):sql.ref(f);t=t.select(Nr(d,l,u,n.dialect,n.introspection,Fe(n)).as(u));}else t=i&&s&&!f.includes(".")?t.select(St(s,f,n,s).as(f)):!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(f)&&$i(f,n,s)?t.select(de(f,n,s).as(f)):t.select(f);else for(let[u,d]of Object.entries(f))re(d)?t=GS(t,u,d,n,r,l,a):t=bS(t,u,d,n,s,i,l);return t}function Fe(t){return t.currentSchema??t.introspection?.default_schema??"public"}function Hi(t,e){if(!t||e.dialect!=="postgres"||!e.introspection?.columns)return false;let n=Fe(e);return e.introspection.columns.some(r=>r.table===t&&(r.schema??"public")===n&&Lt(r.name,e,t))}function Bd(t,e,n,r,s=false,i=e){if(!n.introspection)return s?t.selectAll(i):t.selectAll();let o=rl(e,n.introspection,Fe(n));if(o.length===0)return s?t.selectAll(i):t.selectAll();for(let{name:a,isDomain:l,domainTypeName:c}of o){if(r.has(a))continue;let f=s?sql`${sql.ref(i)}.${sql.ref(a)}`:sql.ref(a);if(l&&c){let u=Pi(f,c);t=t.select((u??f).as(a));}else Lt(a,n,e)?t=t.select(sql`to_jsonb(${f})`.as(a)):t=s?t.select(f.as(a)):t.select(a);}return t}function Wr(t,e,n){let r=n?.dialect==="postgres",s=n?.currentTable;if(!e||e.length===0)return r&&s&&(Dr(s,n.introspection,Fe(n))||Hi(s,n))?qd(t,s,n):t;for(let i of e)if(typeof i=="string")if(i==="*")if(r&&s&&(Dr(s,n.introspection,Fe(n))||Hi(s,n))){let o=new Set;for(let a of e){if(a===i)break;if(typeof a=="string"&&a!=="*")o.add(a.includes(".")?a.split(".").pop():a);else if(typeof a!="string")for(let[l]of Object.entries(a))o.add(l);}t=qd(t,s,n,o);}else t=t.returningAll();else if(r&&s&&Lt(i,n,s))t=t.returning(sql`to_jsonb(${sql.ref(i)})`.as(i));else if(r&&s){let o=sql.ref(i),a=Nr(o,s,i,n.dialect,n.introspection,Fe(n));t=a!==o?t.returning(a.as(i)):t.returning(i);}else t=t.returning(i);else for(let[o,a]of Object.entries(i)){if(re(a))continue;let l=a.column||o;if(r&&s&&!a.cast&&!a.path&&!a.aggregate&&Lt(l,n,s))t=t.returning(sql`to_jsonb(${sql.ref(l)})`.as(o));else if(r&&s&&!a.cast&&!a.path&&!a.aggregate){let c=sql.ref(l),f=Nr(c,s,l,n.dialect,n.introspection,Fe(n));t=f!==c?t.returning(f.as(o)):t.returning(l);}else t=t.returning(l);}return t}function qd(t,e,n,r){if(!n.introspection)return t.returningAll();let s=rl(e,n.introspection,Fe(n));if(s.length===0)return t.returningAll();for(let{name:i,isDomain:o,domainTypeName:a}of s)if(!r?.has(i))if(o&&a){let l=sql.ref(i),c=Pi(l,a);c?t=t.returning(c.as(i)):t=t.returning(i);}else Lt(i,n,e)?t=t.returning(sql`to_jsonb(${sql.ref(i)})`.as(i)):t=t.returning(i);return t}function Kr(t,e,n,r,s,i=false,o){let a;if(n.aggregate==="count"&&!n.column&&!n.path)a=t.fn.countAll();else {let l=n.column||e;if(n.invalidJsonTextTraversalKey&&r.dialect==="postgres")throw Object.assign(new Error(`operator does not exist: text -> ${mS(n.invalidJsonTextTraversalKey)}`),{code:"42883",detail:null,hint:"No operator matches the given name and argument types. You might need to add explicit type casts."});if(n.path)a=bd(l,n.path,r,s,n.pathText===true);else {let c=s&&i?St(s,l,r,s):de(l,r,s);a=r.dialect==="postgres"&&!n.cast&&!n.preCast&&!n.aggregate?Nr(c,o??s??r.currentTable,l,r.dialect,r.introspection,Fe(r)):c;}n.preCast&&(ln(n.preCast,"pre-cast type"),a=sql`cast(${a} as ${sql.raw(n.preCast)})`),n.aggregate&&(a=sql`${sql.raw(n.aggregate)}(${a})`);}return n.cast&&(ln(n.cast,"cast type"),r.dialect==="sqlite"&&n.pathText===true&&pS(n.cast)||(n.cast.trim().toLowerCase()==="text"&&n.column&&yS(r,s,n.column)?a=cd(a,r.dialect):a=r.dialect==="sqlite"&&(hS(n.cast)||gS(n.cast))?sql`json(${a})`:sql`cast(${a} as ${sql.raw(n.cast)})`)),a}function pS(t){let e=t.trim().toLowerCase();return e==="integer"||e==="int"||e==="int2"||e==="int4"||e==="int8"||e==="bigint"||e==="smallint"}function mS(t){return /^-?\d+$/.test(t)?"integer":"unknown"}function hS(t){let e=t.trim().toLowerCase();return e==="json"||e==="jsonb"}function gS(t){let e=t.trim().toLowerCase();return e.startsWith("_")||e.endsWith("[]")}function yS(t,e,n){let r=e??t.currentTable;if(!r||!t.introspection?.columns)return false;let s=t.introspection.columns.filter(o=>o.table===r&&o.name===n);if(s.length===0)return false;let i=s.find(o=>o.schema===Fe(t))??s.find(o=>o.schema==="public")??s[0];return Ne(i.pg_type,i.type)==="color"}function bS(t,e,n,r,s,i=false,o){return t.select(a=>Kr(a,e,n,r,s,i,o).as(e))}function wS(t){if(!t)return false;for(let e of t)if(typeof e!="string"){for(let n of Object.values(e))if(!re(n)&&n.aggregate)return true}return false}function SS(t){if(!t)return false;for(let e of t)if(typeof e!="string"){for(let n of Object.values(e))if(re(n)&&n.spread&&gl(n.select))return true}return false}function Hd(t){if(!t)return false;for(let e of t)if(typeof e!="string"){for(let n of Object.values(e))if(re(n)&&n.spread)return true}return false}function _S(t){return wS(t)||SS(t)}function gl(t){if(!t)return false;for(let e of t)if(typeof e!="string")for(let n of Object.values(e)){if(re(n)){if(gl(n.select))return true;continue}if(n.aggregate)return true}return false}function yl(t){if(!t)return false;for(let e of t)if(typeof e!="string")for(let n of Object.values(e)){if(re(n)){if(n.spread)continue;if(yl(n.select))return true;continue}if(n.aggregate&&!n.bareCount)return true}return false}function bl(t,e,n,r,s,i=false,o){if(!_S(e))return t;let a=[];for(let l of e){if(typeof l=="string"){if(l==="*")continue;a.push(de(l,n,r));continue}for(let[c,f]of Object.entries(l))re(f)||f.aggregate||a.push(u=>Kr(u,c,f,n,r,i,o));}return ES(a,e,n,r,s),a.length===0?t:t.groupBy(a)}function ES(t,e,n,r,s){if(!(!e||!r||!n.introspection?.foreign_keys)){for(let i of e)if(typeof i!="string")for(let[o,a]of Object.entries(i)){if(!re(a)||!a.spread)continue;let l=a,c=s?.[o],f=xe(r,o,c,n.introspection);if(!f.fkRel||!_t(f))continue;let u=f.targetTable;f.fkRel;let p=Gi(l.select,u,n.introspection)??l.select??[],g=`_spread_${o}`;for(let m of p){if(typeof m=="string"){m!=="*"&&t.push(`${g}.${m}`);continue}let[h,y]=Object.entries(m)[0];re(y)||y.aggregate||t.push(w=>Kr(w,h,y,n,g,true));}}}}function zd(t,e,n,r,s){if(!t||!e||!r||!s.introspection?.foreign_keys)return t;let i=new Set;for(let o of e)if(typeof o!="string")for(let[a,l]of Object.entries(o)){if(!re(l)||!l.spread)continue;let c=n?.[a],f=xe(r,a,c,s.introspection);f.fkRel&&_t(f)&&i.add(a);}return i.size===0?t:t.map(o=>o.embed&&i.has(o.embed)?{...o,embed:`_spread_${o.embed}`}:o)}function Vd(t,e,n,r){if(!t||!n||!r.introspection?.foreign_keys)return false;for(let s of t)if(typeof s!="string")for(let[i,o]of Object.entries(s)){if(!re(o)||!o.spread)continue;let a=e?.[i],l=xe(n,i,a,r.introspection);if(l.fkRel&&_t(l))return true}return false}function Ln(t){let e=new Map;for(let n of t){let r=n.foreign_key_group??n.foreign_key_name,s=e.get(r);s?s.push(n):e.set(r,[n]);}return [...e.values()]}function qr(t,e,n,r){let s=r==="m2o"?n.map(o=>`${t}.${o.column}`):n.map(o=>`${e}.${o.column}`),i=r==="m2o"?n.map(o=>`${e}.${o.ref_column}`):n.map(o=>`${t}.${o.ref_column}`);return {leftCol:s[0],rightCol:i[0],leftCols:s,rightCols:i,type:r,fk:n[0]}}function wl(t,e,n,r,s=n){let i=s===n?n:`${n} as ${s}`;return e.type==="m2o"?t.leftJoin(i,o=>{let a=o;for(let{leftCol:l,rightCol:c}of it(e)){let[,f]=l.split("."),[,u]=c.split(".");a=a.onRef(`${s}.${u}`,"=",`${r}.${f}`);}return a}):t.leftJoin(i,o=>{let a=o;for(let{leftCol:l,rightCol:c}of it(e)){let[,f]=l.split("."),[,u]=c.split(".");a=a.onRef(`${s}.${f}`,"=",`${r}.${u}`);}return a})}function Ji(t,e,n,r,s){let i=new Set;if(!e||!r.introspection?.foreign_keys)return {sub:t,joined:i};for(let o of e){if(!o.embed||i.has(o.embed))continue;Pe(o.embed,"order embed alias");let a=s?.[o.embed],l=xe(n,o.embed,a,r.introspection);if(l.targetTable!==o.embed&&Pe(l.targetTable,"order embed target"),!l.fkRel||!_t(l)||l.fkRel.type==="m2m")continue;let{targetTable:c,fkRel:f}=l;t=wl(t,f,c,n,o.embed),i.add(o.embed),i.add(c);}return {sub:t,joined:i}}function xS(t){return t&&t.map(e=>e.embed&&e.nullsFirst===void 0?{...e,nullsFirst:e.direction==="desc"}:e)}function Wi(t,e,n){let r=n.includes(".")?n.split(".").pop():n,s=t.introspection?.columns?.find(o=>o.table===e&&o.name===r),i=(s?.pg_type||s?.type||"").toLowerCase();return i==="json"||i==="jsonb"}function TS(t,e,n){return e.dialect==="sqlite"&&n!==void 0&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)&&Wi(e,n,t)}function RS(t,e){if(!t)return false;let n=e.includes(".")?e.split(".").pop():e;return t.some(r=>r.column.includes("->")?r.column.slice(0,r.column.indexOf("->"))===n:false)}function Qd(t,e,n,r){return Wi(t,e,n)||RS(r,n)}function CS(t,e,n){if(!t)return null;let r=[];for(let s of t){if(typeof s=="string"){if(s==="*")return null;let l=s.includes(".")?s.split(".").pop():s;r.push({alias:l,asJson:Wi(n,e,l)});continue}let[i,o]=Object.entries(s)[0];if(!i||!o)continue;if(re(o))return null;let a=Wi(n,e,o.column||i);r.push({alias:i,asJson:a});}return r}function kS(t,e,n,r){let s=CS(e,n,r);if(!s||s.length===0)return r.jsonObjectFrom(t);let i=s.flatMap(o=>[sql.lit(o.alias),o.asJson?sql`json(${sql.ref(`obj.${o.alias}`)})`:sql.ref(`obj.${o.alias}`)]);return sql`(select json_object(${sql.join(i)}) from ${t} as obj)`}function Xd(t){if(!t||t.length===0)return false;for(let e of t){if(typeof e=="string")return true;let n=hl(e);if(n&&(!re(n.def)||Xd(n.def.select)))return true}return false}function Yd(t,e,n){return n?n.indexes?.some(i=>i.table===t&&i.unique&&i.columns.length===1&&i.columns[0]===e)||n.unique_constraints?.some(i=>i.table===t&&i.columns.length===1&&i.columns[0]===e)?true:n.primary_keys?.some(i=>i.table===t&&i.columns.length===1&&i.columns[0]===e)??false:false}function vS(t,e,n,r){if(t.type==="m2m")return "many-to-many";if(t.type==="m2o"&&r&&t.fk)return Yd(e,t.fk.column,r)?"one-to-one":"many-to-one";if(t.type==="o2m"&&r&&t.fk){let s={leftCol:`${n}.${t.fk.column}`,rightCol:`${e}.${t.fk.ref_column}`,type:"o2m"};if(np(r,e,n,void 0,s))return "one-to-one"}return "one-to-many"}function AS(t,e,n){if(!t?.views?.length)return [];let r=n??t.tables?.find(s=>s.name===e)?.schema??t.foreign_keys?.find(s=>s.table===e)?.schema;return t.views.filter(s=>s.name!==e&&s.sql&&OS(s.sql)===e&&(!r||s.schema===r)).map(s=>s.name)}function OS(t){let e=t.match(/\bfrom\s+((?:"[^"]+"|`[^`]+`|\[[^\]]+\]|[\w$]+)(?:\s*\.\s*(?:"[^"]+"|`[^`]+`|\[[^\]]+\]|[\w$]+))?)/i);if(!e)return;let n=e[1].split(/\s*\.\s*/);return n[n.length-1].replace(/^["`[]|["`\]]$/g,"")}function PS(t,e){let n=new Set(e?.views?.map(s=>s.name)??[]),r=t.filter(s=>s.type==="m2m"&&!n.has(s.junctionTable));for(let s of r){if(s.type!=="m2m")continue;let i=s.parentFkGroup?.[0]?.schema;for(let o of AS(e,s.junctionTable,i))t.push({...s,junctionTable:o});}}function $S(t){if(t.type!=="m2m")return null;let e=t.parentFkGroup?.[0]?.foreign_key_name??"",n=t.targetFkGroup?.[0]?.foreign_key_name??"";return `${t.junctionTable}:${e}:${n}`}function Wd(t){return t.type!=="m2m"?0:[...t.parentFkGroup??[],...t.targetFkGroup??[]].filter(n=>n.foreign_key_group).length}function IS(t){let e=[],n=new Map;for(let r of t){let s=$S(r);if(!s){e.push(r);continue}let i=n.get(s);if(i===void 0){n.set(s,e.length),e.push(r);continue}Wd(r)<Wd(e[i])&&(e[i]=r);}return e}function dl(t,e){if(t.type==="m2m")return t.junctionTable;if(t.fk)return Br(t.fk)}function pl(t,e,n,r){if(t.type==="m2m"&&t.parentFkGroup?.[0]&&t.targetFkGroup?.[0]){let a=t.parentFkGroup[0],l=t.targetFkGroup[0];return `${t.junctionTable} using ${Br(a)}(${a.column}) and ${Br(l)}(${l.column})`}if(t.type==="m2m"||!t.fk)return "";let s=Br(t.fk);if(t.type==="o2m"){let a=qi(t.rightCols??[t.rightCol]),l=qi(t.leftCols??[t.leftCol]);return `${s} using ${e}(${a}) and ${n}(${l})`}let i=qi(t.leftCols??[t.leftCol]),o=qi(t.rightCols??[t.rightCol]);return `${s} using ${e}(${i}) and ${n}(${o})`}function qi(t){return t.map(e=>e.split(".").at(-1)??e).join(", ")}function NS(t,e,n){if(!t||!e)return null;let r=t.partitions?.find(o=>o.name===e&&(!n||o.schema===n));if(r)return `Perhaps you meant '${r.parent}' instead of '${e}'.`;let s=[];for(let o of t.tables??[])s.push(o.name);for(let o of t.views??[])s.push(o.name);let i=s.find(o=>o.length===e.length+1&&o.startsWith(e));return i?`Perhaps you meant '${i}' instead of '${e}'.`:null}function Sl(t,e,n,r){let s=t?.foreign_keys?.find(o=>o.table===e||o.ref_table===e)?.schema||"test",i=r?` using the hint '${r}'`:"";throw new ve({httpStatus:400,code:"PGRST200",message:`Could not find a relationship between '${e}' and '${n}' in the schema cache`,details:`Searched for a foreign key relationship between '${e}' and '${n}'${i} in the schema '${s}', but no matches were found.`,hint:NS(t,n,s)})}function DS(t,e,n,r,s=false){if(!t||!t.foreign_keys)return null;let i=t.foreign_keys.filter(h=>h.is_visible!==false);if(r){let h=jd(r,e,n,i,{preferSelfReferenceTargetColumn:s});if(h)return h;Sl(t,e,n,r);}if(e===n){let h=Ln(i.filter(y=>y.table===n&&y.ref_table===e))[0];if(h)return qr(e,n,h,"o2m")}let o=i.filter(h=>h.table===e&&h.ref_table===n),a=Ln(o),l=i.filter(h=>h.table===n&&h.ref_table===e),c=Ln(l),f=[],u=Ln(i.filter(h=>h.ref_table===e));for(let h of u){let y=h[0].table;if(y===e||y===n)continue;let w=i.filter(S=>S.table===y&&S.ref_table===n);if(w.length!==0)for(let S of Ln(w))f.push({type:"m2m",junctionTable:y,junctionToParentCols:h.map(b=>b.column),parentCols:h.map(b=>b.ref_column),junctionToTargetCols:S.map(b=>b.column),targetCols:S.map(b=>b.ref_column),fk:h[0],parentFkGroup:h,targetFkGroup:S});}if(a.length+c.length+f.length===0)return null;let p=[...f];PS(p,t),p=IS(p);let g=e!==n&&a.length>0&&c.length>0;if(a.length>1||c.length>1||a.length===0&&c.length===0&&p.length>1||g||a.length>0&&p.length>1){let h=[...a.map(E=>qr(e,n,E,"m2o")),...c.map(E=>qr(e,n,E,"o2m")),...p],y={o2m:0,m2o:1,m2m:2},w=[...h].sort((E,x)=>{let O=y[E.type]??3,v=y[x.type]??3;if(O!==v)return O-v;let P=dl(E)??"",C=dl(x)??"",R=P.localeCompare(C);return R!==0?R:pl(E,e,n).localeCompare(pl(x,e,n))}),S=w.map(E=>({cardinality:vS(E,e,n,t),embedding:`${e} with ${n}`,relationship:pl(E,e,n)})),_=w.map(E=>dl(E)).filter(Boolean).map(E=>`'${n}!${E}'`).join(", ");throw new ve({httpStatus:300,code:"PGRST201",message:`Could not embed because more than one relationship was found for '${e}' and '${n}'`,details:S,hint:_?`Try changing '${n}' to one of the following: ${_}. Find the desired relationship in the 'details' key.`:null})}return a.length===1?qr(e,n,a[0],"m2o"):c.length===1?qr(e,n,c[0],"o2m"):f.length===1?f[0]:null}function jS(t,e,n){if(!n?.foreign_keys)return {targetTable:t};let r=n.foreign_keys,s=r.find(l=>l.table===e&&l.column===t);if(s)return {targetTable:s.ref_table,resolvedFkHint:t};let i=r.find(l=>(l.foreign_key_name===t||Mi(l,t))&&(l.table===e||l.ref_table===e));if(i)return {targetTable:i.table===e?i.ref_table:i.table,resolvedFkHint:t};let o=r.find(l=>l.ref_table===e&&l.ref_column===t);return o?{targetTable:o.table,resolvedFkHint:t}:n.tables?.some(l=>l.name===t)||n.views?.some(l=>l.name===t)?{targetTable:t}:{targetTable:t}}function LS(t,e,n,r,s){if(!t)return "o2m";if(t.type==="m2m")return "m2m";if(t.type==="m2o"){let i=t.leftCol.split(".")[1];return Yd(e,i,s)?"o2o":"m2o"}return np(s,e,n,r,t)?"o2o":"o2m"}function xe(t,e,n,r){let s=n?.from||e,{targetTable:i,resolvedFkHint:o}=jS(s,t,r),a=dS(n,e,t,r)??o,l=t===i&&!!(n?.hint&&n.from&&n.from!==e),c=r?.foreign_keys&&t?DS(r,t,i,a,l):null,f=LS(c,t,i,a,r);return {targetTable:i,fkRel:c,cardinality:f,displayHint:a}}function _t(t){return t.cardinality==="m2o"||t.cardinality==="o2o"}function Zd(t,e,n,r){if(!(!t||!n||!r.introspection?.foreign_keys))for(let s of t){if(!s.embed)continue;let i=e?.[s.embed],o=xe(n,s.embed,i,r.introspection);if(o.fkRel&&!_t(o))throw new ve({httpStatus:400,code:"PGRST118",message:`A related order on '${s.embed}' is not possible`,details:`'${n}' and '${s.embed}' do not form a many-to-one or one-to-one relationship`,hint:null})}}function Kd(t,e,n,r,s){let i=e.join??r;if(!e.select||!i)return t;for(let o of e.select){if(typeof o=="string")continue;let a=Object.keys(o)[0],l=o[a];if(!re(l)||!l.select)continue;let c=i[a];if(c?.type!=="inner")continue;let f=Ft(s.introspection,n,c?.from||a,s.dialect,s.currentSchema),u=f?f.targetTable:xe(n,a,c,s.introspection).targetTable;t=t.where(d=>ep(d,l,u,n,c,l.join??i,s));}return t}function ep(t,e,n,r,s,i,o){let a=r?Ft(o.introspection,r,s?.from??n,o.dialect,o.currentSchema):null;if(a){let u=t.selectFrom(Fr(a,r,a.targetTable)).select(sql`1`.as("_"));return e.where&&Object.keys(e.where).length>0&&(u=u.where(d=>Ee(d,e.where,{...o,currentTable:a.targetTable}))),r&&(u=Kd(u,e,a.targetTable,i,o)),t.exists(u)}let c=(r?xe(r,s?.from??n,s,o.introspection):null)?.fkRel??null,f=t.selectFrom(n).select(sql`1`.as("_"));if(s?.on)f=f.where(u=>Ee(u,s.on,o));else if(c&&c.type==="m2m")f=Bi(f,c,n,r);else if(c)for(let{leftCol:u,rightCol:d}of it(c))f=f.whereRef(u,"=",d);else r&&(f=f.whereRef(`${n}.${r}_id`,"=",`${r}.id`));return e.where&&Object.keys(e.where).length>0&&(f=f.where(u=>Ee(u,e.where,{...o,currentTable:n}))),r&&(f=Kd(f,e,n,i,o)),t.exists(f)}function Jd(t,e,n,r,s,i){let o=s?.[e],a=i?Ft(r.introspection,i,o?.from||e,r.dialect,r.currentSchema):null,l=a?a.targetTable:i?xe(i,e,o,r.introspection).targetTable:o?.from||e;return t.where(c=>ep(c,n,l,i,o,s,r))}function tp(t,e,n){if(!n||t.type!=="o2m")return false;let r=t.leftCol.split(".")[1];return n.indexes?.some(o=>o.table===e&&o.unique&&o.columns.length===1&&o.columns[0]===r)||n.unique_constraints?.some(o=>o.table===e&&o.columns.length===1&&o.columns[0]===r)?true:n.primary_keys?.some(o=>o.table===e&&o.columns.length===1&&o.columns[0]===r)??false}function np(t,e,n,r,s){if(!t?.foreign_keys||!s||s.type!=="o2m")return false;if(tp(s,n,t))return true;let o=t.foreign_keys.filter(u=>u.is_visible!==false).filter(u=>u.table===n&&u.ref_table===e);if(r){let u=o.filter(d=>d.foreign_key_name===r);u.length>0&&(o=u);}let a=Ln(o);if(a.length!==1)return false;let l=[...a[0].map(u=>u.column)].sort(),c=t.primary_keys?.find(u=>u.table===n);if(!c?.columns?.length)return false;let f=[...c.columns].sort();return l.length===f.length&&l.every((u,d)=>u===f[d])}function FS(t,e){return t&&t.map(n=>typeof n!="string"||n==="*"||n.includes(".")||/^-?\d+(?:\.\d+)?$/.test(n)?n:`${e}.${n}`)}function Mt(t){if(typeof t=="string")return {colAlias:t,colName:t};let e=Object.keys(t)[0],n=t[e];return {colAlias:e,colName:n?.column||e}}function US(t,e,n,r,s,i){if(!n.select||!i)return t;let o=s?.[e],a=xe(i,e,o,r.introspection),{targetTable:l,fkRel:c}=a,f=Gi(n.select,l,r.introspection)??n.select;if(!r.introspection?.foreign_keys)return JS(t,f,l,i,c);if(!c)throw new ve({httpStatus:400,code:"PGRST120",message:"Could not embed because the relationship is not a one-to-one or many-to-one",details:null,hint:null});if(!_t(a)){if(gl(n.select))throw new ve({httpStatus:400,code:"PGRST127",message:"Feature not implemented",details:"Aggregates are not implemented for one-to-many or many-to-many spreads.",hint:null});return KS(t,f,n,c,l,i,r)}let u=`_spread_${e}`;if(c.type!=="m2o"&&c.type!=="o2m")throw new ve({httpStatus:400,code:"PGRST120",message:"Could not embed because the relationship is not a one-to-one or many-to-one",details:null,hint:null});let d=it(c).map(({leftCol:m,rightCol:h},y)=>{let[w,S]=m.split("."),[,b]=h.split(".");return {targetSideCol:w===l?S:b,parentSideCol:w===i?S:b,joinKey:`__spread_join_key_${y}`}}),p=[],g=new Set;for(let m of f){if(typeof m=="string"&&m==="*")continue;let h;if(typeof m!="string"){let S=Hr(m);if(!S||re(S))continue;h=S;}let{colAlias:y,colName:w}=Mt(m);p.push({src:w,out:y,def:h}),g.add(w);}t=t.leftJoin(m=>{let h=m.selectFrom(l);for(let{targetSideCol:y,joinKey:w}of d)h=h.select(`${l}.${y} as ${w}`);for(let y of g)h=h.select(`${l}.${y} as ${y}`);return h.as(u)},m=>{let h=m;for(let{joinKey:y,parentSideCol:w}of d)h=h.onRef(`${u}.${y}`,"=",`${i}.${w}`);return h});for(let{out:m,def:h}of p)h?t=t.select(y=>Kr(y,m,h,r,u,true).as(m)):t=t.select(`${u}.${m}`);return t}function MS(t,e,n,r){for(let s of t){if(typeof s=="string")continue;let i=Hr(s);if(!i||!re(i))continue;let{colAlias:o}=Mt(s),a=e.join?.[o],l=xe(n,o,a,r.introspection),c=l.targetTable,f=l.fkRel;if(!f||f.type!=="o2m"||!tp(f,c,r.introspection))continue;let u=r.introspection?.primary_keys?.find(d=>d.table===c);if(u?.columns?.length)return {nestedTargetTable:c,fkRel:f,pkColumns:u.columns}}return null}function BS(t,e){let n=e.frames[0],{fkRel:r,fromTable:s,parentTable:i,embed:o}=n,a=t.selectFrom(s);if(a=Mr(a,r,s,i),o.where&&Object.keys(o.where).length>0){let c=e.frames.length>1?e.config:{...e.config,currentTable:s};a=a.where(f=>Ee(f,o.where,c));}let l=Ji(a,o.order,s,e.config,o.join);return a=l.sub,o.order&&(a=Ut(a,xS(o.order),void 0,e.config,s)),o.limit!==void 0&&(a=a.limit(o.limit)),o.offset!==void 0&&(a=a.offset(o.offset)),e.tieBreaker&&e.frames.length===1&&(a=wl(a,e.tieBreaker.fkRel,e.tieBreaker.nestedTargetTable,s),a=Ut(a,e.tieBreaker.pkColumns.map(c=>({column:c,embed:e.tieBreaker.nestedTargetTable})),void 0,e.config)),{inner:a,joinedToOne:l.joined}}function qS(t,e,n,r){if(e.frames[0].embed.order||!n.fkRel||n.fkRel.type!=="o2m")return t;let s=e.config.introspection?.primary_keys?.find(i=>i.table===n.fromTable);return s?.columns?.length?Ut(t,s.columns.map(i=>({column:i,embed:n.fromTable})),void 0,e.config):t}function HS(t,e,n){if(n&&re(n)&&!n.spread)return true;let r=t.frames[t.frames.length-1],s=r.embedRel;if(t.frames.length>1&&s&&!_t(s))return true;let{colName:i}=Mt(e);return Qd(t.config,r.fromTable,i,t.frames[0].embed.order)}function WS(t,e,n,r){let s=Hr(n),{colAlias:i,colName:o}=Mt(n),l=e.frames[r].fromTable;if(r===0&&s&&re(s)&&!s.spread){let c=e.frames[0].embed.join?.[i];return t.select(f=>rp(f,i,s,e.config,c,l).as("value"))}if(s&&!re(s)){let c=r>0?{...s,column:`${l}.${o}`}:s,f=r>0?i:o;return t.select(u=>Kr(u,f,c,e.config,r>0?void 0:l).as("value"))}return t.select(`${l}.${o} as value`)}function ml(t,e,n,r,s){if(r===e.frames.length-1)return WS(t,e,n,r);let o=e.frames[r],a=e.frames[r+1];if(!a.fkRel)return t.where(sql`1 = 0`).select(sql`null`.as("value"));let l=a.embedRel;if(!l)return t.where(sql`1 = 0`).select(sql`null`.as("value"));if(_t(l))return s.has(a.fromTable)||(t=wl(t,a.fkRel,a.fromTable,o.fromTable),s.add(a.fromTable)),t=qS(t,e,a),ml(t,e,n,r+1,s);let{colName:c}=Mt(n);return t.select(f=>{let u=f.selectFrom(a.fromTable);return u=Mr(u,a.fkRel,a.fromTable,o.fromTable),u=ml(u,e,n,r+1,new Set),e.config.jsonScalarArrayFrom(u,"value",Qd(e.config,a.fromTable,c,e.frames[0].embed.order)).as("value")})}function Gd(t,e,n){let{colAlias:r}=Mt(n),s=Hr(n);return t.select(i=>{let{inner:o,joinedToOne:a}=BS(i,e),l=e.frames[e.frames.length-1];if(e.frames.length>1&&!l.fkRel){let f=o.where(sql`1 = 0`).select(sql`null`.as("value"));return e.config.jsonScalarArrayFrom(f).as(r)}let c=ml(o,e,n,0,a);return e.config.jsonScalarArrayFrom(c,"value",HS(e,n,s)).as(r)})}function KS(t,e,n,r,s,i,o){let a=n.order?null:MS(e,n,s,o),l={frames:[{embed:n,fkRel:r,fromTable:s,parentTable:i}],config:o,tieBreaker:a};for(let c of e){if(typeof c=="string"&&c==="*")continue;let f=Hr(c),u=f!==null&&re(f)&&f.spread,{colAlias:d}=Mt(c);if(u){let p=f,g=n.join?.[d],m=xe(s,d,g,o.introspection),h=Gi(p.select,m.targetTable,o.introspection)??p.select??[],y={...l,frames:[...l.frames,{embed:p,fkRel:m.fkRel,fromTable:m.targetTable,parentTable:s,embedRel:m}]};for(let w of h)typeof w=="string"&&w==="*"||(t=Gd(t,y,w));continue}t=Gd(t,l,c);}return t}function JS(t,e,n,r,s){for(let i of e){if(typeof i=="string"&&i==="*")continue;let{colAlias:o,colName:a}=Mt(i);t=t.select(l=>{let c=l.selectFrom(n).select(`${n}.${a}`);if(s&&s.type!=="m2m")for(let{leftCol:f,rightCol:u}of it(s))c=c.whereRef(f,"=",u);else c=c.whereRef(`${n}.${r}_id`,"=",`${r}.id`);return c=c.limit(1),c.as(o)});}return t}function Gi(t,e,n){if(!t||!n?.columns||!t.some(i=>i==="*"))return t;let r=n.columns.filter(i=>i.table===e).sort((i,o)=>i.ordinal_position-o.ordinal_position).map(i=>i.name);if(r.length===0)return t;let s=[];for(let i of t)if(i==="*")for(let o of r)s.push(o);else s.push(i);return s}function GS(t,e,n,r,s,i,o){let a=s?.[e];if(!Xd(n.select)){if(a?.type==="inner"&&i)return Jd(t,e,n,r,s,i);if(i&&!a?.on&&r.introspection?.foreign_keys&&!Ft(r.introspection,i,a?.from||e,r.dialect,r.currentSchema)){let l=xe(i,e,a,r.introspection);l.fkRel||Sl(r.introspection,i,l.targetTable,l.displayHint);}return t}return a?.type==="inner"&&i&&(t=Jd(t,e,n,r,s,i)),n.spread&&i?US(t,e,n,r,s,i):t.select(l=>rp(l,e,n,r,a,i,o).as(e))}function rp(t,e,n,r,s,i,o){let a=i?Ft(r.introspection,i,s?.from||e,r.dialect,r.currentSchema):null,l=a||!i?{targetTable:a?.targetTable??(s?.from||e),fkRel:null,cardinality:"o2m",displayHint:void 0}:xe(i,e,s,r.introspection),c=l.targetTable,{displayHint:f,fkRel:u}=l,d=i===c,p=d?o?`${c}_nested`:`${c}_self`:c,g=d?`${c} as ${p}`:c,m=a?t.selectFrom(Fr(a,o??i,p)):t.selectFrom(g),h=i&&!s?.on&&!a?u:null,y=h?.type==="m2m",w=Gi(n.select,c,r.introspection),S=y?FS(w,p):w;if(m=Ki(m,S,r,n.join,p,y||Hd(S),d?c:p,d?p:void 0),n.where&&Object.keys(n.where).length>0){let x=jn(m,n.where,n.select,n.join,c,r);m=x.qb,Object.keys(x.remainingWhere).length>0&&(m=m.where(O=>Ee(O,x.remainingWhere,{...r,currentTable:c,currentTableAlias:p})));}let b=l.cardinality==="m2m"?"m2m":l.cardinality==="m2o"?"m2o":"o2m";if(s?.on)m=m.where(x=>Ee(x,s.on,r));else if(i&&!a){let x=h;if(x&&x.type==="m2m")b="m2m",m=Bi(m,x,p,i);else if(x?.type==="m2o"){for(let{leftCol:O,rightCol:v}of it(x)){let[,P]=O.split("."),[,C]=v.split("."),R=o?`${o}.${P}`:`${i}.${P}`;m=m.whereRef(`${p}.${C}`,"=",R);}b="m2o";}else if(x){for(let{leftCol:O,rightCol:v}of it(x)){let[,P]=O.split("."),[,C]=v.split("."),R=d?`${p}.${P}`:O,U=o?`${o}.${C}`:d?v.replace(`${c}.`,`${i}.`):v;m=m.whereRef(R,"=",U);}b=x.type;}else r.introspection?.foreign_keys?Sl(r.introspection,i,c,f):m=m.whereRef(`${p}.${i}_id`,"=",`${i}.id`);}m=bl(m,S,r,p,void 0,y||Hd(S),d?c:p),n.order?.some(x=>x.embed)&&(m=Ji(m,n.order,c,r,n.join).sub),m=Ut(m,n.order,void 0,r,c),b==="m2m"&&!n.order&&h?.type==="m2m"&&r.dialect==="sqlite"&&(m=m.orderBy(`${h.junctionTable}.${r.rowIdColumn}`,"asc")),n.limit!==void 0&&(m=m.limit(n.limit)),n.offset!==void 0&&(m=m.offset(n.offset)),a?.toOne&&(m=m.limit(1));let _=n.spread?true:a?a.toOne:b==="m2o"||l.cardinality==="o2o";return _&&r.dialect==="sqlite"?kS(m,S,c,r):(_?r.jsonObjectFrom:r.jsonArrayFrom)(m)}function sp(t,e,n,r){if(!t||!r.introspection?.foreign_keys)return false;for(let s of t){let i=hl(s);if(!i||!re(i.def))continue;let{alias:o,def:a}=i;if(!a.spread)continue;let l=e?.[o],c=xe(n,o,l,r.introspection);if(c.fkRel&&!_t(c))return true}return false}Fn();function _l(t){return t.startsWith("pg_catalog.")?t.slice(11):t}function YS(t,e,n){let r=n.arg_types.map((s,i)=>`${n.arg_names[i]??""} => ${_l(s)}`);return `${t}.${e}(${r.join(", ")})`}function ZS(t){return [...t].sort((e,n)=>{let r=e.arg_types.length-n.arg_types.length;if(r!==0)return r;let s=e.arg_types.map(_l).join(","),i=n.arg_types.map(_l).join(",");return s<i?-1:s>i?1:0})}function op(t,e,n){return {message:`Could not choose the best candidate function between: ${ZS(n).map(i=>YS(t,e,i)).join(", ")}`,details:null,hint:"Try renaming the parameters or the function itself in the database so function overloading can be resolved"}}function lp(t,e){let n=t??[],{schema:r,fnName:s,method:i,providedNames:o,inputType:a,paramsType:l}=e,c=n.filter(u=>u.schema===r&&u.name===s);if(c.length===0)return null;if(!(l==="positional"&&o.length===0)){let u=Bt(n,{schema:r,fnName:s,providedNames:o});if(u.length>1)return op(r,s,c);if(u.length===1)return null}if(i==="POST"&&a!=="text"){let u=c.filter(d=>!d.has_variadic&&d.arg_types.length===1&&d.arg_names.length===0&&(d.arg_types[0]==="json"||d.arg_types[0]==="jsonb"));if(u.length>1)return op(r,s,u)}return null}function fn(t){let e=t.args;if(e==null)return [];if(Array.isArray(e)){let n=e[0];return n&&typeof n=="object"&&!Array.isArray(n)?Object.keys(n):[]}return typeof e=="object"?"_raw"in e?[]:Object.keys(e):[]}function cp(t){if(!t)return;let e=t.toLowerCase();if(e.includes("application/octet-stream"))return "bytea";if(e.includes("xml"))return "xml";if(e.includes("text/plain"))return "text"}function e_(t,e){let n=new Set(t.arg_names.filter(i=>i!=="")),r=new Set(e);for(let i of e)if(!n.has(i))return false;let s=t.arg_types.length-(t.arg_defaults||0)-(t.has_variadic?1:0);for(let i=0;i<s;i++){let o=t.arg_names[i];if(!o||!r.has(o))return false}return true}function Bt(t,e){let{schema:n,fnName:r,providedNames:s}=e;return t.filter(i=>i.schema===n&&i.name===r&&e_(i,s))}function Vi(t,e){let n=t??[],r=e.paramsType==="positional"&&e.providedNames.length===0&&e.method==="POST"&&e.inputType!=="text",s;if(r)s=[];else if(e.paramsType==="positional"){let i=e.argCount??0;s=n.filter(o=>o.schema===e.schema&&o.name===e.fnName&&o.arg_types.length===i);}else s=Bt(n,{schema:e.schema,fnName:e.fnName,providedNames:e.providedNames});if(s.length===1)return s[0];if(s.length===0&&e.method==="POST"&&e.inputType!=="text"){let i=n.filter(o=>o.schema===e.schema&&o.name===e.fnName&&!o.has_variadic&&o.arg_types.length===1&&o.arg_names.length===0&&(o.arg_types[0]==="json"||o.arg_types[0]==="jsonb"));if(i.length===1)return i[0]}return null}function Qi(t,e){let n=Vi(t,e);if(!n)return null;let r=n.has_out_args||n.return_typtype==="c"||n.return_typtype==="p",s=n.return_type.toLowerCase()==="void"&&!n.has_out_args;return {return_is_setof:n.return_is_setof,return_type:n.return_type,returns_object:r,returns_void:s,volatility:n.volatility}}function up(t,e){let n=Vi(t?.functions,e);if(!n||n.return_typtype!=="c")return null;let r=n.return_type.replace(/^setof\s+/i,"").trim(),s=(r.includes(".")?r.slice(r.lastIndexOf(".")+1):r).replace(/^"|"$/g,""),i=[...t?.tables??[],...t?.views??[]];return i.find(a=>a.name===s&&a.schema===e.schema)??i.find(a=>a.name===s)?s:null}function t_(t){return [...t].sort().join(", ")}function n_(t){if(t.arg_types.length===0)return null;let e=t.arg_names.filter(n=>n!=="");return e.length!==t.arg_types.length?null:{arity:t.arg_types.length,sig:t_(e)}}function r_(t,e,n,r){let s=r.filter(d=>d.schema===t),i=()=>{let d=[...new Set(s.map(p=>p.name))].filter(p=>p!==e);return Jr(e,d)},o=d=>`Perhaps you meant to call the function ${t}.${d}`,a=d=>`Perhaps you meant to call the function ${t}.${e}(${d})`,l=s.filter(d=>d.name===e).map(n_).filter(d=>d!==null);if(l.length===0){let d=i();return d?o(d):null}if(s.filter(d=>d.name===e).length>1){let d=l.filter(p=>p.arity===n.length);return d.length===1?a(d[0].sig):null}return l[0].sig.split(", ").every(d=>n.includes(d)||Jr(d,n)!==null)?a(l[0].sig):null}function ap(t,e){let{schema:n,fnName:r,method:s,providedNames:i,inputType:o,rawKind:a}=t,l=[...i].sort(),c=s==="POST",f=c&&o==="text",u;f?u=`with a single unnamed ${a??"text"} parameter`:c?u=l.length===0?"without parameters or with a single unnamed json/jsonb parameter":`with ${l.length===1?"parameter":"parameters"} ${l.join(", ")} or with a single unnamed json/jsonb parameter`:u=l.length===0?"without parameters":`with ${l.length===1?"parameter":"parameters"} ${l.join(", ")}`;let d=`Searched for the function ${n}.${r} ${u}, but no matches were found in the schema cache.`,p;l.length>0?p=`${n}.${r}(${l.join(", ")})`:f?p=`${n}.${r}`:p=`${n}.${r} without parameters`;let g=`Could not find the function ${p} in the schema cache`,m=r_(n,r,i,e);return {message:g,details:d,hint:m}}function El(t,e){let n=t??[],r=n.filter(s=>s.schema===e.schema&&s.name===e.fnName);return r.length===0?ap(e,n):e.paramsType==="positional"&&e.providedNames.length===0||Bt(n,{schema:e.schema,fnName:e.fnName,providedNames:e.providedNames}).length>0||e.method==="POST"&&e.inputType!=="text"&&r.some(i=>!i.has_variadic&&i.arg_types.length===1&&i.arg_names.length===0&&(i.arg_types[0]==="json"||i.arg_types[0]==="jsonb"))||e.inputType==="text"?null:ap(e,n)}function s_(t,e,n){return t.schema?.get(`${e??"public"}.${n}`)}function Tl(t,e,n,r,s={}){if(!t)return t;let i=s_(e,n,r),o=a=>{let l=i_(a,i,e,n,r),c=s.applyDefaults&&i?i.applyDefaults(l):l;return i?i.serializeRow(c):o_(c,e,n,r)};return Array.isArray(t)?t.map(a=>o(a)):o(t)}function i_(t,e,n,r,s){let i={};for(let[o,a]of Object.entries(t)){let l=e?.get(o)?.context.pgTypeName??hp(n,r,s,o)??void 0;i[o]=a_(a,l,n.dialect);}return i}function o_(t,e,n,r){if(e.dialect!=="sqlite")return t;let s={};for(let[i,o]of Object.entries(t)){let a=hp(e,n,r,i);s[i]=l_(a)?Yi(o):o;}return s}function hp(t,e,n,r){let i=(t.introspection?.columns??[]).filter(l=>l.table===n&&l.name===r);if(i.length===0)return;let o=e??t.introspection?.default_schema??"public",a=i.find(l=>l.schema===o)??i.find(l=>l.schema==="public")??i[0];return Ne(a.pg_type,a.type)}function a_(t,e,n){if(t==null)return t;let r=e?.toLowerCase().trim();if(n!=="sqlite"&&r&&Le(r)){if(r==="color"){if(typeof t=="string"){let i=t.trim();return $n(i.startsWith("#")?i:`#${i}`)}return t}return dd(t,r)}if(typeof t!="string")return t;if(r==="color"){let i=t.trim();return $n(i.startsWith("#")?i:`#${i}`)}if(n!=="sqlite"){let i=Gr(e);return i==="boolean"?fp(t):i==="integer"?Xi(t,true):i==="number"?Xi(t,false):i==="json"?xl(t):i==="array"?dp(t):t}if(r==="color")return $n(t);if(r==="isodate"||r==="isodatetext")return t.replace(/Z$/,"+00:00");if(r==="unixtz"){let i=Date.parse(t);if(Number.isFinite(i))return Math.trunc(i/1e3)}if(r==="monetary"||r==="monetarytext"){let i=Number(t);return Number.isFinite(i)?i.toFixed(2):t}let s=Gr(e);return s==="boolean"?fp(t):s==="integer"?Xi(t,true):s==="number"?Xi(t,false):s==="json"?xl(t):s==="array"?dp(t):t}function Gr(t){if(!t)return;let e=t.toLowerCase().trim();if(e.startsWith("_")||e.endsWith("[]"))return "array";if(e==="bool"||e==="boolean")return "boolean";if(["int2","smallint","int4","integer","int","int8","bigint"].includes(e))return "integer";if(["float4","real","float8","double precision","numeric","decimal"].includes(e))return "number";if(e==="json"||e==="jsonb")return "json"}function fp(t){let e=t.trim().toLowerCase();return ["true","t","1","yes","y","on"].includes(e)?true:["false","f","0","no","n","off"].includes(e)?false:t}function Xi(t,e){let n=t.trim();if(n==="")return t;let r=Number(n);return !Number.isFinite(r)||e&&!Number.isInteger(r)?t:r}function xl(t){let e=t.trim();if(e==="")return t;try{return JSON.parse(e)}catch{return t}}function dp(t){let e=xl(t);return Array.isArray(e)?e:t}function l_(t){let e=Gr(t);return e==="json"||e==="array"}var c_=new Set(["text","character","character varying","bpchar","varchar","name","citext"]);function pp(t){let e=t.toLowerCase().trim(),n=e.endsWith("[]")?e.slice(0,-2).trim():e;return !c_.has(n)}function Yi(t){return t==null||typeof t=="string"?t:JSON.stringify(t)}function gp(t,e){let n=e.db;switch(t.schema&&(n=n.withSchema(t.schema),e={...e,currentSchema:t.schema}),t.type){case "query":return cl(t,e,n);case "insert":return f_(t,e,n);case "update":return d_(t,e,n);case "delete":return p_(t,e,n);case "upsert":case "put":return m_(t,e,n);case "rpc":return g_(t,e,n);default:throw t&&"type"in t?(console.error(t),new Error(`Unsupported AST type: ${t.type}`)):new Error("Invalid AST")}}function Ut(t,e,n,r,s){if(!e)return t;for(let i of e){let o=i.embed?(Pe(i.embed,"order embed alias"),i.column.includes("->")?r?Lr(i.column,r,s,i.embed):mp(i.column,i.embed):(Pe(i.column,"order embed column"),r?St(i.embed,i.column,r,s):sql`${sql.ref(i.embed)}.${sql.ref(i.column)}`)):i.column.includes("->")?r?Lr(i.column,r,s,n):mp(i.column,void 0,n):n?r?St(n,i.column,r,s):sql`${sql.ref(n)}.${sql.ref(i.column)}`:r?de(i.column,r,s):i.column,a=i.nullsFirst!==void 0?i.nullsFirst:r?.dialect==="sqlite"?i.direction==="desc":void 0;a!==void 0?t=t.orderBy(o,l=>{let c=i.direction==="desc"?l.desc():l.asc();return a?c.nullsFirst():c.nullsLast()}):t=t.orderBy(o,i.direction||"asc");}return t}function mp(t,e,n){let{col:r,parts:s}=cn(t);if(s.length===0)return sql.ref(t);e&&Pe(r,"order embed column");let i=jr(s,"ORDER BY JSON path key");return e?sql`${sql.ref(e)}.${sql.ref(r)}${sql.raw(i)}`:n?sql`${sql.ref(n)}.${sql.ref(r)}${sql.raw(i)}`:sql`${sql.ref(r)}${sql.raw(i)}`}function zr(t,e,n,r,s){return !e||Object.keys(e).length===0?t:t.where(i=>Ee(i,e,{...n,currentTable:r,currentSchema:s}))}function cl(t,e,n){let r=n.selectFrom(t.from);return yp(r,t,e,t.from)}function yp(t,e,n,r){t=u_(t,e.join,e.select);let s=e.order?.some(f=>f.embed)===true;t=Ki(t,e.select,n,e.join,r,s||Vd(e.select,e.join,r,n));let i=e.where??{},{qb:o,remainingWhere:a}=jn(t,i,e.select,e.join,r,n);t=o,t=zr(t,a,n,r,e.schema),t=bl(t,e.select,n,r,e.join),Zd(e.order,e.join,r,n),s&&(t=Ji(t,e.order,r,n,e.join).sub);let l=sp(e.select,e.join,r,n)?r:void 0,c=zd(e.order,e.select,e.join,r,n);return t=Ut(t,c,l,n,r),e.limit!==void 0&&(t=t.limit(e.limit)),e.offset!==void 0&&(t=t.offset(e.offset)),t}function u_(t,e,n){if(!e)return t;let r=new Set;if(n){for(let s of n)if(typeof s!="string")for(let i of Object.keys(s))r.add(i);}for(let[s,i]of Object.entries(e)){if(!i.on||r.has(s))continue;let o=i.from||s,a=i.type==="left"?"leftJoin":"innerJoin";t=t[a](`${o} as ${s}`,l=>bp(l,i.on));}return t}function bp(t,e){for(let[n,r]of Object.entries(e))if(n==="$and")for(let s of r)t=bp(t,s);else {let s=r;for(let[i,o]of Object.entries(s)){let a=Ni[i];if(!a)throw new Error(`Unsupported join operator: ${i}`);Ai(o)?t=t.onRef(n,a,o.$ref):t=t.on(n,a,o);}}return t}function f_(t,e,n){let r=n.insertInto(t.from);if(t.values){let i=Tl(t.values,e,t.schema,t.from,{applyDefaults:true});r=r.values(i);}let s=t.from?{...e,currentTable:t.from}:e;return r=Wr(r,t.select,s),r}function d_(t,e,n){let r=n.updateTable(t.from);if(t.values){let i=t.values;Array.isArray(i)&&(i=i.length>0?i[0]:i);let o=Tl(i,e,t.schema,t.from);r=r.set(o);}t.limit!==void 0||t.offset!==void 0?r=wp(r,t,e,n):r=zr(r,t.where??{},e,t.from,t.schema);let s=t.from?{...e,currentTable:t.from}:e;return r=Wr(r,t.select,s),r}function p_(t,e,n){let r=n.deleteFrom(t.from);t.limit!==void 0||t.offset!==void 0?r=wp(r,t,e,n):r=zr(r,t.where??{},e,t.from,t.schema);let s=t.from?{...e,currentTable:t.from}:e;return r=Wr(r,t.select,s),r}function wp(t,e,n,r){let i=n.introspection?.primary_keys.find(l=>l.table===e.from)?.columns??[],o=r.selectFrom(e.from),a=n.rowIdColumn;if(i.length>0)for(let l of i)o=o.select(l);else o=o.select(sql.ref(a).as("__rowid"));if(o=zr(o,e.where??{},n,e.from,e.schema),o=Ut(o,e.order,void 0,n,e.from),e.limit!==void 0&&(o=o.limit(e.limit)),e.offset!==void 0&&(o=o.offset(e.offset)),i.length===1)return t.where(i[0],"in",o);if(i.length>1){let l="__ltd_target",c=r.selectFrom(o.as(l)).select(sql`1`.as("_"));for(let f of i)c=c.whereRef(`${l}.${f}`,"=",`${e.from}.${f}`);return t.where(f=>f.exists(c))}else return t.where(sql.ref(a),"in",o)}function m_(t,e,n){let r=t.values,s=Tl(r,e,t.schema,t.from,{applyDefaults:true}),i=n.insertInto(t.from).values(s);t.onConflict&&(i=i.onConflict(a=>{let l=t.onConflict.length===1?a.column(t.onConflict[0]):a.columns(t.onConflict);if(t.ignoreDuplicates)return l.doNothing();let c=Array.isArray(s)?s[0]:s,f=Object.keys(c).filter(u=>!t.onConflict.includes(u));return f.length===0?l.doUpdateSet({[t.onConflict[0]]:sql.ref(`excluded.${t.onConflict[0]}`)}):l.doUpdateSet(u=>{let d={};for(let p of f)d[p]=u.ref(`excluded.${p}`);return d})}));let o=t.from?{...e,currentTable:t.from}:e;return i=Wr(i,t.select,o),i}function h_(t,e,n){let r=n.introspection?.functions;if(!r)return null;let s=t.schema??n.introspection?.default_schema??"public",i=Array.isArray(t.args)?fn(t):Object.keys(t.args);if(Bt(r,{schema:s,fnName:e,providedNames:i}).length>0)return null;let o=r.filter(a=>a.schema===s&&a.name===e&&!a.has_variadic&&a.arg_types.length===1&&a.arg_names.length===0&&(a.arg_types[0]==="json"||a.arg_types[0]==="jsonb"));return o.length===1?o[0].arg_types[0]:null}function g_(t,e,n){let r=t.function;Pe(r,"RPC function name");let s=t.schema??e.introspection?.default_schema,i;r.includes(".")?s!==void 0?(Pe(s,"RPC schema"),i=`"${s}"."${r}"`):i=r:(i=s?`${s}.${r}`:r,Pe(i,"RPC function reference"));let o,l=e.dialect==="postgres"&&t.httpMethod==="POST"&&t.inputType!=="text"&&t.args!=null?h_(t,r,e):null;if(l)o=sql`${sql.raw(i)}(${Yi(t.args)}::${sql.raw(l)})`;else if(t.args&&!Array.isArray(t.args)&&Object.keys(t.args).length>0){let u=Object.entries(t.args),d=null,p=null,g=null;if(e.dialect==="postgres"&&e.introspection?.functions){let y=u.map(([S])=>S),w=Bt(e.introspection.functions,{schema:t.schema??e.introspection?.default_schema??"public",fnName:r,providedNames:y});if(w.length===1){let S=w[0];d=new Map;for(let b=0;b<S.arg_names.length;b++)d.set(S.arg_names[b],S.arg_types[b]);if(S.has_variadic&&S.arg_names.length>0){p=S.arg_names[S.arg_names.length-1];let b=S.arg_types[S.arg_types.length-1];g=b.endsWith("[]")?b.slice(0,-2):b;}}}let m=t.httpMethod==="GET",h=u.map(([y,w])=>{if(Pe(y,"RPC param key"),d){let b=d.get(y);if(b){if(y===p&&g){ln(g,"RPC variadic elem type"),Pe(y,"RPC variadic param key");let _=Array.isArray(w)?w:[w];return sql`VARIADIC ${sql.raw(y)} := ${_}::${sql.raw(g+"[]")}`}if(pp(b)){ln(b,"RPC arg type");let _=m&&Array.isArray(w)?w[w.length-1]:w,E=Gr(b),x=E==="json"||E==="array"&&!Array.isArray(_)?Yi(_):_;return sql`${sql.raw(y)} := ${x}::${sql.raw(b)}`}}}let S=m&&Array.isArray(w)?w[w.length-1]:w;return sql`${sql.raw(y)} := ${S}`});o=sql`${sql.raw(i)}(${sql.join(h)})`;}else if(Array.isArray(t.args)&&t.args.length>0){let u=null;if(e.dialect==="postgres"&&e.introspection?.functions){let p=e.introspection.functions,g=t.schema??e.introspection?.default_schema??"public",h=t.args.length,y=p.filter(w=>w.schema===g&&w.name===r&&w.arg_types.length===h);y.length===1&&(u=y[0].arg_types);}let d=t.args.map((p,g)=>{if(u){let m=u[g];if(m&&pp(m)){ln(m,"RPC positional arg type");let h=Gr(m),y=h==="json"||h==="array"&&!Array.isArray(p)?Yi(p):p;return sql`${y}::${sql.raw(m)}`}}return sql`${p}`});o=sql`${sql.raw(i)}(${sql.join(d)})`;}else o=sql`${sql.raw(i)}()`;let c=!!t.join&&Object.keys(t.join).length>0;if(e.dialect==="postgres"&&c){let u=up(e.introspection,{schema:t.schema??e.introspection?.default_schema??"public",fnName:r,providedNames:fn(t),paramsType:t.paramsType,argCount:Array.isArray(t.args)?t.args.length:void 0,method:t.httpMethod,inputType:t.inputType});if(u)return yp(n.selectFrom(o.as(u)),t,e,u)}let f=n.selectFrom(o.as(r));return f=Ki(f,t.select,e),f=zr(f,t.where??{},e,t.from,t.schema),f=Ut(f,t.order,void 0,e,t.from),t.limit!==void 0&&(f=f.limit(t.limit)),t.offset!==void 0&&(f=f.offset(t.offset)),f}var T_=new Kysely({dialect:{createAdapter:()=>new PostgresAdapter,createDriver:()=>new DummyDriver,createIntrospector:t=>new PostgresIntrospector(t),createQueryCompiler:()=>new PostgresQueryCompiler}}),R_={$ilike:(t,e,n)=>sql`${k(e)} ilike ${n}`,$regex:(t,e,n)=>sql`${k(e)} ~ ${n}`,$iregex:(t,e,n)=>sql`${k(e)} ~* ${n}`,$contains:(t,e,n)=>sql`${k(e)} @> ${n}`,$containedBy:(t,e,n)=>sql`${k(e)} <@ ${n}`,$overlaps:(t,e,n)=>sql`${k(e)} && ${n}`,$rangeLt:(t,e,n)=>sql`${k(e)} << ${n}`,$rangeGt:(t,e,n)=>sql`${k(e)} >> ${n}`,$rangeGte:(t,e,n)=>sql`${k(e)} &> ${n}`,$rangeLte:(t,e,n)=>sql`${k(e)} &< ${n}`,$rangeAdjacent:(t,e,n)=>sql`${k(e)} -|- ${n}`,$textSearch:(t,e,n)=>{let r=n,s=r.config||"english",i="to_tsquery";return r.type==="plain"?i="plainto_tsquery":r.type==="phrase"?i="phraseto_tsquery":r.type==="websearch"&&(i="websearch_to_tsquery"),sql`${k(e)} @@ ${sql.raw(i)}(${sql.literal(s)}, ${r.query})`},$eqAny:(t,e,n)=>sql`${k(e)} = any(${n})`,$neqAny:(t,e,n)=>sql`${k(e)} != any(${n})`,$gtAny:(t,e,n)=>sql`${k(e)} > any(${n})`,$gteAny:(t,e,n)=>sql`${k(e)} >= any(${n})`,$ltAny:(t,e,n)=>sql`${k(e)} < any(${n})`,$lteAny:(t,e,n)=>sql`${k(e)} <= any(${n})`,$likeAny:(t,e,n)=>sql`${k(e)} like any(${n})`,$ilikeAny:(t,e,n)=>sql`${k(e)} ilike any(${n})`,$eqAll:(t,e,n)=>sql`${k(e)} = all(${n})`,$neqAll:(t,e,n)=>sql`${k(e)} != all(${n})`,$gtAll:(t,e,n)=>sql`${k(e)} > all(${n})`,$gteAll:(t,e,n)=>sql`${k(e)} >= all(${n})`,$ltAll:(t,e,n)=>sql`${k(e)} < all(${n})`,$lteAll:(t,e,n)=>sql`${k(e)} <= all(${n})`,$likeAll:(t,e,n)=>sql`${k(e)} like all(${n})`,$ilikeAll:(t,e,n)=>sql`${k(e)} ilike all(${n})`,$regexAny:(t,e,n)=>sql`${k(e)} ~ any(${n})`,$iregexAny:(t,e,n)=>sql`${k(e)} ~* any(${n})`,$regexAll:(t,e,n)=>sql`${k(e)} ~ all(${n})`,$iregexAll:(t,e,n)=>sql`${k(e)} ~* all(${n})`};function C_(t,e){let n=e.replace(/^\$\./,"").split(".");if(n.length===0)return sql.ref(t);let r=n.map((s,i)=>{let o=i===n.length-1?"->>":"->",a=/^-?\d+$/.test(s);return a||In(s,"JSON path key"),a?`${o}${s}`:`${o}'${s}'`}).join("");return sql`${sql.ref(t)}${sql.raw(r)}`}function k_(t,e="value",n=false){let r=sql.ref(e);return sql`(select coalesce(json_agg(${r}), '[]'::json) from ${t} as _agg)`}var Sp={db:T_,operators:{...Ii,...R_},jsonArrayFrom:jsonArrayFrom$1,jsonObjectFrom:jsonObjectFrom$1,jsonScalarArrayFrom:k_,jsonPath:C_,rowIdColumn:"ctid"};var v_=/[.*+?[\]{}()|]/;function Zi(t){let e="";for(let n of t)n==="\\"||n==="*"||n==="?"||n==="["?e+=`[${n}]`:e+=n;return e}function _p(t){return t==="\\"||t==="*"||t==="?"||t==="["?`[${t}]`:t}function Rl(t){let e="";for(let n=0;n<t.length;){let r=t[n];if(r==="\\"){if(n+1>=t.length){e+="[\\\\]",n+=1;continue}e+=_p(t[n+1]),n+=2;continue}if(r==="%"){e+="*",n+=1;continue}if(r==="_"){e+="?",n+=1;continue}e+=_p(r),n+=1;}return e}function eo(t){return t?v_.test(t)?/^[A-Za-z0-9_\-\\%]+$/.test(t):true:false}function Ep(t){if(t.startsWith("^")&&t.endsWith("$")&&t.length>=2){let e=t.slice(1,-1);return eo(e)?{mode:"exact",text:Zi(e)}:null}if(t.startsWith("^")){let e=t.slice(1);return eo(e)?{mode:"prefix",text:Zi(e)}:null}if(t.endsWith("$")){let e=t.slice(0,-1);return eo(e)?{mode:"suffix",text:Zi(e)}:null}return eo(t)?{mode:"contains",text:Zi(t)}:null}function xp(t,e){switch(t){case "exact":return e;case "prefix":return `${e}*`;case "suffix":return `*${e}`;case "contains":return `*${e}*`}}function Tp(t,e){switch(t){case "exact":return e;case "prefix":return `${e}%`;case "suffix":return `%${e}`;case "contains":return `%${e}%`}}var j_=new Kysely({dialect:{createAdapter:()=>new SqliteAdapter,createDriver:()=>new DummyDriver,createIntrospector:t=>new SqliteIntrospector(t),createQueryCompiler:()=>new SqliteQueryCompiler}});function L_(t,e){let n=e.replace(/^\$\./,"").split(".");if(n.length===0)return sql.ref(t);let r=n.map((s,i)=>{let o=i===n.length-1?"->>":"->",a=/^-?\d+$/.test(s);return a||In(s,"JSON path key"),a?`${o}${s}`:`${o}'${s}'`}).join("");return sql`${sql.ref(t)}${sql.raw(r)}`}function F_(t,e){let n=k(t);if(e.length===0)return sql`(${n} is not null)`;let r=sql.join(e.map(s=>sql`${s}`));return sql`(${n} is not null and (select count(distinct value) from json_each(${n}) where value in (${r})) = ${sql.lit(e.length)})`}function U_(t,e){let n=k(t),r=Object.keys(e);if(r.length===0)return sql`${n} is not null`;let s=r.map(i=>(In(i,"JSON object key"),sql`json_extract(${n}, ${sql.raw(`'$.${i}'`)}) = ${e[i]}`));return sql`(${n} is not null and ${sql.join(s,sql` and `)})`}var M_=new Set(["a","an","and","are","as","at","be","by","for","from","in","is","it","of","on","or","that","the","to","was","with"]);function B_(t){let e=t.toLowerCase().replace(/'/g,"''");return e.endsWith("s")&&!e.endsWith("ss")&&e.length>3&&(e=e.slice(0,-1)),e.length===7?e.slice(0,4):e.length>6?e.slice(0,6):e}function Rp(t,e,n){let r=B_(e);if(!r)return sql`1 = 1`;let i=n!=null&&n!=="english"&&n!=="simple"&&r.length>=5?`%'${r}%':%`:`%'${r}':%`;return sql`lower(${t}) like ${i}`}function q_(t){try{return decodeURIComponent(t.replace(/\+/g," "))}catch{return t}}function Cl(t,e){let n=k(t),r=q_(e.query).trim();if(!r)return sql`1 = 1`;if(e.type==="websearch"){let o=r.split(/\s+or\s+/i).map(l=>l.trim()).filter(Boolean);if(o.length>1){let l=o.map(c=>Cl(t,{...e,query:c,type:"plain",config:e.config}));return sql`(${sql.join(l,sql` or `)})`}let a=r.split(/\s+and\s+/i).map(l=>l.trim()).filter(Boolean);if(a.length>1){let l=a.map(c=>Cl(t,{...e,query:c,type:"plain",config:e.config}));return sql`(${sql.join(l,sql` and `)})`}}if(r.includes("|")&&e.type!=="phrase"&&e.type!=="plain"){let o=r.split("|").map(a=>a.trim()).filter(Boolean);return o.length===0?sql`1 = 1`:sql`(${sql.join(o.map(a=>Rp(n,a,e.config)),sql` or `)})`}let s=r.split(/\s+/).map(o=>o.trim()).filter(Boolean);if((e.type==="phrase"||e.type==="plain")&&(s=s.filter(o=>!M_.has(o.toLowerCase()))),s.length===0)return sql`1 = 1`;let i=sql` and `;return sql`(${sql.join(s.map(o=>Rp(n,o,e.config)),i)})`}function kl(t,e){return sql`${k(t)} GLOB ${e}`}function H_(t,e){let n=k(t);return sql`json(${n}) = json(${JSON.stringify(e)})`}function W_(t,e){let n=k(t);return Array.isArray(e)||e!==null&&typeof e=="object"?sql`json(${n}) is distinct from json(${JSON.stringify(e)})`:sql`${n} is distinct from ${e}`}function Cp(t,e,n){if(typeof e!="string")throw new Error(`$${n?"iregex":"regex"} on sqlite requires a string value`);let r=Ep(e);if(!r)throw new Error(`Unsupported operator: $${n?"iregex":"regex"}`);if(n){let i=Tp(r.mode,r.text),o=k(t);return sql`lower(${o}) like lower(${i}) escape '\\'`}let s=xp(r.mode,r.text);return kl(t,s)}function to(t,e,n,r){if(!Array.isArray(e))throw new Error(`$${n}${r} on sqlite requires an array value`);if(e.length===0)return r==="any"?sql`false`:sql`true`;let s=k(t),i=e.map(o=>n==="ilike"?sql`lower(${s}) like lower(${o})`:kl(t,typeof o=="string"?Rl(o):o));return sql`(${sql.join(i,r==="any"?sql` or `:sql` and `)})`}var K_={$eq:(t,e,n)=>Array.isArray(n)||n!==null&&typeof n=="object"?H_(e,n):sql`${k(e)} = ${n}`,$neq:(t,e,n)=>Array.isArray(n)||n!==null&&typeof n=="object"?sql`json(${k(e)}) != json(${JSON.stringify(n)})`:sql`${k(e)} != ${n}`,$textSearch:(t,e,n)=>Cl(e,n),$like:(t,e,n)=>{if(typeof n!="string")throw new Error("$like on sqlite requires a string value");return kl(e,Rl(n))},$regex:(t,e,n)=>Cp(e,n,false),$iregex:(t,e,n)=>Cp(e,n,true),$ilike:(t,e,n)=>sql`lower(${k(e)}) like lower(${n})`,$likeAny:(t,e,n)=>to(e,n,"like","any"),$ilikeAny:(t,e,n)=>to(e,n,"ilike","any"),$likeAll:(t,e,n)=>to(e,n,"like","all"),$ilikeAll:(t,e,n)=>to(e,n,"ilike","all"),$isDistinct:(t,e,n)=>W_(e,n),$contains:(t,e,n)=>{if(Array.isArray(n))return F_(e,n);if(n!==null&&typeof n=="object")return U_(e,n);throw new Error("$contains on sqlite requires an array or object value")},$containedBy:(t,e,n)=>{if(!Array.isArray(n))throw new Error("$containedBy on sqlite requires an array value");let r=k(e),s=n.length===0?sql`${r} is not null and not exists (select 1 from json_each(${r}))`:sql`${r} is not null and not exists (select 1 from json_each(${r}) where value not in (${sql.join(n.map(i=>sql`${i}`))}))`;return sql`(case when ${r} is null then null else (${s}) end)`},$overlaps:(t,e,n)=>{if(!Array.isArray(n))throw new Error("$overlaps on sqlite requires an array value");let r=k(e);if(n.length===0)return sql`1 = 0`;let s=sql.join(n.map(i=>sql`${i}`));return sql`(${r} is not null and exists (select 1 from json_each(${r}) where value in (${s})))`}};function J_(t,e="value",n=false){let r=sql.ref(e),s=n?sql`json_group_array(json(${r}))`:sql`json_group_array(${r})`;return sql`(select coalesce(${s}, json('[]')) from ${t} as _agg)`}var kp={db:j_,operators:{...Ii,...K_},jsonArrayFrom:jsonArrayFrom,jsonObjectFrom:jsonObjectFrom,jsonScalarArrayFrom:J_,jsonPath:L_,rowIdColumn:"rowid"};function G_(t){switch(t){case "postgres":return Sp;case "sqlite":return kp;default:throw new Error(`Unsupported dialect: ${t}`)}}function te(t,e="postgres",n){let r=G_(e),s=n&&"introspection"in n?n:{db:n,introspection:void 0};return gp(t,{...r,dialect:e,db:s.db??r.db,introspection:s.introspection,schema:s.schema})}var dc=da(Al());Xr();function T(t,e,n,r,s){let i=JSON.stringify({code:e,details:r,hint:s,message:n}),o=new TextEncoder().encode(i);return new Response(o,{status:t,headers:{"Content-Type":"application/json; charset=utf-8","Content-Length":String(o.byteLength)}})}function ot(t){return T(t.status,t.code,t.message,t.details??null,t.hint??null)}async function Kp(t,e){if(!t||!t.startsWith("Bearer "))return e.anonymousEnabled?{kind:"ok",payload:null}:{kind:"error",response:ot({status:401,code:"PGRST302",message:"Anonymous access is disabled"})};let n=t.slice(7).trim(),r=n.split(".");if(r.length!==3||r.some(s=>s.length===0))return e.anonymousEnabled?{kind:"ok",payload:null}:{kind:"error",response:ot({status:401,code:"PGRST301",message:`Expected 3 parts in JWT; got ${Math.max(1,r.filter(s=>s.length>0).length)}`})};if(!e.jwtSecret)return {kind:"error",response:ot({status:500,code:"PGRST300",message:"Server lacks JWT secret"})};try{let s=new TextEncoder().encode(e.jwtSecret),{payload:i}=await jwtVerify(n,s,{algorithms:["HS256"]});return typeof i.iat=="number"&&i.iat>Math.floor(Date.now()/1e3)?{kind:"error",response:ot({status:401,code:"PGRST303",message:"JWT issued at future"})}:{kind:"ok",payload:i}}catch(s){return s instanceof errors.JWTExpired?{kind:"error",response:ot({status:401,code:"PGRST303",message:"JWT expired"})}:{kind:"error",response:ot({status:401,code:"PGRST301",message:"No suitable key or wrong key type",details:"None of the keys was able to decode the JWT"})}}}tc();function IE(t,e,n,r){if(n){let i=t.get(`${n}.${e}`);if(i)return i}let s=t.get(`${r}.${e}`);if(s)return s;for(let[i,o]of t)if(i.endsWith(`.${e}`))return o}function NE(t,e){let n=t.schema||"public",r=tl(t,e);return {schema:n,table:t.table,column:t.name,pgTypeName:r,nullable:t.nullable,defaultValue:t.default_value??null,isPrimaryKey:t.is_primary_key,isUnique:false,isSerial:!!t.is_identity,isGenerated:t.is_generated}}function Xp(t,e){let n=NE(t,e);return Le(n.pgTypeName)?md(n)??We(n):We(n)}function DE(t,e="sqlite"){let n=new Map;for(let r of t.columns){let s=r.schema||"public",i=`${s}.${r.table}`,o=n.get(i);o||(o=new at(r.table,s),n.set(i,o)),o.set(r.name,Xp(r,t));}return n}function jE(t,e){for(let n of e.columns){if(!Le(tl(n,e)))continue;let r=n.schema||"public",s=`${r}.${n.table}`,i=t.get(s);i||(i=new at(n.table,r),t.set(s,i)),i.set(n.name,Xp(n,e));}return t}function Yp(t,e,n){if(n==="sqlite")return DE(e,n);if(n==="postgres"||n==="pglite"){let r=t&&t.size>0?t:new Map;return jE(new Map(r),e)}return t&&t.size>0?t:new Map}function Zp(t,e){let n=t.config?.translation?.schemas;return e.schema??n?.defaultSchema??"public"}function em(t,e,n,r){return !n||!e?.from?t:t.map(s=>nc(s,e.select,e.from,e.schema,e.join,n,r))}function nc(t,e,n,r,s,i,o){let a=IE(i,n,r,o),l=FE(e,s),c={};for(let[f,u]of Object.entries(t)){let d=l.get(f);if(d&&"embed"in d){let m=d.embed;c[f]=LE(u,m,r,i,o);continue}let p=d?.sourceColumn??f,g=a?.get(p);c[f]=g?.isShimBacked?g.deserialize(u):u;}return c}function LE(t,e,n,r,s){return Array.isArray(t)?t.map(i=>i&&typeof i=="object"?nc(i,e.select,e.table,n,e.join,r,s):i):t&&typeof t=="object"?nc(t,e.select,e.table,n,e.join,r,s):t}function FE(t,e){let n=new Map;if(!t)return n;for(let r of t){if(typeof r=="string"){if(r==="*")continue;n.set(r,{sourceColumn:r});continue}if(!(!r||typeof r!="object"))for(let[s,i]of Object.entries(r))if(UE(i)){let o=e?.[s]?.from??s;n.set(s,{embed:{table:o,select:i.select,join:i.join}});}else {let o=i;if(o.cast||o.path||o.aggregate)continue;n.set(s,{sourceColumn:o.column??s});}}return n}function UE(t){return t!=null&&typeof t=="object"&&("select"in t||"where"in t||"order"in t||"limit"in t||"offset"in t||"spread"in t||"join"in t)}var Bn=class extends Error{constructor(n,r){super(`Could not find the table '${[n,r].filter(Boolean).join(".")}' in the schema cache`);this.schema=n;this.relation=r;}},rc=class{constructor(e){this.config=e;}kysely;introspection;async translateDdl(e){return e}async clearSchemaCache(){this.introspection=void 0,await this.deleteCachedIntrospection();}async readCachedIntrospection(e){if(typeof this.introspection=="object"&&e?.useCache===true)return this.introspection;if(e?.useCache!==true||!this.config.schemaCache)return;let n=await this.config.schemaCache?.get(this.schemaCacheKey());if(n)try{return this.introspection=JSON.parse(n),this.introspection}catch{await this.deleteCachedIntrospection();return}}async writeCachedIntrospection(e,n){this.introspection=e,n?.useDriver===true&&await this.config.schemaCache?.set(this.schemaCacheKey(),JSON.stringify(e));}async deleteCachedIntrospection(){await this.config.schemaCache?.delete(this.schemaCacheKey());}schemaCacheKey(){return ["@supabase/lite","schema-cache",this.dialect,this.config.introspection?.name??"",this.config.url??""].join(":")}async exec(e,...n){try{return sql(e,...n??[]).execute(this.kysely)}catch(r){throw console.error(r),new Error(`Failed to execute query: ${e}`)}}async ping(){try{let e=await this.exec("SELECT 1");return e&&Array.isArray(e.rows)&&e.rows.length===1}catch{return false}}async transaction(e,n){throw new Error("This Connection does not support transactions")}async runInTransaction(e){return this.kysely.transaction().execute(n=>e(n))}createMigrator(e){throw new Error("This Connection does not support migrations")}async onPostgrestAST(e,n){return e}deserializeRow(e){return e}normalizeDbError(e){return e}async withContext(e,n,r){return n(this.kysely)}get supportsRpc(){return false}async viewOptionsMetadata(e,n){return null}};function Et(t){return JSON.stringify(t,(e,n)=>typeof n=="bigint"?Number.parseInt(n.toString(),10):n)}var tm=/application\/vnd\.pgrst\.plan(?:\+(json|text))?/i;function nm(t){let e=t.match(tm);if(!e)return null;let n=e[1]?.toLowerCase()==="json"?"json":"text",r=t.match(/;\s*options=([^;]+)/i),s=r?`; options=${r[1].trim()}`:"";return {format:n,optionsSegment:s}}function rm(t){return tm.test(t)}function sm(t){return /;\s*nulls\s*=\s*stripped/i.test(t)}function pn(t){if(Array.isArray(t))return t.map(e=>pn(e));if(t!==null&&typeof t=="object"){let e={};for(let[n,r]of Object.entries(t))r!==null&&(e[n]=pn(r));return e}return t}function lo(t,e){if(!e||e.length===0)return t;let n=(r,s)=>{for(let i of e){if(i.embed)continue;let o=r[i.column],a=s[i.column],l=o==null,c=a==null;if(l&&c)continue;if(l)return i.nullsFirst?-1:1;if(c)return i.nullsFirst?1:-1;let f;if(typeof o=="number"&&typeof a=="number"?f=o-a:f=String(o).localeCompare(String(a)),f!==0)return i.direction==="desc"?-f:f}return 0};return [...t].sort(n)}function BE(t,e){return !e||e.length===0?t:t.map(n=>lc(n,e))}function im(t,e,n){if(!e||e.length===0||t.length===0)return t;let r=BE(t,e);return r=HE(r,e),r=WE(r,e),r=KE(r,e),n==="sqlite"&&(r=JE(r,e),r=qE(r,e)),r}function qE(t,e){if(!e||e.length===0)return t;let n=GE(e);return n.size===0?t:t.map(r=>{if(!Hn(r))return r;let s={...r};for(let i of n){let o=s[i];o!==null&&typeof o=="object"&&(s[i]=JSON.stringify(o));}return s})}function HE(t,e){return !e||e.length===0?t:t.map(n=>ic(n,e))}function WE(t,e){return !e||e.length===0?t:t.map(n=>oc(n,e))}function KE(t,e){return !e||e.length===0?t:t.map(n=>ac(n,e))}function JE(t,e){return !e||e.length===0?t:t.map(n=>sc(n,e))}function GE(t){let e=new Set;for(let n of t){if(typeof n=="string")continue;let[r,s]=Object.entries(n)[0]??[];if(!r||!s)continue;let i=s;i.path&&i.pathText&&!om(i.cast)&&e.add(r);}return e}function om(t){let e=t?.trim().toLowerCase();return e==="json"||e==="jsonb"}function zE(t){let e=t?.trim().toLowerCase();return e==="integer"||e==="int"||e==="int2"||e==="int4"||e==="int8"||e==="bigint"||e==="smallint"}function sc(t,e){if(Array.isArray(t))return t.map(r=>sc(r,e));if(!Hn(t))return t;let n={...t};for(let r of e){if(typeof r=="string")continue;let[s,i]=Object.entries(r)[0]??[];if(!s||!i)continue;if(fs(i)){s in n&&i.select&&(n[s]=sc(n[s],i.select));continue}let o=i;if(!o.path||o.pathText!==true||!zE(o.cast)||!(s in n))continue;let a=n[s];if(a==null)continue;let l=String(a);if(!/^-?\d+$/.test(l))throw new An(l);n[s]=Number.parseInt(l,10);}return n}function lc(t,e){if(Array.isArray(t))return t.map(r=>lc(r,e));if(!Hn(t))return t;let n={...t};for(let r of e){if(typeof r=="string")continue;let[s,i]=Object.entries(r)[0]??[];!s||!i||!fs(i)||s in n&&(n[s]=QE(n[s],i.select));}return n}function ic(t,e){if(Array.isArray(t))return t.map(r=>ic(r,e));if(!Hn(t))return t;let n={...t};for(let r of e){if(typeof r=="string")continue;let[s,i]=Object.entries(r)[0]??[];if(!s||!i)continue;if(fs(i)){s in n&&i.select&&(n[s]=ic(n[s],i.select));continue}let o=i;o.aggregate==="avg"&&o.cast!=="text"&&s in n&&(n[s]=VE(n[s]));}return n}function oc(t,e){if(Array.isArray(t))return t.map(r=>oc(r,e));if(!Hn(t))return t;let n={...t};for(let r of e){if(typeof r=="string")continue;let[s,i]=Object.entries(r)[0]??[];if(!s||!i)continue;if(fs(i)){s in n&&i.select&&(n[s]=oc(n[s],i.select));continue}om(i.cast)&&s in n&&(n[s]=am(n[s]));}return n}function ac(t,e){if(Array.isArray(t))return t.map(r=>ac(r,e));if(!Hn(t))return t;let n={...t};for(let r of e){if(typeof r=="string")continue;let[s,i]=Object.entries(r)[0]??[];if(!s||!i)continue;if(fs(i)){s in n&&i.select&&(n[s]=ac(n[s],i.select));continue}let o=i;o.path&&!o.pathText&&s in n&&(n[s]=am(n[s]));}return n}function VE(t){if(typeof t!="string")return t;let e=t.trim();if(!/^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i.test(e))return t;let n=Number(e);return !Number.isFinite(n)||e.replace(/^[+-]/,"").replace(/e[+-]?\d+$/i,"").replace(".","").replace(/^0+/,"").replace(/0+$/,"").length>15?t:n}function QE(t,e){let n=XE(t);return !e||e.length===0?n:lc(n,e)}function XE(t){if(typeof t!="string")return t;let e=t[0];if(e!=="["&&e!=="{")return t;try{return JSON.parse(t)}catch{return t}}function am(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}function Hn(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function fs(t){return t!==null&&typeof t=="object"&&("select"in t||"spread"in t||"join"in t)}var YE=new Set(["*/*","application/*","application/json","application/vnd.pgrst.object","application/vnd.pgrst.object+json","application/vnd.pgrst.array","application/vnd.pgrst.array+json","application/octet-stream","text/csv"]);function lm(t){let e=nm(t);return e?`application/vnd.pgrst.plan+${e.format}; for="application/json"${e.optionsSegment}`:t}function cm(t,e){let n=t.split(",").map(r=>r.split(";")[0].trim().toLowerCase()).filter(Boolean);if(n.length===0)return true;for(let r of n)if(YE.has(r)||e&&r.startsWith("application/vnd.pgrst.plan"))return true;return false}function um(t,e){let n=nm(t)??{format:"text",optionsSegment:""},r=`application/vnd.pgrst.plan+${n.format}; for="application/json"${n.optionsSegment}; charset=utf-8`,s=n.format==="json"?Et({sql:e.sql,parameters:[...e.parameters]}):e.sql;return new Response(s,{status:200,headers:{"Content-Type":r}})}function lt(t,e,n){let r=t+e-1,s=n!==void 0?`${n}`:"*";return `${t}-${r}/${s}`}function fm(t,e){let n=e.startsWith("?")?e.slice(1):e;if(!n)return;let s=[...new URLSearchParams(n).entries()].sort(([o],[a])=>o.localeCompare(a)),i=new URLSearchParams(s).toString();return i?`${t}?${i}`:t}async function qn(t,e,n,r){if(e.type==="rpc"){let f={...e,order:void 0,limit:void 0,offset:void 0},u=te(f,n,{db:t,introspection:r}),{sql:d,parameters:p}=u.compile(),g=`SELECT count(*) as __count FROM (${d}) AS __inner_count`,m=await t.executeQuery({sql:g,parameters:p,query:{kind:"RawNode"}});return Number(m.rows?.[0]?.__count??0)}let s=e.join&&Object.values(e.join).some(f=>f.type==="inner"),i=ZE(e);if(s||i){let f={...e,type:"query",order:void 0,limit:void 0,offset:void 0},u=te(f,n,{db:t,introspection:r}),{sql:d,parameters:p}=u.compile(),g=`SELECT count(*) as __count FROM (${d}) AS __inner_count`,h=(await t.executeQuery({sql:g,parameters:p,query:{kind:"RawNode"}})).rows?.[0];return Number(h?.__count??0)}let o={...e,type:"query",select:[{__count:{aggregate:"count"}}],order:void 0,limit:void 0,offset:void 0,join:void 0},l=await te(o,n,{db:t,introspection:r}).execute(),c=Array.isArray(l)?l[0]:l;return Number(c?.__count??0)}async function cc(t,e,n,r){if(e.$meta?.count!=="planned"&&e.$meta?.count!=="estimated"||n!=="postgres"||e.type==="rpc")return qn(t,e,n,r);let s={...e,type:"query",order:void 0,limit:void 0,offset:void 0},o=te(s,n,{db:t,introspection:r}).compile(),c=(await t.executeQuery({sql:`EXPLAIN (FORMAT JSON) ${o.sql}`,parameters:o.parameters,query:{kind:"RawNode"}})).rows?.[0]?.["QUERY PLAN"],f=Array.isArray(c)&&c[0]&&typeof c[0]=="object"?c[0].Plan:void 0,u=f&&typeof f=="object"?Number(f["Plan Rows"]):Number.NaN;return Number.isFinite(u)?u:qn(t,e,n,r)}function ZE(t){if(t.type!=="query"||!t.where||!t.select)return false;let e=ex(t.select);return e.size===0?false:dm(t.where,e)}function dm(t,e){for(let[n,r]of Object.entries(t)){if((n==="$or"||n==="$and")&&Array.isArray(r)){if(r.some(i=>i&&typeof i=="object"&&dm(i,e)))return true;continue}if(!e.has(n)||!r||typeof r!="object")continue;let s=r;if(s.$is===null||s.$isNot===null)return true}return false}function ex(t){let e=new Set;for(let n of t){if(typeof n=="string")continue;let[r,s]=Object.entries(n)[0]??[];r&&s&&typeof s=="object"&&"select"in s&&e.add(r);}return e}function uc(t){return t?.count==="exact"||t?.count==="planned"||t?.count==="estimated"}function Ht(t,e,n){return uc(e)?`*/${n??0}`:t.type==="update"&&n!==0?lt(0,n??1,void 0):"*/*"}function pm(t,e,n,r){return e&&(t.type==="insert"||t.type==="upsert"||t.type==="delete")?r!==void 0?`*/${r}`:"*/*":lt(n,1,r)}var tx=/[",\n\r ]/;function mm(t){if(t==null)return "";let e;return typeof t=="string"?e=t:typeof t=="number"||typeof t=="boolean"?e=String(t):typeof t=="bigint"?e=t.toString():e=JSON.stringify(t),tx.test(e)?`"${e.replace(/"/g,'""')}"`:e}function co(t,e){let n=t.length>0?Object.keys(t[0]):[];if(n.length===0)return "";let r=[n.map(s=>mm(s)).join(",")];for(let s of t)r.push(n.map(i=>mm(s[i])).join(","));return r.join(`
81
+ `)}function hm(t){return t.split(",").map(n=>n.split(";")[0].trim().toLowerCase()).includes("text/csv")}function bm(t){return t==null?[]:Array.isArray(t)?t.map(e=>ds(e)?new Set(Object.keys(e)):new Set):ds(t)?[new Set(Object.keys(t))]:[]}function wm(t,e,n){return !e?.length||!n?.length||t.length===0?t:t.map((r,s)=>{let i=n[s]??n[0],o={...r};for(let a of e)i.has(a)||(o[a]=null);return o})}function Sm(t,e){if(t.type!=="upsert"&&t.type!=="put")return {ast:t};if(t.type==="put"){if(t.limit!==void 0||t.offset!==void 0)return T(400,"PGRST114","limit/offset querystring parameters are not allowed for PUT",null,null);let r=gm(t,e),s=nx(t.where,r);if(!s)return T(405,"PGRST105","Filters must include all and only primary key columns with 'eq' operators",null,null);if(Array.isArray(t.values)&&t.values.length===0)return {ast:t,emptyPayload:true};if(!ds(t.values))return T(400,"PGRST102","Empty or invalid json",null,null);for(let i of r)if(!sx(t.values[i],s[i]))return T(400,"PGRST115","Payload values do not match URL in primary key column(s)",null,null);return t.onConflict=r,t.ignoreDuplicates=false,{ast:t,preflight:{mode:"put",conflictColumns:r}}}let n=t.onConflict?.length?t.onConflict:gm(t,e);return n.length===0?(t.onConflict=void 0,{ast:t}):(t.onConflict=n,{ast:t,appliedResolution:t.ignoreDuplicates?"ignore-duplicates":"merge-duplicates",preflight:t.ignoreDuplicates?void 0:{mode:"merge-duplicates",conflictColumns:n}})}function _m(t,e){let n=t.$meta,r={"Content-Type":"application/json; charset=utf-8"},s=ps(n,e.appliedResolution),i=n?.count==="exact"||n?.count==="planned"||n?.count==="estimated"?"*/0":"*/*",o=t.type==="upsert"?200:et(t,n?.return==="representation"?"representation":"no-return",e.appliedResolution,false);return n?.return==="representation"?(r["Content-Range"]=i,r["Content-Length"]="2",s&&(r["Preference-Applied"]=s),new Response("[]",{status:o,headers:r})):(r["Content-Range"]=i,s&&(r["Preference-Applied"]=s),new Response(null,{status:o,headers:r}))}function gm(t,e){if(!t.from)return [];let n=t.schema??"public",r=e.primary_keys.find(s=>s.table===t.from&&s.schema===n);return r?r.columns:e.primary_keys.find(s=>s.table===t.from)?.columns??[]}function nx(t,e){if(!t||e.length===0)return null;let n=Object.keys(t);if(n.length!==e.length)return null;let r={};for(let s of n){if(s.startsWith("$")||!e.includes(s))return null;let i=rx(t[s]);if(!i.ok)return null;r[s]=i.value;}return r}function rx(t){if(!ds(t))return {ok:false};let e=Object.keys(t);return e.length!==1||e[0]!=="$eq"?{ok:false}:{ok:true,value:t.$eq}}function sx(t,e){return Object.is(t,e)?true:t!==null&&e!==null&&t!==void 0&&e!==void 0&&typeof t!="object"&&typeof e!="object"?String(t)===String(e):Et(t)===Et(e)}function ps(t,e){let n=[];return e&&n.push(`resolution=${e}`),t?.missing&&n.push(`missing=${t.missing}`),t?.return&&n.push(`return=${t.return}`),t?.count&&t.count!=="none"&&n.push(`count=${t.count}`),t?.tx&&n.push(`tx=${t.tx}`),n.length>0?n.join(", "):void 0}function et(t,e,n,r){switch(t.type){case "insert":return 201;case "upsert":return !n||n==="ignore-duplicates"?201:r===false?200:201;case "put":return e==="representation"?r?201:200:204;case "update":case "delete":return e==="representation"?200:204;default:return 200}}async function Em(t,e,n,r,s){if(e.type==="insert")return true;if(!s.preflight||!e.from)return;if(s.preflight.mode==="put")return !await ym(t,e.from,e.schema,e.where??{},n,r);let i=Array.isArray(e.values)?e.values:e.values?[e.values]:[];for(let o of i){if(!ds(o))continue;let a=ix(s.preflight.conflictColumns,o);if(!a||!await ym(t,e.from,e.schema,a,n,r))return true}return false}function ix(t,e){let n={};for(let r of t){if(!(r in e))return;n[r]={$eq:e[r]};}return n}async function ym(t,e,n,r,s,i){return await qn(t,{type:"query",from:e,schema:n,where:r},s,i)>0}function ds(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function ox(t){return "select"in t||"spread"in t||"join"in t}function xm(t,e){if(t){for(let n of t)if(typeof n!="string")for(let r of Object.values(n))ox(r)&&((r.limit===void 0||r.limit>e)&&(r.limit=e),xm(r.select,e));}}var ax={count:new Set(["exact","planned","estimated"]),resolution:new Set(["merge-duplicates","ignore-duplicates"]),return:new Set(["minimal","headers-only","representation"]),tx:new Set(["commit","rollback"]),missing:new Set(["default","null"]),handling:new Set(["strict","lenient"]),"max-affected":"number",timezone:"string",params:new Set(["single-object","multiple-objects"])};function lx(t,e){if(!t)return [];let n=t.split(",").map(i=>i.trim()).filter(Boolean);if(n.find(i=>i.startsWith("handling="))!=="handling=strict")return [];let s=e?new Set(e):void 0;return n.filter(i=>!cx(i,s))}function cx(t,e){let n=t.indexOf("=");if(n===-1)return false;let r=t.slice(0,n).trim(),s=t.slice(n+1).trim();if(r==="timezone")return e?e.has(s):s.length>0;let i=ax[r];return i?i==="string"?s.length>0:i==="number"?/^-?\d+$/.test(s):i.has(s):false}function ux(t){if(!t.from||!t.order)return null;let e=t.order.find(n=>/^\s+/.test(n.column));return e?T(400,"42703",`column ${t.from}.${e.column.trim()} does not exist`,null,null):null}function Tm(t){let e=t.ast,{dialect:n,introspection:r,apiConfig:s,acceptHeader:i,preferHeader:o,httpMethod:a,rangeHeader:l}=t,c=s??{};if(c?.aggregates_enabled!==true&&yl(e.select))return T(400,"PGRST123","Use of aggregate functions is not allowed",null,null);let f=c?.plan_enabled===true;if(!t.allowRawMedia&&!cm(i,f))return T(406,"PGRST107",`None of these media types are available: ${lm(i)}`,null,null);let u=sm(i),d=hm(i),p=lx(o,r.timezones);if(p.length>0)return T(400,"PGRST122","Invalid preferences given with handling=strict",`Invalid preferences: ${p.join(", ")}`,null);let g=ux(e);if(g)return g;if(n==="sqlite"&&e.from){let b=e.schema??"",_=r.tables.some(x=>x.name===e.from&&(x.schema??"")===b),E=r.views.some(x=>x.name===e.from&&(x.schema??"")===b);if(!_&&!E)throw new Bn(e.schema,e.from)}let m=e.$meta,h=e.type==="update"||e.type==="delete"||e.type==="insert"||e.type==="upsert"||e.type==="put",y={ast:e};if(h&&m?.return!=="representation"&&(e.select=void 0),(e.type==="put"||e.type==="upsert")&&(e.limit!==void 0||e.offset!==void 0))return T(400,"PGRST114","limit/offset querystring parameters are not allowed for PUT",null,null);if((e.type==="update"||e.type==="delete"||e.type==="insert")&&c?.limited_mutations_enabled!==true&&(e.limit=void 0,e.offset=void 0),c?.pg_safe_update&&h){let b=e.where&&Object.keys(e.where).length>0;if(e.type==="update"&&!b)return T(400,"21000","UPDATE requires a WHERE clause",null,null);if(e.type==="delete"&&!b)return T(400,"21000","DELETE requires a WHERE clause",null,null)}if(h&&(e.type==="insert"||e.type==="update"||e.type==="upsert"||e.type==="put")){if((e.type==="update"||e.type==="insert"||e.type==="upsert"||e.type==="put")&&(e.values===void 0||e.values===null))return T(400,"PGRST102","Empty or invalid json",null,null);if(e.type==="update"&&e.values&&typeof e.values=="object"&&!Array.isArray(e.values)&&Object.keys(e.values).length===0){let b=m?.return==="representation"?200:204,_=ps(m,y.appliedResolution),E={"Content-Type":"application/json; charset=utf-8","Content-Range":Ht(e,m,0)};if(_&&(E["Preference-Applied"]=_),m?.return==="representation"){let x=new TextEncoder().encode("[]");return E["Content-Length"]=String(x.byteLength),new Response(x,{status:b,headers:E})}return new Response(null,{status:b,headers:E})}if(e.type==="put"&&Array.isArray(e.values)&&(e.values.length===0?y.emptyPayload=true:e.values=e.values[0]),Array.isArray(e.values)){if(m?.cardinality==="one"&&(e.type==="insert"||e.type==="upsert")&&e.values.length>1)return T(406,"PGRST116","Cannot coerce the result to a single JSON object",`The result contains ${e.values.length} rows`,null);if(e.values.length>0&&e.values.some(b=>typeof b!="object"||b===null||Array.isArray(b)))return m?.columns?T(400,"22023","argument of jsonb_to_recordset must be an array of objects",null,null):T(400,"PGRST102","All object keys must match",null,null);if(!m?.columns&&e.values.length>1){let b=Object.keys(e.values[0]).sort().join(",");for(let _=1;_<e.values.length;_++)if(Object.keys(e.values[_]).sort().join(",")!==b)return T(400,"PGRST102","All object keys must match",null,null)}}if(m?.columns&&e.from){y.bodyKeySets=bm(e.values);let b=r.columns.filter(E=>E.table===e.from).map(E=>E.name);for(let E of m.columns){if(E==="")return T(400,"PGRST100",'"failed to parse columns parameter ()" (line 1, column 1)',"unexpected end of input",null);if(!b.includes(E))return T(400,"PGRST204",`Could not find the '${E}' column of '${e.from}' in the schema cache`,null,null)}let _=new Set(m.columns);if(e.values)if(Array.isArray(e.values))e.values=e.values.map(E=>{let x={};for(let O of _)O in E&&(x[O]=E[O]);return x});else {let E={};for(let x of _)x in e.values&&(E[x]=e.values[x]);e.values=E;}}if(!m?.columns&&e.values&&e.from&&(e.type==="insert"||e.type==="update"||e.type==="upsert"||e.type==="put")){let b=r.columns.filter(_=>_.table===e.from).map(_=>_.name);if(b.length>0){let _=Array.isArray(e.values)?e.values.length>0?Object.keys(e.values[0]):[]:Object.keys(e.values);for(let E of _)if(!b.includes(E))return T(400,"PGRST204",`Could not find the '${E}' column of '${e.from}' in the schema cache`,null,null)}}if(e.values&&e.from&&(e.type==="insert"||e.type==="update"||e.type==="upsert"||e.type==="put")){let b=e.schema??"public",_=new Set(r.columns.filter(E=>E.table===e.from&&(E.schema||"public")===b&&E.is_generated===true).map(E=>E.name));if(_.size>0){let E=Array.isArray(e.values)?e.values:[e.values];for(let x of E)if(!(!x||typeof x!="object")){for(let O of Object.keys(x))if(_.has(O))return T(400,"428C9",`cannot insert a non-DEFAULT value into column "${O}"`,`Column "${O}" is a generated column.`,null)}}}}let w=Sm(e,r);if(w instanceof Response)return w;let S=y.bodyKeySets;if(y=w,y.bodyKeySets=S,e=y.ast,h&&((e.type==="insert"||e.type==="upsert")&&Array.isArray(e.values)&&e.values.length===0||y.emptyPayload))return m?.cardinality==="one"?T(406,"PGRST116","Cannot coerce the result to a single JSON object","The result contains 0 rows",null):_m(e,y);if(l&&(a==="GET"||a==="HEAD")){let b=l.match(/^(\d+)-(\d*)$/);if(b){let _=parseInt(b[1],10);if(b[2]!==""){let E=parseInt(b[2],10);if(_>E)return T(416,"PGRST103","Requested range not satisfiable","The lower boundary must be lower than or equal to the upper boundary in the Range header.",null);e.offset=_,e.limit=E-_+1;}else e.offset=_;}}if(e.limit!==void 0&&e.limit<0||e.limit===0&&e.offset!==void 0&&e.offset>0)return T(416,"PGRST103","Requested range not satisfiable","Limit should be greater than or equal to zero.",null);if(e.offset!==void 0&&e.offset<0&&(e.offset=0),!h){let b=c?.max_rows;b!==void 0&&b>0&&((e.limit===void 0||e.limit>b)&&(e.limit=b),xm(e.select,b));}return {ast:e,meta:m,mutationPlan:y,isMutation:h,stripNullsResponse:u,csvResponse:d,planEnabled:f}}var Wn=class extends Error{constructor(n){super(`new row violates row-level security policy for table "${n.data.table}"`);this.policy=n;this.name="PolicyViolation";}};Oi();Vr();Fn();function Rm(t){if(t.from)return t.from}function vm(t,e){let{connection:n,introspection:r,vars:s,ast:i}=e;if(t instanceof fe){let a=`"${t.message}" (line 1, column ${t.position})`;return T(400,"PGRST100",a,t.details,null)}if(t instanceof He)return T(400,"PGRST100",t.message,t.details,null);if(t instanceof An)return T(400,t.code,t.message,null,null);if(t instanceof jt)return T(400,"PGRST100",t.message,t.details,null);if(t instanceof vn)return T(404,"PGRST125",t.message,t.details,null);if(t instanceof ve)return T(t.httpStatus,t.code,t.message,t.details,t.hint);if(t instanceof On)return T(400,"PGRST102",t.message,null,null);if(t instanceof vr)return T(400,"PGRST102",t.message,null,null);if(t instanceof Error&&t.message.startsWith("Invalid JSON body"))return T(400,"PGRST102","Empty or invalid json",null,null);if(t instanceof wt)return T(400,"PGRST100",t.message,t.message,null);if(t instanceof on)return T(400,"23514",t.message,`check constraint "${t.constraint}" violated`,null);if(t instanceof Wn){let l=qt(s,"auth.role","anon")==="anon"?401:403;return ot({status:l,code:"PGRST301",message:t.message})}let o=n.normalizeDbError(t);if(console.error(o),o instanceof Bn){let a=o.schema||"public",l=[...r.tables.filter(d=>(d.schema||"public")===a).map(d=>d.name),...r.views.filter(d=>(d.schema||"public")===a).map(d=>d.name)],c=l.length>0?l:[...r.tables.map(d=>d.name),...r.views.map(d=>d.name)],f=Jr(o.relation,c),u=f?`Perhaps you meant the table '${a}.${f}'`:null;return ot({status:404,code:"PGRST205",message:o.message,hint:u})}if(typeof o?.code=="string"){if(o.code==="PGRST")return dx(o);let a=/^PT(\d{3})$/.exec(o.code);if(a){let l=Number(a[1]);return T(l>=200&&l<=599?l:500,o.code,o.message,o.detail??null,o.hint??null)}if(o.code.startsWith("PT"))return T(500,o.code,o.message,o.detail??null,o.hint??null)}if(o?.code==="42501"){let l=qt(s,"auth.role","anon")==="anon"?401:403;return T(l,"42501",o.message,o.detail??null,o.hint??null)}if(o?.code==="42P01")return T(404,"PGRST205","Could not find the relation in the schema cache",o.message,null);if(o?.code==="23505"||o?.code==="23503")return T(409,o.code,o.message,o.detail??null,null);if(o?.code==="25006")return T(405,"25006",o.message,o.detail??null,o.hint??null);if(typeof o?.code=="string"){let a=o.code.slice(0,2);if(o.code==="42883"){let l=o.message;return l=l.replace(/^operator does not exist: [\w.]+\.([\w]+) /,"operator does not exist: $1 "),T(404,o.code,l,o.detail??null,o.hint??null)}if(o.code==="42P17")return T(500,o.code,o.message,o.detail??null,o.hint??null);if(a==="42"||a==="22"||a==="21"||o.code==="23502"){let l=o.message,c=i?Rm(i):void 0;if(o.code==="42703"&&c){let f=i?.onConflict;l=l.replace(/^column "([^"]+)" does not exist$/,(u,d)=>f?.includes(d)?u:`column ${c}.${d} does not exist`);}return T(400,o.code,l,o.detail??null,o.hint??null)}if(a==="55"||a==="53")return T(500,o.code,o.message,o.detail??null,o.hint??null)}return o?.message?.includes("Unknown operator")?T(400,"PGRST100",o.message,null,null):o instanceof Error&&(o.message.includes("Expected identifier")||o.message.includes("Invalid filter")||o.message.includes("Unexpected input")||o.message.includes("Unsupported operator")||o.message.includes("failed to parse filter")||o.message.includes("failed to parse logic tree")||/^Expected .* at position \d+$/.test(o.message)||o.message.startsWith('Expected "(" for spread embed'))?T(400,"PGRST100",o.message,o.message,null):T(500,"SUP",String(o),null,null)}var fc=`Could not parse JSON in the "RAISE SQLSTATE 'PGRST'" error`,fx="MESSAGE must be a JSON object with obligatory keys: 'code', 'message' and optional keys: 'details', 'hint'.",Cm="DETAIL must be a JSON object with obligatory keys: 'status', 'headers' and optional key: 'status_text'.";function km(t){if(typeof t!="string")return null;try{let e=JSON.parse(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function dx(t){let e=typeof t.message=="string"?t.message:"",n=km(e);if(!n||typeof n.code!="string"||typeof n.message!="string")return T(500,"PGRST121",fc,`Invalid JSON value for MESSAGE: '${e}'`,fx);let r=t.detail;if(r==null||r==="")return T(500,"PGRST121",fc,"DETAIL is missing in the RAISE statement",Cm);let s=km(r),i=s?.headers,o=!!i&&typeof i=="object"&&!Array.isArray(i);if(!s||typeof s.status!="number"||!o)return T(500,"PGRST121",fc,`Invalid JSON value for DETAIL: '${r}'`,Cm);let a=JSON.stringify({code:n.code,details:n.details??null,hint:n.hint??null,message:n.message}),l=new TextEncoder().encode(a),c={"Content-Type":"application/json; charset=utf-8","Content-Length":String(l.byteLength)};for(let[u,d]of Object.entries(i))typeof d=="string"&&(c[u]=d);let f={status:s.status,headers:c};typeof s.status_text=="string"&&(f.statusText=s.status_text);try{return new Response(l,f)}catch{return new Response(l,{status:500,headers:{"Content-Type":"application/json; charset=utf-8","Content-Length":String(l.byteLength)}})}}var mx="response.status guc must be a valid status code",Kn="response.headers guc must be a JSON array composed of objects with a single key and a string value";async function Am(t,e){let n=(await sql`
82
82
  SELECT current_setting('response.status', true) AS status,
83
83
  current_setting('response.headers', true) AS headers
84
- `.execute(t)).rows[0],r=n?.status??null,s=n?.headers??null,i;if(r&&r.length>0){let f=Number(r);if(!Number.isInteger(f)||f<200||f>599)return T(500,"PGRST112",cx,null,null);i=f;}let o;if(s&&s.length>0){let f;try{f=JSON.parse(s);}catch{return T(500,"PGRST111",Kn,null,null)}if(!Array.isArray(f))return T(500,"PGRST111",Kn,null,null);let u=[];for(let d of f){if(!d||typeof d!="object"||Array.isArray(d))return T(500,"PGRST111",Kn,null,null);let p=Object.keys(d);if(p.length!==1)return T(500,"PGRST111",Kn,null,null);let g=d[p[0]];if(typeof g!="string")return T(500,"PGRST111",Kn,null,null);u.push([p[0],g]);}o=u;}if(i===void 0&&!o)return e;let a=i??e.status,l=new Headers(e.headers);if(o)try{for(let[f,u]of o)l.set(f,u);}catch{return T(500,"PGRST111",Kn,null,null)}let c;return ux.has(a)?(c=null,l.delete("Content-Length"),l.delete("Content-Type")):c=e.body?await e.arrayBuffer():null,new Response(c,{status:a,statusText:e.statusText,headers:l})}var ux=new Set([101,204,205,304]);var fx=/^[\w.+*-]+\/[\w.+*-]+$/,dx=new Set(["text/plain","text/xml","text/csv","application/json","application/geo+json","application/openapi+json"]);function px(t){return t.replace(/^"([\s\S]*)"$/,"$1")}function mx(t){let e=t.match(/^(?:"(?:[^"]|"")*"|[^."]+)\.([\s\S]+)$/);return e?e[1]:t}function hx(t){if(t.return_typtype!=="d"||t.return_is_setof)return null;let e=px(mx(t.return_type));return fx.test(e)?e:null}function vm(t){if(!t)return [];let e=[];for(let n of t.split(",")){let r=n.split(";"),s=r[0].trim().toLowerCase();if(!s)continue;let i=1;for(let o of r.slice(1)){let a=o.trim().match(/^q=(.+)$/i);if(a){let l=Number.parseFloat(a[1]);Number.isFinite(l)&&(i=l);}}e.push({media:s,q:i});}return e}function Am(t){return dx.has(t)?`${t}; charset=utf-8`:t}function gx(t,e){let n=e.indexOf("/"),r=n>0?e.slice(0,n):e,s=-1,i=0;for(let o of t){let a=o.media===e?2:o.media===`${r}/*`?1:o.media==="*/*"?0:-1;a<0||(a>s?(s=a,i=o.q):a===s&&(i=Math.max(i,o.q)));}return s<0?0:i}function yx(t,e){let n=hx(t);if(!n)return null;if(n==="*/*"){let r=vm(e);return r.some(s=>s.media==="*/*"&&s.q<=0)?null:!e||r.some(s=>s.q>0)?{mediaType:"application/octet-stream",isBinary:true}:null}return gx(vm(e),n)>0?{mediaType:n,isBinary:(t.return_base_type??"").toLowerCase()==="bytea"}:null}function ao(t,e,n){let r=Ji(t,e);return r?yx(r,n):null}function Om(t,e){if(t instanceof Uint8Array){let s=new Uint8Array(t.byteLength);return s.set(t),s}if(e&&typeof t=="string"&&t.startsWith("\\x")){let s=t.slice(2),i=new Uint8Array(Math.floor(s.length/2));for(let o=0;o<i.length;o++)i[o]=parseInt(s.substr(o*2,2),16);return i}let n=new TextEncoder().encode(t==null?"":String(t)),r=new Uint8Array(n.byteLength);return r.set(n),r}var Pm=ca(Cl());function Te(t,e,n){if(!n)return;let{sql:r,parameters:s}=e.compile();console.info(Pm.default.dim(`[POSTGREST:SQL:${t}] ${r}
85
- - ${JSON.stringify([...s])}`));}async function $m(t){let{ast:e,meta:n,db:r,dialect:s,introspection:i,deparseSchema:o,mutationPlan:a,mutationCreated:l}=t;if(!t.isMutation||n?.return!=="minimal")return null;let c={...e,select:void 0},f=te(c,s,{db:r,introspection:i,schema:o});Te("",f,t.debug);let u=await f.execute(),d=Array.isArray(u)&&u.length>0&&u[0]&&typeof u[0]=="object"&&("numUpdatedRows"in u[0]||"numInsertedOrUpdatedRows"in u[0]||"numDeletedRows"in u[0])?u[0]:void 0,p=d===void 0?void 0:Number(d.numUpdatedRows??d.numInsertedOrUpdatedRows??d.numDeletedRows??0),g=et(e,"no-return",a.appliedResolution,l),m={"Content-Range":Ht(e,n,p)};return t.prefApplied&&(m["Preference-Applied"]=t.prefApplied),new Response(null,{status:g,headers:m})}async function Im(t){let{ast:e,meta:n,db:r,dialect:s,introspection:i,deparseSchema:o,mutationPlan:a,mutationCreated:l,prefApplied:c}=t;if(!t.isMutation||n?.return!=="headers-only")return null;let u=i.primary_keys.find(w=>w.table===e.from)?.columns??[],d={...e,select:u.length>0?u:void 0},p=te(d,s,{db:r,introspection:i,schema:o});Te("",p,t.debug);let g=await p.execute(),m=Array.isArray(g)?g.length:0,h=et(e,"no-return",a.appliedResolution,l),y={"Content-Range":Ht(e,n,m)};if(c&&(y["Preference-Applied"]=c),u.length>0&&Array.isArray(g)&&g.length>0){let w=g[0],S=u.map(b=>`${b}=eq.${w[b]}`).join("&");y.Location=`/${e.from}?${S}`;}return new Response(null,{status:h,headers:y})}function Jn({rows:t,ast:e,connection:n,responseSchemaMap:r,mutationNullify:s}){let i=t.map(o=>n.deserializeRow(o));return i=Xp(i,e,r,Yp(n,e)),i=rm(i,e.select,n.dialect),s?.meta?.return==="representation"&&(e.type==="insert"||e.type==="upsert"||e.type==="update")&&(i=ym(i,s.meta?.columns,s.mutationPlan.bodyKeySets)),i}function lo(t){let{rows:e,stripNullsResponse:n,csvResponse:r,contentRange:s,status:i=200,preferenceApplied:o,location:a,contentType:l="array"}=t,c=n?pn(e):e,f=r?oo(Array.isArray(c)?c:[c]):Et(c),u=new TextEncoder().encode(f),d={"Content-Type":r?"text/csv; charset=utf-8":n?l==="object"?"application/vnd.pgrst.object+json;nulls=stripped; charset=utf-8":"application/vnd.pgrst.array+json;nulls=stripped; charset=utf-8":l==="object"?"application/vnd.pgrst.object+json; charset=utf-8":"application/json; charset=utf-8","Content-Range":s,"Content-Length":String(u.byteLength)};return o&&(d["Preference-Applied"]=o),a&&(d.Location=a),new Response(u,{status:i,headers:d})}async function Nm(t){let{ast:e,meta:n,db:r,dialect:s,introspection:i,deparseSchema:o,connection:a,responseSchemaMap:l}=t;if(!(t.isMutation&&(e.type==="update"||e.type==="delete")&&(e.limit!==void 0||e.offset!==void 0)))return null;let f={...e,select:void 0},u=te(f,s,{db:r,introspection:i,schema:o});if(Te("LTD",u,t.debug),await u.execute(),n?.return==="representation"){let S={...e,type:"query",values:void 0,limit:void 0,offset:void 0},b=te(S,s,{db:r,introspection:i,schema:o});Te("LTD-SEL",b,t.debug);let _=await b.execute(),E=Array.isArray(_)?_:[],x=Jn({rows:E,ast:e,connection:a,responseSchemaMap:l}),O=x.length,v=[];n.return==="representation"&&v.push("return=representation"),n.count&&v.push(`count=${n.count}`),n.tx&&v.push(`tx=${n.tx}`);let P=e.type==="delete"?"*/*":O>0?lt(0,O,void 0):"*/*";return lo({rows:x,stripNullsResponse:t.stripNullsResponse,csvResponse:t.csvResponse,contentRange:P,preferenceApplied:v.length>0?v.join(", "):void 0})}let d={...e,type:"query",select:[{__count:{aggregate:"count"}}],values:void 0,order:void 0,limit:void 0,offset:void 0},g=await te(d,s,{db:r,introspection:i,schema:o}).execute(),m=Number((Array.isArray(g)?g[0]:g)?.__count??0),y={"Content-Range":m>0?lt(0,m,void 0):"*/*"},w=[];return n?.count&&w.push(`count=${n.count}`),n?.tx&&w.push(`tx=${n.tx}`),w.length>0&&(y["Preference-Applied"]=w.join(", ")),new Response(null,{status:204,headers:y})}function bx(t){return "select"in t||"spread"in t||"join"in t}function Dm(t){if(!t)return false;for(let e of t)if(typeof e!="string")for(let[n,r]of Object.entries(e)){if(bx(r))return true;let s=r;if(s.path||s.cast||s.preCast||s.aggregate||(s.column??n)!==n)return true}return false}async function jm(t){let{ast:e,meta:n,db:r,dialect:s,introspection:i,deparseSchema:o,connection:a,responseSchemaMap:l,mutationPlan:c,mutationCreated:f}=t;if(!(t.isMutation&&n?.return==="representation"&&Dm(e.select)))return null;let p=i.primary_keys.find(_=>_.table===e.from)?.columns??[],g=[];if(e.type==="delete"){let _={...e,type:"query",values:void 0},E=te(_,s,{db:r,introspection:i,schema:o});Te("EMB-PRE",E,t.debug),g=await E.execute();let x={...e,select:void 0},O=te(x,s,{db:r,introspection:i,schema:o});Te("EMB-DEL",O,t.debug),await O.execute();}else {if(p.length===0)return T(500,"PGRSTXXX","Cannot return embedded data on a table without a primary key",null,null);let _={...e,select:p},E=te(_,s,{db:r,introspection:i,schema:o});Te("EMB-MUT",E,t.debug);let x=await E.execute(),O=Array.isArray(x)?x:[];if(O.length>0){let v;if(p.length===1){let U=p[0];v={[U]:{$in:O.map(J=>J[U])}};}else v={$or:O.map(U=>{let J={};for(let F of p)J[F]={$eq:U[F]};return J})};let P=e.where?{$and:[e.where,v]}:v,C={...e,type:"query",values:void 0,where:P},R=te(C,s,{db:r,introspection:i,schema:o});Te("EMB-SEL",R,t.debug),g=await R.execute();}}let m=Jn({rows:g,ast:e,connection:a,responseSchemaMap:l,mutationNullify:{meta:n,mutationPlan:c}});e.order&&e.order.length>0&&(m=io(m,e.order));let h=et(e,"representation",c.appliedResolution,f),y=m.length,w=["return=representation"];n?.count&&w.push(`count=${n.count}`),n?.tx&&w.push(`tx=${n.tx}`);let S=e.type==="delete"||e.type==="insert"||e.type==="upsert"?"*/*":y>0?lt(0,y,void 0):"*/*",b;if((e.type==="insert"||e.type==="upsert")&&p.length>0&&m.length>0){let _=m[0],E=p.map(x=>`${x}=eq.${_[x]}`).join("&");b=`/${e.from}?${E}`;}return lo({rows:m,stripNullsResponse:t.stripNullsResponse,csvResponse:t.csvResponse,contentRange:S,status:h,preferenceApplied:w.join(", "),location:b})}function wx(t){return t?.handling!=="strict"||typeof t.maxAffected!="number"||!Number.isFinite(t.maxAffected)?null:t.maxAffected}function Lm(t){return T(400,"PGRST124","Query result exceeds max-affected preference constraint",`The query affects ${t} rows`,null)}function Sx(t){return t.type!=="insert"&&t.type!=="upsert"&&t.type!=="put"?null:Array.isArray(t.values)?t.values.length:t.values&&typeof t.values=="object"?1:0}async function Fm(t){if(!t.isMutation)return null;let e=wx(t.meta);if(e===null)return null;let n=Sx(t.ast);if(n!==null)return n>e?Lm(n):null;if(t.ast.type!=="update"&&t.ast.type!=="delete")return null;let r={...t.ast,type:"query",select:[{__count:{aggregate:"count"}}],values:void 0,order:void 0,limit:void 0,offset:void 0},s=te(r,t.dialect,{db:t.db,introspection:t.introspection,schema:t.deparseSchema});Te("MAX-AFFECTED",s,t.debug);let i=await s.execute(),o=Number((Array.isArray(i)?i[0]:i)?.__count??0);return t.ast.offset!==void 0&&(o=Math.max(o-t.ast.offset,0)),t.ast.limit!==void 0&&(o=Math.min(o,t.ast.limit)),o>e?Lm(o):null}function mn(t){return t||"public"}function _x(t,e,n){let r=mn(e);return n.views.some(s=>s.name===t&&mn(s.schema)===r)}function Ex(t){let e=t.match(/\bINSERT\s+INTO\s+(?:(?:"([^"]+)"|'([^']+)')|(\w+))(?:\.(?:(?:"([^"]+)"|'([^']+)')|(\w+)))?/i);if(e)return e[6]??e[3]}function xx(t,e,n){let r=mn(e);for(let s of n.triggers){if(s.table!==t||mn(s.schema)!==r||!/\bINSTEAD\s+OF\b/i.test(s.sql))continue;let i=Ex(s.sql);if(i)return i}}async function Um(t,e,n,r,s,i){if(r!=="sqlite"&&r!=="postgres"||!e.from||t.length===0||!_x(e.from,e.schema,n))return t;let o=e.select;if(!o?.length)return t;let a=mn(e.schema),l=n.primary_keys.find(h=>h.table===e.from&&mn(h.schema)===a)?.columns??[];if(l.length===0){let h=xx(e.from,e.schema,n);h&&(l=n.primary_keys.find(y=>y.table===h&&mn(y.schema)===a)?.columns??[]);}if(l.length===0&&t[0]&&"id"in t[0]&&(l=["id"]),l.length!==1)return t;let c=l[0],f=t.map(h=>h[c]).filter(h=>h!=null);if(f.length===0)return t;let u={type:"query",from:e.from,schema:e.schema,select:o,where:{[c]:{$in:f}}},p=await te(u,r,{db:s,introspection:n,schema:i}).execute(),g=h=>String(h[c]),m=new Map(p.map(h=>[g(h),h]));return t.map(h=>m.get(g(h))??h)}async function Mm(t){let{ast:e,meta:n,db:r,dialect:s,introspection:i,deparseSchema:o,connection:a,responseSchemaMap:l,mutationPlan:c,mutationCreated:f,prefApplied:u,isMutation:d,stripNullsResponse:p,csvResponse:g,requestUrl:m,acceptHeader:h}=t,y=te(e,s,{db:r,introspection:i,schema:o});Te("",y,t.debug);let w=await y.execute(),S,b=false,_=0;if(d&&Array.isArray(w)&&w.length>0&&w[0]&&typeof w[0]=="object"&&("numUpdatedRows"in w[0]||"numInsertedOrUpdatedRows"in w[0]||"numDeletedRows"in w[0])){b=true;let G=w[0];_=Number(G.numUpdatedRows??G.numInsertedOrUpdatedRows??G.numDeletedRows??0),S=[];}else S=w;d&&Array.isArray(S)&&S.length>0&&(S=await Um(S,e,i,s,r,o));let E=false,x,O=false,v=false,P=false,C=null;if(e.type==="rpc"&&Array.isArray(S)){let G={schema:e.schema??i.default_schema??"public",fnName:e.function??"",providedNames:fn(e),paramsType:e.paramsType,argCount:Array.isArray(e.args)?e.args.length:void 0,method:e.httpMethod,inputType:e.inputType};C=ao(i.functions,G,h);let pe=Gi(i.functions,G);if(pe){let Me=e.function??"",ht=S;E=!pe.returns_object&&ht.length>0&&ht.every(Xs=>{let gr=Object.keys(Xs);return gr.length===1&&gr[0]===Me}),E&&(x=Me,S=ht.map(Xs=>Xs[Me])),O=!pe.return_is_setof,P=pe.volatility!=="v",v=pe.returns_void;}}if(v){let G={"Content-Range":"0-0/*"};return u&&(G["Preference-Applied"]=u),new Response(null,{status:204,headers:G})}if(C&&Array.isArray(S)&&S.length===1){let G=S[0];if(!E&&G&&typeof G=="object"&&!Array.isArray(G)&&!(G instanceof Uint8Array)){let ht=Object.keys(G);ht.length===1&&(G=G[ht[0]]);}let pe=Om(G,C.isBinary),Me={"Content-Type":Am(C.mediaType),"Content-Range":"0-0/*","Content-Length":String(pe.byteLength)};return u&&(Me["Preference-Applied"]=u),n?.head?new Response(null,{status:200,headers:Me}):new Response(pe,{status:200,headers:Me})}let R=Array.isArray(S);R&&!E&&(S=Jn({rows:S,ast:e,connection:a,responseSchemaMap:l,mutationNullify:{meta:n,mutationPlan:c}})),d&&R&&e.order&&e.order.length>0&&(S=io(S,e.order));let U=R?S:[],J=U.length,F=e.offset??0;if(d&&b){if(n?.cardinality==="one"){if(_===0)return T(406,"PGRST116","Cannot coerce the result to a single JSON object","The result contains 0 rows",null);if(_>1)return T(406,"PGRST116","Cannot coerce the result to a single JSON object",`The result contains ${_} rows`,null)}let G=et(e,"no-return",c.appliedResolution,f),pe={"Content-Type":"application/json; charset=utf-8","Content-Range":Ht(e,n,_)};return u&&(pe["Preference-Applied"]=u),new Response(null,{status:G,headers:pe})}let V;if(ac(n)&&(d?V=J:e.type==="rpc"?F===0&&J<(e.limit??Number.POSITIVE_INFINITY)?V=J:P&&(V=await oc(r,e,s,i)):V=await oc(r,e,s,i)),n?.cardinality==="one"||O){if(J===0)return T(406,"PGRST116","Cannot coerce the result to a single JSON object","The result contains 0 rows",null);if(J>1)return T(406,"PGRST116","Cannot coerce the result to a single JSON object",`The result contains ${J} rows`,null);let G=200;d&&(G=et(e,"representation",c.appliedResolution,f));let pe=p?pn(U[0]):U[0],Me=Et(pe),ht=new TextEncoder().encode(Me),gr=n?.cardinality==="one"?"application/vnd.pgrst.object+json":"application/json",aa={"Content-Type":p?`${gr};nulls=stripped; charset=utf-8`:`${gr}; charset=utf-8`,"Content-Range":fm(e,d,F,V),"Content-Length":String(ht.byteLength)};return u&&(aa["Preference-Applied"]=u),n?.head?new Response(null,{status:G,headers:aa}):new Response(ht,{status:G,headers:aa})}if(V!==void 0&&F>0&&J===0&&F>=V){let G=JSON.stringify({code:"PGRST103",details:`An offset of ${F} was requested, but there are only ${V} rows.`,hint:null,message:"Requested range not satisfiable"}),pe=new TextEncoder().encode(G),Me={"Content-Type":"application/json; charset=utf-8","Content-Range":`*/${V}`,"Content-Length":String(pe.byteLength)};return u&&(Me["Preference-Applied"]=u),new Response(pe,{status:416,headers:Me})}let be;d&&(e.type==="insert"||e.type==="upsert"||e.type==="delete")?be=V!==void 0?`*/${V}`:"*/*":d&&n?.return!=="representation"?be=V!==void 0?`*/${V}`:"*/*":J>0?be=lt(F,J,V):be=V!==void 0?`*/${V}`:"*/*";let he=200;d?he=et(e,"representation",c.appliedResolution,f):V!==void 0&&(F+J<V||F>0)&&(he=206);let Ve=p?pn(S):S,Tn=Array.isArray(Ve)?Ve:[Ve];if(g&&E&&x!==void 0){let G=x;Tn=Tn.map(pe=>({[G]:pe}));}let Ys=g?oo(Tn):Et(Ve),oa=new TextEncoder().encode(Ys),Ot={"Content-Type":g?"text/csv; charset=utf-8":p?"application/vnd.pgrst.array+json;nulls=stripped; charset=utf-8":"application/json; charset=utf-8","Content-Range":be,"Content-Length":String(oa.byteLength)};if(!d&&e.from&&m){let G=cm(`/${e.from}`,new URL(m).search);G&&(Ot["Content-Location"]=G);}return u&&(Ot["Preference-Applied"]=u),n?.head?new Response(null,{status:he,headers:Ot}):new Response(oa,{status:he,headers:Ot})}function Bm(t){return t==="snake_case"?"__":"."}function qm(t,e){let n=new Set;for(let r of t.tables)r.schema&&n.add(r.schema);for(let r of t.views)r.schema&&n.add(r.schema);if(e?.deparseSchema)for(let r of e.deparseSchema.values())r?.schema&&n.add(r.schema);for(let r of e?.internalSchemas??[])n.add(r);return n}function Hm(t){let e=new Set(t.exposedSchemas??["public"]),n=()=>[...e].sort().join(", ");if(t.explicitProfileSchema!==void 0&&!e.has(t.explicitProfileSchema))return T(406,"PGRST106",`Invalid schema: ${t.explicitProfileSchema}`,null,`Only the following schemas are exposed: ${n()}`);let r=t.isRpc?-1:t.relation.indexOf(t.separator);if(r>0){let s=t.relation.slice(0,r);if(t.knownSchemas.has(s)&&!e.has(s)){let i=t.relation.slice(r+t.separator.length);return T(404,"PGRST205",`Could not find the table '${s}.${i}' in the schema cache`,null,null)}}return null}var Tx={swagger:"2.0",info:{description:"",title:"standard public schema",version:"14.1"},basePath:"/",schemes:["https"],consumes:["application/json","application/vnd.pgrst.object+json;nulls=stripped","application/vnd.pgrst.object+json","text/csv"],produces:["application/json","application/vnd.pgrst.object+json;nulls=stripped","application/vnd.pgrst.object+json","text/csv"]},Wm=t=>{let e=async(n,r)=>{let{app:s}=n.var,i=s.connection;if(!s.config.api?.enabled)return n.notFound();let{relation:o,isRpc:a}=r;if(a&&!i.supportsRpc)return T(404,"PGRST202",`Could not find the function public.${o} in the schema cache`,null,null);if(a){let h=n.req.method.toUpperCase();if(!["GET","POST","HEAD","OPTIONS"].includes(h))return T(405,"PGRST101",`Cannot use the ${h} method on RPC`,null,null)}let l=await i.introspect({useCache:true});if(!a&&i.config.introspection?.exclude_tables?.some(h=>Ki(o,h,"sql")))return n.notFound();if(!(kn in n.req.raw)){let h=i.config.translation,y=Bm(h?.schemas?.approach),w=[];s.config.auth?.enabled&&w.push("auth"),s.config.storage?.enabled&&w.push("storage");let S=n.req.method.toUpperCase(),b=n.req.header("Content-Profile"),_=n.req.header("Accept-Profile"),E=S==="OPTIONS"?b??_:["POST","PUT","PATCH","DELETE"].includes(S)?b:_,x=Hm({relation:o,explicitProfileSchema:E,exposedSchemas:s.config.api?.schemas,knownSchemas:qm(l,{deparseSchema:h?.deparse?.schema,internalSchemas:w}),separator:y,isRpc:a});if(x)return x}if(!(kn in n.req.raw)&&n.req.method!=="OPTIONS"){let h=n.var.ignoreAuthorization?void 0:n.req.header("Authorization");if(h||!n.var.apiKeyType){let y=await Hp(h,{jwtSecret:s.config.auth?.jwt_secret,anonymousEnabled:s.config.api?.anonymous_enabled!==false});if(y.kind==="error")return y.response;y.payload&&(n.set("userId",y.payload.sub),n.set("sessionId",y.payload.session_id),n.set("jwt",y.payload));}}if(a&&n.req.method==="OPTIONS"){let h=n.req.header("Content-Profile")??n.req.header("Accept-Profile")??l.default_schema??"public",y=wl(l.functions,{schema:h,fnName:o,method:"OPTIONS",providedNames:[]});if(y)return T(404,"PGRST202",y.message,y.details,y.hint);let w=Bt(l.functions??[],{schema:h,fnName:o,providedNames:[]}),S=w.length>0&&w.every(b=>b.volatility!=="v");return n.header("Allow",S?"OPTIONS,GET,HEAD,POST":"OPTIONS,POST"),n.body(null,200)}if(!a&&n.req.method==="OPTIONS"){let h=n.req.header("Content-Profile")??n.req.header("Accept-Profile")??"public",y=b=>{let _=b||"public";return i.dialect==="sqlite"?_===h||_==="public"||_==="":_===h},w=l.views.find(b=>b.name===o&&y(b.schema)),S=!w&&l.tables.find(b=>b.name===o&&b.type!=="view"&&y(b.schema));if(S||w){let b=new Set(["OPTIONS","GET","HEAD"]);if(S)b.add("POST").add("PUT").add("PATCH").add("DELETE");else {let E=false,x=false,O=false,v=(F,V)=>`${F||"public"}\0${V}`,P=new Set,C=w.schema||"public",R=await i.viewOptionsMetadata(o,C).catch(()=>null);if(R){E=R.canInsert,x=R.canUpdate,O=R.canDelete;for(let F of R.baseTables)P.add(v(F.schema,F.name));}else {let F=l.triggers.filter(he=>he.table===o&&y(he.schema)),V=he=>F.some(Ve=>new RegExp(`instead\\s+of\\s+${he}`,"i").test(Ve.sql));E=V("insert"),x=V("update"),O=V("delete");let be=w?.sql??"";for(let he of l.tables){if(he.type==="view")continue;let Ve=he.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");new RegExp(`\\b${Ve}\\b`,"i").test(be)&&P.add(v(he.schema,he.name));}}let U=new Set(l.columns.filter(F=>F.table===o&&y(F.schema)).map(F=>F.name)),J=l.tables.some(F=>{if(F.type==="view"||!P.has(v(F.schema,F.name)))return false;let V=l.columns.filter(be=>be.table===F.name&&(be.schema||"public")===(F.schema||"public")&&be.is_primary_key);return V.length>0&&V.every(be=>U.has(be.name))});E&&b.add("POST"),x&&b.add("PATCH"),O&&b.add("DELETE"),E&&x&&J&&b.add("PUT");}let _=["OPTIONS","GET","HEAD","POST","PUT","PATCH","DELETE"].filter(E=>b.has(E));return n.header("Allow",_.join(",")),n.body(null,200)}}let{dialect:f}=i,u=i.config.translation?.deparse?.schema,d=Qp(u,l,f),p=n.var.jwt,g={auth:{uid:n.var.userId??null,role:p?.role||"anon",jwt:p??null}},m;try{let h=n.req.header("Content-Profile")??n.req.header("Accept-Profile")??"public",y=new Set(l.columns.filter(C=>{if(C.table!==o)return !1;let R=C.schema||"public";return f==="sqlite"?R===h||R==="public"||R==="":R===h}).map(C=>C.name));m=await Ri(n.req.raw,{basePath:"/rest/v1",parentColumns:y,resolveFilters:(C,R,U)=>Ir(C,R,U,y)}),m=await i.onPostgrestAST(m,g);let w=m.function,S=!1;if(a&&w){let C={schema:m.schema??l.default_schema??"public",fnName:w,method:n.req.method.toUpperCase(),providedNames:fn(m),paramsType:m.paramsType,inputType:m.inputType,rawKind:ap(n.req.header("Content-Type"))},R=wl(l.functions,C);if(R)return T(404,"PGRST202",R.message,R.details,R.hint);let U=op(l.functions,C);if(U)return T(300,"PGRST203",U.message,U.details,U.hint);if(C.method==="OPTIONS"){let J=Gi(l.functions,{schema:C.schema,fnName:C.fnName,providedNames:C.providedNames,paramsType:C.paramsType}),F=J&&J.volatility!=="v"?"OPTIONS,GET,HEAD,POST":"OPTIONS,POST";return new Response(null,{status:200,headers:{Allow:F,"Access-Control-Allow-Origin":"*"}})}S=ao(l.functions,{schema:C.schema,fnName:C.fnName,providedNames:C.providedNames,paramsType:C.paramsType,argCount:Array.isArray(m.args)?m.args.length:void 0,method:C.method,inputType:C.inputType},n.req.header("Accept"))!==null;}t?.debug&&console.log(cc.default.dim("[POSTGREST:AST]"),m);let b=Em({ast:m,dialect:f,introspection:l,apiConfig:s.config.api,acceptHeader:n.req.header("Accept")??"application/json",allowRawMedia:S,preferHeader:n.req.header("Prefer"),httpMethod:n.req.method.toUpperCase(),rangeHeader:n.req.header("Range")});if(b instanceof Response)return b;m=b.ast;let{meta:_,mutationPlan:E,isMutation:x,stripNullsResponse:O,csvResponse:v,planEnabled:P}=b;return await i.withContext(g,async C=>{let R=n.req.header("Accept")??"application/json";if(P&&tm(R)){let Ot=te(m,f,{db:C,introspection:l,schema:u}).compile();return t?.debug&&console.info(cc.default.dim(`[POSTGREST:PLAN] ${Ot.sql}
86
- - ${JSON.stringify([...Ot.parameters])}`)),lm(R,Ot)}let U=x?await Sm(C,m,f,l,E):void 0,J=ps(_,E.appliedResolution),F={ast:m,meta:_,db:C,dialect:f,introspection:l,deparseSchema:u,connection:i,responseSchemaMap:d,mutationPlan:E,mutationCreated:U,prefApplied:J,isMutation:x,stripNullsResponse:O,csvResponse:v,acceptHeader:R,requestUrl:n.req.url,debug:t?.debug},V=await Fm(F);if(V)return V;let be=await $m(F);if(be)return be;let he=await Im(F);if(he)return he;let Ve=await Nm(F);if(Ve)return Ve;let Tn=await jm(F);if(Tn)return Tn;let Ys=await Mm(F);return a&&f==="postgres"?await km(C,Ys):Ys},{forceRollback:t?.forceRollback===!0,rpc:a&&f==="postgres"?{method:n.req.method.toUpperCase(),path:`/rpc/${o}`,readOnly:["GET","HEAD"].includes(n.req.method.toUpperCase()),requestHeaders:Object.fromEntries(n.req.raw.headers)}:void 0})}catch(h){return Cm(h,{connection:i,introspection:l,vars:g,ast:m})}};return new _e().all("/rpc/:function",n=>e(n,{relation:n.req.param("function"),isRpc:true})).all("/:relation",n=>e(n,{relation:n.req.param("relation"),isRpc:false})).use(async(n,r)=>{if(n.req.method==="GET"&&n.req.path.endsWith("/")){if(n.var.apiKeyType==="publishable")return n.json({message:"You cannot consume this service"},403);let{app:s}=n.var,i=n.req.header("Accept-Profile")??n.req.header("Content-Profile")??null;if(i){let o=new Set(s.config.api?.schemas??["public"]);if(o.size>0&&!o.has(i)){let a=[...o].sort().join(", ");return T(406,"PGRST106",`Invalid schema: ${i}`,null,`Only the following schemas are exposed: ${a}`)}}return n.json(Tx)}await r();}).all("*",n=>T(404,"PGRST125","Invalid path specified in request URL",null,null))};var $=class extends Error{constructor(n,r,s,i,o){super(s);this.status=n;this.code=r;this.details=i;this.headers=o;this.name="AuthError";}withInternalError(n){return this.cause=n,this}toJSON(){return {code:this.status,error_code:this.code,msg:this.message,...this.details}}},ct=()=>new $(400,"invalid_credentials","Invalid login credentials"),Km=()=>new $(400,"email_not_confirmed","Email not confirmed"),Jm=(t,e=[],n=["length"])=>{let r=[];return n.includes("length")&&r.push(`Password should be at least ${t} characters.`),n.includes("characters")&&r.push(`Password should contain at least one character of each: ${e.join(", ")}.`),new $(422,"weak_password",r.join(" "),{weak_password:{reasons:n}})},Gm=(t="Access token is required")=>new $(401,"no_authorization",t),hn=()=>new $(401,"no_authorization","This endpoint requires a valid Bearer token"),ms=t=>new $(403,"bad_jwt",t),uc=()=>ms("invalid JWT: unable to parse or verify signature, token is malformed: token contains an invalid number of segments"),fc=t=>ms(`invalid JWT: unable to parse or verify signature, token is malformed: could not JSON decode header: ${t}`),zm=()=>ms("invalid JWT: unable to parse or verify signature, token signature is invalid: signature is invalid"),Vm=()=>ms("invalid JWT: unable to parse or verify signature, token has invalid claims: token is expired"),dc=()=>ms("invalid claim: missing sub claim"),pc=()=>new $(400,"bad_jwt","invalid claim: sub claim must be a UUID");var Qm=()=>new $(403,"user_not_found","User from sub claim in JWT does not exist"),Ym=()=>new $(403,"session_not_found","Session from session_id claim in JWT does not exist"),Xm=()=>new $(422,"user_already_exists","User already registered"),Zm=()=>new $(422,"email_exists","A user with this email address has already been registered"),co=()=>new $(422,"signup_disabled","Signups not allowed for this instance"),eh=()=>new $(400,"email_provider_disabled","Email signups are disabled"),th=()=>new $(422,"otp_disabled","Signups not allowed for otp"),nh=()=>new $(422,"same_password","New password should be different from the old password."),gn=()=>new $(403,"otp_expired","Email link is invalid or has expired"),H=(t,e=422)=>new $(e,"validation_failed",t);var hs=t=>new $(400,"bad_json",t),mc=()=>new $(400,"validation_failed","Refresh token is not valid"),Gn=()=>new $(400,"refresh_token_not_found","Invalid Refresh Token: Refresh Token Not Found"),uo=(t,e)=>new $(400,"refresh_token_already_used","Invalid Refresh Token: Already Used",void 0,{...t?{"Sb-Auth-Session-Id":t}:{},...e?{"Sb-Auth-User-Id":e}:{}}),rh=()=>new $(401,"session_not_found","Invalid Refresh Token: Already Used"),hc=(t,e,n)=>new $(400,"session_expired",t==="inactivity"?"Invalid Refresh Token: Session Expired (Inactivity)":"Invalid Refresh Token: Session Expired",void 0,{...e?{"Sb-Auth-Session-Id":e}:{},...n?{"Sb-Auth-User-Id":n}:{}}),sh=()=>new $(422,"anonymous_provider_disabled","Anonymous sign-ins are disabled"),ih=()=>new $(400,"invalid_credentials","unsupported_grant_type"),fo=()=>new $(429,"over_email_send_rate_limit","For security purposes, you can only request this after 59 seconds."),po=t=>new $(400,"bad_oauth_state",t),gc=t=>new $(400,"bad_oauth_callback",t);var mo=(t="invalid flow state, no valid flow state found")=>new $(404,"flow_state_not_found",t),oh=()=>new $(422,"flow_state_expired","invalid flow state, flow state has expired"),ho=()=>new $(400,"flow_state_already_used","State has already been used"),ah=t=>new $(400,"bad_code_verifier",t),lh=t=>new $(422,"provider_email_needs_verification",t),ch=()=>new $(403,"user_banned","User is banned"),uh=()=>new $(404,"user_not_found","User identified by token not found"),fh=()=>new $(404,"invite_not_found","Invite not found"),gs=t=>new $(500,"unexpected_failure",t),dh=t=>gs(`Unable to exchange external code: ${t.slice(0,4)}`),ph=()=>gs("Error getting user profile from external provider");async function bc(t,e,n){let r=new TextEncoder().encode(e),s=Math.floor(Date.now()/1e3);return new SignJWT({...t,iat:s}).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt(s).setExpirationTime(s+n).sign(r)}async function mh(t,e){let n=t.split(".");if(n.length!==3||n.some(i=>i===""))throw uc();let r=kx(n[0]);if(r)throw r;let s=new TextEncoder().encode(e);try{let{payload:i}=await jwtVerify(t,s,{algorithms:["HS256"]});return i}catch(i){throw i instanceof errors.JWTExpired?Vm():i instanceof errors.JWSSignatureVerificationFailed?zm():i instanceof errors.JWSInvalid||i instanceof errors.JWTInvalid?uc():i}}function kx(t){let e=vx(t);if(!e)return fc("unexpected end of JSON input");let n=Ax(e);try{return JSON.parse(new TextDecoder("utf-8").decode(e)),null}catch{return fc(wc(n))}}function vx(t){try{let e=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),n=atob(e),r=new Uint8Array(n.length);for(let s=0;s<n.length;s++)r[s]=n.charCodeAt(s);return r}catch{return null}}function Ax(t){let e="";for(let n of t)e+=String.fromCharCode(n);return e}var Ox={n:"null",t:"true",f:"false"};function wc(t){let e=0;for(;e<t.length;){let i=t.charCodeAt(e);if(i===32||i===9||i===10||i===13)e++;else break}let n=t.slice(e);if(!n)return "unexpected end of JSON input";let r=n[0],s=Ox[r];if(s){for(let i=1;i<s.length;i++){if(i>=n.length)return "unexpected end of JSON input";if(n[i]!==s[i])return `invalid character ${yc(n[i])} in literal ${s} (expecting '${s[i]}')`}return `invalid character ${yc(n[s.length]??" ")} after top-level value`}return r==="{"||r==="["||r==='"'||r==="-"||r>="0"&&r<="9"?"":`invalid character ${yc(r)} looking for beginning of value`}function yc(t){let e=t.codePointAt(0)??0;return e>=32&&e<127?`'${t}'`:`'\\u${e.toString(16).padStart(4,"0")}'`}var Px=10,$x=4,Ix=4,Nx=31;function Dx(t=process.env){let e=t.LITE_AUTH_BCRYPT_COST;if(e!==void 0&&e.trim()!==""){let n=Number(e);if(Number.isFinite(n))return Math.min(Nx,Math.max(Ix,Math.trunc(n)))}return t.RUN_SPEC==="1"?$x:Px}async function ys(t){return hh.hash(t,Dx())}async function Sc(t,e){return hh.compare(t,e)}function gh(t,e=6,n=[]){let r=[];return t.length<e&&r.push("length"),n.length>0&&n.some(s=>!jx(t,s))&&r.push("characters"),r}function jx(t,e){for(let n of t)if(e.includes(n))return true;return false}function ut(t=6){let e=crypto.getRandomValues(new Uint8Array(t)),n="";for(let r=0;r<t;r++)n+=(e[r]%10).toString();return n}function _c(){let t=crypto.getRandomValues(new Uint8Array(32));return bh(t)}async function tt(t,e){let n=new TextEncoder().encode(t.toLowerCase()+e),r=await crypto.subtle.digest("SHA-256",n);return bh(new Uint8Array(r))}function bh(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}function Ec(){return v7()}function ue(){return v7()}var Lx=["iss","sub","aud","iat","exp","name","family_name","given_name","middle_name","nickname","preferred_username","profile","picture","website","gender","birthdate","zoneinfo","locale","updated_at","email","phone","custom_claims","full_name","avatar_url","slug","provider_id","user_name"];function Fx(t){return !!(t==null||t===""||typeof t=="number"&&t===0||Array.isArray(t)&&t.length===0||typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0)}function wh(t){let e={};for(let n of Lx){let r=t[n];Fx(r)||(e[n]=r);}return e.email_verified=t.email_verified??false,e.phone_verified=t.phone_verified??false,e}var Sh=43,_h=128,Ux="PKCE flow requires code_challenge_method and code_challenge",Mx=/^[a-zA-Z._~0-9-]+$/;function Bx(t){let e=t.length;if(e<Sh||e>_h)throw H(`code challenge has to be between ${Sh} and ${_h} characters`,400);if(!Mx.test(t))throw H("code challenge can only contain alphanumeric characters, hyphens, periods, underscores and tildes",400);return true}function xc(t){return t.toLowerCase()}var qx=new Set(["s256","plain"]);function Eh(t,e){if(e===""!=(t===""))throw H(Ux,400);if(e!==""&&(Bx(e),!qx.has(xc(t))))throw H("Invalid code_challenge_method",400)}function Hx(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function Wx(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Hx(new Uint8Array(n))}async function xh(t,e,n){return e.toLowerCase()==="s256"?await Wx(n)===t:n===t}var Kx="github.com",Th="api.github.com",Jx=["user:email"];function Gx(t){let e=t?t.split(","):[];return [...Jx,...e].join(" ")}function Tc(t,e){let n=JSON.parse(e);if(typeof n.error=="string"&&n.error!=="")throw new Error(`${t}: token endpoint returned error ${n.error}`,{cause:e});if(!n.access_token)throw new Error(`${t}: server response missing access_token`,{cause:e});return n}function Rh(t,e){return t?t.endsWith("/")?t.slice(0,-1):t:`https://${e}`}function zx(t){let e=Rh(t,Kx),n=Rh(t,Th);return n.endsWith(Th)||(n+="/api/v3"),{authHost:e,apiHost:n}}function Ch(t){let{authHost:e,apiHost:n}=zx(t);return {id:"github",authorizeUrl({clientId:r,redirectUri:s,scopes:i,state:o,extraParams:a}){let l=new URLSearchParams({client_id:r,redirect_uri:s,scope:Gx(i),state:o,...a});return `${e}/login/oauth/authorize?${l.toString()}`},async exchangeCode(r,{clientId:s,secret:i,redirectUri:o,fetch:a=globalThis.fetch}){let l=new URLSearchParams({client_id:s,client_secret:i,code:r,redirect_uri:o}),c=await a(`${e}/login/oauth/access_token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:l.toString(),signal:AbortSignal.timeout(1e4)}),f=await c.text();if(c.status<200||c.status>=300)throw new Error(`github: token endpoint returned ${c.status}`,{cause:f});return Tc("github",f)},async getUserData(r,{fetch:s=globalThis.fetch}){let i={Authorization:`Bearer ${r.access_token}`},o=()=>({headers:i,signal:AbortSignal.timeout(1e4)}),a=await s(`${n}/user`,o()),l=await a.text();if(a.status<200||a.status>=300)throw new Error(`github: /user returned ${a.status}`,{cause:l});let c=JSON.parse(l),f=await s(`${n}/user/emails`,o()),u=await f.text();if(f.status<200||f.status>=300)throw new Error(`github: /user/emails returned ${f.status}`,{cause:u});let d=JSON.parse(u);if(!Array.isArray(d))throw new Error("github: /user/emails did not return a JSON array");let p=String(c.id);return {claims:{iss:n,sub:p,name:c.name||void 0,preferred_username:c.login,avatar_url:c.avatar_url||void 0,full_name:c.name||void 0,provider_id:p,user_name:c.login,email_verified:false,phone_verified:false},emails:d.filter(g=>g.email).map(g=>({email:g.email,verified:g.verified,primary:g.primary}))}}}}var Rc="https://accounts.google.com",Xx="accounts.google.com",Zx="https://accounts.google.com/o/oauth2/v2/auth",eT="https://oauth2.googleapis.com/token",tT="https://www.googleapis.com/oauth2/v3/certs",nT="https://www.googleapis.com/userinfo/v2/me",rT=["email","profile"],kc=1e4,kh=new Map;function vh(t,e){return createRemoteJWKSet(new URL(t),{[customFetch]:e,timeoutDuration:kc})}function sT(t,e){if(e!==globalThis.fetch)return vh(t,e);let n=kh.get(t);return n||(n=vh(t,e),kh.set(t,n)),n}async function iT(t,e){let n=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)),r=new Uint8Array(n).slice(0,n.byteLength/2),s="";for(let o of r)s+=String.fromCharCode(o);return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")===e}function oT(t){let e=t?t.split(","):[];return [...rT,...e].join(" ")}function Cc(t){return !!(t.verified_email||t.email_verified)}function Ah(t={}){let e=t.issuer??Rc,n=e===Rc?[Rc,Xx]:e,r=t.userInfoEndpoint??nT,s=t.getKey,i=t.clientIds??[];return {id:"google",authorizeUrl({clientId:o,redirectUri:a,scopes:l,state:c,extraParams:f}){let u=new URLSearchParams({client_id:o,redirect_uri:a,response_type:"code",scope:oT(l),state:c,...f});return `${Zx}?${u.toString()}`},async exchangeCode(o,{clientId:a,secret:l,redirectUri:c,fetch:f=globalThis.fetch}){let u=new URLSearchParams({client_id:a,client_secret:l,code:o,redirect_uri:c,grant_type:"authorization_code"}),d=await f(eT,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:u.toString(),signal:AbortSignal.timeout(kc)}),p=await d.text();if(d.status<200||d.status>=300)throw new Error(`google: token endpoint returned ${d.status}`,{cause:p});return Tc("google",p)},async getUserData(o,{fetch:a=globalThis.fetch,clientId:l}){if(o.id_token){let d=s??sT(tT,a),p=i[0]??l??void 0,{payload:g}=await jwtVerify(o.id_token,d,{issuer:n,...p?{audience:p}:{}}),m=g;if(m.at_hash){if(!o.access_token)throw new Error("oidc: id_token had at_hash but no access_token was returned");if(!await iT(o.access_token,m.at_hash))throw new Error("oidc: access token hash does not match value in ID token")}let h=m.email||"",y=Cc(m),w={};return m.hd&&(w.hd=m.hd),{emails:h?[{email:h,verified:y,primary:true}]:[],claims:{iss:m.iss,sub:m.sub,name:m.name,picture:m.picture,avatar_url:m.picture,full_name:m.name,provider_id:m.sub,custom_claims:Object.keys(w).length?w:void 0,email_verified:false,phone_verified:false}}}let c=await a(r,{headers:{Authorization:`Bearer ${o.access_token}`},signal:AbortSignal.timeout(kc)}),f=await c.text();if(c.status<200||c.status>=300)throw new Error(`google: userinfo returned ${c.status}`,{cause:f});let u=JSON.parse(f);return {emails:u.email?[{email:u.email,verified:Cc(u),primary:true}]:[],claims:{iss:r,sub:u.id,name:u.name,picture:u.picture,email:u.email,email_verified:Cc(u),avatar_url:u.picture,full_name:u.name,provider_id:u.id,phone_verified:false}}}}}function Oh(t){return (t??"").split(",").map(e=>e.trim()).filter(e=>e!=="")}var Ph={github:t=>Ch(t.url),google:t=>Ah({clientIds:Oh(t.client_id)})},$h=new Set(Object.keys(Ph)),vc=["apple","azure","bitbucket","discord","facebook","github","gitlab","google","kakao","keycloak","linkedin","notion","twitch","twitter","slack","spotify","workos","zoom"],Ac=["snapchat","figma","fly","linkedin_oidc","slack_oidc"],aT=new Set([...vc,...Ac]);function Oc(t,e,n){let r=(t??"").toLowerCase();if(!aT.has(r))throw H(`Unsupported provider: Provider ${r} could not be found`,400);let s=e?.[r];if(!s?.enabled)throw H("Unsupported provider: provider is not enabled",400);let i=Oh(s.client_id);if(i.length===0)throw H("Unsupported provider: missing OAuth client ID",400);if(!s.secret)throw H("Unsupported provider: missing OAuth secret",400);let o=Ph[r];if(!o)throw H(`Unsupported provider: provider ${r} is not yet implemented`,400);let a=o(s);return {name:r,provider:a,config:s,clientId:i[0],clientIds:i,secret:s.secret,redirectUri:s.redirect_uri||n.defaultRedirectUri,skipNonceCheck:s.skip_nonce_check??false,emailOptional:s.email_optional??false}}var Ih=3e5,lT=1440*60*1e3;function yo(t){if(!t.jwt_secret)throw new Error('[auth] is enabled but `auth.jwt_secret` is empty. Add `jwt_secret = "<secret>"` under [auth] in your config.toml.')}function cT(t){return t==="localhost"||t==="127.0.0.1"||t==="::1"}function uT(t){let e="^";for(let n=0;n<t.length;n++){let r=t[n];if(r==="\\"){let s=t[++n];s!==void 0?e+=s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):e+="\\\\";}else if(r==="*")t[n+1]==="*"?(e+=".*",n++):e+="[^./]*";else if(r==="?")e+="[^./]";else if(r==="["){let s=t.indexOf("]",n+1);if(s===-1)e+="\\[";else {let i=t.slice(n+1,s);i.startsWith("!")&&(i=`^${i.slice(1)}`),e+=`[${i}]`,n=s;}}else e+=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");}return new RegExp(`${e}$`)}function Nh(t,e){let n=t.indexOf("//");if(n===-1)return e;let r=t.slice(n+2),s=r.search(/[/?#]/);s!==-1&&(r=r.slice(0,s));let i=r.lastIndexOf("@");if(i!==-1&&(r=r.slice(i+1)),r.startsWith("[")){let a=r.indexOf("]");return a===-1?r.slice(1):r.slice(1,a)}let o=r.lastIndexOf(":");return o===-1?r:r.slice(0,o)}function fT(t){let e=t,n=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(e);if(n){let r=n.slice(1).map(Number);return r.some(s=>s>255)?{isIp:false,isLoopback:false}:{isIp:true,isLoopback:r[0]===127}}return e.includes(":")?{isIp:true,isLoopback:e.toLowerCase()==="::1"}:{isIp:false,isLoopback:false}}var dT=/^[0-9]+$/,pT=/^[a-zA-Z0-9]([a-zA-Z0-9.-]*[a-zA-Z0-9])?$/;function Pc(t,e,n){if(t==="")return false;let r;try{r=new URL(t);}catch{return false}let s=r.protocol.replace(/:$/,"").toLowerCase(),i=s==="http"||s==="https",o=Nh(t,r.hostname);try{let c=new URL(e);if(c.protocol===r.protocol&&Nh(e,c.hostname)===o&&(c.port===r.port||cT(o)))return !0}catch{}let a=fT(o);if(dT.test(o))return false;if(a.isIp)return a.isLoopback;if(i&&!pT.test(o))return false;let l=t.split("#")[0];for(let c of n)if(uT(c).test(l))return true;return false}var bs=class t{constructor(e,n,r){this.repo=e;this.config=n;this.mailer=r;yo(n),this.jwtExpiry=n.jwt_expiry??3600,this.minPasswordLength=n.minimum_password_length??6,this.passwordRequiredCharacters=n.password_required_characters??hT(n.password_requirements),this.sessionTimeboxSeconds=Lh(n.sessions?.timebox),this.sessionInactivitySeconds=Lh(n.sessions?.inactivity_timeout);}jwtExpiry;minPasswordLength;passwordRequiredCharacters;sessionTimeboxSeconds;sessionInactivitySeconds;get otpLength(){return this.config.email?.otp_length??6}get otpExpirySeconds(){return this.config.email?.otp_expiry??3600}resolveEmailRedirect(e){let n=this.config.site_url??"http://localhost:3000";return e&&Pc(e,n,this.config.additional_redirect_urls??[])?e:n}async signUp(e,n,r){if(this.config.enable_signup===false)throw co();if(!e)throw sh();if(this.config.email?.enable_signup===false)throw eh();if(n==null||n===void 0||n==="")throw H("Signup requires a valid password",400);if(!zn(e))throw H("Unable to validate email address: invalid format",400);if(n.length>72)throw H("Password cannot be longer than 72 characters",400);this.assertPasswordStrong(n);let i=!(this.config.email?.enable_confirmations??this.config.enable_confirmations??false);e=e.toLowerCase();let o=await this.repo.findUserByEmail(e);if(o)throw i?(await this.createAuditLog(o.id,e,"user_repeated_signup","user"),Xm()):fo();let a=ue(),l=await ys(n),c=new Date().toISOString(),f=null,u=null,d=null;i||(f=ut(this.otpLength),u=await tt(e,f),d=c);let p={...r??{},email:e,email_verified:i,phone_verified:false,sub:a},g={...r??{},email:e,email_verified:false,phone_verified:false,sub:a},m=await this.repo.createUser({id:a,email:e,encrypted_password:l,confirmed_at:i?c:null,raw_user_meta_data:p,raw_app_meta_data:{provider:"email",providers:["email"]},confirmation_token:u,confirmation_sent_at:d});await this.repo.createIdentity({id:ue(),provider:"email",provider_id:a,user_id:a,identity_data:g}),!i&&f&&u&&await this.mailer.sendConfirmation(e,u,f,{userId:a,redirectTo:this.config.site_url});let h=await this.repo.findIdentitiesByUserId(a),y=this.repo.parseUserJson(m),w=this.mapUserToResponse(y,h,"signup");if(i){let S=await this.createSessionForUser(y,h);return await this.createAuditLog(a,e,"user_signedup","team"),{user:w,session:S}}return await this.createAuditLog(a,e,"user_confirmation_requested","user"),{user:w}}async signInWithPassword(e,n){if(!e)throw H("missing email or phone",400);if(!n)throw ct();let r=await this.repo.findUserByEmail(e.toLowerCase());if(!r||!r.encrypted_password)throw ct();let s=this.repo.parseUserJson(r);if(!s.confirmed_at)throw Km();if(!await Sc(n,s.encrypted_password))throw ct();let o=await this.repo.findIdentitiesByUserId(r.id);return this.createSessionForUser(s,o,"user")}async refreshSession(e){if(!e)throw mc();let n=await this.repo.findRefreshToken(e);if(!n)throw Fh(e)?Gn():mc();if(Uh(n))return this.refreshWithRevokedToken(n);let r=await this.repo.findUserById(n.user_id);if(!r)throw Gn();let s=null;if(n.session_id){if(s=await this.repo.findSessionById(n.session_id),!s)throw Gn();this.assertSessionRefreshable(s);}let i=$c(s?.updated_at,s?.refreshed_at,r.updated_at,r.last_sign_in_at);await this.repo.revokeRefreshToken(n.id);let o=Ec(),a=n.session_id??ue();return n.session_id?await this.repo.updateSessionRefreshedAt(n.session_id,i):await this.repo.createSession({id:a,user_id:r.id}),await this.repo.createRefreshToken({token:o,user_id:r.id,session_id:a,parent:n.token}),await this.createAuditLog(r.id,r.email??"","token_refreshed","token",false),await this.createAuditLog(r.id,r.email??"","token_revoked","token",false),this.createRefreshResponse(r,a,o,i)}async refreshWithRevokedToken(e){if(this.config.sessions?.single_per_user)throw rh();if(!e.session_id)throw uo(e.session_id,e.user_id);let n=await this.repo.findRefreshTokensBySession(e.session_id),r=gT(n,e.token),s=r.filter(c=>!Uh(c));if((this.config.enable_refresh_token_rotation??false)&&r.length>1)throw await this.repo.revokeRefreshTokensByIds(s.map(c=>c.id)),uo(e.session_id,e.user_id);let i=s.at(-1);if(!i)throw uo(e.session_id,e.user_id);let o=await this.repo.findUserById(e.user_id);if(!o)throw Gn();let a=await this.repo.findSessionById(e.session_id);if(!a)throw Gn();this.assertSessionRefreshable(a);let l=$c(a.updated_at,a.refreshed_at,o.updated_at,o.last_sign_in_at);return await this.repo.updateSessionRefreshedAt(e.session_id,l),await this.createAuditLog(o.id,o.email??"","token_refreshed","token",false),this.createRefreshResponse(o,e.session_id,i.token,l)}async createRefreshResponse(e,n,r,s){let i=await this.repo.updateUser(e.id,{last_sign_in_at:s}),o=this.repo.parseUserJson(i??e),a=await this.repo.findIdentitiesByUserId(e.id),l=await bc({sub:e.id,aud:e.aud||"authenticated",role:e.role||"authenticated",email:e.email??void 0,session_id:n},this.config.jwt_secret,this.jwtExpiry),c=Math.floor(Date.now()/1e3);return Mh({access_token:l,refresh_token:r,token_type:"bearer",expires_in:this.jwtExpiry,expires_at:c+this.jwtExpiry,user:this.mapUserToResponse(o,a,"user")},n,e.id)}assertSessionRefreshable(e){let n=Date.now();if(this.sessionTimeboxSeconds!==void 0&&n-Date.parse(e.created_at)>this.sessionTimeboxSeconds*1e3)throw hc(void 0,e.id,e.user_id);let r=e.refreshed_at??e.created_at;if(this.sessionInactivitySeconds!==void 0&&n-Date.parse(r)>this.sessionInactivitySeconds*1e3)throw hc("inactivity",e.id,e.user_id)}async getUser(e){let n=await this.repo.findUserById(e);if(!n)throw ct();let r=this.repo.parseUserJson(n),s=await this.repo.findIdentitiesByUserId(e);return this.mapUserToResponse(r,s,"user")}async updateUser(e,n){let r=await this.repo.findUserById(e);if(!r)throw ct();let s=this.repo.parseUserJson(r),i={},o=false,a=false,l=n.data!==void 0||n.password!==void 0||n.email!==void 0;if(n.data!==void 0){let u=typeof s.raw_user_meta_data=="object"?s.raw_user_meta_data:{};i.raw_user_meta_data=jh(u,n.data??{}),o=true;}if(n.password!==void 0){if(this.assertPasswordStrong(n.password),s.encrypted_password&&await Sc(n.password,s.encrypted_password))throw nh();i.encrypted_password=await ys(n.password),i.recovery_token=null,i.recovery_sent_at=null,o=true,a=true;}if(n.email!==void 0)if(n.email==="")o=true;else {let u=n.email.toLowerCase();if(!zn(u))throw H("Unable to validate email address: invalid format",400);if(o=true,u!==s.email?.toLowerCase()){let d=await this.repo.findUserByEmail(u);if(d&&d.id!==e)throw Zm();let p=new Date().toISOString(),g=s.email??"",m=ut(this.otpLength),h=await tt(u,m),y=(this.config.email?.double_confirm_changes??true)&&g!=="",w=ut(this.otpLength),S=y?await tt(g,w):null;i.email_change=u,i.email_change_token_current=S,i.email_change_token_new=h,i.email_change_sent_at=p,y&&S?await this.mailer.sendEmailChange(g,S,w,{userId:e,tokenNew:m,tokenHashNew:h,redirectTo:this.config.site_url,currentEmail:g,newEmail:u}):await this.mailer.sendEmailChange(u,h,m,{userId:e,redirectTo:this.config.site_url,currentEmail:g,newEmail:u});}}l||(o=true);let c=s;if(Object.keys(i).length>0){let u=await this.repo.updateUser(e,i);if(!u)throw ct();c=this.repo.parseUserJson(u);}a&&await this.createAuditLog(e,s.email??"","user_updated_password","user",false),o&&await this.createAuditLog(e,s.email??"","user_modified","user",false);let f=await this.repo.findIdentitiesByUserId(e);return this.mapUserToResponse(c,f,"user")}async signOut(e,n,r){let s=n??"local";if(!["global","local","others"].includes(s))throw H(`Unsupported logout scope "${s}"`,400);let i=await this.repo.findUserById(r);if(!i)throw ct();let o=this.repo.parseUserJson(i);s==="global"?(await this.repo.deleteRefreshTokensForUser(r),await this.repo.deleteUserSessions(r)):s==="others"&&e?(await this.repo.deleteRefreshTokensForUser(r,e),await this.repo.deleteUserSessions(r,e)):e&&(await this.repo.deleteRefreshTokensForSession(e),await this.repo.deleteSession(e)),await this.createAuditLog(r,o.email??"","logout","account",false);}async signInWithOtp(e,n){if(!e)throw H("One of email or phone must be set",400);if(e=e.toLowerCase(),!zn(e))throw H("Unable to validate email address: invalid format",400);let r=await this.repo.findUserByEmail(e),s=!r;if(!r&&n?.shouldCreateUser!==false){let l=ue(),c=await ys(_c()),f=new Date().toISOString();r=await this.repo.createUser({id:l,email:e,encrypted_password:c,confirmed_at:f,raw_app_meta_data:{provider:"email",providers:["email"]},raw_user_meta_data:{email:e,email_verified:true,phone_verified:false,sub:l}}),await this.repo.createIdentity({id:ue(),provider:"email",provider_id:l,user_id:l,identity_data:{email:e,email_verified:false,phone_verified:false,sub:l}});}if(!r)throw th();let i=ut(this.otpLength),o=await tt(e,i),a=new Date().toISOString();if(await this.repo.updateUser(r.id,{recovery_token:o,recovery_sent_at:a}),await this.createAuditLog(r.id,e,"user_recovery_requested","user",false),await this.mailer.sendMagicLink(e,o,i,{userId:r.id,redirectTo:this.config.site_url}),s){let l=await this.repo.findUserById(r.id);if(!l)throw ct();let c=this.repo.parseUserJson(l),f=await this.repo.findIdentitiesByUserId(r.id);await this.createSessionForUser(c,f),await this.createAuditLog(r.id,e,"user_signedup","team");}}async requestMagicLink(e,n){if(!e)throw H("Password recovery requires an email",422);if(e=e.toLowerCase(),!zn(e))throw H("Unable to validate email address: invalid format",400);let r=await this.repo.findUserByEmail(e),s=!r;if(!r){if(this.config.enable_signup===false)throw co();let l=ue(),c=await ys(_c()),f=new Date().toISOString();r=await this.repo.createUser({id:l,email:e,encrypted_password:c,confirmed_at:f,raw_app_meta_data:{provider:"email",providers:["email"]},raw_user_meta_data:{email:e,email_verified:true,phone_verified:false,sub:l}}),await this.repo.createIdentity({id:ue(),provider:l,provider_id:l,user_id:l,identity_data:{email:e,email_verified:false,phone_verified:false,sub:l}});}let i=ut(this.otpLength),o=await tt(e,i),a=new Date().toISOString();if(await this.repo.updateUser(r.id,{recovery_token:o,recovery_sent_at:a}),await this.createAuditLog(r.id,e,"user_recovery_requested","user",false),await this.mailer.sendMagicLink(e,o,i,{userId:r.id,redirectTo:this.config.site_url}),s){let l=await this.repo.findUserById(r.id);if(!l)throw ct();let c=this.repo.parseUserJson(l),f=await this.repo.findIdentitiesByUserId(r.id);await this.createSessionForUser(c,f),await this.createAuditLog(r.id,e,"user_signedup","team");}}async verifyOtp(e){let n;if(e.token_hash)n=e.token_hash;else if(e.email&&e.token)n=await tt(e.email.toLowerCase(),e.token);else throw gn();return await this.repo.transaction(async r=>{let s=this.repo;this.repo=r;try{let i=await this.findUserByTokenAndType(n,e.type),o=i?.user??null,a=i?.tokenColumn??null;if(!o||!a)throw gn();if(this.isTokenExpired(o,a))throw gn();if(e.type==="email_change"){let c=(this.config.email?.double_confirm_changes??!0)&&!!o.email?"email_change_token_current":"email_change_token_new";if(a!==c)throw gn()}if(!await this.repo.claimUserToken(o.id,a,n))throw gn();return await this.completeVerifyOtp(o,a,e.type)}finally{this.repo=s;}})}async completeVerifyOtp(e,n,r){let s=this.repo.parseUserJson(e),i=new Date().toISOString(),o={};if(s.confirmed_at||(o.confirmed_at=i),r==="email_change"&&s.email_change){o.email=s.email_change,o.email_change=null,o.email_change_token_current=null,o.email_change_token_new=null;let f=(await this.repo.findIdentitiesByUserId(e.id)).find(u=>u.provider==="email");if(f){let u=typeof f.identity_data=="string"?JSON.parse(f.identity_data):{...f.identity_data??{}};await this.repo.updateIdentity(f.id,{identity_data:{...u,email:s.email_change,email_verified:true}});}else await this.repo.createIdentity({id:ue(),provider:"email",provider_id:e.id,user_id:e.id,identity_data:{sub:e.id,email:s.email_change,email_verified:true,phone_verified:false}});o.raw_app_meta_data=await this.buildAppMetaDataProviders(e.id,s.raw_app_meta_data),await this.createAuditLog(e.id,s.email??"","user_modified","user",false);}else if(r==="signup"){let c=typeof s.raw_user_meta_data=="object"?s.raw_user_meta_data:{};o.raw_user_meta_data={...c,email_verified:true};let f=await this.repo.findIdentitiesByUserId(e.id);for(let u of f){let d=typeof u.identity_data=="string"?JSON.parse(u.identity_data):{...u.identity_data??{}};await this.repo.updateIdentity(u.id,{identity_data:{...d,email_verified:true}});}n&&(o[n]=null);}else n&&(o[n]=null);o.last_sign_in_at=i,await this.repo.updateUser(e.id,o);let a=await this.repo.findUserById(e.id);if(!a)throw gn();let l=await this.repo.findIdentitiesByUserId(e.id);return r==="signup"&&await this.createAuditLog(e.id,a.email??"","user_signedup","team"),this.createSessionForUser(this.repo.parseUserJson(a),l,"verify",{createLoginAudit:["magiclink","recovery"].includes(r),includeLoginProviderTrait:!["magiclink","recovery"].includes(r),authenticationMethod:["email_change","magiclink","recovery","signup"].includes(r)?"otp":"password"})}async recover(e){if(!e)throw H("Password recovery requires an email",400);if(e=e.toLowerCase(),!zn(e))throw H("Unable to validate email address: invalid format",400);let n=await this.repo.findUserByEmail(e);if(!n)return;let r=ut(this.otpLength),s=await tt(e,r),i=new Date().toISOString();await this.repo.updateUser(n.id,{recovery_token:s,recovery_sent_at:i}),await this.createAuditLog(n.id,e,"user_recovery_requested","user",false),await this.mailer.sendRecovery(e,s,r,{userId:n.id,redirectTo:this.config.site_url});}async resend(e,n){if(!["signup","email_change","sms","phone_change"].includes(e))throw H("Missing one of these types: signup, email_change, sms, phone_change",400);if((e==="signup"||e==="email_change")&&!n)throw H("Type provided requires an email address",400);if(!n)return;if(n=n.toLowerCase(),!zn(n))throw H("Unable to validate email address: invalid format",400);let r=await this.repo.findUserByEmail(n);if(!r)return;let s=ut(this.otpLength),i=new Date().toISOString();if(e==="signup"){if(r.confirmed_at||!r.confirmation_sent_at)return;throw fo()}else if(e==="email_change"){if(!r.email_change)return;if(r.email_change_sent_at)throw fo();let o=await tt(r.email_change,s);await this.repo.updateUser(r.id,{email_change_token_new:o,email_change_sent_at:i}),await this.mailer.sendEmailChange(r.email_change,o,s,{userId:r.id,redirectTo:this.config.site_url,currentEmail:r.email??void 0,newEmail:r.email_change});}}async reauthenticate(e){let n=await this.repo.findUserById(e);if(!n)throw Gm();if(!n.email)throw H("Reauthentication requires the user to have an email or a phone number",400);let r=ut(this.otpLength),s=await tt(n.email,r),i=new Date().toISOString();await this.repo.updateUser(n.id,{reauthentication_token:s,reauthentication_sent_at:i}),await this.mailer.sendReauthentication(n.email,r,{userId:n.id,tokenHash:s,redirectTo:this.config.site_url}),await this.createAuditLog(n.id,n.email??"","user_reauthenticate_requested","",false);}async createSessionForUser(e,n,r="session",s={}){let i=$c(e.last_sign_in_at,e.updated_at),o=await this.repo.updateUser(e.id,{last_sign_in_at:i}),a=o?this.repo.parseUserJson(o):e;this.config.sessions?.single_per_user&&await this.repo.revokeUserRefreshTokens(e.id);let l=ue();await this.repo.createSession({id:l,user_id:e.id});let c=Ec();await this.repo.createRefreshToken({token:c,user_id:e.id,session_id:l}),(s.createLoginAudit??true)&&await this.createAuditLog(e.id,e.email??"","login","account",s.includeLoginProviderTrait??true,s.provider??"email",s.providerTraitKey??"provider");let f=await bc({sub:e.id,aud:e.aud||"authenticated",role:e.role||"authenticated",email:e.email??void 0,session_id:l},this.config.jwt_secret,this.jwtExpiry),u=Math.floor(Date.now()/1e3);return Mh({access_token:f,refresh_token:c,token_type:"bearer",expires_in:this.jwtExpiry,expires_at:u+this.jwtExpiry,user:this.mapUserToResponse(a,n,r)},l,e.id)}assertPasswordStrong(e){let n=gh(e,this.minPasswordLength,this.passwordRequiredCharacters);if(n.length>0)throw Jm(this.minPasswordLength,this.passwordRequiredCharacters,n)}mapUserToResponse(e,n,r){let s=typeof e.raw_app_meta_data=="string"?JSON.parse(e.raw_app_meta_data):e.raw_app_meta_data??{},i=typeof e.raw_user_meta_data=="string"?JSON.parse(e.raw_user_meta_data):e.raw_user_meta_data??{},o={id:e.id,aud:e.aud||"authenticated",role:e.role||"authenticated",email:e.email??"",phone:e.phone??"",app_metadata:s,user_metadata:i,identities:n.map(a=>this.mapIdentityToResponse(a,r,e)),created_at:e.created_at,updated_at:e.updated_at,is_anonymous:false};return e.confirmed_at&&(o.email_confirmed_at=e.confirmed_at,(r==="user"||r==="verify")&&(o.confirmed_at=e.confirmed_at)),e.last_sign_in_at&&(o.last_sign_in_at=e.last_sign_in_at),e.confirmation_sent_at&&(o.confirmation_sent_at=e.confirmation_sent_at),e.email_change&&(o.new_email=e.email_change),e.email_change_sent_at&&(o.email_change_sent_at=e.email_change_sent_at),r==="verify"&&e.recovery_sent_at&&(o.recovery_sent_at=e.recovery_sent_at),o}mapIdentityToResponse(e,n,r){let s=typeof e.identity_data=="string"?JSON.parse(e.identity_data):e.identity_data??{},i=n==="session"&&r.confirmed_at?{...s,email_verified:true}:s,o=e.email??(typeof i.email=="string"?i.email:r.email??void 0);return {identity_id:e.id,id:e.provider_id,user_id:e.user_id,identity_data:i,provider:e.provider,last_sign_in_at:e.last_sign_in_at??e.created_at,created_at:e.created_at,updated_at:e.updated_at,...o?{email:o}:{}}}async findUserByTokenAndType(e,n){if(n==="email_change"){let r=await this.repo.findUserByToken("email_change_token_current",e);if(r)return {user:r,tokenColumn:"email_change_token_current"};let s=await this.repo.findUserByToken("email_change_token_new",e);return s?{user:s,tokenColumn:"email_change_token_new"}:null}for(let r of this.getTokenColumnsForType(n)){let s=await this.repo.findUserByToken(r,e);if(s)return {user:s,tokenColumn:r}}return null}static SENT_AT_COLUMN={confirmation_token:"confirmation_sent_at",recovery_token:"recovery_sent_at",email_change_token_current:"email_change_sent_at",email_change_token_new:"email_change_sent_at",reauthentication_token:"reauthentication_sent_at"};isTokenExpired(e,n){let r=t.SENT_AT_COLUMN[n];if(!r)return false;let s=e[r];if(!s)return false;let i=new Date(s).getTime();return Number.isNaN(i)?false:Date.now()-i>this.otpExpirySeconds*1e3}getTokenColumnsForType(e){switch(e){case "signup":return ["confirmation_token"];case "magiclink":return ["recovery_token","confirmation_token"];case "recovery":return ["recovery_token"];case "email_change":return ["email_change_token_new","email_change_token_current"];case "reauthentication":return ["reauthentication_token"];default:return []}}async createAuditLog(e,n,r,s,i=true,o="email",a="provider"){let l={action:r,actor_id:e,actor_username:n,actor_via_sso:false,log_type:s};i&&(l.traits={[a]:o}),await this.repo.createAuditLogEntry({id:ue(),payload:l});}async createAuditLogWithTraits(e,n,r,s,i){await this.repo.createAuditLogEntry({id:ue(),payload:{action:r,actor_id:e,actor_username:n,actor_via_sso:false,log_type:s,traits:i}});}async getExternalProviderRedirectUrl(e,n){let r=e.provider??"",s=Oc(r,this.config.external,{defaultRedirectUri:n.defaultRedirectUri}),i=e.invite_token??"";if(i!==""&&!await this.repo.findUserByToken("confirmation_token",i))throw uh();let o=e.code_challenge??"",a=e.code_challenge_method??"";Eh(a,o);let l=this.resolveOAuthReferrer(e.redirect_to,n.refererHeader),c={};for(let[d,p]of Object.entries(e))p!==void 0&&(["provider","scopes","code_challenge","code_challenge_method"].includes(d)||(c[d]=p));let f=ue(),u=o!==""?ue():null;return await this.repo.deleteFlowStatesCreatedBefore(new Date(Date.now()-lT).toISOString()),await this.repo.createFlowState({id:f,auth_code:u,authentication_method:"oauth",code_challenge:o!==""?o:null,code_challenge_method:o!==""?xc(a):null,provider_type:s.name,invite_token:i!==""?i:null,referrer:l,email_optional:s.emailOptional}),s.provider.authorizeUrl({clientId:s.clientId,redirectUri:s.redirectUri,scopes:e.scopes,state:f,extraParams:c})}async loadOAuthFlowState(e){if(!e)throw gc("OAuth state parameter missing");if(!Fh(e))throw po("OAuth state parameter is invalid");let n=await this.repo.findFlowStateById(e);if(!n)throw po("OAuth state not found or expired");if(Date.now()-Date.parse(n.created_at)>Ih)throw po("OAuth state has expired");if(n.code_challenge!==null&&n.user_id!==null)throw ho();return n}resolveOAuthRedirectTarget(e){return e.referrer||this.config.site_url||"http://localhost:3000"}async handleExternalProviderCallback(e,n,r){let s=this.resolveOAuthRedirectTarget(e),i=e.provider_type,o=n.code;if(!o)throw gc("OAuth callback with missing authorization code missing");let a=Oc(i,this.config.external,{defaultRedirectUri:r.defaultRedirectUri}),l;try{l=await a.provider.exchangeCode(o,{clientId:a.clientId,secret:a.secret,redirectUri:a.redirectUri});}catch(h){throw dh(o).withInternalError(h)}let c;try{c=await a.provider.getUserData(l,{clientId:a.clientId});}catch(h){throw ph().withInternalError(h)}if(c.emails.length===0&&!e.email_optional)throw gs("Error getting user email from external provider");let f,u=false;for(let h of c.emails)if(f=h.email,u=h.verified,h.primary)break;let d={...c.claims,email:f,email_verified:u},p=wh(d),g=d.sub??"",m=await this.repo.transaction(async h=>{let y=this.repo;this.repo=h;try{let w=e.invite_token??"";if(w!==""){let v=await this.processInvite(w,i,c.emails,p,g);return await this.issueOAuthCallbackResult(v,e,l,s)}let S=await this.determineAccountLinking(c.emails,i,g),b,_,E=!1;if(S.decision==="AccountExists")b=S.user,_=S.identity.id,await this.repo.updateIdentity(_,{identity_data:p,last_sign_in_at:new Date().toISOString()}),await this.updateUserMetaDataAndProviders(b.id,p);else if(S.decision==="LinkAccount"){b=S.user;let v=await this.repo.createIdentity({id:ue(),provider:i,provider_id:g,user_id:b.id,identity_data:p});_=v.id,await this.updateUserMetaDataAndProviders(b.id,p),await this.createAuditLogWithTraits(b.id,b.email??"","identity_linked","user",{identity_id:v.id,provider:i,provider_id:g});}else if(S.decision==="CreateAccount"){if(this.config.enable_signup===!1)throw co();E=!0;let v=ue();b=await this.repo.createUser({id:v,email:S.candidateEmail.email||null,raw_app_meta_data:{provider:i,providers:[i]},raw_user_meta_data:p}),_=(await this.repo.createIdentity({id:ue(),provider:i,provider_id:g,user_id:v,identity_data:p})).id;}else throw gs("Multiple accounts with the same email address in the same linking domain detected: default");let x=this.repo.parseUserJson(await this.repo.findUserById(b.id));if(mT(x))throw ch();if(!(e.email_optional&&S.candidateEmail.email==="")&&!x.confirmed_at){await this.removeUnconfirmedIdentities(x.id,_,p);let v=!(this.config.email?.enable_confirmations??this.config.enable_confirmations??!1);if(S.candidateEmail.verified||v)await this.createAuditLog(x.id,S.candidateEmail.email,"user_signedup","team",!0,i),await this.repo.updateUser(x.id,{confirmed_at:new Date().toISOString(),raw_user_meta_data:{...p,email_verified:!0}});else {let P=!1;if(S.candidateEmail.email){let C=ut(this.otpLength),R=await tt(S.candidateEmail.email,C),U=new Date().toISOString();await this.repo.updateUser(x.id,{confirmation_token:R,confirmation_sent_at:U}),await this.mailer.sendConfirmation(S.candidateEmail.email,R,C,{userId:x.id,redirectTo:this.config.site_url}),P=!0;}return {commitError:lh(P?`Unverified email with ${i}. A confirmation email has been sent to your ${i} email`:`Unverified email with ${i}. Verify the email with ${i} in order to sign in`)}}}else await this.createAuditLog(x.id,x.email??"","login","account",!0,i);return await this.issueOAuthCallbackResult(x,e,l,s)}finally{this.repo=y;}});if(m.commitError)throw m.commitError;return m}async issueOAuthCallbackResult(e,n,r,s){if(n.code_challenge!=null&&n.auth_code!=null){if(!await this.repo.claimFlowStateForPkce(n.id,{user_id:e.id,provider_access_token:r.access_token??"",provider_refresh_token:r.refresh_token??"",auth_code_issued_at:new Date().toISOString()}))throw ho();let m=new URL(s);return m.searchParams.set("code",n.auth_code),{commitError:void 0,type:"pkce",redirectUrl:m.toString()}}let o=this.repo.parseUserJson(await this.repo.findUserById(e.id)),a=await this.repo.findIdentitiesByUserId(e.id),l=await this.createSessionForUser(o,a,"session",{createLoginAudit:false});if(!await this.repo.deleteFlowState(n.id))throw ho();let f={access_token:l.access_token,expires_at:String(l.expires_at),expires_in:String(l.expires_in),provider_token:r.access_token??""};r.refresh_token&&(f.provider_refresh_token=r.refresh_token),f.refresh_token=l.refresh_token,f.sb="",f.token_type=l.token_type;let d=Object.keys(f).sort().map(g=>`${encodeURIComponent(g)}=${encodeURIComponent(f[g])}`).join("&"),p=new URL(s);return p.hash=d,{commitError:void 0,type:"implicit",redirectUrl:p.toString()}}async processInvite(e,n,r,s,i){let o=await this.repo.findUserByToken("confirmation_token",e);if(!o)throw fh();let a=this.repo.parseUserJson(o),l=(a.email??"").toLowerCase();if(!r.some(u=>u.email.toLowerCase()===l))throw H("Invited email does not match emails from external provider",400);let f=await this.repo.createIdentity({id:ue(),provider:n,provider_id:i,user_id:a.id,identity_data:s});return await this.updateUserMetaDataAndProviders(a.id,s),await this.createAuditLog(a.id,a.email??"","invite_accepted","account",true,n),await this.removeUnconfirmedIdentities(a.id,f.id,s),await this.repo.updateUser(a.id,{confirmation_token:null,confirmed_at:new Date().toISOString(),raw_user_meta_data:{...s,email_verified:true}}),this.repo.parseUserJson(await this.repo.findUserById(a.id))}async exchangePkceCode(e,n){if(!e||!n)throw H("invalid request: both auth code and code verifier should be non-empty",400);let r=await this.repo.findFlowStateByAuthCode(e);if(!r||!r.user_id)throw mo();if(Date.now()-Date.parse(r.created_at)>Ih)throw oh();if(!await xh(r.code_challenge??"",r.code_challenge_method??"",n))throw ah("code challenge does not match previously saved code verifier");return {...await this.repo.transaction(async o=>{let a=this.repo;this.repo=o;try{if(!await this.repo.deleteFlowState(r.id))throw mo();let c=await this.repo.findUserById(r.user_id);if(!c)throw mo();let f=this.repo.parseUserJson(c),u=await this.repo.findIdentitiesByUserId(c.id);return await this.createSessionForUser(f,u,"session",{includeLoginProviderTrait:!0,provider:r.provider_type,providerTraitKey:"provider_type"})}finally{this.repo=a;}}),...r.provider_access_token?{provider_token:r.provider_access_token}:{},...r.provider_refresh_token?{provider_refresh_token:r.provider_refresh_token}:{}}}resolveOAuthReferrer(e,n){let r=this.config.site_url??"http://localhost:3000",s=this.config.additional_redirect_urls??[];return e&&Pc(e,r,s)?e:n&&Pc(n,r,s)?n:r}async updateUserMetaDataAndProviders(e,n){let r=await this.repo.findUserById(e);if(!r)return;let s=this.repo.parseUserJson(r),i=typeof s.raw_user_meta_data=="object"?s.raw_user_meta_data:{},o=jh(i,n),a=await this.buildAppMetaDataProviders(e,s.raw_app_meta_data);await this.repo.updateUser(e,{raw_user_meta_data:o,raw_app_meta_data:a});}async buildAppMetaDataProviders(e,n){let r=typeof n=="object"&&n?{...n}:{},i=[...await this.repo.findIdentitiesByUserId(e)].sort((a,l)=>Date.parse(a.created_at)-Date.parse(l.created_at)),o=[];for(let a of i)o.includes(a.provider)||o.push(a.provider);return r.providers=o,o.length>0&&(r.provider=o[0]),r}async removeUnconfirmedIdentities(e,n,r){await this.repo.deleteIdentitiesExcept(e,n);let s=await this.repo.findUserById(e),i=await this.buildAppMetaDataProviders(e,s?this.repo.parseUserJson(s).raw_app_meta_data:{});await this.repo.updateUser(e,{raw_user_meta_data:r,raw_app_meta_data:i,encrypted_password:null});}async determineAccountLinking(e,n,r){let s=e.find(p=>p.primary),i=s?{email:s.email.toLowerCase(),verified:s.verified}:{email:"",verified:false},o=r?await this.repo.findIdentityByProviderAndId(n,r):null;if(o){let p=await this.repo.findUserById(o.user_id);if(!p)throw new Error("Database error finding user for existing identity");return i={email:(p.email??"").toLowerCase(),verified:i.verified},{decision:"AccountExists",user:p,identity:o,candidateEmail:i}}let a=!(this.config.email?.enable_confirmations??this.config.enable_confirmations??false),l=Array.from(new Set(e.filter(p=>p.verified||a).map(p=>p.email.toLowerCase())));if(l.length===0)return i.email&&await this.repo.findUserByEmail(i.email)&&(i={...i,email:""}),{decision:"CreateAccount",candidateEmail:i};let c=await this.repo.findIdentitiesByEmails(l),f=Array.from(new Set(c.map(p=>p.user_id))),d=(await Promise.all(f.map(p=>this.repo.findUserById(p)))).filter(p=>p!==null).filter(p=>!Dh(p));if(d.length===0){let p=await Promise.all(l.map(m=>this.repo.findUserByEmail(m))),g=new Map;for(let m of p)m&&!Dh(m)&&g.set(m.id,m);d=Array.from(g.values());}return d.length===0?{decision:"CreateAccount",candidateEmail:i}:d.length>1?{decision:"MultipleAccounts"}:{decision:"LinkAccount",user:d[0],candidateEmail:i}}};function Dh(t){return t.is_sso_user===true||t.is_sso_user===1}function mT(t){return t.banned_until?Date.parse(t.banned_until)>Date.now():false}function jh(t,e){let n={...t};for(let[r,s]of Object.entries(e))s===null?delete n[r]:n[r]=s;return n}function hT(t){switch(t){case "letters_digits":return ["abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ","0123456789"];case "lower_upper_letters_digits":return ["abcdefghijklmnopqrstuvwxyz","ABCDEFGHIJKLMNOPQRSTUVWXYZ","0123456789"];case "lower_upper_letters_digits_symbols":return ["abcdefghijklmnopqrstuvwxyz","ABCDEFGHIJKLMNOPQRSTUVWXYZ","0123456789","!@#$%^&*"];default:return []}}function Lh(t){if(!t)return;let e=t.match(/^(\d+)(ms|s|m|h)?$/);if(!e)return;let n=Number(e[1]);switch(e[2]??"s"){case "ms":return n/1e3;case "m":return n*60;case "h":return n*3600;default:return n}}function zn(t){return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}function Fh(t){return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)}function Uh(t){return t.revoked===true||t.revoked===1}function gT(t,e){let n=[],r=[e];for(;r.length>0;){let s=r.shift();for(let i of t)i.parent!==s||n.some(o=>o.id===i.id)||(n.push(i),r.push(i.token));}return n}function $c(...t){let e=Math.max(0,...t.map(r=>r?Date.parse(r):0)),n=Date.now();return new Date(Math.max(n,e+1)).toISOString()}function Mh(t,e,n){return Object.defineProperties(t,{session_id:{value:e,enumerable:false},user_id:{value:n,enumerable:false}}),t}var yT=100;function ws(t){if(t==null)return {};if(typeof t=="string")try{return JSON.parse(t)}catch{return {}}return t}function yn(t){return typeof t=="string"?t:JSON.stringify(t??{})}var Ss=class t{constructor(e,n,r=s=>e.transaction().execute(s)){this.db=e;this.dialect=n;this.runInTransaction=r;this.schema="auth";}schema;bool(e){return this.dialect==="sqlite"?e?1:0:e}async transaction(e){return this.runInTransaction(n=>e(new t(n,this.dialect,this.runInTransaction)))}table(e){return this.db.withSchema(this.schema).selectFrom(e)}insertInto(e){return this.db.withSchema(this.schema).insertInto(e)}update(e){return this.db.withSchema(this.schema).updateTable(e)}deleteFrom(e){return this.db.withSchema(this.schema).deleteFrom(e)}async findUserByEmail(e){return await this.table("users").selectAll().where("email","=",e.toLowerCase()).executeTakeFirst()??null}async findUserById(e){return await this.table("users").selectAll().where("id","=",e).executeTakeFirst()??null}async findUserByToken(e,n){return await this.table("users").selectAll().where(e,"=",n).executeTakeFirst()??null}async claimUserToken(e,n,r){let s=await this.update("users").set({[n]:null}).where("id","=",e).where(n,"=",r).executeTakeFirst();return Number(s.numUpdatedRows??0)>0}async createUser(e){let n=new Date().toISOString(),r={id:e.id,aud:e.aud??"authenticated",role:e.role??"authenticated",email:e.email?e.email.toLowerCase():null,encrypted_password:e.encrypted_password??null,phone:e.phone??null,email_confirmed_at:e.email_confirmed_at??e.confirmed_at??null,confirmation_token:e.confirmation_token??null,confirmation_sent_at:e.confirmation_sent_at??null,recovery_token:e.recovery_token??null,recovery_sent_at:e.recovery_sent_at??null,email_change:e.email_change??null,email_change_token_new:e.email_change_token_new??null,email_change_token_current:e.email_change_token_current??null,email_change_sent_at:e.email_change_sent_at??null,email_change_confirm_status:e.email_change_confirm_status??0,reauthentication_token:e.reauthentication_token??null,reauthentication_sent_at:e.reauthentication_sent_at??null,raw_app_meta_data:yn(e.raw_app_meta_data??{provider:"email",providers:["email"]}),raw_user_meta_data:yn(e.raw_user_meta_data??{}),is_sso_user:this.bool(e.is_sso_user??false),is_anonymous:this.bool(e.is_anonymous??false),last_sign_in_at:e.last_sign_in_at??null,created_at:n,updated_at:n};return await this.insertInto("users").values(r).execute(),await this.findUserById(e.id)}async updateUser(e,n){let r={...n,updated_at:new Date().toISOString()};return r.confirmed_at!=null&&r.email_confirmed_at==null&&(r.email_confirmed_at=r.confirmed_at),delete r.confirmed_at,r.raw_app_meta_data!=null&&(r.raw_app_meta_data=yn(r.raw_app_meta_data)),r.raw_user_meta_data!=null&&(r.raw_user_meta_data=yn(r.raw_user_meta_data)),r.is_sso_user!=null&&(r.is_sso_user=this.bool(!!r.is_sso_user)),r.is_anonymous!=null&&(r.is_anonymous=this.bool(!!r.is_anonymous)),await this.update("users").set(r).where("id","=",e).execute(),this.findUserById(e)}async createSession(e){let n=new Date().toISOString(),r={id:e.id,user_id:e.user_id,aal:e.aal??"aal1",not_after:null,refreshed_at:null,user_agent:null,ip:null,tag:null,refresh_token_hmac_key:null,refresh_token_counter:null,scopes:null,factor_id:null,created_at:n,updated_at:n};return await this.insertInto("sessions").values(r).execute(),r}async findSessionById(e){return await this.table("sessions").selectAll().where("id","=",e).executeTakeFirst()??null}async updateSessionRefreshedAt(e,n){return await this.update("sessions").set({refreshed_at:n,updated_at:n}).where("id","=",e).execute(),this.findSessionById(e)}async deleteSession(e){await this.deleteFrom("sessions").where("id","=",e).execute();}async deleteUserSessions(e,n){let r=this.deleteFrom("sessions").where("user_id","=",e);n&&(r=r.where("id","!=",n)),await r.execute();}async deleteRefreshTokensForSession(e){await this.deleteFrom("refresh_tokens").where("session_id","=",e).execute();}async deleteRefreshTokensForUser(e,n){let r=this.deleteFrom("refresh_tokens").where("user_id","=",e);n&&(r=r.where("session_id","!=",n)),await r.execute();}async createRefreshToken(e){let n=new Date().toISOString(),r={id:ue(),token:e.token,user_id:e.user_id,session_id:e.session_id,revoked:this.bool(false),parent:e.parent??null,created_at:n,updated_at:n};return await this.insertInto("refresh_tokens").values(r).execute(),r}async findRefreshToken(e){return await this.table("refresh_tokens").selectAll().where("token","=",e).executeTakeFirst()??null}async findRefreshTokensBySession(e){return await this.table("refresh_tokens").selectAll().where("session_id","=",e).execute()}async revokeRefreshToken(e){await this.update("refresh_tokens").set({revoked:this.bool(true),updated_at:new Date().toISOString()}).where("id","=",e).execute();}async revokeSessionRefreshTokens(e){await this.update("refresh_tokens").set({revoked:this.bool(true),updated_at:new Date().toISOString()}).where("session_id","=",e).execute();}async revokeRefreshTokensByIds(e){e.length!==0&&await this.update("refresh_tokens").set({revoked:this.bool(true),updated_at:new Date().toISOString()}).where("id","in",e).execute();}async revokeUserRefreshTokens(e){await this.update("refresh_tokens").set({revoked:this.bool(true),updated_at:new Date().toISOString()}).where("user_id","=",e).execute();}async createIdentity(e){let n=new Date().toISOString(),r={id:e.id,provider:e.provider,provider_id:e.provider_id,user_id:e.user_id,identity_data:yn(e.identity_data),last_sign_in_at:e.last_sign_in_at??n,created_at:n,updated_at:n};return await this.insertInto("identities").values(r).execute(),{...r,identity_data:e.identity_data}}async findIdentitiesByUserId(e){return (await this.table("identities").selectAll().where("user_id","=",e).execute()).map(r=>({...r,identity_data:ws(r.identity_data)}))}async updateIdentity(e,n){let r={...n,updated_at:new Date().toISOString()};r.identity_data!=null&&(r.identity_data=yn(r.identity_data)),delete r.email,await this.update("identities").set(r).where("id","=",e).execute();}async deleteIdentitiesExcept(e,n){await this.deleteFrom("identities").where("user_id","=",e).where("id","!=",n).execute();}async findIdentityByProviderAndId(e,n){let r=await this.table("identities").selectAll().where("provider","=",e).where("provider_id","=",n).executeTakeFirst();if(!r)return null;let s=r;return {...s,identity_data:ws(s.identity_data)}}async findIdentitiesByEmails(e){return e.length===0?[]:(await this.table("identities").selectAll().where("email","in",e.map(r=>r.toLowerCase())).execute()).map(r=>({...r,identity_data:ws(r.identity_data)}))}async createFlowState(e){let n=new Date().toISOString(),r={id:e.id,user_id:e.user_id??null,auth_code:e.auth_code??null,authentication_method:e.authentication_method,code_challenge_method:e.code_challenge_method??null,code_challenge:e.code_challenge??null,provider_type:e.provider_type,provider_access_token:"",provider_refresh_token:"",auth_code_issued_at:null,invite_token:e.invite_token??null,referrer:e.referrer??null,oauth_client_state_id:e.oauth_client_state_id??null,linking_target_id:e.linking_target_id??null,email_optional:this.bool(e.email_optional??false),created_at:n,updated_at:n};return await this.insertInto("flow_state").values(r).execute(),r}async findFlowStateById(e){return await this.table("flow_state").selectAll().where("id","=",e).executeTakeFirst()??null}async findFlowStateByAuthCode(e){return await this.table("flow_state").selectAll().where("auth_code","=",e).executeTakeFirst()??null}async updateFlowState(e,n){let r={...n,updated_at:new Date().toISOString()};r.email_optional!=null&&(r.email_optional=this.bool(!!r.email_optional)),await this.update("flow_state").set(r).where("id","=",e).execute();}async claimFlowStateForPkce(e,n){let r=await this.update("flow_state").set({...n,updated_at:new Date().toISOString()}).where("id","=",e).where("user_id","is",null).executeTakeFirst();return Number(r.numUpdatedRows??0)>0}async deleteFlowStatesCreatedBefore(e){let n=await this.deleteFrom("flow_state").where("id","in",this.db.selectFrom("flow_state").select("id").where("created_at","<",e).limit(yT)).executeTakeFirst();return Number(n.numDeletedRows??0)}async deleteFlowState(e){let n=await this.deleteFrom("flow_state").where("id","=",e).executeTakeFirst();return Number(n.numDeletedRows??0)>0}async createAuditLogEntry(e){let n={id:e.id,payload:yn(e.payload??{}),ip_address:e.ip_address??"",created_at:new Date().toISOString()};await this.insertInto("audit_log_entries").values(n).execute();}parseUserJson(e){return {...e,raw_app_meta_data:ws(e.raw_app_meta_data),raw_user_meta_data:ws(e.raw_user_meta_data),confirmed_at:e.confirmed_at??e.email_confirmed_at??null}}};var Vn=class{maxSizeBytes;now;entries=new Map;sizeBytes=0;constructor(e={}){this.maxSizeBytes=e.maxSizeBytes??1024*1024,this.now=e.now??Date.now;}async get(e){let n=this.entries.get(e);if(n){if(this.isExpired(n)){this.deleteEntry(e,n);return}return this.entries.delete(e),this.entries.set(e,n),n.value}}async set(e,n,r){let s=this.entries.get(e);s&&this.deleteEntry(e,s);let i={value:n,size:Bh(e)+Bh(n),expiresAt:r?.ttl&&r.ttl>0?this.now()+r.ttl*1e3:void 0};this.entries.set(e,i),this.sizeBytes+=i.size,this.evictToSize();}async delete(e){let n=this.entries.get(e);n&&this.deleteEntry(e,n);}isExpired(e){return typeof e.expiresAt=="number"&&e.expiresAt<=this.now()}evictToSize(){for(;this.sizeBytes>this.maxSizeBytes;){let e=this.entries.keys().next().value;if(typeof e!="string")break;let n=this.entries.get(e);if(!n)break;this.deleteEntry(e,n);}}deleteEntry(e,n){this.entries.delete(e),this.sizeBytes-=n.size;}};function Bh(t){return new TextEncoder().encode(t).byteLength}var bo=class{constructor(e){this.options=e;}async get(e){return await this.options.namespace.get(e)??void 0}async set(e,n,r){await this.options.namespace.put(e,n,{...r?.ttl&&r.ttl>0?{expirationTtl:r.ttl}:{}});}async delete(e){await this.options.namespace.delete(e);}};var wo=class{constructor(e){this.options=e;}async get(e){return await this.options.client.get(e)??void 0}async set(e,n,r){if(r?.ttl&&r.ttl>0){await this.options.client.set(e,n,"EX",r.ttl);return}await this.options.client.set(e,n);}async delete(e){if(this.options.client.del){await this.options.client.del(e);return}if(this.options.client.delete){await this.options.client.delete(e);return}throw new Error("RedisCacheDriver client must provide del() or delete()")}};var So=class{constructor(e){this.options=e;this.endpoint=e.endpoint??"https://api.resend.com/emails",this.fetchFn=e.fetch??fetch;}endpoint;fetchFn;async send(e){let n=await this.fetchFn(this.endpoint,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${this.options.apiKey}`},body:JSON.stringify({from:this.options.from,to:e.to,subject:e.subject,...e.text?{text:e.text}:{},...e.html?{html:e.html}:{}})});if(!n.ok)throw new Error(`Resend email failed (${n.status}): ${await n.text()}`)}};var Eo=class{constructor(e){this.options=e;this.endpoint=`https://email.${e.region}.amazonaws.com/v2/email/outbound-emails`,this.client=e.client;}endpoint;client;async send(e){let n=await this.getClient(),r={FromEmailAddress:this.options.from,Destination:{ToAddresses:[e.to]},Content:{Simple:{Subject:{Data:e.subject,Charset:"UTF-8"},Body:{...e.text?{Text:{Data:e.text,Charset:"UTF-8"}}:{},...e.html?{Html:{Data:e.html,Charset:"UTF-8"}}:{}}}}},s=await n.fetch(this.endpoint,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw new Error(`AWS SES email failed (${s.status}): ${await s.text()}`)}async getClient(){if(this.client)return this.client;let{AwsClient:e}=await Promise.resolve().then(()=>(Jh(),Kh));return this.client=new e({accessKeyId:this.options.accessKeyId,secretAccessKey:this.options.secretAccessKey,service:"ses",region:this.options.region}),this.client}};var xo=class{constructor(e){this.options=e;this.sendmailPath=e.sendmailPath??"/usr/sbin/sendmail";}sendmailPath;async send(e){let{spawn:n}=await import('node:child_process').catch(()=>{throw new Error("SendmailEmailDriver requires a Node-compatible runtime")}),r=jc(this.options.from,e);await new Promise((s,i)=>{let o=n(this.sendmailPath,["-t","-i"],{stdio:["pipe","ignore","pipe"]}),a=[];o.on("error",l=>{i(new Error(`SendmailEmailDriver failed to start ${this.sendmailPath}: ${l.message}`));}),o.stderr?.on("data",l=>a.push(Buffer.from(l))),o.on("close",l=>{if(l===0){s();return}i(new Error(`SendmailEmailDriver exited with code ${l}: ${Buffer.concat(a).toString("utf8")}`));}),o.stdin.end(r);});}};function jc(t,e){let n=e.html?"text/html; charset=UTF-8":"text/plain; charset=UTF-8";return [`From: ${t}`,`To: ${e.to}`,`Subject: ${e.subject}`,"MIME-Version: 1.0",`Content-Type: ${n}`,"",e.html??e.text??""].join(`
87
- `)}Ol();function To(t){let e=t.port??587,n=t.timeoutMs??3e4,r=!!(t.user&&t.pass),s=r?{user:t.user,pass:t.pass}:void 0,i=t.secure??e===465;return {host:t.host,port:e,secure:i,...s?{auth:s}:{},requireTLS:t.requireTls??(r&&!i),...t.rejectUnauthorized===false?{tls:{rejectUnauthorized:false}}:{},connectionTimeout:n,greetingTimeout:n,socketTimeout:n}}function Lc(t,e){return {from:t,to:e.to,subject:e.subject,...e.text!==void 0?{text:e.text}:{},...e.html!==void 0?{html:e.html}:{}}}function Fc(t){if(!t)throw new Error("SMTP email is not supported in this runtime (SmtpEmailDriver requires Node or Bun)")}var _T="nodemailer",Qn=class{constructor(e){this.options=e;}transporter;async send(e){Fc(!Dp()&&(Np()||Al()));let n=await this.getTransporter();try{await n.sendMail(Lc(this.options.from,e));}catch(r){let s=r instanceof Error?r.message:String(r);throw new Error(`SmtpEmailDriver send failed: ${s}`,{cause:r})}}async getTransporter(){if(this.transporter)return this.transporter;if(this.options.createTransport)return this.transporter=this.options.createTransport(To(this.options)),this.transporter;let e=await import(_T);return this.transporter=e.createTransport(To(this.options)),this.transporter}};var Es=class{messages=new Map;maxKeepCount;order=[];constructor(e={}){this.maxKeepCount=e.maxKeepCount??100;}async send(e){if(this.maxKeepCount<=0)return;let n=e.to.toLowerCase(),r={...e,sentAt:new Date().toISOString()},s=this.messages.get(n)??[];s.push(r),this.messages.set(n,s),this.order.push({key:n,message:r}),this.trim();}clear(){this.messages.clear(),this.order.length=0;}trim(){for(;this.order.length>this.maxKeepCount;){let e=this.order.shift();if(!e)return;let n=this.messages.get(e.key);if(!n)continue;let r=n.indexOf(e.message);r>=0&&n.splice(r,1),n.length===0&&this.messages.delete(e.key);}}},Yn=class extends Es{silent;logger;constructor(e={}){super({maxKeepCount:0}),this.silent=e.silent??false,this.logger=e.logger??console;}async send(e){if(await super.send(e),!this.silent){let n=e.text?e.text:"(html-only email, body omitted)";this.logger.info(["[@supabase/lite] email captured (not delivered)",`To: ${e.to}`,`Subject: ${e.subject}`,"",n].join(`
84
+ `.execute(t)).rows[0],r=n?.status??null,s=n?.headers??null,i;if(r&&r.length>0){let f=Number(r);if(!Number.isInteger(f)||f<200||f>599)return T(500,"PGRST112",mx,null,null);i=f;}let o;if(s&&s.length>0){let f;try{f=JSON.parse(s);}catch{return T(500,"PGRST111",Kn,null,null)}if(!Array.isArray(f))return T(500,"PGRST111",Kn,null,null);let u=[];for(let d of f){if(!d||typeof d!="object"||Array.isArray(d))return T(500,"PGRST111",Kn,null,null);let p=Object.keys(d);if(p.length!==1)return T(500,"PGRST111",Kn,null,null);let g=d[p[0]];if(typeof g!="string")return T(500,"PGRST111",Kn,null,null);u.push([p[0],g]);}o=u;}if(i===void 0&&!o)return e;let a=i??e.status,l=new Headers(e.headers);if(o)try{for(let[f,u]of o)l.set(f,u);}catch{return T(500,"PGRST111",Kn,null,null)}let c;return hx.has(a)?(c=null,l.delete("Content-Length"),l.delete("Content-Type")):c=e.body?await e.arrayBuffer():null,new Response(c,{status:a,statusText:e.statusText,headers:l})}var hx=new Set([101,204,205,304]);var gx=/^[\w.+*-]+\/[\w.+*-]+$/,yx=new Set(["text/plain","text/xml","text/csv","application/json","application/geo+json","application/openapi+json"]);function bx(t){return t.replace(/^"([\s\S]*)"$/,"$1")}function wx(t){let e=t.match(/^(?:"(?:[^"]|"")*"|[^."]+)\.([\s\S]+)$/);return e?e[1]:t}function Sx(t){if(t.return_typtype!=="d"||t.return_is_setof)return null;let e=bx(wx(t.return_type));return gx.test(e)?e:null}function Om(t){if(!t)return [];let e=[];for(let n of t.split(",")){let r=n.split(";"),s=r[0].trim().toLowerCase();if(!s)continue;let i=1;for(let o of r.slice(1)){let a=o.trim().match(/^q=(.+)$/i);if(a){let l=Number.parseFloat(a[1]);Number.isFinite(l)&&(i=l);}}e.push({media:s,q:i});}return e}function Pm(t){return yx.has(t)?`${t}; charset=utf-8`:t}function _x(t,e){let n=e.indexOf("/"),r=n>0?e.slice(0,n):e,s=-1,i=0;for(let o of t){let a=o.media===e?2:o.media===`${r}/*`?1:o.media==="*/*"?0:-1;a<0||(a>s?(s=a,i=o.q):a===s&&(i=Math.max(i,o.q)));}return s<0?0:i}function Ex(t,e){let n=Sx(t);if(!n)return null;if(n==="*/*"){let r=Om(e);return r.some(s=>s.media==="*/*"&&s.q<=0)?null:!e||r.some(s=>s.q>0)?{mediaType:"application/octet-stream",isBinary:true}:null}return _x(Om(e),n)>0?{mediaType:n,isBinary:(t.return_base_type??"").toLowerCase()==="bytea"}:null}function uo(t,e,n){let r=Vi(t,e);return r?Ex(r,n):null}function $m(t,e){if(t instanceof Uint8Array){let s=new Uint8Array(t.byteLength);return s.set(t),s}if(e&&typeof t=="string"&&t.startsWith("\\x")){let s=t.slice(2),i=new Uint8Array(Math.floor(s.length/2));for(let o=0;o<i.length;o++)i[o]=parseInt(s.substr(o*2,2),16);return i}let n=new TextEncoder().encode(t==null?"":String(t)),r=new Uint8Array(n.byteLength);return r.set(n),r}var Im=da(Al());function Te(t,e,n){if(!n)return;let{sql:r,parameters:s}=e.compile();console.info(Im.default.dim(`[POSTGREST:SQL:${t}] ${r}
85
+ - ${JSON.stringify([...s])}`));}async function Nm(t){let{ast:e,meta:n,db:r,dialect:s,introspection:i,deparseSchema:o,mutationPlan:a,mutationCreated:l}=t;if(!t.isMutation||n?.return!=="minimal")return null;let c={...e,select:void 0},f=te(c,s,{db:r,introspection:i,schema:o});Te("",f,t.debug);let u=await f.execute(),d=Array.isArray(u)&&u.length>0&&u[0]&&typeof u[0]=="object"&&("numUpdatedRows"in u[0]||"numInsertedOrUpdatedRows"in u[0]||"numDeletedRows"in u[0])?u[0]:void 0,p=d===void 0?void 0:Number(d.numUpdatedRows??d.numInsertedOrUpdatedRows??d.numDeletedRows??0),g=et(e,"no-return",a.appliedResolution,l),m={"Content-Range":Ht(e,n,p)};return t.prefApplied&&(m["Preference-Applied"]=t.prefApplied),new Response(null,{status:g,headers:m})}async function Dm(t){let{ast:e,meta:n,db:r,dialect:s,introspection:i,deparseSchema:o,mutationPlan:a,mutationCreated:l,prefApplied:c}=t;if(!t.isMutation||n?.return!=="headers-only")return null;let u=i.primary_keys.find(w=>w.table===e.from)?.columns??[],d={...e,select:u.length>0?u:void 0},p=te(d,s,{db:r,introspection:i,schema:o});Te("",p,t.debug);let g=await p.execute(),m=Array.isArray(g)?g.length:0,h=et(e,"no-return",a.appliedResolution,l),y={"Content-Range":Ht(e,n,m)};if(c&&(y["Preference-Applied"]=c),u.length>0&&Array.isArray(g)&&g.length>0){let w=g[0],S=u.map(b=>`${b}=eq.${w[b]}`).join("&");y.Location=`/${e.from}?${S}`;}return new Response(null,{status:h,headers:y})}function Jn({rows:t,ast:e,connection:n,responseSchemaMap:r,mutationNullify:s}){let i=t.map(o=>n.deserializeRow(o));return i=em(i,e,r,Zp(n,e)),i=im(i,e.select,n.dialect),s?.meta?.return==="representation"&&(e.type==="insert"||e.type==="upsert"||e.type==="update")&&(i=wm(i,s.meta?.columns,s.mutationPlan.bodyKeySets)),i}function fo(t){let{rows:e,stripNullsResponse:n,csvResponse:r,contentRange:s,status:i=200,preferenceApplied:o,location:a,contentType:l="array"}=t,c=n?pn(e):e,f=r?co(Array.isArray(c)?c:[c]):Et(c),u=new TextEncoder().encode(f),d={"Content-Type":r?"text/csv; charset=utf-8":n?l==="object"?"application/vnd.pgrst.object+json;nulls=stripped; charset=utf-8":"application/vnd.pgrst.array+json;nulls=stripped; charset=utf-8":l==="object"?"application/vnd.pgrst.object+json; charset=utf-8":"application/json; charset=utf-8","Content-Range":s,"Content-Length":String(u.byteLength)};return o&&(d["Preference-Applied"]=o),a&&(d.Location=a),new Response(u,{status:i,headers:d})}async function jm(t){let{ast:e,meta:n,db:r,dialect:s,introspection:i,deparseSchema:o,connection:a,responseSchemaMap:l}=t;if(!(t.isMutation&&(e.type==="update"||e.type==="delete")&&(e.limit!==void 0||e.offset!==void 0)))return null;let f={...e,select:void 0},u=te(f,s,{db:r,introspection:i,schema:o});if(Te("LTD",u,t.debug),await u.execute(),n?.return==="representation"){let S={...e,type:"query",values:void 0,limit:void 0,offset:void 0},b=te(S,s,{db:r,introspection:i,schema:o});Te("LTD-SEL",b,t.debug);let _=await b.execute(),E=Array.isArray(_)?_:[],x=Jn({rows:E,ast:e,connection:a,responseSchemaMap:l}),O=x.length,v=[];n.return==="representation"&&v.push("return=representation"),n.count&&v.push(`count=${n.count}`),n.tx&&v.push(`tx=${n.tx}`);let P=e.type==="delete"?"*/*":O>0?lt(0,O,void 0):"*/*";return fo({rows:x,stripNullsResponse:t.stripNullsResponse,csvResponse:t.csvResponse,contentRange:P,preferenceApplied:v.length>0?v.join(", "):void 0})}let d={...e,type:"query",select:[{__count:{aggregate:"count"}}],values:void 0,order:void 0,limit:void 0,offset:void 0},g=await te(d,s,{db:r,introspection:i,schema:o}).execute(),m=Number((Array.isArray(g)?g[0]:g)?.__count??0),y={"Content-Range":m>0?lt(0,m,void 0):"*/*"},w=[];return n?.count&&w.push(`count=${n.count}`),n?.tx&&w.push(`tx=${n.tx}`),w.length>0&&(y["Preference-Applied"]=w.join(", ")),new Response(null,{status:204,headers:y})}function xx(t){return "select"in t||"spread"in t||"join"in t}function Lm(t){if(!t)return false;for(let e of t)if(typeof e!="string")for(let[n,r]of Object.entries(e)){if(xx(r))return true;let s=r;if(s.path||s.cast||s.preCast||s.aggregate||(s.column??n)!==n)return true}return false}async function Fm(t){let{ast:e,meta:n,db:r,dialect:s,introspection:i,deparseSchema:o,connection:a,responseSchemaMap:l,mutationPlan:c,mutationCreated:f}=t;if(!(t.isMutation&&n?.return==="representation"&&Lm(e.select)))return null;let p=i.primary_keys.find(_=>_.table===e.from)?.columns??[],g=[];if(e.type==="delete"){let _={...e,type:"query",values:void 0},E=te(_,s,{db:r,introspection:i,schema:o});Te("EMB-PRE",E,t.debug),g=await E.execute();let x={...e,select:void 0},O=te(x,s,{db:r,introspection:i,schema:o});Te("EMB-DEL",O,t.debug),await O.execute();}else {if(p.length===0)return T(500,"PGRSTXXX","Cannot return embedded data on a table without a primary key",null,null);let _={...e,select:p},E=te(_,s,{db:r,introspection:i,schema:o});Te("EMB-MUT",E,t.debug);let x=await E.execute(),O=Array.isArray(x)?x:[];if(O.length>0){let v;if(p.length===1){let U=p[0];v={[U]:{$in:O.map(J=>J[U])}};}else v={$or:O.map(U=>{let J={};for(let F of p)J[F]={$eq:U[F]};return J})};let P=e.where?{$and:[e.where,v]}:v,C={...e,type:"query",values:void 0,where:P},R=te(C,s,{db:r,introspection:i,schema:o});Te("EMB-SEL",R,t.debug),g=await R.execute();}}let m=Jn({rows:g,ast:e,connection:a,responseSchemaMap:l,mutationNullify:{meta:n,mutationPlan:c}});e.order&&e.order.length>0&&(m=lo(m,e.order));let h=et(e,"representation",c.appliedResolution,f),y=m.length,w=["return=representation"];n?.count&&w.push(`count=${n.count}`),n?.tx&&w.push(`tx=${n.tx}`);let S=e.type==="delete"||e.type==="insert"||e.type==="upsert"?"*/*":y>0?lt(0,y,void 0):"*/*",b;if((e.type==="insert"||e.type==="upsert")&&p.length>0&&m.length>0){let _=m[0],E=p.map(x=>`${x}=eq.${_[x]}`).join("&");b=`/${e.from}?${E}`;}return fo({rows:m,stripNullsResponse:t.stripNullsResponse,csvResponse:t.csvResponse,contentRange:S,status:h,preferenceApplied:w.join(", "),location:b})}function Tx(t){return t?.handling!=="strict"||typeof t.maxAffected!="number"||!Number.isFinite(t.maxAffected)?null:t.maxAffected}function Um(t){return T(400,"PGRST124","Query result exceeds max-affected preference constraint",`The query affects ${t} rows`,null)}function Rx(t){return t.type!=="insert"&&t.type!=="upsert"&&t.type!=="put"?null:Array.isArray(t.values)?t.values.length:t.values&&typeof t.values=="object"?1:0}async function Mm(t){if(!t.isMutation)return null;let e=Tx(t.meta);if(e===null)return null;let n=Rx(t.ast);if(n!==null)return n>e?Um(n):null;if(t.ast.type!=="update"&&t.ast.type!=="delete")return null;let r={...t.ast,type:"query",select:[{__count:{aggregate:"count"}}],values:void 0,order:void 0,limit:void 0,offset:void 0},s=te(r,t.dialect,{db:t.db,introspection:t.introspection,schema:t.deparseSchema});Te("MAX-AFFECTED",s,t.debug);let i=await s.execute(),o=Number((Array.isArray(i)?i[0]:i)?.__count??0);return t.ast.offset!==void 0&&(o=Math.max(o-t.ast.offset,0)),t.ast.limit!==void 0&&(o=Math.min(o,t.ast.limit)),o>e?Um(o):null}function mn(t){return t||"public"}function Cx(t,e,n){let r=mn(e);return n.views.some(s=>s.name===t&&mn(s.schema)===r)}function kx(t){let e=t.match(/\bINSERT\s+INTO\s+(?:(?:"([^"]+)"|'([^']+)')|(\w+))(?:\.(?:(?:"([^"]+)"|'([^']+)')|(\w+)))?/i);if(e)return e[6]??e[3]}function vx(t,e,n){let r=mn(e);for(let s of n.triggers){if(s.table!==t||mn(s.schema)!==r||!/\bINSTEAD\s+OF\b/i.test(s.sql))continue;let i=kx(s.sql);if(i)return i}}async function Bm(t,e,n,r,s,i){if(r!=="sqlite"&&r!=="postgres"||!e.from||t.length===0||!Cx(e.from,e.schema,n))return t;let o=e.select;if(!o?.length)return t;let a=mn(e.schema),l=n.primary_keys.find(h=>h.table===e.from&&mn(h.schema)===a)?.columns??[];if(l.length===0){let h=vx(e.from,e.schema,n);h&&(l=n.primary_keys.find(y=>y.table===h&&mn(y.schema)===a)?.columns??[]);}if(l.length===0&&t[0]&&"id"in t[0]&&(l=["id"]),l.length!==1)return t;let c=l[0],f=t.map(h=>h[c]).filter(h=>h!=null);if(f.length===0)return t;let u={type:"query",from:e.from,schema:e.schema,select:o,where:{[c]:{$in:f}}},p=await te(u,r,{db:s,introspection:n,schema:i}).execute(),g=h=>String(h[c]),m=new Map(p.map(h=>[g(h),h]));return t.map(h=>m.get(g(h))??h)}async function qm(t){let{ast:e,meta:n,db:r,dialect:s,introspection:i,deparseSchema:o,connection:a,responseSchemaMap:l,mutationPlan:c,mutationCreated:f,prefApplied:u,isMutation:d,stripNullsResponse:p,csvResponse:g,requestUrl:m,acceptHeader:h}=t,y=te(e,s,{db:r,introspection:i,schema:o});Te("",y,t.debug);let w=await y.execute(),S,b=false,_=0;if(d&&Array.isArray(w)&&w.length>0&&w[0]&&typeof w[0]=="object"&&("numUpdatedRows"in w[0]||"numInsertedOrUpdatedRows"in w[0]||"numDeletedRows"in w[0])){b=true;let G=w[0];_=Number(G.numUpdatedRows??G.numInsertedOrUpdatedRows??G.numDeletedRows??0),S=[];}else S=w;d&&Array.isArray(S)&&S.length>0&&(S=await Bm(S,e,i,s,r,o));let E=false,x,O=false,v=false,P=false,C=null;if(e.type==="rpc"&&Array.isArray(S)){let G={schema:e.schema??i.default_schema??"public",fnName:e.function??"",providedNames:fn(e),paramsType:e.paramsType,argCount:Array.isArray(e.args)?e.args.length:void 0,method:e.httpMethod,inputType:e.inputType};C=uo(i.functions,G,h);let pe=Qi(i.functions,G);if(pe){let Me=e.function??"",ht=S;E=!pe.returns_object&&ht.length>0&&ht.every(Ys=>{let gr=Object.keys(Ys);return gr.length===1&&gr[0]===Me}),E&&(x=Me,S=ht.map(Ys=>Ys[Me])),O=!pe.return_is_setof,P=pe.volatility!=="v",v=pe.returns_void;}}if(v){let G={"Content-Range":"0-0/*"};return u&&(G["Preference-Applied"]=u),new Response(null,{status:204,headers:G})}if(C&&Array.isArray(S)&&S.length===1){let G=S[0];if(!E&&G&&typeof G=="object"&&!Array.isArray(G)&&!(G instanceof Uint8Array)){let ht=Object.keys(G);ht.length===1&&(G=G[ht[0]]);}let pe=$m(G,C.isBinary),Me={"Content-Type":Pm(C.mediaType),"Content-Range":"0-0/*","Content-Length":String(pe.byteLength)};return u&&(Me["Preference-Applied"]=u),n?.head?new Response(null,{status:200,headers:Me}):new Response(pe,{status:200,headers:Me})}let R=Array.isArray(S);R&&!E&&(S=Jn({rows:S,ast:e,connection:a,responseSchemaMap:l,mutationNullify:{meta:n,mutationPlan:c}})),d&&R&&e.order&&e.order.length>0&&(S=lo(S,e.order));let U=R?S:[],J=U.length,F=e.offset??0;if(d&&b){if(n?.cardinality==="one"){if(_===0)return T(406,"PGRST116","Cannot coerce the result to a single JSON object","The result contains 0 rows",null);if(_>1)return T(406,"PGRST116","Cannot coerce the result to a single JSON object",`The result contains ${_} rows`,null)}let G=et(e,"no-return",c.appliedResolution,f),pe={"Content-Type":"application/json; charset=utf-8","Content-Range":Ht(e,n,_)};return u&&(pe["Preference-Applied"]=u),new Response(null,{status:G,headers:pe})}let V;if(uc(n)&&(d?V=J:e.type==="rpc"?F===0&&J<(e.limit??Number.POSITIVE_INFINITY)?V=J:P&&(V=await cc(r,e,s,i)):V=await cc(r,e,s,i)),n?.cardinality==="one"||O){if(J===0)return T(406,"PGRST116","Cannot coerce the result to a single JSON object","The result contains 0 rows",null);if(J>1)return T(406,"PGRST116","Cannot coerce the result to a single JSON object",`The result contains ${J} rows`,null);let G=200;d&&(G=et(e,"representation",c.appliedResolution,f));let pe=p?pn(U[0]):U[0],Me=Et(pe),ht=new TextEncoder().encode(Me),gr=n?.cardinality==="one"?"application/vnd.pgrst.object+json":"application/json",ua={"Content-Type":p?`${gr};nulls=stripped; charset=utf-8`:`${gr}; charset=utf-8`,"Content-Range":pm(e,d,F,V),"Content-Length":String(ht.byteLength)};return u&&(ua["Preference-Applied"]=u),n?.head?new Response(null,{status:G,headers:ua}):new Response(ht,{status:G,headers:ua})}if(V!==void 0&&F>0&&J===0&&F>=V){let G=JSON.stringify({code:"PGRST103",details:`An offset of ${F} was requested, but there are only ${V} rows.`,hint:null,message:"Requested range not satisfiable"}),pe=new TextEncoder().encode(G),Me={"Content-Type":"application/json; charset=utf-8","Content-Range":`*/${V}`,"Content-Length":String(pe.byteLength)};return u&&(Me["Preference-Applied"]=u),new Response(pe,{status:416,headers:Me})}let be;d&&(e.type==="insert"||e.type==="upsert"||e.type==="delete")?be=V!==void 0?`*/${V}`:"*/*":d&&n?.return!=="representation"?be=V!==void 0?`*/${V}`:"*/*":J>0?be=lt(F,J,V):be=V!==void 0?`*/${V}`:"*/*";let he=200;d?he=et(e,"representation",c.appliedResolution,f):V!==void 0&&(F+J<V||F>0)&&(he=206);let Ve=p?pn(S):S,Tn=Array.isArray(Ve)?Ve:[Ve];if(g&&E&&x!==void 0){let G=x;Tn=Tn.map(pe=>({[G]:pe}));}let Xs=g?co(Tn):Et(Ve),ca=new TextEncoder().encode(Xs),Ot={"Content-Type":g?"text/csv; charset=utf-8":p?"application/vnd.pgrst.array+json;nulls=stripped; charset=utf-8":"application/json; charset=utf-8","Content-Range":be,"Content-Length":String(ca.byteLength)};if(!d&&e.from&&m){let G=fm(`/${e.from}`,new URL(m).search);G&&(Ot["Content-Location"]=G);}return u&&(Ot["Preference-Applied"]=u),n?.head?new Response(null,{status:he,headers:Ot}):new Response(ca,{status:he,headers:Ot})}function Hm(t){return t==="snake_case"?"__":"."}function Wm(t,e){let n=new Set;for(let r of t.tables)r.schema&&n.add(r.schema);for(let r of t.views)r.schema&&n.add(r.schema);if(e?.deparseSchema)for(let r of e.deparseSchema.values())r?.schema&&n.add(r.schema);for(let r of e?.internalSchemas??[])n.add(r);return n}function Km(t){let e=new Set(t.exposedSchemas??["public"]),n=()=>[...e].sort().join(", ");if(t.explicitProfileSchema!==void 0&&!e.has(t.explicitProfileSchema))return T(406,"PGRST106",`Invalid schema: ${t.explicitProfileSchema}`,null,`Only the following schemas are exposed: ${n()}`);let r=t.isRpc?-1:t.relation.indexOf(t.separator);if(r>0){let s=t.relation.slice(0,r);if(t.knownSchemas.has(s)&&!e.has(s)){let i=t.relation.slice(r+t.separator.length);return T(404,"PGRST205",`Could not find the table '${s}.${i}' in the schema cache`,null,null)}}return null}var Ax={swagger:"2.0",info:{description:"",title:"standard public schema",version:"14.1"},basePath:"/",schemes:["https"],consumes:["application/json","application/vnd.pgrst.object+json;nulls=stripped","application/vnd.pgrst.object+json","text/csv"],produces:["application/json","application/vnd.pgrst.object+json;nulls=stripped","application/vnd.pgrst.object+json","text/csv"]},Jm=t=>{let e=async(n,r)=>{let{app:s}=n.var,i=s.connection;if(!s.config.api?.enabled)return n.notFound();let{relation:o,isRpc:a}=r;if(a&&!i.supportsRpc)return T(404,"PGRST202",`Could not find the function public.${o} in the schema cache`,null,null);if(a){let h=n.req.method.toUpperCase();if(!["GET","POST","HEAD","OPTIONS"].includes(h))return T(405,"PGRST101",`Cannot use the ${h} method on RPC`,null,null)}let l=await i.introspect({useCache:true});if(!a&&i.config.introspection?.exclude_tables?.some(h=>zi(o,h,"sql")))return n.notFound();if(!(kn in n.req.raw)){let h=i.config.translation,y=Hm(h?.schemas?.approach),w=[];s.config.auth?.enabled&&w.push("auth"),s.config.storage?.enabled&&w.push("storage");let S=n.req.method.toUpperCase(),b=n.req.header("Content-Profile"),_=n.req.header("Accept-Profile"),E=S==="OPTIONS"?b??_:["POST","PUT","PATCH","DELETE"].includes(S)?b:_,x=Km({relation:o,explicitProfileSchema:E,exposedSchemas:s.config.api?.schemas,knownSchemas:Wm(l,{deparseSchema:h?.deparse?.schema,internalSchemas:w}),separator:y,isRpc:a});if(x)return x}if(!(kn in n.req.raw)&&n.req.method!=="OPTIONS"){let h=n.var.ignoreAuthorization?void 0:n.req.header("Authorization");if(h||!n.var.apiKeyType){let y=await Kp(h,{jwtSecret:s.config.auth?.jwt_secret,anonymousEnabled:s.config.api?.anonymous_enabled!==false});if(y.kind==="error")return y.response;y.payload&&(n.set("userId",y.payload.sub),n.set("sessionId",y.payload.session_id),n.set("jwt",y.payload));}}if(a&&n.req.method==="OPTIONS"){let h=n.req.header("Content-Profile")??n.req.header("Accept-Profile")??l.default_schema??"public",y=El(l.functions,{schema:h,fnName:o,method:"OPTIONS",providedNames:[]});if(y)return T(404,"PGRST202",y.message,y.details,y.hint);let w=Bt(l.functions??[],{schema:h,fnName:o,providedNames:[]}),S=w.length>0&&w.every(b=>b.volatility!=="v");return n.header("Allow",S?"OPTIONS,GET,HEAD,POST":"OPTIONS,POST"),n.body(null,200)}if(!a&&n.req.method==="OPTIONS"){let h=n.req.header("Content-Profile")??n.req.header("Accept-Profile")??"public",y=b=>{let _=b||"public";return i.dialect==="sqlite"?_===h||_==="public"||_==="":_===h},w=l.views.find(b=>b.name===o&&y(b.schema)),S=!w&&l.tables.find(b=>b.name===o&&b.type!=="view"&&y(b.schema));if(S||w){let b=new Set(["OPTIONS","GET","HEAD"]);if(S)b.add("POST").add("PUT").add("PATCH").add("DELETE");else {let E=false,x=false,O=false,v=(F,V)=>`${F||"public"}\0${V}`,P=new Set,C=w.schema||"public",R=await i.viewOptionsMetadata(o,C).catch(()=>null);if(R){E=R.canInsert,x=R.canUpdate,O=R.canDelete;for(let F of R.baseTables)P.add(v(F.schema,F.name));}else {let F=l.triggers.filter(he=>he.table===o&&y(he.schema)),V=he=>F.some(Ve=>new RegExp(`instead\\s+of\\s+${he}`,"i").test(Ve.sql));E=V("insert"),x=V("update"),O=V("delete");let be=w?.sql??"";for(let he of l.tables){if(he.type==="view")continue;let Ve=he.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");new RegExp(`\\b${Ve}\\b`,"i").test(be)&&P.add(v(he.schema,he.name));}}let U=new Set(l.columns.filter(F=>F.table===o&&y(F.schema)).map(F=>F.name)),J=l.tables.some(F=>{if(F.type==="view"||!P.has(v(F.schema,F.name)))return false;let V=l.columns.filter(be=>be.table===F.name&&(be.schema||"public")===(F.schema||"public")&&be.is_primary_key);return V.length>0&&V.every(be=>U.has(be.name))});E&&b.add("POST"),x&&b.add("PATCH"),O&&b.add("DELETE"),E&&x&&J&&b.add("PUT");}let _=["OPTIONS","GET","HEAD","POST","PUT","PATCH","DELETE"].filter(E=>b.has(E));return n.header("Allow",_.join(",")),n.body(null,200)}}let{dialect:f}=i,u=i.config.translation?.deparse?.schema,d=Yp(u,l,f),p=n.var.jwt,g={auth:{uid:n.var.userId??null,role:p?.role||"anon",jwt:p??null}},m;try{let h=n.req.header("Content-Profile")??n.req.header("Accept-Profile")??"public",y=new Set(l.columns.filter(C=>{if(C.table!==o)return !1;let R=C.schema||"public";return f==="sqlite"?R===h||R==="public"||R==="":R===h}).map(C=>C.name));m=await vi(n.req.raw,{basePath:"/rest/v1",parentColumns:y,resolveFilters:(C,R,U)=>Ir(C,R,U,y)}),m=await i.onPostgrestAST(m,g);let w=m.function,S=!1;if(a&&w){let C={schema:m.schema??l.default_schema??"public",fnName:w,method:n.req.method.toUpperCase(),providedNames:fn(m),paramsType:m.paramsType,inputType:m.inputType,rawKind:cp(n.req.header("Content-Type"))},R=El(l.functions,C);if(R)return T(404,"PGRST202",R.message,R.details,R.hint);let U=lp(l.functions,C);if(U)return T(300,"PGRST203",U.message,U.details,U.hint);if(C.method==="OPTIONS"){let J=Qi(l.functions,{schema:C.schema,fnName:C.fnName,providedNames:C.providedNames,paramsType:C.paramsType}),F=J&&J.volatility!=="v"?"OPTIONS,GET,HEAD,POST":"OPTIONS,POST";return new Response(null,{status:200,headers:{Allow:F,"Access-Control-Allow-Origin":"*"}})}S=uo(l.functions,{schema:C.schema,fnName:C.fnName,providedNames:C.providedNames,paramsType:C.paramsType,argCount:Array.isArray(m.args)?m.args.length:void 0,method:C.method,inputType:C.inputType},n.req.header("Accept"))!==null;}t?.debug&&console.log(dc.default.dim("[POSTGREST:AST]"),m);let b=Tm({ast:m,dialect:f,introspection:l,apiConfig:s.config.api,acceptHeader:n.req.header("Accept")??"application/json",allowRawMedia:S,preferHeader:n.req.header("Prefer"),httpMethod:n.req.method.toUpperCase(),rangeHeader:n.req.header("Range")});if(b instanceof Response)return b;m=b.ast;let{meta:_,mutationPlan:E,isMutation:x,stripNullsResponse:O,csvResponse:v,planEnabled:P}=b;return await i.withContext(g,async C=>{let R=n.req.header("Accept")??"application/json";if(P&&rm(R)){let Ot=te(m,f,{db:C,introspection:l,schema:u}).compile();return t?.debug&&console.info(dc.default.dim(`[POSTGREST:PLAN] ${Ot.sql}
86
+ - ${JSON.stringify([...Ot.parameters])}`)),um(R,Ot)}let U=x?await Em(C,m,f,l,E):void 0,J=ps(_,E.appliedResolution),F={ast:m,meta:_,db:C,dialect:f,introspection:l,deparseSchema:u,connection:i,responseSchemaMap:d,mutationPlan:E,mutationCreated:U,prefApplied:J,isMutation:x,stripNullsResponse:O,csvResponse:v,acceptHeader:R,requestUrl:n.req.url,debug:t?.debug},V=await Mm(F);if(V)return V;let be=await Nm(F);if(be)return be;let he=await Dm(F);if(he)return he;let Ve=await jm(F);if(Ve)return Ve;let Tn=await Fm(F);if(Tn)return Tn;let Xs=await qm(F);return a&&f==="postgres"?await Am(C,Xs):Xs},{forceRollback:t?.forceRollback===!0,rpc:a&&f==="postgres"?{method:n.req.method.toUpperCase(),path:`/rpc/${o}`,readOnly:["GET","HEAD"].includes(n.req.method.toUpperCase()),requestHeaders:Object.fromEntries(n.req.raw.headers)}:void 0})}catch(h){return vm(h,{connection:i,introspection:l,vars:g,ast:m})}};return new _e().all("/rpc/:function",n=>e(n,{relation:n.req.param("function"),isRpc:true})).all("/:relation",n=>e(n,{relation:n.req.param("relation"),isRpc:false})).use(async(n,r)=>{if(n.req.method==="GET"&&n.req.path.endsWith("/")){if(n.var.apiKeyType==="publishable")return n.json({message:"You cannot consume this service"},403);let{app:s}=n.var,i=n.req.header("Accept-Profile")??n.req.header("Content-Profile")??null;if(i){let o=new Set(s.config.api?.schemas??["public"]);if(o.size>0&&!o.has(i)){let a=[...o].sort().join(", ");return T(406,"PGRST106",`Invalid schema: ${i}`,null,`Only the following schemas are exposed: ${a}`)}}return n.json(Ax)}await r();}).all("*",n=>T(404,"PGRST125","Invalid path specified in request URL",null,null))};var $=class extends Error{constructor(n,r,s,i,o){super(s);this.status=n;this.code=r;this.details=i;this.headers=o;this.name="AuthError";}withInternalError(n){return this.cause=n,this}toJSON(){return {code:this.status,error_code:this.code,msg:this.message,...this.details}}},ct=()=>new $(400,"invalid_credentials","Invalid login credentials"),Gm=()=>new $(400,"email_not_confirmed","Email not confirmed"),zm=(t,e=[],n=["length"])=>{let r=[];return n.includes("length")&&r.push(`Password should be at least ${t} characters.`),n.includes("characters")&&r.push(`Password should contain at least one character of each: ${e.join(", ")}.`),new $(422,"weak_password",r.join(" "),{weak_password:{reasons:n}})},Vm=(t="Access token is required")=>new $(401,"no_authorization",t),hn=()=>new $(401,"no_authorization","This endpoint requires a valid Bearer token"),ms=t=>new $(403,"bad_jwt",t),pc=()=>ms("invalid JWT: unable to parse or verify signature, token is malformed: token contains an invalid number of segments"),mc=t=>ms(`invalid JWT: unable to parse or verify signature, token is malformed: could not JSON decode header: ${t}`),Qm=()=>ms("invalid JWT: unable to parse or verify signature, token signature is invalid: signature is invalid"),Xm=()=>ms("invalid JWT: unable to parse or verify signature, token has invalid claims: token is expired"),hc=()=>ms("invalid claim: missing sub claim"),gc=()=>new $(400,"bad_jwt","invalid claim: sub claim must be a UUID");var Ym=()=>new $(403,"user_not_found","User from sub claim in JWT does not exist"),Zm=()=>new $(403,"session_not_found","Session from session_id claim in JWT does not exist"),eh=()=>new $(422,"user_already_exists","User already registered"),th=()=>new $(422,"email_exists","A user with this email address has already been registered"),po=()=>new $(422,"signup_disabled","Signups not allowed for this instance"),nh=()=>new $(400,"email_provider_disabled","Email signups are disabled"),rh=()=>new $(422,"otp_disabled","Signups not allowed for otp"),sh=()=>new $(422,"same_password","New password should be different from the old password."),gn=()=>new $(403,"otp_expired","Email link is invalid or has expired"),H=(t,e=422)=>new $(e,"validation_failed",t);var hs=t=>new $(400,"bad_json",t),yc=()=>new $(400,"validation_failed","Refresh token is not valid"),Gn=()=>new $(400,"refresh_token_not_found","Invalid Refresh Token: Refresh Token Not Found"),mo=(t,e)=>new $(400,"refresh_token_already_used","Invalid Refresh Token: Already Used",void 0,{...t?{"Sb-Auth-Session-Id":t}:{},...e?{"Sb-Auth-User-Id":e}:{}}),ih=()=>new $(401,"session_not_found","Invalid Refresh Token: Already Used"),bc=(t,e,n)=>new $(400,"session_expired",t==="inactivity"?"Invalid Refresh Token: Session Expired (Inactivity)":"Invalid Refresh Token: Session Expired",void 0,{...e?{"Sb-Auth-Session-Id":e}:{},...n?{"Sb-Auth-User-Id":n}:{}}),oh=()=>new $(422,"anonymous_provider_disabled","Anonymous sign-ins are disabled"),ah=()=>new $(400,"invalid_credentials","unsupported_grant_type"),ho=()=>new $(429,"over_email_send_rate_limit","For security purposes, you can only request this after 59 seconds."),go=t=>new $(400,"bad_oauth_state",t),wc=t=>new $(400,"bad_oauth_callback",t);var yo=(t="invalid flow state, no valid flow state found")=>new $(404,"flow_state_not_found",t),lh=()=>new $(422,"flow_state_expired","invalid flow state, flow state has expired"),bo=()=>new $(400,"flow_state_already_used","State has already been used"),ch=t=>new $(400,"bad_code_verifier",t),uh=t=>new $(422,"provider_email_needs_verification",t),fh=()=>new $(403,"user_banned","User is banned"),dh=()=>new $(404,"user_not_found","User identified by token not found"),ph=()=>new $(404,"invite_not_found","Invite not found"),gs=t=>new $(500,"unexpected_failure",t),mh=t=>gs(`Unable to exchange external code: ${t.slice(0,4)}`),hh=()=>gs("Error getting user profile from external provider");async function _c(t,e,n){let r=new TextEncoder().encode(e),s=Math.floor(Date.now()/1e3);return new SignJWT({...t,iat:s}).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt(s).setExpirationTime(s+n).sign(r)}async function gh(t,e){let n=t.split(".");if(n.length!==3||n.some(i=>i===""))throw pc();let r=$x(n[0]);if(r)throw r;let s=new TextEncoder().encode(e);try{let{payload:i}=await jwtVerify(t,s,{algorithms:["HS256"]});return i}catch(i){throw i instanceof errors.JWTExpired?Xm():i instanceof errors.JWSSignatureVerificationFailed?Qm():i instanceof errors.JWSInvalid||i instanceof errors.JWTInvalid?pc():i}}function $x(t){let e=Ix(t);if(!e)return mc("unexpected end of JSON input");let n=Nx(e);try{return JSON.parse(new TextDecoder("utf-8").decode(e)),null}catch{return mc(Ec(n))}}function Ix(t){try{let e=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),n=atob(e),r=new Uint8Array(n.length);for(let s=0;s<n.length;s++)r[s]=n.charCodeAt(s);return r}catch{return null}}function Nx(t){let e="";for(let n of t)e+=String.fromCharCode(n);return e}var Dx={n:"null",t:"true",f:"false"};function Ec(t){let e=0;for(;e<t.length;){let i=t.charCodeAt(e);if(i===32||i===9||i===10||i===13)e++;else break}let n=t.slice(e);if(!n)return "unexpected end of JSON input";let r=n[0],s=Dx[r];if(s){for(let i=1;i<s.length;i++){if(i>=n.length)return "unexpected end of JSON input";if(n[i]!==s[i])return `invalid character ${Sc(n[i])} in literal ${s} (expecting '${s[i]}')`}return `invalid character ${Sc(n[s.length]??" ")} after top-level value`}return r==="{"||r==="["||r==='"'||r==="-"||r>="0"&&r<="9"?"":`invalid character ${Sc(r)} looking for beginning of value`}function Sc(t){let e=t.codePointAt(0)??0;return e>=32&&e<127?`'${t}'`:`'\\u${e.toString(16).padStart(4,"0")}'`}var jx=10,Lx=4,Fx=4,Ux=31;function Mx(t=process.env){let e=t.LITE_AUTH_BCRYPT_COST;if(e!==void 0&&e.trim()!==""){let n=Number(e);if(Number.isFinite(n))return Math.min(Ux,Math.max(Fx,Math.trunc(n)))}return t.RUN_SPEC==="1"?Lx:jx}async function ys(t){return yh.hash(t,Mx())}async function xc(t,e){return yh.compare(t,e)}function bh(t,e=6,n=[]){let r=[];return t.length<e&&r.push("length"),n.length>0&&n.some(s=>!Bx(t,s))&&r.push("characters"),r}function Bx(t,e){for(let n of t)if(e.includes(n))return true;return false}function ut(t=6){let e=crypto.getRandomValues(new Uint8Array(t)),n="";for(let r=0;r<t;r++)n+=(e[r]%10).toString();return n}function Tc(){let t=crypto.getRandomValues(new Uint8Array(32));return Sh(t)}async function tt(t,e){let n=new TextEncoder().encode(t.toLowerCase()+e),r=await crypto.subtle.digest("SHA-256",n);return Sh(new Uint8Array(r))}function Sh(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}function Rc(){return v7()}function ue(){return v7()}var qx=["iss","sub","aud","iat","exp","name","family_name","given_name","middle_name","nickname","preferred_username","profile","picture","website","gender","birthdate","zoneinfo","locale","updated_at","email","phone","custom_claims","full_name","avatar_url","slug","provider_id","user_name"];function Hx(t){return !!(t==null||t===""||typeof t=="number"&&t===0||Array.isArray(t)&&t.length===0||typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0)}function _h(t){let e={};for(let n of qx){let r=t[n];Hx(r)||(e[n]=r);}return e.email_verified=t.email_verified??false,e.phone_verified=t.phone_verified??false,e}var Eh=43,xh=128,Wx="PKCE flow requires code_challenge_method and code_challenge",Kx=/^[a-zA-Z._~0-9-]+$/;function Jx(t){let e=t.length;if(e<Eh||e>xh)throw H(`code challenge has to be between ${Eh} and ${xh} characters`,400);if(!Kx.test(t))throw H("code challenge can only contain alphanumeric characters, hyphens, periods, underscores and tildes",400);return true}function Cc(t){return t.toLowerCase()}var Gx=new Set(["s256","plain"]);function Th(t,e){if(e===""!=(t===""))throw H(Wx,400);if(e!==""&&(Jx(e),!Gx.has(Cc(t))))throw H("Invalid code_challenge_method",400)}function zx(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function Vx(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return zx(new Uint8Array(n))}async function Rh(t,e,n){return e.toLowerCase()==="s256"?await Vx(n)===t:n===t}var Qx="github.com",Ch="api.github.com",Xx=["user:email"];function Yx(t){let e=t?t.split(","):[];return [...Xx,...e].join(" ")}function kc(t,e){let n=JSON.parse(e);if(typeof n.error=="string"&&n.error!=="")throw new Error(`${t}: token endpoint returned error ${n.error}`,{cause:e});if(!n.access_token)throw new Error(`${t}: server response missing access_token`,{cause:e});return n}function kh(t,e){return t?t.endsWith("/")?t.slice(0,-1):t:`https://${e}`}function Zx(t){let e=kh(t,Qx),n=kh(t,Ch);return n.endsWith(Ch)||(n+="/api/v3"),{authHost:e,apiHost:n}}function vh(t){let{authHost:e,apiHost:n}=Zx(t);return {id:"github",authorizeUrl({clientId:r,redirectUri:s,scopes:i,state:o,extraParams:a}){let l=new URLSearchParams({client_id:r,redirect_uri:s,scope:Yx(i),state:o,...a});return `${e}/login/oauth/authorize?${l.toString()}`},async exchangeCode(r,{clientId:s,secret:i,redirectUri:o,fetch:a=globalThis.fetch}){let l=new URLSearchParams({client_id:s,client_secret:i,code:r,redirect_uri:o}),c=await a(`${e}/login/oauth/access_token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:l.toString(),signal:AbortSignal.timeout(1e4)}),f=await c.text();if(c.status<200||c.status>=300)throw new Error(`github: token endpoint returned ${c.status}`,{cause:f});return kc("github",f)},async getUserData(r,{fetch:s=globalThis.fetch}){let i={Authorization:`Bearer ${r.access_token}`},o=()=>({headers:i,signal:AbortSignal.timeout(1e4)}),a=await s(`${n}/user`,o()),l=await a.text();if(a.status<200||a.status>=300)throw new Error(`github: /user returned ${a.status}`,{cause:l});let c=JSON.parse(l),f=await s(`${n}/user/emails`,o()),u=await f.text();if(f.status<200||f.status>=300)throw new Error(`github: /user/emails returned ${f.status}`,{cause:u});let d=JSON.parse(u);if(!Array.isArray(d))throw new Error("github: /user/emails did not return a JSON array");let p=String(c.id);return {claims:{iss:n,sub:p,name:c.name||void 0,preferred_username:c.login,avatar_url:c.avatar_url||void 0,full_name:c.name||void 0,provider_id:p,user_name:c.login,email_verified:false,phone_verified:false},emails:d.filter(g=>g.email).map(g=>({email:g.email,verified:g.verified,primary:g.primary}))}}}}var vc="https://accounts.google.com",rT="accounts.google.com",sT="https://accounts.google.com/o/oauth2/v2/auth",iT="https://oauth2.googleapis.com/token",oT="https://www.googleapis.com/oauth2/v3/certs",aT="https://www.googleapis.com/userinfo/v2/me",lT=["email","profile"],Oc=1e4,Ah=new Map;function Oh(t,e){return createRemoteJWKSet(new URL(t),{[customFetch]:e,timeoutDuration:Oc})}function cT(t,e){if(e!==globalThis.fetch)return Oh(t,e);let n=Ah.get(t);return n||(n=Oh(t,e),Ah.set(t,n)),n}async function uT(t,e){let n=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)),r=new Uint8Array(n).slice(0,n.byteLength/2),s="";for(let o of r)s+=String.fromCharCode(o);return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")===e}function fT(t){let e=t?t.split(","):[];return [...lT,...e].join(" ")}function Ac(t){return !!(t.verified_email||t.email_verified)}function Ph(t={}){let e=t.issuer??vc,n=e===vc?[vc,rT]:e,r=t.userInfoEndpoint??aT,s=t.getKey,i=t.clientIds??[];return {id:"google",authorizeUrl({clientId:o,redirectUri:a,scopes:l,state:c,extraParams:f}){let u=new URLSearchParams({client_id:o,redirect_uri:a,response_type:"code",scope:fT(l),state:c,...f});return `${sT}?${u.toString()}`},async exchangeCode(o,{clientId:a,secret:l,redirectUri:c,fetch:f=globalThis.fetch}){let u=new URLSearchParams({client_id:a,client_secret:l,code:o,redirect_uri:c,grant_type:"authorization_code"}),d=await f(iT,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:u.toString(),signal:AbortSignal.timeout(Oc)}),p=await d.text();if(d.status<200||d.status>=300)throw new Error(`google: token endpoint returned ${d.status}`,{cause:p});return kc("google",p)},async getUserData(o,{fetch:a=globalThis.fetch,clientId:l}){if(o.id_token){let d=s??cT(oT,a),p=i[0]??l??void 0,{payload:g}=await jwtVerify(o.id_token,d,{issuer:n,...p?{audience:p}:{}}),m=g;if(m.at_hash){if(!o.access_token)throw new Error("oidc: id_token had at_hash but no access_token was returned");if(!await uT(o.access_token,m.at_hash))throw new Error("oidc: access token hash does not match value in ID token")}let h=m.email||"",y=Ac(m),w={};return m.hd&&(w.hd=m.hd),{emails:h?[{email:h,verified:y,primary:true}]:[],claims:{iss:m.iss,sub:m.sub,name:m.name,picture:m.picture,avatar_url:m.picture,full_name:m.name,provider_id:m.sub,custom_claims:Object.keys(w).length?w:void 0,email_verified:false,phone_verified:false}}}let c=await a(r,{headers:{Authorization:`Bearer ${o.access_token}`},signal:AbortSignal.timeout(Oc)}),f=await c.text();if(c.status<200||c.status>=300)throw new Error(`google: userinfo returned ${c.status}`,{cause:f});let u=JSON.parse(f);return {emails:u.email?[{email:u.email,verified:Ac(u),primary:true}]:[],claims:{iss:r,sub:u.id,name:u.name,picture:u.picture,email:u.email,email_verified:Ac(u),avatar_url:u.picture,full_name:u.name,provider_id:u.id,phone_verified:false}}}}}function $h(t){return (t??"").split(",").map(e=>e.trim()).filter(e=>e!=="")}var Ih={github:t=>vh(t.url),google:t=>Ph({clientIds:$h(t.client_id)})},Nh=new Set(Object.keys(Ih)),Pc=["apple","azure","bitbucket","discord","facebook","github","gitlab","google","kakao","keycloak","linkedin","notion","twitch","twitter","slack","spotify","workos","zoom"],$c=["snapchat","figma","fly","linkedin_oidc","slack_oidc"],dT=new Set([...Pc,...$c]);function Ic(t,e,n){let r=(t??"").toLowerCase();if(!dT.has(r))throw H(`Unsupported provider: Provider ${r} could not be found`,400);let s=e?.[r];if(!s?.enabled)throw H("Unsupported provider: provider is not enabled",400);let i=$h(s.client_id);if(i.length===0)throw H("Unsupported provider: missing OAuth client ID",400);if(!s.secret)throw H("Unsupported provider: missing OAuth secret",400);let o=Ih[r];if(!o)throw H(`Unsupported provider: provider ${r} is not yet implemented`,400);let a=o(s);return {name:r,provider:a,config:s,clientId:i[0],clientIds:i,secret:s.secret,redirectUri:s.redirect_uri||n.defaultRedirectUri,skipNonceCheck:s.skip_nonce_check??false,emailOptional:s.email_optional??false}}var Dh=3e5,pT=1440*60*1e3;function So(t){if(!t.jwt_secret)throw new Error('[auth] is enabled but `auth.jwt_secret` is empty. Add `jwt_secret = "<secret>"` under [auth] in your config.toml.')}function mT(t){return t==="localhost"||t==="127.0.0.1"||t==="::1"}function hT(t){let e="^";for(let n=0;n<t.length;n++){let r=t[n];if(r==="\\"){let s=t[++n];s!==void 0?e+=s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):e+="\\\\";}else if(r==="*")t[n+1]==="*"?(e+=".*",n++):e+="[^./]*";else if(r==="?")e+="[^./]";else if(r==="["){let s=t.indexOf("]",n+1);if(s===-1)e+="\\[";else {let i=t.slice(n+1,s);i.startsWith("!")&&(i=`^${i.slice(1)}`),e+=`[${i}]`,n=s;}}else e+=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");}return new RegExp(`${e}$`)}function jh(t,e){let n=t.indexOf("//");if(n===-1)return e;let r=t.slice(n+2),s=r.search(/[/?#]/);s!==-1&&(r=r.slice(0,s));let i=r.lastIndexOf("@");if(i!==-1&&(r=r.slice(i+1)),r.startsWith("[")){let a=r.indexOf("]");return a===-1?r.slice(1):r.slice(1,a)}let o=r.lastIndexOf(":");return o===-1?r:r.slice(0,o)}function gT(t){let e=t,n=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(e);if(n){let r=n.slice(1).map(Number);return r.some(s=>s>255)?{isIp:false,isLoopback:false}:{isIp:true,isLoopback:r[0]===127}}return e.includes(":")?{isIp:true,isLoopback:e.toLowerCase()==="::1"}:{isIp:false,isLoopback:false}}var yT=/^[0-9]+$/,bT=/^[a-zA-Z0-9]([a-zA-Z0-9.-]*[a-zA-Z0-9])?$/;function Nc(t,e,n){if(t==="")return false;let r;try{r=new URL(t);}catch{return false}let s=r.protocol.replace(/:$/,"").toLowerCase(),i=s==="http"||s==="https",o=jh(t,r.hostname);try{let c=new URL(e);if(c.protocol===r.protocol&&jh(e,c.hostname)===o&&(c.port===r.port||mT(o)))return !0}catch{}let a=gT(o);if(yT.test(o))return false;if(a.isIp)return a.isLoopback;if(i&&!bT.test(o))return false;let l=t.split("#")[0];for(let c of n)if(hT(c).test(l))return true;return false}var bs=class t{constructor(e,n,r){this.repo=e;this.config=n;this.mailer=r;So(n),this.jwtExpiry=n.jwt_expiry??3600,this.minPasswordLength=n.minimum_password_length??6,this.passwordRequiredCharacters=n.password_required_characters??ST(n.password_requirements),this.sessionTimeboxSeconds=Uh(n.sessions?.timebox),this.sessionInactivitySeconds=Uh(n.sessions?.inactivity_timeout);}jwtExpiry;minPasswordLength;passwordRequiredCharacters;sessionTimeboxSeconds;sessionInactivitySeconds;get otpLength(){return this.config.email?.otp_length??6}get otpExpirySeconds(){return this.config.email?.otp_expiry??3600}resolveEmailRedirect(e){let n=this.config.site_url??"http://localhost:3000";return e&&Nc(e,n,this.config.additional_redirect_urls??[])?e:n}async signUp(e,n,r){if(this.config.enable_signup===false)throw po();if(!e)throw oh();if(this.config.email?.enable_signup===false)throw nh();if(n==null||n===void 0||n==="")throw H("Signup requires a valid password",400);if(!zn(e))throw H("Unable to validate email address: invalid format",400);if(n.length>72)throw H("Password cannot be longer than 72 characters",400);this.assertPasswordStrong(n);let i=!(this.config.email?.enable_confirmations??this.config.enable_confirmations??false);e=e.toLowerCase();let o=await this.repo.findUserByEmail(e);if(o)throw i?(await this.createAuditLog(o.id,e,"user_repeated_signup","user"),eh()):ho();let a=ue(),l=await ys(n),c=new Date().toISOString(),f=null,u=null,d=null;i||(f=ut(this.otpLength),u=await tt(e,f),d=c);let p={...r??{},email:e,email_verified:i,phone_verified:false,sub:a},g={...r??{},email:e,email_verified:false,phone_verified:false,sub:a},m=await this.repo.createUser({id:a,email:e,encrypted_password:l,confirmed_at:i?c:null,raw_user_meta_data:p,raw_app_meta_data:{provider:"email",providers:["email"]},confirmation_token:u,confirmation_sent_at:d});await this.repo.createIdentity({id:ue(),provider:"email",provider_id:a,user_id:a,identity_data:g}),!i&&f&&u&&await this.mailer.sendConfirmation(e,u,f,{userId:a,redirectTo:this.config.site_url});let h=await this.repo.findIdentitiesByUserId(a),y=this.repo.parseUserJson(m),w=this.mapUserToResponse(y,h,"signup");if(i){let S=await this.createSessionForUser(y,h);return await this.createAuditLog(a,e,"user_signedup","team"),{user:w,session:S}}return await this.createAuditLog(a,e,"user_confirmation_requested","user"),{user:w}}async signInWithPassword(e,n){if(!e)throw H("missing email or phone",400);if(!n)throw ct();let r=await this.repo.findUserByEmail(e.toLowerCase());if(!r||!r.encrypted_password)throw ct();let s=this.repo.parseUserJson(r);if(!s.confirmed_at)throw Gm();if(!await xc(n,s.encrypted_password))throw ct();let o=await this.repo.findIdentitiesByUserId(r.id);return this.createSessionForUser(s,o,"user")}async refreshSession(e){if(!e)throw yc();let n=await this.repo.findRefreshToken(e);if(!n)throw Mh(e)?Gn():yc();if(Bh(n))return this.refreshWithRevokedToken(n);let r=await this.repo.findUserById(n.user_id);if(!r)throw Gn();let s=null;if(n.session_id){if(s=await this.repo.findSessionById(n.session_id),!s)throw Gn();this.assertSessionRefreshable(s);}let i=Dc(s?.updated_at,s?.refreshed_at,r.updated_at,r.last_sign_in_at);await this.repo.revokeRefreshToken(n.id);let o=Rc(),a=n.session_id??ue();return n.session_id?await this.repo.updateSessionRefreshedAt(n.session_id,i):await this.repo.createSession({id:a,user_id:r.id}),await this.repo.createRefreshToken({token:o,user_id:r.id,session_id:a,parent:n.token}),await this.createAuditLog(r.id,r.email??"","token_refreshed","token",false),await this.createAuditLog(r.id,r.email??"","token_revoked","token",false),this.createRefreshResponse(r,a,o,i)}async refreshWithRevokedToken(e){if(this.config.sessions?.single_per_user)throw ih();if(!e.session_id)throw mo(e.session_id,e.user_id);let n=await this.repo.findRefreshTokensBySession(e.session_id),r=_T(n,e.token),s=r.filter(c=>!Bh(c));if((this.config.enable_refresh_token_rotation??false)&&r.length>1)throw await this.repo.revokeRefreshTokensByIds(s.map(c=>c.id)),mo(e.session_id,e.user_id);let i=s.at(-1);if(!i)throw mo(e.session_id,e.user_id);let o=await this.repo.findUserById(e.user_id);if(!o)throw Gn();let a=await this.repo.findSessionById(e.session_id);if(!a)throw Gn();this.assertSessionRefreshable(a);let l=Dc(a.updated_at,a.refreshed_at,o.updated_at,o.last_sign_in_at);return await this.repo.updateSessionRefreshedAt(e.session_id,l),await this.createAuditLog(o.id,o.email??"","token_refreshed","token",false),this.createRefreshResponse(o,e.session_id,i.token,l)}async createRefreshResponse(e,n,r,s){let i=await this.repo.updateUser(e.id,{last_sign_in_at:s}),o=this.repo.parseUserJson(i??e),a=await this.repo.findIdentitiesByUserId(e.id),l=await _c({sub:e.id,aud:e.aud||"authenticated",role:e.role||"authenticated",email:e.email??void 0,session_id:n},this.config.jwt_secret,this.jwtExpiry),c=Math.floor(Date.now()/1e3);return qh({access_token:l,refresh_token:r,token_type:"bearer",expires_in:this.jwtExpiry,expires_at:c+this.jwtExpiry,user:this.mapUserToResponse(o,a,"user")},n,e.id)}assertSessionRefreshable(e){let n=Date.now();if(this.sessionTimeboxSeconds!==void 0&&n-Date.parse(e.created_at)>this.sessionTimeboxSeconds*1e3)throw bc(void 0,e.id,e.user_id);let r=e.refreshed_at??e.created_at;if(this.sessionInactivitySeconds!==void 0&&n-Date.parse(r)>this.sessionInactivitySeconds*1e3)throw bc("inactivity",e.id,e.user_id)}async getUser(e){let n=await this.repo.findUserById(e);if(!n)throw ct();let r=this.repo.parseUserJson(n),s=await this.repo.findIdentitiesByUserId(e);return this.mapUserToResponse(r,s,"user")}async updateUser(e,n){let r=await this.repo.findUserById(e);if(!r)throw ct();let s=this.repo.parseUserJson(r),i={},o=false,a=false,l=n.data!==void 0||n.password!==void 0||n.email!==void 0;if(n.data!==void 0){let u=typeof s.raw_user_meta_data=="object"?s.raw_user_meta_data:{};i.raw_user_meta_data=Fh(u,n.data??{}),o=true;}if(n.password!==void 0){if(this.assertPasswordStrong(n.password),s.encrypted_password&&await xc(n.password,s.encrypted_password))throw sh();i.encrypted_password=await ys(n.password),i.recovery_token=null,i.recovery_sent_at=null,o=true,a=true;}if(n.email!==void 0)if(n.email==="")o=true;else {let u=n.email.toLowerCase();if(!zn(u))throw H("Unable to validate email address: invalid format",400);if(o=true,u!==s.email?.toLowerCase()){let d=await this.repo.findUserByEmail(u);if(d&&d.id!==e)throw th();let p=new Date().toISOString(),g=s.email??"",m=ut(this.otpLength),h=await tt(u,m),y=(this.config.email?.double_confirm_changes??true)&&g!=="",w=ut(this.otpLength),S=y?await tt(g,w):null;i.email_change=u,i.email_change_token_current=S,i.email_change_token_new=h,i.email_change_sent_at=p,y&&S?await this.mailer.sendEmailChange(g,S,w,{userId:e,tokenNew:m,tokenHashNew:h,redirectTo:this.config.site_url,currentEmail:g,newEmail:u}):await this.mailer.sendEmailChange(u,h,m,{userId:e,redirectTo:this.config.site_url,currentEmail:g,newEmail:u});}}l||(o=true);let c=s;if(Object.keys(i).length>0){let u=await this.repo.updateUser(e,i);if(!u)throw ct();c=this.repo.parseUserJson(u);}a&&await this.createAuditLog(e,s.email??"","user_updated_password","user",false),o&&await this.createAuditLog(e,s.email??"","user_modified","user",false);let f=await this.repo.findIdentitiesByUserId(e);return this.mapUserToResponse(c,f,"user")}async signOut(e,n,r){let s=n??"local";if(!["global","local","others"].includes(s))throw H(`Unsupported logout scope "${s}"`,400);let i=await this.repo.findUserById(r);if(!i)throw ct();let o=this.repo.parseUserJson(i);s==="global"?(await this.repo.deleteRefreshTokensForUser(r),await this.repo.deleteUserSessions(r)):s==="others"&&e?(await this.repo.deleteRefreshTokensForUser(r,e),await this.repo.deleteUserSessions(r,e)):e&&(await this.repo.deleteRefreshTokensForSession(e),await this.repo.deleteSession(e)),await this.createAuditLog(r,o.email??"","logout","account",false);}async signInWithOtp(e,n){if(!e)throw H("One of email or phone must be set",400);if(e=e.toLowerCase(),!zn(e))throw H("Unable to validate email address: invalid format",400);let r=await this.repo.findUserByEmail(e),s=!r;if(!r&&n?.shouldCreateUser!==false){let l=ue(),c=await ys(Tc()),f=new Date().toISOString();r=await this.repo.createUser({id:l,email:e,encrypted_password:c,confirmed_at:f,raw_app_meta_data:{provider:"email",providers:["email"]},raw_user_meta_data:{email:e,email_verified:true,phone_verified:false,sub:l}}),await this.repo.createIdentity({id:ue(),provider:"email",provider_id:l,user_id:l,identity_data:{email:e,email_verified:false,phone_verified:false,sub:l}});}if(!r)throw rh();let i=ut(this.otpLength),o=await tt(e,i),a=new Date().toISOString();if(await this.repo.updateUser(r.id,{recovery_token:o,recovery_sent_at:a}),await this.createAuditLog(r.id,e,"user_recovery_requested","user",false),await this.mailer.sendMagicLink(e,o,i,{userId:r.id,redirectTo:this.config.site_url}),s){let l=await this.repo.findUserById(r.id);if(!l)throw ct();let c=this.repo.parseUserJson(l),f=await this.repo.findIdentitiesByUserId(r.id);await this.createSessionForUser(c,f),await this.createAuditLog(r.id,e,"user_signedup","team");}}async requestMagicLink(e,n){if(!e)throw H("Password recovery requires an email",422);if(e=e.toLowerCase(),!zn(e))throw H("Unable to validate email address: invalid format",400);let r=await this.repo.findUserByEmail(e),s=!r;if(!r){if(this.config.enable_signup===false)throw po();let l=ue(),c=await ys(Tc()),f=new Date().toISOString();r=await this.repo.createUser({id:l,email:e,encrypted_password:c,confirmed_at:f,raw_app_meta_data:{provider:"email",providers:["email"]},raw_user_meta_data:{email:e,email_verified:true,phone_verified:false,sub:l}}),await this.repo.createIdentity({id:ue(),provider:l,provider_id:l,user_id:l,identity_data:{email:e,email_verified:false,phone_verified:false,sub:l}});}let i=ut(this.otpLength),o=await tt(e,i),a=new Date().toISOString();if(await this.repo.updateUser(r.id,{recovery_token:o,recovery_sent_at:a}),await this.createAuditLog(r.id,e,"user_recovery_requested","user",false),await this.mailer.sendMagicLink(e,o,i,{userId:r.id,redirectTo:this.config.site_url}),s){let l=await this.repo.findUserById(r.id);if(!l)throw ct();let c=this.repo.parseUserJson(l),f=await this.repo.findIdentitiesByUserId(r.id);await this.createSessionForUser(c,f),await this.createAuditLog(r.id,e,"user_signedup","team");}}async verifyOtp(e){let n;if(e.token_hash)n=e.token_hash;else if(e.email&&e.token)n=await tt(e.email.toLowerCase(),e.token);else throw gn();return await this.repo.transaction(async r=>{let s=this.repo;this.repo=r;try{let i=await this.findUserByTokenAndType(n,e.type),o=i?.user??null,a=i?.tokenColumn??null;if(!o||!a)throw gn();if(this.isTokenExpired(o,a))throw gn();if(e.type==="email_change"){let c=(this.config.email?.double_confirm_changes??!0)&&!!o.email?"email_change_token_current":"email_change_token_new";if(a!==c)throw gn()}if(!await this.repo.claimUserToken(o.id,a,n))throw gn();return await this.completeVerifyOtp(o,a,e.type)}finally{this.repo=s;}})}async completeVerifyOtp(e,n,r){let s=this.repo.parseUserJson(e),i=new Date().toISOString(),o={};if(s.confirmed_at||(o.confirmed_at=i),r==="email_change"&&s.email_change){o.email=s.email_change,o.email_change=null,o.email_change_token_current=null,o.email_change_token_new=null;let f=(await this.repo.findIdentitiesByUserId(e.id)).find(u=>u.provider==="email");if(f){let u=typeof f.identity_data=="string"?JSON.parse(f.identity_data):{...f.identity_data??{}};await this.repo.updateIdentity(f.id,{identity_data:{...u,email:s.email_change,email_verified:true}});}else await this.repo.createIdentity({id:ue(),provider:"email",provider_id:e.id,user_id:e.id,identity_data:{sub:e.id,email:s.email_change,email_verified:true,phone_verified:false}});o.raw_app_meta_data=await this.buildAppMetaDataProviders(e.id,s.raw_app_meta_data),await this.createAuditLog(e.id,s.email??"","user_modified","user",false);}else if(r==="signup"){let c=typeof s.raw_user_meta_data=="object"?s.raw_user_meta_data:{};o.raw_user_meta_data={...c,email_verified:true};let f=await this.repo.findIdentitiesByUserId(e.id);for(let u of f){let d=typeof u.identity_data=="string"?JSON.parse(u.identity_data):{...u.identity_data??{}};await this.repo.updateIdentity(u.id,{identity_data:{...d,email_verified:true}});}n&&(o[n]=null);}else n&&(o[n]=null);o.last_sign_in_at=i,await this.repo.updateUser(e.id,o);let a=await this.repo.findUserById(e.id);if(!a)throw gn();let l=await this.repo.findIdentitiesByUserId(e.id);return r==="signup"&&await this.createAuditLog(e.id,a.email??"","user_signedup","team"),this.createSessionForUser(this.repo.parseUserJson(a),l,"verify",{createLoginAudit:["magiclink","recovery"].includes(r),includeLoginProviderTrait:!["magiclink","recovery"].includes(r),authenticationMethod:["email_change","magiclink","recovery","signup"].includes(r)?"otp":"password"})}async recover(e){if(!e)throw H("Password recovery requires an email",400);if(e=e.toLowerCase(),!zn(e))throw H("Unable to validate email address: invalid format",400);let n=await this.repo.findUserByEmail(e);if(!n)return;let r=ut(this.otpLength),s=await tt(e,r),i=new Date().toISOString();await this.repo.updateUser(n.id,{recovery_token:s,recovery_sent_at:i}),await this.createAuditLog(n.id,e,"user_recovery_requested","user",false),await this.mailer.sendRecovery(e,s,r,{userId:n.id,redirectTo:this.config.site_url});}async resend(e,n){if(!["signup","email_change","sms","phone_change"].includes(e))throw H("Missing one of these types: signup, email_change, sms, phone_change",400);if((e==="signup"||e==="email_change")&&!n)throw H("Type provided requires an email address",400);if(!n)return;if(n=n.toLowerCase(),!zn(n))throw H("Unable to validate email address: invalid format",400);let r=await this.repo.findUserByEmail(n);if(!r)return;let s=ut(this.otpLength),i=new Date().toISOString();if(e==="signup"){if(r.confirmed_at||!r.confirmation_sent_at)return;throw ho()}else if(e==="email_change"){if(!r.email_change)return;if(r.email_change_sent_at)throw ho();let o=await tt(r.email_change,s);await this.repo.updateUser(r.id,{email_change_token_new:o,email_change_sent_at:i}),await this.mailer.sendEmailChange(r.email_change,o,s,{userId:r.id,redirectTo:this.config.site_url,currentEmail:r.email??void 0,newEmail:r.email_change});}}async reauthenticate(e){let n=await this.repo.findUserById(e);if(!n)throw Vm();if(!n.email)throw H("Reauthentication requires the user to have an email or a phone number",400);let r=ut(this.otpLength),s=await tt(n.email,r),i=new Date().toISOString();await this.repo.updateUser(n.id,{reauthentication_token:s,reauthentication_sent_at:i}),await this.mailer.sendReauthentication(n.email,r,{userId:n.id,tokenHash:s,redirectTo:this.config.site_url}),await this.createAuditLog(n.id,n.email??"","user_reauthenticate_requested","",false);}async createSessionForUser(e,n,r="session",s={}){let i=Dc(e.last_sign_in_at,e.updated_at),o=await this.repo.updateUser(e.id,{last_sign_in_at:i}),a=o?this.repo.parseUserJson(o):e;this.config.sessions?.single_per_user&&await this.repo.revokeUserRefreshTokens(e.id);let l=ue();await this.repo.createSession({id:l,user_id:e.id});let c=Rc();await this.repo.createRefreshToken({token:c,user_id:e.id,session_id:l}),(s.createLoginAudit??true)&&await this.createAuditLog(e.id,e.email??"","login","account",s.includeLoginProviderTrait??true,s.provider??"email",s.providerTraitKey??"provider");let f=await _c({sub:e.id,aud:e.aud||"authenticated",role:e.role||"authenticated",email:e.email??void 0,session_id:l},this.config.jwt_secret,this.jwtExpiry),u=Math.floor(Date.now()/1e3);return qh({access_token:f,refresh_token:c,token_type:"bearer",expires_in:this.jwtExpiry,expires_at:u+this.jwtExpiry,user:this.mapUserToResponse(a,n,r)},l,e.id)}assertPasswordStrong(e){let n=bh(e,this.minPasswordLength,this.passwordRequiredCharacters);if(n.length>0)throw zm(this.minPasswordLength,this.passwordRequiredCharacters,n)}mapUserToResponse(e,n,r){let s=typeof e.raw_app_meta_data=="string"?JSON.parse(e.raw_app_meta_data):e.raw_app_meta_data??{},i=typeof e.raw_user_meta_data=="string"?JSON.parse(e.raw_user_meta_data):e.raw_user_meta_data??{},o={id:e.id,aud:e.aud||"authenticated",role:e.role||"authenticated",email:e.email??"",phone:e.phone??"",app_metadata:s,user_metadata:i,identities:n.map(a=>this.mapIdentityToResponse(a,r,e)),created_at:e.created_at,updated_at:e.updated_at,is_anonymous:false};return e.confirmed_at&&(o.email_confirmed_at=e.confirmed_at,(r==="user"||r==="verify")&&(o.confirmed_at=e.confirmed_at)),e.last_sign_in_at&&(o.last_sign_in_at=e.last_sign_in_at),e.confirmation_sent_at&&(o.confirmation_sent_at=e.confirmation_sent_at),e.email_change&&(o.new_email=e.email_change),e.email_change_sent_at&&(o.email_change_sent_at=e.email_change_sent_at),r==="verify"&&e.recovery_sent_at&&(o.recovery_sent_at=e.recovery_sent_at),o}mapIdentityToResponse(e,n,r){let s=typeof e.identity_data=="string"?JSON.parse(e.identity_data):e.identity_data??{},i=n==="session"&&r.confirmed_at?{...s,email_verified:true}:s,o=e.email??(typeof i.email=="string"?i.email:r.email??void 0);return {identity_id:e.id,id:e.provider_id,user_id:e.user_id,identity_data:i,provider:e.provider,last_sign_in_at:e.last_sign_in_at??e.created_at,created_at:e.created_at,updated_at:e.updated_at,...o?{email:o}:{}}}async findUserByTokenAndType(e,n){if(n==="email_change"){let r=await this.repo.findUserByToken("email_change_token_current",e);if(r)return {user:r,tokenColumn:"email_change_token_current"};let s=await this.repo.findUserByToken("email_change_token_new",e);return s?{user:s,tokenColumn:"email_change_token_new"}:null}for(let r of this.getTokenColumnsForType(n)){let s=await this.repo.findUserByToken(r,e);if(s)return {user:s,tokenColumn:r}}return null}static SENT_AT_COLUMN={confirmation_token:"confirmation_sent_at",recovery_token:"recovery_sent_at",email_change_token_current:"email_change_sent_at",email_change_token_new:"email_change_sent_at",reauthentication_token:"reauthentication_sent_at"};isTokenExpired(e,n){let r=t.SENT_AT_COLUMN[n];if(!r)return false;let s=e[r];if(!s)return false;let i=new Date(s).getTime();return Number.isNaN(i)?false:Date.now()-i>this.otpExpirySeconds*1e3}getTokenColumnsForType(e){switch(e){case "signup":return ["confirmation_token"];case "magiclink":return ["recovery_token","confirmation_token"];case "recovery":return ["recovery_token"];case "email_change":return ["email_change_token_new","email_change_token_current"];case "reauthentication":return ["reauthentication_token"];default:return []}}async createAuditLog(e,n,r,s,i=true,o="email",a="provider"){let l={action:r,actor_id:e,actor_username:n,actor_via_sso:false,log_type:s};i&&(l.traits={[a]:o}),await this.repo.createAuditLogEntry({id:ue(),payload:l});}async createAuditLogWithTraits(e,n,r,s,i){await this.repo.createAuditLogEntry({id:ue(),payload:{action:r,actor_id:e,actor_username:n,actor_via_sso:false,log_type:s,traits:i}});}async getExternalProviderRedirectUrl(e,n){let r=e.provider??"",s=Ic(r,this.config.external,{defaultRedirectUri:n.defaultRedirectUri}),i=e.invite_token??"";if(i!==""&&!await this.repo.findUserByToken("confirmation_token",i))throw dh();let o=e.code_challenge??"",a=e.code_challenge_method??"";Th(a,o);let l=this.resolveOAuthReferrer(e.redirect_to,n.refererHeader),c={};for(let[d,p]of Object.entries(e))p!==void 0&&(["provider","scopes","code_challenge","code_challenge_method"].includes(d)||(c[d]=p));let f=ue(),u=o!==""?ue():null;return await this.repo.deleteFlowStatesCreatedBefore(new Date(Date.now()-pT).toISOString()),await this.repo.createFlowState({id:f,auth_code:u,authentication_method:"oauth",code_challenge:o!==""?o:null,code_challenge_method:o!==""?Cc(a):null,provider_type:s.name,invite_token:i!==""?i:null,referrer:l,email_optional:s.emailOptional}),s.provider.authorizeUrl({clientId:s.clientId,redirectUri:s.redirectUri,scopes:e.scopes,state:f,extraParams:c})}async loadOAuthFlowState(e){if(!e)throw wc("OAuth state parameter missing");if(!Mh(e))throw go("OAuth state parameter is invalid");let n=await this.repo.findFlowStateById(e);if(!n)throw go("OAuth state not found or expired");if(Date.now()-Date.parse(n.created_at)>Dh)throw go("OAuth state has expired");if(n.code_challenge!==null&&n.user_id!==null)throw bo();return n}resolveOAuthRedirectTarget(e){return e.referrer||this.config.site_url||"http://localhost:3000"}async handleExternalProviderCallback(e,n,r){let s=this.resolveOAuthRedirectTarget(e),i=e.provider_type,o=n.code;if(!o)throw wc("OAuth callback with missing authorization code missing");let a=Ic(i,this.config.external,{defaultRedirectUri:r.defaultRedirectUri}),l;try{l=await a.provider.exchangeCode(o,{clientId:a.clientId,secret:a.secret,redirectUri:a.redirectUri});}catch(h){throw mh(o).withInternalError(h)}let c;try{c=await a.provider.getUserData(l,{clientId:a.clientId});}catch(h){throw hh().withInternalError(h)}if(c.emails.length===0&&!e.email_optional)throw gs("Error getting user email from external provider");let f,u=false;for(let h of c.emails)if(f=h.email,u=h.verified,h.primary)break;let d={...c.claims,email:f,email_verified:u},p=_h(d),g=d.sub??"",m=await this.repo.transaction(async h=>{let y=this.repo;this.repo=h;try{let w=e.invite_token??"";if(w!==""){let v=await this.processInvite(w,i,c.emails,p,g);return await this.issueOAuthCallbackResult(v,e,l,s)}let S=await this.determineAccountLinking(c.emails,i,g),b,_,E=!1;if(S.decision==="AccountExists")b=S.user,_=S.identity.id,await this.repo.updateIdentity(_,{identity_data:p,last_sign_in_at:new Date().toISOString()}),await this.updateUserMetaDataAndProviders(b.id,p);else if(S.decision==="LinkAccount"){b=S.user;let v=await this.repo.createIdentity({id:ue(),provider:i,provider_id:g,user_id:b.id,identity_data:p});_=v.id,await this.updateUserMetaDataAndProviders(b.id,p),await this.createAuditLogWithTraits(b.id,b.email??"","identity_linked","user",{identity_id:v.id,provider:i,provider_id:g});}else if(S.decision==="CreateAccount"){if(this.config.enable_signup===!1)throw po();E=!0;let v=ue();b=await this.repo.createUser({id:v,email:S.candidateEmail.email||null,raw_app_meta_data:{provider:i,providers:[i]},raw_user_meta_data:p}),_=(await this.repo.createIdentity({id:ue(),provider:i,provider_id:g,user_id:v,identity_data:p})).id;}else throw gs("Multiple accounts with the same email address in the same linking domain detected: default");let x=this.repo.parseUserJson(await this.repo.findUserById(b.id));if(wT(x))throw fh();if(!(e.email_optional&&S.candidateEmail.email==="")&&!x.confirmed_at){await this.removeUnconfirmedIdentities(x.id,_,p);let v=!(this.config.email?.enable_confirmations??this.config.enable_confirmations??!1);if(S.candidateEmail.verified||v)await this.createAuditLog(x.id,S.candidateEmail.email,"user_signedup","team",!0,i),await this.repo.updateUser(x.id,{confirmed_at:new Date().toISOString(),raw_user_meta_data:{...p,email_verified:!0}});else {let P=!1;if(S.candidateEmail.email){let C=ut(this.otpLength),R=await tt(S.candidateEmail.email,C),U=new Date().toISOString();await this.repo.updateUser(x.id,{confirmation_token:R,confirmation_sent_at:U}),await this.mailer.sendConfirmation(S.candidateEmail.email,R,C,{userId:x.id,redirectTo:this.config.site_url}),P=!0;}return {commitError:uh(P?`Unverified email with ${i}. A confirmation email has been sent to your ${i} email`:`Unverified email with ${i}. Verify the email with ${i} in order to sign in`)}}}else await this.createAuditLog(x.id,x.email??"","login","account",!0,i);return await this.issueOAuthCallbackResult(x,e,l,s)}finally{this.repo=y;}});if(m.commitError)throw m.commitError;return m}async issueOAuthCallbackResult(e,n,r,s){if(n.code_challenge!=null&&n.auth_code!=null){if(!await this.repo.claimFlowStateForPkce(n.id,{user_id:e.id,provider_access_token:r.access_token??"",provider_refresh_token:r.refresh_token??"",auth_code_issued_at:new Date().toISOString()}))throw bo();let m=new URL(s);return m.searchParams.set("code",n.auth_code),{commitError:void 0,type:"pkce",redirectUrl:m.toString()}}let o=this.repo.parseUserJson(await this.repo.findUserById(e.id)),a=await this.repo.findIdentitiesByUserId(e.id),l=await this.createSessionForUser(o,a,"session",{createLoginAudit:false});if(!await this.repo.deleteFlowState(n.id))throw bo();let f={access_token:l.access_token,expires_at:String(l.expires_at),expires_in:String(l.expires_in),provider_token:r.access_token??""};r.refresh_token&&(f.provider_refresh_token=r.refresh_token),f.refresh_token=l.refresh_token,f.sb="",f.token_type=l.token_type;let d=Object.keys(f).sort().map(g=>`${encodeURIComponent(g)}=${encodeURIComponent(f[g])}`).join("&"),p=new URL(s);return p.hash=d,{commitError:void 0,type:"implicit",redirectUrl:p.toString()}}async processInvite(e,n,r,s,i){let o=await this.repo.findUserByToken("confirmation_token",e);if(!o)throw ph();let a=this.repo.parseUserJson(o),l=(a.email??"").toLowerCase();if(!r.some(u=>u.email.toLowerCase()===l))throw H("Invited email does not match emails from external provider",400);let f=await this.repo.createIdentity({id:ue(),provider:n,provider_id:i,user_id:a.id,identity_data:s});return await this.updateUserMetaDataAndProviders(a.id,s),await this.createAuditLog(a.id,a.email??"","invite_accepted","account",true,n),await this.removeUnconfirmedIdentities(a.id,f.id,s),await this.repo.updateUser(a.id,{confirmation_token:null,confirmed_at:new Date().toISOString(),raw_user_meta_data:{...s,email_verified:true}}),this.repo.parseUserJson(await this.repo.findUserById(a.id))}async exchangePkceCode(e,n){if(!e||!n)throw H("invalid request: both auth code and code verifier should be non-empty",400);let r=await this.repo.findFlowStateByAuthCode(e);if(!r||!r.user_id)throw yo();if(Date.now()-Date.parse(r.created_at)>Dh)throw lh();if(!await Rh(r.code_challenge??"",r.code_challenge_method??"",n))throw ch("code challenge does not match previously saved code verifier");return {...await this.repo.transaction(async o=>{let a=this.repo;this.repo=o;try{if(!await this.repo.deleteFlowState(r.id))throw yo();let c=await this.repo.findUserById(r.user_id);if(!c)throw yo();let f=this.repo.parseUserJson(c),u=await this.repo.findIdentitiesByUserId(c.id);return await this.createSessionForUser(f,u,"session",{includeLoginProviderTrait:!0,provider:r.provider_type,providerTraitKey:"provider_type"})}finally{this.repo=a;}}),...r.provider_access_token?{provider_token:r.provider_access_token}:{},...r.provider_refresh_token?{provider_refresh_token:r.provider_refresh_token}:{}}}resolveOAuthReferrer(e,n){let r=this.config.site_url??"http://localhost:3000",s=this.config.additional_redirect_urls??[];return e&&Nc(e,r,s)?e:n&&Nc(n,r,s)?n:r}async updateUserMetaDataAndProviders(e,n){let r=await this.repo.findUserById(e);if(!r)return;let s=this.repo.parseUserJson(r),i=typeof s.raw_user_meta_data=="object"?s.raw_user_meta_data:{},o=Fh(i,n),a=await this.buildAppMetaDataProviders(e,s.raw_app_meta_data);await this.repo.updateUser(e,{raw_user_meta_data:o,raw_app_meta_data:a});}async buildAppMetaDataProviders(e,n){let r=typeof n=="object"&&n?{...n}:{},i=[...await this.repo.findIdentitiesByUserId(e)].sort((a,l)=>Date.parse(a.created_at)-Date.parse(l.created_at)),o=[];for(let a of i)o.includes(a.provider)||o.push(a.provider);return r.providers=o,o.length>0&&(r.provider=o[0]),r}async removeUnconfirmedIdentities(e,n,r){await this.repo.deleteIdentitiesExcept(e,n);let s=await this.repo.findUserById(e),i=await this.buildAppMetaDataProviders(e,s?this.repo.parseUserJson(s).raw_app_meta_data:{});await this.repo.updateUser(e,{raw_user_meta_data:r,raw_app_meta_data:i,encrypted_password:null});}async determineAccountLinking(e,n,r){let s=e.find(p=>p.primary),i=s?{email:s.email.toLowerCase(),verified:s.verified}:{email:"",verified:false},o=r?await this.repo.findIdentityByProviderAndId(n,r):null;if(o){let p=await this.repo.findUserById(o.user_id);if(!p)throw new Error("Database error finding user for existing identity");return i={email:(p.email??"").toLowerCase(),verified:i.verified},{decision:"AccountExists",user:p,identity:o,candidateEmail:i}}let a=!(this.config.email?.enable_confirmations??this.config.enable_confirmations??false),l=Array.from(new Set(e.filter(p=>p.verified||a).map(p=>p.email.toLowerCase())));if(l.length===0)return i.email&&await this.repo.findUserByEmail(i.email)&&(i={...i,email:""}),{decision:"CreateAccount",candidateEmail:i};let c=await this.repo.findIdentitiesByEmails(l),f=Array.from(new Set(c.map(p=>p.user_id))),d=(await Promise.all(f.map(p=>this.repo.findUserById(p)))).filter(p=>p!==null).filter(p=>!Lh(p));if(d.length===0){let p=await Promise.all(l.map(m=>this.repo.findUserByEmail(m))),g=new Map;for(let m of p)m&&!Lh(m)&&g.set(m.id,m);d=Array.from(g.values());}return d.length===0?{decision:"CreateAccount",candidateEmail:i}:d.length>1?{decision:"MultipleAccounts"}:{decision:"LinkAccount",user:d[0],candidateEmail:i}}};function Lh(t){return t.is_sso_user===true||t.is_sso_user===1}function wT(t){return t.banned_until?Date.parse(t.banned_until)>Date.now():false}function Fh(t,e){let n={...t};for(let[r,s]of Object.entries(e))s===null?delete n[r]:n[r]=s;return n}function ST(t){switch(t){case "letters_digits":return ["abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ","0123456789"];case "lower_upper_letters_digits":return ["abcdefghijklmnopqrstuvwxyz","ABCDEFGHIJKLMNOPQRSTUVWXYZ","0123456789"];case "lower_upper_letters_digits_symbols":return ["abcdefghijklmnopqrstuvwxyz","ABCDEFGHIJKLMNOPQRSTUVWXYZ","0123456789","!@#$%^&*"];default:return []}}function Uh(t){if(!t)return;let e=t.match(/^(\d+)(ms|s|m|h)?$/);if(!e)return;let n=Number(e[1]);switch(e[2]??"s"){case "ms":return n/1e3;case "m":return n*60;case "h":return n*3600;default:return n}}function zn(t){return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}function Mh(t){return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)}function Bh(t){return t.revoked===true||t.revoked===1}function _T(t,e){let n=[],r=[e];for(;r.length>0;){let s=r.shift();for(let i of t)i.parent!==s||n.some(o=>o.id===i.id)||(n.push(i),r.push(i.token));}return n}function Dc(...t){let e=Math.max(0,...t.map(r=>r?Date.parse(r):0)),n=Date.now();return new Date(Math.max(n,e+1)).toISOString()}function qh(t,e,n){return Object.defineProperties(t,{session_id:{value:e,enumerable:false},user_id:{value:n,enumerable:false}}),t}var ET=100;function ws(t){if(t==null)return {};if(typeof t=="string")try{return JSON.parse(t)}catch{return {}}return t}function yn(t){return typeof t=="string"?t:JSON.stringify(t??{})}var Ss=class t{constructor(e,n,r=s=>e.transaction().execute(s)){this.db=e;this.dialect=n;this.runInTransaction=r;this.schema="auth";}schema;bool(e){return this.dialect==="sqlite"?e?1:0:e}async transaction(e){return this.runInTransaction(n=>e(new t(n,this.dialect,this.runInTransaction)))}table(e){return this.db.withSchema(this.schema).selectFrom(e)}insertInto(e){return this.db.withSchema(this.schema).insertInto(e)}update(e){return this.db.withSchema(this.schema).updateTable(e)}deleteFrom(e){return this.db.withSchema(this.schema).deleteFrom(e)}async findUserByEmail(e){return await this.table("users").selectAll().where("email","=",e.toLowerCase()).executeTakeFirst()??null}async findUserById(e){return await this.table("users").selectAll().where("id","=",e).executeTakeFirst()??null}async findUserByToken(e,n){return await this.table("users").selectAll().where(e,"=",n).executeTakeFirst()??null}async claimUserToken(e,n,r){let s=await this.update("users").set({[n]:null}).where("id","=",e).where(n,"=",r).executeTakeFirst();return Number(s.numUpdatedRows??0)>0}async createUser(e){let n=new Date().toISOString(),r={id:e.id,aud:e.aud??"authenticated",role:e.role??"authenticated",email:e.email?e.email.toLowerCase():null,encrypted_password:e.encrypted_password??null,phone:e.phone??null,email_confirmed_at:e.email_confirmed_at??e.confirmed_at??null,confirmation_token:e.confirmation_token??null,confirmation_sent_at:e.confirmation_sent_at??null,recovery_token:e.recovery_token??null,recovery_sent_at:e.recovery_sent_at??null,email_change:e.email_change??null,email_change_token_new:e.email_change_token_new??null,email_change_token_current:e.email_change_token_current??null,email_change_sent_at:e.email_change_sent_at??null,email_change_confirm_status:e.email_change_confirm_status??0,reauthentication_token:e.reauthentication_token??null,reauthentication_sent_at:e.reauthentication_sent_at??null,raw_app_meta_data:yn(e.raw_app_meta_data??{provider:"email",providers:["email"]}),raw_user_meta_data:yn(e.raw_user_meta_data??{}),is_sso_user:this.bool(e.is_sso_user??false),is_anonymous:this.bool(e.is_anonymous??false),last_sign_in_at:e.last_sign_in_at??null,created_at:n,updated_at:n};return await this.insertInto("users").values(r).execute(),await this.findUserById(e.id)}async updateUser(e,n){let r={...n,updated_at:new Date().toISOString()};return r.confirmed_at!=null&&r.email_confirmed_at==null&&(r.email_confirmed_at=r.confirmed_at),delete r.confirmed_at,r.raw_app_meta_data!=null&&(r.raw_app_meta_data=yn(r.raw_app_meta_data)),r.raw_user_meta_data!=null&&(r.raw_user_meta_data=yn(r.raw_user_meta_data)),r.is_sso_user!=null&&(r.is_sso_user=this.bool(!!r.is_sso_user)),r.is_anonymous!=null&&(r.is_anonymous=this.bool(!!r.is_anonymous)),await this.update("users").set(r).where("id","=",e).execute(),this.findUserById(e)}async createSession(e){let n=new Date().toISOString(),r={id:e.id,user_id:e.user_id,aal:e.aal??"aal1",not_after:null,refreshed_at:null,user_agent:null,ip:null,tag:null,refresh_token_hmac_key:null,refresh_token_counter:null,scopes:null,factor_id:null,created_at:n,updated_at:n};return await this.insertInto("sessions").values(r).execute(),r}async findSessionById(e){return await this.table("sessions").selectAll().where("id","=",e).executeTakeFirst()??null}async updateSessionRefreshedAt(e,n){return await this.update("sessions").set({refreshed_at:n,updated_at:n}).where("id","=",e).execute(),this.findSessionById(e)}async deleteSession(e){await this.deleteFrom("sessions").where("id","=",e).execute();}async deleteUserSessions(e,n){let r=this.deleteFrom("sessions").where("user_id","=",e);n&&(r=r.where("id","!=",n)),await r.execute();}async deleteRefreshTokensForSession(e){await this.deleteFrom("refresh_tokens").where("session_id","=",e).execute();}async deleteRefreshTokensForUser(e,n){let r=this.deleteFrom("refresh_tokens").where("user_id","=",e);n&&(r=r.where("session_id","!=",n)),await r.execute();}async createRefreshToken(e){let n=new Date().toISOString(),r={id:ue(),token:e.token,user_id:e.user_id,session_id:e.session_id,revoked:this.bool(false),parent:e.parent??null,created_at:n,updated_at:n};return await this.insertInto("refresh_tokens").values(r).execute(),r}async findRefreshToken(e){return await this.table("refresh_tokens").selectAll().where("token","=",e).executeTakeFirst()??null}async findRefreshTokensBySession(e){return await this.table("refresh_tokens").selectAll().where("session_id","=",e).execute()}async revokeRefreshToken(e){await this.update("refresh_tokens").set({revoked:this.bool(true),updated_at:new Date().toISOString()}).where("id","=",e).execute();}async revokeSessionRefreshTokens(e){await this.update("refresh_tokens").set({revoked:this.bool(true),updated_at:new Date().toISOString()}).where("session_id","=",e).execute();}async revokeRefreshTokensByIds(e){e.length!==0&&await this.update("refresh_tokens").set({revoked:this.bool(true),updated_at:new Date().toISOString()}).where("id","in",e).execute();}async revokeUserRefreshTokens(e){await this.update("refresh_tokens").set({revoked:this.bool(true),updated_at:new Date().toISOString()}).where("user_id","=",e).execute();}async createIdentity(e){let n=new Date().toISOString(),r={id:e.id,provider:e.provider,provider_id:e.provider_id,user_id:e.user_id,identity_data:yn(e.identity_data),last_sign_in_at:e.last_sign_in_at??n,created_at:n,updated_at:n};return await this.insertInto("identities").values(r).execute(),{...r,identity_data:e.identity_data}}async findIdentitiesByUserId(e){return (await this.table("identities").selectAll().where("user_id","=",e).execute()).map(r=>({...r,identity_data:ws(r.identity_data)}))}async updateIdentity(e,n){let r={...n,updated_at:new Date().toISOString()};r.identity_data!=null&&(r.identity_data=yn(r.identity_data)),delete r.email,await this.update("identities").set(r).where("id","=",e).execute();}async deleteIdentitiesExcept(e,n){await this.deleteFrom("identities").where("user_id","=",e).where("id","!=",n).execute();}async findIdentityByProviderAndId(e,n){let r=await this.table("identities").selectAll().where("provider","=",e).where("provider_id","=",n).executeTakeFirst();if(!r)return null;let s=r;return {...s,identity_data:ws(s.identity_data)}}async findIdentitiesByEmails(e){return e.length===0?[]:(await this.table("identities").selectAll().where("email","in",e.map(r=>r.toLowerCase())).execute()).map(r=>({...r,identity_data:ws(r.identity_data)}))}async createFlowState(e){let n=new Date().toISOString(),r={id:e.id,user_id:e.user_id??null,auth_code:e.auth_code??null,authentication_method:e.authentication_method,code_challenge_method:e.code_challenge_method??null,code_challenge:e.code_challenge??null,provider_type:e.provider_type,provider_access_token:"",provider_refresh_token:"",auth_code_issued_at:null,invite_token:e.invite_token??null,referrer:e.referrer??null,oauth_client_state_id:e.oauth_client_state_id??null,linking_target_id:e.linking_target_id??null,email_optional:this.bool(e.email_optional??false),created_at:n,updated_at:n};return await this.insertInto("flow_state").values(r).execute(),r}async findFlowStateById(e){return await this.table("flow_state").selectAll().where("id","=",e).executeTakeFirst()??null}async findFlowStateByAuthCode(e){return await this.table("flow_state").selectAll().where("auth_code","=",e).executeTakeFirst()??null}async updateFlowState(e,n){let r={...n,updated_at:new Date().toISOString()};r.email_optional!=null&&(r.email_optional=this.bool(!!r.email_optional)),await this.update("flow_state").set(r).where("id","=",e).execute();}async claimFlowStateForPkce(e,n){let r=await this.update("flow_state").set({...n,updated_at:new Date().toISOString()}).where("id","=",e).where("user_id","is",null).executeTakeFirst();return Number(r.numUpdatedRows??0)>0}async deleteFlowStatesCreatedBefore(e){let n=await this.deleteFrom("flow_state").where("id","in",this.db.selectFrom("flow_state").select("id").where("created_at","<",e).limit(ET)).executeTakeFirst();return Number(n.numDeletedRows??0)}async deleteFlowState(e){let n=await this.deleteFrom("flow_state").where("id","=",e).executeTakeFirst();return Number(n.numDeletedRows??0)>0}async createAuditLogEntry(e){let n={id:e.id,payload:yn(e.payload??{}),ip_address:e.ip_address??"",created_at:new Date().toISOString()};await this.insertInto("audit_log_entries").values(n).execute();}parseUserJson(e){return {...e,raw_app_meta_data:ws(e.raw_app_meta_data),raw_user_meta_data:ws(e.raw_user_meta_data),confirmed_at:e.confirmed_at??e.email_confirmed_at??null}}};var Vn=class{maxSizeBytes;now;entries=new Map;sizeBytes=0;constructor(e={}){this.maxSizeBytes=e.maxSizeBytes??1024*1024,this.now=e.now??Date.now;}async get(e){let n=this.entries.get(e);if(n){if(this.isExpired(n)){this.deleteEntry(e,n);return}return this.entries.delete(e),this.entries.set(e,n),n.value}}async set(e,n,r){let s=this.entries.get(e);s&&this.deleteEntry(e,s);let i={value:n,size:Hh(e)+Hh(n),expiresAt:r?.ttl&&r.ttl>0?this.now()+r.ttl*1e3:void 0};this.entries.set(e,i),this.sizeBytes+=i.size,this.evictToSize();}async delete(e){let n=this.entries.get(e);n&&this.deleteEntry(e,n);}isExpired(e){return typeof e.expiresAt=="number"&&e.expiresAt<=this.now()}evictToSize(){for(;this.sizeBytes>this.maxSizeBytes;){let e=this.entries.keys().next().value;if(typeof e!="string")break;let n=this.entries.get(e);if(!n)break;this.deleteEntry(e,n);}}deleteEntry(e,n){this.entries.delete(e),this.sizeBytes-=n.size;}};function Hh(t){return new TextEncoder().encode(t).byteLength}var _o=class{constructor(e){this.options=e;}async get(e){return await this.options.namespace.get(e)??void 0}async set(e,n,r){await this.options.namespace.put(e,n,{...r?.ttl&&r.ttl>0?{expirationTtl:r.ttl}:{}});}async delete(e){await this.options.namespace.delete(e);}};var Eo=class{constructor(e){this.options=e;}async get(e){return await this.options.client.get(e)??void 0}async set(e,n,r){if(r?.ttl&&r.ttl>0){await this.options.client.set(e,n,"EX",r.ttl);return}await this.options.client.set(e,n);}async delete(e){if(this.options.client.del){await this.options.client.del(e);return}if(this.options.client.delete){await this.options.client.delete(e);return}throw new Error("RedisCacheDriver client must provide del() or delete()")}};var xo=class{constructor(e){this.options=e;this.endpoint=e.endpoint??"https://api.resend.com/emails",this.fetchFn=e.fetch??fetch;}endpoint;fetchFn;async send(e){let n=await this.fetchFn(this.endpoint,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${this.options.apiKey}`},body:JSON.stringify({from:this.options.from,to:e.to,subject:e.subject,...e.text?{text:e.text}:{},...e.html?{html:e.html}:{}})});if(!n.ok)throw new Error(`Resend email failed (${n.status}): ${await n.text()}`)}};var Ro=class{constructor(e){this.options=e;this.endpoint=`https://email.${e.region}.amazonaws.com/v2/email/outbound-emails`,this.client=e.client;}endpoint;client;async send(e){let n=await this.getClient(),r={FromEmailAddress:this.options.from,Destination:{ToAddresses:[e.to]},Content:{Simple:{Subject:{Data:e.subject,Charset:"UTF-8"},Body:{...e.text?{Text:{Data:e.text,Charset:"UTF-8"}}:{},...e.html?{Html:{Data:e.html,Charset:"UTF-8"}}:{}}}}},s=await n.fetch(this.endpoint,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw new Error(`AWS SES email failed (${s.status}): ${await s.text()}`)}async getClient(){if(this.client)return this.client;let{AwsClient:e}=await Promise.resolve().then(()=>(zh(),Gh));return this.client=new e({accessKeyId:this.options.accessKeyId,secretAccessKey:this.options.secretAccessKey,service:"ses",region:this.options.region}),this.client}};var Co=class{constructor(e){this.options=e;this.sendmailPath=e.sendmailPath??"/usr/sbin/sendmail";}sendmailPath;async send(e){let{spawn:n}=await import('node:child_process').catch(()=>{throw new Error("SendmailEmailDriver requires a Node-compatible runtime")}),r=Uc(this.options.from,e);await new Promise((s,i)=>{let o=n(this.sendmailPath,["-t","-i"],{stdio:["pipe","ignore","pipe"]}),a=[];o.on("error",l=>{i(new Error(`SendmailEmailDriver failed to start ${this.sendmailPath}: ${l.message}`));}),o.stderr?.on("data",l=>a.push(Buffer.from(l))),o.on("close",l=>{if(l===0){s();return}i(new Error(`SendmailEmailDriver exited with code ${l}: ${Buffer.concat(a).toString("utf8")}`));}),o.stdin.end(r);});}};function Uc(t,e){let n=e.html?"text/html; charset=UTF-8":"text/plain; charset=UTF-8";return [`From: ${t}`,`To: ${e.to}`,`Subject: ${e.subject}`,"MIME-Version: 1.0",`Content-Type: ${n}`,"",e.html??e.text??""].join(`
87
+ `)}Il();function ko(t){let e=t.port??587,n=t.timeoutMs??3e4,r=!!(t.user&&t.pass),s=r?{user:t.user,pass:t.pass}:void 0,i=t.secure??e===465;return {host:t.host,port:e,secure:i,...s?{auth:s}:{},requireTLS:t.requireTls??(r&&!i),...t.rejectUnauthorized===false?{tls:{rejectUnauthorized:false}}:{},connectionTimeout:n,greetingTimeout:n,socketTimeout:n}}function Mc(t,e){return {from:t,to:e.to,subject:e.subject,...e.text!==void 0?{text:e.text}:{},...e.html!==void 0?{html:e.html}:{}}}function Bc(t){if(!t)throw new Error("SMTP email is not supported in this runtime (SmtpEmailDriver requires Node or Bun)")}var CT="nodemailer",Qn=class{constructor(e){this.options=e;}transporter;async send(e){Bc(!Lp()&&(jp()||$l()));let n=await this.getTransporter();try{await n.sendMail(Mc(this.options.from,e));}catch(r){let s=r instanceof Error?r.message:String(r);throw new Error(`SmtpEmailDriver send failed: ${s}`,{cause:r})}}async getTransporter(){if(this.transporter)return this.transporter;if(this.options.createTransport)return this.transporter=this.options.createTransport(ko(this.options)),this.transporter;let e=await import(CT);return this.transporter=e.createTransport(ko(this.options)),this.transporter}};var Es=class{messages=new Map;maxKeepCount;order=[];constructor(e={}){this.maxKeepCount=e.maxKeepCount??100;}async send(e){if(this.maxKeepCount<=0)return;let n=e.to.toLowerCase(),r={...e,sentAt:new Date().toISOString()},s=this.messages.get(n)??[];s.push(r),this.messages.set(n,s),this.order.push({key:n,message:r}),this.trim();}clear(){this.messages.clear(),this.order.length=0;}trim(){for(;this.order.length>this.maxKeepCount;){let e=this.order.shift();if(!e)return;let n=this.messages.get(e.key);if(!n)continue;let r=n.indexOf(e.message);r>=0&&n.splice(r,1),n.length===0&&this.messages.delete(e.key);}}},Xn=class extends Es{silent;logger;constructor(e={}){super({maxKeepCount:0}),this.silent=e.silent??false,this.logger=e.logger??console;}async send(e){if(await super.send(e),!this.silent){let n=e.text?e.text:"(html-only email, body omitted)";this.logger.info(["[@supabase/lite] email captured (not delivered)",`To: ${e.to}`,`Subject: ${e.subject}`,"",n].join(`
88
88
  `));}}};var xs=class{silent;logger;constructor(e={}){this.silent=e.silent??false,this.logger=e.logger??console;}async send(e){this.silent||this.logger.info(["[@supabase/lite] SMS driver noop send",`To: ${e.to}`,`Body: ${e.body}`].join(`
89
- `));}};function ET(t){let e=t?.auth?.email?.smtp;if(e?.enabled!==true)return;if(!e.host)throw new Error("Missing required field in config: auth.email.smtp.host");if(!e.port)throw new Error("Missing required field in config: auth.email.smtp.port");if(!e.user)throw new Error("Missing required field in config: auth.email.smtp.user");if(!e.pass)throw new Error("Missing required field in config: auth.email.smtp.pass");if(!e.admin_email)throw new Error("Missing required field in config: auth.email.smtp.admin_email");let n=e.sender_name?{name:e.sender_name,address:e.admin_email}:e.admin_email;return new Qn({host:e.host,port:e.port,user:e.user,pass:e.pass,from:n})}function Gh(t={},e){return {email:t.email??ET(e)??new Yn,sms:t.sms??new xs,cache:t.cache??new Vn}}var xT="/auth/v1/verify";function zh(t,e,n,r){let s=new URL(xT,TT(t));return s.searchParams.set("token",e),s.searchParams.set("type",n),s.searchParams.set("redirect_to",r),s.toString()}function TT(t){return t.endsWith("/")?t:`${t}/`}function Co(t,e){return t.replace(/\{\{\s*\.(\w+)\s*\}\}/g,(n,r)=>r in e?e[r]??"":n)}var Vh={invite:"You have been invited",confirmation:"Confirm Your Signup",recovery:"Reset Your Password",magic_link:"Your Magic Link",email_change:"Confirm Email Change",reauthentication:"Confirm Reauthentication"},Ro="-apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial,sans-serif,'Apple Color Emoji','Segoe UI Emoji'";function Xn(t,e){return `<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
89
+ `));}};function kT(t){let e=t?.auth?.email?.smtp;if(e?.enabled!==true)return;if(!e.host)throw new Error("Missing required field in config: auth.email.smtp.host");if(!e.port)throw new Error("Missing required field in config: auth.email.smtp.port");if(!e.user)throw new Error("Missing required field in config: auth.email.smtp.user");if(!e.pass)throw new Error("Missing required field in config: auth.email.smtp.pass");if(!e.admin_email)throw new Error("Missing required field in config: auth.email.smtp.admin_email");let n=e.sender_name?{name:e.sender_name,address:e.admin_email}:e.admin_email;return new Qn({host:e.host,port:e.port,user:e.user,pass:e.pass,from:n})}function Vh(t={},e){return {email:t.email??kT(e)??new Xn,sms:t.sms??new xs,cache:t.cache??new Vn}}var vT="/auth/v1/verify";function Qh(t,e,n,r){let s=new URL(vT,AT(t));return s.searchParams.set("token",e),s.searchParams.set("type",n),s.searchParams.set("redirect_to",r),s.toString()}function AT(t){return t.endsWith("/")?t:`${t}/`}function Ao(t,e){return t.replace(/\{\{\s*\.(\w+)\s*\}\}/g,(n,r)=>r in e?e[r]??"":n)}var Xh={invite:"You have been invited",confirmation:"Confirm Your Signup",recovery:"Reset Your Password",magic_link:"Your Magic Link",email_change:"Confirm Email Change",reauthentication:"Confirm Reauthentication"},vo="-apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial,sans-serif,'Apple Color Emoji','Segoe UI Emoji'";function Yn(t,e){return `<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
90
90
  <html xmlns="http://www.w3.org/1999/xhtml" lang="en">
91
91
  <head>
92
92
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
@@ -105,16 +105,16 @@ ${s}`)}return t}var Gu=[{name:"Self-hosted Logflare Configuration",link:"https:/
105
105
  :root { color-scheme: light dark; supported-color-schemes: light dark }
106
106
  </style>
107
107
  </head>
108
- <body style="height:100%;margin:0;-webkit-text-size-adjust:none;font-family:${Ro};background-color:#FFFFFF;color:#687076;width:100% !important;">
108
+ <body style="height:100%;margin:0;-webkit-text-size-adjust:none;font-family:${vo};background-color:#FFFFFF;color:#687076;width:100% !important;">
109
109
  <table class="email-wrapper" width="100%" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;margin:0;padding:0;background-color:#FFFFFF;">
110
110
  <tr>
111
- <td align="center" style="font-family:${Ro};font-size:16px;padding:0;">
111
+ <td align="center" style="font-family:${vo};font-size:16px;padding:0;">
112
112
  <table class="email-content" width="100%" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;margin:0;padding:0;">
113
113
  <tr>
114
- <td class="email-body" width="570" cellpadding="0" cellspacing="0" style="font-family:${Ro};font-size:16px;padding:0;width:100%;margin:0;">
114
+ <td class="email-body" width="570" cellpadding="0" cellspacing="0" style="font-family:${vo};font-size:16px;padding:0;width:100%;margin:0;">
115
115
  <table class="email-body_inner" align="center" width="570" cellpadding="0" cellspacing="0" role="presentation" style="width:570px;margin:0 auto;padding:0;background-color:#FFFFFF;">
116
116
  <tr>
117
- <td class="content-cell" style="font-family:${Ro};font-size:16px;padding:15px;">
117
+ <td class="content-cell" style="font-family:${vo};font-size:16px;padding:15px;">
118
118
  <h1 style="margin:0;color:#1C1C1C;font-size:22px;font-weight:600;">${t}</h1>
119
119
  ${e}
120
120
  <p style="margin:1.5em 0 0;font-size:13px;line-height:1.625;color:#A8AAAF;text-align:left;">Powered by Supabase Lite</p>
@@ -133,20 +133,20 @@ ${s}`)}return t}var Gu=[{name:"Self-hosted Logflare Configuration",link:"https:/
133
133
  </div>`}function Rs(){return `<p style="margin:0.4em 0 0.5em;font-size:16px;line-height:1.625;color:#687076;">Or enter this code:</p>
134
134
  <div class="code-box" style="background-color:#f4f4f4;border:1px solid #eee;border-radius:5px;padding:24px 10px;text-align:center;">
135
135
  <span style="font-size:28px;font-weight:700;letter-spacing:6px;color:#1C1C1C;">{{ .Token }}</span>
136
- </div>`}var RT={signup:Xn("Confirm your signup",`${Zn("Follow this link to confirm your account:")}
136
+ </div>`}var OT={signup:Yn("Confirm your signup",`${Zn("Follow this link to confirm your account:")}
137
137
  ${Ts("{{ .ConfirmationURL }}","Confirm your email")}
138
- ${Rs()}`),recovery:Xn("Reset your password",`${Zn("Follow this link to reset the password for your account:")}
138
+ ${Rs()}`),recovery:Yn("Reset your password",`${Zn("Follow this link to reset the password for your account:")}
139
139
  ${Ts("{{ .ConfirmationURL }}","Reset password")}
140
- ${Rs()}`),magiclink:Xn("Your magic link",`${Zn("Follow this link to sign in:")}
140
+ ${Rs()}`),magiclink:Yn("Your magic link",`${Zn("Follow this link to sign in:")}
141
141
  ${Ts("{{ .ConfirmationURL }}","Sign in")}
142
- ${Rs()}`),email_change:Xn("Confirm your new email",`${Zn("Follow this link to confirm the update of your email from {{ .Email }} to {{ .NewEmail }}:")}
142
+ ${Rs()}`),email_change:Yn("Confirm your new email",`${Zn("Follow this link to confirm the update of your email from {{ .Email }} to {{ .NewEmail }}:")}
143
143
  ${Ts("{{ .ConfirmationURL }}","Change email")}
144
- ${Rs()}`),invite:Xn("You have been invited",`${Zn("You have been invited to create a user. Follow this link to accept the invite:")}
144
+ ${Rs()}`),invite:Yn("You have been invited",`${Zn("You have been invited to create a user. Follow this link to accept the invite:")}
145
145
  ${Ts("{{ .ConfirmationURL }}","Accept the invite")}
146
- ${Rs()}`),reauthentication:Xn("Confirm reauthentication",`${Zn("Enter this code to continue:")}
146
+ ${Rs()}`),reauthentication:Yn("Confirm reauthentication",`${Zn("Enter this code to continue:")}
147
147
  <div class="code-box" style="background-color:#f4f4f4;border:1px solid #eee;border-radius:5px;padding:24px 10px;text-align:center;">
148
148
  <span style="font-size:28px;font-weight:700;letter-spacing:6px;color:#1C1C1C;">{{ .Token }}</span>
149
- </div>`)},CT={signup:`Confirm your signup with this code: {{ .Token }}
149
+ </div>`)},PT={signup:`Confirm your signup with this code: {{ .Token }}
150
150
 
151
151
  Or follow this link: {{ .ConfirmationURL }}`,recovery:`Reset your password with this code: {{ .Token }}
152
152
 
@@ -154,8 +154,8 @@ Or follow this link: {{ .ConfirmationURL }}`,magiclink:`Your login code is: {{ .
154
154
 
155
155
  Or follow this link: {{ .ConfirmationURL }}`,email_change:`Confirm your email change with this code: {{ .Token }}
156
156
 
157
- Or follow this link: {{ .ConfirmationURL }}`,invite:"You have been invited. Accept with this link: {{ .ConfirmationURL }}",reauthentication:"Enter this code to continue: {{ .Token }}"};function Uc(t){return RT[t]}function Qh(t){return CT[t]}var kT={signup:"confirmation",recovery:"recovery",magiclink:"magic_link",email_change:"email_change",invite:"invite"},Cs=class{constructor(e,n={}){this.driver=e;this.config=n;}async sendConfirmation(e,n,r,s){await this.send(await this.render("signup",e,n,r,s));}async sendRecovery(e,n,r,s){await this.send(await this.render("recovery",e,n,r,s));}async sendMagicLink(e,n,r,s){await this.send(await this.render("magiclink",e,n,r,s));}async sendEmailChange(e,n,r,s){await this.send(await this.render("email_change",e,n,r,s));}async sendReauthentication(e,n,r){await this.send(await this.render("reauthentication",e,r?.tokenHash??"",n,r));}async render(e,n,r,s,i){let o=this.config.site_url??"http://localhost:3000",a=i?.redirectTo??o,l={ConfirmationURL:e==="reauthentication"?"":zh(o,r,e,a),Token:s,TokenHash:r,SiteURL:o,Email:i?.currentEmail??n,NewEmail:i?.newEmail??n,RedirectTo:a,Data:i?.data??""},c=kT[e],f=c?this.config.email?.template?.[c]:void 0,u=f?.subject??Vh[c??"reauthentication"]??"Notification",d=f?.content_path?await vT(f.content_path)??Uc(e):Uc(e);return {to:n,subject:Co(u,l),body:{text:Co(Qh(e),l),html:Co(d,l)},otp:s,tokenHash:r,meta:{...i,emailActionType:i?.emailActionType??e}}}async send(e){await this.driver.send({to:e.to,subject:e.subject,text:e.body.text,html:e.body.html});}};async function vT(t){try{let{readFile:e}=await import('node:fs/promises');return await e(t,"utf8")}catch(e){return console.warn(`[auth] failed to load email template "${t}":`,e),null}}function Yh(){return {version:AT(),name:"GoTrue",description:"GoTrue is a user registration and authentication API"}}function Xh(t){let e={};for(let n of vc)e[n]=(t.external?.[n]?.enabled??false)&&$h.has(n);for(let n of Ac)e[n]=false;return {external:{anonymous_users:t.enable_anonymous_sign_ins??false,...e,email:t.email?.enable_signup??true,phone:false},disable_signup:!(t.enable_signup??true),mailer_autoconfirm:!(t.email?.enable_confirmations??false),phone_autoconfirm:false,sms_provider:"",saml_enabled:false}}function Zh(){return {keys:[]}}function eg(){return {issuer:"",jwks_uri:"/.well-known/jwks.json"}}function AT(){return [Mc(JSON.stringify({alg:"HS256",typ:"JWT"})),Mc(JSON.stringify({name:"GoTrue",implementation:"@supabase/lite"})),Mc("metadata")].join(".")}function Mc(t){if(typeof Buffer<"u")return Buffer.from(t,"utf-8").toString("base64url");let e=new TextEncoder().encode(t),n="";for(let r of e)n+=String.fromCharCode(r);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}var ks=t=>t;var OT="00000000-0000-0000-0000-000000000000",PT=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Bc=({onError:t}={})=>ks(async(e,n)=>{if(!e.var.userId||!e.var.sessionId){let r=await ng(e);if(r&&t)return t(r,e)}await n();}),vs=(t={})=>ks(async(e,n)=>{if(t.acceptSecretApiKey&&e.var.apiKeyType==="secret"&&e.var.ignoreAuthorization)return n();if(!e.var.userId){let r=await ng(e);if(r)return tg(e,r);if(!e.var.userId)return tg(e,hn())}await n();});async function ng(t){if(t.var.ignoreAuthorization)return hn();let e=t.req.header("Authorization");if(!e)return hn();if(!e.startsWith("Bearer "))return hn();let n=e.slice(7);if(!n||/^\s/.test(n))return hn();let r=t.get("app").config.auth?.jwt_secret;if(!r)return null;let s;try{s=await mh(n,r);}catch(c){return c instanceof $?c:hn()}let i=$T(s);if(i)return i;let o=s.sub;if(s.role!=="service_role"&&!await t.var.authService.repo.findUserById(o))return Qm();let l=s.session_id;if(l){if(!await t.var.authService.repo.findSessionById(l))return Ym();t.set("sessionId",l);}return t.set("userId",o),t.set("jwt",s),null}function $T(t){let e=t.sub,n=t.role;return e==null||e===""?dc():typeof e!="string"?pc():PT.test(e)?e===OT&&n==="service_role"?dc():null:pc()}function tg(t,e){return t.header("X-Sb-Error-Code",e.code),t.json(e.toJSON(),e.status)}var Hc=new _e().onError((t,e)=>{if(t instanceof $){e.header("X-Sb-Error-Code",t.code);for(let[n,r]of Object.entries(t.headers??{}))e.header(n,r);return e.json(t.toJSON(),t.status)}return console.error("Auth error:",t),e.json({error:"server_error",error_description:"Internal server error"},500)}).options("*",t=>{let e=t.req.header("Access-Control-Request-Method");return e&&t.header("Access-Control-Allow-Methods",e),t.header("Access-Control-Allow-Credentials","true"),t.header("Access-Control-Allow-Origin","*"),t.body(null,204)}).post("/signup",async t=>{let e=await xt(t,{requireBody:true}),{authService:n}=t.var,r=await n.signUp(e.email,e.password,e.data);return r.session?(As(t,r.session),t.json(r.session,200)):t.json(r.user,200)}).all("/signup",bn("POST")).post("/token",async t=>{let e=t.req.query("grant_type"),n=await xt(t,{requireBody:true}),{authService:r}=t.var;if(e==="password"){let s=await r.signInWithPassword(n.email,n.password);return As(t,s),t.json({...s,weak_password:null},200)}if(e==="refresh_token"){let s=await r.refreshSession(n.refresh_token);return As(t,s),t.json(s,200)}if(e==="pkce"){let s=await r.exchangePkceCode(n.auth_code,n.code_verifier);return As(t,s),t.json(s,200)}throw ih()}).all("/token",bn("POST")).post("/otp",async t=>{let e=await xt(t),{authService:n}=t.var;return await n.signInWithOtp(e.email,{shouldCreateUser:e.create_user??e.options?.shouldCreateUser}),t.json({},200)}).post("/magiclink",async t=>{let e=await xt(t),{authService:n}=t.var;return await n.requestMagicLink(e.email,e.gotrue_meta_security),t.json({},200)}).all("/magiclink",bn("POST")).post("/verify",async t=>{let e=await xt(t),{authService:n}=t.var;LT(e);let r=await n.verifyOtp({email:e.email,token:e.token,token_hash:e.token_hash,type:e.type});return As(t,r),t.json(r,200)}).get("/verify",async t=>{let e=t.req.query("type"),n=t.req.query("token"),{authService:r}=t.var;if(!e)throw H("Verify requires a verification type",400);if(!lg.has(e))throw H("Invalid email verification type",400);if(!n)throw H("Verify requires a token or a token hash",400);let s=r.resolveEmailRedirect(t.req.query("redirect_to"));try{let i=await r.verifyOtp({token_hash:n,type:e}),o=new URLSearchParams({access_token:i.access_token,refresh_token:i.refresh_token,expires_in:String(i.expires_in),expires_at:String(i.expires_at),token_type:i.token_type,type:e});return t.redirect(`${s}#${o.toString()}`,303)}catch(i){let o=i instanceof $?i.code:"server_error",a=i instanceof $?i.message:"Verification failed",l=new URLSearchParams({error:"access_denied",error_code:o,error_description:a});return t.redirect(`${s}#${l.toString()}`,303)}}).post("/recover",async t=>{let e=await xt(t),{authService:n}=t.var;return await n.recover(e.email),t.json({},200)}).post("/resend",async t=>{let e=await xt(t),{authService:n}=t.var;return await n.resend(e.type,e.email),t.json({},200)}).get("/health",t=>t.json(Yh(),200)).all("/health",bn("GET")).get("/settings",t=>t.json(Xh(t.var.app.config.auth??{}),200)).all("/settings",bn("GET")).get("/.well-known/jwks.json",t=>(t.header("Cache-Control","public, max-age=600"),t.json(Zh(),200))).get("/.well-known/openid-configuration",t=>(t.header("Cache-Control","public, max-age=600"),t.json(eg(),200))).get("/authorize",async t=>{let{authService:e}=t.var,n=Object.fromEntries(new URL(t.req.url).searchParams),r=await e.getExternalProviderRedirectUrl(n,{refererHeader:t.req.header("Referer"),defaultRedirectUri:og(t.req.url,t.var.app.config.api?.external_url)});return t.header("Content-Type","text/html; charset=utf-8"),t.header("Location",r),t.body(ag(r,"Found"),302)}).get("/callback",ig).post("/callback",ig).all("/nonexistent",IT).use(vs()).post("/logout",async t=>{let e=await xt(t),{authService:n}=t.var;return await n.signOut(t.get("sessionId"),t.req.query("scope")??e.scope,t.get("userId")),t.body(null,204)}).get("/user",async t=>{let{authService:e}=t.var,n=await e.getUser(t.get("userId"));return t.json(n,200)}).put("/user",async t=>{let e=await xt(t),{authService:n}=t.var,r=await n.updateUser(t.get("userId"),{data:e.data,password:e.password,email:e.email});return t.json(r,200)}).all("/user",bn("GET, PUT")).get("/reauthenticate",async t=>{let{authService:e}=t.var;return await e.reauthenticate(t.get("userId")),t.json({},200)}).all("/reauthenticate",bn("GET"));function bn(t){return e=>(e.header("Allow",t),e.body(null,405))}function IT(t){return t.header("Content-Type","text/plain; charset=utf-8"),t.header("X-Content-Type-Options","nosniff"),t.body("404 page not found",404)}function og(t,e){return `${(e||new URL(t).origin).replace(/\/+$/,"")}/auth/v1/callback`}function ag(t,e){return `<a href="${NT(t)}">${e}</a>.
158
- `}function NT(t){return t.replace(/&/g,"&amp;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&#34;")}var DT={400:"invalid_request",401:"unauthorized_client",403:"access_denied",500:"server_error",503:"temporarily_unavailable"},jT=new Set(["signup_disabled","user_banned","provider_email_needs_verification"]);function rg(t){return t instanceof $?{error:jT.has(t.code)?"access_denied":DT[t.status]??"server_error",description:t.message,code:t.code}:{error:"server_error",description:"Unexpected failure, please check server logs for more information"}}function sg(t,e){let n=new URL(t);n.searchParams.set("error",e.error),n.searchParams.set("error_description",e.description),e.code&&n.searchParams.set("error_code",e.code);let r=new URLSearchParams;return r.set("error",e.error),r.set("error_description",e.description),e.code&&r.set("error_code",e.code),r.set("sb",""),n.hash=r.toString(),n.toString()}function qc(t,e,n){return t.header("Location",e),n?(t.header("Content-Type","text/html; charset=utf-8"),t.body(ag(e,"Found"),302)):t.body(null,302)}async function ig(t){let{authService:e}=t.var,n=t.req.method==="GET",r;if(n)r=Object.fromEntries(new URL(t.req.url).searchParams);else {let o=t.req.header("Content-Type")?.toLowerCase().split(";")[0]?.trim();if(o==="application/x-www-form-urlencoded"||o==="multipart/form-data"){let a=await t.req.parseBody();r=Object.fromEntries(Object.entries(a).map(([l,c])=>[l,typeof c=="string"?c:void 0]));}else r={};}let s;try{s=await e.loadOAuthFlowState(r.state);}catch(o){let a=t.var.app.config.auth?.site_url??"http://localhost:3000",l=new URL(a),c=rg(o);l.searchParams.set("error",c.error),l.searchParams.set("error_description",c.description),c.code&&l.searchParams.set("error_code",c.code),t.header("Location",l.toString()),t.header("Content-Type","text/plain; charset=utf-8");let f=o instanceof $?JSON.stringify(o.toJSON()):JSON.stringify(c);return t.body(f,303)}let i=e.resolveOAuthRedirectTarget(s);if(r.error){let o=sg(i,{error:r.error,description:r.error_description??""});return qc(t,o,n)}try{let o=og(t.req.url,t.var.app.config.api?.external_url),a=await e.handleExternalProviderCallback(s,r,{defaultRedirectUri:o});return qc(t,a.redirectUrl,n)}catch(o){(!(o instanceof $)||o.status>=500)&&console.error("Auth error:",o);let a=rg(o),l=sg(i,a);return qc(t,l,n)}}var lg=new Set(["signup","magiclink","recovery","email_change","reauthentication"]);function LT(t){let e=typeof t.type=="string"?t.type:"";if(!e)throw H("Verify requires a verification type",400);if(!lg.has(e))throw H("Invalid email verification type",400);let n=typeof t.token_hash=="string"?t.token_hash:"",r=typeof t.token=="string"?t.token:"",s=typeof t.email=="string"?t.email:"";if(e==="signup"&&!n&&!(s&&r))throw H("Verify requires either a token or a token hash",400)}async function xt(t,e={}){if(!t.req.raw.body){if(e.requireBody)throw hs("Could not parse request body as JSON: unexpected end of JSON input");return {}}let n=await t.req.text();if(n===""){if(e.requireBody)throw hs("Could not parse request body as JSON: unexpected end of JSON input");return {}}try{return JSON.parse(n)}catch{if(t.req.header("Content-Type")?.toLowerCase().split(";")[0]?.trim()==="application/x-www-form-urlencoded")throw hs("Could not parse request body as JSON: unexpected end of JSON input");let s=wc(n)||"invalid character ' ' looking for beginning of value";throw hs(`Could not parse request body as JSON: ${s}`)}}function As(t,e){e.session_id&&t.header("Sb-Auth-Session-Id",e.session_id),e.user_id&&t.header("Sb-Auth-User-Id",e.user_id),e.refresh_token&&t.header("Sb-Auth-Refresh-Token-Prefix",String(e.refresh_token).slice(0,8));}function cg(t){let e=t.connection.dialect,n=new Ss(t.connection.kysely,e,s=>t.connection.runInTransaction(s)),r=t.config.auth;return new bs(n,r,t._mailer??new Cs(t.drivers.email,{site_url:r.site_url,email:r.email}))}function ug(t){if(t==null)return {};if(typeof t=="string")try{return JSON.parse(t)}catch{return {}}return t}function fg(t){if(t==null)return [];if(Array.isArray(t))return t;if(typeof t=="string")try{return JSON.parse(t)}catch{return []}return []}function Wt(t){return typeof t=="string"?t:JSON.stringify(t??{})}var Os=class{constructor(e,n){this.db=e;this.dialect=n;this.schema="storage";}schema;table(e){return this.db.withSchema(this.schema).selectFrom(e)}insertInto(e){return this.db.withSchema(this.schema).insertInto(e)}update(e){return this.db.withSchema(this.schema).updateTable(e)}deleteFrom(e){return this.db.withSchema(this.schema).deleteFrom(e)}async createBucket(e){let n=new Date().toISOString(),r={id:e.id,name:e.name,owner:e.owner??null,owner_id:e.owner_id??null,public:e.public??false,file_size_limit:e.file_size_limit??null,allowed_mime_types:this.dialect==="postgres"?e.allowed_mime_types??null:Wt(e.allowed_mime_types??[]),created_at:n,updated_at:n};return await this.insertInto("buckets").values(r).execute(),await this.findBucketById(e.id)}async findBucketById(e){let n=await this.table("buckets").selectAll().where("id","=",e).executeTakeFirst();return n?this.parseBucketRow(n):null}async findBucketByName(e){let n=await this.table("buckets").selectAll().where("name","=",e).executeTakeFirst();return n?this.parseBucketRow(n):null}async listBuckets(){return (await this.table("buckets").selectAll().execute()).map(n=>this.parseBucketRow(n))}async updateBucket(e,n){let r={updated_at:new Date().toISOString()};return n.public!==void 0&&(r.public=n.public),n.file_size_limit!==void 0&&(r.file_size_limit=n.file_size_limit),n.allowed_mime_types!==void 0&&(r.allowed_mime_types=this.dialect==="postgres"?n.allowed_mime_types??null:Wt(n.allowed_mime_types)),await this.update("buckets").set(r).where("id","=",e).execute(),this.findBucketById(e)}async deleteBucket(e){await this.deleteFrom("buckets").where("id","=",e).execute();}async isBucketEmpty(e){let n=await this.table("objects").select(this.db.fn.count("id").as("count")).where("bucket_id","=",e).executeTakeFirst();return Number(n?.count??0)===0}async createObject(e){let n=new Date().toISOString(),r={id:e.id,bucket_id:e.bucket_id,name:e.name,owner:e.owner??null,owner_id:e.owner_id??null,metadata:Wt(e.metadata??{}),user_metadata:Wt(e.user_metadata??{}),version:e.version??null,created_at:n,updated_at:n,last_accessed_at:n};return this.dialect!=="postgres"&&(r.path_tokens=Wt(e.name.split("/"))),await this.insertInto("objects").values(r).execute(),await this.findObjectById(e.id)}async findObjectById(e){let n=await this.table("objects").selectAll().where("id","=",e).executeTakeFirst();return n?this.parseObjectRow(n):null}async findObjectByPath(e,n){let r=await this.table("objects").selectAll().where("bucket_id","=",e).where("name","=",n).executeTakeFirst();return r?this.parseObjectRow(r):null}async listObjects(e,n,r){let s=this.table("objects").selectAll().where("bucket_id","=",e);return n&&(s=s.where("name","like",`${n}%`)),r?.search&&(s=s.where("name","like",`%${r.search}%`)),r?.sortBy?s=s.orderBy(r.sortBy.column,r.sortBy.order):s=s.orderBy("name","asc"),r?.limit&&(s=s.limit(r.limit)),r?.offset&&(s=s.offset(r.offset)),(await s.execute()).map(o=>this.parseObjectRow(o))}async updateObject(e,n){let r={updated_at:new Date().toISOString()};return n.name!==void 0&&(r.name=n.name,this.dialect!=="postgres"&&(r.path_tokens=Wt(n.name.split("/")))),n.metadata!==void 0&&(r.metadata=Wt(n.metadata)),n.user_metadata!==void 0&&(r.user_metadata=Wt(n.user_metadata)),n.version!==void 0&&(r.version=n.version),n.owner!==void 0&&(r.owner=n.owner),n.owner_id!==void 0&&(r.owner_id=n.owner_id),await this.update("objects").set(r).where("id","=",e).execute(),this.findObjectById(e)}async deleteObject(e){await this.deleteFrom("objects").where("id","=",e).execute();}async deleteObjectsByBucket(e){let r=(await this.table("objects").select("name").where("bucket_id","=",e).execute()).map(s=>s.name);return r.length>0&&await this.deleteFrom("objects").where("bucket_id","=",e).execute(),r}async objectExists(e,n){return !!await this.table("objects").select("id").where("bucket_id","=",e).where("name","=",n).executeTakeFirst()}async touchObject(e){await this.update("objects").set({last_accessed_at:new Date().toISOString()}).where("id","=",e).execute();}parseBucketRow(e){return {...e,owner:e.owner??"",owner_id:e.owner_id??"",public:!!e.public,allowed_mime_types:e.allowed_mime_types==null?null:fg(e.allowed_mime_types)}}parseObjectRow(e){return {...e,metadata:ug(e.metadata),user_metadata:ug(e.user_metadata),path_tokens:fg(e.path_tokens)}}};var Z=class t extends Error{constructor(n,r,s){super(s);this.status=n;this.code=r;}name="StorageError";static bucketNotFound(n){return new t(404,"Bucket not found",`Bucket not found: ${n}`)}static bucketAlreadyExists(n){return new t(409,"Duplicate","The resource already exists")}static bucketNotEmpty(n){return new t(409,"ResourceNotEmpty","The bucket you tried to delete is not empty")}static objectNotFound(n){return new t(404,"Object not found",`Object not found: ${n}`)}static invalidMimeType(n,r){return new t(415,"invalid_mime_type",`mime type ${n} is not supported. Supported: ${r.join(", ")}`)}static fileTooLarge(n){return new t(413,"Payload too large",`The object exceeded the maximum allowed size of ${n} bytes`)}static invalidKey(n){return new t(400,"Invalid key",`Invalid object key: ${n}`)}static storageNotConfigured(){return new t(500,"Storage not configured","Storage is enabled but no storage adapter has been set. Set app._storageAdapter before making storage requests.")}toJSON(){return {statusCode:String(this.status),error:this.code,message:this.message}}};var Ps=class{constructor(e,n,r,s={},i){this.repo=e;this.adapter=n;this.config=r;this.options=s;this.transformationAdapter=i;}initialized=false;async init(){if(!this.initialized&&(this.initialized=true,this.options.autoCreateBuckets!==false&&this.config.buckets))for(let[e,n]of Object.entries(this.config.buckets))await this.repo.findBucketById(e)||await this.repo.createBucket({id:e,name:e,public:n.public??false,file_size_limit:n.file_size_limit?BT(n.file_size_limit):null,allowed_mime_types:n.allowed_mime_types});}async createBucket(e){if(await this.repo.findBucketById(e.id))throw Z.bucketAlreadyExists(e.id);return this.repo.createBucket(e)}async getBucket(e){let n=await this.repo.findBucketById(e);if(!n)throw Z.bucketNotFound(e);return n}async listBuckets(){return this.repo.listBuckets()}async updateBucket(e,n){if(!await this.repo.findBucketById(e))throw Z.bucketNotFound(e);return await this.repo.updateBucket(e,n)}async deleteBucket(e){if(!await this.repo.findBucketById(e))throw Z.bucketNotFound(e);if(!await this.repo.isBucketEmpty(e))throw Z.bucketNotEmpty(e);await this.repo.deleteBucket(e);}async emptyBucket(e){if(!await this.repo.findBucketById(e))throw Z.bucketNotFound(e);let r=await this.repo.deleteObjectsByBucket(e);r.length>0&&await this.adapter.deleteObjects(e,r);}async upload(e,n,r,s){Wc(n);let i=await this.repo.findBucketById(e);if(!i)throw Z.bucketNotFound(e);let o=s?.contentType??"application/octet-stream",a=s?.cacheControl??"no-cache";if(i.allowed_mime_types&&i.allowed_mime_types.length>0&&!i.allowed_mime_types.includes(o))throw Z.invalidMimeType(o,i.allowed_mime_types);let l=i.file_size_limit??this.config.fileSizeLimit??null;if(l&&s?.contentLength&&s.contentLength>l)throw Z.fileTooLarge(l);let c=await this.repo.findObjectByPath(e,n);if(c&&!s?.upsert)throw Z.bucketAlreadyExists(n);return await this.adapter.uploadObject(e,n,void 0,r,o,a),c&&s?.upsert?await this.repo.updateObject(c.id,{metadata:s?.metadata??c.metadata,version:crypto.randomUUID()}):this.repo.createObject({id:crypto.randomUUID(),bucket_id:e,name:n,owner:s?.owner??null,owner_id:s?.owner??null,metadata:s?.metadata??{},version:crypto.randomUUID()})}async download(e,n,r){let s=await this.repo.findObjectByPath(e,n);if(!s)throw Z.objectNotFound(n);if(await this.repo.touchObject(s.id),r?.transform&&this.transformationAdapter&&!this.transformationAdapter.requiresBuffer&&this.transformationAdapter.transformFromUrl){let o=await this.adapter.privateAssetUrl(e,n,s.version??void 0),a=await this.transformationAdapter.transformFromUrl(o,r.transform);return {body:a.body,metadata:{cacheControl:"public, max-age=3600",contentLength:a.contentLength??0,size:a.contentLength??0,mimetype:a.contentType,eTag:""}}}let i=await this.adapter.getObject(e,n,s.version??void 0);if(!i.body)throw Z.objectNotFound(n);if(r?.transform&&this.transformationAdapter?.requiresBuffer){let o=await MT(i.body),a=await this.transformationAdapter.transform(o,r.transform);return {body:a.body,metadata:{...i.metadata,mimetype:a.contentType,size:a.contentLength??0,contentLength:a.contentLength??0}}}return {body:i.body,metadata:i.metadata}}async update(e,n,r,s){return this.upload(e,n,r,{...s,upsert:s?.upsert??true})}async remove(e,n){if(!await this.repo.findBucketById(e))throw Z.bucketNotFound(e);let s=[];for(let i of n){let o=await this.repo.findObjectByPath(e,i);o&&(await this.adapter.deleteObject(e,i,o.version??void 0),await this.repo.deleteObject(o.id),s.push(o));}return s}async list(e,n,r){if(!await this.repo.findBucketById(e))throw Z.bucketNotFound(e);return this.repo.listObjects(e,n,r)}async move(e,n,r){Wc(r);let s=await this.repo.findObjectByPath(e,n);if(!s)throw Z.objectNotFound(n);await this.adapter.copyObject(e,n,s.version??void 0,r,void 0),await this.adapter.deleteObject(e,n,s.version??void 0),await this.repo.updateObject(s.id,{name:r,version:crypto.randomUUID()});}async copy(e,n,r){Wc(r);let s=await this.repo.findObjectByPath(e,n);if(!s)throw Z.objectNotFound(n);return await this.adapter.copyObject(e,n,s.version??void 0,r,void 0),await this.repo.createObject({id:crypto.randomUUID(),bucket_id:e,name:r,owner:s.owner,owner_id:s.owner_id,metadata:s.metadata,version:crypto.randomUUID()}),{key:r}}async info(e,n){let r=await this.repo.findObjectByPath(e,n);if(!r)throw Z.objectNotFound(n);let s=await this.adapter.headObject(e,n,r.version??void 0);return {...r,httpMetadata:s}}async exists(e,n){return this.repo.objectExists(e,n)}async createSignedUrl(e,n,r){if(!await this.repo.findObjectByPath(e,n))throw Z.objectNotFound(n);let i=await this.signStorageToken({sub:n,bucket:e,intent:"download"},r);return {signedUrl:`/storage/v1/object/sign/${e}/${n}?token=${i}`}}async createSignedUrls(e,n,r){let s=[];for(let i of n)try{let{signedUrl:o}=await this.createSignedUrl(e,i,r);s.push({path:i,signedUrl:o,error:null});}catch(o){s.push({path:i,signedUrl:"",error:o.message});}return s}async createSignedUploadUrl(e,n){if(!await this.repo.findBucketById(e))throw Z.bucketNotFound(e);let s=await this.signStorageToken({sub:n,bucket:e,intent:"upload"},7200);return {signedUrl:`/storage/v1/object/upload/sign/${e}/${n}?token=${s}`,token:s,path:n}}async verifySignedUrl(e){let n=new TextEncoder().encode(this.config.jwtSecret),{payload:r}=await jwtVerify(e,n,{algorithms:["HS256"]});return {bucket:r.bucket,path:r.sub,intent:r.intent}}async signStorageToken(e,n){let r=new TextEncoder().encode(this.config.jwtSecret),s=Math.floor(Date.now()/1e3);return new SignJWT({...e,iat:s}).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt(s).setExpirationTime(s+n).sign(r)}};async function MT(t){if(t instanceof Uint8Array||Buffer.isBuffer(t))return t;if(t instanceof Blob)return new Uint8Array(await t.arrayBuffer());let e=[],n=t.getReader();for(;;){let{done:r,value:s}=await n.read();if(r)break;e.push(s);}return Buffer.concat(e)}function Wc(t){if(!t||t.includes("..")||t.startsWith("/"))throw Z.invalidKey(t)}function BT(t){let e=t.match(/^(\d+(?:\.\d+)?)\s*(B|KB|KiB|MB|MiB|GB|GiB)$/i);if(!e)return 0;let n=Number.parseFloat(e[1]),r=e[2].toUpperCase();return Math.floor(n*({B:1,KB:1e3,KIB:1024,MB:1e6,MIB:1048576,GB:1e9,GIB:1073741824}[r]??1))}var qT=s.object({id:s.string(),name:s.string(),public:s.boolean({default:false}).optional(),file_size_limit:s.number().optional(),allowed_mime_types:s.array(s.string()).optional()}),HT=s.object({public:s.boolean().optional(),file_size_limit:s.number().optional(),allowed_mime_types:s.array(s.string()).optional()}),WT=s.object({prefix:s.string().optional(),limit:s.number().optional(),offset:s.number().optional(),sortBy:s.object({column:s.string(),order:s.string()}).optional(),search:s.string().optional()}),dg=s.object({bucketId:s.string(),sourceKey:s.string(),destinationKey:s.string()}),KT=s.object({expiresIn:s.number()}),JT=s.object({expiresIn:s.number(),paths:s.array(s.string())}),GT=s.object({prefixes:s.array(s.string())}),zT=new _e().get("/object/public/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=ft(t.req.path,`/object/public/${e}/`),{storageService:r}=t.var;if(!(await r.getBucket(e)).public)return t.json({error:"Bucket is not public"},400);let i=Kc(t.req.query()),o=await r.download(e,n,{transform:i??void 0});return new Response(o.body,{headers:Jc(o.metadata)})}).get("/object/sign/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=ft(t.req.path,`/object/sign/${e}/`),r=t.req.query("token"),{storageService:s}=t.var;if(!r)return t.json({error:"Missing token"},400);let i=await s.verifySignedUrl(r);if(i.bucket!==e||i.path!==n)return t.json({error:"Invalid token"},403);let o=Kc(t.req.query()),a=await s.download(e,n,{transform:o??void 0});return new Response(a.body,{headers:Jc(a.metadata)})}).put("/object/upload/sign/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=ft(t.req.path,`/object/upload/sign/${e}/`),r=t.req.query("token"),{storageService:s}=t.var;if(!r)return t.json({error:"Missing token"},400);let i=await s.verifySignedUrl(r);if(i.bucket!==e||i.path!==n||i.intent!=="upload")return t.json({error:"Invalid token"},403);let o=t.req.header("content-type")??"application/octet-stream",a=t.req.header("content-length")?Number.parseInt(t.req.header("content-length"),10):void 0,l=t.req.raw.body??new Uint8Array(await t.req.arrayBuffer()),c=await s.upload(e,n,l,{contentType:o,contentLength:a,upsert:true});return t.json({Key:c.name},200)}),VT=new _e().use(vs({acceptSecretApiKey:true})).post("/bucket",validator("json",qT),async t=>{let e=t.req.valid("json"),{storageService:n}=t.var,r=await n.createBucket({id:e.id,name:e.name??e.id,public:e.public,file_size_limit:e.file_size_limit,allowed_mime_types:e.allowed_mime_types});return t.json({name:r.name},200)}).get("/bucket",async t=>{let{storageService:e}=t.var,n=await e.listBuckets();return t.json(n,200)}).get("/bucket/:id",async t=>{let{storageService:e}=t.var,n=await e.getBucket(t.req.param("id"));return t.json(n,200)}).put("/bucket/:id",validator("json",HT),async t=>{let{storageService:e}=t.var;return await e.updateBucket(t.req.param("id"),t.req.valid("json")),t.json({message:"Successfully updated"},200)}).delete("/bucket/:id",async t=>{let{storageService:e}=t.var;return await e.deleteBucket(t.req.param("id")),t.json({message:"Successfully deleted"},200)}).post("/bucket/:id/empty",async t=>{let{storageService:e}=t.var;return await e.emptyBucket(t.req.param("id")),t.json({message:"Empty bucket has been queued. Completion may take up to an hour."},200)}).post("/object/list/:bucketId",validator("json",WT),async t=>{let e=t.req.param("bucketId"),n=t.req.valid("json"),{storageService:r}=t.var,s=await r.list(e,n.prefix,{limit:n.limit,offset:n.offset,sortBy:n.sortBy,search:n.search});return t.json(s,200)}).post("/object/move",validator("json",dg),async t=>{let e=t.req.valid("json"),{storageService:n}=t.var;return await n.move(e.bucketId,e.sourceKey,e.destinationKey),t.json({message:"Successfully moved"},200)}).post("/object/copy",validator("json",dg),async t=>{let e=t.req.valid("json"),{storageService:n}=t.var,r=await n.copy(e.bucketId,e.sourceKey,e.destinationKey);return t.json({key:r.key},200)}).get("/object/info/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=ft(t.req.path,`/object/info/${e}/`),{storageService:r}=t.var,s=await r.info(e,n);return t.json(s,200)}).post("/object/sign/:bucketId/*",validator("json",KT),async t=>{let e=t.req.param("bucketId"),n=ft(t.req.path,`/object/sign/${e}/`),{expiresIn:r}=t.req.valid("json"),{storageService:s}=t.var,i=await s.createSignedUrl(e,n,r);return t.json(i,200)}).post("/object/sign/:bucketId",validator("json",JT),async t=>{let e=t.req.param("bucketId"),{expiresIn:n,paths:r}=t.req.valid("json"),{storageService:s}=t.var,i=await s.createSignedUrls(e,r,n);return t.json(i,200)}).post("/object/upload/sign/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=ft(t.req.path,`/object/upload/sign/${e}/`),{storageService:r}=t.var,s=await r.createSignedUploadUrl(e,n);return t.json(s,200)}).delete("/object/:bucketId",validator("json",GT),async t=>{let e=t.req.param("bucketId"),{prefixes:n}=t.req.valid("json"),{storageService:r}=t.var,s=await r.remove(e,n);return t.json(s,200)}).post("/object/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=ft(t.req.path,`/object/${e}/`),{storageService:r}=t.var,s=t.req.header("content-type")??"application/octet-stream",i=t.req.header("cache-control")??"no-cache",o=t.req.header("x-upsert")==="true",a,l,c;if(s.startsWith("multipart/form-data")){let d=(await t.req.formData()).get("file");if(!d)throw new Z(400,"InvalidRequest","Missing file in multipart upload");let p=new Uint8Array(await d.arrayBuffer());a=p,l=d.type||"application/octet-stream",c=p.length;}else a=t.req.raw.body??new Uint8Array(await t.req.arrayBuffer()),l=s,c=t.req.header("content-length")?Number.parseInt(t.req.header("content-length"),10):void 0;let f=await r.upload(e,n,a,{contentType:l,cacheControl:i,contentLength:c,upsert:o,owner:t.get("userId")??null});return t.json({Key:`${e}/${f.name}`,Id:f.id},200)}).put("/object/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=ft(t.req.path,`/object/${e}/`),{storageService:r}=t.var,s=t.req.header("content-type")??"application/octet-stream",i=t.req.header("cache-control")??"no-cache",o=t.req.header("content-length")?Number.parseInt(t.req.header("content-length"),10):void 0,a=t.req.raw.body??new Uint8Array(await t.req.arrayBuffer()),l=await r.update(e,n,a,{contentType:s,cacheControl:i,contentLength:o,owner:t.get("userId")??null});return t.json({Key:`${e}/${l.name}`,Id:l.id},200)}).get("/object/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=ft(t.req.path,`/object/${e}/`),{storageService:r}=t.var,s=Kc(t.req.query()),i=await r.download(e,n,{transform:s??void 0});return new Response(i.body,{headers:Jc(i.metadata)})}).on("HEAD","/object/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=ft(t.req.path,`/object/${e}/`),{storageService:r}=t.var;return await r.exists(e,n)?t.body(null,200):t.body(null,404)}),Gc=new _e().onError((t,e)=>t instanceof Z?e.json(t.toJSON(),400):(console.error("Storage error:",t),e.json({error:"server_error",message:"Internal server error"},500))).route("/",zT).route("/",VT);function ft(t,e){let n=t.replace(/^\/storage\/v1/,""),r=n.indexOf(e);return r===-1?n.split("/").slice(3).join("/"):n.slice(r+e.length)}function Kc(t){let{width:e,height:n,resize:r,format:s,quality:i}=t;return !e&&!n&&!r&&!s&&!i?null:{width:e?Number.parseInt(e,10):void 0,height:n?Number.parseInt(n,10):void 0,resize:r,format:s,quality:i?Number.parseInt(i,10):void 0}}function Jc(t){let e={"Content-Type":t.mimetype,"Cache-Control":t.cacheControl,ETag:t.eTag};return t.contentLength&&(e["Content-Length"]=String(t.contentLength)),t.lastModified&&(e["Last-Modified"]=t.lastModified.toUTCString()),t.contentRange&&(e["Content-Range"]=t.contentRange),e}Un();var zc=`-- supabase/storage core schema (Postgres)
157
+ Or follow this link: {{ .ConfirmationURL }}`,invite:"You have been invited. Accept with this link: {{ .ConfirmationURL }}",reauthentication:"Enter this code to continue: {{ .Token }}"};function qc(t){return OT[t]}function Yh(t){return PT[t]}var $T={signup:"confirmation",recovery:"recovery",magiclink:"magic_link",email_change:"email_change",invite:"invite"},Cs=class{constructor(e,n={}){this.driver=e;this.config=n;}async sendConfirmation(e,n,r,s){await this.send(await this.render("signup",e,n,r,s));}async sendRecovery(e,n,r,s){await this.send(await this.render("recovery",e,n,r,s));}async sendMagicLink(e,n,r,s){await this.send(await this.render("magiclink",e,n,r,s));}async sendEmailChange(e,n,r,s){await this.send(await this.render("email_change",e,n,r,s));}async sendReauthentication(e,n,r){await this.send(await this.render("reauthentication",e,r?.tokenHash??"",n,r));}async render(e,n,r,s,i){let o=this.config.site_url??"http://localhost:3000",a=i?.redirectTo??o,l={ConfirmationURL:e==="reauthentication"?"":Qh(o,r,e,a),Token:s,TokenHash:r,SiteURL:o,Email:i?.currentEmail??n,NewEmail:i?.newEmail??n,RedirectTo:a,Data:i?.data??""},c=$T[e],f=c?this.config.email?.template?.[c]:void 0,u=f?.subject??Xh[c??"reauthentication"]??"Notification",d=f?.content_path?await IT(f.content_path)??qc(e):qc(e);return {to:n,subject:Ao(u,l),body:{text:Ao(Yh(e),l),html:Ao(d,l)},otp:s,tokenHash:r,meta:{...i,emailActionType:i?.emailActionType??e}}}async send(e){await this.driver.send({to:e.to,subject:e.subject,text:e.body.text,html:e.body.html});}};async function IT(t){try{let{readFile:e}=await import('node:fs/promises');return await e(t,"utf8")}catch(e){return console.warn(`[auth] failed to load email template "${t}":`,e),null}}function Zh(){return {version:NT(),name:"GoTrue",description:"GoTrue is a user registration and authentication API"}}function eg(t){let e={};for(let n of Pc)e[n]=(t.external?.[n]?.enabled??false)&&Nh.has(n);for(let n of $c)e[n]=false;return {external:{anonymous_users:t.enable_anonymous_sign_ins??false,...e,email:t.email?.enable_signup??true,phone:false},disable_signup:!(t.enable_signup??true),mailer_autoconfirm:!(t.email?.enable_confirmations??false),phone_autoconfirm:false,sms_provider:"",saml_enabled:false}}function tg(){return {keys:[]}}function ng(){return {issuer:"",jwks_uri:"/.well-known/jwks.json"}}function NT(){return [Hc(JSON.stringify({alg:"HS256",typ:"JWT"})),Hc(JSON.stringify({name:"GoTrue",implementation:"@supabase/lite"})),Hc("metadata")].join(".")}function Hc(t){if(typeof Buffer<"u")return Buffer.from(t,"utf-8").toString("base64url");let e=new TextEncoder().encode(t),n="";for(let r of e)n+=String.fromCharCode(r);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}var ks=t=>t;var DT="00000000-0000-0000-0000-000000000000",jT=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Wc=({onError:t}={})=>ks(async(e,n)=>{if(!e.var.userId||!e.var.sessionId){let r=await sg(e);if(r&&t)return t(r,e)}await n();}),vs=(t={})=>ks(async(e,n)=>{if(t.acceptSecretApiKey&&e.var.apiKeyType==="secret"&&e.var.ignoreAuthorization)return n();if(!e.var.userId){let r=await sg(e);if(r)return rg(e,r);if(!e.var.userId)return rg(e,hn())}await n();});async function sg(t){if(t.var.ignoreAuthorization)return hn();let e=t.req.header("Authorization");if(!e)return hn();if(!e.startsWith("Bearer "))return hn();let n=e.slice(7);if(!n||/^\s/.test(n))return hn();let r=t.get("app").config.auth?.jwt_secret;if(!r)return null;let s;try{s=await gh(n,r);}catch(c){return c instanceof $?c:hn()}let i=LT(s);if(i)return i;let o=s.sub;if(s.role!=="service_role"&&!await t.var.authService.repo.findUserById(o))return Ym();let l=s.session_id;if(l){if(!await t.var.authService.repo.findSessionById(l))return Zm();t.set("sessionId",l);}return t.set("userId",o),t.set("jwt",s),null}function LT(t){let e=t.sub,n=t.role;return e==null||e===""?hc():typeof e!="string"?gc():jT.test(e)?e===DT&&n==="service_role"?hc():null:gc()}function rg(t,e){return t.header("X-Sb-Error-Code",e.code),t.json(e.toJSON(),e.status)}var Jc=new _e().onError((t,e)=>{if(t instanceof $){e.header("X-Sb-Error-Code",t.code);for(let[n,r]of Object.entries(t.headers??{}))e.header(n,r);return e.json(t.toJSON(),t.status)}return console.error("Auth error:",t),e.json({error:"server_error",error_description:"Internal server error"},500)}).options("*",t=>{let e=t.req.header("Access-Control-Request-Method");return e&&t.header("Access-Control-Allow-Methods",e),t.header("Access-Control-Allow-Credentials","true"),t.header("Access-Control-Allow-Origin","*"),t.body(null,204)}).post("/signup",async t=>{let e=await xt(t,{requireBody:true}),{authService:n}=t.var,r=await n.signUp(e.email,e.password,e.data);return r.session?(As(t,r.session),t.json(r.session,200)):t.json(r.user,200)}).all("/signup",bn("POST")).post("/token",async t=>{let e=t.req.query("grant_type"),n=await xt(t,{requireBody:true}),{authService:r}=t.var;if(e==="password"){let s=await r.signInWithPassword(n.email,n.password);return As(t,s),t.json({...s,weak_password:null},200)}if(e==="refresh_token"){let s=await r.refreshSession(n.refresh_token);return As(t,s),t.json(s,200)}if(e==="pkce"){let s=await r.exchangePkceCode(n.auth_code,n.code_verifier);return As(t,s),t.json(s,200)}throw ah()}).all("/token",bn("POST")).post("/otp",async t=>{let e=await xt(t),{authService:n}=t.var;return await n.signInWithOtp(e.email,{shouldCreateUser:e.create_user??e.options?.shouldCreateUser}),t.json({},200)}).post("/magiclink",async t=>{let e=await xt(t),{authService:n}=t.var;return await n.requestMagicLink(e.email,e.gotrue_meta_security),t.json({},200)}).all("/magiclink",bn("POST")).post("/verify",async t=>{let e=await xt(t),{authService:n}=t.var;qT(e);let r=await n.verifyOtp({email:e.email,token:e.token,token_hash:e.token_hash,type:e.type});return As(t,r),t.json(r,200)}).get("/verify",async t=>{let e=t.req.query("type"),n=t.req.query("token"),{authService:r}=t.var;if(!e)throw H("Verify requires a verification type",400);if(!ug.has(e))throw H("Invalid email verification type",400);if(!n)throw H("Verify requires a token or a token hash",400);let s=r.resolveEmailRedirect(t.req.query("redirect_to"));try{let i=await r.verifyOtp({token_hash:n,type:e}),o=new URLSearchParams({access_token:i.access_token,refresh_token:i.refresh_token,expires_in:String(i.expires_in),expires_at:String(i.expires_at),token_type:i.token_type,type:e});return t.redirect(`${s}#${o.toString()}`,303)}catch(i){let o=i instanceof $?i.code:"server_error",a=i instanceof $?i.message:"Verification failed",l=new URLSearchParams({error:"access_denied",error_code:o,error_description:a});return t.redirect(`${s}#${l.toString()}`,303)}}).post("/recover",async t=>{let e=await xt(t),{authService:n}=t.var;return await n.recover(e.email),t.json({},200)}).post("/resend",async t=>{let e=await xt(t),{authService:n}=t.var;return await n.resend(e.type,e.email),t.json({},200)}).get("/health",t=>t.json(Zh(),200)).all("/health",bn("GET")).get("/settings",t=>t.json(eg(t.var.app.config.auth??{}),200)).all("/settings",bn("GET")).get("/.well-known/jwks.json",t=>(t.header("Cache-Control","public, max-age=600"),t.json(tg(),200))).get("/.well-known/openid-configuration",t=>(t.header("Cache-Control","public, max-age=600"),t.json(ng(),200))).get("/authorize",async t=>{let{authService:e}=t.var,n=Object.fromEntries(new URL(t.req.url).searchParams),r=await e.getExternalProviderRedirectUrl(n,{refererHeader:t.req.header("Referer"),defaultRedirectUri:lg(t.req.url,t.var.app.config.api?.external_url)});return t.header("Content-Type","text/html; charset=utf-8"),t.header("Location",r),t.body(cg(r,"Found"),302)}).get("/callback",ag).post("/callback",ag).all("/nonexistent",FT).use(vs()).post("/logout",async t=>{let e=await xt(t),{authService:n}=t.var;return await n.signOut(t.get("sessionId"),t.req.query("scope")??e.scope,t.get("userId")),t.body(null,204)}).get("/user",async t=>{let{authService:e}=t.var,n=await e.getUser(t.get("userId"));return t.json(n,200)}).put("/user",async t=>{let e=await xt(t),{authService:n}=t.var,r=await n.updateUser(t.get("userId"),{data:e.data,password:e.password,email:e.email});return t.json(r,200)}).all("/user",bn("GET, PUT")).get("/reauthenticate",async t=>{let{authService:e}=t.var;return await e.reauthenticate(t.get("userId")),t.json({},200)}).all("/reauthenticate",bn("GET"));function bn(t){return e=>(e.header("Allow",t),e.body(null,405))}function FT(t){return t.header("Content-Type","text/plain; charset=utf-8"),t.header("X-Content-Type-Options","nosniff"),t.body("404 page not found",404)}function lg(t,e){return `${(e||new URL(t).origin).replace(/\/+$/,"")}/auth/v1/callback`}function cg(t,e){return `<a href="${UT(t)}">${e}</a>.
158
+ `}function UT(t){return t.replace(/&/g,"&amp;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&#34;")}var MT={400:"invalid_request",401:"unauthorized_client",403:"access_denied",500:"server_error",503:"temporarily_unavailable"},BT=new Set(["signup_disabled","user_banned","provider_email_needs_verification"]);function ig(t){return t instanceof $?{error:BT.has(t.code)?"access_denied":MT[t.status]??"server_error",description:t.message,code:t.code}:{error:"server_error",description:"Unexpected failure, please check server logs for more information"}}function og(t,e){let n=new URL(t);n.searchParams.set("error",e.error),n.searchParams.set("error_description",e.description),e.code&&n.searchParams.set("error_code",e.code);let r=new URLSearchParams;return r.set("error",e.error),r.set("error_description",e.description),e.code&&r.set("error_code",e.code),r.set("sb",""),n.hash=r.toString(),n.toString()}function Kc(t,e,n){return t.header("Location",e),n?(t.header("Content-Type","text/html; charset=utf-8"),t.body(cg(e,"Found"),302)):t.body(null,302)}async function ag(t){let{authService:e}=t.var,n=t.req.method==="GET",r;if(n)r=Object.fromEntries(new URL(t.req.url).searchParams);else {let o=t.req.header("Content-Type")?.toLowerCase().split(";")[0]?.trim();if(o==="application/x-www-form-urlencoded"||o==="multipart/form-data"){let a=await t.req.parseBody();r=Object.fromEntries(Object.entries(a).map(([l,c])=>[l,typeof c=="string"?c:void 0]));}else r={};}let s;try{s=await e.loadOAuthFlowState(r.state);}catch(o){let a=t.var.app.config.auth?.site_url??"http://localhost:3000",l=new URL(a),c=ig(o);l.searchParams.set("error",c.error),l.searchParams.set("error_description",c.description),c.code&&l.searchParams.set("error_code",c.code),t.header("Location",l.toString()),t.header("Content-Type","text/plain; charset=utf-8");let f=o instanceof $?JSON.stringify(o.toJSON()):JSON.stringify(c);return t.body(f,303)}let i=e.resolveOAuthRedirectTarget(s);if(r.error){let o=og(i,{error:r.error,description:r.error_description??""});return Kc(t,o,n)}try{let o=lg(t.req.url,t.var.app.config.api?.external_url),a=await e.handleExternalProviderCallback(s,r,{defaultRedirectUri:o});return Kc(t,a.redirectUrl,n)}catch(o){(!(o instanceof $)||o.status>=500)&&console.error("Auth error:",o);let a=ig(o),l=og(i,a);return Kc(t,l,n)}}var ug=new Set(["signup","magiclink","recovery","email_change","reauthentication"]);function qT(t){let e=typeof t.type=="string"?t.type:"";if(!e)throw H("Verify requires a verification type",400);if(!ug.has(e))throw H("Invalid email verification type",400);let n=typeof t.token_hash=="string"?t.token_hash:"",r=typeof t.token=="string"?t.token:"",s=typeof t.email=="string"?t.email:"";if(e==="signup"&&!n&&!(s&&r))throw H("Verify requires either a token or a token hash",400)}async function xt(t,e={}){if(!t.req.raw.body){if(e.requireBody)throw hs("Could not parse request body as JSON: unexpected end of JSON input");return {}}let n=await t.req.text();if(n===""){if(e.requireBody)throw hs("Could not parse request body as JSON: unexpected end of JSON input");return {}}try{return JSON.parse(n)}catch{if(t.req.header("Content-Type")?.toLowerCase().split(";")[0]?.trim()==="application/x-www-form-urlencoded")throw hs("Could not parse request body as JSON: unexpected end of JSON input");let s=Ec(n)||"invalid character ' ' looking for beginning of value";throw hs(`Could not parse request body as JSON: ${s}`)}}function As(t,e){e.session_id&&t.header("Sb-Auth-Session-Id",e.session_id),e.user_id&&t.header("Sb-Auth-User-Id",e.user_id),e.refresh_token&&t.header("Sb-Auth-Refresh-Token-Prefix",String(e.refresh_token).slice(0,8));}function fg(t){let e=t.connection.dialect,n=new Ss(t.connection.kysely,e,s=>t.connection.runInTransaction(s)),r=t.config.auth;return new bs(n,r,t._mailer??new Cs(t.drivers.email,{site_url:r.site_url,email:r.email}))}function dg(t){if(t==null)return {};if(typeof t=="string")try{return JSON.parse(t)}catch{return {}}return t}function pg(t){if(t==null)return [];if(Array.isArray(t))return t;if(typeof t=="string")try{return JSON.parse(t)}catch{return []}return []}function Wt(t){return typeof t=="string"?t:JSON.stringify(t??{})}var Os=class{constructor(e,n){this.db=e;this.dialect=n;this.schema="storage";}schema;table(e){return this.db.withSchema(this.schema).selectFrom(e)}insertInto(e){return this.db.withSchema(this.schema).insertInto(e)}update(e){return this.db.withSchema(this.schema).updateTable(e)}deleteFrom(e){return this.db.withSchema(this.schema).deleteFrom(e)}async createBucket(e){let n=new Date().toISOString(),r={id:e.id,name:e.name,owner:e.owner??null,owner_id:e.owner_id??null,public:e.public??false,file_size_limit:e.file_size_limit??null,allowed_mime_types:this.dialect==="postgres"?e.allowed_mime_types??null:Wt(e.allowed_mime_types??[]),created_at:n,updated_at:n};return await this.insertInto("buckets").values(r).execute(),await this.findBucketById(e.id)}async findBucketById(e){let n=await this.table("buckets").selectAll().where("id","=",e).executeTakeFirst();return n?this.parseBucketRow(n):null}async findBucketByName(e){let n=await this.table("buckets").selectAll().where("name","=",e).executeTakeFirst();return n?this.parseBucketRow(n):null}async listBuckets(){return (await this.table("buckets").selectAll().execute()).map(n=>this.parseBucketRow(n))}async updateBucket(e,n){let r={updated_at:new Date().toISOString()};return n.public!==void 0&&(r.public=n.public),n.file_size_limit!==void 0&&(r.file_size_limit=n.file_size_limit),n.allowed_mime_types!==void 0&&(r.allowed_mime_types=this.dialect==="postgres"?n.allowed_mime_types??null:Wt(n.allowed_mime_types)),await this.update("buckets").set(r).where("id","=",e).execute(),this.findBucketById(e)}async deleteBucket(e){await this.deleteFrom("buckets").where("id","=",e).execute();}async isBucketEmpty(e){let n=await this.table("objects").select(this.db.fn.count("id").as("count")).where("bucket_id","=",e).executeTakeFirst();return Number(n?.count??0)===0}async createObject(e){let n=new Date().toISOString(),r={id:e.id,bucket_id:e.bucket_id,name:e.name,owner:e.owner??null,owner_id:e.owner_id??null,metadata:Wt(e.metadata??{}),user_metadata:Wt(e.user_metadata??{}),version:e.version??null,created_at:n,updated_at:n,last_accessed_at:n};return this.dialect!=="postgres"&&(r.path_tokens=Wt(e.name.split("/"))),await this.insertInto("objects").values(r).execute(),await this.findObjectById(e.id)}async findObjectById(e){let n=await this.table("objects").selectAll().where("id","=",e).executeTakeFirst();return n?this.parseObjectRow(n):null}async findObjectByPath(e,n){let r=await this.table("objects").selectAll().where("bucket_id","=",e).where("name","=",n).executeTakeFirst();return r?this.parseObjectRow(r):null}async listObjects(e,n,r){let s=this.table("objects").selectAll().where("bucket_id","=",e);return n&&(s=s.where("name","like",`${n}%`)),r?.search&&(s=s.where("name","like",`%${r.search}%`)),r?.sortBy?s=s.orderBy(r.sortBy.column,r.sortBy.order):s=s.orderBy("name","asc"),r?.limit&&(s=s.limit(r.limit)),r?.offset&&(s=s.offset(r.offset)),(await s.execute()).map(o=>this.parseObjectRow(o))}async updateObject(e,n){let r={updated_at:new Date().toISOString()};return n.name!==void 0&&(r.name=n.name,this.dialect!=="postgres"&&(r.path_tokens=Wt(n.name.split("/")))),n.metadata!==void 0&&(r.metadata=Wt(n.metadata)),n.user_metadata!==void 0&&(r.user_metadata=Wt(n.user_metadata)),n.version!==void 0&&(r.version=n.version),n.owner!==void 0&&(r.owner=n.owner),n.owner_id!==void 0&&(r.owner_id=n.owner_id),await this.update("objects").set(r).where("id","=",e).execute(),this.findObjectById(e)}async deleteObject(e){await this.deleteFrom("objects").where("id","=",e).execute();}async deleteObjectsByBucket(e){let r=(await this.table("objects").select("name").where("bucket_id","=",e).execute()).map(s=>s.name);return r.length>0&&await this.deleteFrom("objects").where("bucket_id","=",e).execute(),r}async objectExists(e,n){return !!await this.table("objects").select("id").where("bucket_id","=",e).where("name","=",n).executeTakeFirst()}async touchObject(e){await this.update("objects").set({last_accessed_at:new Date().toISOString()}).where("id","=",e).execute();}parseBucketRow(e){return {...e,owner:e.owner??"",owner_id:e.owner_id??"",public:!!e.public,allowed_mime_types:e.allowed_mime_types==null?null:pg(e.allowed_mime_types)}}parseObjectRow(e){return {...e,metadata:dg(e.metadata),user_metadata:dg(e.user_metadata),path_tokens:pg(e.path_tokens)}}};var Z=class t extends Error{constructor(n,r,s){super(s);this.status=n;this.code=r;}name="StorageError";static bucketNotFound(n){return new t(404,"Bucket not found",`Bucket not found: ${n}`)}static bucketAlreadyExists(n){return new t(409,"Duplicate","The resource already exists")}static bucketNotEmpty(n){return new t(409,"ResourceNotEmpty","The bucket you tried to delete is not empty")}static objectNotFound(n){return new t(404,"Object not found",`Object not found: ${n}`)}static invalidMimeType(n,r){return new t(415,"invalid_mime_type",`mime type ${n} is not supported. Supported: ${r.join(", ")}`)}static fileTooLarge(n){return new t(413,"Payload too large",`The object exceeded the maximum allowed size of ${n} bytes`)}static invalidKey(n){return new t(400,"Invalid key",`Invalid object key: ${n}`)}static storageNotConfigured(){return new t(500,"Storage not configured","Storage is enabled but no storage adapter has been set. Set app._storageAdapter before making storage requests.")}toJSON(){return {statusCode:String(this.status),error:this.code,message:this.message}}};var Ps=class{constructor(e,n,r,s={},i){this.repo=e;this.adapter=n;this.config=r;this.options=s;this.transformationAdapter=i;}initialized=false;async init(){if(!this.initialized&&(this.initialized=true,this.options.autoCreateBuckets!==false&&this.config.buckets))for(let[e,n]of Object.entries(this.config.buckets))await this.repo.findBucketById(e)||await this.repo.createBucket({id:e,name:e,public:n.public??false,file_size_limit:n.file_size_limit?JT(n.file_size_limit):null,allowed_mime_types:n.allowed_mime_types});}async createBucket(e){if(await this.repo.findBucketById(e.id))throw Z.bucketAlreadyExists(e.id);return this.repo.createBucket(e)}async getBucket(e){let n=await this.repo.findBucketById(e);if(!n)throw Z.bucketNotFound(e);return n}async listBuckets(){return this.repo.listBuckets()}async updateBucket(e,n){if(!await this.repo.findBucketById(e))throw Z.bucketNotFound(e);return await this.repo.updateBucket(e,n)}async deleteBucket(e){if(!await this.repo.findBucketById(e))throw Z.bucketNotFound(e);if(!await this.repo.isBucketEmpty(e))throw Z.bucketNotEmpty(e);await this.repo.deleteBucket(e);}async emptyBucket(e){if(!await this.repo.findBucketById(e))throw Z.bucketNotFound(e);let r=await this.repo.deleteObjectsByBucket(e);r.length>0&&await this.adapter.deleteObjects(e,r);}async upload(e,n,r,s){Gc(n);let i=await this.repo.findBucketById(e);if(!i)throw Z.bucketNotFound(e);let o=s?.contentType??"application/octet-stream",a=s?.cacheControl??"no-cache";if(i.allowed_mime_types&&i.allowed_mime_types.length>0&&!i.allowed_mime_types.includes(o))throw Z.invalidMimeType(o,i.allowed_mime_types);let l=i.file_size_limit??this.config.fileSizeLimit??null;if(l&&s?.contentLength&&s.contentLength>l)throw Z.fileTooLarge(l);let c=await this.repo.findObjectByPath(e,n);if(c&&!s?.upsert)throw Z.bucketAlreadyExists(n);return await this.adapter.uploadObject(e,n,void 0,r,o,a),c&&s?.upsert?await this.repo.updateObject(c.id,{metadata:s?.metadata??c.metadata,version:crypto.randomUUID()}):this.repo.createObject({id:crypto.randomUUID(),bucket_id:e,name:n,owner:s?.owner??null,owner_id:s?.owner??null,metadata:s?.metadata??{},version:crypto.randomUUID()})}async download(e,n,r){let s=await this.repo.findObjectByPath(e,n);if(!s)throw Z.objectNotFound(n);if(await this.repo.touchObject(s.id),r?.transform&&this.transformationAdapter&&!this.transformationAdapter.requiresBuffer&&this.transformationAdapter.transformFromUrl){let o=await this.adapter.privateAssetUrl(e,n,s.version??void 0),a=await this.transformationAdapter.transformFromUrl(o,r.transform);return {body:a.body,metadata:{cacheControl:"public, max-age=3600",contentLength:a.contentLength??0,size:a.contentLength??0,mimetype:a.contentType,eTag:""}}}let i=await this.adapter.getObject(e,n,s.version??void 0);if(!i.body)throw Z.objectNotFound(n);if(r?.transform&&this.transformationAdapter?.requiresBuffer){let o=await KT(i.body),a=await this.transformationAdapter.transform(o,r.transform);return {body:a.body,metadata:{...i.metadata,mimetype:a.contentType,size:a.contentLength??0,contentLength:a.contentLength??0}}}return {body:i.body,metadata:i.metadata}}async update(e,n,r,s){return this.upload(e,n,r,{...s,upsert:s?.upsert??true})}async remove(e,n){if(!await this.repo.findBucketById(e))throw Z.bucketNotFound(e);let s=[];for(let i of n){let o=await this.repo.findObjectByPath(e,i);o&&(await this.adapter.deleteObject(e,i,o.version??void 0),await this.repo.deleteObject(o.id),s.push(o));}return s}async list(e,n,r){if(!await this.repo.findBucketById(e))throw Z.bucketNotFound(e);return this.repo.listObjects(e,n,r)}async move(e,n,r){Gc(r);let s=await this.repo.findObjectByPath(e,n);if(!s)throw Z.objectNotFound(n);await this.adapter.copyObject(e,n,s.version??void 0,r,void 0),await this.adapter.deleteObject(e,n,s.version??void 0),await this.repo.updateObject(s.id,{name:r,version:crypto.randomUUID()});}async copy(e,n,r){Gc(r);let s=await this.repo.findObjectByPath(e,n);if(!s)throw Z.objectNotFound(n);return await this.adapter.copyObject(e,n,s.version??void 0,r,void 0),await this.repo.createObject({id:crypto.randomUUID(),bucket_id:e,name:r,owner:s.owner,owner_id:s.owner_id,metadata:s.metadata,version:crypto.randomUUID()}),{key:r}}async info(e,n){let r=await this.repo.findObjectByPath(e,n);if(!r)throw Z.objectNotFound(n);let s=await this.adapter.headObject(e,n,r.version??void 0);return {...r,httpMetadata:s}}async exists(e,n){return this.repo.objectExists(e,n)}async createSignedUrl(e,n,r){if(!await this.repo.findObjectByPath(e,n))throw Z.objectNotFound(n);let i=await this.signStorageToken({sub:n,bucket:e,intent:"download"},r);return {signedUrl:`/storage/v1/object/sign/${e}/${n}?token=${i}`}}async createSignedUrls(e,n,r){let s=[];for(let i of n)try{let{signedUrl:o}=await this.createSignedUrl(e,i,r);s.push({path:i,signedUrl:o,error:null});}catch(o){s.push({path:i,signedUrl:"",error:o.message});}return s}async createSignedUploadUrl(e,n){if(!await this.repo.findBucketById(e))throw Z.bucketNotFound(e);let s=await this.signStorageToken({sub:n,bucket:e,intent:"upload"},7200);return {signedUrl:`/storage/v1/object/upload/sign/${e}/${n}?token=${s}`,token:s,path:n}}async verifySignedUrl(e){let n=new TextEncoder().encode(this.config.jwtSecret),{payload:r}=await jwtVerify(e,n,{algorithms:["HS256"]});return {bucket:r.bucket,path:r.sub,intent:r.intent}}async signStorageToken(e,n){let r=new TextEncoder().encode(this.config.jwtSecret),s=Math.floor(Date.now()/1e3);return new SignJWT({...e,iat:s}).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt(s).setExpirationTime(s+n).sign(r)}};async function KT(t){if(t instanceof Uint8Array||Buffer.isBuffer(t))return t;if(t instanceof Blob)return new Uint8Array(await t.arrayBuffer());let e=[],n=t.getReader();for(;;){let{done:r,value:s}=await n.read();if(r)break;e.push(s);}return Buffer.concat(e)}function Gc(t){if(!t||t.includes("..")||t.startsWith("/"))throw Z.invalidKey(t)}function JT(t){let e=t.match(/^(\d+(?:\.\d+)?)\s*(B|KB|KiB|MB|MiB|GB|GiB)$/i);if(!e)return 0;let n=Number.parseFloat(e[1]),r=e[2].toUpperCase();return Math.floor(n*({B:1,KB:1e3,KIB:1024,MB:1e6,MIB:1048576,GB:1e9,GIB:1073741824}[r]??1))}var GT=t=>t.req[mi][0].map(([[,e]])=>e);var zT=(t,e)=>GT(t).at(e??t.req.routeIndex)?.basePath??"",mg=new WeakMap,hg=(t,e)=>{e??=t.req.routeIndex;let n=mg.get(t)||[];if(typeof n[e]=="string")return n[e];let r,s=zT(t,e);if(!/[:*]/.test(s))r=s;else {let i=yi(s),o=t.req.path,a=0;for(let l=0,c=i.length;l<c;l++){let f=bi(i[l],i[l+1]);if(f){let u=f[2]===true||f==="*"?/[^\/]+/:f[2];a+=o.substring(a+1).match(u)?.[0].length||0;}else a+=i[l].length;a+=1;}r=o.substring(0,a);}return n[e]=r,mg.set(t,n),r};var VT=s.object({id:s.string(),name:s.string(),public:s.boolean({default:false}).optional(),file_size_limit:s.number().optional(),allowed_mime_types:s.array(s.string()).optional()}),QT=s.object({public:s.boolean().optional(),file_size_limit:s.number().optional(),allowed_mime_types:s.array(s.string()).optional()}),XT=s.object({prefix:s.string().optional(),limit:s.number().optional(),offset:s.number().optional(),sortBy:s.object({column:s.string(),order:s.string()}).optional(),search:s.string().optional()}),gg=s.object({bucketId:s.string(),sourceKey:s.string(),destinationKey:s.string()}),YT=s.object({expiresIn:s.number()}),ZT=s.object({expiresIn:s.number(),paths:s.array(s.string())}),eR=s.object({prefixes:s.array(s.string())}),tR=new _e().get("/status",async t=>t.json({status:"ok"},200)).get("/object/public/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=ft(t.req.path,`/object/public/${e}/`),{storageService:r}=t.var;if(!(await r.getBucket(e)).public)return t.json({error:"Bucket is not public"},400);let i=Vc(t.req.query()),o=await r.download(e,n,{transform:i??void 0});return new Response(o.body,{headers:Qc(o.metadata)})}).get("/object/sign/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=ft(t.req.path,`/object/sign/${e}/`),r=t.req.query("token"),{storageService:s}=t.var;if(!r)return t.json({error:"Missing token"},400);let i=await s.verifySignedUrl(r);if(i.bucket!==e||i.path!==n)return t.json({error:"Invalid token"},403);let o=Vc(t.req.query()),a=await s.download(e,n,{transform:o??void 0});return new Response(a.body,{headers:Qc(a.metadata)})}).put("/object/upload/sign/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=ft(t.req.path,`/object/upload/sign/${e}/`),r=t.req.query("token"),{storageService:s}=t.var;if(!r)return t.json({error:"Missing token"},400);let i=await s.verifySignedUrl(r);if(i.bucket!==e||i.path!==n||i.intent!=="upload")return t.json({error:"Invalid token"},403);let o=t.req.header("content-type")??"application/octet-stream",a=t.req.header("content-length")?Number.parseInt(t.req.header("content-length"),10):void 0,l=t.req.raw.body??new Uint8Array(await t.req.arrayBuffer()),c=await s.upload(e,n,l,{contentType:o,contentLength:a,upsert:true});return t.json({Key:c.name},200)}),zc=vs({acceptSecretApiKey:true}),nR=new _e().use("/bucket",zc).use("/bucket/*",zc).use("/object/*",zc).post("/bucket",validator("json",VT),async t=>{let e=t.req.valid("json"),{storageService:n}=t.var,r=await n.createBucket({id:e.id,name:e.name??e.id,public:e.public,file_size_limit:e.file_size_limit,allowed_mime_types:e.allowed_mime_types});return t.json({name:r.name},200)}).get("/bucket",async t=>{let{storageService:e}=t.var,n=await e.listBuckets();return t.json(n,200)}).get("/bucket/:id",async t=>{let{storageService:e}=t.var,n=await e.getBucket(t.req.param("id"));return t.json(n,200)}).put("/bucket/:id",validator("json",QT),async t=>{let{storageService:e}=t.var;return await e.updateBucket(t.req.param("id"),t.req.valid("json")),t.json({message:"Successfully updated"},200)}).delete("/bucket/:id",async t=>{let{storageService:e}=t.var;return await e.deleteBucket(t.req.param("id")),t.json({message:"Successfully deleted"},200)}).post("/bucket/:id/empty",async t=>{let{storageService:e}=t.var;return await e.emptyBucket(t.req.param("id")),t.json({message:"Empty bucket has been queued. Completion may take up to an hour."},200)}).post("/object/list/:bucketId",validator("json",XT),async t=>{let e=t.req.param("bucketId"),n=t.req.valid("json"),{storageService:r}=t.var,s=await r.list(e,n.prefix,{limit:n.limit,offset:n.offset,sortBy:n.sortBy,search:n.search});return t.json(s,200)}).post("/object/move",validator("json",gg),async t=>{let e=t.req.valid("json"),{storageService:n}=t.var;return await n.move(e.bucketId,e.sourceKey,e.destinationKey),t.json({message:"Successfully moved"},200)}).post("/object/copy",validator("json",gg),async t=>{let e=t.req.valid("json"),{storageService:n}=t.var,r=await n.copy(e.bucketId,e.sourceKey,e.destinationKey);return t.json({key:r.key},200)}).get("/object/info/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=ft(t.req.path,`/object/info/${e}/`),{storageService:r}=t.var,s=await r.info(e,n);return t.json(s,200)}).post("/object/sign/:bucketId/*",validator("json",YT),async t=>{let e=t.req.param("bucketId"),n=ft(t.req.path,`/object/sign/${e}/`),{expiresIn:r}=t.req.valid("json"),{storageService:s}=t.var,i=await s.createSignedUrl(e,n,r);return t.json(i,200)}).post("/object/sign/:bucketId",validator("json",ZT),async t=>{let e=t.req.param("bucketId"),{expiresIn:n,paths:r}=t.req.valid("json"),{storageService:s}=t.var,i=await s.createSignedUrls(e,r,n);return t.json(i,200)}).post("/object/upload/sign/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=ft(t.req.path,`/object/upload/sign/${e}/`),{storageService:r}=t.var,s=await r.createSignedUploadUrl(e,n);return t.json(s,200)}).delete("/object/:bucketId",validator("json",eR),async t=>{let e=t.req.param("bucketId"),{prefixes:n}=t.req.valid("json"),{storageService:r}=t.var,s=await r.remove(e,n);return t.json(s,200)}).post("/object/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=ft(t.req.path,`/object/${e}/`),{storageService:r}=t.var,s=t.req.header("content-type")??"application/octet-stream",i=t.req.header("cache-control")??"no-cache",o=t.req.header("x-upsert")==="true",a,l,c;if(s.startsWith("multipart/form-data")){let d=(await t.req.formData()).get("file");if(!d)throw new Z(400,"InvalidRequest","Missing file in multipart upload");let p=new Uint8Array(await d.arrayBuffer());a=p,l=d.type||"application/octet-stream",c=p.length;}else a=t.req.raw.body??new Uint8Array(await t.req.arrayBuffer()),l=s,c=t.req.header("content-length")?Number.parseInt(t.req.header("content-length"),10):void 0;let f=await r.upload(e,n,a,{contentType:l,cacheControl:i,contentLength:c,upsert:o,owner:t.get("userId")??null});return t.json({Key:`${e}/${f.name}`,Id:f.id},200)}).put("/object/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=ft(t.req.path,`/object/${e}/`),{storageService:r}=t.var,s=t.req.header("content-type")??"application/octet-stream",i=t.req.header("cache-control")??"no-cache",o=t.req.header("content-length")?Number.parseInt(t.req.header("content-length"),10):void 0,a=t.req.raw.body??new Uint8Array(await t.req.arrayBuffer()),l=await r.update(e,n,a,{contentType:s,cacheControl:i,contentLength:o,owner:t.get("userId")??null});return t.json({Key:`${e}/${l.name}`,Id:l.id},200)}).get("/object/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=ft(t.req.path,`/object/${e}/`),{storageService:r}=t.var,s=Vc(t.req.query()),i=await r.download(e,n,{transform:s??void 0});return new Response(i.body,{headers:Qc(i.metadata)})}).on("HEAD","/object/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=ft(t.req.path,`/object/${e}/`),{storageService:r}=t.var;return await r.exists(e,n)?t.body(null,200):t.body(null,404)}),Xc=new _e().onError((t,e)=>t instanceof Z?e.json(t.toJSON(),400):(console.error("Storage error:",t),e.json({error:"server_error",message:"Internal server error"},500))).route("/",tR).route("/",nR).all("*",async t=>{let e=t.req.path.replace(hg(t),"");return t.json({message:`Route ${t.req.method}:${e} not found`,error:"Not Found",statusCode:404},404)});function ft(t,e){let n=t.replace(/^\/storage\/v1/,""),r=n.indexOf(e);return r===-1?n.split("/").slice(3).join("/"):n.slice(r+e.length)}function Vc(t){let{width:e,height:n,resize:r,format:s,quality:i}=t;return !e&&!n&&!r&&!s&&!i?null:{width:e?Number.parseInt(e,10):void 0,height:n?Number.parseInt(n,10):void 0,resize:r,format:s,quality:i?Number.parseInt(i,10):void 0}}function Qc(t){let e={"Content-Type":t.mimetype,"Cache-Control":t.cacheControl,ETag:t.eTag};return t.contentLength&&(e["Content-Length"]=String(t.contentLength)),t.lastModified&&(e["Last-Modified"]=t.lastModified.toUTCString()),t.contentRange&&(e["Content-Range"]=t.contentRange),e}Un();var Yc=`-- supabase/storage core schema (Postgres)
159
159
  -- Source: supabase/storage migrations (consolidated)
160
160
 
161
161
  CREATE SCHEMA IF NOT EXISTS storage;
@@ -190,11 +190,11 @@ CREATE TABLE IF NOT EXISTS storage.objects (
190
190
  );
191
191
 
192
192
  CREATE INDEX IF NOT EXISTS storage_objects_name_pattern_search ON storage.objects (name text_pattern_ops);
193
- `;function ko(t=true){return t?Qr(zc):zc}var vo=class{driver=null;requiresBuffer=false;async transform(e,n){return {body:e,contentType:"application/octet-stream",contentLength:e.byteLength}}};function pg(t){if(!t._storageAdapter)throw Z.storageNotConfigured();let e=t.connection.dialect,n=new Os(t.connection.kysely,e),r=t.config.auth?.jwt_secret??"",s=t._transformationAdapter??new vo;return new Ps(n,t._storageAdapter,{jwtSecret:r,fileSizeLimit:t.config.storage?.file_size_limit?YT(t.config.storage.file_size_limit):void 0,buckets:t.config.storage?.buckets},{autoCreateBuckets:true},s)}function YT(t){let e=t.match(/^(\d+(?:\.\d+)?)\s*(B|KB|KiB|MB|MiB|GB|GiB)$/i);if(!e)return 0;let n=Number.parseFloat(e[1]),r=e[2].toUpperCase();return Math.floor(n*({B:1,KB:1e3,KIB:1024,MB:1e6,MIB:1048576,GB:1e9,GIB:1073741824}[r]??1))}var Ke=Symbol("RENDERER"),Jt=Symbol("ERROR_HANDLER"),ee=Symbol("STASH"),Ao=Symbol("INTERNAL"),Vc=Symbol("MEMO"),er=Symbol("PERMALINK");var Qc=t=>(t[Ao]=true,t);var Yc=t=>({value:e,children:n})=>{if(!n)return;let r={children:[{tag:Qc(()=>{t.push(e);}),props:{}}]};Array.isArray(n)?r.children.push(...n.flat()):r.children.push(n),r.children.push({tag:Qc(()=>{t.pop();}),props:{}});let s={tag:"",props:r,type:""};return s[Jt]=i=>{throw t.pop(),i},s},Oo=t=>{let e=[t],n=Yc(e);return n.values=e,n.Provider=n,Tt.push(n),n};var Tt=[],$s=t=>{let e=[t],n=(r=>{e.push(r.value);let s;try{s=r.children?(Array.isArray(r.children)?new Xc("",{},r.children):r.children).toString():"";}catch(i){throw e.pop(),i}return s instanceof Promise?s.finally(()=>e.pop()).then(i=>X(i,i.callbacks)):(e.pop(),X(s))});return n.values=e,n.Provider=n,n[Ke]=Yc(e),Tt.push(n),n},Re=t=>t.values.at(-1);var tr={title:[],script:["src"],style:["data-href"],link:["href"],meta:["name","httpEquiv","charset","itemProp"]},Is={},nr="data-precedence";var js={};Zs(js,{button:()=>iR,form:()=>rR,input:()=>sR,link:()=>tR,meta:()=>nR,script:()=>ZT,style:()=>eR,title:()=>XT});var wn=t=>Array.isArray(t)?t:[t];var mg=new WeakMap,hg=(t,e,n,r)=>({buffer:s,context:i})=>{if(!s)return;let o=mg.get(i)||{};mg.set(i,o);let a=o[t]||=[],l=false,c=tr[t];if(c.length>0){e:for(let[,f]of a)for(let u of c)if((f?.[u]??null)===n?.[u]){l=true;break e}}if(l?s[0]=s[0].replaceAll(e,""):c.length>0?a.push([e,n,r]):a.unshift([e,n,r]),s[0].indexOf("</head>")!==-1){let f;if(r===void 0)f=a.map(([u])=>u);else {let u=[];f=a.map(([d,,p])=>{let g=u.indexOf(p);return g===-1&&(u.push(p),g=u.length-1),[d,g]}).sort((d,p)=>d[1]-p[1]).map(([d])=>d);}f.forEach(u=>{s[0]=s[0].replaceAll(u,"");}),s[0]=s[0].replace(/(?=<\/head>)/,f.join(""));}},Ns=(t,e,n)=>X(new Ue(t,n,wn(e??[])).toString()),Ds=(t,e,n,r)=>{if("itemProp"in n)return Ns(t,e,n);let{precedence:s,blocking:i,...o}=n;s=r?s??"":void 0,r&&(o[nr]=s);let a=new Ue(t,o,wn(e||[])).toString();return a instanceof Promise?a.then(l=>X(a,[...l.callbacks||[],hg(t,l,o,s)])):X(a,[hg(t,a,o,s)])},XT=({children:t,...e})=>{let n=Po();if(n){let r=Re(n);if(r==="svg"||r==="head")return new Ue("title",e,wn(t??[]))}return Ds("title",t,e,false)},ZT=({children:t,...e})=>{let n=Po();return ["src","async"].some(r=>!e[r])||n&&Re(n)==="head"?Ns("script",t,e):Ds("script",t,e,false)},eR=({children:t,...e})=>["href","precedence"].every(n=>n in e)?(e["data-href"]=e.href,delete e.href,Ds("style",t,e,true)):Ns("style",t,e),tR=({children:t,...e})=>["onLoad","onError"].some(n=>n in e)||e.rel==="stylesheet"&&(!("precedence"in e)||"disabled"in e)?Ns("link",t,e):Ds("link",t,e,"precedence"in e),nR=({children:t,...e})=>{let n=Po();return n&&Re(n)==="head"?Ns("meta",t,e):Ds("meta",t,e,false)},gg=(t,{children:e,...n})=>new Ue(t,n,wn(e??[])),rR=t=>(typeof t.action=="function"&&(t.action=er in t.action?t.action[er]:void 0),gg("form",t)),yg=(t,e)=>(typeof e.formAction=="function"&&(e.formAction=er in e.formAction?e.formAction[er]:void 0),gg(t,e)),sR=t=>yg("input",t),iR=t=>yg("button",t);var oR=new Map([["className","class"],["htmlFor","for"],["crossOrigin","crossorigin"],["httpEquiv","http-equiv"],["itemProp","itemprop"],["fetchPriority","fetchpriority"],["noModule","nomodule"],["formAction","formaction"]]),rr=t=>oR.get(t)||t,Ls=(t,e)=>{for(let[n,r]of Object.entries(t)){let s=n[0]==="-"||!/[A-Z]/.test(n)?n:n.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);e(s,r==null?null:typeof r=="number"?s.match(/^(?:a|border-im|column(?:-c|s)|flex(?:$|-[^b])|grid-(?:ar|[^a])|font-w|li|or|sca|st|ta|wido|z)|ty$/)?`${r}`:`${r}px`:r);}};var Fs=void 0,Po=()=>Fs,aR=t=>/[A-Z]/.test(t)&&t.match(/^(?:al|basel|clip(?:Path|Rule)$|co|do|fill|fl|fo|gl|let|lig|i|marker[EMS]|o|pai|pointe|sh|st[or]|text[^L]|tr|u|ve|w)/)?t.replace(/([A-Z])/g,"-$1").toLowerCase():t,lR=["area","base","br","col","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"],cR=["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","download","formnovalidate","hidden","inert","ismap","itemscope","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"],eu=(t,e)=>{for(let n=0,r=t.length;n<r;n++){let s=t[n];if(typeof s=="string")bt(s,e);else {if(typeof s=="boolean"||s===null||s===void 0)continue;s instanceof Ue?s.toStringToBuffer(e):typeof s=="number"||s.isEscaped?e[0]+=s:s instanceof Promise?e.unshift("",s):eu(s,e);}}},Ue=class{tag;props;key;children;isEscaped=true;localContexts;constructor(t,e,n){this.tag=t,this.props=e,this.children=n;}get type(){return this.tag}get ref(){return this.props.ref||null}toString(){let t=[""];this.localContexts?.forEach(([e,n])=>{e.values.push(n);});try{this.toStringToBuffer(t);}finally{this.localContexts?.forEach(([e])=>{e.values.pop();});}return t.length===1?"callbacks"in t?Ea(X(t[0],t.callbacks)).toString():t[0]:bi(t,t.callbacks)}toStringToBuffer(t){let e=this.tag,n=this.props,{children:r}=this;t[0]+=`<${e}`;let s=Fs&&Re(Fs)==="svg"?i=>aR(rr(i)):i=>rr(i);for(let[i,o]of Object.entries(n))if(i=s(i),i!=="children"){if(i==="style"&&typeof o=="object"){let a="";Ls(o,(l,c)=>{c!=null&&(a+=`${a?";":""}${l}:${c}`);}),t[0]+=' style="',bt(a,t),t[0]+='"';}else if(typeof o=="string")t[0]+=` ${i}="`,bt(o,t),t[0]+='"';else if(o!=null)if(typeof o=="number"||o.isEscaped)t[0]+=` ${i}="${o}"`;else if(typeof o=="boolean"&&cR.includes(i))o&&(t[0]+=` ${i}=""`);else if(i==="dangerouslySetInnerHTML"){if(r.length>0)throw new Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");r=[X(o.__html)];}else if(o instanceof Promise)t[0]+=` ${i}="`,t.unshift('"',o);else if(typeof o=="function"){if(!i.startsWith("on")&&i!=="ref")throw new Error(`Invalid prop '${i}' of type 'function' supplied to '${e}'.`)}else t[0]+=` ${i}="`,bt(o.toString(),t),t[0]+='"';}if(lR.includes(e)&&r.length===0){t[0]+="/>";return}t[0]+=">",eu(r,t),t[0]+=`</${e}>`;}},Zc=class extends Ue{toStringToBuffer(t){let{children:e}=this,n={...this.props};e.length&&(n.children=e.length===1?e[0]:e);let r=this.tag.call(null,n);if(!(typeof r=="boolean"||r==null))if(r instanceof Promise)if(Tt.length===0)t.unshift("",r);else {let s=Tt.map(i=>[i,i.values.at(-1)]);t.unshift("",r.then(i=>(i instanceof Ue&&(i.localContexts=s),i)));}else r instanceof Ue?r.toStringToBuffer(t):typeof r=="number"||r.isEscaped?(t[0]+=r,r.callbacks&&(t.callbacks||=[],t.callbacks.push(...r.callbacks))):bt(r,t);}},Xc=class extends Ue{toStringToBuffer(t){eu(this.children,t);}},bg=false,Us=(t,e,n)=>{if(!bg){for(let r in Is)js[r][Ke]=Is[r];bg=true;}return typeof t=="function"?new Zc(t,e,n):js[t]?new Zc(js[t],e,n):t==="svg"||t==="head"?(Fs||=$s(""),new Ue(t,e,[new Zc(Fs,{value:t},n)])):new Ue(t,e,n)};var dt=({children:t})=>new Xc("",{children:t},Array.isArray(t)?t:t?[t]:[]);var Do={};Zs(Do,{button:()=>Kg,clearCache:()=>_R,composeRef:()=>No,form:()=>qg,input:()=>Wg,link:()=>Ug,meta:()=>Mg,script:()=>Lg,style:()=>Fg,title:()=>jg});var Bs="_hp",uR={Change:"Input",DoubleClick:"DblClick"},fR={svg:"2000/svg",math:"1998/Math/MathML"},pt=[],ru=new WeakMap,sr=void 0,Rg=()=>sr,Rt=t=>"t"in t,nu={onClick:["click",false]},wg=t=>{if(!t.startsWith("on"))return;if(nu[t])return nu[t];let e=t.match(/^on([A-Z][a-zA-Z]+?(?:PointerCapture)?)(Capture)?$/);if(e){let[,n,r]=e;return nu[t]=[(uR[n]||n).toLowerCase(),!!r]}},Sg=(t,e)=>sr&&t instanceof SVGElement&&/[A-Z]/.test(e)&&(e in t.style||e.match(/^(?:o|pai|str|u|ve)/))?e.replace(/([A-Z])/g,"-$1").toLowerCase():e,dR=(t,e,n)=>{e||={};for(let r in e){let s=e[r];if(r!=="children"&&(!n||n[r]!==s)){r=rr(r);let i=wg(r);if(i){if(n?.[r]!==s&&(n&&t.removeEventListener(i[0],n[r],i[1]),s!=null)){if(typeof s!="function")throw new Error(`Event handler for "${r}" is not a function`);t.addEventListener(i[0],s,i[1]);}}else if(r==="dangerouslySetInnerHTML"&&s)t.innerHTML=s.__html;else if(r==="ref"){let o;typeof s=="function"?o=s(t)||(()=>s(null)):s&&"current"in s&&(s.current=t,o=()=>s.current=null),ru.set(t,o);}else if(r==="style"){let o=t.style;typeof s=="string"?o.cssText=s:(o.cssText="",s!=null&&Ls(s,o.setProperty.bind(o)));}else {if(r==="value"){let a=t.nodeName;if(a==="INPUT"||a==="TEXTAREA"||a==="SELECT"){if(t.value=s==null||s===false?null:s,a==="TEXTAREA"){t.textContent=s;continue}else if(a==="SELECT"){t.selectedIndex===-1&&(t.selectedIndex=0);continue}}}else (r==="checked"&&t.nodeName==="INPUT"||r==="selected"&&t.nodeName==="OPTION")&&(t[r]=s);let o=Sg(t,r);s==null||s===false?t.removeAttribute(o):s===true?t.setAttribute(o,""):typeof s=="string"||typeof s=="number"?t.setAttribute(o,s):t.setAttribute(o,s.toString());}}}if(n)for(let r in n){let s=n[r];if(r!=="children"&&!(r in e)){r=rr(r);let i=wg(r);i?t.removeEventListener(i[0],s,i[1]):r==="ref"?ru.get(t)?.():t.removeAttribute(Sg(t,r));}}},pR=(t,e)=>{e[ee][0]=0,pt.push([t,e]);let n=e.tag[Ke]||e.tag,r=n.defaultProps?{...n.defaultProps,...e.props}:e.props;try{return [n.call(null,r)]}finally{pt.pop();}},Cg=(t,e,n,r,s)=>{t.vR?.length&&(r.push(...t.vR),delete t.vR),typeof t.tag=="function"&&t[ee][1][iu]?.forEach(i=>s.push(i)),t.vC.forEach(i=>{if(Rt(i))n.push(i);else if(typeof i.tag=="function"||i.tag===""){i.c=e;let o=n.length;if(Cg(i,e,n,r,s),i.s){for(let a=o;a<n.length;a++)n[a].s=true;i.s=false;}}else n.push(i),i.vR?.length&&(r.push(...i.vR),delete i.vR);});},mR=t=>{for(;t&&(t.tag===Bs||!t.e);)t=t.tag===Bs||!t.vC?.[0]?t.nN:t.vC[0];return t?.e},kg=t=>{Rt(t)||(t[ee]?.[1][iu]?.forEach(e=>e[2]?.()),ru.get(t.e)?.(),t.p===2&&t.vC?.forEach(e=>e.p=2),t.vC?.forEach(kg)),t.p||(t.e?.remove(),delete t.e),typeof t.tag=="function"&&(Ms.delete(t),$o.delete(t),delete t[ee][3],t.a=true);},vg=(t,e,n)=>{t.c=e,Ag(t,e,n);},_g=(t,e)=>{if(e){for(let n=0,r=t.length;n<r;n++)if(t[n]===e)return n}},Eg=Symbol(),Ag=(t,e,n)=>{let r=[],s=[],i=[];Cg(t,e,r,s,i),s.forEach(kg);let o=n?void 0:e.childNodes,a,l=null;if(n)a=-1;else if(!o.length)a=0;else {let c=_g(o,mR(t.nN));c!==void 0?(l=o[c],a=c):a=_g(o,r.find(f=>f.tag!==Bs&&f.e)?.e)??-1,a===-1&&(n=true);}for(let c=0,f=r.length;c<f;c++,a++){let u=r[c],d;if(u.s&&u.e)d=u.e,u.s=false;else {let p=n||!u.e;Rt(u)?(u.e&&u.d&&(u.e.textContent=u.t),u.d=false,d=u.e||=document.createTextNode(u.t)):(d=u.e||=u.n?document.createElementNS(u.n,u.tag):document.createElement(u.tag),dR(d,u.props,u.pP),Ag(u,d,p));}u.tag===Bs?a--:n?d.parentNode||e.appendChild(d):o[a]!==d&&o[a-1]!==d&&(o[a+1]===d?e.appendChild(o[a]):e.insertBefore(d,l||o[a]||null));}if(t.pP&&(t.pP=void 0),i.length){let c=[],f=[];i.forEach(([,u,,d,p])=>{u&&c.push(u),d&&f.push(d),p?.();}),c.forEach(u=>u()),f.length&&requestAnimationFrame(()=>{f.forEach(u=>u());});}},hR=(t,e)=>!!(t&&t.length===e.length&&t.every((n,r)=>n[1]===e[r][1])),$o=new WeakMap,su=(t,e,n)=>{let r=!n&&e.pC;n&&(e.pC||=e.vC);let s;try{n||=typeof e.tag=="function"?pR(t,e):wn(e.props.children),n[0]?.tag===""&&n[0][Jt]&&(s=n[0][Jt],t[5].push([t,s,e]));let i=r?[...e.pC]:e.vC?[...e.vC]:void 0,o=[],a;for(let l=0;l<n.length;l++){if(Array.isArray(n[l])){n.splice(l,1,...n[l].flat(1/0)),l--;continue}let c=gR(n[l]);if(c){typeof c.tag=="function"&&!c.tag[Ao]&&(Tt.length>0&&(c[ee][2]=Tt.map(u=>[u,u.values.at(-1)])),t[5]?.length&&(c[ee][3]=t[5].at(-1)));let f;if(i&&i.length){let u=i.findIndex(Rt(c)?d=>Rt(d):c.key!==void 0?d=>d.key===c.key&&d.tag===c.tag:d=>d.tag===c.tag);u!==-1&&(f=i[u],i.splice(u,1));}if(f)if(Rt(c))f.t!==c.t&&(f.t=c.t,f.d=!0),c=f;else {let u=f.pP=f.props;if(f.props=c.props,f.f||=c.f||e.f,typeof c.tag=="function"){let d=f[ee][2];f[ee][2]=c[ee][2]||[],f[ee][3]=c[ee][3],!f.f&&((f.o||f)===c.o||f.tag[Vc]?.(u,f.props))&&hR(d,f[ee][2])&&(f.s=!0);}c=f;}else if(!Rt(c)&&sr){let u=Re(sr);u&&(c.n=u);}if(!Rt(c)&&!c.s&&(su(t,c),delete c.f),o.push(c),a&&!a.s&&!c.s)for(let u=a;u&&!Rt(u);u=u.vC?.at(-1))u.nN=c;a=c;}}e.vR=r?[...e.vC,...i||[]]:i||[],e.vC=o,r&&delete e.pC;}catch(i){if(e.f=true,i===Eg){if(s)return;throw i}let[o,a,l]=e[ee]?.[3]||[];if(a){let c=()=>qs([0,false,t[2]],l),f=$o.get(l)||[];f.push(c),$o.set(l,f);let u=a(i,()=>{let d=$o.get(l);if(d){let p=d.indexOf(c);if(p!==-1)return d.splice(p,1),c()}});if(u){if(t[0]===1)t[1]=true;else if(su(t,l,[u]),(a.length===1||t!==o)&&l.c){vg(l,l.c,false);return}throw Eg}}throw i}finally{s&&t[5].pop();}},gR=t=>{if(!(t==null||typeof t=="boolean")){if(typeof t=="string"||typeof t=="number")return {t:t.toString(),d:true};if("vR"in t&&(t={tag:t.tag,props:t.props,key:t.key,f:t.f,type:t.tag,ref:t.props.ref,o:t.o||t}),typeof t.tag=="function")t[ee]=[0,[]];else {let e=fR[t.tag];e&&(sr||=Oo(""),t.props.children=[{tag:sr,props:{value:t.n=`http://www.w3.org/${e}`,children:t.props.children}}]);}return t}};var xg=(t,e)=>{e[ee][2]?.forEach(([n,r])=>{n.values.push(r);});try{su(t,e,void 0);}catch{return}if(e.a){delete e.a;return}e[ee][2]?.forEach(([n])=>{n.values.pop();}),(t[0]!==1||!t[1])&&vg(e,e.c,false);},Ms=new WeakMap,Tg=[],qs=async(t,e)=>{t[5]||=[];let n=Ms.get(e);n&&n[0](void 0);let r,s=new Promise(i=>r=i);if(Ms.set(e,[r,()=>{t[2]?t[2](t,e,i=>{xg(i,e);}).then(()=>r(e)):(xg(t,e),r(e));}]),Tg.length)Tg.at(-1).add(e);else {await Promise.resolve();let i=Ms.get(e);i&&(Ms.delete(e),i[1]());}return s};var Og=(t,e,n)=>({tag:Bs,props:{children:t},key:n,e,p:1});var yR=0,iu=1,bR=2,wR=3;var ou=new WeakMap,$g=(t,e)=>!t||!e||t.length!==e.length||e.some((n,r)=>n!==t[r]);var SR=void 0;var Pg=[];var Io=t=>{let e=()=>typeof t=="function"?t():t,n=pt.at(-1);if(!n)return [e(),()=>{}];let[,r]=n,s=r[ee][1][yR]||=[],i=r[ee][0]++;return s[i]||=[e(),o=>{let a=SR,l=s[i];if(typeof o=="function"&&(o=o(l[0])),!Object.is(o,l[0]))if(l[0]=o,Pg.length){let[c,f]=Pg.at(-1);Promise.all([c===3?r:qs([c,false,a],r),f]).then(([u])=>{if(!u||!(c===2||c===3))return;let d=u.vC;requestAnimationFrame(()=>{setTimeout(()=>{d===u.vC&&qs([c===3?1:0,false,a],u);});});});}else qs([0,false,a],r);}]};var ir=(t,e)=>{let n=pt.at(-1);if(!n)return t;let[,r]=n,s=r[ee][1][bR]||=[],i=r[ee][0]++,o=s[i];return $g(o?.[1],e)?s[i]=[t,e]:t=s[i][0],t};var au=t=>{let e=ou.get(t);if(e){if(e.length===2)throw e[1];return e[0]}throw t.then(n=>ou.set(t,[n]),n=>ou.set(t,[void 0,n])),t},lu=(t,e)=>{let n=pt.at(-1);if(!n)return t();let[,r]=n,s=r[ee][1][wR]||=[],i=r[ee][0]++,o=s[i];return $g(o?.[1],e)&&(s[i]=[t(),e]),s[i][0]};var Ng=Oo({pending:false,data:null,method:null,action:null}),Ig=new Set,Dg=t=>{Ig.add(t),t.finally(()=>Ig.delete(t));};var _R=()=>{cu=Object.create(null),uu=Object.create(null);},No=(t,e)=>lu(()=>n=>{let r;t&&(typeof t=="function"?r=t(n)||(()=>{t(null);}):t&&"current"in t&&(t.current=n,r=()=>{t.current=null;}));let s=e(n);return ()=>{s?.(),r?.();}},[t]),cu=Object.create(null),uu=Object.create(null),Hs=(t,e,n,r,s)=>{if(e?.itemProp)return {tag:t,props:e,type:t,ref:e.ref};let i=document.head,{onLoad:o,onError:a,precedence:l,blocking:c,...f}=e,u=null,d=false,p=tr[t],g;if(p.length>0){let w=i.querySelectorAll(t);e:for(let S of w)for(let b of tr[t])if(S.getAttribute(b)===e[b]){u=S;break e}if(!u){let S=p.reduce((b,_)=>e[_]===void 0?b:`${b}-${_}-${e[_]}`,t);d=!uu[S],u=uu[S]||=(()=>{let b=document.createElement(t);for(let _ of p)e[_]!==void 0&&b.setAttribute(_,e[_]),e.rel&&b.setAttribute("rel",e.rel);return b})();}}else g=i.querySelectorAll(t);l=r?l??"":void 0,r&&(f[nr]=l);let m=ir(w=>{if(p.length>0){let S=false;for(let b of i.querySelectorAll(t)){if(S&&b.getAttribute(nr)!==l){i.insertBefore(w,b);return}b.getAttribute(nr)===l&&(S=true);}i.appendChild(w);}else if(g){let S=false;for(let b of g)if(b===w){S=true;break}S||i.insertBefore(w,i.contains(g[0])?g[0]:i.querySelector(t)),g=void 0;}},[l]),h=No(e.ref,w=>{let S=p[0];if(n===2&&(w.innerHTML=""),(d||g)&&m(w),!a&&!o)return;let b=cu[w.getAttribute(S)]||=new Promise((_,E)=>{w.addEventListener("load",_),w.addEventListener("error",E);});o&&(b=b.then(o)),a&&(b=b.catch(a)),b.catch(()=>{});});if(s&&c==="render"){let w=tr[t][0];if(e[w]){let S=e[w],b=cu[S]||=new Promise((_,E)=>{m(u),u.addEventListener("load",_),u.addEventListener("error",E);});au(b);}}let y={tag:t,type:t,props:{...f,ref:h},ref:h};return y.p=n,u&&(y.e=u),Og(y,i)},jg=t=>{let e=Rg();return (e&&Re(e))?.endsWith("svg")?{tag:"title",props:t,type:"title",ref:t.ref}:Hs("title",t,void 0,false,false)},Lg=t=>!t||["src","async"].some(e=>!t[e])?{tag:"script",props:t,type:"script",ref:t.ref}:Hs("script",t,1,false,true),Fg=t=>!t||!["href","precedence"].every(e=>e in t)?{tag:"style",props:t,type:"style",ref:t.ref}:(t["data-href"]=t.href,delete t.href,Hs("style",t,2,true,true)),Ug=t=>!t||["onLoad","onError"].some(e=>e in t)||t.rel==="stylesheet"&&(!("precedence"in t)||"disabled"in t)?{tag:"link",props:t,type:"link",ref:t.ref}:Hs("link",t,1,"precedence"in t,true),Mg=t=>Hs("meta",t,void 0,false,false),Bg=Symbol(),qg=t=>{let{action:e,...n}=t;typeof e!="function"&&(n.action=e);let[r,s]=Io([null,false]),i=ir(async c=>{let f=c.isTrusted?e:c.detail[Bg];if(typeof f!="function")return;c.preventDefault();let u=new FormData(c.target);s([u,true]);let d=f(u);d instanceof Promise&&(Dg(d),await d),s([null,true]);},[]),o=No(t.ref,c=>(c.addEventListener("submit",i),()=>{c.removeEventListener("submit",i);})),[a,l]=r;return r[1]=false,{tag:Ng,props:{value:{pending:a!==null,data:a,method:a?"post":null,action:a?e:null},children:{tag:"form",props:{...n,ref:o},type:"form",ref:o}},f:l}},Hg=(t,{formAction:e,...n})=>{if(typeof e=="function"){let r=ir(s=>{s.preventDefault(),s.currentTarget.form.dispatchEvent(new CustomEvent("submit",{detail:{[Bg]:e}}));},[]);n.ref=No(n.ref,s=>(s.addEventListener("click",r),()=>{s.removeEventListener("click",r);}));}return {tag:t,props:n,type:t,ref:n.ref}},Wg=t=>Hg("input",t),Kg=t=>Hg("button",t);Object.assign(Is,{title:jg,script:Lg,style:Fg,link:Ug,meta:Mg,form:qg,input:Wg,button:Kg});$s(null);new TextEncoder;var Sn=":-hono-global",RR=new RegExp(`^${Sn}{(.*)}$`),Fo="hono-css",Ct=Symbol(),ge=Symbol(),De=Symbol(),mt=Symbol(),Uo=Symbol(),Qg=Symbol();var Yg=t=>{let e=0,n=11;for(;e<t.length;)n=101*n+t.charCodeAt(e++)>>>0;return "css-"+n},CR=['"(?:(?:\\\\[\\s\\S]|[^"\\\\])*)"',"'(?:(?:\\\\[\\s\\S]|[^'\\\\])*)'"].join("|"),kR=new RegExp(["("+CR+")","(?:"+["^\\s+","\\/\\*.*?\\*\\/\\s*","\\/\\/.*\\n\\s*","\\s+$"].join("|")+")","\\s*;\\s*(}|$)\\s*","\\s*([{};:,])\\s*","(\\s)\\s+"].join("|"),"g"),vR=t=>t.replace(kR,(e,n,r,s,i)=>n||r||s||i||""),Xg=(t,e)=>{let n=[],r=[],s=t[0].match(/^\s*\/\*(.*?)\*\//)?.[1]||"",i="";for(let o=0,a=t.length;o<a;o++){i+=t[o];let l=e[o];if(!(typeof l=="boolean"||l===null||l===void 0)){Array.isArray(l)||(l=[l]);for(let c=0,f=l.length;c<f;c++){let u=l[c];if(!(typeof u=="boolean"||u===null||u===void 0))if(typeof u=="string")/([\\"'\/])/.test(u)?i+=u.replace(/([\\"']|(?<=<)\/)/g,"\\$1"):i+=u;else if(typeof u=="number")i+=u;else if(u[Qg])i+=u[Qg];else if(u[ge].startsWith("@keyframes "))n.push(u),i+=` ${u[ge].substring(11)} `;else {if(t[o+1]?.match(/^\s*{/))n.push(u),u=`.${u[ge]}`;else {n.push(...u[mt]),r.push(...u[Uo]),u=u[De];let d=u.length;if(d>0){let p=u[d-1];p!==";"&&p!=="}"&&(u+=";");}}i+=`${u||""}`;}}}}return [s,vR(i),n,r]},or=(t,e)=>{let[n,r,s,i]=Xg(t,e),o=RR.exec(r);o&&(r=o[1]);let a=(o?Sn:"")+Yg(n+r),l=(o?s.map(c=>c[ge]):[a,...i]).join(" ");return {[Ct]:a,[ge]:l,[De]:r,[mt]:s,[Uo]:i}},Mo=t=>{for(let e=0,n=t.length;e<n;e++){let r=t[e];typeof r=="string"&&(t[e]={[Ct]:"",[ge]:"",[De]:"",[mt]:[],[Uo]:[r]});}return t},Bo=(t,...e)=>{let[n,r]=Xg(t,e);return {[Ct]:"",[ge]:`@keyframes ${Yg(n+r)}`,[De]:r,[mt]:[],[Uo]:[]}},AR=0,qo=((t,e)=>{t||(t=[`/* h-v-t ${AR++} */`]);let n=Array.isArray(t)?or(t,e):t,r=n[ge],s=or(["view-transition-name:",""],[r]);return n[ge]=Sn+n[ge],n[De]=n[De].replace(/(?<=::view-transition(?:[a-z-]*)\()(?=\))/g,r),s[ge]=s[Ct]=r,s[mt]=[...n[mt],n],s});var PR=t=>{let e=[],n=0,r=0;for(let s=0,i=t.length;s<i;s++){let o=t[s];if(o==="'"||o==='"'){let a=o;for(s++;s<i;s++){if(t[s]==="\\"){s++;continue}if(t[s]===a)break}continue}if(o==="{"){r++;continue}if(o==="}"){r--,r===0&&(e.push(t.slice(n,s+1)),n=s+1);continue}}return e},pu=({id:t})=>{let e,n=()=>(e||(e=document.querySelector(`style#${t}`)?.sheet,e&&(e.addedStyles=new Set)),e?[e,e.addedStyles]:[]),r=(o,a)=>{let[l,c]=n();if(!l||!c){Promise.resolve().then(()=>{if(!n()[0])throw new Error("style sheet not found");r(o,a);});return}c.has(o)||(c.add(o),(o.startsWith(Sn)?PR(a):[`${o[0]==="@"?"":"."}${o}{${a}}`]).forEach(f=>{l.insertRule(f,l.cssRules.length);}));};return [{toString(){let o=this[Ct];return r(o,this[De]),this[mt].forEach(({[ge]:a,[De]:l})=>{r(a,l);}),this[ge]}},({children:o,nonce:a})=>({tag:"style",props:{id:t,nonce:a,children:o&&(Array.isArray(o)?o:[o]).map(l=>l[De])}})]};var IR=({id:t})=>{let[e,n]=pu({id:t}),r=new WeakMap,s=new WeakMap,i=new RegExp(`(<style id="${t}"(?: nonce="[^"]*")?>.*?)(</style>)`),o=d=>{let p=({buffer:y,context:w})=>{let[S,b]=r.get(w),_=Object.keys(S);if(!_.length)return;let E="";if(_.forEach(v=>{b[v]=true,E+=v.startsWith(Sn)?S[v]:`${v[0]==="@"?"":"."}${v}{${S[v]}}`;}),r.set(w,[{},b]),y&&i.test(y[0])){y[0]=y[0].replace(i,(v,P,C)=>`${P}${E}${C}`);return}let x=s.get(w),O=`<script${x?` nonce="${x}"`:""}>document.querySelector('#${t}').textContent+=${JSON.stringify(E)}</script>`;if(y){y[0]=`${O}${y[0]}`;return}return Promise.resolve(O)},g=({context:y})=>{r.has(y)||r.set(y,[{},{}]);let[w,S]=r.get(y),b=true;if(S[d[Ct]]||(b=false,w[d[Ct]]=d[De]),d[mt].forEach(({[ge]:_,[De]:E})=>{S[_]||(b=false,w[_]=E);}),!b)return Promise.resolve(X("",[p]))},m=new String(d[ge]);Object.assign(m,d),m.isEscaped=true,m.callbacks=[g];let h=Promise.resolve(m);return Object.assign(h,d),h.toString=e.toString,h},a=(d,...p)=>o(or(d,p)),l=(...d)=>(d=Mo(d),a(Array(d.length).fill(""),...d)),c=Bo,f=((d,...p)=>o(qo(d,p))),u=({children:d,nonce:p}={})=>X(`<style id="${t}"${p?` nonce="${p}"`:""}>${d?d[De]:""}</style>`,[({context:g})=>{s.set(g,p);}]);return u[Ke]=n,{css:a,cx:l,keyframes:c,viewTransition:f,Style:u}},Ks=IR({id:Fo}),Zg=Ks.Style;function ye(t,e,n){let r;if(!e||!("children"in e))r=Us(t,e,[]);else {let s=e.children;r=Array.isArray(s)?Us(t,e,s):Us(t,e,[s]);}return r.key=n,r}var mu=new _e().get("/*",async t=>{let e={js:"main.js",css:["styles.css"]},n="/static/",r=await Promise.resolve().then(()=>ca(ey())).then(s=>s.default);try{let s=Object.values(r).find(i=>i.isEntry);if(!s)throw new Error("No entry found in manifest");e.js=s?.file,e.css=s?.css??[];}catch(s){console.warn("Couldn't find assets in manifest",s);}return t.html(ye(dt,{children:ye("html",{lang:"en","data-theme":"dark",style:"color-scheme: dark",class:"dark",children:[ye("head",{children:[ye("meta",{charset:"UTF-8"}),ye("meta",{name:"viewport",content:"width=device-width, initial-scale=1, maximum-scale=1"}),ye("link",{rel:"icon",href:n+"favicon.ico",type:"image/x-icon"}),ye("title",{children:"Supalite"}),ye(dt,{children:[ye("script",{type:"module",src:n+e?.js}),e?.css.map((s,i)=>ye("link",{rel:"stylesheet",href:n+s},i))]}),ye(Zg,{})]}),ye("body",{children:ye("div",{id:"root"})})]})}))});async function DR(t){return mu.fetch(t)}var jR={storage:"EXPERIMENTAL_STORAGE",cloud:"EXPERIMENTAL_CLOUD"},ty=["storage","cloud"],gu=Object.fromEntries(ty.map(t=>[t,LR(t)]));function LR(t){let e=typeof process<"u"&&process.env||void 0;return e?e.NODE_ENV==="test"?true:e[jR[t]]==="1":false}function ar(t){return gu[t]}function FR(t,e){gu[t]=e;}function ny(){return ty.filter(t=>gu[t])}function UR(){let t=ny();if(t.length===0)return null;let e=t.includes("storage")?" Cloud sync (lite cloud deploy) is disabled.":"";return `EXPERIMENTAL FEATURES ENABLED: ${t.join(", ")} - not supported, do not use in production.${e}`}var hu=false;function ry(t=e=>console.warn(e)){if(hu)return;if(typeof process<"u"&&process.env?.NODE_ENV==="test"){hu=true;return}let e=UR();e&&t(e),hu=true;}var MR=["/rest/v1","/auth/v1","/storage/v1"],BR=[/^\/auth\/v1\/(callback|authorize|verify)$/,/^\/auth\/v1\/oauth\//,/^\/auth\/v1\/sso\/saml\//,/^\/auth\/v1\/\.well-known\//,/^\/auth\/v1\/scim\/v2/],qR=/^\s*Mozilla\s*\/\s*5\s*\.\s*0/i;function HR(t){return MR.some(e=>t.startsWith(e))?!BR.some(e=>e.test(t)):false}function yu(){return {"Access-Control-Allow-Origin":"*"}}function WR(t){return t.startsWith("/storage/v1")}function sy(t){return ks(async(e,n)=>{if(e.req.method==="OPTIONS"||!HR(e.req.path))return n();let r=WR(e.req.path),s=e.req.header("Authorization")?.match(/^Bearer\s+(.+)$/)?.[1],i=e.req.header("apikey")??e.req.query("apikey");if(!i)return r?(s?.startsWith("sb_")&&e.set("ignoreAuthorization",true),n()):e.json({message:"No API key found in request",hint:"No `apikey` request header or url param was found."},401,{"sb-error-code":"UNAUTHORIZED_MISSING_API_KEY",...yu()});let o=await t(i,e);if(!o)return r?(s?.startsWith("sb_")&&e.set("ignoreAuthorization",true),n()):e.json({message:"Invalid API key",hint:"Double check your Supabase `apikey`"},401,{"sb-error-code":"UNAUTHORIZED_INVALID_API_KEY",...yu()});if(o.type==="secret"){let a=e.req.header("User-Agent");if(a&&qR.test(a))return e.json({message:"Forbidden use of secret API key in browser"},401,{"sb-error-code":"UNAUTHORIZED_INVALID_API_KEY_TYPE",...yu()})}return e.set("apiKeyType",o.type),s&&s!==i&&!s.startsWith("sb_")||(e.set("ignoreAuthorization",true),e.set("jwt",o.claims),typeof o.claims.sub=="string"&&e.set("userId",o.claims.sub)),n()})}function iy(t){let e=t.config.auth?.publishable_key,n=t.config.auth?.secret_key,r=typeof e=="string"&&e.length>0,s=typeof n=="string"&&n.length>0;return !r&&!s?null:async i=>r&&i===e?{type:"publishable",claims:{role:"anon"}}:s&&i===n?{type:"secret",claims:{role:"service_role"}}:null}function oy(t,e={}){let n=e.middlewares??[async(u,d)=>{await d();}],r=["GET","POST","PATCH","PUT","DELETE","OPTIONS","HEAD"],s=["authorization","apikey","content-type","cache-control","prefer","x-client-info","x-upsert","x-region","x-metadata","accept-profile","content-profile","range","range-unit","accept","x-supabase-api-version"],i=["Content-Range","Content-Location","Preference-Applied"],o=e.apiKeys===false?null:e.apiKeys?.resolver??iy(t),a=o?sy(o):async(u,d)=>{await d();},l=e.admin?Uf(a):a,c=Lf({origin:"*",allowMethods:r,allowHeaders:s,exposeHeaders:i,maxAge:86400}),f=async(u,d)=>{await d();let p=u.res.headers;p.has("Access-Control-Allow-Origin")||p.set("Access-Control-Allow-Origin","*"),p.set("Access-Control-Expose-Headers",i.join(", ")),u.req.method==="OPTIONS"&&(p.set("Access-Control-Allow-Methods",r.join(", ")),p.set("Access-Control-Allow-Headers",u.req.header("Access-Control-Request-Headers")??s.join(", ")),p.set("Access-Control-Max-Age","86400"));};return new _e().use("/storage/v1/*",c).use("/rest/v1/*",f).use(async(u,d)=>{u.set("app",t),t.config.auth?.enabled&&u.set("authService",cg(t)),t.config.storage?.enabled&&t._storageAdapter&&ar("storage")&&u.set("storageService",pg(t)),await d();}).use(...n).use(l).use(Bc()).route("/auth/v1",Hc).route("/rest/v1",Wm({forceRollback:e.forceRollback})).use("/storage/v1/*",async(u,d)=>{if(!ar("storage"))return u.notFound();await d();}).route("/storage/v1",Gc).route("/_system",Hf).use(async(u,d)=>{if(!e.disableStudio&&t.config.studio?.enabled)return mu.fetch(u.req.raw);if(!e.disableFallback)return u.notFound();await d();})}var KR=t=>{let e=t.toJSON();return yt.fromSchema(e)},bu=class extends Error{constructor(n,r,s=[]){super(`Invalid schema given for ${JSON.stringify(r,null,2)}
193
+ `;function Oo(t=true){return t?Qr(Yc):Yc}var Po=class{driver=null;requiresBuffer=false;async transform(e,n){return {body:e,contentType:"application/octet-stream",contentLength:e.byteLength}}};function yg(t){if(!t._storageAdapter)throw Z.storageNotConfigured();let e=t.connection.dialect,n=new Os(t.connection.kysely,e),r=t.config.auth?.jwt_secret??"",s=t._transformationAdapter??new Po;return new Ps(n,t._storageAdapter,{jwtSecret:r,fileSizeLimit:t.config.storage?.file_size_limit?sR(t.config.storage.file_size_limit):void 0,buckets:t.config.storage?.buckets},{autoCreateBuckets:true},s)}function sR(t){let e=t.match(/^(\d+(?:\.\d+)?)\s*(B|KB|KiB|MB|MiB|GB|GiB)$/i);if(!e)return 0;let n=Number.parseFloat(e[1]),r=e[2].toUpperCase();return Math.floor(n*({B:1,KB:1e3,KIB:1024,MB:1e6,MIB:1048576,GB:1e9,GIB:1073741824}[r]??1))}var Ke=Symbol("RENDERER"),Jt=Symbol("ERROR_HANDLER"),ee=Symbol("STASH"),$o=Symbol("INTERNAL"),Zc=Symbol("MEMO"),er=Symbol("PERMALINK");var eu=t=>(t[$o]=true,t);var tu=t=>({value:e,children:n})=>{if(!n)return;let r={children:[{tag:eu(()=>{t.push(e);}),props:{}}]};Array.isArray(n)?r.children.push(...n.flat()):r.children.push(n),r.children.push({tag:eu(()=>{t.pop();}),props:{}});let s={tag:"",props:r,type:""};return s[Jt]=i=>{throw t.pop(),i},s},Io=t=>{let e=[t],n=tu(e);return n.values=e,n.Provider=n,Tt.push(n),n};var Tt=[],$s=t=>{let e=[t],n=(r=>{e.push(r.value);let s;try{s=r.children?(Array.isArray(r.children)?new nu("",{},r.children):r.children).toString():"";}catch(i){throw e.pop(),i}return s instanceof Promise?s.finally(()=>e.pop()).then(i=>Y(i,i.callbacks)):(e.pop(),Y(s))});return n.values=e,n.Provider=n,n[Ke]=tu(e),Tt.push(n),n},Re=t=>t.values.at(-1);var tr={title:[],script:["src"],style:["data-href"],link:["href"],meta:["name","httpEquiv","charset","itemProp"]},Is={},nr="data-precedence";var js={};Zs(js,{button:()=>dR,form:()=>uR,input:()=>fR,link:()=>lR,meta:()=>cR,script:()=>oR,style:()=>aR,title:()=>iR});var wn=t=>Array.isArray(t)?t:[t];var bg=new WeakMap,wg=(t,e,n,r)=>({buffer:s,context:i})=>{if(!s)return;let o=bg.get(i)||{};bg.set(i,o);let a=o[t]||=[],l=false,c=tr[t];if(c.length>0){e:for(let[,f]of a)for(let u of c)if((f?.[u]??null)===n?.[u]){l=true;break e}}if(l?s[0]=s[0].replaceAll(e,""):c.length>0?a.push([e,n,r]):a.unshift([e,n,r]),s[0].indexOf("</head>")!==-1){let f;if(r===void 0)f=a.map(([u])=>u);else {let u=[];f=a.map(([d,,p])=>{let g=u.indexOf(p);return g===-1&&(u.push(p),g=u.length-1),[d,g]}).sort((d,p)=>d[1]-p[1]).map(([d])=>d);}f.forEach(u=>{s[0]=s[0].replaceAll(u,"");}),s[0]=s[0].replace(/(?=<\/head>)/,f.join(""));}},Ns=(t,e,n)=>Y(new Ue(t,n,wn(e??[])).toString()),Ds=(t,e,n,r)=>{if("itemProp"in n)return Ns(t,e,n);let{precedence:s,blocking:i,...o}=n;s=r?s??"":void 0,r&&(o[nr]=s);let a=new Ue(t,o,wn(e||[])).toString();return a instanceof Promise?a.then(l=>Y(a,[...l.callbacks||[],wg(t,l,o,s)])):Y(a,[wg(t,a,o,s)])},iR=({children:t,...e})=>{let n=No();if(n){let r=Re(n);if(r==="svg"||r==="head")return new Ue("title",e,wn(t??[]))}return Ds("title",t,e,false)},oR=({children:t,...e})=>{let n=No();return ["src","async"].some(r=>!e[r])||n&&Re(n)==="head"?Ns("script",t,e):Ds("script",t,e,false)},aR=({children:t,...e})=>["href","precedence"].every(n=>n in e)?(e["data-href"]=e.href,delete e.href,Ds("style",t,e,true)):Ns("style",t,e),lR=({children:t,...e})=>["onLoad","onError"].some(n=>n in e)||e.rel==="stylesheet"&&(!("precedence"in e)||"disabled"in e)?Ns("link",t,e):Ds("link",t,e,"precedence"in e),cR=({children:t,...e})=>{let n=No();return n&&Re(n)==="head"?Ns("meta",t,e):Ds("meta",t,e,false)},Sg=(t,{children:e,...n})=>new Ue(t,n,wn(e??[])),uR=t=>(typeof t.action=="function"&&(t.action=er in t.action?t.action[er]:void 0),Sg("form",t)),_g=(t,e)=>(typeof e.formAction=="function"&&(e.formAction=er in e.formAction?e.formAction[er]:void 0),Sg(t,e)),fR=t=>_g("input",t),dR=t=>_g("button",t);var pR=new Map([["className","class"],["htmlFor","for"],["crossOrigin","crossorigin"],["httpEquiv","http-equiv"],["itemProp","itemprop"],["fetchPriority","fetchpriority"],["noModule","nomodule"],["formAction","formaction"]]),rr=t=>pR.get(t)||t,Ls=(t,e)=>{for(let[n,r]of Object.entries(t)){let s=n[0]==="-"||!/[A-Z]/.test(n)?n:n.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);e(s,r==null?null:typeof r=="number"?s.match(/^(?:a|border-im|column(?:-c|s)|flex(?:$|-[^b])|grid-(?:ar|[^a])|font-w|li|or|sca|st|ta|wido|z)|ty$/)?`${r}`:`${r}px`:r);}};var Fs=void 0,No=()=>Fs,mR=t=>/[A-Z]/.test(t)&&t.match(/^(?:al|basel|clip(?:Path|Rule)$|co|do|fill|fl|fo|gl|let|lig|i|marker[EMS]|o|pai|pointe|sh|st[or]|text[^L]|tr|u|ve|w)/)?t.replace(/([A-Z])/g,"-$1").toLowerCase():t,hR=["area","base","br","col","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"],gR=["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","download","formnovalidate","hidden","inert","ismap","itemscope","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"],su=(t,e)=>{for(let n=0,r=t.length;n<r;n++){let s=t[n];if(typeof s=="string")bt(s,e);else {if(typeof s=="boolean"||s===null||s===void 0)continue;s instanceof Ue?s.toStringToBuffer(e):typeof s=="number"||s.isEscaped?e[0]+=s:s instanceof Promise?e.unshift("",s):su(s,e);}}},Ue=class{tag;props;key;children;isEscaped=true;localContexts;constructor(t,e,n){this.tag=t,this.props=e,this.children=n;}get type(){return this.tag}get ref(){return this.props.ref||null}toString(){let t=[""];this.localContexts?.forEach(([e,n])=>{e.values.push(n);});try{this.toStringToBuffer(t);}finally{this.localContexts?.forEach(([e])=>{e.values.pop();});}return t.length===1?"callbacks"in t?Ra(Y(t[0],t.callbacks)).toString():t[0]:_i(t,t.callbacks)}toStringToBuffer(t){let e=this.tag,n=this.props,{children:r}=this;t[0]+=`<${e}`;let s=Fs&&Re(Fs)==="svg"?i=>mR(rr(i)):i=>rr(i);for(let[i,o]of Object.entries(n))if(i=s(i),i!=="children"){if(i==="style"&&typeof o=="object"){let a="";Ls(o,(l,c)=>{c!=null&&(a+=`${a?";":""}${l}:${c}`);}),t[0]+=' style="',bt(a,t),t[0]+='"';}else if(typeof o=="string")t[0]+=` ${i}="`,bt(o,t),t[0]+='"';else if(o!=null)if(typeof o=="number"||o.isEscaped)t[0]+=` ${i}="${o}"`;else if(typeof o=="boolean"&&gR.includes(i))o&&(t[0]+=` ${i}=""`);else if(i==="dangerouslySetInnerHTML"){if(r.length>0)throw new Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");r=[Y(o.__html)];}else if(o instanceof Promise)t[0]+=` ${i}="`,t.unshift('"',o);else if(typeof o=="function"){if(!i.startsWith("on")&&i!=="ref")throw new Error(`Invalid prop '${i}' of type 'function' supplied to '${e}'.`)}else t[0]+=` ${i}="`,bt(o.toString(),t),t[0]+='"';}if(hR.includes(e)&&r.length===0){t[0]+="/>";return}t[0]+=">",su(r,t),t[0]+=`</${e}>`;}},ru=class extends Ue{toStringToBuffer(t){let{children:e}=this,n={...this.props};e.length&&(n.children=e.length===1?e[0]:e);let r=this.tag.call(null,n);if(!(typeof r=="boolean"||r==null))if(r instanceof Promise)if(Tt.length===0)t.unshift("",r);else {let s=Tt.map(i=>[i,i.values.at(-1)]);t.unshift("",r.then(i=>(i instanceof Ue&&(i.localContexts=s),i)));}else r instanceof Ue?r.toStringToBuffer(t):typeof r=="number"||r.isEscaped?(t[0]+=r,r.callbacks&&(t.callbacks||=[],t.callbacks.push(...r.callbacks))):bt(r,t);}},nu=class extends Ue{toStringToBuffer(t){su(this.children,t);}},Eg=false,Us=(t,e,n)=>{if(!Eg){for(let r in Is)js[r][Ke]=Is[r];Eg=true;}return typeof t=="function"?new ru(t,e,n):js[t]?new ru(js[t],e,n):t==="svg"||t==="head"?(Fs||=$s(""),new Ue(t,e,[new ru(Fs,{value:t},n)])):new Ue(t,e,n)};var dt=({children:t})=>new nu("",{children:t},Array.isArray(t)?t:t?[t]:[]);var Fo={};Zs(Fo,{button:()=>Vg,clearCache:()=>vR,composeRef:()=>Lo,form:()=>Jg,input:()=>zg,link:()=>Hg,meta:()=>Wg,script:()=>Bg,style:()=>qg,title:()=>Mg});var Bs="_hp",yR={Change:"Input",DoubleClick:"DblClick"},bR={svg:"2000/svg",math:"1998/Math/MathML"},pt=[],au=new WeakMap,sr=void 0,Ag=()=>sr,Rt=t=>"t"in t,ou={onClick:["click",false]},xg=t=>{if(!t.startsWith("on"))return;if(ou[t])return ou[t];let e=t.match(/^on([A-Z][a-zA-Z]+?(?:PointerCapture)?)(Capture)?$/);if(e){let[,n,r]=e;return ou[t]=[(yR[n]||n).toLowerCase(),!!r]}},Tg=(t,e)=>sr&&t instanceof SVGElement&&/[A-Z]/.test(e)&&(e in t.style||e.match(/^(?:o|pai|str|u|ve)/))?e.replace(/([A-Z])/g,"-$1").toLowerCase():e,wR=(t,e,n)=>{e||={};for(let r in e){let s=e[r];if(r!=="children"&&(!n||n[r]!==s)){r=rr(r);let i=xg(r);if(i){if(n?.[r]!==s&&(n&&t.removeEventListener(i[0],n[r],i[1]),s!=null)){if(typeof s!="function")throw new Error(`Event handler for "${r}" is not a function`);t.addEventListener(i[0],s,i[1]);}}else if(r==="dangerouslySetInnerHTML"&&s)t.innerHTML=s.__html;else if(r==="ref"){let o;typeof s=="function"?o=s(t)||(()=>s(null)):s&&"current"in s&&(s.current=t,o=()=>s.current=null),au.set(t,o);}else if(r==="style"){let o=t.style;typeof s=="string"?o.cssText=s:(o.cssText="",s!=null&&Ls(s,o.setProperty.bind(o)));}else {if(r==="value"){let a=t.nodeName;if(a==="INPUT"||a==="TEXTAREA"||a==="SELECT"){if(t.value=s==null||s===false?null:s,a==="TEXTAREA"){t.textContent=s;continue}else if(a==="SELECT"){t.selectedIndex===-1&&(t.selectedIndex=0);continue}}}else (r==="checked"&&t.nodeName==="INPUT"||r==="selected"&&t.nodeName==="OPTION")&&(t[r]=s);let o=Tg(t,r);s==null||s===false?t.removeAttribute(o):s===true?t.setAttribute(o,""):typeof s=="string"||typeof s=="number"?t.setAttribute(o,s):t.setAttribute(o,s.toString());}}}if(n)for(let r in n){let s=n[r];if(r!=="children"&&!(r in e)){r=rr(r);let i=xg(r);i?t.removeEventListener(i[0],s,i[1]):r==="ref"?au.get(t)?.():t.removeAttribute(Tg(t,r));}}},SR=(t,e)=>{e[ee][0]=0,pt.push([t,e]);let n=e.tag[Ke]||e.tag,r=n.defaultProps?{...n.defaultProps,...e.props}:e.props;try{return [n.call(null,r)]}finally{pt.pop();}},Og=(t,e,n,r,s)=>{t.vR?.length&&(r.push(...t.vR),delete t.vR),typeof t.tag=="function"&&t[ee][1][cu]?.forEach(i=>s.push(i)),t.vC.forEach(i=>{if(Rt(i))n.push(i);else if(typeof i.tag=="function"||i.tag===""){i.c=e;let o=n.length;if(Og(i,e,n,r,s),i.s){for(let a=o;a<n.length;a++)n[a].s=true;i.s=false;}}else n.push(i),i.vR?.length&&(r.push(...i.vR),delete i.vR);});},_R=t=>{for(;t&&(t.tag===Bs||!t.e);)t=t.tag===Bs||!t.vC?.[0]?t.nN:t.vC[0];return t?.e},Pg=t=>{Rt(t)||(t[ee]?.[1][cu]?.forEach(e=>e[2]?.()),au.get(t.e)?.(),t.p===2&&t.vC?.forEach(e=>e.p=2),t.vC?.forEach(Pg)),t.p||(t.e?.remove(),delete t.e),typeof t.tag=="function"&&(Ms.delete(t),Do.delete(t),delete t[ee][3],t.a=true);},$g=(t,e,n)=>{t.c=e,Ig(t,e,n);},Rg=(t,e)=>{if(e){for(let n=0,r=t.length;n<r;n++)if(t[n]===e)return n}},Cg=Symbol(),Ig=(t,e,n)=>{let r=[],s=[],i=[];Og(t,e,r,s,i),s.forEach(Pg);let o=n?void 0:e.childNodes,a,l=null;if(n)a=-1;else if(!o.length)a=0;else {let c=Rg(o,_R(t.nN));c!==void 0?(l=o[c],a=c):a=Rg(o,r.find(f=>f.tag!==Bs&&f.e)?.e)??-1,a===-1&&(n=true);}for(let c=0,f=r.length;c<f;c++,a++){let u=r[c],d;if(u.s&&u.e)d=u.e,u.s=false;else {let p=n||!u.e;Rt(u)?(u.e&&u.d&&(u.e.textContent=u.t),u.d=false,d=u.e||=document.createTextNode(u.t)):(d=u.e||=u.n?document.createElementNS(u.n,u.tag):document.createElement(u.tag),wR(d,u.props,u.pP),Ig(u,d,p));}u.tag===Bs?a--:n?d.parentNode||e.appendChild(d):o[a]!==d&&o[a-1]!==d&&(o[a+1]===d?e.appendChild(o[a]):e.insertBefore(d,l||o[a]||null));}if(t.pP&&(t.pP=void 0),i.length){let c=[],f=[];i.forEach(([,u,,d,p])=>{u&&c.push(u),d&&f.push(d),p?.();}),c.forEach(u=>u()),f.length&&requestAnimationFrame(()=>{f.forEach(u=>u());});}},ER=(t,e)=>!!(t&&t.length===e.length&&t.every((n,r)=>n[1]===e[r][1])),Do=new WeakMap,lu=(t,e,n)=>{let r=!n&&e.pC;n&&(e.pC||=e.vC);let s;try{n||=typeof e.tag=="function"?SR(t,e):wn(e.props.children),n[0]?.tag===""&&n[0][Jt]&&(s=n[0][Jt],t[5].push([t,s,e]));let i=r?[...e.pC]:e.vC?[...e.vC]:void 0,o=[],a;for(let l=0;l<n.length;l++){if(Array.isArray(n[l])){n.splice(l,1,...n[l].flat(1/0)),l--;continue}let c=xR(n[l]);if(c){typeof c.tag=="function"&&!c.tag[$o]&&(Tt.length>0&&(c[ee][2]=Tt.map(u=>[u,u.values.at(-1)])),t[5]?.length&&(c[ee][3]=t[5].at(-1)));let f;if(i&&i.length){let u=i.findIndex(Rt(c)?d=>Rt(d):c.key!==void 0?d=>d.key===c.key&&d.tag===c.tag:d=>d.tag===c.tag);u!==-1&&(f=i[u],i.splice(u,1));}if(f)if(Rt(c))f.t!==c.t&&(f.t=c.t,f.d=!0),c=f;else {let u=f.pP=f.props;if(f.props=c.props,f.f||=c.f||e.f,typeof c.tag=="function"){let d=f[ee][2];f[ee][2]=c[ee][2]||[],f[ee][3]=c[ee][3],!f.f&&((f.o||f)===c.o||f.tag[Zc]?.(u,f.props))&&ER(d,f[ee][2])&&(f.s=!0);}c=f;}else if(!Rt(c)&&sr){let u=Re(sr);u&&(c.n=u);}if(!Rt(c)&&!c.s&&(lu(t,c),delete c.f),o.push(c),a&&!a.s&&!c.s)for(let u=a;u&&!Rt(u);u=u.vC?.at(-1))u.nN=c;a=c;}}e.vR=r?[...e.vC,...i||[]]:i||[],e.vC=o,r&&delete e.pC;}catch(i){if(e.f=true,i===Cg){if(s)return;throw i}let[o,a,l]=e[ee]?.[3]||[];if(a){let c=()=>qs([0,false,t[2]],l),f=Do.get(l)||[];f.push(c),Do.set(l,f);let u=a(i,()=>{let d=Do.get(l);if(d){let p=d.indexOf(c);if(p!==-1)return d.splice(p,1),c()}});if(u){if(t[0]===1)t[1]=true;else if(lu(t,l,[u]),(a.length===1||t!==o)&&l.c){$g(l,l.c,false);return}throw Cg}}throw i}finally{s&&t[5].pop();}},xR=t=>{if(!(t==null||typeof t=="boolean")){if(typeof t=="string"||typeof t=="number")return {t:t.toString(),d:true};if("vR"in t&&(t={tag:t.tag,props:t.props,key:t.key,f:t.f,type:t.tag,ref:t.props.ref,o:t.o||t}),typeof t.tag=="function")t[ee]=[0,[]];else {let e=bR[t.tag];e&&(sr||=Io(""),t.props.children=[{tag:sr,props:{value:t.n=`http://www.w3.org/${e}`,children:t.props.children}}]);}return t}};var kg=(t,e)=>{e[ee][2]?.forEach(([n,r])=>{n.values.push(r);});try{lu(t,e,void 0);}catch{return}if(e.a){delete e.a;return}e[ee][2]?.forEach(([n])=>{n.values.pop();}),(t[0]!==1||!t[1])&&$g(e,e.c,false);},Ms=new WeakMap,vg=[],qs=async(t,e)=>{t[5]||=[];let n=Ms.get(e);n&&n[0](void 0);let r,s=new Promise(i=>r=i);if(Ms.set(e,[r,()=>{t[2]?t[2](t,e,i=>{kg(i,e);}).then(()=>r(e)):(kg(t,e),r(e));}]),vg.length)vg.at(-1).add(e);else {await Promise.resolve();let i=Ms.get(e);i&&(Ms.delete(e),i[1]());}return s};var Ng=(t,e,n)=>({tag:Bs,props:{children:t},key:n,e,p:1});var TR=0,cu=1,RR=2,CR=3;var uu=new WeakMap,jg=(t,e)=>!t||!e||t.length!==e.length||e.some((n,r)=>n!==t[r]);var kR=void 0;var Dg=[];var jo=t=>{let e=()=>typeof t=="function"?t():t,n=pt.at(-1);if(!n)return [e(),()=>{}];let[,r]=n,s=r[ee][1][TR]||=[],i=r[ee][0]++;return s[i]||=[e(),o=>{let a=kR,l=s[i];if(typeof o=="function"&&(o=o(l[0])),!Object.is(o,l[0]))if(l[0]=o,Dg.length){let[c,f]=Dg.at(-1);Promise.all([c===3?r:qs([c,false,a],r),f]).then(([u])=>{if(!u||!(c===2||c===3))return;let d=u.vC;requestAnimationFrame(()=>{setTimeout(()=>{d===u.vC&&qs([c===3?1:0,false,a],u);});});});}else qs([0,false,a],r);}]};var ir=(t,e)=>{let n=pt.at(-1);if(!n)return t;let[,r]=n,s=r[ee][1][RR]||=[],i=r[ee][0]++,o=s[i];return jg(o?.[1],e)?s[i]=[t,e]:t=s[i][0],t};var fu=t=>{let e=uu.get(t);if(e){if(e.length===2)throw e[1];return e[0]}throw t.then(n=>uu.set(t,[n]),n=>uu.set(t,[void 0,n])),t},du=(t,e)=>{let n=pt.at(-1);if(!n)return t();let[,r]=n,s=r[ee][1][CR]||=[],i=r[ee][0]++,o=s[i];return jg(o?.[1],e)&&(s[i]=[t(),e]),s[i][0]};var Fg=Io({pending:false,data:null,method:null,action:null}),Lg=new Set,Ug=t=>{Lg.add(t),t.finally(()=>Lg.delete(t));};var vR=()=>{pu=Object.create(null),mu=Object.create(null);},Lo=(t,e)=>du(()=>n=>{let r;t&&(typeof t=="function"?r=t(n)||(()=>{t(null);}):t&&"current"in t&&(t.current=n,r=()=>{t.current=null;}));let s=e(n);return ()=>{s?.(),r?.();}},[t]),pu=Object.create(null),mu=Object.create(null),Hs=(t,e,n,r,s)=>{if(e?.itemProp)return {tag:t,props:e,type:t,ref:e.ref};let i=document.head,{onLoad:o,onError:a,precedence:l,blocking:c,...f}=e,u=null,d=false,p=tr[t],g;if(p.length>0){let w=i.querySelectorAll(t);e:for(let S of w)for(let b of tr[t])if(S.getAttribute(b)===e[b]){u=S;break e}if(!u){let S=p.reduce((b,_)=>e[_]===void 0?b:`${b}-${_}-${e[_]}`,t);d=!mu[S],u=mu[S]||=(()=>{let b=document.createElement(t);for(let _ of p)e[_]!==void 0&&b.setAttribute(_,e[_]),e.rel&&b.setAttribute("rel",e.rel);return b})();}}else g=i.querySelectorAll(t);l=r?l??"":void 0,r&&(f[nr]=l);let m=ir(w=>{if(p.length>0){let S=false;for(let b of i.querySelectorAll(t)){if(S&&b.getAttribute(nr)!==l){i.insertBefore(w,b);return}b.getAttribute(nr)===l&&(S=true);}i.appendChild(w);}else if(g){let S=false;for(let b of g)if(b===w){S=true;break}S||i.insertBefore(w,i.contains(g[0])?g[0]:i.querySelector(t)),g=void 0;}},[l]),h=Lo(e.ref,w=>{let S=p[0];if(n===2&&(w.innerHTML=""),(d||g)&&m(w),!a&&!o)return;let b=pu[w.getAttribute(S)]||=new Promise((_,E)=>{w.addEventListener("load",_),w.addEventListener("error",E);});o&&(b=b.then(o)),a&&(b=b.catch(a)),b.catch(()=>{});});if(s&&c==="render"){let w=tr[t][0];if(e[w]){let S=e[w],b=pu[S]||=new Promise((_,E)=>{m(u),u.addEventListener("load",_),u.addEventListener("error",E);});fu(b);}}let y={tag:t,type:t,props:{...f,ref:h},ref:h};return y.p=n,u&&(y.e=u),Ng(y,i)},Mg=t=>{let e=Ag();return (e&&Re(e))?.endsWith("svg")?{tag:"title",props:t,type:"title",ref:t.ref}:Hs("title",t,void 0,false,false)},Bg=t=>!t||["src","async"].some(e=>!t[e])?{tag:"script",props:t,type:"script",ref:t.ref}:Hs("script",t,1,false,true),qg=t=>!t||!["href","precedence"].every(e=>e in t)?{tag:"style",props:t,type:"style",ref:t.ref}:(t["data-href"]=t.href,delete t.href,Hs("style",t,2,true,true)),Hg=t=>!t||["onLoad","onError"].some(e=>e in t)||t.rel==="stylesheet"&&(!("precedence"in t)||"disabled"in t)?{tag:"link",props:t,type:"link",ref:t.ref}:Hs("link",t,1,"precedence"in t,true),Wg=t=>Hs("meta",t,void 0,false,false),Kg=Symbol(),Jg=t=>{let{action:e,...n}=t;typeof e!="function"&&(n.action=e);let[r,s]=jo([null,false]),i=ir(async c=>{let f=c.isTrusted?e:c.detail[Kg];if(typeof f!="function")return;c.preventDefault();let u=new FormData(c.target);s([u,true]);let d=f(u);d instanceof Promise&&(Ug(d),await d),s([null,true]);},[]),o=Lo(t.ref,c=>(c.addEventListener("submit",i),()=>{c.removeEventListener("submit",i);})),[a,l]=r;return r[1]=false,{tag:Fg,props:{value:{pending:a!==null,data:a,method:a?"post":null,action:a?e:null},children:{tag:"form",props:{...n,ref:o},type:"form",ref:o}},f:l}},Gg=(t,{formAction:e,...n})=>{if(typeof e=="function"){let r=ir(s=>{s.preventDefault(),s.currentTarget.form.dispatchEvent(new CustomEvent("submit",{detail:{[Kg]:e}}));},[]);n.ref=Lo(n.ref,s=>(s.addEventListener("click",r),()=>{s.removeEventListener("click",r);}));}return {tag:t,props:n,type:t,ref:n.ref}},zg=t=>Gg("input",t),Vg=t=>Gg("button",t);Object.assign(Is,{title:Mg,script:Bg,style:qg,link:Hg,meta:Wg,form:Jg,input:zg,button:Vg});$s(null);new TextEncoder;var Sn=":-hono-global",$R=new RegExp(`^${Sn}{(.*)}$`),Bo="hono-css",Ct=Symbol(),ge=Symbol(),De=Symbol(),mt=Symbol(),qo=Symbol(),ey=Symbol();var ty=t=>{let e=0,n=11;for(;e<t.length;)n=101*n+t.charCodeAt(e++)>>>0;return "css-"+n},IR=['"(?:(?:\\\\[\\s\\S]|[^"\\\\])*)"',"'(?:(?:\\\\[\\s\\S]|[^'\\\\])*)'"].join("|"),NR=new RegExp(["("+IR+")","(?:"+["^\\s+","\\/\\*.*?\\*\\/\\s*","\\/\\/.*\\n\\s*","\\s+$"].join("|")+")","\\s*;\\s*(}|$)\\s*","\\s*([{};:,])\\s*","(\\s)\\s+"].join("|"),"g"),DR=t=>t.replace(NR,(e,n,r,s,i)=>n||r||s||i||""),ny=(t,e)=>{let n=[],r=[],s=t[0].match(/^\s*\/\*(.*?)\*\//)?.[1]||"",i="";for(let o=0,a=t.length;o<a;o++){i+=t[o];let l=e[o];if(!(typeof l=="boolean"||l===null||l===void 0)){Array.isArray(l)||(l=[l]);for(let c=0,f=l.length;c<f;c++){let u=l[c];if(!(typeof u=="boolean"||u===null||u===void 0))if(typeof u=="string")/([\\"'\/])/.test(u)?i+=u.replace(/([\\"']|(?<=<)\/)/g,"\\$1"):i+=u;else if(typeof u=="number")i+=u;else if(u[ey])i+=u[ey];else if(u[ge].startsWith("@keyframes "))n.push(u),i+=` ${u[ge].substring(11)} `;else {if(t[o+1]?.match(/^\s*{/))n.push(u),u=`.${u[ge]}`;else {n.push(...u[mt]),r.push(...u[qo]),u=u[De];let d=u.length;if(d>0){let p=u[d-1];p!==";"&&p!=="}"&&(u+=";");}}i+=`${u||""}`;}}}}return [s,DR(i),n,r]},or=(t,e)=>{let[n,r,s,i]=ny(t,e),o=$R.exec(r);o&&(r=o[1]);let a=(o?Sn:"")+ty(n+r),l=(o?s.map(c=>c[ge]):[a,...i]).join(" ");return {[Ct]:a,[ge]:l,[De]:r,[mt]:s,[qo]:i}},Ho=t=>{for(let e=0,n=t.length;e<n;e++){let r=t[e];typeof r=="string"&&(t[e]={[Ct]:"",[ge]:"",[De]:"",[mt]:[],[qo]:[r]});}return t},Wo=(t,...e)=>{let[n,r]=ny(t,e);return {[Ct]:"",[ge]:`@keyframes ${ty(n+r)}`,[De]:r,[mt]:[],[qo]:[]}},jR=0,Ko=((t,e)=>{t||(t=[`/* h-v-t ${jR++} */`]);let n=Array.isArray(t)?or(t,e):t,r=n[ge],s=or(["view-transition-name:",""],[r]);return n[ge]=Sn+n[ge],n[De]=n[De].replace(/(?<=::view-transition(?:[a-z-]*)\()(?=\))/g,r),s[ge]=s[Ct]=r,s[mt]=[...n[mt],n],s});var FR=t=>{let e=[],n=0,r=0;for(let s=0,i=t.length;s<i;s++){let o=t[s];if(o==="'"||o==='"'){let a=o;for(s++;s<i;s++){if(t[s]==="\\"){s++;continue}if(t[s]===a)break}continue}if(o==="{"){r++;continue}if(o==="}"){r--,r===0&&(e.push(t.slice(n,s+1)),n=s+1);continue}}return e},yu=({id:t})=>{let e,n=()=>(e||(e=document.querySelector(`style#${t}`)?.sheet,e&&(e.addedStyles=new Set)),e?[e,e.addedStyles]:[]),r=(o,a)=>{let[l,c]=n();if(!l||!c){Promise.resolve().then(()=>{if(!n()[0])throw new Error("style sheet not found");r(o,a);});return}c.has(o)||(c.add(o),(o.startsWith(Sn)?FR(a):[`${o[0]==="@"?"":"."}${o}{${a}}`]).forEach(f=>{l.insertRule(f,l.cssRules.length);}));};return [{toString(){let o=this[Ct];return r(o,this[De]),this[mt].forEach(({[ge]:a,[De]:l})=>{r(a,l);}),this[ge]}},({children:o,nonce:a})=>({tag:"style",props:{id:t,nonce:a,children:o&&(Array.isArray(o)?o:[o]).map(l=>l[De])}})]};var MR=({id:t})=>{let[e,n]=yu({id:t}),r=new WeakMap,s=new WeakMap,i=new RegExp(`(<style id="${t}"(?: nonce="[^"]*")?>.*?)(</style>)`),o=d=>{let p=({buffer:y,context:w})=>{let[S,b]=r.get(w),_=Object.keys(S);if(!_.length)return;let E="";if(_.forEach(v=>{b[v]=true,E+=v.startsWith(Sn)?S[v]:`${v[0]==="@"?"":"."}${v}{${S[v]}}`;}),r.set(w,[{},b]),y&&i.test(y[0])){y[0]=y[0].replace(i,(v,P,C)=>`${P}${E}${C}`);return}let x=s.get(w),O=`<script${x?` nonce="${x}"`:""}>document.querySelector('#${t}').textContent+=${JSON.stringify(E)}</script>`;if(y){y[0]=`${O}${y[0]}`;return}return Promise.resolve(O)},g=({context:y})=>{r.has(y)||r.set(y,[{},{}]);let[w,S]=r.get(y),b=true;if(S[d[Ct]]||(b=false,w[d[Ct]]=d[De]),d[mt].forEach(({[ge]:_,[De]:E})=>{S[_]||(b=false,w[_]=E);}),!b)return Promise.resolve(Y("",[p]))},m=new String(d[ge]);Object.assign(m,d),m.isEscaped=true,m.callbacks=[g];let h=Promise.resolve(m);return Object.assign(h,d),h.toString=e.toString,h},a=(d,...p)=>o(or(d,p)),l=(...d)=>(d=Ho(d),a(Array(d.length).fill(""),...d)),c=Wo,f=((d,...p)=>o(Ko(d,p))),u=({children:d,nonce:p}={})=>Y(`<style id="${t}"${p?` nonce="${p}"`:""}>${d?d[De]:""}</style>`,[({context:g})=>{s.set(g,p);}]);return u[Ke]=n,{css:a,cx:l,keyframes:c,viewTransition:f,Style:u}},Ks=MR({id:Bo}),ry=Ks.Style;function ye(t,e,n){let r;if(!e||!("children"in e))r=Us(t,e,[]);else {let s=e.children;r=Array.isArray(s)?Us(t,e,s):Us(t,e,[s]);}return r.key=n,r}var bu=new _e().get("/*",async t=>{let e={js:"main.js",css:["styles.css"]},n="/static/",r=await Promise.resolve().then(()=>da(sy())).then(s=>s.default);try{let s=Object.values(r).find(i=>i.isEntry);if(!s)throw new Error("No entry found in manifest");e.js=s?.file,e.css=s?.css??[];}catch(s){console.warn("Couldn't find assets in manifest",s);}return t.html(ye(dt,{children:ye("html",{lang:"en","data-theme":"dark",style:"color-scheme: dark",class:"dark",children:[ye("head",{children:[ye("meta",{charset:"UTF-8"}),ye("meta",{name:"viewport",content:"width=device-width, initial-scale=1, maximum-scale=1"}),ye("link",{rel:"icon",href:n+"favicon.ico",type:"image/x-icon"}),ye("title",{children:"Supalite"}),ye(dt,{children:[ye("script",{type:"module",src:n+e?.js}),e?.css.map((s,i)=>ye("link",{rel:"stylesheet",href:n+s},i))]}),ye(ry,{})]}),ye("body",{children:ye("div",{id:"root"})})]})}))});async function qR(t){return bu.fetch(t)}var HR={storage:"EXPERIMENTAL_STORAGE",cloud:"EXPERIMENTAL_CLOUD"},iy=["storage","cloud"],Su=Object.fromEntries(iy.map(t=>[t,WR(t)]));function WR(t){let e=typeof process<"u"&&process.env||void 0;return e?e.NODE_ENV==="test"?true:e[HR[t]]==="1":false}function ar(t){return Su[t]}function KR(t,e){Su[t]=e;}function oy(){return iy.filter(t=>Su[t])}function JR(){let t=oy();if(t.length===0)return null;let e=t.includes("storage")?" Cloud sync (lite cloud deploy) is disabled.":"";return `EXPERIMENTAL FEATURES ENABLED: ${t.join(", ")} - not supported, do not use in production.${e}`}var wu=false;function ay(t=e=>console.warn(e)){if(wu)return;if(typeof process<"u"&&process.env?.NODE_ENV==="test"){wu=true;return}let e=JR();e&&t(e),wu=true;}var GR=["/rest/v1","/auth/v1","/storage/v1"],zR=[/^\/auth\/v1\/(callback|authorize|verify)$/,/^\/auth\/v1\/oauth\//,/^\/auth\/v1\/sso\/saml\//,/^\/auth\/v1\/\.well-known\//,/^\/auth\/v1\/scim\/v2/],VR=/^\s*Mozilla\s*\/\s*5\s*\.\s*0/i;function QR(t){return GR.some(e=>t.startsWith(e))?!zR.some(e=>e.test(t)):false}function _u(){return {"Access-Control-Allow-Origin":"*"}}function XR(t){return t.startsWith("/storage/v1")}function ly(t){return ks(async(e,n)=>{if(e.req.method==="OPTIONS"||!QR(e.req.path))return n();let r=XR(e.req.path),s=e.req.header("Authorization")?.match(/^Bearer\s+(.+)$/)?.[1],i=e.req.header("apikey")??e.req.query("apikey");if(!i)return r?(s?.startsWith("sb_")&&e.set("ignoreAuthorization",true),n()):e.json({message:"No API key found in request",hint:"No `apikey` request header or url param was found."},401,{"sb-error-code":"UNAUTHORIZED_MISSING_API_KEY",..._u()});let o=await t(i,e);if(!o)return r?(s?.startsWith("sb_")&&e.set("ignoreAuthorization",true),n()):e.json({message:"Invalid API key",hint:"Double check your Supabase `apikey`"},401,{"sb-error-code":"UNAUTHORIZED_INVALID_API_KEY",..._u()});if(o.type==="secret"){let a=e.req.header("User-Agent");if(a&&VR.test(a))return e.json({message:"Forbidden use of secret API key in browser"},401,{"sb-error-code":"UNAUTHORIZED_INVALID_API_KEY_TYPE",..._u()})}return e.set("apiKeyType",o.type),s&&s!==i&&!s.startsWith("sb_")||(e.set("ignoreAuthorization",true),e.set("jwt",o.claims),typeof o.claims.sub=="string"&&e.set("userId",o.claims.sub)),n()})}function cy(t){let e=t.config.auth?.publishable_key,n=t.config.auth?.secret_key,r=typeof e=="string"&&e.length>0,s=typeof n=="string"&&n.length>0;return !r&&!s?null:async i=>r&&i===e?{type:"publishable",claims:{role:"anon"}}:s&&i===n?{type:"secret",claims:{role:"service_role"}}:null}function uy(t,e={}){let n=e.middlewares??[async(u,d)=>{await d();}],r=["GET","POST","PATCH","PUT","DELETE","OPTIONS","HEAD"],s=["authorization","apikey","content-type","cache-control","prefer","x-client-info","x-upsert","x-region","x-metadata","accept-profile","content-profile","range","range-unit","accept","x-supabase-api-version"],i=["Content-Range","Content-Location","Preference-Applied"],o=e.apiKeys===false?null:e.apiKeys?.resolver??cy(t),a=o?ly(o):async(u,d)=>{await d();},l=e.admin?Bf(a):a,c=Uf({origin:"*",allowMethods:r,allowHeaders:s,exposeHeaders:i,maxAge:86400}),f=async(u,d)=>{await d();let p=u.res.headers;p.has("Access-Control-Allow-Origin")||p.set("Access-Control-Allow-Origin","*"),p.set("Access-Control-Expose-Headers",i.join(", ")),u.req.method==="OPTIONS"&&(p.set("Access-Control-Allow-Methods",r.join(", ")),p.set("Access-Control-Allow-Headers",u.req.header("Access-Control-Request-Headers")??s.join(", ")),p.set("Access-Control-Max-Age","86400"));};return new _e().use("/storage/v1/*",c).use("/rest/v1/*",f).use(async(u,d)=>{u.set("app",t),t.config.auth?.enabled&&u.set("authService",fg(t)),t.config.storage?.enabled&&t._storageAdapter&&ar("storage")&&u.set("storageService",yg(t)),await d();}).use(...n).use(l).use(Wc()).route("/auth/v1",Jc).route("/rest/v1",Jm({forceRollback:e.forceRollback})).use("/storage/v1/*",async(u,d)=>{if(!ar("storage"))return u.notFound();await d();}).route("/storage/v1",Xc).route("/_system",Kf).use(async(u,d)=>{if(!e.disableStudio&&t.config.studio?.enabled)return bu.fetch(u.req.raw);if(!e.disableFallback)return u.notFound();await d();})}var YR=t=>{let e=t.toJSON();return yt.fromSchema(e)},Eu=class extends Error{constructor(n,r,s=[]){super(`Invalid schema given for ${JSON.stringify(r,null,2)}
194
194
 
195
195
  Error: ${JSON.stringify(s[0],null,2)}
196
196
 
197
- Schema: ${JSON.stringify(n.toJSON(),null,2)}`);this.schema=n;this.value=r;this.errors=s;}name="InvalidSchemaError";first(){return this.errors[0]}firstToString(){let n=this.first();return `${n.error} at ${n.instanceLocation}`}};function ly(t,e,n){let r=n?.clone?KR(t):t,s=n?.coerce!==false?r.coerce(e,{dropUnknown:n?.coerceDropUnknown??false}):e;n?.withDefaults!==false&&(s=r.template(s,{withOptional:true,withExtendedOptional:n?.withExtendedDefaults??false}));let i=t.validate(s,{shortCircuit:true,ignoreUnsupported:true});if(!i.valid)if(n?.onError)n.onError(i.errors);else throw new bu(r,e,i.errors);return s}Un();var wu=`-- supabase/auth core schema (Postgres)
197
+ Schema: ${JSON.stringify(n.toJSON(),null,2)}`);this.schema=n;this.value=r;this.errors=s;}name="InvalidSchemaError";first(){return this.errors[0]}firstToString(){let n=this.first();return `${n.error} at ${n.instanceLocation}`}};function dy(t,e,n){let r=n?.clone?YR(t):t,s=n?.coerce!==false?r.coerce(e,{dropUnknown:n?.coerceDropUnknown??false}):e;n?.withDefaults!==false&&(s=r.template(s,{withOptional:true,withExtendedOptional:n?.withExtendedDefaults??false}));let i=t.validate(s,{shortCircuit:true,ignoreUnsupported:true});if(!i.valid)if(n?.onError)n.onError(i.errors);else throw new Eu(r,e,i.errors);return s}Un();var xu=`-- supabase/auth core schema (Postgres)
198
198
  -- Scope: Core Authentication + User Management
199
199
  -- Source: GoTrue migrations + runtime analysis
200
200
 
@@ -402,7 +402,7 @@ CREATE TABLE IF NOT EXISTS auth.audit_log_entries (
402
402
  created_at timestamptz DEFAULT now(),
403
403
  ip_address varchar(64) DEFAULT ''
404
404
  );
405
- `;function Su(t=true){return t?Qr(wu):wu}function Je(t){return t.dialect==="postgres"?"pg":t.config?.ddlDialect==="sqlite"?"sqlite":"pg-flat"}function kt(t){return t==="sqlite"?{schema_migrations:"migrations",seed_files:"seed_files"}:t==="pg-flat"?{schema_migrations:'"supabase_migrations.schema_migrations"',seed_files:'"supabase_migrations.seed_files"'}:{schema_migrations:"supabase_migrations.schema_migrations",seed_files:"supabase_migrations.seed_files"}}function lr(t){return `'${t.replace(/'/g,"''")}'`}function GR(t){return `'${`{${t.map(r=>`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`).join(",")}}`.replace(/'/g,"''")}'`}function cy(t,e){return e==null?"NULL":t==="pg"?GR(e):lr(JSON.stringify(e))}function _u(t){return t==null?"NULL":lr(t)}function uy(t){if(t==null)return [];if(Array.isArray(t))return t;if(typeof t=="string"){let e=t.trim();if(e==="")return [];try{let n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return []}}return []}function fy(t){return {version:String(t.version),name:t.name??null,statements:uy(t.statements),rollback:uy(t.rollback),created_by:t.created_by??null,idempotency_key:t.idempotency_key??null}}var zR=[{name:"created_by",pgType:"text",sqliteType:"TEXT"},{name:"idempotency_key",pgType:"text",sqliteType:"TEXT"},{name:"rollback",pgType:"text[]",sqliteType:"TEXT"}];function dy(t){let{schema_migrations:e,seed_files:n}=kt(t);return t==="pg"?["CREATE SCHEMA IF NOT EXISTS supabase_migrations",`CREATE TABLE IF NOT EXISTS ${e} (
405
+ `;function Tu(t=true){return t?Qr(xu):xu}function Je(t){return t.dialect==="postgres"?"pg":t.config?.ddlDialect==="sqlite"?"sqlite":"pg-flat"}function kt(t){return t==="sqlite"?{schema_migrations:"migrations",seed_files:"seed_files"}:t==="pg-flat"?{schema_migrations:'"supabase_migrations.schema_migrations"',seed_files:'"supabase_migrations.seed_files"'}:{schema_migrations:"supabase_migrations.schema_migrations",seed_files:"supabase_migrations.seed_files"}}function lr(t){return `'${t.replace(/'/g,"''")}'`}function eC(t){return `'${`{${t.map(r=>`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`).join(",")}}`.replace(/'/g,"''")}'`}function py(t,e){return e==null?"NULL":t==="pg"?eC(e):lr(JSON.stringify(e))}function Ru(t){return t==null?"NULL":lr(t)}function my(t){if(t==null)return [];if(Array.isArray(t))return t;if(typeof t=="string"){let e=t.trim();if(e==="")return [];try{let n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return []}}return []}function hy(t){return {version:String(t.version),name:t.name??null,statements:my(t.statements),rollback:my(t.rollback),created_by:t.created_by??null,idempotency_key:t.idempotency_key??null}}var tC=[{name:"created_by",pgType:"text",sqliteType:"TEXT"},{name:"idempotency_key",pgType:"text",sqliteType:"TEXT"},{name:"rollback",pgType:"text[]",sqliteType:"TEXT"}];function gy(t){let{schema_migrations:e,seed_files:n}=kt(t);return t==="pg"?["CREATE SCHEMA IF NOT EXISTS supabase_migrations",`CREATE TABLE IF NOT EXISTS ${e} (
406
406
  version text NOT NULL PRIMARY KEY,
407
407
  statements text[],
408
408
  name text,
@@ -422,12 +422,12 @@ CREATE TABLE IF NOT EXISTS auth.audit_log_entries (
422
422
  )`,`CREATE TABLE IF NOT EXISTS ${n} (
423
423
  path TEXT NOT NULL PRIMARY KEY,
424
424
  hash TEXT NOT NULL
425
- )`]}function py(t){let{schema_migrations:e}=kt(t);return [`CREATE UNIQUE INDEX IF NOT EXISTS ${t==="sqlite"?"migrations_idempotency_key_idx":"schema_migrations_idempotency_key_idx"} ON ${e} (idempotency_key)`]}function VR(t){let e=dy(t),n=py(t);return [...e.slice(0,1),...n,...e.slice(1)]}function Eu(t){return VR(t).map(e=>e.trim()).join(`;
426
- `)+";"}function QR(t,e){let{schema_migrations:n}=kt(t);return `INSERT INTO ${n} (version, name, statements, rollback, created_by, idempotency_key) VALUES (${lr(e.version)}, ${_u(e.name)}, ${cy(t,e.statements)}, ${cy(t,e.rollback??null)}, ${_u(e.created_by??null)}, ${_u(e.idempotency_key??null)}) ON CONFLICT (idempotency_key) DO UPDATE SET version = EXCLUDED.version, name = EXCLUDED.name, statements = EXCLUDED.statements, rollback = EXCLUDED.rollback, created_by = EXCLUDED.created_by`}function YR(t,e){let{schema_migrations:n}=kt(t);return `DELETE FROM ${n} WHERE version = ${lr(e)}`}function XR(t){let{schema_migrations:e}=kt(t);return `SELECT version FROM ${e} ORDER BY version ASC`}var my="version, name, statements, rollback, created_by, idempotency_key";function ZR(t){let{schema_migrations:e}=kt(t);return `SELECT ${my} FROM ${e} ORDER BY version ASC`}function eC(t,e){let{schema_migrations:n}=kt(t);return `SELECT ${my} FROM ${n} WHERE version = ${lr(e)}`}function tC(t,e){let{schema_migrations:n}=kt(t);return `DELETE FROM ${n} WHERE version >= ${lr(e)}`}async function nC(t,e){let{schema_migrations:n}=kt(e);for(let r of zR){let s=e==="pg"?r.pgType:r.sqliteType;if(e==="pg")await t.exec(`ALTER TABLE ${n} ADD COLUMN IF NOT EXISTS ${r.name} ${s}`);else try{await t.exec(`ALTER TABLE ${n} ADD COLUMN ${r.name} ${s}`);}catch{}}}async function xu(t){let e=Je(t);for(let n of dy(e))await t.exec(n);await nC(t,e);for(let n of py(e))await t.exec(n);}async function rC(t){let e=Je(t);return ((await t.exec(XR(e)))?.rows??[]).map(r=>r.version)}async function sC(t,e){let n=Je(t);await t.exec(QR(n,e));}async function iC(t,e){let n=Je(t);await t.exec(YR(n,e));}async function Tu(t){let e=Je(t);return ((await t.exec(ZR(e)))?.rows??[]).map(fy)}async function oC(t,e){let n=Je(t),s=(await t.exec(eC(n,e)))?.rows?.[0];return s?fy(s):null}async function aC(t,e){let n=Je(t);await t.exec(tC(n,e));}Un();var Ru=[{schema:"auth",enabled:t=>!!t.config.auth?.enabled,getSchemaSql:()=>Su(),provision:"baseSchema"},{schema:"storage",enabled:t=>!!(t.config.storage?.enabled&&t.storageAdapter&&ar("storage")),getSchemaSql:()=>ko(),provision:"baseSchema"},{schema:"supabase_migrations",enabled:t=>(t.config.db?.migrations?.enabled??true)!==false,getSchemaSql:t=>Eu(Je(t.connection)),provision:"direct"}],hy=Ru.filter(t=>t.provision==="baseSchema").map(t=>t.schema);function gy(t){return Ru.filter(e=>e.provision==="baseSchema"&&e.enabled(t)).map(e=>e.getSchemaSql(t)).filter(Boolean).join(`
425
+ )`]}function yy(t){let{schema_migrations:e}=kt(t);return [`CREATE UNIQUE INDEX IF NOT EXISTS ${t==="sqlite"?"migrations_idempotency_key_idx":"schema_migrations_idempotency_key_idx"} ON ${e} (idempotency_key)`]}function nC(t){let e=gy(t),n=yy(t);return [...e.slice(0,1),...n,...e.slice(1)]}function Cu(t){return nC(t).map(e=>e.trim()).join(`;
426
+ `)+";"}function rC(t,e){let{schema_migrations:n}=kt(t);return `INSERT INTO ${n} (version, name, statements, rollback, created_by, idempotency_key) VALUES (${lr(e.version)}, ${Ru(e.name)}, ${py(t,e.statements)}, ${py(t,e.rollback??null)}, ${Ru(e.created_by??null)}, ${Ru(e.idempotency_key??null)}) ON CONFLICT (idempotency_key) DO UPDATE SET version = EXCLUDED.version, name = EXCLUDED.name, statements = EXCLUDED.statements, rollback = EXCLUDED.rollback, created_by = EXCLUDED.created_by`}function sC(t,e){let{schema_migrations:n}=kt(t);return `DELETE FROM ${n} WHERE version = ${lr(e)}`}function iC(t){let{schema_migrations:e}=kt(t);return `SELECT version FROM ${e} ORDER BY version ASC`}var by="version, name, statements, rollback, created_by, idempotency_key";function oC(t){let{schema_migrations:e}=kt(t);return `SELECT ${by} FROM ${e} ORDER BY version ASC`}function aC(t,e){let{schema_migrations:n}=kt(t);return `SELECT ${by} FROM ${n} WHERE version = ${lr(e)}`}function lC(t,e){let{schema_migrations:n}=kt(t);return `DELETE FROM ${n} WHERE version >= ${lr(e)}`}async function cC(t,e){let{schema_migrations:n}=kt(e);for(let r of tC){let s=e==="pg"?r.pgType:r.sqliteType;if(e==="pg")await t.exec(`ALTER TABLE ${n} ADD COLUMN IF NOT EXISTS ${r.name} ${s}`);else try{await t.exec(`ALTER TABLE ${n} ADD COLUMN ${r.name} ${s}`);}catch{}}}async function ku(t){let e=Je(t);for(let n of gy(e))await t.exec(n);await cC(t,e);for(let n of yy(e))await t.exec(n);}async function uC(t){let e=Je(t);return ((await t.exec(iC(e)))?.rows??[]).map(r=>r.version)}async function fC(t,e){let n=Je(t);await t.exec(rC(n,e));}async function dC(t,e){let n=Je(t);await t.exec(sC(n,e));}async function vu(t){let e=Je(t);return ((await t.exec(oC(e)))?.rows??[]).map(hy)}async function pC(t,e){let n=Je(t),s=(await t.exec(aC(n,e)))?.rows?.[0];return s?hy(s):null}async function mC(t,e){let n=Je(t);await t.exec(lC(n,e));}Un();var Au=[{schema:"auth",enabled:t=>!!t.config.auth?.enabled,getSchemaSql:()=>Tu(),provision:"baseSchema"},{schema:"storage",enabled:t=>!!(t.config.storage?.enabled&&t.storageAdapter&&ar("storage")),getSchemaSql:()=>Oo(),provision:"baseSchema"},{schema:"supabase_migrations",enabled:t=>(t.config.db?.migrations?.enabled??true)!==false,getSchemaSql:t=>Cu(Je(t.connection)),provision:"direct"}],wy=Au.filter(t=>t.provision==="baseSchema").map(t=>t.schema);function Sy(t){return Au.filter(e=>e.provision==="baseSchema"&&e.enabled(t)).map(e=>e.getSchemaSql(t)).filter(Boolean).join(`
427
427
 
428
- `)}function yy(t){return !!Ru.find(n=>n.schema==="supabase_migrations")?.enabled(t)}async function by(t){let e=t.config?.baseSchema;if(!e||!e.trim())return;let n=t,r=e;if(n.dialect==="sqlite"&&n.config.ddlDialect!=="sqlite"&&n.translateDdl){let s=await n.translateDdl(e);r=typeof s=="string"?s:s.ddl??e;}for(let s of Fp(r))try{await n.exec(s);}catch{}}var Cu=class{_connection;_rls;config;server;adminMode;drivers;#t;#e=false;_mailer;_storageAdapter;_transformationAdapter;constructor({connection:e,options:n={},rls:r,...s}){this._connection=e,this._rls=r,this.#t=n.system??{},this.config=ly(pi,s,{withDefaults:n.defaults??true}),this.drivers=Gh(n.drivers,this.config),this.adminMode=n.server?.admin===true,this.server=oy(this,n.server);}get connection(){if(this._connection instanceof Promise)throw new Error("Connection is not available yet");return this._connection}async init(){if(this.#e)return this;ry(),this.config.auth?.enabled&&yo(this.config.auth),await this._connection;let e=this.connection;if(e.config.schemaCache??=this.drivers.cache,e.config.baseSchema=[e.config.baseSchema??"",gy(this.#n())].filter(Boolean).join(`
428
+ `)}function _y(t){return !!Au.find(n=>n.schema==="supabase_migrations")?.enabled(t)}async function Ey(t){let e=t.config?.baseSchema;if(!e||!e.trim())return;let n=t,r=e;if(n.dialect==="sqlite"&&n.config.ddlDialect!=="sqlite"&&n.translateDdl){let s=await n.translateDdl(e);r=typeof s=="string"?s:s.ddl??e;}for(let s of Mp(r))try{await n.exec(s);}catch{}}var Ou=class{_connection;_rls;config;server;adminMode;drivers;#t;#e=false;_mailer;_storageAdapter;_transformationAdapter;constructor({connection:e,options:n={},rls:r,...s}){this._connection=e,this._rls=r,this.#t=n.system??{},this.config=dy(pi,s,{withDefaults:n.defaults??true}),this.drivers=Vh(n.drivers,this.config),this.adminMode=n.server?.admin===true,this.server=uy(this,n.server);}get connection(){if(this._connection instanceof Promise)throw new Error("Connection is not available yet");return this._connection}async init(){if(this.#e)return this;ay(),this.config.auth?.enabled&&So(this.config.auth),await this._connection;let e=this.connection;if(e.config.schemaCache??=this.drivers.cache,e.config.baseSchema=[e.config.baseSchema??"",Sy(this.#n())].filter(Boolean).join(`
429
429
 
430
- `),this._rls){let n=e;if(typeof n.updateDeparseInfo=="function"){let r=n.config.translation?.deparse;n.updateDeparseInfo({enums:r?.enums??new Map,schema:r?.schema??new Map,vars:r?.vars??new Map,...r,rls:{tables:new Set(this._rls.tables),policies:this._rls.policies}});}}return this.#e=true,this}#n(){return {config:this.config,connection:this.connection,storageAdapter:this._storageAdapter}}async ensureSystemSchema(e){await this.init();let n=this.connection,r=this.#n();if(yy(r)&&await xu(n),(this.#t.schemaReconciliation??"additive")==="full"&&Je(n)!=="sqlite"){let i=n.createMigrator(""),{plan:o}=await i.diff({schemas:hy});await i.migratePlan(o,{force:e?.force});}else await by(n);}isValidConfig(e){if(typeof e=="object"&&e!==null&&("connection"in e||"options"in e)){let{connection:n,options:r,...s}=e;return pi.validate(s).valid}return pi.validate(e).valid}getClient(e){let n=s=>{let i=s?.trim();return i&&i.length>0?i:void 0},r=n(e?.apikey)??n(this.config.auth?.publishable_key)??"<nokey>";return createClient("http://localhost",r,{...e,global:{...e?.global,fetch:async(s,i)=>{let o=new Request(s,i);return Object.assign(o,{[kn]:true}),await this.fetch(o)}}})}isLocalRequest(e){return kn in e}fetch=async e=>(await this.init(),this.server.fetch(e));getInfoJson(){return JSON.parse(jsonStringify({connection:this.connection?.config??{},config:this.config}))}};var wy=class extends Error{name="UnableToCreateRuntimeConnection";constructor(e){super(`Unable to create runtime connection: ${e}`);}},Sy=class extends Error{constructor(n,r,s){super(`Failed to translate Postgres to SQLite DDL: ${String(s)}`);this.pgSql=n;this.sqliteDdl=r;this.cause=s;}name="InvalidPostgresToSQLiteTranslation"};Ho();Yr();var uC=(t={})=>{let e=(n="m")=>[...t.exclude_tables??[],"sqlite_%"].map(r=>r.includes("%")?`${n}.name NOT LIKE '${r}'`:`${n}.name != '${r}'`).join(" AND ");return `WITH table_info AS (SELECT
430
+ `),this._rls){let n=e;if(typeof n.updateDeparseInfo=="function"){let r=n.config.translation?.deparse;n.updateDeparseInfo({enums:r?.enums??new Map,schema:r?.schema??new Map,vars:r?.vars??new Map,...r,rls:{tables:new Set(this._rls.tables),policies:this._rls.policies}});}}return this.#e=true,this}#n(){return {config:this.config,connection:this.connection,storageAdapter:this._storageAdapter}}async ensureSystemSchema(e){await this.init();let n=this.connection,r=this.#n();if(_y(r)&&await ku(n),(this.#t.schemaReconciliation??"additive")==="full"&&Je(n)!=="sqlite"){let i=n.createMigrator(""),{plan:o}=await i.diff({schemas:wy});await i.migratePlan(o,{force:e?.force});}else await Ey(n);}isValidConfig(e){if(typeof e=="object"&&e!==null&&("connection"in e||"options"in e)){let{connection:n,options:r,...s}=e;return pi.validate(s).valid}return pi.validate(e).valid}getClient(e){let n=s=>{let i=s?.trim();return i&&i.length>0?i:void 0},r=n(e?.apikey)??n(this.config.auth?.publishable_key)??"<nokey>";return createClient("http://localhost",r,{...e,global:{...e?.global,fetch:async(s,i)=>{let o=new Request(s,i);return Object.assign(o,{[kn]:true}),await this.fetch(o)}}})}isLocalRequest(e){return kn in e}fetch=async e=>(await this.init(),this.server.fetch(e));getInfoJson(){return JSON.parse(jsonStringify({connection:this.connection?.config??{},config:this.config}))}};var xy=class extends Error{name="UnableToCreateRuntimeConnection";constructor(e){super(`Unable to create runtime connection: ${e}`);}},Ty=class extends Error{constructor(n,r,s){super(`Failed to translate Postgres to SQLite DDL: ${String(s)}`);this.pgSql=n;this.sqliteDdl=r;this.cause=s;}name="InvalidPostgresToSQLiteTranslation"};Jo();Xr();var yC=(t={})=>{let e=(n="m")=>[...t.exclude_tables??[],"sqlite_%"].map(r=>r.includes("%")?`${n}.name NOT LIKE '${r}'`:`${n}.name != '${r}'`).join(" AND ");return `WITH table_info AS (SELECT
431
431
  json_group_array(
432
432
  json_object(
433
433
  'name', m.name,
@@ -628,15 +628,15 @@ CREATE TABLE IF NOT EXISTS auth.audit_log_entries (
628
628
  (SELECT data FROM trigger_info) AS triggers,
629
629
  (SELECT data FROM unique_info) AS unique_constraints,
630
630
  ${t.name?`'${t.name}'`:"'sqlite'"} AS database_name,
631
- ${t.version?`'${t.version}'`:"sqlite_version()"} AS version;`};function Gt(t){if(!t)return [];try{return Array.isArray(t)?t:JSON.parse(t)}catch{return []}}async function xy(t,e={}){let r=(await t.exec(uC(e)))?.rows?.[0]||{};return {tables:Gt(r.tables),columns:Gt(r.columns),indexes:Gt(r.indexes),foreign_keys:Gt(r.foreign_keys),primary_keys:Gt(r.primary_keys),views:Gt(r.views),triggers:Gt(r.triggers),check_constraints:[],unique_constraints:Gt(r.unique_constraints),comments:[],custom_types:[],database_name:r.database_name??"sqlite",version:r.version??""}}function fC(t,e){if(!t||!e.ref_column)return;let n=i=>i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`CONSTRAINT\\s+("?)(\\w+)\\1\\s+FOREIGN\\s+KEY\\s*\\(\\s*"?${n(e.column)}"?\\s*\\)\\s+REFERENCES\\s+"?${n(e.ref_table)}"?\\s*\\(\\s*"?${n(e.ref_column)}"?\\s*\\)`,"i");return t.match(r)?.[2]}function Ty(t){return t.startsWith("fk_")&&!t.endsWith("_fkey")}function vu(t){return `${t.schema}.${t.table}.${t.foreign_key_name}.${t.ref_schema??""}.${t.ref_table}`}function dC(t){let e=new Map;for(let r of t){if(!Ty(r.foreign_key_name))continue;let s=e.get(vu(r));s?s.push(r):e.set(vu(r),[r]);}let n=new Map;for(let[r,s]of e)s.length<2||n.set(r,`${s[0].table}_${s.map(i=>i.column).join("_")}_fkey`);return n.size===0?t:t.map(r=>{let s=n.get(vu(r));return s?{...r,foreign_key_name:s}:r})}function Ry(t){if(!t.tables?.length||!t.foreign_keys?.length)return t;let e=new Map(t.tables.map(r=>[r.name,r.sql])),n=t.foreign_keys.map(r=>{if(r.foreign_key_name?.endsWith("_fkey")||r.foreign_key_name&&!Ty(r.foreign_key_name))return r;let s=e.get(r.table),i=fC(s,r);return i?{...r,foreign_key_name:i}:r});return {...t,foreign_keys:dC(n)}}function Au(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')||e.startsWith("`")&&e.endsWith("`")||e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function pC(t){let e=[],n="",r=0,s=null;for(let i=0;i<t.length;i++){let o=t[i];if(s){n+=o,o===s&&(s=null);continue}if(o==='"'||o==="`"||o==="'"){s=o,n+=o;continue}if(o==="("?r++:o===")"&&r>0&&r--,o===","&&r===0){e.push(n.trim()),n="";continue}n+=o;}return n.trim()&&e.push(n.trim()),e}function mC(t){let e=t.match(/^(.*?)\s+as\s+(.+)$/i),n=e?e[1].trim():t.trim(),r=e?e[2].trim():void 0;if(!r){let o=t.match(/^(.+?)\s+((?:"[^"]+"|`[^`]+`|\[[^\]]+\]|\w+))$/);o&&!/[()]/.test(o[1])&&(n=o[1].trim(),r=o[2].trim());}let s=n.split(".").map(Au);if(s.length>2)return null;let i=s.at(-1);return !i||!/^[A-Za-z_][\w$]*$/.test(i)?null:{baseColumn:i,viewColumn:r?Au(r):i}}function Cy(t){return !!(t&&/[A-Za-z0-9_$]/.test(t))}function hC(t){let e=/\bselect\b/i.exec(t);if(!e)return null;let n=0,r=null;for(let s=e.index+e[0].length;s<t.length;s++){let i=t[s];if(r){i===r&&(r=null);continue}if(i==='"'||i==="`"||i==="'"){r=i;continue}if(i==="("){n++;continue}if(i===")"&&n>0){n--;continue}if(n===0&&t.slice(s,s+4).toLowerCase()==="from"&&!Cy(t[s-1])&&!Cy(t[s+4]))return {selectList:t.slice(e.index+e[0].length,s).trim(),fromRest:t.slice(s+4).trim()}}return null}function gC(t){let e=0,n=[];for(;e<t.length;){for(;/\s/.test(t[e]??"");)e++;let r=t[e],s="";if(r==='"'||r==="`"){let a=t.indexOf(r,e+1);if(a===-1)return null;s=t.slice(e,a+1),e=a+1;}else if(r==="["){let a=t.indexOf("]",e+1);if(a===-1)return null;s=t.slice(e,a+1),e=a+1;}else {let a=/^[A-Za-z_][\w$]*/.exec(t.slice(e));if(!a)return null;s=a[0],e+=s.length;}n.push(s);let i=t.slice(e),o=/^\s*\./.exec(i);if(!o)break;e+=o[0].length;}return n.length===0?null:{raw:n.join("."),rest:t.slice(e).trim()}}function ky(t,e,n){let r=t.get(e)??[];r.includes(n)||r.push(n),t.set(e,r);}function yC(t,e){if(!t)return null;let n=hC(t);if(!n)return null;let r=gC(n.fromRest);if(!r)return null;let{raw:s,rest:i}=r;if(/\b(join|union|intersect|except)\b/i.test(i))return null;let o=s.split(".").map(Au).at(-1);if(!o)return null;let a=new Map,l=e.get(o)??new Set;for(let c of pC(n.selectList)){let f=c.trim();if(f==="*"||f.endsWith(".*")){for(let d of l)ky(a,d,d);continue}let u=mC(c);u&&ky(a,u.baseColumn,u.viewColumn);}return a.size===0?null:{baseTable:o,columns:a}}function bC(t,e){let n=new Map;for(let[r,s]of e){let i=[];for(let o of s){let a=t.get(o);if(a)for(let l of a)i.includes(l)||i.push(l);}i.length>0&&n.set(r,i);}return n}function wC(t){let e=new Map,n=new Map;for(let a of t.columns??[]){let l=n.get(a.table)??new Set;l.add(a.name),n.set(a.table,l);}let r=(a,l)=>{let c=e.get(a)??[];c.some(f=>f.name===l.name&&f.schema===l.schema)||c.push(l),e.set(a,c);};for(let a of t.tables??[]){if(a.type!=="table")continue;let l=n.get(a.name);l&&r(a.name,{name:a.name,schema:a.schema,columnByBaseColumn:new Map([...l].map(c=>[c,[c]]))});}let s=new Map;for(let a of t.views??[]){let l=yC(a.sql,n);if(!l)continue;let c=n.get(a.name);if(!c)continue;let f=new Map;for(let[d,p]of l.columns){let g=p.filter(m=>c.has(m));g.length>0&&f.set(d,g);}if(f.size===0)continue;let u={name:a.name,schema:a.schema,columnByBaseColumn:f,fromRelation:l.baseTable};s.set(a.name,u);}let i=16;function o(a,l,c){if(l>i)return null;let f=a.fromRelation;if(e.has(f))return {physicalBase:f,columnByBaseColumn:a.columnByBaseColumn};let u=s.get(f);if(!u||c.has(f))return null;c.add(f);let d=o(u,l+1,c);if(c.delete(f),!d)return null;let p=bC(a.columnByBaseColumn,d.columnByBaseColumn);return p.size===0?null:{physicalBase:d.physicalBase,columnByBaseColumn:p}}for(let a of s.values()){let l=o(a,0,new Set([a.name]));l&&r(l.physicalBase,{name:a.name,schema:a.schema,columnByBaseColumn:l.columnByBaseColumn});}return e}function vy(t){return `${t.foreign_key_group??""}:${t.table}.${t.column}->${t.ref_table}.${t.ref_column}`}function SC(t){let e=new Map;for(let n of t){let r=`${n.schema}.${n.table}.${n.foreign_key_name}.${n.ref_schema??""}.${n.ref_table}`,s=e.get(r);s?s.push(n):e.set(r,[n]);}return [...e.values()]}function _C(t){let e=[[]];for(let n of t){let r=[];for(let s of e)for(let i of n)r.push([...s,i]);e=r;}return e}function EC(t,e,n,r){let s=r.map(o=>o.childColumn).join(","),i=r.map(o=>o.parentColumn).join(",");return `${n}:${t.name}(${s})->${e.name}(${i})`}function Ay(t){if(!t.foreign_keys?.length||!t.views?.length)return t;let e=wC(t),n=new Set(t.foreign_keys.map(vy)),r=[];for(let s of SC(t.foreign_keys)){let i=s[0],o=e.get(i.table)??[],a=e.get(i.ref_table)??[];for(let l of o)for(let c of a){if(l.schema!==c.schema)continue;let f=[];for(let u of s){let d=l.columnByBaseColumn.get(u.column)??[],p=c.columnByBaseColumn.get(u.ref_column)??[],g=d.flatMap(m=>p.map(h=>({fk:u,childColumn:m,parentColumn:h})));if(g.length===0){f.length=0;break}f.push(g);}for(let u of _C(f)){let p=l.name===i.table&&c.name===i.ref_table&&u.every(g=>g.childColumn===g.fk.column&&g.parentColumn===g.fk.ref_column)?void 0:EC(l,c,i.foreign_key_name,u);for(let g of u){let m={...g.fk,table:l.name,column:g.childColumn,schema:l.schema,ref_table:c.name,ref_column:g.parentColumn,ref_schema:c.schema,foreign_key_group:p},h=vy(m);n.has(h)||(n.add(h),r.push(m));}}}}return r.length?{...t,foreign_keys:[...t.foreign_keys,...r]}:t}var AC=new Set(["AlterTableNode","CreateIndexNode","CreateSchemaNode","CreateTableNode","CreateTypeNode","CreateViewNode","RefreshMaterializedViewNode","DeleteQueryNode","DropIndexNode","DropSchemaNode","DropTableNode","DropTypeNode","DropViewNode","InsertQueryNode","RawNode","SelectQueryNode","UpdateQueryNode","MergeQueryNode"]),Ou=class extends OperationNodeTransformer{constructor(n){super();this.config=n;}#t=new Set;#e=new Set;transformNodeImpl(n,r){if(!AC.has(n.kind))return super.transformNodeImpl(n,r);let s=this.#s(n);for(let o of s)this.#e.add(o);let i=this.#n(n);for(let o of i)this.#t.add(o);try{return super.transformNodeImpl(n,r)}finally{for(let o of i)this.#t.delete(o);for(let o of s)this.#e.delete(o);}}transformSchemableIdentifier(n,r){let s=n.identifier.name,i=n.schema?.name,o=!i&&this.config.appendDefaultSchema&&this.config.defaultSchema&&!this.#e.has(s)&&this.#t.has(s),a=i??(o?this.config.defaultSchema:void 0);if(!a)return {kind:"SchemableIdentifierNode",schema:void 0,identifier:{kind:"IdentifierNode",name:s}};let l=this.config.approach==="snake_case"?"__":".";return {kind:"SchemableIdentifierNode",schema:void 0,identifier:{kind:"IdentifierNode",name:`${a}${l}${s}`}}}#n(n){let r=new Set;if(n?.name&&SchemableIdentifierNode.is(n.name)&&this.#r(n.name,r),n?.from?.froms)for(let s of n.from.froms)this.#i(s,r);if(n?.into&&this.#i(n.into,r),n?.table&&this.#i(n.table,r),n?.joins)for(let s of n.joins)this.#i(s.table,r);return n?.using&&(JoinNode.is(n.using)?this.#i(n.using.table,r):this.#i(n.using,r)),r}#i(n,r){if(TableNode.is(n)){this.#r(n.table,r);return}if(AliasNode.is(n)&&TableNode.is(n.node)){this.#r(n.node.table,r);return}if(ListNode.is(n)){for(let s of n.items)this.#i(s,r);return}if(UsingNode.is(n))for(let s of n.tables)this.#i(s,r);}#r(n,r){let s=n.identifier.name;this.#e.has(s)||r.add(s);}#s(n){let r=new Set;if(n?.with?.expressions)for(let s of n.with.expressions){let i=s?.name?.table?.table?.identifier?.name;i&&r.add(i);}return r}},Wo=class{#t;constructor(e){this.#t=new Ou(e);}transformQuery(e){return this.#t.transformNode(e.node)}async transformResult(e){return e.result}};Js();Pu();$u();function NC(t,e){return t==="migrations"||t==="supabase_migrations.schema_migrations"||t==="supabase_migrations.seed_files"||e==="sqlite"&&t==="seed_files"}function $y(t,e){let n=r=>NC(r,e);return {...t,tables:t.tables.filter(r=>!n(r.name)),columns:t.columns.filter(r=>!n(r.table)),indexes:t.indexes.filter(r=>!n(r.table)),foreign_keys:t.foreign_keys.filter(r=>!n(r.table)),primary_keys:t.primary_keys.filter(r=>!n(r.table))}}function fr(t,e,n){return n.includes(t)?true:n.some(r=>e.startsWith(`${r}.`)||e.startsWith(`${r}__`))}function Iy(t,e){let n=t.tables.filter(i=>fr(i.schema,i.name,e)),r=new Set(n.map(i=>i.name)),s=i=>i.filter(o=>r.has(o.table)||fr(o.schema,o.table,e));return {...t,tables:n,columns:s(t.columns),indexes:s(t.indexes),foreign_keys:s(t.foreign_keys),primary_keys:s(t.primary_keys),views:t.views.filter(i=>fr(i.schema,i.name,e)),check_constraints:s(t.check_constraints),unique_constraints:s(t.unique_constraints),comments:s(t.comments),custom_types:t.custom_types.filter(i=>fr(i.schema,i.type,e)),triggers:t.triggers.filter(i=>fr(i.schema,i.table,e)),functions:t.functions?.filter(i=>e.includes(i.schema)),partitions:t.partitions?.filter(i=>fr(i.schema,i.name,e))}}var Jo=class{constructor(e,n,r={}){this.conn=e;this.desiredSchema=n;this.options=r;this.differ=new cr,this.planner=new ur;}differ;planner;translationResult;async getDesiredSchema(){let e=await this.conn.translateDdl(this.desiredSchema);return this.translationResult=e,await this.options.onTranslation?.(e),e.ddl}async diff(e){let n=await this.conn.introspect({postprocess:false}),r=await this.getDesiredSchema();if(!r||r.trim().length===0)return {current:n,desired:n,diff:{tables:[],columns:[],indexes:[],foreign_keys:[],has_changes:false},plan:{steps:[],warnings:[],unsafe:false}};let{createConnection:s}=await import('@supabase/lite/sqlite'),i=await s({url:":memory:"});try{await i.exec(r);let o=await i.introspect({postprocess:!1}),a=this.conn.config.ddlDialect,[l,c]=e?.schemas?[Iy(n,e.schemas),Iy(o,e.schemas)]:[$y(n,a),$y(o,a)],f=this.differ.diff(l,c),u=this.planner.plan(f,l,c);return {current:n,desired:o,diff:f,plan:u}}finally{await i.close();}}safeSortPlanSteps(e){return invariant(Array.isArray(e),"steps must be an array"),e}async migratePlan(e,n){if(e.steps.length===0)return;if(e.unsafe&&!n?.force)throw new DataLossError(e.warnings??[]);let r=this.safeSortPlanSteps(e.steps).filter(s=>![PlanStepType.DISABLE_FOREIGN_KEYS,PlanStepType.BEGIN_TRANSACTION,PlanStepType.COMMIT_TRANSACTION,PlanStepType.ENABLE_FOREIGN_KEYS].includes(s.type));await this.conn.transaction(r.map(s=>s.sql),{intent:"migration"});}async migrate(e){let n=await this.diff({schemas:e?.schemas});return await this.migratePlan(n.plan,e),n}};Vr();var Dy=/^\{\{(.+)\}\}$/;function jy(t){return typeof t=="string"&&Dy.test(t)}function DC(t){return Dy.exec(t)[1]}var Ny=Symbol("unresolved");function Ly(t,e){let n=DC(t),r=qt(e,n,Ny);if(r===Ny)throw new Error(`Unresolved variable: {{${n}}}`);return r}function vt(t,e){let n={};for(let[r,s]of Object.entries(t)){if(r==="$or"||r==="$and"){n[r]=s.map(i=>vt(i,e));continue}if(r==="$not"){n[r]=vt(s,e);continue}if(r==="$always"){n[r]=s;continue}if(r==="$exists"){let i=s;n[r]={...i,where:i?.where?vt(i.where,e):i?.where};continue}if(jy(r)){let i=Ly(r,e),a=LC(i,s);n.$always=a;continue}if(s!=null&&typeof s=="object"&&!Array.isArray(s)){n[r]=Fy(s,e);continue}n[r]=s;}return n}function Fy(t,e){let n={};for(let[r,s]of Object.entries(t))r==="$not"&&s!=null&&typeof s=="object"?n[r]=Fy(s,e):jC(s)?n[r]={...s,where:s?.where?vt(s?.where,e):void 0}:jy(s)?n[r]=Ly(s,e):n[r]=s;return n}function jC(t){return t!=null&&typeof t=="object"&&t.type==="query"}function LC(t,e){for(let[n,r]of Object.entries(e))switch(n){case "$eq":if(t!==r)return false;break;case "$neq":if(t===r)return false;break;case "$in":if(!Array.isArray(r)||!r.includes(t))return false;break;case "$notIn":if(Array.isArray(r)&&r.includes(t))return false;break;default:throw new Error(`Cannot statically evaluate operator ${n} on placeholder key`)}return true}Vr();var Gs=class{constructor(e,n,r){this.tables=e;this.policies=n;this.defaultSchema=r;}enforce(e,n){let r=e.from;if(!r||!this.isRlsEnabled(r,e.schema))return e;let s=FC(e.type);if(!s)return e;let i=qt(n,"auth.role")??"anon";if(i==="service_role")return e;let{permissive:o,restrictive:a}=this.resolvePolicies(r,e.schema,s,i);switch(s){case "SELECT":case "DELETE":{let l=this.combineUsing(o,a,n);return {...e,where:Uy(e.where,l)}}case "UPDATE":{let l=this.combineUsing(o,a,n),c={...e,where:Uy(e.where,l)};if(l.$always===false)return c;let f=this.combineWithCheck(o,a,n,s);if(e.values&&Object.keys(f).length>0){let u=new Set(Object.keys(e.values));this.validateWithCheck(f,e.values,o,a,u);}return c}case "INSERT":{let l=this.combineWithCheck(o,a,n,s);if(e.values){let c=Array.isArray(e.values)?e.values:[e.values];for(let f of c)this.validateWithCheck(l,f,o,a);}return e}default:return e}}isRlsEnabled(e,n){return this.tables.has(e)}resolvePolicies(e,n,r,s){let i=this.policies.filter(o=>o.data.table===e&&this.schemasMatch(o.data.schema,n)&&o.appliesTo(r)&&o.appliesToRole(s));return {permissive:i.filter(o=>o.data.permissive),restrictive:i.filter(o=>!o.data.permissive)}}schemasMatch(e,n){let r=e||this.defaultSchema,s=n||this.defaultSchema;return r===s}combineUsing(e,n,r){if(e.length===0)return {$always:false};let s=e.map(o=>o.data.using).filter(o=>o!=null&&Object.keys(o).length>0).map(o=>vt(o,r)),i;s.length===0?i={}:s.length===1?i=s[0]:i={$or:s};for(let o of n)if(o.data.using&&Object.keys(o.data.using).length>0){let a=vt(o.data.using,r);i=Object.keys(i).length===0?a:{$and:[i,a]};}return i}combineWithCheck(e,n,r,s){if(e.length===0)return {$always:false};let i=e.map(a=>a.data.withCheck??(s==="UPDATE"?a.data.using:void 0)).filter(a=>a!=null&&Object.keys(a).length>0).map(a=>vt(a,r)),o;i.length===0?o={}:i.length===1?o=i[0]:o={$or:i};for(let a of n){let l=a.data.withCheck??(s==="UPDATE"?a.data.using:void 0);if(l&&Object.keys(l).length>0){let c=vt(l,r);o=Object.keys(o).length===0?c:{$and:[o,c]};}}return o}validateWithCheck(e,n,r,s,i){if(Object.keys(e).length===0)return;if(!Go(e,n,i)){let a=r[0]??s[0];throw a?new Wn(a):new Error("RLS policy violation")}}};function FC(t){switch(t){case "query":return "SELECT";case "insert":case "upsert":case "put":return "INSERT";case "update":return "UPDATE";case "delete":return "DELETE";default:return}}function Uy(t,e){return !t||Object.keys(t).length===0?e:Object.keys(e).length===0?t:{$and:[t,e]}}function Go(t,e,n){for(let[r,s]of Object.entries(t)){if(r==="$always"){if(s===false)return false;continue}if(r==="$and"){if(!s.every(l=>Go(l,e,n)))return false;continue}if(r==="$or"){if(!s.some(l=>Go(l,e,n)))return false;continue}if(r==="$not"){if(Go(s,e,n))return false;continue}if(n&&!n.has(r))continue;let i=s,o=e[r];for(let[a,l]of Object.entries(i))if(!UC(o,a,l))return false}return true}function UC(t,e,n){switch(e){case "$eq":return t===n;case "$neq":return t!==n;case "$gt":return t>n;case "$gte":return t>=n;case "$lt":return t<n;case "$lte":return t<=n;case "$in":return Array.isArray(n)&&n.includes(t);case "$notIn":return !Array.isArray(n)||!n.includes(t);case "$is":return t===n;case "$isNot":return t!==n;default:throw new Error(`Cannot evaluate operator "${e}" client-side for WITH CHECK`)}}var zo=class{transformQuery(e){return e.node}transformResult(e){return e.result.rows?Promise.resolve({...e.result,rows:e.result.rows.map(n=>{let r={};for(let s in n){let i=n[s];if(typeof i=="string"&&(i[0]==="{"||i[0]==="["))try{r[s]=JSON.parse(i);}catch{r[s]=i;}else r[s]=i;}return r})}):Promise.resolve(e.result)}};function My(t){let e={};for(let n in t){let r=t[n];if(typeof r=="string"&&(r[0]==="["||r[0]==="{"))try{e[n]=JSON.parse(r);}catch{e[n]=r;}else e[n]=r;}return e}Yl();ro();function MC(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/--.*$/gm,"")}function BC(t){let e=t.trim();return e.startsWith('"')?e.replace(/^"(.*)"$/,"$1"):e.toLowerCase()}function Vo(t){let e=t.split(".");return BC(e[e.length-1]??t)}var Du='(?:"[^"]+"|[A-Za-z_][\\w$]*)',Iu=`${Du}(?:\\s*\\.\\s*${Du})?`,Nu=new RegExp([`\\bALTER\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?(?:ONLY\\s+)?(${Iu})\\s+(?:(ENABLE|DISABLE)\\s+ROW\\s+LEVEL\\s+SECURITY\\b|RENAME\\s+TO\\s+(${Du}))`,`\\bDROP\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?(${Iu}(?:\\s*,\\s*${Iu})*)`].join("|"),"gi");function By(t){let e=[...t].sort((i,o)=>i.version.localeCompare(o.version)),n=MC(e.flatMap(i=>i.statements??[]).join(`
632
- `)),r=new Set;Nu.lastIndex=0;let s=Nu.exec(n);for(;s!==null;){let[,i,o,a,l]=s;if(i&&o){let c=Vo(i);o.toUpperCase()==="ENABLE"?r.add(c):r.delete(c);}else if(i&&a)r.delete(Vo(i))&&r.add(Vo(a));else if(l)for(let c of l.split(","))r.delete(Vo(c));s=Nu.exec(n);}return r}var Qs=class t extends Connection{dialect="sqlite";#t=false;#e;deserializeRow(e){return this.config.ddlDialect==="postgres"?My(e):e}constructor(e={}){let n=e.translation?.deparse!=null;super({...e,translation:{...e.translation,schemas:{appendDefaultSchema:false,approach:"quote",defaultSchema:"public",...e.translation?.schemas},deparse:t.parseDeparseInfo(e.translation?.deparse)},introspection:{name:"sqlite",...e.introspection,exclude_tables:Array.from(new Set([...e.introspection?.exclude_tables??[],"sqlite_%","supabase_migrations.%","migrations",...e.ddlDialect==="sqlite"?["seed_files"]:[]]))}}),this.#t=n;}static parseDeparseInfo(e,n){try{if(typeof e!="object"||e===null)return {};let r=e?.rls?.tables instanceof Set?e.rls.tables:new Set(e.rls?.tables??[]),s=(e?.rls?.policies??[]).map(f=>new Ge(JSON.parse(JSON.stringify(f)))),i=e?.vars instanceof Map?e.vars:new Map(Object.entries(e.vars??{})),o=e?.enums instanceof Map?e.enums:new Map(Object.entries(e.enums??{})),a;if(e?.schema instanceof Map)a=e.schema;else if(e?.schema&&typeof e.schema=="object"){a=new Map;for(let[f,u]of Object.entries(e.schema)){let d;for(let{context:p,extra:g}of u??[]){d??=new at(p.table,p.schema);let m=o.get(p.pgTypeName.toLowerCase());d.set(p.column,We({...p,defaultFn:null},{...g,...m?{enumValues:m}:{}}));}d&&a.set(f,d);}}let l=e?.tableConstraints??void 0,c=e?.comments??void 0;return {rls:{tables:r,policies:s},vars:i,enums:o,...a?{schema:a}:{},...l?{tableConstraints:l}:{},...c?{comments:c}:{}}}catch(r){if(n?.strict)throw r;return console.log("error parsing deparse info",r),{}}}static serializeDeparseInfo(e){let n=e?.rls??{tables:new Set,policies:[]},r=e?.vars??new Map,s=e?.enums??new Map,i={};for(let[l,c]of e?.schema??new Map)i[l]=c.all().map(f=>{let{defaultFn:u,...d}=f.context;return {context:d,extra:f.factoryExtra}});let o=e?.tableConstraints??[],a=e?.comments??[];return JSON.parse($p({rls:{tables:n.tables,policies:n.policies},vars:r,enums:s,schema:i,tableConstraints:o,comments:a}))}updateDeparseInfo(e){this.config.translation={...this.config.translation,deparse:e},this.#t=true;}withSqlitePlugins(e=[]){let n=[];return this.config.ddlDialect==="sqlite"&&n.push(new zo),n.push(new Wo(vl({appendDefaultSchema:false,approach:"quote",defaultSchema:"public"},{...this.config.translation?.schemas}))),[...n,...e]}async translateDdl(e){if(e.trim().length===0)return {ddl:e};if(this.config.ddlDialect==="sqlite")return {ddl:e};let n=this.config.translation?.schemas?.defaultSchema&&this.config.translation?.schemas?.appendDefaultSchema?this.config.translation?.schemas?.defaultSchema:false,r=await this.introspect({postprocess:false}).catch(()=>{}),{deparsePostgresDdl:s}=await Promise.resolve().then(()=>(Bu(),db));return await s(e,{forceDefaultSchema:n,introspection:r,defaultSchema:this.config.translation?.schemas?.defaultSchema||void 0,schemaHandling:this.config.translation?.schemas?.approach==="snake_case"?"prefix":"default"})}async introspect(e){jp(typeof e=="object"||e===void 0,"options must be an object");let n=e?.useCache??false;if(e?.postprocess!==false){let i=await this.readCachedIntrospection({useCache:n});if(i)return i}let r=await xy(this,this.config.introspection),s=this.config.translation?.schemas?.approach==="snake_case"?"__":".";if(this.config.ddlDialect==="postgres"&&e?.postprocess!==false){let i=this.config.translation?.schemas?.defaultSchema??this.config.translation?.schemas?.appendDefaultSchema?"public":void 0,o=(l="table")=>c=>{let f=c[l],u=c.schema??i;return !u&&i&&f.includes(s)&&([u,f]=f.split(s)),{...c,[l]:f,schema:u??i}},a=l=>{let c=o()(l),f=c.ref_table,u=c.ref_schema??i;return f?.includes(s)&&([u,f]=f.split(s)),{...c,ref_table:f,ref_schema:u??i}};r={...r,tables:r.tables.map(o("name")),columns:r.columns.map(o()),indexes:r.indexes.map(o()),primary_keys:r.primary_keys.map(o()),foreign_keys:r.foreign_keys.map(a),views:r.views.map(o("name")),check_constraints:r.check_constraints.map(o("table"))};}return r=Ry(r),r=Ay(r),this.config.ddlDialect==="postgres"&&e?.postprocess!==false&&(r=this.mergeDeparseMetadata(r)),r={...r,columns:r.columns.map(i=>!i.pg_type&&Le(i.type)?{...i,pg_type:i.type.toLowerCase().trim()}:i),ddl_dialect:this.config.ddlDialect??"postgres",schema_separator:s},e?.postprocess!==false&&await this.writeCachedIntrospection(r,{useDriver:n}),r}async transaction(e,n){n?.intent==="migration"&&await this.exec("PRAGMA foreign_keys=OFF;"),await this.exec("BEGIN");try{for(let r of e)try{await this.exec(r);}catch(s){throw console.error(`Failed to execute statement: ${r}`),s}await this.exec("COMMIT");}catch(r){throw await this.exec("ROLLBACK"),r}finally{n?.intent==="migration"&&(await this.exec("PRAGMA foreign_keys=ON;"),await this.clearSchemaCache());}}async close(){}mergeDeparseMetadata(e){let n=this.config.translation?.deparse;if(!n?.schema)return e;let r=e.columns.map(l=>({...l})),s=e.foreign_keys.map(l=>({...l})),i=[...e.unique_constraints??[]],o=[...e.check_constraints??[]];for(let[,l]of n.schema)for(let c of l.all()){let f=c.context,u=r.find(d=>d.table===f.table&&d.name===f.column);if(u&&(u.pg_type=f.pgTypeName,f.isGenerated!==void 0&&(u.is_generated=f.isGenerated)),f.fkRef?.constraintName){let d=s.find(p=>p.table===f.table&&p.column===f.column&&p.ref_table===f.fkRef.refTable&&p.ref_column===f.fkRef.refColumn);d&&(d.foreign_key_name=f.fkRef.constraintName);}f.uniqueConstraintName&&i.push({schema:f.schema,table:f.table,name:f.uniqueConstraintName,columns:[f.column]}),f.hasCheck&&o.push({schema:f.schema,table:f.table,expression:"",name:f.checkConstraintName,column:f.column});}for(let l of n.tableConstraints??[])if(l.kind==="unique")i.push({schema:l.schema,table:l.table,name:l.name??"",columns:l.columns});else if(l.kind==="check")o.push({schema:l.schema,table:l.table,expression:"",name:l.name});else if(l.kind==="foreign_key"&&l.name){let c=l.refTable;for(let f=0;f<l.columns.length;f++){let u=s.find(d=>d.table===l.table&&d.column===l.columns[f]&&d.ref_table===c&&d.ref_column===(l.refColumns?.[f]??""));u&&(u.foreign_key_name=l.name);}}let a=[...e.comments??[],...n.comments??[]];return {...e,columns:r,foreign_keys:s,unique_constraints:i,check_constraints:o,comments:a}}createMigrator(e){let n=[this.config.baseSchema,e].filter(Boolean).join(`
631
+ ${t.version?`'${t.version}'`:"sqlite_version()"} AS version;`};function Gt(t){if(!t)return [];try{return Array.isArray(t)?t:JSON.parse(t)}catch{return []}}async function ky(t,e={}){let r=(await t.exec(yC(e)))?.rows?.[0]||{};return {tables:Gt(r.tables),columns:Gt(r.columns),indexes:Gt(r.indexes),foreign_keys:Gt(r.foreign_keys),primary_keys:Gt(r.primary_keys),views:Gt(r.views),triggers:Gt(r.triggers),check_constraints:[],unique_constraints:Gt(r.unique_constraints),comments:[],custom_types:[],database_name:r.database_name??"sqlite",version:r.version??""}}function bC(t,e){if(!t||!e.ref_column)return;let n=i=>i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`CONSTRAINT\\s+("?)(\\w+)\\1\\s+FOREIGN\\s+KEY\\s*\\(\\s*"?${n(e.column)}"?\\s*\\)\\s+REFERENCES\\s+"?${n(e.ref_table)}"?\\s*\\(\\s*"?${n(e.ref_column)}"?\\s*\\)`,"i");return t.match(r)?.[2]}function vy(t){return t.startsWith("fk_")&&!t.endsWith("_fkey")}function $u(t){return `${t.schema}.${t.table}.${t.foreign_key_name}.${t.ref_schema??""}.${t.ref_table}`}function wC(t){let e=new Map;for(let r of t){if(!vy(r.foreign_key_name))continue;let s=e.get($u(r));s?s.push(r):e.set($u(r),[r]);}let n=new Map;for(let[r,s]of e)s.length<2||n.set(r,`${s[0].table}_${s.map(i=>i.column).join("_")}_fkey`);return n.size===0?t:t.map(r=>{let s=n.get($u(r));return s?{...r,foreign_key_name:s}:r})}function Ay(t){if(!t.tables?.length||!t.foreign_keys?.length)return t;let e=new Map(t.tables.map(r=>[r.name,r.sql])),n=t.foreign_keys.map(r=>{if(r.foreign_key_name?.endsWith("_fkey")||r.foreign_key_name&&!vy(r.foreign_key_name))return r;let s=e.get(r.table),i=bC(s,r);return i?{...r,foreign_key_name:i}:r});return {...t,foreign_keys:wC(n)}}function Iu(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')||e.startsWith("`")&&e.endsWith("`")||e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function SC(t){let e=[],n="",r=0,s=null;for(let i=0;i<t.length;i++){let o=t[i];if(s){n+=o,o===s&&(s=null);continue}if(o==='"'||o==="`"||o==="'"){s=o,n+=o;continue}if(o==="("?r++:o===")"&&r>0&&r--,o===","&&r===0){e.push(n.trim()),n="";continue}n+=o;}return n.trim()&&e.push(n.trim()),e}function _C(t){let e=t.match(/^(.*?)\s+as\s+(.+)$/i),n=e?e[1].trim():t.trim(),r=e?e[2].trim():void 0;if(!r){let o=t.match(/^(.+?)\s+((?:"[^"]+"|`[^`]+`|\[[^\]]+\]|\w+))$/);o&&!/[()]/.test(o[1])&&(n=o[1].trim(),r=o[2].trim());}let s=n.split(".").map(Iu);if(s.length>2)return null;let i=s.at(-1);return !i||!/^[A-Za-z_][\w$]*$/.test(i)?null:{baseColumn:i,viewColumn:r?Iu(r):i}}function Oy(t){return !!(t&&/[A-Za-z0-9_$]/.test(t))}function EC(t){let e=/\bselect\b/i.exec(t);if(!e)return null;let n=0,r=null;for(let s=e.index+e[0].length;s<t.length;s++){let i=t[s];if(r){i===r&&(r=null);continue}if(i==='"'||i==="`"||i==="'"){r=i;continue}if(i==="("){n++;continue}if(i===")"&&n>0){n--;continue}if(n===0&&t.slice(s,s+4).toLowerCase()==="from"&&!Oy(t[s-1])&&!Oy(t[s+4]))return {selectList:t.slice(e.index+e[0].length,s).trim(),fromRest:t.slice(s+4).trim()}}return null}function xC(t){let e=0,n=[];for(;e<t.length;){for(;/\s/.test(t[e]??"");)e++;let r=t[e],s="";if(r==='"'||r==="`"){let a=t.indexOf(r,e+1);if(a===-1)return null;s=t.slice(e,a+1),e=a+1;}else if(r==="["){let a=t.indexOf("]",e+1);if(a===-1)return null;s=t.slice(e,a+1),e=a+1;}else {let a=/^[A-Za-z_][\w$]*/.exec(t.slice(e));if(!a)return null;s=a[0],e+=s.length;}n.push(s);let i=t.slice(e),o=/^\s*\./.exec(i);if(!o)break;e+=o[0].length;}return n.length===0?null:{raw:n.join("."),rest:t.slice(e).trim()}}function Py(t,e,n){let r=t.get(e)??[];r.includes(n)||r.push(n),t.set(e,r);}function TC(t,e){if(!t)return null;let n=EC(t);if(!n)return null;let r=xC(n.fromRest);if(!r)return null;let{raw:s,rest:i}=r;if(/\b(join|union|intersect|except)\b/i.test(i))return null;let o=s.split(".").map(Iu).at(-1);if(!o)return null;let a=new Map,l=e.get(o)??new Set;for(let c of SC(n.selectList)){let f=c.trim();if(f==="*"||f.endsWith(".*")){for(let d of l)Py(a,d,d);continue}let u=_C(c);u&&Py(a,u.baseColumn,u.viewColumn);}return a.size===0?null:{baseTable:o,columns:a}}function RC(t,e){let n=new Map;for(let[r,s]of e){let i=[];for(let o of s){let a=t.get(o);if(a)for(let l of a)i.includes(l)||i.push(l);}i.length>0&&n.set(r,i);}return n}function CC(t){let e=new Map,n=new Map;for(let a of t.columns??[]){let l=n.get(a.table)??new Set;l.add(a.name),n.set(a.table,l);}let r=(a,l)=>{let c=e.get(a)??[];c.some(f=>f.name===l.name&&f.schema===l.schema)||c.push(l),e.set(a,c);};for(let a of t.tables??[]){if(a.type!=="table")continue;let l=n.get(a.name);l&&r(a.name,{name:a.name,schema:a.schema,columnByBaseColumn:new Map([...l].map(c=>[c,[c]]))});}let s=new Map;for(let a of t.views??[]){let l=TC(a.sql,n);if(!l)continue;let c=n.get(a.name);if(!c)continue;let f=new Map;for(let[d,p]of l.columns){let g=p.filter(m=>c.has(m));g.length>0&&f.set(d,g);}if(f.size===0)continue;let u={name:a.name,schema:a.schema,columnByBaseColumn:f,fromRelation:l.baseTable};s.set(a.name,u);}let i=16;function o(a,l,c){if(l>i)return null;let f=a.fromRelation;if(e.has(f))return {physicalBase:f,columnByBaseColumn:a.columnByBaseColumn};let u=s.get(f);if(!u||c.has(f))return null;c.add(f);let d=o(u,l+1,c);if(c.delete(f),!d)return null;let p=RC(a.columnByBaseColumn,d.columnByBaseColumn);return p.size===0?null:{physicalBase:d.physicalBase,columnByBaseColumn:p}}for(let a of s.values()){let l=o(a,0,new Set([a.name]));l&&r(l.physicalBase,{name:a.name,schema:a.schema,columnByBaseColumn:l.columnByBaseColumn});}return e}function $y(t){return `${t.foreign_key_group??""}:${t.table}.${t.column}->${t.ref_table}.${t.ref_column}`}function kC(t){let e=new Map;for(let n of t){let r=`${n.schema}.${n.table}.${n.foreign_key_name}.${n.ref_schema??""}.${n.ref_table}`,s=e.get(r);s?s.push(n):e.set(r,[n]);}return [...e.values()]}function vC(t){let e=[[]];for(let n of t){let r=[];for(let s of e)for(let i of n)r.push([...s,i]);e=r;}return e}function AC(t,e,n,r){let s=r.map(o=>o.childColumn).join(","),i=r.map(o=>o.parentColumn).join(",");return `${n}:${t.name}(${s})->${e.name}(${i})`}function Iy(t){if(!t.foreign_keys?.length||!t.views?.length)return t;let e=CC(t),n=new Set(t.foreign_keys.map($y)),r=[];for(let s of kC(t.foreign_keys)){let i=s[0],o=e.get(i.table)??[],a=e.get(i.ref_table)??[];for(let l of o)for(let c of a){if(l.schema!==c.schema)continue;let f=[];for(let u of s){let d=l.columnByBaseColumn.get(u.column)??[],p=c.columnByBaseColumn.get(u.ref_column)??[],g=d.flatMap(m=>p.map(h=>({fk:u,childColumn:m,parentColumn:h})));if(g.length===0){f.length=0;break}f.push(g);}for(let u of vC(f)){let p=l.name===i.table&&c.name===i.ref_table&&u.every(g=>g.childColumn===g.fk.column&&g.parentColumn===g.fk.ref_column)?void 0:AC(l,c,i.foreign_key_name,u);for(let g of u){let m={...g.fk,table:l.name,column:g.childColumn,schema:l.schema,ref_table:c.name,ref_column:g.parentColumn,ref_schema:c.schema,foreign_key_group:p},h=$y(m);n.has(h)||(n.add(h),r.push(m));}}}}return r.length?{...t,foreign_keys:[...t.foreign_keys,...r]}:t}var jC=new Set(["AlterTableNode","CreateIndexNode","CreateSchemaNode","CreateTableNode","CreateTypeNode","CreateViewNode","RefreshMaterializedViewNode","DeleteQueryNode","DropIndexNode","DropSchemaNode","DropTableNode","DropTypeNode","DropViewNode","InsertQueryNode","RawNode","SelectQueryNode","UpdateQueryNode","MergeQueryNode"]),Nu=class extends OperationNodeTransformer{constructor(n){super();this.config=n;}#t=new Set;#e=new Set;transformNodeImpl(n,r){if(!jC.has(n.kind))return super.transformNodeImpl(n,r);let s=this.#s(n);for(let o of s)this.#e.add(o);let i=this.#n(n);for(let o of i)this.#t.add(o);try{return super.transformNodeImpl(n,r)}finally{for(let o of i)this.#t.delete(o);for(let o of s)this.#e.delete(o);}}transformSchemableIdentifier(n,r){let s=n.identifier.name,i=n.schema?.name,o=!i&&this.config.appendDefaultSchema&&this.config.defaultSchema&&!this.#e.has(s)&&this.#t.has(s),a=i??(o?this.config.defaultSchema:void 0);if(!a)return {kind:"SchemableIdentifierNode",schema:void 0,identifier:{kind:"IdentifierNode",name:s}};let l=this.config.approach==="snake_case"?"__":".";return {kind:"SchemableIdentifierNode",schema:void 0,identifier:{kind:"IdentifierNode",name:`${a}${l}${s}`}}}#n(n){let r=new Set;if(n?.name&&SchemableIdentifierNode.is(n.name)&&this.#r(n.name,r),n?.from?.froms)for(let s of n.from.froms)this.#i(s,r);if(n?.into&&this.#i(n.into,r),n?.table&&this.#i(n.table,r),n?.joins)for(let s of n.joins)this.#i(s.table,r);return n?.using&&(JoinNode.is(n.using)?this.#i(n.using.table,r):this.#i(n.using,r)),r}#i(n,r){if(TableNode.is(n)){this.#r(n.table,r);return}if(AliasNode.is(n)&&TableNode.is(n.node)){this.#r(n.node.table,r);return}if(ListNode.is(n)){for(let s of n.items)this.#i(s,r);return}if(UsingNode.is(n))for(let s of n.tables)this.#i(s,r);}#r(n,r){let s=n.identifier.name;this.#e.has(s)||r.add(s);}#s(n){let r=new Set;if(n?.with?.expressions)for(let s of n.with.expressions){let i=s?.name?.table?.table?.identifier?.name;i&&r.add(i);}return r}},Go=class{#t;constructor(e){this.#t=new Nu(e);}transformQuery(e){return this.#t.transformNode(e.node)}async transformResult(e){return e.result}};Js();Du();ju();function BC(t,e){return t==="migrations"||t==="supabase_migrations.schema_migrations"||t==="supabase_migrations.seed_files"||e==="sqlite"&&t==="seed_files"}function jy(t,e){let n=r=>BC(r,e);return {...t,tables:t.tables.filter(r=>!n(r.name)),columns:t.columns.filter(r=>!n(r.table)),indexes:t.indexes.filter(r=>!n(r.table)),foreign_keys:t.foreign_keys.filter(r=>!n(r.table)),primary_keys:t.primary_keys.filter(r=>!n(r.table))}}function fr(t,e,n){return n.includes(t)?true:n.some(r=>e.startsWith(`${r}.`)||e.startsWith(`${r}__`))}function Ly(t,e){let n=t.tables.filter(i=>fr(i.schema,i.name,e)),r=new Set(n.map(i=>i.name)),s=i=>i.filter(o=>r.has(o.table)||fr(o.schema,o.table,e));return {...t,tables:n,columns:s(t.columns),indexes:s(t.indexes),foreign_keys:s(t.foreign_keys),primary_keys:s(t.primary_keys),views:t.views.filter(i=>fr(i.schema,i.name,e)),check_constraints:s(t.check_constraints),unique_constraints:s(t.unique_constraints),comments:s(t.comments),custom_types:t.custom_types.filter(i=>fr(i.schema,i.type,e)),triggers:t.triggers.filter(i=>fr(i.schema,i.table,e)),functions:t.functions?.filter(i=>e.includes(i.schema)),partitions:t.partitions?.filter(i=>fr(i.schema,i.name,e))}}var Vo=class{constructor(e,n,r={}){this.conn=e;this.desiredSchema=n;this.options=r;this.differ=new cr,this.planner=new ur;}differ;planner;translationResult;async getDesiredSchema(){let e=await this.conn.translateDdl(this.desiredSchema);return this.translationResult=e,await this.options.onTranslation?.(e),e.ddl}async diff(e){let n=await this.conn.introspect({postprocess:false}),r=await this.getDesiredSchema();if(!r||r.trim().length===0)return {current:n,desired:n,diff:{tables:[],columns:[],indexes:[],foreign_keys:[],has_changes:false},plan:{steps:[],warnings:[],unsafe:false}};let{createConnection:s}=await import('@supabase/lite/sqlite'),i=await s({url:":memory:"});try{await i.exec(r);let o=await i.introspect({postprocess:!1}),a=this.conn.config.ddlDialect,[l,c]=e?.schemas?[Ly(n,e.schemas),Ly(o,e.schemas)]:[jy(n,a),jy(o,a)],f=this.differ.diff(l,c),u=this.planner.plan(f,l,c);return {current:n,desired:o,diff:f,plan:u}}finally{await i.close();}}safeSortPlanSteps(e){return invariant(Array.isArray(e),"steps must be an array"),e}async migratePlan(e,n){if(e.steps.length===0)return;if(e.unsafe&&!n?.force)throw new DataLossError(e.warnings??[]);let r=this.safeSortPlanSteps(e.steps).filter(s=>![PlanStepType.DISABLE_FOREIGN_KEYS,PlanStepType.BEGIN_TRANSACTION,PlanStepType.COMMIT_TRANSACTION,PlanStepType.ENABLE_FOREIGN_KEYS].includes(s.type));await this.conn.transaction(r.map(s=>s.sql),{intent:"migration"});}async migrate(e){let n=await this.diff({schemas:e?.schemas});return await this.migratePlan(n.plan,e),n}};Vr();var Uy=/^\{\{(.+)\}\}$/;function My(t){return typeof t=="string"&&Uy.test(t)}function qC(t){return Uy.exec(t)[1]}var Fy=Symbol("unresolved");function By(t,e){let n=qC(t),r=qt(e,n,Fy);if(r===Fy)throw new Error(`Unresolved variable: {{${n}}}`);return r}function vt(t,e){let n={};for(let[r,s]of Object.entries(t)){if(r==="$or"||r==="$and"){n[r]=s.map(i=>vt(i,e));continue}if(r==="$not"){n[r]=vt(s,e);continue}if(r==="$always"){n[r]=s;continue}if(r==="$exists"){let i=s;n[r]={...i,where:i?.where?vt(i.where,e):i?.where};continue}if(My(r)){let i=By(r,e),a=WC(i,s);n.$always=a;continue}if(s!=null&&typeof s=="object"&&!Array.isArray(s)){n[r]=qy(s,e);continue}n[r]=s;}return n}function qy(t,e){let n={};for(let[r,s]of Object.entries(t))r==="$not"&&s!=null&&typeof s=="object"?n[r]=qy(s,e):HC(s)?n[r]={...s,where:s?.where?vt(s?.where,e):void 0}:My(s)?n[r]=By(s,e):n[r]=s;return n}function HC(t){return t!=null&&typeof t=="object"&&t.type==="query"}function WC(t,e){for(let[n,r]of Object.entries(e))switch(n){case "$eq":if(t!==r)return false;break;case "$neq":if(t===r)return false;break;case "$in":if(!Array.isArray(r)||!r.includes(t))return false;break;case "$notIn":if(Array.isArray(r)&&r.includes(t))return false;break;default:throw new Error(`Cannot statically evaluate operator ${n} on placeholder key`)}return true}Vr();var Gs=class{constructor(e,n,r){this.tables=e;this.policies=n;this.defaultSchema=r;}enforce(e,n){let r=e.from;if(!r||!this.isRlsEnabled(r,e.schema))return e;let s=KC(e.type);if(!s)return e;let i=qt(n,"auth.role")??"anon";if(i==="service_role")return e;let{permissive:o,restrictive:a}=this.resolvePolicies(r,e.schema,s,i);switch(s){case "SELECT":case "DELETE":{let l=this.combineUsing(o,a,n);return {...e,where:Hy(e.where,l)}}case "UPDATE":{let l=this.combineUsing(o,a,n),c={...e,where:Hy(e.where,l)};if(l.$always===false)return c;let f=this.combineWithCheck(o,a,n,s);if(e.values&&Object.keys(f).length>0){let u=new Set(Object.keys(e.values));this.validateWithCheck(f,e.values,o,a,u);}return c}case "INSERT":{let l=this.combineWithCheck(o,a,n,s);if(e.values){let c=Array.isArray(e.values)?e.values:[e.values];for(let f of c)this.validateWithCheck(l,f,o,a);}return e}default:return e}}isRlsEnabled(e,n){return this.tables.has(e)}resolvePolicies(e,n,r,s){let i=this.policies.filter(o=>o.data.table===e&&this.schemasMatch(o.data.schema,n)&&o.appliesTo(r)&&o.appliesToRole(s));return {permissive:i.filter(o=>o.data.permissive),restrictive:i.filter(o=>!o.data.permissive)}}schemasMatch(e,n){let r=e||this.defaultSchema,s=n||this.defaultSchema;return r===s}combineUsing(e,n,r){if(e.length===0)return {$always:false};let s=e.map(o=>o.data.using).filter(o=>o!=null&&Object.keys(o).length>0).map(o=>vt(o,r)),i;s.length===0?i={}:s.length===1?i=s[0]:i={$or:s};for(let o of n)if(o.data.using&&Object.keys(o.data.using).length>0){let a=vt(o.data.using,r);i=Object.keys(i).length===0?a:{$and:[i,a]};}return i}combineWithCheck(e,n,r,s){if(e.length===0)return {$always:false};let i=e.map(a=>a.data.withCheck??(s==="UPDATE"?a.data.using:void 0)).filter(a=>a!=null&&Object.keys(a).length>0).map(a=>vt(a,r)),o;i.length===0?o={}:i.length===1?o=i[0]:o={$or:i};for(let a of n){let l=a.data.withCheck??(s==="UPDATE"?a.data.using:void 0);if(l&&Object.keys(l).length>0){let c=vt(l,r);o=Object.keys(o).length===0?c:{$and:[o,c]};}}return o}validateWithCheck(e,n,r,s,i){if(Object.keys(e).length===0)return;if(!Qo(e,n,i)){let a=r[0]??s[0];throw a?new Wn(a):new Error("RLS policy violation")}}};function KC(t){switch(t){case "query":return "SELECT";case "insert":case "upsert":case "put":return "INSERT";case "update":return "UPDATE";case "delete":return "DELETE";default:return}}function Hy(t,e){return !t||Object.keys(t).length===0?e:Object.keys(e).length===0?t:{$and:[t,e]}}function Qo(t,e,n){for(let[r,s]of Object.entries(t)){if(r==="$always"){if(s===false)return false;continue}if(r==="$and"){if(!s.every(l=>Qo(l,e,n)))return false;continue}if(r==="$or"){if(!s.some(l=>Qo(l,e,n)))return false;continue}if(r==="$not"){if(Qo(s,e,n))return false;continue}if(n&&!n.has(r))continue;let i=s,o=e[r];for(let[a,l]of Object.entries(i))if(!JC(o,a,l))return false}return true}function JC(t,e,n){switch(e){case "$eq":return t===n;case "$neq":return t!==n;case "$gt":return t>n;case "$gte":return t>=n;case "$lt":return t<n;case "$lte":return t<=n;case "$in":return Array.isArray(n)&&n.includes(t);case "$notIn":return !Array.isArray(n)||!n.includes(t);case "$is":return t===n;case "$isNot":return t!==n;default:throw new Error(`Cannot evaluate operator "${e}" client-side for WITH CHECK`)}}var Xo=class{transformQuery(e){return e.node}transformResult(e){return e.result.rows?Promise.resolve({...e.result,rows:e.result.rows.map(n=>{let r={};for(let s in n){let i=n[s];if(typeof i=="string"&&(i[0]==="{"||i[0]==="["))try{r[s]=JSON.parse(i);}catch{r[s]=i;}else r[s]=i;}return r})}):Promise.resolve(e.result)}};function Wy(t){let e={};for(let n in t){let r=t[n];if(typeof r=="string"&&(r[0]==="["||r[0]==="{"))try{e[n]=JSON.parse(r);}catch{e[n]=r;}else e[n]=r;}return e}ec();oo();function GC(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/--.*$/gm,"")}function zC(t){let e=t.trim();return e.startsWith('"')?e.replace(/^"(.*)"$/,"$1"):e.toLowerCase()}function Yo(t){let e=t.split(".");return zC(e[e.length-1]??t)}var Uu='(?:"[^"]+"|[A-Za-z_][\\w$]*)',Lu=`${Uu}(?:\\s*\\.\\s*${Uu})?`,Fu=new RegExp([`\\bALTER\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?(?:ONLY\\s+)?(${Lu})\\s+(?:(ENABLE|DISABLE)\\s+ROW\\s+LEVEL\\s+SECURITY\\b|RENAME\\s+TO\\s+(${Uu}))`,`\\bDROP\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?(${Lu}(?:\\s*,\\s*${Lu})*)`].join("|"),"gi");function Ky(t){let e=[...t].sort((i,o)=>i.version.localeCompare(o.version)),n=GC(e.flatMap(i=>i.statements??[]).join(`
632
+ `)),r=new Set;Fu.lastIndex=0;let s=Fu.exec(n);for(;s!==null;){let[,i,o,a,l]=s;if(i&&o){let c=Yo(i);o.toUpperCase()==="ENABLE"?r.add(c):r.delete(c);}else if(i&&a)r.delete(Yo(i))&&r.add(Yo(a));else if(l)for(let c of l.split(","))r.delete(Yo(c));s=Fu.exec(n);}return r}var Qs=class t extends Connection{dialect="sqlite";#t=false;#e;deserializeRow(e){return this.config.ddlDialect==="postgres"?Wy(e):e}constructor(e={}){let n=e.translation?.deparse!=null;super({...e,translation:{...e.translation,schemas:{appendDefaultSchema:false,approach:"quote",defaultSchema:"public",...e.translation?.schemas},deparse:t.parseDeparseInfo(e.translation?.deparse)},introspection:{name:"sqlite",...e.introspection,exclude_tables:Array.from(new Set([...e.introspection?.exclude_tables??[],"sqlite_%","supabase_migrations.%","migrations",...e.ddlDialect==="sqlite"?["seed_files"]:[]]))}}),this.#t=n;}static parseDeparseInfo(e,n){try{if(typeof e!="object"||e===null)return {};let r=e?.rls?.tables instanceof Set?e.rls.tables:new Set(e.rls?.tables??[]),s=(e?.rls?.policies??[]).map(f=>new Ge(JSON.parse(JSON.stringify(f)))),i=e?.vars instanceof Map?e.vars:new Map(Object.entries(e.vars??{})),o=e?.enums instanceof Map?e.enums:new Map(Object.entries(e.enums??{})),a;if(e?.schema instanceof Map)a=e.schema;else if(e?.schema&&typeof e.schema=="object"){a=new Map;for(let[f,u]of Object.entries(e.schema)){let d;for(let{context:p,extra:g}of u??[]){d??=new at(p.table,p.schema);let m=o.get(p.pgTypeName.toLowerCase());d.set(p.column,We({...p,defaultFn:null},{...g,...m?{enumValues:m}:{}}));}d&&a.set(f,d);}}let l=e?.tableConstraints??void 0,c=e?.comments??void 0;return {rls:{tables:r,policies:s},vars:i,enums:o,...a?{schema:a}:{},...l?{tableConstraints:l}:{},...c?{comments:c}:{}}}catch(r){if(n?.strict)throw r;return console.log("error parsing deparse info",r),{}}}static serializeDeparseInfo(e){let n=e?.rls??{tables:new Set,policies:[]},r=e?.vars??new Map,s=e?.enums??new Map,i={};for(let[l,c]of e?.schema??new Map)i[l]=c.all().map(f=>{let{defaultFn:u,...d}=f.context;return {context:d,extra:f.factoryExtra}});let o=e?.tableConstraints??[],a=e?.comments??[];return JSON.parse(Np({rls:{tables:n.tables,policies:n.policies},vars:r,enums:s,schema:i,tableConstraints:o,comments:a}))}updateDeparseInfo(e){this.config.translation={...this.config.translation,deparse:e},this.#t=true;}withSqlitePlugins(e=[]){let n=[];return this.config.ddlDialect==="sqlite"&&n.push(new Xo),n.push(new Go(Pl({appendDefaultSchema:false,approach:"quote",defaultSchema:"public"},{...this.config.translation?.schemas}))),[...n,...e]}async translateDdl(e){if(e.trim().length===0)return {ddl:e};if(this.config.ddlDialect==="sqlite")return {ddl:e};let n=this.config.translation?.schemas?.defaultSchema&&this.config.translation?.schemas?.appendDefaultSchema?this.config.translation?.schemas?.defaultSchema:false,r=await this.introspect({postprocess:false}).catch(()=>{}),{deparsePostgresDdl:s}=await Promise.resolve().then(()=>(Ju(),yb));return await s(e,{forceDefaultSchema:n,introspection:r,defaultSchema:this.config.translation?.schemas?.defaultSchema||void 0,schemaHandling:this.config.translation?.schemas?.approach==="snake_case"?"prefix":"default"})}async introspect(e){Fp(typeof e=="object"||e===void 0,"options must be an object");let n=e?.useCache??false;if(e?.postprocess!==false){let i=await this.readCachedIntrospection({useCache:n});if(i)return i}let r=await ky(this,this.config.introspection),s=this.config.translation?.schemas?.approach==="snake_case"?"__":".";if(this.config.ddlDialect==="postgres"&&e?.postprocess!==false){let i=this.config.translation?.schemas?.defaultSchema??this.config.translation?.schemas?.appendDefaultSchema?"public":void 0,o=(l="table")=>c=>{let f=c[l],u=c.schema??i;return !u&&i&&f.includes(s)&&([u,f]=f.split(s)),{...c,[l]:f,schema:u??i}},a=l=>{let c=o()(l),f=c.ref_table,u=c.ref_schema??i;return f?.includes(s)&&([u,f]=f.split(s)),{...c,ref_table:f,ref_schema:u??i}};r={...r,tables:r.tables.map(o("name")),columns:r.columns.map(o()),indexes:r.indexes.map(o()),primary_keys:r.primary_keys.map(o()),foreign_keys:r.foreign_keys.map(a),views:r.views.map(o("name")),check_constraints:r.check_constraints.map(o("table"))};}return r=Ay(r),r=Iy(r),this.config.ddlDialect==="postgres"&&e?.postprocess!==false&&(r=this.mergeDeparseMetadata(r)),r={...r,columns:r.columns.map(i=>!i.pg_type&&Le(i.type)?{...i,pg_type:i.type.toLowerCase().trim()}:i),ddl_dialect:this.config.ddlDialect??"postgres",schema_separator:s},e?.postprocess!==false&&await this.writeCachedIntrospection(r,{useDriver:n}),r}async transaction(e,n){n?.intent==="migration"&&await this.exec("PRAGMA foreign_keys=OFF;"),await this.exec("BEGIN");try{for(let r of e)try{await this.exec(r);}catch(s){throw console.error(`Failed to execute statement: ${r}`),s}await this.exec("COMMIT");}catch(r){throw await this.exec("ROLLBACK"),r}finally{n?.intent==="migration"&&(await this.exec("PRAGMA foreign_keys=ON;"),await this.clearSchemaCache());}}async close(){}mergeDeparseMetadata(e){let n=this.config.translation?.deparse;if(!n?.schema)return e;let r=e.columns.map(l=>({...l})),s=e.foreign_keys.map(l=>({...l})),i=[...e.unique_constraints??[]],o=[...e.check_constraints??[]];for(let[,l]of n.schema)for(let c of l.all()){let f=c.context,u=r.find(d=>d.table===f.table&&d.name===f.column);if(u&&(u.pg_type=f.pgTypeName,f.isGenerated!==void 0&&(u.is_generated=f.isGenerated)),f.fkRef?.constraintName){let d=s.find(p=>p.table===f.table&&p.column===f.column&&p.ref_table===f.fkRef.refTable&&p.ref_column===f.fkRef.refColumn);d&&(d.foreign_key_name=f.fkRef.constraintName);}f.uniqueConstraintName&&i.push({schema:f.schema,table:f.table,name:f.uniqueConstraintName,columns:[f.column]}),f.hasCheck&&o.push({schema:f.schema,table:f.table,expression:"",name:f.checkConstraintName,column:f.column});}for(let l of n.tableConstraints??[])if(l.kind==="unique")i.push({schema:l.schema,table:l.table,name:l.name??"",columns:l.columns});else if(l.kind==="check")o.push({schema:l.schema,table:l.table,expression:"",name:l.name});else if(l.kind==="foreign_key"&&l.name){let c=l.refTable;for(let f=0;f<l.columns.length;f++){let u=s.find(d=>d.table===l.table&&d.column===l.columns[f]&&d.ref_table===c&&d.ref_column===(l.refColumns?.[f]??""));u&&(u.foreign_key_name=l.name);}}let a=[...e.comments??[],...n.comments??[]];return {...e,columns:r,foreign_keys:s,unique_constraints:i,check_constraints:o,comments:a}}createMigrator(e){let n=[this.config.baseSchema,e].filter(Boolean).join(`
633
633
 
634
- `);return new Jo(this,n,{onTranslation:async r=>{if(this.config.translation){let s={enums:r.enums,rls:r.rls,schema:r.schema,vars:r.vars,tableConstraints:r.tableConstraints??[],comments:r.comments??[]};this.updateDeparseInfo(s);}}})}get maxBoundParameters(){return this.config.maxBoundParameters??100}assertParamLimit(e){let n=e?.length??0,r=this.maxBoundParameters;if(!(n<=r))throw Object.assign(new Error(`Query exceeds max bound parameters (${n} > ${r}). SQLite drivers vary in how many parameters they accept per statement; @supabase/lite enforces a conservative limit of ${r} for portability. Split the query (e.g. chunk large .in() filters or batch INSERTs) on the caller.`),{code:"54000"})}prepareBindParams(e){return this.assertParamLimit(e),this.normalizeBindParams(e)}normalizeBindParams(e){if(!e||e.length===0)return [];let n=[];for(let r=0;r<e.length;r++){let s=e[r];if(s===void 0)continue;if(s===null){n.push(s);continue}let i=typeof s;if(i==="boolean"){n.push(s?1:0);continue}if(i==="number"||i==="bigint"||i==="string"){n.push(s);continue}if(s instanceof Uint8Array||s instanceof ArrayBuffer||s instanceof Date){n.push(s);continue}throw new Error(`Cannot bind value at parameter ${r+1}: unsupported type ${Array.isArray(s)?"array":i}`)}return n}normalizeDbError(e){let n=e,r=n?.cause?.code??n?.code,s=n?.cause?.message??n?.message??String(e);if(r==="SQLITE_CONSTRAINT_NOTNULL")return Object.assign(new Error(s),{code:"23502",detail:s});if(r==="SQLITE_CONSTRAINT_UNIQUE"||r==="SQLITE_CONSTRAINT_PRIMARYKEY")return Object.assign(new Error(s),{code:"23505",detail:s});if(r==="SQLITE_CONSTRAINT_FOREIGNKEY")return Object.assign(new Error(s),{code:"23503",detail:s});if(typeof s=="string"){if(/too many SQL variables/i.test(s)){let a=this.maxBoundParameters;return Object.assign(new Error(`Query exceeds SQLite bound-parameter limit. @supabase/lite enforces a conservative limit of ${a} for portability across drivers. Split the query (e.g. chunk large .in() filters or batch INSERTs) on the caller.`),{code:"54000",detail:s})}let i=s.match(/no such table:\s*([A-Za-z0-9_.]+)/i);if(i){let a=i[1],l=a.lastIndexOf("."),c=l>=0?a.slice(0,l):void 0,f=l>=0?a.slice(l+1):a;return new RelationNotFoundError(c,f)}let o=s.match(/no such column:\s*([A-Za-z0-9_.]+)/i);if(o)return Object.assign(new Error(`column ${o[1]} does not exist`),{code:"42703",detail:s})}return e}async onPostgrestAST(e,n){if(this.config.ddlDialect==="sqlite")return e.schema=void 0,await this.applyRls(e,n);let r=this.config.translation?.schemas?.appendDefaultSchema,s=this.config.translation?.schemas?.defaultSchema;if(e.schema&&e.schema===s&&!r?e.schema=void 0:!e.schema&&s&&r&&(e.schema=s),!e.from)return e;let i=await this.introspect({useCache:true}),o=e.schema??(r&&s?s:""),a=e.from;if(!(i.tables.some(c=>c.name===a&&(c.schema??"")===o)||i.views.some(c=>c.name===a&&(c.schema??"")===o))){if(!(i.tables.some(f=>f.name===a&&["","public",s].includes(f.schema??""))||i.views.some(f=>f.name===a&&["","public",s].includes(f.schema??""))))throw new RelationNotFoundError(o,a);e.schema=void 0;}return await this.applyRls(e,n)}rlsEnabledFromHistory(){return this.config.ddlDialect!=="postgres"?Promise.resolve(new Set):(this.#e||(this.#e=Tu(this).then(e=>By(e)).catch(()=>new Set)),this.#e)}async applyRls(e,n){let r=this.config.translation?.deparse,s=this.config.translation?.schemas?.defaultSchema||void 0,i=n??{auth:{uid:null,role:"anon",jwt:null}};if(this.config.ddlDialect==="postgres"&&!this.#t){let l=await this.rlsEnabledFromHistory();if(l.size>0)return mb||(mb=true,console.error("[ RLS ] RLS metadata is missing for this database \u2014 denying requests to protected tables (fail closed). Run `lite migration up` or `lite db reset` to regenerate RLS metadata.")),e.from?new Gs(l,[],s).enforce(e,i):e}let o=r?.rls;return o?new Gs(o.tables,o.policies,s).enforce(e,i):e}},mb=false;var ia=class extends Qs{constructor(n){super({...n,introspection:{...n.introspection,version:"3.47.0"}});this.config=n;}dialect="sqlite";driver=null;kysely=null;fetch(n,r){let s=n instanceof URL?new URL(n.toString(),this.config.host):new URL(n,this.config.host);return fetch(s,{...r,headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${this.config.token}`,...r?.headers}})}async introspect(n){let r=new URLSearchParams({useCache:n?.useCache?"1":"0",postprocess:n?.postprocess?"1":"0"}),s=await this.fetch(`/v1/projects/${this.config.projectRef}/db/introspect?${r}`),i=await s.text();if(!s.ok)throw console.error(i),new Error(`Failed to get project introspect: ${s.status} ${s.statusText}`);try{let o=JSON.parse(i);if(!o)throw new Error("Failed to get project introspect");return o}catch(o){throw console.error(o),console.log(i),new Error(`Failed to parse introspect response: "${i}"`)}}async transaction(n,r){let s=await this.fetch(`/v1/projects/${this.config.projectRef}/db/transaction?intent=${r?.intent??"migration"}`,{method:"POST",body:JSON.stringify({statements:n})});if(!s.ok)throw new Error(`Failed to execute transaction: ${s.status} ${s.statusText}`)}async exec(n,...r){let s=await this.fetch(`/v1/projects/${this.config.projectRef}/db/exec`,{method:"POST",body:JSON.stringify({statement:n,parameters:r})}),i=await s.text();if(!s.ok)throw console.error(i),new Error(`Failed to execute statement: ${s.status} ${s.statusText}`);if(i.trim())try{return JSON.parse(i)}catch(o){throw console.error(o),new Error(`Failed to parse exec response: "${i}"`)}}async close(){}};function fk(t){return new ia(t)}Bu();Js();Yr();var dk=["anon","authenticated","service_role"];function pk(t){return t==="service_role"?"NOLOGIN BYPASSRLS":"NOLOGIN"}function mk(t){return t.size===0?"":`DO $$ BEGIN${[...t].map(n=>`
634
+ `);return new Vo(this,n,{onTranslation:async r=>{if(this.config.translation){let s={enums:r.enums,rls:r.rls,schema:r.schema,vars:r.vars,tableConstraints:r.tableConstraints??[],comments:r.comments??[]};this.updateDeparseInfo(s);}}})}get maxBoundParameters(){return this.config.maxBoundParameters??100}assertParamLimit(e){let n=e?.length??0,r=this.maxBoundParameters;if(!(n<=r))throw Object.assign(new Error(`Query exceeds max bound parameters (${n} > ${r}). SQLite drivers vary in how many parameters they accept per statement; @supabase/lite enforces a conservative limit of ${r} for portability. Split the query (e.g. chunk large .in() filters or batch INSERTs) on the caller.`),{code:"54000"})}prepareBindParams(e){return this.assertParamLimit(e),this.normalizeBindParams(e)}normalizeBindParams(e){if(!e||e.length===0)return [];let n=[];for(let r=0;r<e.length;r++){let s=e[r];if(s===void 0)continue;if(s===null){n.push(s);continue}let i=typeof s;if(i==="boolean"){n.push(s?1:0);continue}if(i==="number"||i==="bigint"||i==="string"){n.push(s);continue}if(s instanceof Uint8Array||s instanceof ArrayBuffer||s instanceof Date){n.push(s);continue}throw new Error(`Cannot bind value at parameter ${r+1}: unsupported type ${Array.isArray(s)?"array":i}`)}return n}normalizeDbError(e){let n=e,r=n?.cause?.code??n?.code,s=n?.cause?.message??n?.message??String(e);if(r==="SQLITE_CONSTRAINT_NOTNULL")return Object.assign(new Error(s),{code:"23502",detail:s});if(r==="SQLITE_CONSTRAINT_UNIQUE"||r==="SQLITE_CONSTRAINT_PRIMARYKEY")return Object.assign(new Error(s),{code:"23505",detail:s});if(r==="SQLITE_CONSTRAINT_FOREIGNKEY")return Object.assign(new Error(s),{code:"23503",detail:s});if(typeof s=="string"){if(/too many SQL variables/i.test(s)){let a=this.maxBoundParameters;return Object.assign(new Error(`Query exceeds SQLite bound-parameter limit. @supabase/lite enforces a conservative limit of ${a} for portability across drivers. Split the query (e.g. chunk large .in() filters or batch INSERTs) on the caller.`),{code:"54000",detail:s})}let i=s.match(/no such table:\s*([A-Za-z0-9_.]+)/i);if(i){let a=i[1],l=a.lastIndexOf("."),c=l>=0?a.slice(0,l):void 0,f=l>=0?a.slice(l+1):a;return new RelationNotFoundError(c,f)}let o=s.match(/no such column:\s*([A-Za-z0-9_.]+)/i);if(o)return Object.assign(new Error(`column ${o[1]} does not exist`),{code:"42703",detail:s})}return e}async onPostgrestAST(e,n){if(this.config.ddlDialect==="sqlite")return e.schema=void 0,await this.applyRls(e,n);let r=this.config.translation?.schemas?.appendDefaultSchema,s=this.config.translation?.schemas?.defaultSchema;if(e.schema&&e.schema===s&&!r?e.schema=void 0:!e.schema&&s&&r&&(e.schema=s),!e.from)return e;let i=await this.introspect({useCache:true}),o=e.schema??(r&&s?s:""),a=e.from;if(!(i.tables.some(c=>c.name===a&&(c.schema??"")===o)||i.views.some(c=>c.name===a&&(c.schema??"")===o))){if(!(i.tables.some(f=>f.name===a&&["","public",s].includes(f.schema??""))||i.views.some(f=>f.name===a&&["","public",s].includes(f.schema??""))))throw new RelationNotFoundError(o,a);e.schema=void 0;}return await this.applyRls(e,n)}rlsEnabledFromHistory(){return this.config.ddlDialect!=="postgres"?Promise.resolve(new Set):(this.#e||(this.#e=vu(this).then(e=>Ky(e)).catch(()=>new Set)),this.#e)}async applyRls(e,n){let r=this.config.translation?.deparse,s=this.config.translation?.schemas?.defaultSchema||void 0,i=n??{auth:{uid:null,role:"anon",jwt:null}};if(this.config.ddlDialect==="postgres"&&!this.#t){let l=await this.rlsEnabledFromHistory();if(l.size>0)return wb||(wb=true,console.error("[ RLS ] RLS metadata is missing for this database \u2014 denying requests to protected tables (fail closed). Run `lite migration up` or `lite db reset` to regenerate RLS metadata.")),e.from?new Gs(l,[],s).enforce(e,i):e}let o=r?.rls;return o?new Gs(o.tables,o.policies,s).enforce(e,i):e}},wb=false;var la=class extends Qs{constructor(n){super({...n,introspection:{...n.introspection,version:"3.47.0"}});this.config=n;}dialect="sqlite";driver=null;kysely=null;fetch(n,r){let s=n instanceof URL?new URL(n.toString(),this.config.host):new URL(n,this.config.host);return fetch(s,{...r,headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${this.config.token}`,...r?.headers}})}async introspect(n){let r=new URLSearchParams({useCache:n?.useCache?"1":"0",postprocess:n?.postprocess?"1":"0"}),s=await this.fetch(`/v1/projects/${this.config.projectRef}/db/introspect?${r}`),i=await s.text();if(!s.ok)throw console.error(i),new Error(`Failed to get project introspect: ${s.status} ${s.statusText}`);try{let o=JSON.parse(i);if(!o)throw new Error("Failed to get project introspect");return o}catch(o){throw console.error(o),console.log(i),new Error(`Failed to parse introspect response: "${i}"`)}}async transaction(n,r){let s=await this.fetch(`/v1/projects/${this.config.projectRef}/db/transaction?intent=${r?.intent??"migration"}`,{method:"POST",body:JSON.stringify({statements:n})});if(!s.ok)throw new Error(`Failed to execute transaction: ${s.status} ${s.statusText}`)}async exec(n,...r){let s=await this.fetch(`/v1/projects/${this.config.projectRef}/db/exec`,{method:"POST",body:JSON.stringify({statement:n,parameters:r})}),i=await s.text();if(!s.ok)throw console.error(i),new Error(`Failed to execute statement: ${s.status} ${s.statusText}`);if(i.trim())try{return JSON.parse(i)}catch(o){throw console.error(o),new Error(`Failed to parse exec response: "${i}"`)}}async close(){}};function bk(t){return new la(t)}Ju();Js();Xr();var wk=["anon","authenticated","service_role"];function Sk(t){return t==="service_role"?"NOLOGIN BYPASSRLS":"NOLOGIN"}function _k(t){return t.size===0?"":`DO $$ BEGIN${[...t].map(n=>`
635
635
  IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '${n}') THEN
636
- CREATE ROLE ${n} ${pk(n)};
636
+ CREATE ROLE ${n} ${Sk(n)};
637
637
  END IF;`).join("")}
638
638
  END $$;
639
- `}mk(new Set(dk));var hk=`
639
+ `}_k(new Set(wk));var Ek=`
640
640
  CREATE SCHEMA IF NOT EXISTS auth;
641
641
 
642
642
  CREATE OR REPLACE FUNCTION auth.uid() RETURNS UUID AS $$
@@ -657,11 +657,11 @@ CREATE OR REPLACE FUNCTION auth.jwt() RETURNS JSONB AS $$
657
657
  '{}'
658
658
  )::jsonb;
659
659
  $$ LANGUAGE SQL STABLE;
660
- `;var hb="supabase-self-hosted";function qu(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function gb(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return new Uint8Array(n)}async function gk(t,e=hb,n){let r=n??crypto.getRandomValues(new Uint8Array(17)),s=`sb_${t}_`,i=s+qu(r).slice(0,22),o=qu(await gb(`${e}|${i}`)).slice(0,8),a=`${i}_${o}`,l=await yb(a),c=a.slice(0,s.length+5);return {key:a,hash:l,prefix:c,type:t}}async function yb(t){return qu(await gb(t))}function yk(t){return t.startsWith("sb_publishable_")?"publishable":t.startsWith("sb_secret_")?"secret":null}try{let{emitWarning:t}=process;process.emitWarning=(e,...n)=>{if(!e.includes("SQLite is an experimental feature"))return t(e,...n)};}catch{}/*! Bundled license information:
660
+ `;var Sb="supabase-self-hosted";function Gu(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function _b(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return new Uint8Array(n)}async function xk(t,e=Sb,n){let r=n??crypto.getRandomValues(new Uint8Array(17)),s=`sb_${t}_`,i=s+Gu(r).slice(0,22),o=Gu(await _b(`${e}|${i}`)).slice(0,8),a=`${i}_${o}`,l=await Eb(a),c=a.slice(0,s.length+5);return {key:a,hash:l,prefix:c,type:t}}async function Eb(t){return Gu(await _b(t))}function Tk(t){return t.startsWith("sb_publishable_")?"publishable":t.startsWith("sb_secret_")?"secret":null}try{let{emitWarning:t}=process;process.emitWarning=(e,...n)=>{if(!e.includes("SQLite is an experimental feature"))return t(e,...n)};}catch{}/*! Bundled license information:
661
661
 
662
662
  aws4fetch/dist/aws4fetch.esm.mjs:
663
663
  (**
664
664
  * @license MIT <https://opensource.org/licenses/MIT>
665
665
  * @copyright Michael Hart 2024
666
666
  *)
667
- */export{Cu as App,Eo as AwsSesEmailDriver,ia as CloudConnection,bo as CloudflareKvCacheDriver,ec as Connection,Yn as ConsoleEmailDriver,_y as DataLossError,Es as InMemoryEmailDriver,Vn as InMemoryLruCacheDriver,Sy as InvalidPostgresToSQLiteTranslation,Ey as MigrationError,xs as NoopSmsDriver,ku as PlanStepType,Ge as Policy,wo as RedisCacheDriver,Bn as RelationNotFoundError,So as ResendEmailDriver,hb as SELF_HOSTED_PROJECT_REF,hk as SUPABASE_AUTH_HELPERS_SQL,xo as SendmailEmailDriver,Qn as SmtpEmailDriver,Qs as SqliteConnection,wy as UnableToCreateRuntimeConnection,yk as apiKeyType,rC as appliedVersions,Fc as assertSmtpSupportedRuntime,Lc as buildSmtpMail,To as buildSmtpTransportOptions,UO as checkPasswordStrength,Qr as cleanSql,fk as cloud,Gh as createAppDrivers,xu as ensureHistoryTable,o$ as ensureVar,e$ as filterSearchParams,jc as formatSendmailMessage,Jr as fuzzyMatch,gk as generateApiKey,Su as getAuthSchemaSql,Eu as getMigrationHistorySchemaSql,qt as getPath,l$ as getStatementsArray,ko as getStorageSchemaSql,oC as getVersion,yb as hashApiKey,Je as historyVariant,jp as invariant,HP as isBooleanLike,Al as isBun,FO as isEmail,kl as isEqual,ar as isExperimentalEnabled,Np as isNode,Pp as isObject,Op as isPlainObject,qP as isPrimitive,WP as isString,Dp as isWorkerd,$p as jsonStringify,ny as listEnabledExperimentals,Tu as listHistory,i$ as measureTime,vl as mergeObject,G_ as mergeObjectWith,Nl as normalizeDefault,to as normalizeSql,WS as normalizeString,$l as normalizeType,VP as objectDiff,YP as omit,ZP as params,u$ as parseBigInt,Ki as patternMatch,QP as pick,JP as pipe,GP as pipeEach,N as quote,LO as randomString,sC as recordVersion,iC as removeVersion,aC as removeVersionsGte,KO as replacePlaceholders,vs as requireAuth,Bc as resolveAuth,FR as setExperimental,J_ as setPath,HO as slugify,qO as snakeToPascalWithSpaces,Fp as splitSqlStatements,DR as studioRouteHandler,Il as tableStructuralItems,n$ as threw,r$ as threwAsync,ub as translatePostgresDdl,WO as truncate,s$ as trySync,MO as ucFirst,BO as ucFirstAll,d$ as uuid};
667
+ */export{Ou as App,Ro as AwsSesEmailDriver,la as CloudConnection,_o as CloudflareKvCacheDriver,rc as Connection,Xn as ConsoleEmailDriver,Ry as DataLossError,Es as InMemoryEmailDriver,Vn as InMemoryLruCacheDriver,Ty as InvalidPostgresToSQLiteTranslation,Cy as MigrationError,xs as NoopSmsDriver,Pu as PlanStepType,Ge as Policy,Eo as RedisCacheDriver,Bn as RelationNotFoundError,xo as ResendEmailDriver,Sb as SELF_HOSTED_PROJECT_REF,Ek as SUPABASE_AUTH_HELPERS_SQL,Co as SendmailEmailDriver,Qn as SmtpEmailDriver,Qs as SqliteConnection,xy as UnableToCreateRuntimeConnection,Tk as apiKeyType,uC as appliedVersions,Bc as assertSmtpSupportedRuntime,Mc as buildSmtpMail,ko as buildSmtpTransportOptions,JO as checkPasswordStrength,Qr as cleanSql,bk as cloud,Vh as createAppDrivers,ku as ensureHistoryTable,p$ as ensureVar,a$ as filterSearchParams,Uc as formatSendmailMessage,Jr as fuzzyMatch,xk as generateApiKey,Tu as getAuthSchemaSql,Cu as getMigrationHistorySchemaSql,qt as getPath,h$ as getStatementsArray,Oo as getStorageSchemaSql,pC as getVersion,Eb as hashApiKey,Je as historyVariant,Fp as invariant,QP as isBooleanLike,$l as isBun,KO as isEmail,Ol as isEqual,ar as isExperimentalEnabled,jp as isNode,Ip as isObject,$p as isPlainObject,VP as isPrimitive,XP as isString,Lp as isWorkerd,Np as jsonStringify,oy as listEnabledExperimentals,vu as listHistory,d$ as measureTime,Pl as mergeObject,Y_ as mergeObjectWith,Ll as normalizeDefault,so as normalizeSql,VS as normalizeString,Dl as normalizeType,n$ as objectDiff,s$ as omit,o$ as params,y$ as parseBigInt,zi as patternMatch,r$ as pick,ZP as pipe,e$ as pipeEach,N as quote,WO as randomString,fC as recordVersion,dC as removeVersion,mC as removeVersionsGte,YO as replacePlaceholders,vs as requireAuth,Wc as resolveAuth,KR as setExperimental,X_ as setPath,QO as slugify,VO as snakeToPascalWithSpaces,Mp as splitSqlStatements,qR as studioRouteHandler,jl as tableStructuralItems,c$ as threw,u$ as threwAsync,hb as translatePostgresDdl,XO as truncate,f$ as trySync,GO as ucFirst,zO as ucFirstAll,w$ as uuid};