@nvwa-app/sdk-core 0.4.5 → 0.4.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import * as _nvwa_app_postgrest_js from '@nvwa-app/postgrest-js';
2
- import { PostgrestClient } from '@nvwa-app/postgrest-js';
1
+ import * as _supabase_postgrest_js from '@supabase/postgrest-js';
2
+ import { PostgrestClient } from '@supabase/postgrest-js';
3
3
  import { User } from 'better-auth';
4
4
  import { createAuthClient } from 'better-auth/client';
5
5
 
@@ -210,7 +210,7 @@ declare class NvwaEdgeFunctions {
210
210
  }
211
211
 
212
212
  declare const ENTITIES_BASE_PATH = "/entities";
213
- declare const createPostgrestClient: (baseUrl: string, httpClient: NvwaHttpClient, handleUnauthorized: () => void) => PostgrestClient<any, {} | _nvwa_app_postgrest_js.PostgrestClientOptions, "public", any>;
213
+ declare const createPostgrestClient: (baseUrl: string, httpClient: NvwaHttpClient, handleUnauthorized: () => void) => PostgrestClient<any, {} | _supabase_postgrest_js.PostgrestClientOptions, "public", any>;
214
214
 
215
215
  interface INvwa {
216
216
  entities: PostgrestClient;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import * as _nvwa_app_postgrest_js from '@nvwa-app/postgrest-js';
2
- import { PostgrestClient } from '@nvwa-app/postgrest-js';
1
+ import * as _supabase_postgrest_js from '@supabase/postgrest-js';
2
+ import { PostgrestClient } from '@supabase/postgrest-js';
3
3
  import { User } from 'better-auth';
4
4
  import { createAuthClient } from 'better-auth/client';
5
5
 
@@ -210,7 +210,7 @@ declare class NvwaEdgeFunctions {
210
210
  }
211
211
 
212
212
  declare const ENTITIES_BASE_PATH = "/entities";
213
- declare const createPostgrestClient: (baseUrl: string, httpClient: NvwaHttpClient, handleUnauthorized: () => void) => PostgrestClient<any, {} | _nvwa_app_postgrest_js.PostgrestClientOptions, "public", any>;
213
+ declare const createPostgrestClient: (baseUrl: string, httpClient: NvwaHttpClient, handleUnauthorized: () => void) => PostgrestClient<any, {} | _supabase_postgrest_js.PostgrestClientOptions, "public", any>;
214
214
 
215
215
  interface INvwa {
216
216
  entities: PostgrestClient;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var Gt=Object.create;var ge=Object.defineProperty;var zt=Object.getOwnPropertyDescriptor;var Vt=Object.getOwnPropertyNames;var Kt=Object.getPrototypeOf,Jt=Object.prototype.hasOwnProperty;var Yt=(r,e)=>()=>(r&&(e=r(r=0)),e);var F=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Qt=(r,e)=>{for(var t in e)ge(r,t,{get:e[t],enumerable:!0})},st=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Vt(e))!Jt.call(r,n)&&n!==t&&ge(r,n,{get:()=>e[n],enumerable:!(s=zt(e,n))||s.enumerable});return r};var Xt=(r,e,t)=>(t=r!=null?Gt(Kt(r)):{},st(e||!r||!r.__esModule?ge(t,"default",{value:r,enumerable:!0}):t,r)),Zt=r=>st(ge({},"__esModule",{value:!0}),r);var a=Yt(()=>{"use strict"});var se=F(T=>{"use strict";a();Object.defineProperty(T,"__esModule",{value:!0});T.File=T.FormData=T.Blob=T.FetchResponse=T.URL=T.URLSearchParams=T.FetchHeaders=void 0;var te=class{constructor(e){if(this.map=new Map,e)for(let[t,s]of Object.entries(e))this.set(t,s)}get(e){var t;return(t=this.map.get(e))!==null&&t!==void 0?t:null}set(e,t){this.map.set(e,t)}has(e){return this.map.has(e)}append(e,t){let s=this.map.get(e);s?this.map.set(e,`${s}${t}`):this.map.set(e,t)}delete(e){this.map.delete(e)}forEach(e){this.map.forEach(e)}size(){return this.map.size}keys(){return this.map.keys()}values(){return this.map.values()}entries(){return this.map.entries()}headers(){return Object.fromEntries(this.map.entries())}[Symbol.iterator](){return this.map[Symbol.iterator]()}};T.FetchHeaders=te;var Se=class r{constructor(e){if(this.params=new Map,e){if(typeof e=="string")this.parseString(e);else if(e instanceof r)this.params=new Map(e.params);else if(Array.isArray(e))for(let[t,s]of e)this.append(t,s);else if(e&&typeof e=="object")for(let[t,s]of Object.entries(e))this.set(t,s)}}parseString(e){e.startsWith("?")&&(e=e.slice(1));let t=e.split("&");for(let s of t)if(s){let[n,o]=s.split("=");n&&this.append(decodeURIComponent(n),o?decodeURIComponent(o):"")}}append(e,t){let s=this.params.get(e)||[];s.push(t),this.params.set(e,s)}delete(e){this.params.delete(e)}get(e){let t=this.params.get(e);return t?t[0]:null}getAll(e){return this.params.get(e)||[]}has(e){return this.params.has(e)}set(e,t){this.params.set(e,[t])}sort(){let e=Array.from(this.params.entries()).sort(([t],[s])=>t.localeCompare(s));this.params=new Map(e)}toString(){let e=[];for(let[t,s]of this.params.entries())for(let n of s)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(n)}`);return e.join("&")}forEach(e){for(let[t,s]of this.params.entries())for(let n of s)e(n,t,this)}keys(){return this.params.keys()}values(){let e=[];for(let t of this.params.values())e.push(...t);return e[Symbol.iterator]()}entries(){let e=[];for(let[t,s]of this.params.entries())for(let n of s)e.push([t,n]);return e[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}};T.URLSearchParams=Se;var _e=class r{constructor(e,t){let s;if(e instanceof r)s=e.href;else if(t){let o=t instanceof r?t.href:t;s=this.resolve(o,e)}else s=e;let n=this.parseUrl(s);this.href=s,this.origin=`${n.protocol}//${n.host}`,this.protocol=n.protocol,this.username=n.username,this.password=n.password,this.host=n.host,this.hostname=n.hostname,this.port=n.port,this.pathname=n.pathname,this.search=n.search,this.searchParams=new Se(n.search),this.hash=n.hash}resolve(e,t){if(t.startsWith("http://")||t.startsWith("https://"))return t;if(t.startsWith("//"))return`${this.parseUrl(e).protocol}${t}`;if(t.startsWith("/")){let o=this.parseUrl(e);return`${o.protocol}//${o.host}${t}`}let s=this.parseUrl(e),n=s.pathname.endsWith("/")?s.pathname:s.pathname+"/";return`${s.protocol}//${s.host}${n}${t}`}parseUrl(e){let t=e.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!t)throw new TypeError("Invalid URL");let s=t[2]||"",n=t[4]||"",o=t[5]||"/",i=t[7]?`?${t[7]}`:"",c=t[9]?`#${t[9]}`:"";if(!s&&!n&&!o.startsWith("/")&&!o.includes("/")&&!o.includes("."))throw new TypeError("Invalid URL");let d=n.match(/^([^@]*)@(.+)$/),u="",l="",h=n;if(d){let I=d[1];h=d[2];let y=I.match(/^([^:]*):?(.*)$/);y&&(u=y[1]||"",l=y[2]||"")}let p=h.match(/^([^:]+):?(\d*)$/),R=p?p[1]:h,E=p&&p[2]?p[2]:"";return{protocol:s?`${s}:`:"",username:u,password:l,host:h,hostname:R,port:E,pathname:o,search:i,hash:c}}toString(){let e=this.searchParams.toString(),t=e?`?${e}`:"";return`${this.protocol}//${this.host}${this.pathname}${t}${this.hash}`}toJSON(){return this.toString()}};T.URL=_e;var Fe=class r{constructor(e,t){var s,n;this.status=(s=t?.status)!==null&&s!==void 0?s:200,this.statusText=(n=t?.statusText)!==null&&n!==void 0?n:"",this.headers=new te(t?.headers),this.ok=this.status>=200&&this.status<300,this.redirected=!1,this.url="",this.bodyUsed=!1,this.body=e||null}async arrayBuffer(){if(this.bodyUsed)throw new TypeError("Body has already been consumed");return this.bodyUsed=!0,this.body===null?new ArrayBuffer(0):new TextEncoder().encode(this.body).buffer}async blob(){if(this.bodyUsed)throw new TypeError("Body has already been consumed");return this.bodyUsed=!0,new re([this.body||""])}async formData(){if(this.bodyUsed)throw new TypeError("Body has already been consumed");return this.bodyUsed=!0,new Pe}async json(){if(this.bodyUsed)throw new TypeError("Body has already been consumed");return this.bodyUsed=!0,this.body===null?null:JSON.parse(this.body)}async text(){if(this.bodyUsed)throw new TypeError("Body has already been consumed");return this.bodyUsed=!0,this.body||""}clone(){if(this.bodyUsed)throw new TypeError("Body has already been consumed");return new r(this.body,{status:this.status,statusText:this.statusText,headers:this.headers.headers()})}static error(){let e=new r(null,{status:0,statusText:""});return Object.defineProperty(e,"type",{value:"error",writable:!1}),e}static redirect(e,t=302){let s=e instanceof _e?e.href:e,n=new r(null,{status:t,statusText:"Found"});return n.headers.set("Location",s),n}static json(e,t){let s=JSON.stringify(e),n=new te(t?.headers);return n.set("Content-Type","application/json"),new r(s,Object.assign(Object.assign({},t),{headers:n.headers()}))}};T.FetchResponse=Fe;var re=class r{constructor(e,t){this._content=e||[],this.type=t?.type||"";let s=0;for(let n of this._content)typeof n=="string"?s+=new TextEncoder().encode(n).length:n instanceof ArrayBuffer?s+=n.byteLength:n instanceof Uint8Array&&(s+=n.length);this.size=s}async text(){let e="";for(let t of this._content)typeof t=="string"?e+=t:t instanceof ArrayBuffer?e+=new TextDecoder().decode(t):t instanceof Uint8Array&&(e+=new TextDecoder().decode(t));return e}async arrayBuffer(){let e=await this.text();return new TextEncoder().encode(e).buffer}slice(e,t,s){return new r(this._content.slice(e,t),{type:s})}};T.Blob=re;var Pe=class{constructor(){this._entries=[]}append(e,t,s){this._entries.push([e,t])}delete(e){this._entries=this._entries.filter(([t])=>t!==e)}get(e){let t=this._entries.find(([s])=>s===e);return t?t[1]:null}getAll(e){return this._entries.filter(([t])=>t===e).map(([,t])=>t)}has(e){return this._entries.some(([t])=>t===e)}set(e,t,s){this.delete(e),this.append(e,t,s)}forEach(e){for(let[t,s]of this._entries)e(s,t,this)}keys(){return this._entries.map(([e])=>e)[Symbol.iterator]()}values(){return this._entries.map(([,e])=>e)[Symbol.iterator]()}entries(){return this._entries[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}};T.FormData=Pe;var He=class extends re{constructor(e,t,s){super(e,s),this.name=t,this.lastModified=s?.lastModified||Date.now()}};T.File=He});var Ge=F(We=>{"use strict";a();Object.defineProperty(We,"__esModule",{value:!0});var qe=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};We.default=qe});var Ve=F(ne=>{"use strict";a();var ss=ne&&ne.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ne,"__esModule",{value:!0});var ns=ss(Ge()),Ut=se(),ze=class{constructor(e){var t,s;this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=new Ut.FetchHeaders(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=(t=e.shouldThrowOnError)!==null&&t!==void 0?t:!1,this.signal=e.signal,this.isMaybeSingle=(s=e.isMaybeSingle)!==null&&s!==void 0?s:!1,e.fetch?this.fetch=e.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=new Ut.FetchHeaders(this.headers),this.headers.set(e,t),this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");let s=this.fetch,n=s(this.url.toString(),{method:this.method,headers:this.headers.headers(),body:JSON.stringify(this.body),signal:this.signal}).then(async o=>{var i,c,d,u;let l=null,h=null,p=null,R=o.status,E=o.statusText;if(o.ok){if(this.method!=="HEAD"){let _=await o.text();_===""||(this.headers.get("Accept")==="text/csv"||this.headers.get("Accept")&&(!((i=this.headers.get("Accept"))===null||i===void 0)&&i.includes("application/vnd.pgrst.plan+text"))?h=_:h=JSON.parse(_))}let y=(c=this.headers.get("Prefer"))===null||c===void 0?void 0:c.match(/count=(exact|planned|estimated)/),O=(d=o.headers.get("content-range"))===null||d===void 0?void 0:d.split("/");y&&O&&O.length>1&&(p=parseInt(O[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(h)&&(h.length>1?(l={code:"PGRST116",details:`Results contain ${h.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},h=null,p=null,R=406,E="Not Acceptable"):h.length===1?h=h[0]:h=null)}else{let y=await o.text();try{l=JSON.parse(y),Array.isArray(l)&&o.status===404&&(h=[],l=null,R=200,E="OK")}catch{o.status===404&&y===""?(R=204,E="No Content"):l={message:y}}if(l&&this.isMaybeSingle&&(!((u=l?.details)===null||u===void 0)&&u.includes("0 rows"))&&(l=null,R=200,E="OK"),l&&this.shouldThrowOnError)throw new ns.default(l)}return{error:l,data:h,count:p,status:R,statusText:E}});return this.shouldThrowOnError||(n=n.catch(o=>{var i,c,d;return{error:{message:`${(i=o?.name)!==null&&i!==void 0?i:"FetchError"}: ${o?.message}`,details:`${(c=o?.stack)!==null&&c!==void 0?c:""}`,hint:"",code:`${(d=o?.code)!==null&&d!==void 0?d:""}`},data:null,count:null,status:0,statusText:""}})),n.then(e,t)}returns(){return this}overrideTypes(){return this}};ne.default=ze});var Je=F(oe=>{"use strict";a();var os=oe&&oe.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(oe,"__esModule",{value:!0});var as=os(Ve()),Ke=class extends as.default{select(e){let t=!1,s=(e??"*").split("").map(n=>/\s/.test(n)&&!t?"":(n==='"'&&(t=!t),n)).join("");return this.url.searchParams.set("select",s),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:s,foreignTable:n,referencedTable:o=n}={}){let i=o?`${o}.order`:"order",c=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${c?`${c},`:""}${e}.${t?"asc":"desc"}${s===void 0?"":s?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:s=t}={}){let n=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(n,`${e}`),this}range(e,t,{foreignTable:s,referencedTable:n=s}={}){let o=typeof n>"u"?"offset":`${n}.offset`,i=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(o,`${e}`),this.url.searchParams.set(i,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.method==="GET"?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:e=!1,verbose:t=!1,settings:s=!1,buffers:n=!1,wal:o=!1,format:i="text"}={}){var c;let d=[e?"analyze":null,t?"verbose":null,s?"settings":null,n?"buffers":null,o?"wal":null].filter(Boolean).join("|"),u=(c=this.headers.get("Accept"))!==null&&c!==void 0?c:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${u}"; options=${d};`),i==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}};oe.default=Ke});var Ae=F(ae=>{"use strict";a();var is=ae&&ae.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ae,"__esModule",{value:!0});var ls=is(Je()),Ye=class extends ls.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let s=Array.from(new Set(t)).map(n=>typeof n=="string"&&new RegExp("[,()]").test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(e,`in.(${s})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:s,type:n}={}){let o="";n==="plain"?o="pl":n==="phrase"?o="ph":n==="websearch"&&(o="w");let i=s===void 0?"":`(${s})`;return this.url.searchParams.append(e,`${o}fts${i}.${t}`),this}match(e){return Object.entries(e).forEach(([t,s])=>{this.url.searchParams.append(t,`eq.${s}`)}),this}not(e,t,s){return this.url.searchParams.append(e,`not.${t}.${s}`),this}or(e,{foreignTable:t,referencedTable:s=t}={}){let n=s?`${s}.or`:"or";return this.url.searchParams.append(n,`(${e})`),this}filter(e,t,s){return this.url.searchParams.append(e,`${t}.${s}`),this}};ae.default=Ye});var Xe=F(le=>{"use strict";a();var cs=le&&le.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(le,"__esModule",{value:!0});var us=se(),ie=cs(Ae()),Qe=class{constructor(e,{headers:t={},schema:s,fetch:n}){this.url=e,this.headers=new us.FetchHeaders(t),this.schema=s,this.fetch=n}select(e,t){let{head:s=!1,count:n}=t??{},o=s?"HEAD":"GET",i=!1,c=(e??"*").split("").map(d=>/\s/.test(d)&&!i?"":(d==='"'&&(i=!i),d)).join("");return this.url.searchParams.set("select",c),n&&this.headers.append("Prefer",`count=${n}`),new ie.default({method:o,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch})}insert(e,{count:t,defaultToNull:s=!0}={}){var n;let o="POST";if(t&&this.headers.append("Prefer",`count=${t}`),s||this.headers.append("Prefer","missing=default"),Array.isArray(e)){let i=e.reduce((c,d)=>c.concat(Object.keys(d)),[]);if(i.length>0){let c=[...new Set(i)].map(d=>`"${d}"`);this.url.searchParams.set("columns",c.join(","))}}return new ie.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch})}upsert(e,{onConflict:t,ignoreDuplicates:s=!1,count:n,defaultToNull:o=!0}={}){var i;let c="POST";if(this.headers.append("Prefer",`resolution=${s?"ignore":"merge"}-duplicates`),t!==void 0&&this.url.searchParams.set("on_conflict",t),n&&this.headers.append("Prefer",`count=${n}`),o||this.headers.append("Prefer","missing=default"),Array.isArray(e)){let d=e.reduce((u,l)=>u.concat(Object.keys(l)),[]);if(d.length>0){let u=[...new Set(d)].map(l=>`"${l}"`);this.url.searchParams.set("columns",u.join(","))}}return new ie.default({method:c,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch})}update(e,{count:t}={}){var s;let n="PATCH";return t&&this.headers.append("Prefer",`count=${t}`),new ie.default({method:n,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch})}delete({count:e}={}){var t;let s="DELETE";return e&&this.headers.append("Prefer",`count=${e}`),new ie.default({method:s,url:this.url,headers:this.headers,schema:this.schema,fetch:(t=this.fetch)!==null&&t!==void 0?t:fetch})}};le.default=Qe});var xt=F(ue=>{"use strict";a();var It=ue&&ue.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ue,"__esModule",{value:!0});var ds=It(Xe()),hs=It(Ae()),ce=se(),Ze=class r{constructor(e,{headers:t={},schema:s,fetch:n}={}){this.url=e,this.headers=new ce.FetchHeaders(t),this.schemaName=s,this.fetch=n}from(e){let t=new ce.URL(`${this.url}/${e}`);return new ds.default(t,{headers:new ce.FetchHeaders(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new r(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:s=!1,get:n=!1,count:o}={}){var i;let c,d=new ce.URL(`${this.url}/rpc/${e}`),u;s||n?(c=s?"HEAD":"GET",Object.entries(t).filter(([h,p])=>p!==void 0).map(([h,p])=>[h,Array.isArray(p)?`{${p.join(",")}}`:`${p}`]).forEach(([h,p])=>{d.searchParams.append(h,p)})):(c="POST",u=t);let l=new ce.FetchHeaders(this.headers);return o&&l.set("Prefer",`count=${o}`),new hs.default({method:c,url:d,headers:l,schema:this.schemaName,body:u,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch})}};ue.default=Ze});var Mt=F(g=>{"use strict";a();var z=g&&g.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(g,"__esModule",{value:!0});g.File=g.FormData=g.Blob=g.FetchResponse=g.FetchHeaders=g.URLSearchParams=g.URL=g.PostgrestError=g.PostgrestBuilder=g.PostgrestTransformBuilder=g.PostgrestFilterBuilder=g.PostgrestQueryBuilder=g.PostgrestClient=void 0;var Ct=z(xt());g.PostgrestClient=Ct.default;var Nt=z(Xe());g.PostgrestQueryBuilder=Nt.default;var Lt=z(Ae());g.PostgrestFilterBuilder=Lt.default;var $t=z(Je());g.PostgrestTransformBuilder=$t.default;var Dt=z(Ve());g.PostgrestBuilder=Dt.default;var kt=z(Ge());g.PostgrestError=kt.default;var k=se();Object.defineProperty(g,"FetchHeaders",{enumerable:!0,get:function(){return k.FetchHeaders}});Object.defineProperty(g,"FetchResponse",{enumerable:!0,get:function(){return k.FetchResponse}});Object.defineProperty(g,"URL",{enumerable:!0,get:function(){return k.URL}});Object.defineProperty(g,"URLSearchParams",{enumerable:!0,get:function(){return k.URLSearchParams}});Object.defineProperty(g,"Blob",{enumerable:!0,get:function(){return k.Blob}});Object.defineProperty(g,"FormData",{enumerable:!0,get:function(){return k.FormData}});Object.defineProperty(g,"File",{enumerable:!0,get:function(){return k.File}});g.default={PostgrestClient:Ct.default,PostgrestQueryBuilder:Nt.default,PostgrestFilterBuilder:Lt.default,PostgrestTransformBuilder:$t.default,PostgrestBuilder:Dt.default,PostgrestError:kt.default,URLSearchParams:k.URLSearchParams,FetchHeaders:k.FetchHeaders,FetchResponse:k.FetchResponse}});var ys={};Qt(ys,{AUTH_BASE_PATH:()=>Pt,AbortController:()=>pe,AbortSignal:()=>K,ENTITIES_BASE_PATH:()=>Ft,FILE_STORAGE_BASE_PATH:()=>At,FetchResponse:()=>Me,GENERATE_UPLOAD_URL_PATH:()=>Ot,Headers:()=>N,LOGIN_TOKEN_KEY:()=>ee,LOGIN_USER_PROFILE_KEY:()=>Te,NvwaAuthClient:()=>De,NvwaEdgeFunctions:()=>ke,NvwaFileStorage:()=>je,NvwaHttpClient:()=>Be,Request:()=>he,Response:()=>fe,URL:()=>de,URLSearchParams:()=>V,createPostgrestClient:()=>ps,polyfill:()=>gs});module.exports=Zt(ys);a();a();a();a();a();a();var er=Object.defineProperty,tr=Object.defineProperties,rr=Object.getOwnPropertyDescriptors,nt=Object.getOwnPropertySymbols,sr=Object.prototype.hasOwnProperty,nr=Object.prototype.propertyIsEnumerable,ot=(r,e,t)=>e in r?er(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,x=(r,e)=>{for(var t in e||(e={}))sr.call(e,t)&&ot(r,t,e[t]);if(nt)for(var t of nt(e))nr.call(e,t)&&ot(r,t,e[t]);return r},L=(r,e)=>tr(r,rr(e)),or=class extends Error{constructor(r,e,t){super(e||r.toString(),{cause:t}),this.status=r,this.statusText=e,this.error=t}},ar=async(r,e)=>{var t,s,n,o,i,c;let d=e||{},u={onRequest:[e?.onRequest],onResponse:[e?.onResponse],onSuccess:[e?.onSuccess],onError:[e?.onError],onRetry:[e?.onRetry]};if(!e||!e?.plugins)return{url:r,options:d,hooks:u};for(let l of e?.plugins||[]){if(l.init){let h=await((t=l.init)==null?void 0:t.call(l,r.toString(),e));d=h.options||d,r=h.url}u.onRequest.push((s=l.hooks)==null?void 0:s.onRequest),u.onResponse.push((n=l.hooks)==null?void 0:n.onResponse),u.onSuccess.push((o=l.hooks)==null?void 0:o.onSuccess),u.onError.push((i=l.hooks)==null?void 0:i.onError),u.onRetry.push((c=l.hooks)==null?void 0:c.onRetry)}return{url:r,options:d,hooks:u}},at=class{constructor(r){this.options=r}shouldAttemptRetry(r,e){return this.options.shouldRetry?Promise.resolve(r<this.options.attempts&&this.options.shouldRetry(e)):Promise.resolve(r<this.options.attempts)}getDelay(){return this.options.delay}},ir=class{constructor(r){this.options=r}shouldAttemptRetry(r,e){return this.options.shouldRetry?Promise.resolve(r<this.options.attempts&&this.options.shouldRetry(e)):Promise.resolve(r<this.options.attempts)}getDelay(r){return Math.min(this.options.maxDelay,this.options.baseDelay*2**r)}};function lr(r){if(typeof r=="number")return new at({type:"linear",attempts:r,delay:1e3});switch(r.type){case"linear":return new at(r);case"exponential":return new ir(r);default:throw new Error("Invalid retry strategy")}}var cr=async r=>{let e={},t=async s=>typeof s=="function"?await s():s;if(r?.auth){if(r.auth.type==="Bearer"){let s=await t(r.auth.token);if(!s)return e;e.authorization=`Bearer ${s}`}else if(r.auth.type==="Basic"){let s=t(r.auth.username),n=t(r.auth.password);if(!s||!n)return e;e.authorization=`Basic ${btoa(`${s}:${n}`)}`}else if(r.auth.type==="Custom"){let s=t(r.auth.value);if(!s)return e;e.authorization=`${t(r.auth.prefix)} ${s}`}}return e},ur=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function dr(r){let e=r.headers.get("content-type"),t=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!e)return"json";let s=e.split(";").shift()||"";return ur.test(s)?"json":t.has(s)||s.startsWith("text/")?"text":"blob"}function hr(r){try{return JSON.parse(r),!0}catch{return!1}}function ct(r){if(r===void 0)return!1;let e=typeof r;return e==="string"||e==="number"||e==="boolean"||e===null?!0:e!=="object"?!1:Array.isArray(r)?!0:r.buffer?!1:r.constructor&&r.constructor.name==="Object"||typeof r.toJSON=="function"}function it(r){try{return JSON.parse(r)}catch{return r}}function lt(r){return typeof r=="function"}function fr(r){if(r?.customFetchImpl)return r.customFetchImpl;if(typeof globalThis<"u"&&lt(globalThis.fetch))return globalThis.fetch;if(typeof window<"u"&&lt(window.fetch))return window.fetch;throw new Error("No fetch implementation found")}async function pr(r){let e=new Headers(r?.headers),t=await cr(r);for(let[s,n]of Object.entries(t||{}))e.set(s,n);if(!e.has("content-type")){let s=mr(r?.body);s&&e.set("content-type",s)}return e}function mr(r){return ct(r)?"application/json":null}function gr(r){if(!r?.body)return null;let e=new Headers(r?.headers);if(ct(r.body)&&!e.has("content-type")){for(let[t,s]of Object.entries(r?.body))s instanceof Date&&(r.body[t]=s.toISOString());return JSON.stringify(r.body)}return r.body}function yr(r,e){var t;if(e?.method)return e.method.toUpperCase();if(r.startsWith("@")){let s=(t=r.split("@")[1])==null?void 0:t.split("/")[0];return dt.includes(s)?s.toUpperCase():e?.body?"POST":"GET"}return e?.body?"POST":"GET"}function br(r,e){let t;return!r?.signal&&r?.timeout&&(t=setTimeout(()=>e?.abort(),r?.timeout)),{abortTimeout:t,clearTimeout:()=>{t&&clearTimeout(t)}}}var Rr=class ut extends Error{constructor(e,t){super(t||JSON.stringify(e,null,2)),this.issues=e,Object.setPrototypeOf(this,ut.prototype)}};async function ye(r,e){let t=await r["~standard"].validate(e);if(t.issues)throw new Rr(t.issues);return t.value}var dt=["get","post","put","patch","delete"];var wr=r=>({id:"apply-schema",name:"Apply Schema",version:"1.0.0",async init(e,t){var s,n,o,i;let c=((n=(s=r.plugins)==null?void 0:s.find(d=>{var u;return(u=d.schema)!=null&&u.config?e.startsWith(d.schema.config.baseURL||"")||e.startsWith(d.schema.config.prefix||""):!1}))==null?void 0:n.schema)||r.schema;if(c){let d=e;(o=c.config)!=null&&o.prefix&&d.startsWith(c.config.prefix)&&(d=d.replace(c.config.prefix,""),c.config.baseURL&&(e=e.replace(c.config.prefix,c.config.baseURL))),(i=c.config)!=null&&i.baseURL&&d.startsWith(c.config.baseURL)&&(d=d.replace(c.config.baseURL,""));let u=c.schema[d];if(u){let l=L(x({},t),{method:u.method,output:u.output});return t?.disableValidation||(l=L(x({},l),{body:u.input?await ye(u.input,t?.body):t?.body,params:u.params?await ye(u.params,t?.params):t?.params,query:u.query?await ye(u.query,t?.query):t?.query})),{url:e,options:l}}}return{url:e,options:t}}}),ht=r=>{async function e(t,s){let n=L(x(x({},r),s),{plugins:[...r?.plugins||[],wr(r||{})]});if(r?.catchAllError)try{return await Ue(t,n)}catch(o){return{data:null,error:{status:500,statusText:"Fetch Error",message:"Fetch related error. Captured by catchAllError option. See error property for more details.",error:o}}}return await Ue(t,n)}return e};function Er(r,e){let{baseURL:t,params:s,query:n}=e||{query:{},params:{},baseURL:""},o=r.startsWith("http")?r.split("/").slice(0,3).join("/"):t||"";if(r.startsWith("@")){let h=r.toString().split("@")[1].split("/")[0];dt.includes(h)&&(r=r.replace(`@${h}/`,"/"))}o.endsWith("/")||(o+="/");let[i,c]=r.replace(o,"").split("?"),d=new URLSearchParams(c);for(let[h,p]of Object.entries(n||{}))p!=null&&d.set(h,String(p));if(s)if(Array.isArray(s)){let h=i.split("/").filter(p=>p.startsWith(":"));for(let[p,R]of h.entries()){let E=s[p];i=i.replace(R,E)}}else for(let[h,p]of Object.entries(s))i=i.replace(`:${h}`,String(p));i=i.split("/").map(encodeURIComponent).join("/"),i.startsWith("/")&&(i=i.slice(1));let u=d.toString();return u=u.length>0?`?${u}`.replace(/\+/g,"%20"):"",o.startsWith("http")?new URL(`${i}${u}`,o):`${o}${i}${u}`}var Ue=async(r,e)=>{var t,s,n,o,i,c,d,u;let{hooks:l,url:h,options:p}=await ar(r,e),R=fr(p),E=new AbortController,I=(t=p.signal)!=null?t:E.signal,y=Er(h,p),O=gr(p),_=await pr(p),M=yr(h,p),m=L(x({},p),{url:y,headers:_,body:O,method:M,signal:I});for(let U of l.onRequest)if(U){let S=await U(m);S instanceof Object&&(m=S)}("pipeTo"in m&&typeof m.pipeTo=="function"||typeof((s=e?.body)==null?void 0:s.pipe)=="function")&&("duplex"in m||(m.duplex="half"));let{clearTimeout:q}=br(p,E),w=await R(m.url,m);q();let tt={response:w,request:m};for(let U of l.onResponse)if(U){let S=await U(L(x({},tt),{response:(n=e?.hookOptions)!=null&&n.cloneResponse?w.clone():w}));S instanceof Response?w=S:S instanceof Object&&(w=S.response)}if(w.ok){if(!(m.method!=="HEAD"))return{data:"",error:null};let S=dr(w),B={data:"",response:w,request:m};if(S==="json"||S==="text"){let j=await w.text(),Wt=await((o=m.jsonParser)!=null?o:it)(j);B.data=Wt}else B.data=await w[S]();m?.output&&m.output&&!m.disableValidation&&(B.data=await ye(m.output,B.data));for(let j of l.onSuccess)j&&await j(L(x({},B),{response:(i=e?.hookOptions)!=null&&i.cloneResponse?w.clone():w}));return e?.throw?B.data:{data:B.data,error:null}}let Ht=(c=e?.jsonParser)!=null?c:it,me=await w.text(),rt=hr(me),Oe=rt?await Ht(me):null,qt={response:w,responseText:me,request:m,error:L(x({},Oe),{status:w.status,statusText:w.statusText})};for(let U of l.onError)U&&await U(L(x({},qt),{response:(d=e?.hookOptions)!=null&&d.cloneResponse?w.clone():w}));if(e?.retry){let U=lr(e.retry),S=(u=e.retryAttempt)!=null?u:0;if(await U.shouldAttemptRetry(S,w)){for(let j of l.onRetry)j&&await j(tt);let B=U.getDelay(S);return await new Promise(j=>setTimeout(j,B)),await Ue(r,L(x({},e),{retryAttempt:S+1}))}}if(e?.throw)throw new or(w.status,w.statusText,rt?Oe:me);return{data:null,error:L(x({},Oe),{status:w.status,statusText:w.statusText})}};a();a();var be=Object.create(null),J=r=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(r?be:globalThis),A=new Proxy(be,{get(r,e){return J()[e]??be[e]},has(r,e){let t=J();return e in t||e in be},set(r,e,t){let s=J(!0);return s[e]=t,!0},deleteProperty(r,e){if(!e)return!1;let t=J(!0);return delete t[e],!0},ownKeys(){let r=J(!0);return Object.keys(r)}});var Ps=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";function b(r,e){return typeof process<"u"&&process.env?process.env[r]??e:typeof Deno<"u"?Deno.env.get(r)??e:typeof Bun<"u"?Bun.env[r]??e:e}var As=Object.freeze({get BETTER_AUTH_SECRET(){return b("BETTER_AUTH_SECRET")},get AUTH_SECRET(){return b("AUTH_SECRET")},get BETTER_AUTH_TELEMETRY(){return b("BETTER_AUTH_TELEMETRY")},get BETTER_AUTH_TELEMETRY_ID(){return b("BETTER_AUTH_TELEMETRY_ID")},get NODE_ENV(){return b("NODE_ENV","development")},get PACKAGE_VERSION(){return b("PACKAGE_VERSION","0.0.0")},get BETTER_AUTH_TELEMETRY_ENDPOINT(){return b("BETTER_AUTH_TELEMETRY_ENDPOINT","https://telemetry.better-auth.com/v1/track")}}),Y=1,v=4,$=8,P=24,ft={eterm:v,cons25:v,console:v,cygwin:v,dtterm:v,gnome:v,hurd:v,jfbterm:v,konsole:v,kterm:v,mlterm:v,mosh:P,putty:v,st:v,"rxvt-unicode-24bit":P,terminator:P,"xterm-kitty":P},vr=new Map(Object.entries({APPVEYOR:$,BUILDKITE:$,CIRCLECI:P,DRONE:$,GITEA_ACTIONS:P,GITHUB_ACTIONS:P,GITLAB_CI:$,TRAVIS:$})),Tr=[/ansi/,/color/,/linux/,/direct/,/^con[0-9]*x[0-9]/,/^rxvt/,/^screen/,/^xterm/,/^vt100/,/^vt220/];function Sr(){if(b("FORCE_COLOR")!==void 0)switch(b("FORCE_COLOR")){case"":case"1":case"true":return v;case"2":return $;case"3":return P;default:return Y}if(b("NODE_DISABLE_COLORS")!==void 0&&b("NODE_DISABLE_COLORS")!==""||b("NO_COLOR")!==void 0&&b("NO_COLOR")!==""||b("TERM")==="dumb")return Y;if(b("TMUX"))return P;if("TF_BUILD"in A&&"AGENT_NAME"in A)return v;if("CI"in A){for(let{0:r,1:e}of vr)if(r in A)return e;return b("CI_NAME")==="codeship"?$:Y}if("TEAMCITY_VERSION"in A)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.exec(b("TEAMCITY_VERSION"))!==null?v:Y;switch(b("TERM_PROGRAM")){case"iTerm.app":return!b("TERM_PROGRAM_VERSION")||/^[0-2]\./.exec(b("TERM_PROGRAM_VERSION"))!==null?$:P;case"HyperTerm":case"MacTerm":return P;case"Apple_Terminal":return $}if(b("COLORTERM")==="truecolor"||b("COLORTERM")==="24bit")return P;if(b("TERM")){if(/truecolor/.exec(b("TERM"))!==null)return P;if(/^xterm-256/.exec(b("TERM"))!==null)return $;let r=b("TERM").toLowerCase();if(ft[r])return ft[r];if(Tr.some(e=>e.exec(r)!==null))return v}return b("COLORTERM")?v:Y}var D={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",undim:"\x1B[22m",underscore:"\x1B[4m",blink:"\x1B[5m",reverse:"\x1B[7m",hidden:"\x1B[8m",fg:{black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"},bg:{black:"\x1B[40m",red:"\x1B[41m",green:"\x1B[42m",yellow:"\x1B[43m",blue:"\x1B[44m",magenta:"\x1B[45m",cyan:"\x1B[46m",white:"\x1B[47m"}},Ie=["info","success","warn","error","debug"];function _r(r,e){return Ie.indexOf(e)<=Ie.indexOf(r)}var Pr={info:D.fg.blue,success:D.fg.green,warn:D.fg.yellow,error:D.fg.red,debug:D.fg.magenta},Ar=(r,e,t)=>{let s=new Date().toISOString();return t?`${D.dim}${s}${D.reset} ${Pr[r]}${r.toUpperCase()}${D.reset} ${D.bright}[Better Auth]:${D.reset} ${e}`:`${s} ${r.toUpperCase()} [Better Auth]: ${e}`},Or=r=>{let e=r?.disabled!==!0,t=r?.level??"error",n=r?.disableColors!==void 0?!r.disableColors:Sr()!==1,o=(c,d,u=[])=>{if(!e||!_r(t,c))return;let l=Ar(c,d,n);if(!r||typeof r.log!="function"){c==="error"?console.error(l,...u):c==="warn"?console.warn(l,...u):console.log(l,...u);return}r.log(c==="success"?"info":c,d,...u)};return{...Object.fromEntries(Ie.map(c=>[c,(...[d,...u])=>o(c,d,u)])),get level(){return t}}},Os=Or();a();a();var $s={USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_USER:"Failed to create user",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_UPDATE_USER:"Failed to update user",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"Invalid token",ID_TOKEN_NOT_SUPPORTED:"id_token not supported",FAILED_TO_GET_USER_INFO:"Failed to get user info",USER_EMAIL_NOT_FOUND:"User email not found",EMAIL_NOT_VERIFIED:"Email not verified",PASSWORD_TOO_SHORT:"Password too short",PASSWORD_TOO_LONG:"Password too long",USER_ALREADY_EXISTS:"User already exists.",USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL:"User already exists. Use another email.",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found",SESSION_EXPIRED:"Session expired. Re-authenticate to perform this action.",FAILED_TO_UNLINK_LAST_ACCOUNT:"You can't unlink your last account",ACCOUNT_NOT_FOUND:"Account not found",USER_ALREADY_HAS_PASSWORD:"User already has a password. Provide that to delete the account."},W=class extends Error{constructor(e,t){super(e),this.name="BetterAuthError",this.message=e,this.cause=t,this.stack=""}};function Ur(r){try{return(new URL(r).pathname.replace(/\/+$/,"")||"/")!=="/"}catch{throw new W(`Invalid base URL: ${r}. Please provide a valid base URL.`)}}function Q(r,e="/api/auth"){if(Ur(r))return r;let s=r.replace(/\/+$/,"");return!e||e==="/"?s:(e=e.startsWith("/")?e:`/${e}`,`${s}${e}`)}function pt(r,e,t,s){if(r)return Q(r,e);if(s!==!1){let i=A.BETTER_AUTH_URL||A.NEXT_PUBLIC_BETTER_AUTH_URL||A.PUBLIC_BETTER_AUTH_URL||A.NUXT_PUBLIC_BETTER_AUTH_URL||A.NUXT_PUBLIC_AUTH_URL||(A.BASE_URL!=="/"?A.BASE_URL:void 0);if(i)return Q(i,e)}let n=t?.headers.get("x-forwarded-host"),o=t?.headers.get("x-forwarded-proto");if(n&&o)return Q(`${o}://${n}`,e);if(t){let i=Ir(t.url);if(!i)throw new W("Could not get origin from request. Please provide a valid base URL.");return Q(i,e)}if(typeof window<"u"&&window.location)return Q(window.location.origin,e)}function Ir(r){try{return new URL(r).origin}catch{return null}}a();a();a();var X=Symbol("clean");var C=[],H=0,Re=4,xr=0,Z=r=>{let e=[],t={get(){return t.lc||t.listen(()=>{})(),t.value},lc:0,listen(s){return t.lc=e.push(s),()=>{for(let o=H+Re;o<C.length;)C[o]===s?C.splice(o,Re):o+=Re;let n=e.indexOf(s);~n&&(e.splice(n,1),--t.lc||t.off())}},notify(s,n){xr++;let o=!C.length;for(let i of e)C.push(i,t.value,s,n);if(o){for(H=0;H<C.length;H+=Re)C[H](C[H+1],C[H+2],C[H+3]);C.length=0}},off(){},set(s){let n=t.value;n!==s&&(t.value=s,t.notify(n))},subscribe(s){let n=t.listen(s);return s(t.value),n},value:r};return process.env.NODE_ENV!=="production"&&(t[X]=()=>{e=[],t.lc=0,t.off()}),t};a();var Cr=5,G=6,we=10,Nr=(r,e,t,s)=>(r.events=r.events||{},r.events[t+we]||(r.events[t+we]=s(n=>{r.events[t].reduceRight((o,i)=>(i(o),o),{shared:{},...n})})),r.events[t]=r.events[t]||[],r.events[t].push(e),()=>{let n=r.events[t],o=n.indexOf(e);n.splice(o,1),n.length||(delete r.events[t],r.events[t+we](),delete r.events[t+we])});var mt=1e3,xe=(r,e)=>Nr(r,s=>{let n=e(s);n&&r.events[G].push(n)},Cr,s=>{let n=r.listen;r.listen=(...i)=>(!r.lc&&!r.active&&(r.active=!0,s()),n(...i));let o=r.off;if(r.events[G]=[],r.off=()=>{o(),setTimeout(()=>{if(r.active&&!r.lc){r.active=!1;for(let i of r.events[G])i();r.events[G]=[]}},mt)},process.env.NODE_ENV!=="production"){let i=r[X];r[X]=()=>{for(let c of r.events[G])c();r.events[G]=[],r.active=!1,i()}}return()=>{r.listen=n,r.off=o}});a();var Lr=typeof window>"u",Ee=(r,e,t,s)=>{let n=Z({data:null,error:null,isPending:!0,isRefetching:!1,refetch:c=>o(c)}),o=c=>{let d=typeof s=="function"?s({data:n.get().data,error:n.get().error,isPending:n.get().isPending}):s;t(e,{...d,query:{...d?.query,...c?.query},async onSuccess(u){n.set({data:u.data,error:null,isPending:!1,isRefetching:!1,refetch:n.value.refetch}),await d?.onSuccess?.(u)},async onError(u){let{request:l}=u,h=typeof l.retry=="number"?l.retry:l.retry?.attempts,p=l.retryAttempt||0;h&&p<h||(n.set({error:u.error,data:null,isPending:!1,isRefetching:!1,refetch:n.value.refetch}),await d?.onError?.(u))},async onRequest(u){let l=n.get();n.set({isPending:l.data===null,data:l.data,error:null,isRefetching:!0,refetch:n.value.refetch}),await d?.onRequest?.(u)}}).catch(u=>{n.set({error:u,data:null,isPending:!1,isRefetching:!1,refetch:n.value.refetch})})};r=Array.isArray(r)?r:[r];let i=!1;for(let c of r)c.subscribe(()=>{Lr||(i?o():xe(n,()=>{let d=setTimeout(()=>{i||(o(),i=!0)},0);return()=>{n.off(),c.off(),clearTimeout(d)}}))});return n};a();var $r={proto:/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,constructor:/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,protoShort:/"__proto__"\s*:/,constructorShort:/"constructor"\s*:/},Dr=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,gt={true:!0,false:!1,null:null,undefined:void 0,nan:Number.NaN,infinity:Number.POSITIVE_INFINITY,"-infinity":Number.NEGATIVE_INFINITY},kr=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function Mr(r){return r instanceof Date&&!isNaN(r.getTime())}function Br(r){let e=kr.exec(r);if(!e)return null;let[,t,s,n,o,i,c,d,u,l,h]=e,p=new Date(Date.UTC(parseInt(t,10),parseInt(s,10)-1,parseInt(n,10),parseInt(o,10),parseInt(i,10),parseInt(c,10),d?parseInt(d.padEnd(3,"0"),10):0));if(u){let R=(parseInt(l,10)*60+parseInt(h,10))*(u==="+"?-1:1);p.setUTCMinutes(p.getUTCMinutes()+R)}return Mr(p)?p:null}function jr(r,e={}){let{strict:t=!1,warnings:s=!1,reviver:n,parseDates:o=!0}=e;if(typeof r!="string")return r;let i=r.trim();if(i.length>0&&i[0]==='"'&&i.endsWith('"')&&!i.slice(1,-1).includes('"'))return i.slice(1,-1);let c=i.toLowerCase();if(c.length<=9&&c in gt)return gt[c];if(!Dr.test(i)){if(t)throw new SyntaxError("[better-json] Invalid JSON");return r}if(Object.entries($r).some(([u,l])=>{let h=l.test(i);return h&&s&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${u} pattern`),h})&&t)throw new Error("[better-json] Potential prototype pollution attempt detected");try{return JSON.parse(i,(l,h)=>{if(l==="__proto__"||l==="constructor"&&h&&typeof h=="object"&&"prototype"in h){s&&console.warn(`[better-json] Dropping "${l}" key to prevent prototype pollution`);return}if(o&&typeof h=="string"){let p=Br(h);if(p)return p}return n?n(l,h):h})}catch(u){if(t)throw u;return r}}function yt(r,e={strict:!0}){return jr(r,e)}var Fr={id:"redirect",name:"Redirect",hooks:{onSuccess(r){if(r.data?.url&&r.data?.redirect&&typeof window<"u"&&window.location&&window.location)try{window.location.href=r.data.url}catch{}}}};function Hr(r){let e=Z(!1);return{session:Ee(e,"/get-session",r,{method:"GET"}),$sessionSignal:e}}var bt=(r,e)=>{let t="credentials"in Request.prototype,s=pt(r?.baseURL,r?.basePath,void 0,e)??"/api/auth",n=r?.plugins?.flatMap(m=>m.fetchPlugins).filter(m=>m!==void 0)||[],o={id:"lifecycle-hooks",name:"lifecycle-hooks",hooks:{onSuccess:r?.fetchOptions?.onSuccess,onError:r?.fetchOptions?.onError,onRequest:r?.fetchOptions?.onRequest,onResponse:r?.fetchOptions?.onResponse}},{onSuccess:i,onError:c,onRequest:d,onResponse:u,...l}=r?.fetchOptions||{},h=ht({baseURL:s,...t?{credentials:"include"}:{},method:"GET",jsonParser(m){return m?yt(m,{strict:!1}):null},customFetchImpl:fetch,...l,plugins:[o,...l.plugins||[],...r?.disableDefaultFetchPlugins?[]:[Fr],...n]}),{$sessionSignal:p,session:R}=Hr(h),E=r?.plugins||[],I={},y={$sessionSignal:p,session:R},O={"/sign-out":"POST","/revoke-sessions":"POST","/revoke-other-sessions":"POST","/delete-user":"POST"},_=[{signal:"$sessionSignal",matcher(m){return m==="/sign-out"||m==="/update-user"||m.startsWith("/sign-in")||m.startsWith("/sign-up")||m==="/delete-user"||m==="/verify-email"}}];for(let m of E)m.getAtoms&&Object.assign(y,m.getAtoms?.(h)),m.pathMethods&&Object.assign(O,m.pathMethods),m.atomListeners&&_.push(...m.atomListeners);let M={notify:m=>{y[m].set(!y[m].get())},listen:(m,q)=>{y[m].subscribe(q)},atoms:y};for(let m of E)m.getActions&&Object.assign(I,m.getActions?.(h,M,r));return{get baseURL(){return s},pluginsActions:I,pluginsAtoms:y,pluginPathMethods:O,atomListeners:_,$fetch:h,$store:M}};function qr(r){return typeof r=="object"&&r!==null&&"get"in r&&typeof r.get=="function"&&"lc"in r&&typeof r.lc=="number"}function Wr(r,e,t){let s=e[r],{fetchOptions:n,query:o,...i}=t||{};return s||(n?.method?n.method:i&&Object.keys(i).length>0?"POST":"GET")}function Rt(r,e,t,s,n){function o(i=[]){return new Proxy(function(){},{get(c,d){if(typeof d!="string"||d==="then"||d==="catch"||d==="finally")return;let u=[...i,d],l=r;for(let h of u)if(l&&typeof l=="object"&&h in l)l=l[h];else{l=void 0;break}return typeof l=="function"||qr(l)?l:o(u)},apply:async(c,d,u)=>{let l="/"+i.map(_=>_.replace(/[A-Z]/g,M=>`-${M.toLowerCase()}`)).join("/"),h=u[0]||{},p=u[1]||{},{query:R,fetchOptions:E,...I}=h,y={...p,...E},O=Wr(l,t,h);return await e(l,{...y,body:O==="GET"?void 0:{...I,...y?.body||{}},query:R||y?.query,method:O,async onSuccess(_){if(await y?.onSuccess?.(_),!n)return;let M=n.filter(m=>m.matcher(l));if(M.length)for(let m of M){let q=s[m.signal];if(!q)return;let w=q.get();setTimeout(()=>{q.set(!w)},10)}}})}})}return o()}a();function wt(r){return r.charAt(0).toUpperCase()+r.slice(1)}function Ce(r){let{pluginPathMethods:e,pluginsActions:t,pluginsAtoms:s,$fetch:n,atomListeners:o,$store:i}=bt(r),c={};for(let[l,h]of Object.entries(s))c[`use${wt(l)}`]=h;let d={...t,...c,$fetch:n,$store:i};return Rt(d,n,e,s,o)}a();a();a();function Gr(r){return{authorize(e,t="AND"){let s=!1;for(let[n,o]of Object.entries(e)){let i=r[n];if(!i)return{success:!1,error:`You are not allowed to access resource: ${n}`};if(Array.isArray(o))s=o.every(c=>i.includes(c));else if(typeof o=="object"){let c=o;c.connector==="OR"?s=c.actions.some(d=>i.includes(d)):s=c.actions.every(d=>i.includes(d))}else throw new W("Invalid access control request");if(s&&t==="OR")return{success:s};if(!s&&t==="AND")return{success:!1,error:`unauthorized to access resource "${n}"`}}return s?{success:s}:{success:!1,error:"Not authorized"}},statements:r}}function ve(r){return{newRole(e){return Gr(e)},statements:r}}var zr={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"],team:["create","update","delete"],ac:["create","read","update","delete"]},Ne=ve(zr),Vr=Ne.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"],team:["create","update","delete"],ac:["create","read","update","delete"]}),Kr=Ne.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"],team:["create","update","delete"],ac:["create","read","update","delete"]}),Jr=Ne.newRole({organization:[],member:[],invitation:[],team:[],ac:["read"]});a();a();a();a();a();a();a();a();a();a();a();var Le=class{constructor(){Object.defineProperty(this,"controller",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}createNewAbortSignal(){if(this.controller){let t=new Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}},Tt=new Le;a();a();a();a();a();a();a();a();var es={user:["create","list","set-role","ban","impersonate","delete","set-password","get","update"],session:["list","revoke","delete"]},St=ve(es),ts=St.newRole({user:["create","list","set-role","ban","impersonate","delete","set-password","get","update"],session:["list","revoke","delete"]}),rs=St.newRole({user:[],session:[]});a();a();var _t=()=>({id:"username",$InferServerPlugin:{}});var Pt="/auth",ee="nvwa_login_token",Te="nvwa_user_profile",De=class{constructor(e,t,s){this.storage=s,this.authClient=Ce({baseURL:e,basePath:Pt,fetchOptions:{customFetchImpl:t,auth:{type:"Bearer",token:()=>s.get(ee)},onSuccess:n=>{let o=n.response.headers.get("set-auth-token");o&&s.set(ee,o)}},plugins:[_t()]})}async currentUser(){return await this.storage.get(Te)}async signUp(e,t){let s=await this.authClient.signUp.email({email:e.email??`${e.username}@nvwa.app`,name:e.name,username:e.username,displayUsername:e.displayUsername,password:t});this.saveSession(s)}async signInWithUsername(e,t){let s=await this.authClient.signIn.username({username:e,password:t});this.saveSession(s)}saveSession(e){if(e.error)throw new Error(e.error.message);this.storage.set(ee,e.data?.token),this.storage.set(Te,e.data?.user)}async signOut(){await this.storage.remove(ee),await this.storage.remove(Te)}async updateUserPassword(e,t,s=!1){let n=await this.authClient.changePassword({currentPassword:e,newPassword:t,revokeOtherSessions:s});this.saveSession(n)}};a();var ke=class{constructor(e){this.http=e}async invoke(e,t){return(await this.http.request("/functions/"+e,{method:t.method||"POST",data:t.body,headers:t.headers})).body}};a();var Me=class{constructor(e,t,s,n,o){this.ok=e,this.status=t,this.statusText=s,this.headers=n,this.body=o}async text(){return typeof this.body=="string"?this.body:JSON.stringify(this.body)}async json(){if(typeof this.body=="string")try{return JSON.parse(this.body)}catch{return this.body}return this.body}async arrayBuffer(){if(this.body instanceof ArrayBuffer)return this.body;if(typeof this.body=="string")return new TextEncoder().encode(this.body).buffer;throw new Error("Cannot convert body to ArrayBuffer")}async blob(){if(this.body instanceof Blob)return this.body;if(typeof this.body=="string")return new Blob([this.body],{type:this.headers["content-type"]||"text/plain"});throw new Error("Cannot convert body to Blob")}},Be=class{async jsonRequest(e,t){let s={...t,headers:{"Content-Type":"application/json",...t.headers},data:typeof t.data=="object"?JSON.stringify(t.data):t.data};return this.request(e,s)}async jsonRequestWithAuth(e,t,s){let n={...t,headers:{"Content-Type":"application/json",...t.headers},data:typeof t.data=="object"?JSON.stringify(t.data):t.data};return this.requestWithAuth(e,n,s)}};a();var At="/storage",Ot=At+"/generateUploadUrl",je=class{constructor(e,t){this.baseUrl=e,this.http=t}async uploadFile(e){let t=await this.http.request(this.baseUrl+Ot,{method:"POST",data:{fileName:e.name||e.fileName,fileSize:e.size||e.fileSize,fileType:e.type||e.fileType}}),{url:s}=t.body;if(!s)throw new Error("\u83B7\u53D6\u4E0A\u4F20URL\u5931\u8D25");return{url:(await this.http.request(s,{method:"PUT",data:e,headers:{"Content-Type":e.type||e.fileType||"application/octet-stream"}})).body.url.split("?")[0]}}};a();a();a();var Bt=Xt(Mt(),1),{PostgrestClient:jt,PostgrestQueryBuilder:ii,PostgrestFilterBuilder:li,PostgrestTransformBuilder:ci,PostgrestBuilder:ui,PostgrestError:di,FetchHeaders:hi,FetchResponse:et,PostgrestFetch:fi,URL:pi,URLSearchParams:mi}=Bt.default;var Ft="/entities",fs=(r,e)=>async(s,n)=>{console.log("customFetch",s,n);let o;if(typeof s=="string")o=s;else if(s&&typeof s=="object")if(typeof s.toString=="function"&&!s.url)o=s.toString();else if(s.url)o=s.url,n||(n={}),n.method=s.method,n.headers=s.headers,n.body=s.body;else throw new Error("Unsupported input type for fetch");else throw new Error("Unsupported input type for fetch");let i=(n?.method||"GET").toUpperCase(),c={};if(n?.headers)if(n.headers&&typeof n.headers.forEach=="function")n.headers.forEach((R,E)=>{c[E]=R});else if(Array.isArray(n.headers))for(let[R,E]of n.headers)c[R]=E;else Object.assign(c,n.headers);let d=n?.body,u;try{u=await r.requestWithAuth(o,{method:i,data:d,headers:c},e)}catch(R){return new et(R?.message||"Internal Error",{status:500,statusText:"Internal Error"})}let l=u.body,h=null;return(u.headers["content-type"]||u.headers["Content-Type"]||"").startsWith("application/json")&&typeof l!="string"?h=JSON.stringify(l):typeof l=="string"||l&&(l.constructor===Blob||l.constructor===ArrayBuffer||typeof l.getReader=="function")?h=l:h=JSON.stringify(l),new et(h,{status:u.status,headers:u.headers})},ps=(r,e,t)=>new jt(r+Ft,{fetch:fs(e,t)});a();a();var N=class r{constructor(e){this.headerMap=new Map;if(e){if(e instanceof r)e.forEach((t,s)=>this.set(s,t));else if(Array.isArray(e))for(let[t,s]of e)this.set(t,String(s));else if(typeof e=="object")for(let t of Object.keys(e))this.set(t,String(e[t]))}}append(e,t){let s=e.toLowerCase(),n=this.headerMap.get(s);this.headerMap.set(s,n?`${n}, ${t}`:t)}set(e,t){this.headerMap.set(e.toLowerCase(),String(t))}get(e){let t=this.headerMap.get(e.toLowerCase());return t??null}has(e){return this.headerMap.has(e.toLowerCase())}delete(e){this.headerMap.delete(e.toLowerCase())}forEach(e){for(let[t,s]of this.headerMap.entries())e(s,t,this)}entries(){return this.headerMap.entries()}keys(){return this.headerMap.keys()}values(){return this.headerMap.values()}[Symbol.iterator](){return this.entries()}},V=class r{constructor(e){this.params=new Map;if(e){if(typeof e=="string")this.parseString(e);else if(e instanceof r)this.params=new Map(e.params);else if(Array.isArray(e))for(let[t,s]of e)this.append(t,s);else if(e&&typeof e=="object")for(let[t,s]of Object.entries(e))this.set(t,s)}}parseString(e){e.startsWith("?")&&(e=e.slice(1));let t=e.split("&");for(let s of t)if(s){let[n,o]=s.split("=");n&&this.append(decodeURIComponent(n),o?decodeURIComponent(o):"")}}append(e,t){let s=this.params.get(e)||[];s.push(t),this.params.set(e,s)}delete(e){this.params.delete(e)}get(e){let t=this.params.get(e);return t?t[0]:null}getAll(e){return this.params.get(e)||[]}has(e){return this.params.has(e)}set(e,t){this.params.set(e,[t])}sort(){let e=Array.from(this.params.entries()).sort(([t],[s])=>t.localeCompare(s));this.params=new Map(e)}toString(){let e=[];for(let[t,s]of this.params.entries())for(let n of s)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(n)}`);return e.join("&")}forEach(e){for(let[t,s]of this.params.entries())for(let n of s)e(n,t,this)}keys(){return this.params.keys()}values(){let e=[];for(let t of this.params.values())e.push(...t);return e[Symbol.iterator]()}entries(){let e=[];for(let[t,s]of this.params.entries())for(let n of s)e.push([t,n]);return e[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}},de=class r{constructor(e,t){let s;if(e instanceof r)s=e.href;else if(t){let o=t instanceof r?t.href:t;s=this.resolve(o,e)}else s=e;let n=this.parseUrl(s);this.href=s,this.origin=`${n.protocol}//${n.host}`,this.protocol=n.protocol,this.username=n.username,this.password=n.password,this.host=n.host,this.hostname=n.hostname,this.port=n.port,this.pathname=n.pathname,this.search=n.search,this.searchParams=new V(n.search),this.hash=n.hash}resolve(e,t){if(t.startsWith("http://")||t.startsWith("https://"))return t;if(t.startsWith("//"))return`${this.parseUrl(e).protocol}${t}`;if(t.startsWith("/")){let o=this.parseUrl(e);return`${o.protocol}//${o.host}${t}`}let s=this.parseUrl(e),n=s.pathname.endsWith("/")?s.pathname:s.pathname+"/";return`${s.protocol}//${s.host}${n}${t}`}parseUrl(e){let t=e.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!t)throw new TypeError("Invalid URL");let s=t[2]||"",n=t[4]||"",o=t[5]||"/",i=t[7]?`?${t[7]}`:"",c=t[9]?`#${t[9]}`:"";if(!s&&!n&&!o.startsWith("/")&&!o.includes("/")&&!o.includes("."))throw new TypeError("Invalid URL");let d=n.match(/^([^@]*)@(.+)$/),u="",l="",h=n;if(d){let I=d[1];h=d[2];let y=I.match(/^([^:]*):?(.*)$/);y&&(u=y[1]||"",l=y[2]||"")}let p=h.match(/^([^:]+):?(\d*)$/),R=p?p[1]:h,E=p&&p[2]?p[2]:"";return{protocol:s?`${s}:`:"",username:u,password:l,host:h,hostname:R,port:E,pathname:o,search:i,hash:c}}toString(){let e=this.searchParams.toString(),t=e?`?${e}`:"";return`${this.protocol}//${this.host}${this.pathname}${t}${this.hash}`}toJSON(){return this.toString()}};a();var he=class r{constructor(e,t){if(typeof e=="string")this.url=e;else if(e?.url)this.url=String(e.url);else if(typeof e?.toString=="function")this.url=String(e.toString());else throw new Error("Invalid input for Request");this.method=(t?.method||"GET").toUpperCase(),this.headers=t?.headers instanceof N?t.headers:new N(t?.headers),this.body=t?.body,this.timeout=t?.timeout,this.signal=t?.signal||void 0}clone(){return new r(this.url,{method:this.method,headers:this.headers,body:this.body,timeout:this.timeout})}toString(){return this.url}};a();var fe=class{constructor(e,t){this.bodyData=e,this.status=t?.status??200,this.statusText=t?.statusText??"",this.headers=ms(t?.headers),this.ok=this.status>=200&&this.status<300}async text(){return typeof this.bodyData=="string"?this.bodyData:this.bodyData==null?"":typeof this.bodyData=="object"?JSON.stringify(this.bodyData):String(this.bodyData)}async json(){if(typeof this.bodyData=="string")try{return JSON.parse(this.bodyData)}catch{}return this.bodyData}async arrayBuffer(){let e=await this.text();return new TextEncoder().encode(e).buffer}};function ms(r){return r?new N(r):new N}a();var K=class{constructor(){this._aborted=!1;this.listeners=new Set;this.onabort=null}get aborted(){return this._aborted}_trigger(){if(!this._aborted){if(this._aborted=!0,typeof this.onabort=="function")try{this.onabort()}catch{}for(let e of Array.from(this.listeners))try{e()}catch{}this.listeners.clear()}}addEventListener(e,t){if(this._aborted){try{t()}catch{}return}this.listeners.add(t)}removeEventListener(e,t){this.listeners.delete(t)}toString(){return"[object AbortSignal]"}},pe=class{constructor(){this._signal=new K}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}};a();function gs(r){r.URL=de,r.URLSearchParams=V,r.Headers=N,r.Request=he,r.Response=fe,r.AbortController=pe,r.AbortSignal=K}0&&(module.exports={AUTH_BASE_PATH,AbortController,AbortSignal,ENTITIES_BASE_PATH,FILE_STORAGE_BASE_PATH,FetchResponse,GENERATE_UPLOAD_URL_PATH,Headers,LOGIN_TOKEN_KEY,LOGIN_USER_PROFILE_KEY,NvwaAuthClient,NvwaEdgeFunctions,NvwaFileStorage,NvwaHttpClient,Request,Response,URL,URLSearchParams,createPostgrestClient,polyfill});
1
+ "use strict";var ce=Object.defineProperty;var Ze=Object.getOwnPropertyDescriptor;var et=Object.getOwnPropertyNames;var tt=Object.prototype.hasOwnProperty;var rt=(t,e)=>{for(var r in e)ce(t,r,{get:e[r],enumerable:!0})},nt=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of et(e))!tt.call(t,s)&&s!==r&&ce(t,s,{get:()=>e[s],enumerable:!(n=Ze(e,s))||n.enumerable});return t};var st=t=>nt(ce({},"__esModule",{value:!0}),t);var fr={};rt(fr,{AUTH_BASE_PATH:()=>Ve,AbortController:()=>X,AbortSignal:()=>j,ENTITIES_BASE_PATH:()=>Je,FILE_STORAGE_BASE_PATH:()=>Ge,FetchResponse:()=>be,GENERATE_UPLOAD_URL_PATH:()=>ze,Headers:()=>v,LOGIN_TOKEN_KEY:()=>J,LOGIN_USER_PROFILE_KEY:()=>ie,NvwaAuthClient:()=>ge,NvwaEdgeFunctions:()=>ye,NvwaFileStorage:()=>Ee,NvwaHttpClient:()=>Re,Request:()=>Q,Response:()=>M,URL:()=>Y,URLSearchParams:()=>q,createPostgrestClient:()=>dr,polyfill:()=>lr});module.exports=st(fr);var ot=Object.defineProperty,it=Object.defineProperties,at=Object.getOwnPropertyDescriptors,Se=Object.getOwnPropertySymbols,ct=Object.prototype.hasOwnProperty,lt=Object.prototype.propertyIsEnumerable,ve=(t,e,r)=>e in t?ot(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,O=(t,e)=>{for(var r in e||(e={}))ct.call(e,r)&&ve(t,r,e[r]);if(Se)for(var r of Se(e))lt.call(e,r)&&ve(t,r,e[r]);return t},P=(t,e)=>it(t,at(e)),ut=class extends Error{constructor(t,e,r){super(e||t.toString(),{cause:r}),this.status=t,this.statusText=e,this.error=r}},dt=async(t,e)=>{var r,n,s,o,c,l;let u=e||{},a={onRequest:[e?.onRequest],onResponse:[e?.onResponse],onSuccess:[e?.onSuccess],onError:[e?.onError],onRetry:[e?.onRetry]};if(!e||!e?.plugins)return{url:t,options:u,hooks:a};for(let i of e?.plugins||[]){if(i.init){let d=await((r=i.init)==null?void 0:r.call(i,t.toString(),e));u=d.options||u,t=d.url}a.onRequest.push((n=i.hooks)==null?void 0:n.onRequest),a.onResponse.push((s=i.hooks)==null?void 0:s.onResponse),a.onSuccess.push((o=i.hooks)==null?void 0:o.onSuccess),a.onError.push((c=i.hooks)==null?void 0:c.onError),a.onRetry.push((l=i.hooks)==null?void 0:l.onRetry)}return{url:t,options:u,hooks:a}},Ae=class{constructor(t){this.options=t}shouldAttemptRetry(t,e){return this.options.shouldRetry?Promise.resolve(t<this.options.attempts&&this.options.shouldRetry(e)):Promise.resolve(t<this.options.attempts)}getDelay(){return this.options.delay}},ft=class{constructor(t){this.options=t}shouldAttemptRetry(t,e){return this.options.shouldRetry?Promise.resolve(t<this.options.attempts&&this.options.shouldRetry(e)):Promise.resolve(t<this.options.attempts)}getDelay(t){return Math.min(this.options.maxDelay,this.options.baseDelay*2**t)}};function pt(t){if(typeof t=="number")return new Ae({type:"linear",attempts:t,delay:1e3});switch(t.type){case"linear":return new Ae(t);case"exponential":return new ft(t);default:throw new Error("Invalid retry strategy")}}var ht=async t=>{let e={},r=async n=>typeof n=="function"?await n():n;if(t?.auth){if(t.auth.type==="Bearer"){let n=await r(t.auth.token);if(!n)return e;e.authorization=`Bearer ${n}`}else if(t.auth.type==="Basic"){let n=r(t.auth.username),s=r(t.auth.password);if(!n||!s)return e;e.authorization=`Basic ${btoa(`${n}:${s}`)}`}else if(t.auth.type==="Custom"){let n=r(t.auth.value);if(!n)return e;e.authorization=`${r(t.auth.prefix)} ${n}`}}return e},mt=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function gt(t){let e=t.headers.get("content-type"),r=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!e)return"json";let n=e.split(";").shift()||"";return mt.test(n)?"json":r.has(n)||n.startsWith("text/")?"text":"blob"}function yt(t){try{return JSON.parse(t),!0}catch{return!1}}function Pe(t){if(t===void 0)return!1;let e=typeof t;return e==="string"||e==="number"||e==="boolean"||e===null?!0:e!=="object"?!1:Array.isArray(t)?!0:t.buffer?!1:t.constructor&&t.constructor.name==="Object"||typeof t.toJSON=="function"}function Oe(t){try{return JSON.parse(t)}catch{return t}}function _e(t){return typeof t=="function"}function bt(t){if(t?.customFetchImpl)return t.customFetchImpl;if(typeof globalThis<"u"&&_e(globalThis.fetch))return globalThis.fetch;if(typeof window<"u"&&_e(window.fetch))return window.fetch;throw new Error("No fetch implementation found")}async function Rt(t){let e=new Headers(t?.headers),r=await ht(t);for(let[n,s]of Object.entries(r||{}))e.set(n,s);if(!e.has("content-type")){let n=Et(t?.body);n&&e.set("content-type",n)}return e}function Et(t){return Pe(t)?"application/json":null}function Tt(t){if(!t?.body)return null;let e=new Headers(t?.headers);if(Pe(t.body)&&!e.has("content-type")){for(let[r,n]of Object.entries(t?.body))n instanceof Date&&(t.body[r]=n.toISOString());return JSON.stringify(t.body)}return t.body}function wt(t,e){var r;if(e?.method)return e.method.toUpperCase();if(t.startsWith("@")){let n=(r=t.split("@")[1])==null?void 0:r.split("/")[0];return Ue.includes(n)?n.toUpperCase():e?.body?"POST":"GET"}return e?.body?"POST":"GET"}function St(t,e){let r;return!t?.signal&&t?.timeout&&(r=setTimeout(()=>e?.abort(),t?.timeout)),{abortTimeout:r,clearTimeout:()=>{r&&clearTimeout(r)}}}var vt=class Ie extends Error{constructor(e,r){super(r||JSON.stringify(e,null,2)),this.issues=e,Object.setPrototypeOf(this,Ie.prototype)}};async function ee(t,e){let r=await t["~standard"].validate(e);if(r.issues)throw new vt(r.issues);return r.value}var Ue=["get","post","put","patch","delete"];var At=t=>({id:"apply-schema",name:"Apply Schema",version:"1.0.0",async init(e,r){var n,s,o,c;let l=((s=(n=t.plugins)==null?void 0:n.find(u=>{var a;return(a=u.schema)!=null&&a.config?e.startsWith(u.schema.config.baseURL||"")||e.startsWith(u.schema.config.prefix||""):!1}))==null?void 0:s.schema)||t.schema;if(l){let u=e;(o=l.config)!=null&&o.prefix&&u.startsWith(l.config.prefix)&&(u=u.replace(l.config.prefix,""),l.config.baseURL&&(e=e.replace(l.config.prefix,l.config.baseURL))),(c=l.config)!=null&&c.baseURL&&u.startsWith(l.config.baseURL)&&(u=u.replace(l.config.baseURL,""));let a=l.schema[u];if(a){let i=P(O({},r),{method:a.method,output:a.output});return r?.disableValidation||(i=P(O({},i),{body:a.input?await ee(a.input,r?.body):r?.body,params:a.params?await ee(a.params,r?.params):r?.params,query:a.query?await ee(a.query,r?.query):r?.query})),{url:e,options:i}}}return{url:e,options:r}}}),xe=t=>{async function e(r,n){let s=P(O(O({},t),n),{plugins:[...t?.plugins||[],At(t||{})]});if(t?.catchAllError)try{return await le(r,s)}catch(o){return{data:null,error:{status:500,statusText:"Fetch Error",message:"Fetch related error. Captured by catchAllError option. See error property for more details.",error:o}}}return await le(r,s)}return e};function Ot(t,e){let{baseURL:r,params:n,query:s}=e||{query:{},params:{},baseURL:""},o=t.startsWith("http")?t.split("/").slice(0,3).join("/"):r||"";if(t.startsWith("@")){let d=t.toString().split("@")[1].split("/")[0];Ue.includes(d)&&(t=t.replace(`@${d}/`,"/"))}o.endsWith("/")||(o+="/");let[c,l]=t.replace(o,"").split("?"),u=new URLSearchParams(l);for(let[d,h]of Object.entries(s||{}))h!=null&&u.set(d,String(h));if(n)if(Array.isArray(n)){let d=c.split("/").filter(h=>h.startsWith(":"));for(let[h,b]of d.entries()){let E=n[h];c=c.replace(b,E)}}else for(let[d,h]of Object.entries(n))c=c.replace(`:${d}`,String(h));c=c.split("/").map(encodeURIComponent).join("/"),c.startsWith("/")&&(c=c.slice(1));let a=u.toString();return a=a.length>0?`?${a}`.replace(/\+/g,"%20"):"",o.startsWith("http")?new URL(`${c}${a}`,o):`${o}${c}${a}`}var le=async(t,e)=>{var r,n,s,o,c,l,u,a;let{hooks:i,url:d,options:h}=await dt(t,e),b=bt(h),E=new AbortController,L=(r=h.signal)!=null?r:E.signal,R=Ot(d,h),B=Tt(h),D=await Rt(h),x=wt(d,h),f=P(O({},h),{url:R,headers:D,body:B,method:x,signal:L});for(let A of i.onRequest)if(A){let T=await A(f);T instanceof Object&&(f=T)}("pipeTo"in f&&typeof f.pipeTo=="function"||typeof((n=e?.body)==null?void 0:n.pipe)=="function")&&("duplex"in f||(f.duplex="half"));let{clearTimeout:H}=St(h,E),g=await b(f.url,f);H();let Te={response:g,request:f};for(let A of i.onResponse)if(A){let T=await A(P(O({},Te),{response:(s=e?.hookOptions)!=null&&s.cloneResponse?g.clone():g}));T instanceof Response?g=T:T instanceof Object&&(g=T.response)}if(g.ok){if(!(f.method!=="HEAD"))return{data:"",error:null};let T=gt(g),C={data:"",response:g,request:f};if(T==="json"||T==="text"){let N=await g.text(),Xe=await((o=f.jsonParser)!=null?o:Oe)(N);C.data=Xe}else C.data=await g[T]();f?.output&&f.output&&!f.disableValidation&&(C.data=await ee(f.output,C.data));for(let N of i.onSuccess)N&&await N(P(O({},C),{response:(c=e?.hookOptions)!=null&&c.cloneResponse?g.clone():g}));return e?.throw?C.data:{data:C.data,error:null}}let Ye=(l=e?.jsonParser)!=null?l:Oe,Z=await g.text(),we=yt(Z),ae=we?await Ye(Z):null,Qe={response:g,responseText:Z,request:f,error:P(O({},ae),{status:g.status,statusText:g.statusText})};for(let A of i.onError)A&&await A(P(O({},Qe),{response:(u=e?.hookOptions)!=null&&u.cloneResponse?g.clone():g}));if(e?.retry){let A=pt(e.retry),T=(a=e.retryAttempt)!=null?a:0;if(await A.shouldAttemptRetry(T,g)){for(let N of i.onRetry)N&&await N(Te);let C=A.getDelay(T);return await new Promise(N=>setTimeout(N,C)),await le(t,P(O({},e),{retryAttempt:T+1}))}}if(e?.throw)throw new ut(g.status,g.statusText,we?ae:Z);return{data:null,error:P(O({},ae),{status:g.status,statusText:g.statusText})}};var te=Object.create(null),W=t=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(t?te:globalThis),S=new Proxy(te,{get(t,e){return W()[e]??te[e]},has(t,e){let r=W();return e in r||e in te},set(t,e,r){let n=W(!0);return n[e]=r,!0},deleteProperty(t,e){if(!e)return!1;let r=W(!0);return delete r[e],!0},ownKeys(){let t=W(!0);return Object.keys(t)}});var Er=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";function m(t,e){return typeof process<"u"&&process.env?process.env[t]??e:typeof Deno<"u"?Deno.env.get(t)??e:typeof Bun<"u"?Bun.env[t]??e:e}var Tr=Object.freeze({get BETTER_AUTH_SECRET(){return m("BETTER_AUTH_SECRET")},get AUTH_SECRET(){return m("AUTH_SECRET")},get BETTER_AUTH_TELEMETRY(){return m("BETTER_AUTH_TELEMETRY")},get BETTER_AUTH_TELEMETRY_ID(){return m("BETTER_AUTH_TELEMETRY_ID")},get NODE_ENV(){return m("NODE_ENV","development")},get PACKAGE_VERSION(){return m("PACKAGE_VERSION","0.0.0")},get BETTER_AUTH_TELEMETRY_ENDPOINT(){return m("BETTER_AUTH_TELEMETRY_ENDPOINT","https://telemetry.better-auth.com/v1/track")}}),V=1,y=4,I=8,w=24,Ce={eterm:y,cons25:y,console:y,cygwin:y,dtterm:y,gnome:y,hurd:y,jfbterm:y,konsole:y,kterm:y,mlterm:y,mosh:w,putty:y,st:y,"rxvt-unicode-24bit":w,terminator:w,"xterm-kitty":w},_t=new Map(Object.entries({APPVEYOR:I,BUILDKITE:I,CIRCLECI:w,DRONE:I,GITEA_ACTIONS:w,GITHUB_ACTIONS:w,GITLAB_CI:I,TRAVIS:I})),Pt=[/ansi/,/color/,/linux/,/direct/,/^con[0-9]*x[0-9]/,/^rxvt/,/^screen/,/^xterm/,/^vt100/,/^vt220/];function It(){if(m("FORCE_COLOR")!==void 0)switch(m("FORCE_COLOR")){case"":case"1":case"true":return y;case"2":return I;case"3":return w;default:return V}if(m("NODE_DISABLE_COLORS")!==void 0&&m("NODE_DISABLE_COLORS")!==""||m("NO_COLOR")!==void 0&&m("NO_COLOR")!==""||m("TERM")==="dumb")return V;if(m("TMUX"))return w;if("TF_BUILD"in S&&"AGENT_NAME"in S)return y;if("CI"in S){for(let{0:t,1:e}of _t)if(t in S)return e;return m("CI_NAME")==="codeship"?I:V}if("TEAMCITY_VERSION"in S)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.exec(m("TEAMCITY_VERSION"))!==null?y:V;switch(m("TERM_PROGRAM")){case"iTerm.app":return!m("TERM_PROGRAM_VERSION")||/^[0-2]\./.exec(m("TERM_PROGRAM_VERSION"))!==null?I:w;case"HyperTerm":case"MacTerm":return w;case"Apple_Terminal":return I}if(m("COLORTERM")==="truecolor"||m("COLORTERM")==="24bit")return w;if(m("TERM")){if(/truecolor/.exec(m("TERM"))!==null)return w;if(/^xterm-256/.exec(m("TERM"))!==null)return I;let t=m("TERM").toLowerCase();if(Ce[t])return Ce[t];if(Pt.some(e=>e.exec(t)!==null))return y}return m("COLORTERM")?y:V}var U={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",undim:"\x1B[22m",underscore:"\x1B[4m",blink:"\x1B[5m",reverse:"\x1B[7m",hidden:"\x1B[8m",fg:{black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"},bg:{black:"\x1B[40m",red:"\x1B[41m",green:"\x1B[42m",yellow:"\x1B[43m",blue:"\x1B[44m",magenta:"\x1B[45m",cyan:"\x1B[46m",white:"\x1B[47m"}},ue=["info","success","warn","error","debug"];function Ut(t,e){return ue.indexOf(e)<=ue.indexOf(t)}var xt={info:U.fg.blue,success:U.fg.green,warn:U.fg.yellow,error:U.fg.red,debug:U.fg.magenta},Ct=(t,e,r)=>{let n=new Date().toISOString();return r?`${U.dim}${n}${U.reset} ${xt[t]}${t.toUpperCase()}${U.reset} ${U.bright}[Better Auth]:${U.reset} ${e}`:`${n} ${t.toUpperCase()} [Better Auth]: ${e}`},Nt=t=>{let e=t?.disabled!==!0,r=t?.level??"error",s=t?.disableColors!==void 0?!t.disableColors:It()!==1,o=(l,u,a=[])=>{if(!e||!Ut(r,l))return;let i=Ct(l,u,s);if(!t||typeof t.log!="function"){l==="error"?console.error(i,...a):l==="warn"?console.warn(i,...a):console.log(i,...a);return}t.log(l==="success"?"info":l,u,...a)};return{...Object.fromEntries(ue.map(l=>[l,(...[u,...a])=>o(l,u,a)])),get level(){return r}}},wr=Nt();var Ir={USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_USER:"Failed to create user",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_UPDATE_USER:"Failed to update user",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"Invalid token",ID_TOKEN_NOT_SUPPORTED:"id_token not supported",FAILED_TO_GET_USER_INFO:"Failed to get user info",USER_EMAIL_NOT_FOUND:"User email not found",EMAIL_NOT_VERIFIED:"Email not verified",PASSWORD_TOO_SHORT:"Password too short",PASSWORD_TOO_LONG:"Password too long",USER_ALREADY_EXISTS:"User already exists.",USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL:"User already exists. Use another email.",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found",SESSION_EXPIRED:"Session expired. Re-authenticate to perform this action.",FAILED_TO_UNLINK_LAST_ACCOUNT:"You can't unlink your last account",ACCOUNT_NOT_FOUND:"Account not found",USER_ALREADY_HAS_PASSWORD:"User already has a password. Provide that to delete the account."},$=class extends Error{constructor(e,r){super(e),this.name="BetterAuthError",this.message=e,this.cause=r,this.stack=""}};function Lt(t){try{return(new URL(t).pathname.replace(/\/+$/,"")||"/")!=="/"}catch{throw new $(`Invalid base URL: ${t}. Please provide a valid base URL.`)}}function G(t,e="/api/auth"){if(Lt(t))return t;let n=t.replace(/\/+$/,"");return!e||e==="/"?n:(e=e.startsWith("/")?e:`/${e}`,`${n}${e}`)}function Ne(t,e,r,n){if(t)return G(t,e);if(n!==!1){let c=S.BETTER_AUTH_URL||S.NEXT_PUBLIC_BETTER_AUTH_URL||S.PUBLIC_BETTER_AUTH_URL||S.NUXT_PUBLIC_BETTER_AUTH_URL||S.NUXT_PUBLIC_AUTH_URL||(S.BASE_URL!=="/"?S.BASE_URL:void 0);if(c)return G(c,e)}let s=r?.headers.get("x-forwarded-host"),o=r?.headers.get("x-forwarded-proto");if(s&&o)return G(`${o}://${s}`,e);if(r){let c=Dt(r.url);if(!c)throw new $("Could not get origin from request. Please provide a valid base URL.");return G(c,e)}if(typeof window<"u"&&window.location)return G(window.location.origin,e)}function Dt(t){try{return new URL(t).origin}catch{return null}}var z=Symbol("clean");var _=[],k=0,re=4,kt=0,K=t=>{let e=[],r={get(){return r.lc||r.listen(()=>{})(),r.value},lc:0,listen(n){return r.lc=e.push(n),()=>{for(let o=k+re;o<_.length;)_[o]===n?_.splice(o,re):o+=re;let s=e.indexOf(n);~s&&(e.splice(s,1),--r.lc||r.off())}},notify(n,s){kt++;let o=!_.length;for(let c of e)_.push(c,r.value,n,s);if(o){for(k=0;k<_.length;k+=re)_[k](_[k+1],_[k+2],_[k+3]);_.length=0}},off(){},set(n){let s=r.value;s!==n&&(r.value=n,r.notify(s))},subscribe(n){let s=r.listen(n);return n(r.value),s},value:t};return process.env.NODE_ENV!=="production"&&(r[z]=()=>{e=[],r.lc=0,r.off()}),r};var Mt=5,F=6,ne=10,Bt=(t,e,r,n)=>(t.events=t.events||{},t.events[r+ne]||(t.events[r+ne]=n(s=>{t.events[r].reduceRight((o,c)=>(c(o),o),{shared:{},...s})})),t.events[r]=t.events[r]||[],t.events[r].push(e),()=>{let s=t.events[r],o=s.indexOf(e);s.splice(o,1),s.length||(delete t.events[r],t.events[r+ne](),delete t.events[r+ne])});var Le=1e3,de=(t,e)=>Bt(t,n=>{let s=e(n);s&&t.events[F].push(s)},Mt,n=>{let s=t.listen;t.listen=(...c)=>(!t.lc&&!t.active&&(t.active=!0,n()),s(...c));let o=t.off;if(t.events[F]=[],t.off=()=>{o(),setTimeout(()=>{if(t.active&&!t.lc){t.active=!1;for(let c of t.events[F])c();t.events[F]=[]}},Le)},process.env.NODE_ENV!=="production"){let c=t[z];t[z]=()=>{for(let l of t.events[F])l();t.events[F]=[],t.active=!1,c()}}return()=>{t.listen=s,t.off=o}});var Ht=typeof window>"u",se=(t,e,r,n)=>{let s=K({data:null,error:null,isPending:!0,isRefetching:!1,refetch:l=>o(l)}),o=l=>{let u=typeof n=="function"?n({data:s.get().data,error:s.get().error,isPending:s.get().isPending}):n;r(e,{...u,query:{...u?.query,...l?.query},async onSuccess(a){s.set({data:a.data,error:null,isPending:!1,isRefetching:!1,refetch:s.value.refetch}),await u?.onSuccess?.(a)},async onError(a){let{request:i}=a,d=typeof i.retry=="number"?i.retry:i.retry?.attempts,h=i.retryAttempt||0;d&&h<d||(s.set({error:a.error,data:null,isPending:!1,isRefetching:!1,refetch:s.value.refetch}),await u?.onError?.(a))},async onRequest(a){let i=s.get();s.set({isPending:i.data===null,data:i.data,error:null,isRefetching:!0,refetch:s.value.refetch}),await u?.onRequest?.(a)}}).catch(a=>{s.set({error:a,data:null,isPending:!1,isRefetching:!1,refetch:s.value.refetch})})};t=Array.isArray(t)?t:[t];let c=!1;for(let l of t)l.subscribe(()=>{Ht||(c?o():de(s,()=>{let u=setTimeout(()=>{c||(o(),c=!0)},0);return()=>{s.off(),l.off(),clearTimeout(u)}}))});return s};var $t={proto:/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,constructor:/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,protoShort:/"__proto__"\s*:/,constructorShort:/"constructor"\s*:/},Ft=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,De={true:!0,false:!1,null:null,undefined:void 0,nan:Number.NaN,infinity:Number.POSITIVE_INFINITY,"-infinity":Number.NEGATIVE_INFINITY},qt=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function jt(t){return t instanceof Date&&!isNaN(t.getTime())}function Wt(t){let e=qt.exec(t);if(!e)return null;let[,r,n,s,o,c,l,u,a,i,d]=e,h=new Date(Date.UTC(parseInt(r,10),parseInt(n,10)-1,parseInt(s,10),parseInt(o,10),parseInt(c,10),parseInt(l,10),u?parseInt(u.padEnd(3,"0"),10):0));if(a){let b=(parseInt(i,10)*60+parseInt(d,10))*(a==="+"?-1:1);h.setUTCMinutes(h.getUTCMinutes()+b)}return jt(h)?h:null}function Vt(t,e={}){let{strict:r=!1,warnings:n=!1,reviver:s,parseDates:o=!0}=e;if(typeof t!="string")return t;let c=t.trim();if(c.length>0&&c[0]==='"'&&c.endsWith('"')&&!c.slice(1,-1).includes('"'))return c.slice(1,-1);let l=c.toLowerCase();if(l.length<=9&&l in De)return De[l];if(!Ft.test(c)){if(r)throw new SyntaxError("[better-json] Invalid JSON");return t}if(Object.entries($t).some(([a,i])=>{let d=i.test(c);return d&&n&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${a} pattern`),d})&&r)throw new Error("[better-json] Potential prototype pollution attempt detected");try{return JSON.parse(c,(i,d)=>{if(i==="__proto__"||i==="constructor"&&d&&typeof d=="object"&&"prototype"in d){n&&console.warn(`[better-json] Dropping "${i}" key to prevent prototype pollution`);return}if(o&&typeof d=="string"){let h=Wt(d);if(h)return h}return s?s(i,d):d})}catch(a){if(r)throw a;return t}}function ke(t,e={strict:!0}){return Vt(t,e)}var Gt={id:"redirect",name:"Redirect",hooks:{onSuccess(t){if(t.data?.url&&t.data?.redirect&&typeof window<"u"&&window.location&&window.location)try{window.location.href=t.data.url}catch{}}}};function zt(t){let e=K(!1);return{session:se(e,"/get-session",t,{method:"GET"}),$sessionSignal:e}}var Me=(t,e)=>{let r="credentials"in Request.prototype,n=Ne(t?.baseURL,t?.basePath,void 0,e)??"/api/auth",s=t?.plugins?.flatMap(f=>f.fetchPlugins).filter(f=>f!==void 0)||[],o={id:"lifecycle-hooks",name:"lifecycle-hooks",hooks:{onSuccess:t?.fetchOptions?.onSuccess,onError:t?.fetchOptions?.onError,onRequest:t?.fetchOptions?.onRequest,onResponse:t?.fetchOptions?.onResponse}},{onSuccess:c,onError:l,onRequest:u,onResponse:a,...i}=t?.fetchOptions||{},d=xe({baseURL:n,...r?{credentials:"include"}:{},method:"GET",jsonParser(f){return f?ke(f,{strict:!1}):null},customFetchImpl:fetch,...i,plugins:[o,...i.plugins||[],...t?.disableDefaultFetchPlugins?[]:[Gt],...s]}),{$sessionSignal:h,session:b}=zt(d),E=t?.plugins||[],L={},R={$sessionSignal:h,session:b},B={"/sign-out":"POST","/revoke-sessions":"POST","/revoke-other-sessions":"POST","/delete-user":"POST"},D=[{signal:"$sessionSignal",matcher(f){return f==="/sign-out"||f==="/update-user"||f.startsWith("/sign-in")||f.startsWith("/sign-up")||f==="/delete-user"||f==="/verify-email"}}];for(let f of E)f.getAtoms&&Object.assign(R,f.getAtoms?.(d)),f.pathMethods&&Object.assign(B,f.pathMethods),f.atomListeners&&D.push(...f.atomListeners);let x={notify:f=>{R[f].set(!R[f].get())},listen:(f,H)=>{R[f].subscribe(H)},atoms:R};for(let f of E)f.getActions&&Object.assign(L,f.getActions?.(d,x,t));return{get baseURL(){return n},pluginsActions:L,pluginsAtoms:R,pluginPathMethods:B,atomListeners:D,$fetch:d,$store:x}};function Kt(t){return typeof t=="object"&&t!==null&&"get"in t&&typeof t.get=="function"&&"lc"in t&&typeof t.lc=="number"}function Jt(t,e,r){let n=e[t],{fetchOptions:s,query:o,...c}=r||{};return n||(s?.method?s.method:c&&Object.keys(c).length>0?"POST":"GET")}function Be(t,e,r,n,s){function o(c=[]){return new Proxy(function(){},{get(l,u){if(typeof u!="string"||u==="then"||u==="catch"||u==="finally")return;let a=[...c,u],i=t;for(let d of a)if(i&&typeof i=="object"&&d in i)i=i[d];else{i=void 0;break}return typeof i=="function"||Kt(i)?i:o(a)},apply:async(l,u,a)=>{let i="/"+c.map(D=>D.replace(/[A-Z]/g,x=>`-${x.toLowerCase()}`)).join("/"),d=a[0]||{},h=a[1]||{},{query:b,fetchOptions:E,...L}=d,R={...h,...E},B=Jt(i,r,d);return await e(i,{...R,body:B==="GET"?void 0:{...L,...R?.body||{}},query:b||R?.query,method:B,async onSuccess(D){if(await R?.onSuccess?.(D),!s)return;let x=s.filter(f=>f.matcher(i));if(x.length)for(let f of x){let H=n[f.signal];if(!H)return;let g=H.get();setTimeout(()=>{H.set(!g)},10)}}})}})}return o()}function He(t){return t.charAt(0).toUpperCase()+t.slice(1)}function fe(t){let{pluginPathMethods:e,pluginsActions:r,pluginsAtoms:n,$fetch:s,atomListeners:o,$store:c}=Me(t),l={};for(let[i,d]of Object.entries(n))l[`use${He(i)}`]=d;let u={...r,...l,$fetch:s,$store:c};return Be(u,s,e,n,o)}function Yt(t){return{authorize(e,r="AND"){let n=!1;for(let[s,o]of Object.entries(e)){let c=t[s];if(!c)return{success:!1,error:`You are not allowed to access resource: ${s}`};if(Array.isArray(o))n=o.every(l=>c.includes(l));else if(typeof o=="object"){let l=o;l.connector==="OR"?n=l.actions.some(u=>c.includes(u)):n=l.actions.every(u=>c.includes(u))}else throw new $("Invalid access control request");if(n&&r==="OR")return{success:n};if(!n&&r==="AND")return{success:!1,error:`unauthorized to access resource "${s}"`}}return n?{success:n}:{success:!1,error:"Not authorized"}},statements:t}}function oe(t){return{newRole(e){return Yt(e)},statements:t}}var Qt={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"],team:["create","update","delete"],ac:["create","read","update","delete"]},pe=oe(Qt),Xt=pe.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"],team:["create","update","delete"],ac:["create","read","update","delete"]}),Zt=pe.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"],team:["create","update","delete"],ac:["create","read","update","delete"]}),er=pe.newRole({organization:[],member:[],invitation:[],team:[],ac:["read"]});var he=class{constructor(){Object.defineProperty(this,"controller",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}createNewAbortSignal(){if(this.controller){let r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}},qe=new he;var or={user:["create","list","set-role","ban","impersonate","delete","set-password","get","update"],session:["list","revoke","delete"]},je=oe(or),ir=je.newRole({user:["create","list","set-role","ban","impersonate","delete","set-password","get","update"],session:["list","revoke","delete"]}),ar=je.newRole({user:[],session:[]});var We=()=>({id:"username",$InferServerPlugin:{}});var Ve="/auth",J="nvwa_login_token",ie="nvwa_user_profile",ge=class{constructor(e,r,n){this.storage=n,this.authClient=fe({baseURL:e,basePath:Ve,fetchOptions:{customFetchImpl:r,auth:{type:"Bearer",token:()=>n.get(J)},onSuccess:s=>{let o=s.response.headers.get("set-auth-token");o&&n.set(J,o)}},plugins:[We()]})}async currentUser(){return await this.storage.get(ie)}async signUp(e,r){let n=await this.authClient.signUp.email({email:e.email??`${e.username}@nvwa.app`,name:e.name,username:e.username,displayUsername:e.displayUsername,password:r});this.saveSession(n)}async signInWithUsername(e,r){let n=await this.authClient.signIn.username({username:e,password:r});this.saveSession(n)}saveSession(e){if(e.error)throw new Error(e.error.message);this.storage.set(J,e.data?.token),this.storage.set(ie,e.data?.user)}async signOut(){await this.storage.remove(J),await this.storage.remove(ie)}async updateUserPassword(e,r,n=!1){let s=await this.authClient.changePassword({currentPassword:e,newPassword:r,revokeOtherSessions:n});this.saveSession(s)}};var ye=class{constructor(e){this.http=e}async invoke(e,r){return(await this.http.request("/functions/"+e,{method:r.method||"POST",data:r.body,headers:r.headers})).body}};var be=class{constructor(e,r,n,s,o){this.ok=e,this.status=r,this.statusText=n,this.headers=s,this.body=o}async text(){return typeof this.body=="string"?this.body:JSON.stringify(this.body)}async json(){if(typeof this.body=="string")try{return JSON.parse(this.body)}catch{return this.body}return this.body}async arrayBuffer(){if(this.body instanceof ArrayBuffer)return this.body;if(typeof this.body=="string")return new TextEncoder().encode(this.body).buffer;throw new Error("Cannot convert body to ArrayBuffer")}async blob(){if(this.body instanceof Blob)return this.body;if(typeof this.body=="string")return new Blob([this.body],{type:this.headers["content-type"]||"text/plain"});throw new Error("Cannot convert body to Blob")}},Re=class{async jsonRequest(e,r){let n={...r,headers:{"Content-Type":"application/json",...r.headers},data:typeof r.data=="object"?JSON.stringify(r.data):r.data};return this.request(e,n)}async jsonRequestWithAuth(e,r,n){let s={...r,headers:{"Content-Type":"application/json",...r.headers},data:typeof r.data=="object"?JSON.stringify(r.data):r.data};return this.requestWithAuth(e,s,n)}};var Ge="/storage",ze=Ge+"/generateUploadUrl",Ee=class{constructor(e,r){this.baseUrl=e,this.http=r}async uploadFile(e){let r=await this.http.request(this.baseUrl+ze,{method:"POST",data:{fileName:e.name||e.fileName,fileSize:e.size||e.fileSize,fileType:e.type||e.fileType}}),{url:n}=r.body;if(!n)throw new Error("\u83B7\u53D6\u4E0A\u4F20URL\u5931\u8D25");return{url:(await this.http.request(n,{method:"PUT",data:e,headers:{"Content-Type":e.type||e.fileType||"application/octet-stream"}})).body.url.split("?")[0]}}};var Ke=require("@supabase/postgrest-js");var v=class t{constructor(e){this.headerMap=new Map;if(e){if(e instanceof t)e.forEach((r,n)=>this.set(n,r));else if(Array.isArray(e))for(let[r,n]of e)this.set(r,String(n));else if(typeof e=="object")for(let r of Object.keys(e))this.set(r,String(e[r]))}}append(e,r){let n=e.toLowerCase(),s=this.headerMap.get(n);this.headerMap.set(n,s?`${s}, ${r}`:r)}set(e,r){this.headerMap.set(e.toLowerCase(),String(r))}get(e){let r=this.headerMap.get(e.toLowerCase());return r??null}has(e){return this.headerMap.has(e.toLowerCase())}delete(e){this.headerMap.delete(e.toLowerCase())}forEach(e){for(let[r,n]of this.headerMap.entries())e(n,r,this)}entries(){return this.headerMap.entries()}keys(){return this.headerMap.keys()}values(){return this.headerMap.values()}[Symbol.iterator](){return this.entries()}},q=class t{constructor(e){this.params=new Map;if(e){if(typeof e=="string")this.parseString(e);else if(e instanceof t)this.params=new Map(e.params);else if(Array.isArray(e))for(let[r,n]of e)this.append(r,n);else if(e&&typeof e=="object")for(let[r,n]of Object.entries(e))this.set(r,n)}}parseString(e){e.startsWith("?")&&(e=e.slice(1));let r=e.split("&");for(let n of r)if(n){let[s,o]=n.split("=");s&&this.append(decodeURIComponent(s),o?decodeURIComponent(o):"")}}append(e,r){let n=this.params.get(e)||[];n.push(r),this.params.set(e,n)}delete(e){this.params.delete(e)}get(e){let r=this.params.get(e);return r?r[0]:null}getAll(e){return this.params.get(e)||[]}has(e){return this.params.has(e)}set(e,r){this.params.set(e,[r])}sort(){let e=Array.from(this.params.entries()).sort(([r],[n])=>r.localeCompare(n));this.params=new Map(e)}toString(){let e=[];for(let[r,n]of this.params.entries())for(let s of n)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(s)}`);return e.join("&")}forEach(e){for(let[r,n]of this.params.entries())for(let s of n)e(s,r,this)}keys(){return this.params.keys()}values(){let e=[];for(let r of this.params.values())e.push(...r);return e[Symbol.iterator]()}entries(){let e=[];for(let[r,n]of this.params.entries())for(let s of n)e.push([r,s]);return e[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}},Y=class t{constructor(e,r){let n;if(e instanceof t)n=e.href;else if(r){let o=r instanceof t?r.href:r;n=this.resolve(o,e)}else n=e;let s=this.parseUrl(n);this.href=n,this.origin=`${s.protocol}//${s.host}`,this.protocol=s.protocol,this.username=s.username,this.password=s.password,this.host=s.host,this.hostname=s.hostname,this.port=s.port,this.pathname=s.pathname,this.search=s.search,this.searchParams=new q(s.search),this.hash=s.hash}resolve(e,r){if(r.startsWith("http://")||r.startsWith("https://"))return r;if(r.startsWith("//"))return`${this.parseUrl(e).protocol}${r}`;if(r.startsWith("/")){let o=this.parseUrl(e);return`${o.protocol}//${o.host}${r}`}let n=this.parseUrl(e),s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return`${n.protocol}//${n.host}${s}${r}`}parseUrl(e){let r=e.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!r)throw new TypeError("Invalid URL");let n=r[2]||"",s=r[4]||"",o=r[5]||"/",c=r[7]?`?${r[7]}`:"",l=r[9]?`#${r[9]}`:"";if(!n&&!s&&!o.startsWith("/")&&!o.includes("/")&&!o.includes("."))throw new TypeError("Invalid URL");let u=s.match(/^([^@]*)@(.+)$/),a="",i="",d=s;if(u){let L=u[1];d=u[2];let R=L.match(/^([^:]*):?(.*)$/);R&&(a=R[1]||"",i=R[2]||"")}let h=d.match(/^([^:]+):?(\d*)$/),b=h?h[1]:d,E=h&&h[2]?h[2]:"";return{protocol:n?`${n}:`:"",username:a,password:i,host:d,hostname:b,port:E,pathname:o,search:c,hash:l}}toString(){let e=this.searchParams.toString(),r=e?`?${e}`:"";return`${this.protocol}//${this.host}${this.pathname}${r}${this.hash}`}toJSON(){return this.toString()}};var Q=class t{constructor(e,r){if(typeof e=="string")this.url=e;else if(e?.url)this.url=String(e.url);else if(typeof e?.toString=="function")this.url=String(e.toString());else throw new Error("Invalid input for Request");this.method=(r?.method||"GET").toUpperCase(),this.headers=r?.headers instanceof v?r.headers:new v(r?.headers),this.body=r?.body,this.timeout=r?.timeout,this.signal=r?.signal||void 0}clone(){return new t(this.url,{method:this.method,headers:this.headers,body:this.body,timeout:this.timeout})}toString(){return this.url}};var M=class{constructor(e,r){this.bodyData=e,this.status=r?.status??200,this.statusText=r?.statusText??"",this.headers=cr(r?.headers),this.ok=this.status>=200&&this.status<300}async text(){return typeof this.bodyData=="string"?this.bodyData:this.bodyData==null?"":typeof this.bodyData=="object"?JSON.stringify(this.bodyData):String(this.bodyData)}async json(){if(typeof this.bodyData=="string")try{return JSON.parse(this.bodyData)}catch{}return this.bodyData}async arrayBuffer(){let e=await this.text();return new TextEncoder().encode(e).buffer}};function cr(t){return t?new v(t):new v}var j=class{constructor(){this._aborted=!1;this.listeners=new Set;this.onabort=null}get aborted(){return this._aborted}_trigger(){if(!this._aborted){if(this._aborted=!0,typeof this.onabort=="function")try{this.onabort()}catch{}for(let e of Array.from(this.listeners))try{e()}catch{}this.listeners.clear()}}addEventListener(e,r){if(this._aborted){try{r()}catch{}return}this.listeners.add(r)}removeEventListener(e,r){this.listeners.delete(r)}toString(){return"[object AbortSignal]"}},X=class{constructor(){this._signal=new j}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}};function lr(t){t.URL=Y,t.URLSearchParams=q,t.Headers=v,t.Request=Q,t.Response=M,t.AbortController=X,t.AbortSignal=j}var Je="/entities",ur=(t,e)=>async(n,s)=>{console.log("customFetch",n,s);let o;if(typeof n=="string")o=n;else if(n&&typeof n=="object")if(typeof n.toString=="function"&&!n.url)o=n.toString();else if(n.url)o=n.url,s||(s={}),s.method=n.method,s.headers=n.headers,s.body=n.body;else throw new Error("Unsupported input type for fetch");else throw new Error("Unsupported input type for fetch");let c=(s?.method||"GET").toUpperCase(),l={};if(s?.headers)if(s.headers&&typeof s.headers.forEach=="function")s.headers.forEach((b,E)=>{l[E]=b});else if(Array.isArray(s.headers))for(let[b,E]of s.headers)l[b]=E;else Object.assign(l,s.headers);let u=s?.body,a;try{a=await t.requestWithAuth(o,{method:c,data:u,headers:l},e)}catch(b){return new M(b?.message||"Internal Error",{status:500,statusText:"Internal Error"})}let i=a.body,d=null;return(a.headers["content-type"]||a.headers["Content-Type"]||"").startsWith("application/json")&&typeof i!="string"?d=JSON.stringify(i):typeof i=="string"||i&&(i.constructor===Blob||i.constructor===ArrayBuffer||typeof i.getReader=="function")?d=i:d=JSON.stringify(i),new M(d,{status:a.status,headers:new v(a.headers)})},dr=(t,e,r)=>new Ke.PostgrestClient(t+Je,{fetch:ur(e,r)});0&&(module.exports={AUTH_BASE_PATH,AbortController,AbortSignal,ENTITIES_BASE_PATH,FILE_STORAGE_BASE_PATH,FetchResponse,GENERATE_UPLOAD_URL_PATH,Headers,LOGIN_TOKEN_KEY,LOGIN_USER_PROFILE_KEY,NvwaAuthClient,NvwaEdgeFunctions,NvwaFileStorage,NvwaHttpClient,Request,Response,URL,URLSearchParams,createPostgrestClient,polyfill});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- var Ft=Object.create;var Xe=Object.defineProperty;var Ht=Object.getOwnPropertyDescriptor;var qt=Object.getOwnPropertyNames;var Wt=Object.getPrototypeOf,Gt=Object.prototype.hasOwnProperty;var zt=(r,e)=>()=>(r&&(e=r(r=0)),e);var H=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Vt=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of qt(e))!Gt.call(r,n)&&n!==t&&Xe(r,n,{get:()=>e[n],enumerable:!(s=Ht(e,n))||s.enumerable});return r};var Kt=(r,e,t)=>(t=r!=null?Ft(Wt(r)):{},Vt(e||!r||!r.__esModule?Xe(t,"default",{value:r,enumerable:!0}):t,r));import ys from"path";import{fileURLToPath as Rs}from"url";var a=zt(()=>{"use strict"});var te=H(_=>{"use strict";a();Object.defineProperty(_,"__esModule",{value:!0});_.File=_.FormData=_.Blob=_.FetchResponse=_.URL=_.URLSearchParams=_.FetchHeaders=void 0;var Z=class{constructor(e){if(this.map=new Map,e)for(let[t,s]of Object.entries(e))this.set(t,s)}get(e){var t;return(t=this.map.get(e))!==null&&t!==void 0?t:null}set(e,t){this.map.set(e,t)}has(e){return this.map.has(e)}append(e,t){let s=this.map.get(e);s?this.map.set(e,`${s}${t}`):this.map.set(e,t)}delete(e){this.map.delete(e)}forEach(e){this.map.forEach(e)}size(){return this.map.size}keys(){return this.map.keys()}values(){return this.map.values()}entries(){return this.map.entries()}headers(){return Object.fromEntries(this.map.entries())}[Symbol.iterator](){return this.map[Symbol.iterator]()}};_.FetchHeaders=Z;var Re=class r{constructor(e){if(this.params=new Map,e){if(typeof e=="string")this.parseString(e);else if(e instanceof r)this.params=new Map(e.params);else if(Array.isArray(e))for(let[t,s]of e)this.append(t,s);else if(e&&typeof e=="object")for(let[t,s]of Object.entries(e))this.set(t,s)}}parseString(e){e.startsWith("?")&&(e=e.slice(1));let t=e.split("&");for(let s of t)if(s){let[n,o]=s.split("=");n&&this.append(decodeURIComponent(n),o?decodeURIComponent(o):"")}}append(e,t){let s=this.params.get(e)||[];s.push(t),this.params.set(e,s)}delete(e){this.params.delete(e)}get(e){let t=this.params.get(e);return t?t[0]:null}getAll(e){return this.params.get(e)||[]}has(e){return this.params.has(e)}set(e,t){this.params.set(e,[t])}sort(){let e=Array.from(this.params.entries()).sort(([t],[s])=>t.localeCompare(s));this.params=new Map(e)}toString(){let e=[];for(let[t,s]of this.params.entries())for(let n of s)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(n)}`);return e.join("&")}forEach(e){for(let[t,s]of this.params.entries())for(let n of s)e(n,t,this)}keys(){return this.params.keys()}values(){let e=[];for(let t of this.params.values())e.push(...t);return e[Symbol.iterator]()}entries(){let e=[];for(let[t,s]of this.params.entries())for(let n of s)e.push([t,n]);return e[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}};_.URLSearchParams=Re;var we=class r{constructor(e,t){let s;if(e instanceof r)s=e.href;else if(t){let o=t instanceof r?t.href:t;s=this.resolve(o,e)}else s=e;let n=this.parseUrl(s);this.href=s,this.origin=`${n.protocol}//${n.host}`,this.protocol=n.protocol,this.username=n.username,this.password=n.password,this.host=n.host,this.hostname=n.hostname,this.port=n.port,this.pathname=n.pathname,this.search=n.search,this.searchParams=new Re(n.search),this.hash=n.hash}resolve(e,t){if(t.startsWith("http://")||t.startsWith("https://"))return t;if(t.startsWith("//"))return`${this.parseUrl(e).protocol}${t}`;if(t.startsWith("/")){let o=this.parseUrl(e);return`${o.protocol}//${o.host}${t}`}let s=this.parseUrl(e),n=s.pathname.endsWith("/")?s.pathname:s.pathname+"/";return`${s.protocol}//${s.host}${n}${t}`}parseUrl(e){let t=e.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!t)throw new TypeError("Invalid URL");let s=t[2]||"",n=t[4]||"",o=t[5]||"/",i=t[7]?`?${t[7]}`:"",c=t[9]?`#${t[9]}`:"";if(!s&&!n&&!o.startsWith("/")&&!o.includes("/")&&!o.includes("."))throw new TypeError("Invalid URL");let d=n.match(/^([^@]*)@(.+)$/),u="",l="",h=n;if(d){let x=d[1];h=d[2];let b=x.match(/^([^:]*):?(.*)$/);b&&(u=b[1]||"",l=b[2]||"")}let m=h.match(/^([^:]+):?(\d*)$/),w=m?m[1]:h,v=m&&m[2]?m[2]:"";return{protocol:s?`${s}:`:"",username:u,password:l,host:h,hostname:w,port:v,pathname:o,search:i,hash:c}}toString(){let e=this.searchParams.toString(),t=e?`?${e}`:"";return`${this.protocol}//${this.host}${this.pathname}${t}${this.hash}`}toJSON(){return this.toString()}};_.URL=we;var De=class r{constructor(e,t){var s,n;this.status=(s=t?.status)!==null&&s!==void 0?s:200,this.statusText=(n=t?.statusText)!==null&&n!==void 0?n:"",this.headers=new Z(t?.headers),this.ok=this.status>=200&&this.status<300,this.redirected=!1,this.url="",this.bodyUsed=!1,this.body=e||null}async arrayBuffer(){if(this.bodyUsed)throw new TypeError("Body has already been consumed");return this.bodyUsed=!0,this.body===null?new ArrayBuffer(0):new TextEncoder().encode(this.body).buffer}async blob(){if(this.bodyUsed)throw new TypeError("Body has already been consumed");return this.bodyUsed=!0,new ee([this.body||""])}async formData(){if(this.bodyUsed)throw new TypeError("Body has already been consumed");return this.bodyUsed=!0,new Ee}async json(){if(this.bodyUsed)throw new TypeError("Body has already been consumed");return this.bodyUsed=!0,this.body===null?null:JSON.parse(this.body)}async text(){if(this.bodyUsed)throw new TypeError("Body has already been consumed");return this.bodyUsed=!0,this.body||""}clone(){if(this.bodyUsed)throw new TypeError("Body has already been consumed");return new r(this.body,{status:this.status,statusText:this.statusText,headers:this.headers.headers()})}static error(){let e=new r(null,{status:0,statusText:""});return Object.defineProperty(e,"type",{value:"error",writable:!1}),e}static redirect(e,t=302){let s=e instanceof we?e.href:e,n=new r(null,{status:t,statusText:"Found"});return n.headers.set("Location",s),n}static json(e,t){let s=JSON.stringify(e),n=new Z(t?.headers);return n.set("Content-Type","application/json"),new r(s,Object.assign(Object.assign({},t),{headers:n.headers()}))}};_.FetchResponse=De;var ee=class r{constructor(e,t){this._content=e||[],this.type=t?.type||"";let s=0;for(let n of this._content)typeof n=="string"?s+=new TextEncoder().encode(n).length:n instanceof ArrayBuffer?s+=n.byteLength:n instanceof Uint8Array&&(s+=n.length);this.size=s}async text(){let e="";for(let t of this._content)typeof t=="string"?e+=t:t instanceof ArrayBuffer?e+=new TextDecoder().decode(t):t instanceof Uint8Array&&(e+=new TextDecoder().decode(t));return e}async arrayBuffer(){let e=await this.text();return new TextEncoder().encode(e).buffer}slice(e,t,s){return new r(this._content.slice(e,t),{type:s})}};_.Blob=ee;var Ee=class{constructor(){this._entries=[]}append(e,t,s){this._entries.push([e,t])}delete(e){this._entries=this._entries.filter(([t])=>t!==e)}get(e){let t=this._entries.find(([s])=>s===e);return t?t[1]:null}getAll(e){return this._entries.filter(([t])=>t===e).map(([,t])=>t)}has(e){return this._entries.some(([t])=>t===e)}set(e,t,s){this.delete(e),this.append(e,t,s)}forEach(e){for(let[t,s]of this._entries)e(s,t,this)}keys(){return this._entries.map(([e])=>e)[Symbol.iterator]()}values(){return this._entries.map(([,e])=>e)[Symbol.iterator]()}entries(){return this._entries[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}};_.FormData=Ee;var ke=class extends ee{constructor(e,t,s){super(e,s),this.name=t,this.lastModified=s?.lastModified||Date.now()}};_.File=ke});var je=H(Be=>{"use strict";a();Object.defineProperty(Be,"__esModule",{value:!0});var Me=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};Be.default=Me});var He=H(re=>{"use strict";a();var ts=re&&re.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(re,"__esModule",{value:!0});var rs=ts(je()),Pt=te(),Fe=class{constructor(e){var t,s;this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=new Pt.FetchHeaders(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=(t=e.shouldThrowOnError)!==null&&t!==void 0?t:!1,this.signal=e.signal,this.isMaybeSingle=(s=e.isMaybeSingle)!==null&&s!==void 0?s:!1,e.fetch?this.fetch=e.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=new Pt.FetchHeaders(this.headers),this.headers.set(e,t),this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");let s=this.fetch,n=s(this.url.toString(),{method:this.method,headers:this.headers.headers(),body:JSON.stringify(this.body),signal:this.signal}).then(async o=>{var i,c,d,u;let l=null,h=null,m=null,w=o.status,v=o.statusText;if(o.ok){if(this.method!=="HEAD"){let P=await o.text();P===""||(this.headers.get("Accept")==="text/csv"||this.headers.get("Accept")&&(!((i=this.headers.get("Accept"))===null||i===void 0)&&i.includes("application/vnd.pgrst.plan+text"))?h=P:h=JSON.parse(P))}let b=(c=this.headers.get("Prefer"))===null||c===void 0?void 0:c.match(/count=(exact|planned|estimated)/),U=(d=o.headers.get("content-range"))===null||d===void 0?void 0:d.split("/");b&&U&&U.length>1&&(m=parseInt(U[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(h)&&(h.length>1?(l={code:"PGRST116",details:`Results contain ${h.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},h=null,m=null,w=406,v="Not Acceptable"):h.length===1?h=h[0]:h=null)}else{let b=await o.text();try{l=JSON.parse(b),Array.isArray(l)&&o.status===404&&(h=[],l=null,w=200,v="OK")}catch{o.status===404&&b===""?(w=204,v="No Content"):l={message:b}}if(l&&this.isMaybeSingle&&(!((u=l?.details)===null||u===void 0)&&u.includes("0 rows"))&&(l=null,w=200,v="OK"),l&&this.shouldThrowOnError)throw new rs.default(l)}return{error:l,data:h,count:m,status:w,statusText:v}});return this.shouldThrowOnError||(n=n.catch(o=>{var i,c,d;return{error:{message:`${(i=o?.name)!==null&&i!==void 0?i:"FetchError"}: ${o?.message}`,details:`${(c=o?.stack)!==null&&c!==void 0?c:""}`,hint:"",code:`${(d=o?.code)!==null&&d!==void 0?d:""}`},data:null,count:null,status:0,statusText:""}})),n.then(e,t)}returns(){return this}overrideTypes(){return this}};re.default=Fe});var We=H(se=>{"use strict";a();var ss=se&&se.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(se,"__esModule",{value:!0});var ns=ss(He()),qe=class extends ns.default{select(e){let t=!1,s=(e??"*").split("").map(n=>/\s/.test(n)&&!t?"":(n==='"'&&(t=!t),n)).join("");return this.url.searchParams.set("select",s),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:s,foreignTable:n,referencedTable:o=n}={}){let i=o?`${o}.order`:"order",c=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${c?`${c},`:""}${e}.${t?"asc":"desc"}${s===void 0?"":s?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:s=t}={}){let n=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(n,`${e}`),this}range(e,t,{foreignTable:s,referencedTable:n=s}={}){let o=typeof n>"u"?"offset":`${n}.offset`,i=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(o,`${e}`),this.url.searchParams.set(i,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.method==="GET"?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:e=!1,verbose:t=!1,settings:s=!1,buffers:n=!1,wal:o=!1,format:i="text"}={}){var c;let d=[e?"analyze":null,t?"verbose":null,s?"settings":null,n?"buffers":null,o?"wal":null].filter(Boolean).join("|"),u=(c=this.headers.get("Accept"))!==null&&c!==void 0?c:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${u}"; options=${d};`),i==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}};se.default=qe});var ve=H(ne=>{"use strict";a();var os=ne&&ne.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ne,"__esModule",{value:!0});var as=os(We()),Ge=class extends as.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let s=Array.from(new Set(t)).map(n=>typeof n=="string"&&new RegExp("[,()]").test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(e,`in.(${s})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:s,type:n}={}){let o="";n==="plain"?o="pl":n==="phrase"?o="ph":n==="websearch"&&(o="w");let i=s===void 0?"":`(${s})`;return this.url.searchParams.append(e,`${o}fts${i}.${t}`),this}match(e){return Object.entries(e).forEach(([t,s])=>{this.url.searchParams.append(t,`eq.${s}`)}),this}not(e,t,s){return this.url.searchParams.append(e,`not.${t}.${s}`),this}or(e,{foreignTable:t,referencedTable:s=t}={}){let n=s?`${s}.or`:"or";return this.url.searchParams.append(n,`(${e})`),this}filter(e,t,s){return this.url.searchParams.append(e,`${t}.${s}`),this}};ne.default=Ge});var Ve=H(ae=>{"use strict";a();var is=ae&&ae.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ae,"__esModule",{value:!0});var ls=te(),oe=is(ve()),ze=class{constructor(e,{headers:t={},schema:s,fetch:n}){this.url=e,this.headers=new ls.FetchHeaders(t),this.schema=s,this.fetch=n}select(e,t){let{head:s=!1,count:n}=t??{},o=s?"HEAD":"GET",i=!1,c=(e??"*").split("").map(d=>/\s/.test(d)&&!i?"":(d==='"'&&(i=!i),d)).join("");return this.url.searchParams.set("select",c),n&&this.headers.append("Prefer",`count=${n}`),new oe.default({method:o,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch})}insert(e,{count:t,defaultToNull:s=!0}={}){var n;let o="POST";if(t&&this.headers.append("Prefer",`count=${t}`),s||this.headers.append("Prefer","missing=default"),Array.isArray(e)){let i=e.reduce((c,d)=>c.concat(Object.keys(d)),[]);if(i.length>0){let c=[...new Set(i)].map(d=>`"${d}"`);this.url.searchParams.set("columns",c.join(","))}}return new oe.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch})}upsert(e,{onConflict:t,ignoreDuplicates:s=!1,count:n,defaultToNull:o=!0}={}){var i;let c="POST";if(this.headers.append("Prefer",`resolution=${s?"ignore":"merge"}-duplicates`),t!==void 0&&this.url.searchParams.set("on_conflict",t),n&&this.headers.append("Prefer",`count=${n}`),o||this.headers.append("Prefer","missing=default"),Array.isArray(e)){let d=e.reduce((u,l)=>u.concat(Object.keys(l)),[]);if(d.length>0){let u=[...new Set(d)].map(l=>`"${l}"`);this.url.searchParams.set("columns",u.join(","))}}return new oe.default({method:c,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch})}update(e,{count:t}={}){var s;let n="PATCH";return t&&this.headers.append("Prefer",`count=${t}`),new oe.default({method:n,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch})}delete({count:e}={}){var t;let s="DELETE";return e&&this.headers.append("Prefer",`count=${e}`),new oe.default({method:s,url:this.url,headers:this.headers,schema:this.schema,fetch:(t=this.fetch)!==null&&t!==void 0?t:fetch})}};ae.default=ze});var Ot=H(le=>{"use strict";a();var At=le&&le.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(le,"__esModule",{value:!0});var cs=At(Ve()),us=At(ve()),ie=te(),Ke=class r{constructor(e,{headers:t={},schema:s,fetch:n}={}){this.url=e,this.headers=new ie.FetchHeaders(t),this.schemaName=s,this.fetch=n}from(e){let t=new ie.URL(`${this.url}/${e}`);return new cs.default(t,{headers:new ie.FetchHeaders(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new r(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:s=!1,get:n=!1,count:o}={}){var i;let c,d=new ie.URL(`${this.url}/rpc/${e}`),u;s||n?(c=s?"HEAD":"GET",Object.entries(t).filter(([h,m])=>m!==void 0).map(([h,m])=>[h,Array.isArray(m)?`{${m.join(",")}}`:`${m}`]).forEach(([h,m])=>{d.searchParams.append(h,m)})):(c="POST",u=t);let l=new ie.FetchHeaders(this.headers);return o&&l.set("Prefer",`count=${o}`),new us.default({method:c,url:d,headers:l,schema:this.schemaName,body:u,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch})}};le.default=Ke});var $t=H(y=>{"use strict";a();var V=y&&y.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(y,"__esModule",{value:!0});y.File=y.FormData=y.Blob=y.FetchResponse=y.FetchHeaders=y.URLSearchParams=y.URL=y.PostgrestError=y.PostgrestBuilder=y.PostgrestTransformBuilder=y.PostgrestFilterBuilder=y.PostgrestQueryBuilder=y.PostgrestClient=void 0;var Ut=V(Ot());y.PostgrestClient=Ut.default;var It=V(Ve());y.PostgrestQueryBuilder=It.default;var xt=V(ve());y.PostgrestFilterBuilder=xt.default;var Ct=V(We());y.PostgrestTransformBuilder=Ct.default;var Nt=V(He());y.PostgrestBuilder=Nt.default;var Lt=V(je());y.PostgrestError=Lt.default;var k=te();Object.defineProperty(y,"FetchHeaders",{enumerable:!0,get:function(){return k.FetchHeaders}});Object.defineProperty(y,"FetchResponse",{enumerable:!0,get:function(){return k.FetchResponse}});Object.defineProperty(y,"URL",{enumerable:!0,get:function(){return k.URL}});Object.defineProperty(y,"URLSearchParams",{enumerable:!0,get:function(){return k.URLSearchParams}});Object.defineProperty(y,"Blob",{enumerable:!0,get:function(){return k.Blob}});Object.defineProperty(y,"FormData",{enumerable:!0,get:function(){return k.FormData}});Object.defineProperty(y,"File",{enumerable:!0,get:function(){return k.File}});y.default={PostgrestClient:Ut.default,PostgrestQueryBuilder:It.default,PostgrestFilterBuilder:xt.default,PostgrestTransformBuilder:Ct.default,PostgrestBuilder:Nt.default,PostgrestError:Lt.default,URLSearchParams:k.URLSearchParams,FetchHeaders:k.FetchHeaders,FetchResponse:k.FetchResponse}});a();a();a();a();a();a();var Jt=Object.defineProperty,Yt=Object.defineProperties,Qt=Object.getOwnPropertyDescriptors,Ze=Object.getOwnPropertySymbols,Xt=Object.prototype.hasOwnProperty,Zt=Object.prototype.propertyIsEnumerable,et=(r,e,t)=>e in r?Jt(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,C=(r,e)=>{for(var t in e||(e={}))Xt.call(e,t)&&et(r,t,e[t]);if(Ze)for(var t of Ze(e))Zt.call(e,t)&&et(r,t,e[t]);return r},L=(r,e)=>Yt(r,Qt(e)),er=class extends Error{constructor(r,e,t){super(e||r.toString(),{cause:t}),this.status=r,this.statusText=e,this.error=t}},tr=async(r,e)=>{var t,s,n,o,i,c;let d=e||{},u={onRequest:[e?.onRequest],onResponse:[e?.onResponse],onSuccess:[e?.onSuccess],onError:[e?.onError],onRetry:[e?.onRetry]};if(!e||!e?.plugins)return{url:r,options:d,hooks:u};for(let l of e?.plugins||[]){if(l.init){let h=await((t=l.init)==null?void 0:t.call(l,r.toString(),e));d=h.options||d,r=h.url}u.onRequest.push((s=l.hooks)==null?void 0:s.onRequest),u.onResponse.push((n=l.hooks)==null?void 0:n.onResponse),u.onSuccess.push((o=l.hooks)==null?void 0:o.onSuccess),u.onError.push((i=l.hooks)==null?void 0:i.onError),u.onRetry.push((c=l.hooks)==null?void 0:c.onRetry)}return{url:r,options:d,hooks:u}},tt=class{constructor(r){this.options=r}shouldAttemptRetry(r,e){return this.options.shouldRetry?Promise.resolve(r<this.options.attempts&&this.options.shouldRetry(e)):Promise.resolve(r<this.options.attempts)}getDelay(){return this.options.delay}},rr=class{constructor(r){this.options=r}shouldAttemptRetry(r,e){return this.options.shouldRetry?Promise.resolve(r<this.options.attempts&&this.options.shouldRetry(e)):Promise.resolve(r<this.options.attempts)}getDelay(r){return Math.min(this.options.maxDelay,this.options.baseDelay*2**r)}};function sr(r){if(typeof r=="number")return new tt({type:"linear",attempts:r,delay:1e3});switch(r.type){case"linear":return new tt(r);case"exponential":return new rr(r);default:throw new Error("Invalid retry strategy")}}var nr=async r=>{let e={},t=async s=>typeof s=="function"?await s():s;if(r?.auth){if(r.auth.type==="Bearer"){let s=await t(r.auth.token);if(!s)return e;e.authorization=`Bearer ${s}`}else if(r.auth.type==="Basic"){let s=t(r.auth.username),n=t(r.auth.password);if(!s||!n)return e;e.authorization=`Basic ${btoa(`${s}:${n}`)}`}else if(r.auth.type==="Custom"){let s=t(r.auth.value);if(!s)return e;e.authorization=`${t(r.auth.prefix)} ${s}`}}return e},or=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function ar(r){let e=r.headers.get("content-type"),t=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!e)return"json";let s=e.split(";").shift()||"";return or.test(s)?"json":t.has(s)||s.startsWith("text/")?"text":"blob"}function ir(r){try{return JSON.parse(r),!0}catch{return!1}}function nt(r){if(r===void 0)return!1;let e=typeof r;return e==="string"||e==="number"||e==="boolean"||e===null?!0:e!=="object"?!1:Array.isArray(r)?!0:r.buffer?!1:r.constructor&&r.constructor.name==="Object"||typeof r.toJSON=="function"}function rt(r){try{return JSON.parse(r)}catch{return r}}function st(r){return typeof r=="function"}function lr(r){if(r?.customFetchImpl)return r.customFetchImpl;if(typeof globalThis<"u"&&st(globalThis.fetch))return globalThis.fetch;if(typeof window<"u"&&st(window.fetch))return window.fetch;throw new Error("No fetch implementation found")}async function cr(r){let e=new Headers(r?.headers),t=await nr(r);for(let[s,n]of Object.entries(t||{}))e.set(s,n);if(!e.has("content-type")){let s=ur(r?.body);s&&e.set("content-type",s)}return e}function ur(r){return nt(r)?"application/json":null}function dr(r){if(!r?.body)return null;let e=new Headers(r?.headers);if(nt(r.body)&&!e.has("content-type")){for(let[t,s]of Object.entries(r?.body))s instanceof Date&&(r.body[t]=s.toISOString());return JSON.stringify(r.body)}return r.body}function hr(r,e){var t;if(e?.method)return e.method.toUpperCase();if(r.startsWith("@")){let s=(t=r.split("@")[1])==null?void 0:t.split("/")[0];return at.includes(s)?s.toUpperCase():e?.body?"POST":"GET"}return e?.body?"POST":"GET"}function fr(r,e){let t;return!r?.signal&&r?.timeout&&(t=setTimeout(()=>e?.abort(),r?.timeout)),{abortTimeout:t,clearTimeout:()=>{t&&clearTimeout(t)}}}var pr=class ot extends Error{constructor(e,t){super(t||JSON.stringify(e,null,2)),this.issues=e,Object.setPrototypeOf(this,ot.prototype)}};async function he(r,e){let t=await r["~standard"].validate(e);if(t.issues)throw new pr(t.issues);return t.value}var at=["get","post","put","patch","delete"];var mr=r=>({id:"apply-schema",name:"Apply Schema",version:"1.0.0",async init(e,t){var s,n,o,i;let c=((n=(s=r.plugins)==null?void 0:s.find(d=>{var u;return(u=d.schema)!=null&&u.config?e.startsWith(d.schema.config.baseURL||"")||e.startsWith(d.schema.config.prefix||""):!1}))==null?void 0:n.schema)||r.schema;if(c){let d=e;(o=c.config)!=null&&o.prefix&&d.startsWith(c.config.prefix)&&(d=d.replace(c.config.prefix,""),c.config.baseURL&&(e=e.replace(c.config.prefix,c.config.baseURL))),(i=c.config)!=null&&i.baseURL&&d.startsWith(c.config.baseURL)&&(d=d.replace(c.config.baseURL,""));let u=c.schema[d];if(u){let l=L(C({},t),{method:u.method,output:u.output});return t?.disableValidation||(l=L(C({},l),{body:u.input?await he(u.input,t?.body):t?.body,params:u.params?await he(u.params,t?.params):t?.params,query:u.query?await he(u.query,t?.query):t?.query})),{url:e,options:l}}}return{url:e,options:t}}}),it=r=>{async function e(t,s){let n=L(C(C({},r),s),{plugins:[...r?.plugins||[],mr(r||{})]});if(r?.catchAllError)try{return await Oe(t,n)}catch(o){return{data:null,error:{status:500,statusText:"Fetch Error",message:"Fetch related error. Captured by catchAllError option. See error property for more details.",error:o}}}return await Oe(t,n)}return e};function gr(r,e){let{baseURL:t,params:s,query:n}=e||{query:{},params:{},baseURL:""},o=r.startsWith("http")?r.split("/").slice(0,3).join("/"):t||"";if(r.startsWith("@")){let h=r.toString().split("@")[1].split("/")[0];at.includes(h)&&(r=r.replace(`@${h}/`,"/"))}o.endsWith("/")||(o+="/");let[i,c]=r.replace(o,"").split("?"),d=new URLSearchParams(c);for(let[h,m]of Object.entries(n||{}))m!=null&&d.set(h,String(m));if(s)if(Array.isArray(s)){let h=i.split("/").filter(m=>m.startsWith(":"));for(let[m,w]of h.entries()){let v=s[m];i=i.replace(w,v)}}else for(let[h,m]of Object.entries(s))i=i.replace(`:${h}`,String(m));i=i.split("/").map(encodeURIComponent).join("/"),i.startsWith("/")&&(i=i.slice(1));let u=d.toString();return u=u.length>0?`?${u}`.replace(/\+/g,"%20"):"",o.startsWith("http")?new URL(`${i}${u}`,o):`${o}${i}${u}`}var Oe=async(r,e)=>{var t,s,n,o,i,c,d,u;let{hooks:l,url:h,options:m}=await tr(r,e),w=lr(m),v=new AbortController,x=(t=m.signal)!=null?t:v.signal,b=gr(h,m),U=dr(m),P=await cr(m),B=hr(h,m),g=L(C({},m),{url:b,headers:P,body:U,method:B,signal:x});for(let I of l.onRequest)if(I){let S=await I(g);S instanceof Object&&(g=S)}("pipeTo"in g&&typeof g.pipeTo=="function"||typeof((s=e?.body)==null?void 0:s.pipe)=="function")&&("duplex"in g||(g.duplex="half"));let{clearTimeout:W}=fr(m,v),E=await w(g.url,g);W();let Ye={response:E,request:g};for(let I of l.onResponse)if(I){let S=await I(L(C({},Ye),{response:(n=e?.hookOptions)!=null&&n.cloneResponse?E.clone():E}));S instanceof Response?E=S:S instanceof Object&&(E=S.response)}if(E.ok){if(!(g.method!=="HEAD"))return{data:"",error:null};let S=ar(E),j={data:"",response:E,request:g};if(S==="json"||S==="text"){let F=await E.text(),jt=await((o=g.jsonParser)!=null?o:rt)(F);j.data=jt}else j.data=await E[S]();g?.output&&g.output&&!g.disableValidation&&(j.data=await he(g.output,j.data));for(let F of l.onSuccess)F&&await F(L(C({},j),{response:(i=e?.hookOptions)!=null&&i.cloneResponse?E.clone():E}));return e?.throw?j.data:{data:j.data,error:null}}let Mt=(c=e?.jsonParser)!=null?c:rt,de=await E.text(),Qe=ir(de),Ae=Qe?await Mt(de):null,Bt={response:E,responseText:de,request:g,error:L(C({},Ae),{status:E.status,statusText:E.statusText})};for(let I of l.onError)I&&await I(L(C({},Bt),{response:(d=e?.hookOptions)!=null&&d.cloneResponse?E.clone():E}));if(e?.retry){let I=sr(e.retry),S=(u=e.retryAttempt)!=null?u:0;if(await I.shouldAttemptRetry(S,E)){for(let F of l.onRetry)F&&await F(Ye);let j=I.getDelay(S);return await new Promise(F=>setTimeout(F,j)),await Oe(r,L(C({},e),{retryAttempt:S+1}))}}if(e?.throw)throw new er(E.status,E.statusText,Qe?Ae:de);return{data:null,error:L(C({},Ae),{status:E.status,statusText:E.statusText})}};a();a();var fe=Object.create(null),K=r=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(r?fe:globalThis),O=new Proxy(fe,{get(r,e){return K()[e]??fe[e]},has(r,e){let t=K();return e in t||e in fe},set(r,e,t){let s=K(!0);return s[e]=t,!0},deleteProperty(r,e){if(!e)return!1;let t=K(!0);return delete t[e],!0},ownKeys(){let r=K(!0);return Object.keys(r)}});var Ps=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";function R(r,e){return typeof process<"u"&&process.env?process.env[r]??e:typeof Deno<"u"?Deno.env.get(r)??e:typeof Bun<"u"?Bun.env[r]??e:e}var As=Object.freeze({get BETTER_AUTH_SECRET(){return R("BETTER_AUTH_SECRET")},get AUTH_SECRET(){return R("AUTH_SECRET")},get BETTER_AUTH_TELEMETRY(){return R("BETTER_AUTH_TELEMETRY")},get BETTER_AUTH_TELEMETRY_ID(){return R("BETTER_AUTH_TELEMETRY_ID")},get NODE_ENV(){return R("NODE_ENV","development")},get PACKAGE_VERSION(){return R("PACKAGE_VERSION","0.0.0")},get BETTER_AUTH_TELEMETRY_ENDPOINT(){return R("BETTER_AUTH_TELEMETRY_ENDPOINT","https://telemetry.better-auth.com/v1/track")}}),J=1,T=4,$=8,A=24,lt={eterm:T,cons25:T,console:T,cygwin:T,dtterm:T,gnome:T,hurd:T,jfbterm:T,konsole:T,kterm:T,mlterm:T,mosh:A,putty:T,st:T,"rxvt-unicode-24bit":A,terminator:A,"xterm-kitty":A},yr=new Map(Object.entries({APPVEYOR:$,BUILDKITE:$,CIRCLECI:A,DRONE:$,GITEA_ACTIONS:A,GITHUB_ACTIONS:A,GITLAB_CI:$,TRAVIS:$})),br=[/ansi/,/color/,/linux/,/direct/,/^con[0-9]*x[0-9]/,/^rxvt/,/^screen/,/^xterm/,/^vt100/,/^vt220/];function Rr(){if(R("FORCE_COLOR")!==void 0)switch(R("FORCE_COLOR")){case"":case"1":case"true":return T;case"2":return $;case"3":return A;default:return J}if(R("NODE_DISABLE_COLORS")!==void 0&&R("NODE_DISABLE_COLORS")!==""||R("NO_COLOR")!==void 0&&R("NO_COLOR")!==""||R("TERM")==="dumb")return J;if(R("TMUX"))return A;if("TF_BUILD"in O&&"AGENT_NAME"in O)return T;if("CI"in O){for(let{0:r,1:e}of yr)if(r in O)return e;return R("CI_NAME")==="codeship"?$:J}if("TEAMCITY_VERSION"in O)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.exec(R("TEAMCITY_VERSION"))!==null?T:J;switch(R("TERM_PROGRAM")){case"iTerm.app":return!R("TERM_PROGRAM_VERSION")||/^[0-2]\./.exec(R("TERM_PROGRAM_VERSION"))!==null?$:A;case"HyperTerm":case"MacTerm":return A;case"Apple_Terminal":return $}if(R("COLORTERM")==="truecolor"||R("COLORTERM")==="24bit")return A;if(R("TERM")){if(/truecolor/.exec(R("TERM"))!==null)return A;if(/^xterm-256/.exec(R("TERM"))!==null)return $;let r=R("TERM").toLowerCase();if(lt[r])return lt[r];if(br.some(e=>e.exec(r)!==null))return T}return R("COLORTERM")?T:J}var D={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",undim:"\x1B[22m",underscore:"\x1B[4m",blink:"\x1B[5m",reverse:"\x1B[7m",hidden:"\x1B[8m",fg:{black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"},bg:{black:"\x1B[40m",red:"\x1B[41m",green:"\x1B[42m",yellow:"\x1B[43m",blue:"\x1B[44m",magenta:"\x1B[45m",cyan:"\x1B[46m",white:"\x1B[47m"}},Ue=["info","success","warn","error","debug"];function wr(r,e){return Ue.indexOf(e)<=Ue.indexOf(r)}var Er={info:D.fg.blue,success:D.fg.green,warn:D.fg.yellow,error:D.fg.red,debug:D.fg.magenta},vr=(r,e,t)=>{let s=new Date().toISOString();return t?`${D.dim}${s}${D.reset} ${Er[r]}${r.toUpperCase()}${D.reset} ${D.bright}[Better Auth]:${D.reset} ${e}`:`${s} ${r.toUpperCase()} [Better Auth]: ${e}`},Tr=r=>{let e=r?.disabled!==!0,t=r?.level??"error",n=r?.disableColors!==void 0?!r.disableColors:Rr()!==1,o=(c,d,u=[])=>{if(!e||!wr(t,c))return;let l=vr(c,d,n);if(!r||typeof r.log!="function"){c==="error"?console.error(l,...u):c==="warn"?console.warn(l,...u):console.log(l,...u);return}r.log(c==="success"?"info":c,d,...u)};return{...Object.fromEntries(Ue.map(c=>[c,(...[d,...u])=>o(c,d,u)])),get level(){return t}}},Os=Tr();a();a();var $s={USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_USER:"Failed to create user",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_UPDATE_USER:"Failed to update user",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"Invalid token",ID_TOKEN_NOT_SUPPORTED:"id_token not supported",FAILED_TO_GET_USER_INFO:"Failed to get user info",USER_EMAIL_NOT_FOUND:"User email not found",EMAIL_NOT_VERIFIED:"Email not verified",PASSWORD_TOO_SHORT:"Password too short",PASSWORD_TOO_LONG:"Password too long",USER_ALREADY_EXISTS:"User already exists.",USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL:"User already exists. Use another email.",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found",SESSION_EXPIRED:"Session expired. Re-authenticate to perform this action.",FAILED_TO_UNLINK_LAST_ACCOUNT:"You can't unlink your last account",ACCOUNT_NOT_FOUND:"Account not found",USER_ALREADY_HAS_PASSWORD:"User already has a password. Provide that to delete the account."},G=class extends Error{constructor(e,t){super(e),this.name="BetterAuthError",this.message=e,this.cause=t,this.stack=""}};function _r(r){try{return(new URL(r).pathname.replace(/\/+$/,"")||"/")!=="/"}catch{throw new G(`Invalid base URL: ${r}. Please provide a valid base URL.`)}}function Y(r,e="/api/auth"){if(_r(r))return r;let s=r.replace(/\/+$/,"");return!e||e==="/"?s:(e=e.startsWith("/")?e:`/${e}`,`${s}${e}`)}function ct(r,e,t,s){if(r)return Y(r,e);if(s!==!1){let i=O.BETTER_AUTH_URL||O.NEXT_PUBLIC_BETTER_AUTH_URL||O.PUBLIC_BETTER_AUTH_URL||O.NUXT_PUBLIC_BETTER_AUTH_URL||O.NUXT_PUBLIC_AUTH_URL||(O.BASE_URL!=="/"?O.BASE_URL:void 0);if(i)return Y(i,e)}let n=t?.headers.get("x-forwarded-host"),o=t?.headers.get("x-forwarded-proto");if(n&&o)return Y(`${o}://${n}`,e);if(t){let i=Sr(t.url);if(!i)throw new G("Could not get origin from request. Please provide a valid base URL.");return Y(i,e)}if(typeof window<"u"&&window.location)return Y(window.location.origin,e)}function Sr(r){try{return new URL(r).origin}catch{return null}}a();a();a();var Q=Symbol("clean");var N=[],q=0,pe=4,Pr=0,X=r=>{let e=[],t={get(){return t.lc||t.listen(()=>{})(),t.value},lc:0,listen(s){return t.lc=e.push(s),()=>{for(let o=q+pe;o<N.length;)N[o]===s?N.splice(o,pe):o+=pe;let n=e.indexOf(s);~n&&(e.splice(n,1),--t.lc||t.off())}},notify(s,n){Pr++;let o=!N.length;for(let i of e)N.push(i,t.value,s,n);if(o){for(q=0;q<N.length;q+=pe)N[q](N[q+1],N[q+2],N[q+3]);N.length=0}},off(){},set(s){let n=t.value;n!==s&&(t.value=s,t.notify(n))},subscribe(s){let n=t.listen(s);return s(t.value),n},value:r};return process.env.NODE_ENV!=="production"&&(t[Q]=()=>{e=[],t.lc=0,t.off()}),t};a();var Ar=5,z=6,me=10,Or=(r,e,t,s)=>(r.events=r.events||{},r.events[t+me]||(r.events[t+me]=s(n=>{r.events[t].reduceRight((o,i)=>(i(o),o),{shared:{},...n})})),r.events[t]=r.events[t]||[],r.events[t].push(e),()=>{let n=r.events[t],o=n.indexOf(e);n.splice(o,1),n.length||(delete r.events[t],r.events[t+me](),delete r.events[t+me])});var ut=1e3,Ie=(r,e)=>Or(r,s=>{let n=e(s);n&&r.events[z].push(n)},Ar,s=>{let n=r.listen;r.listen=(...i)=>(!r.lc&&!r.active&&(r.active=!0,s()),n(...i));let o=r.off;if(r.events[z]=[],r.off=()=>{o(),setTimeout(()=>{if(r.active&&!r.lc){r.active=!1;for(let i of r.events[z])i();r.events[z]=[]}},ut)},process.env.NODE_ENV!=="production"){let i=r[Q];r[Q]=()=>{for(let c of r.events[z])c();r.events[z]=[],r.active=!1,i()}}return()=>{r.listen=n,r.off=o}});a();var Ur=typeof window>"u",ge=(r,e,t,s)=>{let n=X({data:null,error:null,isPending:!0,isRefetching:!1,refetch:c=>o(c)}),o=c=>{let d=typeof s=="function"?s({data:n.get().data,error:n.get().error,isPending:n.get().isPending}):s;t(e,{...d,query:{...d?.query,...c?.query},async onSuccess(u){n.set({data:u.data,error:null,isPending:!1,isRefetching:!1,refetch:n.value.refetch}),await d?.onSuccess?.(u)},async onError(u){let{request:l}=u,h=typeof l.retry=="number"?l.retry:l.retry?.attempts,m=l.retryAttempt||0;h&&m<h||(n.set({error:u.error,data:null,isPending:!1,isRefetching:!1,refetch:n.value.refetch}),await d?.onError?.(u))},async onRequest(u){let l=n.get();n.set({isPending:l.data===null,data:l.data,error:null,isRefetching:!0,refetch:n.value.refetch}),await d?.onRequest?.(u)}}).catch(u=>{n.set({error:u,data:null,isPending:!1,isRefetching:!1,refetch:n.value.refetch})})};r=Array.isArray(r)?r:[r];let i=!1;for(let c of r)c.subscribe(()=>{Ur||(i?o():Ie(n,()=>{let d=setTimeout(()=>{i||(o(),i=!0)},0);return()=>{n.off(),c.off(),clearTimeout(d)}}))});return n};a();var Ir={proto:/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,constructor:/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,protoShort:/"__proto__"\s*:/,constructorShort:/"constructor"\s*:/},xr=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,dt={true:!0,false:!1,null:null,undefined:void 0,nan:Number.NaN,infinity:Number.POSITIVE_INFINITY,"-infinity":Number.NEGATIVE_INFINITY},Cr=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function Nr(r){return r instanceof Date&&!isNaN(r.getTime())}function Lr(r){let e=Cr.exec(r);if(!e)return null;let[,t,s,n,o,i,c,d,u,l,h]=e,m=new Date(Date.UTC(parseInt(t,10),parseInt(s,10)-1,parseInt(n,10),parseInt(o,10),parseInt(i,10),parseInt(c,10),d?parseInt(d.padEnd(3,"0"),10):0));if(u){let w=(parseInt(l,10)*60+parseInt(h,10))*(u==="+"?-1:1);m.setUTCMinutes(m.getUTCMinutes()+w)}return Nr(m)?m:null}function $r(r,e={}){let{strict:t=!1,warnings:s=!1,reviver:n,parseDates:o=!0}=e;if(typeof r!="string")return r;let i=r.trim();if(i.length>0&&i[0]==='"'&&i.endsWith('"')&&!i.slice(1,-1).includes('"'))return i.slice(1,-1);let c=i.toLowerCase();if(c.length<=9&&c in dt)return dt[c];if(!xr.test(i)){if(t)throw new SyntaxError("[better-json] Invalid JSON");return r}if(Object.entries(Ir).some(([u,l])=>{let h=l.test(i);return h&&s&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${u} pattern`),h})&&t)throw new Error("[better-json] Potential prototype pollution attempt detected");try{return JSON.parse(i,(l,h)=>{if(l==="__proto__"||l==="constructor"&&h&&typeof h=="object"&&"prototype"in h){s&&console.warn(`[better-json] Dropping "${l}" key to prevent prototype pollution`);return}if(o&&typeof h=="string"){let m=Lr(h);if(m)return m}return n?n(l,h):h})}catch(u){if(t)throw u;return r}}function ht(r,e={strict:!0}){return $r(r,e)}var Dr={id:"redirect",name:"Redirect",hooks:{onSuccess(r){if(r.data?.url&&r.data?.redirect&&typeof window<"u"&&window.location&&window.location)try{window.location.href=r.data.url}catch{}}}};function kr(r){let e=X(!1);return{session:ge(e,"/get-session",r,{method:"GET"}),$sessionSignal:e}}var ft=(r,e)=>{let t="credentials"in Request.prototype,s=ct(r?.baseURL,r?.basePath,void 0,e)??"/api/auth",n=r?.plugins?.flatMap(g=>g.fetchPlugins).filter(g=>g!==void 0)||[],o={id:"lifecycle-hooks",name:"lifecycle-hooks",hooks:{onSuccess:r?.fetchOptions?.onSuccess,onError:r?.fetchOptions?.onError,onRequest:r?.fetchOptions?.onRequest,onResponse:r?.fetchOptions?.onResponse}},{onSuccess:i,onError:c,onRequest:d,onResponse:u,...l}=r?.fetchOptions||{},h=it({baseURL:s,...t?{credentials:"include"}:{},method:"GET",jsonParser(g){return g?ht(g,{strict:!1}):null},customFetchImpl:fetch,...l,plugins:[o,...l.plugins||[],...r?.disableDefaultFetchPlugins?[]:[Dr],...n]}),{$sessionSignal:m,session:w}=kr(h),v=r?.plugins||[],x={},b={$sessionSignal:m,session:w},U={"/sign-out":"POST","/revoke-sessions":"POST","/revoke-other-sessions":"POST","/delete-user":"POST"},P=[{signal:"$sessionSignal",matcher(g){return g==="/sign-out"||g==="/update-user"||g.startsWith("/sign-in")||g.startsWith("/sign-up")||g==="/delete-user"||g==="/verify-email"}}];for(let g of v)g.getAtoms&&Object.assign(b,g.getAtoms?.(h)),g.pathMethods&&Object.assign(U,g.pathMethods),g.atomListeners&&P.push(...g.atomListeners);let B={notify:g=>{b[g].set(!b[g].get())},listen:(g,W)=>{b[g].subscribe(W)},atoms:b};for(let g of v)g.getActions&&Object.assign(x,g.getActions?.(h,B,r));return{get baseURL(){return s},pluginsActions:x,pluginsAtoms:b,pluginPathMethods:U,atomListeners:P,$fetch:h,$store:B}};function Mr(r){return typeof r=="object"&&r!==null&&"get"in r&&typeof r.get=="function"&&"lc"in r&&typeof r.lc=="number"}function Br(r,e,t){let s=e[r],{fetchOptions:n,query:o,...i}=t||{};return s||(n?.method?n.method:i&&Object.keys(i).length>0?"POST":"GET")}function pt(r,e,t,s,n){function o(i=[]){return new Proxy(function(){},{get(c,d){if(typeof d!="string"||d==="then"||d==="catch"||d==="finally")return;let u=[...i,d],l=r;for(let h of u)if(l&&typeof l=="object"&&h in l)l=l[h];else{l=void 0;break}return typeof l=="function"||Mr(l)?l:o(u)},apply:async(c,d,u)=>{let l="/"+i.map(P=>P.replace(/[A-Z]/g,B=>`-${B.toLowerCase()}`)).join("/"),h=u[0]||{},m=u[1]||{},{query:w,fetchOptions:v,...x}=h,b={...m,...v},U=Br(l,t,h);return await e(l,{...b,body:U==="GET"?void 0:{...x,...b?.body||{}},query:w||b?.query,method:U,async onSuccess(P){if(await b?.onSuccess?.(P),!n)return;let B=n.filter(g=>g.matcher(l));if(B.length)for(let g of B){let W=s[g.signal];if(!W)return;let E=W.get();setTimeout(()=>{W.set(!E)},10)}}})}})}return o()}a();function mt(r){return r.charAt(0).toUpperCase()+r.slice(1)}function xe(r){let{pluginPathMethods:e,pluginsActions:t,pluginsAtoms:s,$fetch:n,atomListeners:o,$store:i}=ft(r),c={};for(let[l,h]of Object.entries(s))c[`use${mt(l)}`]=h;let d={...t,...c,$fetch:n,$store:i};return pt(d,n,e,s,o)}a();a();a();function jr(r){return{authorize(e,t="AND"){let s=!1;for(let[n,o]of Object.entries(e)){let i=r[n];if(!i)return{success:!1,error:`You are not allowed to access resource: ${n}`};if(Array.isArray(o))s=o.every(c=>i.includes(c));else if(typeof o=="object"){let c=o;c.connector==="OR"?s=c.actions.some(d=>i.includes(d)):s=c.actions.every(d=>i.includes(d))}else throw new G("Invalid access control request");if(s&&t==="OR")return{success:s};if(!s&&t==="AND")return{success:!1,error:`unauthorized to access resource "${n}"`}}return s?{success:s}:{success:!1,error:"Not authorized"}},statements:r}}function ye(r){return{newRole(e){return jr(e)},statements:r}}var Fr={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"],team:["create","update","delete"],ac:["create","read","update","delete"]},Ce=ye(Fr),Hr=Ce.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"],team:["create","update","delete"],ac:["create","read","update","delete"]}),qr=Ce.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"],team:["create","update","delete"],ac:["create","read","update","delete"]}),Wr=Ce.newRole({organization:[],member:[],invitation:[],team:[],ac:["read"]});a();a();a();a();a();a();a();a();a();a();a();var Ne=class{constructor(){Object.defineProperty(this,"controller",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}createNewAbortSignal(){if(this.controller){let t=new Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}},bt=new Ne;a();a();a();a();a();a();a();a();var Jr={user:["create","list","set-role","ban","impersonate","delete","set-password","get","update"],session:["list","revoke","delete"]},Rt=ye(Jr),Yr=Rt.newRole({user:["create","list","set-role","ban","impersonate","delete","set-password","get","update"],session:["list","revoke","delete"]}),Qr=Rt.newRole({user:[],session:[]});a();a();var wt=()=>({id:"username",$InferServerPlugin:{}});var Xr="/auth",be="nvwa_login_token",$e="nvwa_user_profile",Et=class{constructor(e,t,s){this.storage=s,this.authClient=xe({baseURL:e,basePath:Xr,fetchOptions:{customFetchImpl:t,auth:{type:"Bearer",token:()=>s.get(be)},onSuccess:n=>{let o=n.response.headers.get("set-auth-token");o&&s.set(be,o)}},plugins:[wt()]})}async currentUser(){return await this.storage.get($e)}async signUp(e,t){let s=await this.authClient.signUp.email({email:e.email??`${e.username}@nvwa.app`,name:e.name,username:e.username,displayUsername:e.displayUsername,password:t});this.saveSession(s)}async signInWithUsername(e,t){let s=await this.authClient.signIn.username({username:e,password:t});this.saveSession(s)}saveSession(e){if(e.error)throw new Error(e.error.message);this.storage.set(be,e.data?.token),this.storage.set($e,e.data?.user)}async signOut(){await this.storage.remove(be),await this.storage.remove($e)}async updateUserPassword(e,t,s=!1){let n=await this.authClient.changePassword({currentPassword:e,newPassword:t,revokeOtherSessions:s});this.saveSession(n)}};a();var vt=class{constructor(e){this.http=e}async invoke(e,t){return(await this.http.request("/functions/"+e,{method:t.method||"POST",data:t.body,headers:t.headers})).body}};a();var Tt=class{constructor(e,t,s,n,o){this.ok=e,this.status=t,this.statusText=s,this.headers=n,this.body=o}async text(){return typeof this.body=="string"?this.body:JSON.stringify(this.body)}async json(){if(typeof this.body=="string")try{return JSON.parse(this.body)}catch{return this.body}return this.body}async arrayBuffer(){if(this.body instanceof ArrayBuffer)return this.body;if(typeof this.body=="string")return new TextEncoder().encode(this.body).buffer;throw new Error("Cannot convert body to ArrayBuffer")}async blob(){if(this.body instanceof Blob)return this.body;if(typeof this.body=="string")return new Blob([this.body],{type:this.headers["content-type"]||"text/plain"});throw new Error("Cannot convert body to Blob")}},_t=class{async jsonRequest(e,t){let s={...t,headers:{"Content-Type":"application/json",...t.headers},data:typeof t.data=="object"?JSON.stringify(t.data):t.data};return this.request(e,s)}async jsonRequestWithAuth(e,t,s){let n={...t,headers:{"Content-Type":"application/json",...t.headers},data:typeof t.data=="object"?JSON.stringify(t.data):t.data};return this.requestWithAuth(e,n,s)}};a();var Zr="/storage",es=Zr+"/generateUploadUrl",St=class{constructor(e,t){this.baseUrl=e,this.http=t}async uploadFile(e){let t=await this.http.request(this.baseUrl+es,{method:"POST",data:{fileName:e.name||e.fileName,fileSize:e.size||e.fileSize,fileType:e.type||e.fileType}}),{url:s}=t.body;if(!s)throw new Error("\u83B7\u53D6\u4E0A\u4F20URL\u5931\u8D25");return{url:(await this.http.request(s,{method:"PUT",data:e,headers:{"Content-Type":e.type||e.fileType||"application/octet-stream"}})).body.url.split("?")[0]}}};a();a();a();var Dt=Kt($t(),1),{PostgrestClient:kt,PostgrestQueryBuilder:ii,PostgrestFilterBuilder:li,PostgrestTransformBuilder:ci,PostgrestBuilder:ui,PostgrestError:di,FetchHeaders:hi,FetchResponse:Je,PostgrestFetch:fi,URL:pi,URLSearchParams:mi}=Dt.default;var ds="/entities",hs=(r,e)=>async(s,n)=>{console.log("customFetch",s,n);let o;if(typeof s=="string")o=s;else if(s&&typeof s=="object")if(typeof s.toString=="function"&&!s.url)o=s.toString();else if(s.url)o=s.url,n||(n={}),n.method=s.method,n.headers=s.headers,n.body=s.body;else throw new Error("Unsupported input type for fetch");else throw new Error("Unsupported input type for fetch");let i=(n?.method||"GET").toUpperCase(),c={};if(n?.headers)if(n.headers&&typeof n.headers.forEach=="function")n.headers.forEach((w,v)=>{c[v]=w});else if(Array.isArray(n.headers))for(let[w,v]of n.headers)c[w]=v;else Object.assign(c,n.headers);let d=n?.body,u;try{u=await r.requestWithAuth(o,{method:i,data:d,headers:c},e)}catch(w){return new Je(w?.message||"Internal Error",{status:500,statusText:"Internal Error"})}let l=u.body,h=null;return(u.headers["content-type"]||u.headers["Content-Type"]||"").startsWith("application/json")&&typeof l!="string"?h=JSON.stringify(l):typeof l=="string"||l&&(l.constructor===Blob||l.constructor===ArrayBuffer||typeof l.getReader=="function")?h=l:h=JSON.stringify(l),new Je(h,{status:u.status,headers:u.headers})},Ei=(r,e,t)=>new kt(r+ds,{fetch:hs(e,t)});a();a();var M=class r{constructor(e){this.headerMap=new Map;if(e){if(e instanceof r)e.forEach((t,s)=>this.set(s,t));else if(Array.isArray(e))for(let[t,s]of e)this.set(t,String(s));else if(typeof e=="object")for(let t of Object.keys(e))this.set(t,String(e[t]))}}append(e,t){let s=e.toLowerCase(),n=this.headerMap.get(s);this.headerMap.set(s,n?`${n}, ${t}`:t)}set(e,t){this.headerMap.set(e.toLowerCase(),String(t))}get(e){let t=this.headerMap.get(e.toLowerCase());return t??null}has(e){return this.headerMap.has(e.toLowerCase())}delete(e){this.headerMap.delete(e.toLowerCase())}forEach(e){for(let[t,s]of this.headerMap.entries())e(s,t,this)}entries(){return this.headerMap.entries()}keys(){return this.headerMap.keys()}values(){return this.headerMap.values()}[Symbol.iterator](){return this.entries()}},ce=class r{constructor(e){this.params=new Map;if(e){if(typeof e=="string")this.parseString(e);else if(e instanceof r)this.params=new Map(e.params);else if(Array.isArray(e))for(let[t,s]of e)this.append(t,s);else if(e&&typeof e=="object")for(let[t,s]of Object.entries(e))this.set(t,s)}}parseString(e){e.startsWith("?")&&(e=e.slice(1));let t=e.split("&");for(let s of t)if(s){let[n,o]=s.split("=");n&&this.append(decodeURIComponent(n),o?decodeURIComponent(o):"")}}append(e,t){let s=this.params.get(e)||[];s.push(t),this.params.set(e,s)}delete(e){this.params.delete(e)}get(e){let t=this.params.get(e);return t?t[0]:null}getAll(e){return this.params.get(e)||[]}has(e){return this.params.has(e)}set(e,t){this.params.set(e,[t])}sort(){let e=Array.from(this.params.entries()).sort(([t],[s])=>t.localeCompare(s));this.params=new Map(e)}toString(){let e=[];for(let[t,s]of this.params.entries())for(let n of s)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(n)}`);return e.join("&")}forEach(e){for(let[t,s]of this.params.entries())for(let n of s)e(n,t,this)}keys(){return this.params.keys()}values(){let e=[];for(let t of this.params.values())e.push(...t);return e[Symbol.iterator]()}entries(){let e=[];for(let[t,s]of this.params.entries())for(let n of s)e.push([t,n]);return e[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}},Te=class r{constructor(e,t){let s;if(e instanceof r)s=e.href;else if(t){let o=t instanceof r?t.href:t;s=this.resolve(o,e)}else s=e;let n=this.parseUrl(s);this.href=s,this.origin=`${n.protocol}//${n.host}`,this.protocol=n.protocol,this.username=n.username,this.password=n.password,this.host=n.host,this.hostname=n.hostname,this.port=n.port,this.pathname=n.pathname,this.search=n.search,this.searchParams=new ce(n.search),this.hash=n.hash}resolve(e,t){if(t.startsWith("http://")||t.startsWith("https://"))return t;if(t.startsWith("//"))return`${this.parseUrl(e).protocol}${t}`;if(t.startsWith("/")){let o=this.parseUrl(e);return`${o.protocol}//${o.host}${t}`}let s=this.parseUrl(e),n=s.pathname.endsWith("/")?s.pathname:s.pathname+"/";return`${s.protocol}//${s.host}${n}${t}`}parseUrl(e){let t=e.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!t)throw new TypeError("Invalid URL");let s=t[2]||"",n=t[4]||"",o=t[5]||"/",i=t[7]?`?${t[7]}`:"",c=t[9]?`#${t[9]}`:"";if(!s&&!n&&!o.startsWith("/")&&!o.includes("/")&&!o.includes("."))throw new TypeError("Invalid URL");let d=n.match(/^([^@]*)@(.+)$/),u="",l="",h=n;if(d){let x=d[1];h=d[2];let b=x.match(/^([^:]*):?(.*)$/);b&&(u=b[1]||"",l=b[2]||"")}let m=h.match(/^([^:]+):?(\d*)$/),w=m?m[1]:h,v=m&&m[2]?m[2]:"";return{protocol:s?`${s}:`:"",username:u,password:l,host:h,hostname:w,port:v,pathname:o,search:i,hash:c}}toString(){let e=this.searchParams.toString(),t=e?`?${e}`:"";return`${this.protocol}//${this.host}${this.pathname}${t}${this.hash}`}toJSON(){return this.toString()}};a();var _e=class r{constructor(e,t){if(typeof e=="string")this.url=e;else if(e?.url)this.url=String(e.url);else if(typeof e?.toString=="function")this.url=String(e.toString());else throw new Error("Invalid input for Request");this.method=(t?.method||"GET").toUpperCase(),this.headers=t?.headers instanceof M?t.headers:new M(t?.headers),this.body=t?.body,this.timeout=t?.timeout,this.signal=t?.signal||void 0}clone(){return new r(this.url,{method:this.method,headers:this.headers,body:this.body,timeout:this.timeout})}toString(){return this.url}};a();var Se=class{constructor(e,t){this.bodyData=e,this.status=t?.status??200,this.statusText=t?.statusText??"",this.headers=fs(t?.headers),this.ok=this.status>=200&&this.status<300}async text(){return typeof this.bodyData=="string"?this.bodyData:this.bodyData==null?"":typeof this.bodyData=="object"?JSON.stringify(this.bodyData):String(this.bodyData)}async json(){if(typeof this.bodyData=="string")try{return JSON.parse(this.bodyData)}catch{}return this.bodyData}async arrayBuffer(){let e=await this.text();return new TextEncoder().encode(e).buffer}};function fs(r){return r?new M(r):new M}a();var ue=class{constructor(){this._aborted=!1;this.listeners=new Set;this.onabort=null}get aborted(){return this._aborted}_trigger(){if(!this._aborted){if(this._aborted=!0,typeof this.onabort=="function")try{this.onabort()}catch{}for(let e of Array.from(this.listeners))try{e()}catch{}this.listeners.clear()}}addEventListener(e,t){if(this._aborted){try{t()}catch{}return}this.listeners.add(t)}removeEventListener(e,t){this.listeners.delete(t)}toString(){return"[object AbortSignal]"}},Pe=class{constructor(){this._signal=new ue}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}};a();function Mi(r){r.URL=Te,r.URLSearchParams=ce,r.Headers=M,r.Request=_e,r.Response=Se,r.AbortController=Pe,r.AbortSignal=ue}export{Xr as AUTH_BASE_PATH,Pe as AbortController,ue as AbortSignal,ds as ENTITIES_BASE_PATH,Zr as FILE_STORAGE_BASE_PATH,Tt as FetchResponse,es as GENERATE_UPLOAD_URL_PATH,M as Headers,be as LOGIN_TOKEN_KEY,$e as LOGIN_USER_PROFILE_KEY,Et as NvwaAuthClient,vt as NvwaEdgeFunctions,St as NvwaFileStorage,_t as NvwaHttpClient,_e as Request,Se as Response,Te as URL,ce as URLSearchParams,Ei as createPostgrestClient,Mi as polyfill};
1
+ var Ke=Object.defineProperty,Je=Object.defineProperties,Ye=Object.getOwnPropertyDescriptors,be=Object.getOwnPropertySymbols,Qe=Object.prototype.hasOwnProperty,Xe=Object.prototype.propertyIsEnumerable,Re=(t,e,r)=>e in t?Ke(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,_=(t,e)=>{for(var r in e||(e={}))Qe.call(e,r)&&Re(t,r,e[r]);if(be)for(var r of be(e))Xe.call(e,r)&&Re(t,r,e[r]);return t},I=(t,e)=>Je(t,Ye(e)),Ze=class extends Error{constructor(t,e,r){super(e||t.toString(),{cause:r}),this.status=t,this.statusText=e,this.error=r}},et=async(t,e)=>{var r,n,s,o,c,l;let u=e||{},a={onRequest:[e?.onRequest],onResponse:[e?.onResponse],onSuccess:[e?.onSuccess],onError:[e?.onError],onRetry:[e?.onRetry]};if(!e||!e?.plugins)return{url:t,options:u,hooks:a};for(let i of e?.plugins||[]){if(i.init){let d=await((r=i.init)==null?void 0:r.call(i,t.toString(),e));u=d.options||u,t=d.url}a.onRequest.push((n=i.hooks)==null?void 0:n.onRequest),a.onResponse.push((s=i.hooks)==null?void 0:s.onResponse),a.onSuccess.push((o=i.hooks)==null?void 0:o.onSuccess),a.onError.push((c=i.hooks)==null?void 0:c.onError),a.onRetry.push((l=i.hooks)==null?void 0:l.onRetry)}return{url:t,options:u,hooks:a}},Ee=class{constructor(t){this.options=t}shouldAttemptRetry(t,e){return this.options.shouldRetry?Promise.resolve(t<this.options.attempts&&this.options.shouldRetry(e)):Promise.resolve(t<this.options.attempts)}getDelay(){return this.options.delay}},tt=class{constructor(t){this.options=t}shouldAttemptRetry(t,e){return this.options.shouldRetry?Promise.resolve(t<this.options.attempts&&this.options.shouldRetry(e)):Promise.resolve(t<this.options.attempts)}getDelay(t){return Math.min(this.options.maxDelay,this.options.baseDelay*2**t)}};function rt(t){if(typeof t=="number")return new Ee({type:"linear",attempts:t,delay:1e3});switch(t.type){case"linear":return new Ee(t);case"exponential":return new tt(t);default:throw new Error("Invalid retry strategy")}}var nt=async t=>{let e={},r=async n=>typeof n=="function"?await n():n;if(t?.auth){if(t.auth.type==="Bearer"){let n=await r(t.auth.token);if(!n)return e;e.authorization=`Bearer ${n}`}else if(t.auth.type==="Basic"){let n=r(t.auth.username),s=r(t.auth.password);if(!n||!s)return e;e.authorization=`Basic ${btoa(`${n}:${s}`)}`}else if(t.auth.type==="Custom"){let n=r(t.auth.value);if(!n)return e;e.authorization=`${r(t.auth.prefix)} ${n}`}}return e},st=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function ot(t){let e=t.headers.get("content-type"),r=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!e)return"json";let n=e.split(";").shift()||"";return st.test(n)?"json":r.has(n)||n.startsWith("text/")?"text":"blob"}function it(t){try{return JSON.parse(t),!0}catch{return!1}}function Se(t){if(t===void 0)return!1;let e=typeof t;return e==="string"||e==="number"||e==="boolean"||e===null?!0:e!=="object"?!1:Array.isArray(t)?!0:t.buffer?!1:t.constructor&&t.constructor.name==="Object"||typeof t.toJSON=="function"}function Te(t){try{return JSON.parse(t)}catch{return t}}function we(t){return typeof t=="function"}function at(t){if(t?.customFetchImpl)return t.customFetchImpl;if(typeof globalThis<"u"&&we(globalThis.fetch))return globalThis.fetch;if(typeof window<"u"&&we(window.fetch))return window.fetch;throw new Error("No fetch implementation found")}async function ct(t){let e=new Headers(t?.headers),r=await nt(t);for(let[n,s]of Object.entries(r||{}))e.set(n,s);if(!e.has("content-type")){let n=lt(t?.body);n&&e.set("content-type",n)}return e}function lt(t){return Se(t)?"application/json":null}function ut(t){if(!t?.body)return null;let e=new Headers(t?.headers);if(Se(t.body)&&!e.has("content-type")){for(let[r,n]of Object.entries(t?.body))n instanceof Date&&(t.body[r]=n.toISOString());return JSON.stringify(t.body)}return t.body}function dt(t,e){var r;if(e?.method)return e.method.toUpperCase();if(t.startsWith("@")){let n=(r=t.split("@")[1])==null?void 0:r.split("/")[0];return Ae.includes(n)?n.toUpperCase():e?.body?"POST":"GET"}return e?.body?"POST":"GET"}function ft(t,e){let r;return!t?.signal&&t?.timeout&&(r=setTimeout(()=>e?.abort(),t?.timeout)),{abortTimeout:r,clearTimeout:()=>{r&&clearTimeout(r)}}}var pt=class ve extends Error{constructor(e,r){super(r||JSON.stringify(e,null,2)),this.issues=e,Object.setPrototypeOf(this,ve.prototype)}};async function Q(t,e){let r=await t["~standard"].validate(e);if(r.issues)throw new pt(r.issues);return r.value}var Ae=["get","post","put","patch","delete"];var ht=t=>({id:"apply-schema",name:"Apply Schema",version:"1.0.0",async init(e,r){var n,s,o,c;let l=((s=(n=t.plugins)==null?void 0:n.find(u=>{var a;return(a=u.schema)!=null&&a.config?e.startsWith(u.schema.config.baseURL||"")||e.startsWith(u.schema.config.prefix||""):!1}))==null?void 0:s.schema)||t.schema;if(l){let u=e;(o=l.config)!=null&&o.prefix&&u.startsWith(l.config.prefix)&&(u=u.replace(l.config.prefix,""),l.config.baseURL&&(e=e.replace(l.config.prefix,l.config.baseURL))),(c=l.config)!=null&&c.baseURL&&u.startsWith(l.config.baseURL)&&(u=u.replace(l.config.baseURL,""));let a=l.schema[u];if(a){let i=I(_({},r),{method:a.method,output:a.output});return r?.disableValidation||(i=I(_({},i),{body:a.input?await Q(a.input,r?.body):r?.body,params:a.params?await Q(a.params,r?.params):r?.params,query:a.query?await Q(a.query,r?.query):r?.query})),{url:e,options:i}}}return{url:e,options:r}}}),Oe=t=>{async function e(r,n){let s=I(_(_({},t),n),{plugins:[...t?.plugins||[],ht(t||{})]});if(t?.catchAllError)try{return await ce(r,s)}catch(o){return{data:null,error:{status:500,statusText:"Fetch Error",message:"Fetch related error. Captured by catchAllError option. See error property for more details.",error:o}}}return await ce(r,s)}return e};function mt(t,e){let{baseURL:r,params:n,query:s}=e||{query:{},params:{},baseURL:""},o=t.startsWith("http")?t.split("/").slice(0,3).join("/"):r||"";if(t.startsWith("@")){let d=t.toString().split("@")[1].split("/")[0];Ae.includes(d)&&(t=t.replace(`@${d}/`,"/"))}o.endsWith("/")||(o+="/");let[c,l]=t.replace(o,"").split("?"),u=new URLSearchParams(l);for(let[d,m]of Object.entries(s||{}))m!=null&&u.set(d,String(m));if(n)if(Array.isArray(n)){let d=c.split("/").filter(m=>m.startsWith(":"));for(let[m,R]of d.entries()){let T=n[m];c=c.replace(R,T)}}else for(let[d,m]of Object.entries(n))c=c.replace(`:${d}`,String(m));c=c.split("/").map(encodeURIComponent).join("/"),c.startsWith("/")&&(c=c.slice(1));let a=u.toString();return a=a.length>0?`?${a}`.replace(/\+/g,"%20"):"",o.startsWith("http")?new URL(`${c}${a}`,o):`${o}${c}${a}`}var ce=async(t,e)=>{var r,n,s,o,c,l,u,a;let{hooks:i,url:d,options:m}=await et(t,e),R=at(m),T=new AbortController,D=(r=m.signal)!=null?r:T.signal,E=mt(d,m),B=ut(m),k=await ct(m),C=dt(d,m),f=I(_({},m),{url:E,headers:k,body:B,method:C,signal:D});for(let A of i.onRequest)if(A){let w=await A(f);w instanceof Object&&(f=w)}("pipeTo"in f&&typeof f.pipeTo=="function"||typeof((n=e?.body)==null?void 0:n.pipe)=="function")&&("duplex"in f||(f.duplex="half"));let{clearTimeout:H}=ft(m,T),y=await R(f.url,f);H();let ge={response:y,request:f};for(let A of i.onResponse)if(A){let w=await A(I(_({},ge),{response:(s=e?.hookOptions)!=null&&s.cloneResponse?y.clone():y}));w instanceof Response?y=w:w instanceof Object&&(y=w.response)}if(y.ok){if(!(f.method!=="HEAD"))return{data:"",error:null};let w=ot(y),N={data:"",response:y,request:f};if(w==="json"||w==="text"){let L=await y.text(),ze=await((o=f.jsonParser)!=null?o:Te)(L);N.data=ze}else N.data=await y[w]();f?.output&&f.output&&!f.disableValidation&&(N.data=await Q(f.output,N.data));for(let L of i.onSuccess)L&&await L(I(_({},N),{response:(c=e?.hookOptions)!=null&&c.cloneResponse?y.clone():y}));return e?.throw?N.data:{data:N.data,error:null}}let Ve=(l=e?.jsonParser)!=null?l:Te,Y=await y.text(),ye=it(Y),ae=ye?await Ve(Y):null,Ge={response:y,responseText:Y,request:f,error:I(_({},ae),{status:y.status,statusText:y.statusText})};for(let A of i.onError)A&&await A(I(_({},Ge),{response:(u=e?.hookOptions)!=null&&u.cloneResponse?y.clone():y}));if(e?.retry){let A=rt(e.retry),w=(a=e.retryAttempt)!=null?a:0;if(await A.shouldAttemptRetry(w,y)){for(let L of i.onRetry)L&&await L(ge);let N=A.getDelay(w);return await new Promise(L=>setTimeout(L,N)),await ce(t,I(_({},e),{retryAttempt:w+1}))}}if(e?.throw)throw new Ze(y.status,y.statusText,ye?ae:Y);return{data:null,error:I(_({},ae),{status:y.status,statusText:y.statusText})}};var X=Object.create(null),j=t=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(t?X:globalThis),v=new Proxy(X,{get(t,e){return j()[e]??X[e]},has(t,e){let r=j();return e in r||e in X},set(t,e,r){let n=j(!0);return n[e]=r,!0},deleteProperty(t,e){if(!e)return!1;let r=j(!0);return delete r[e],!0},ownKeys(){let t=j(!0);return Object.keys(t)}});var ur=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";function g(t,e){return typeof process<"u"&&process.env?process.env[t]??e:typeof Deno<"u"?Deno.env.get(t)??e:typeof Bun<"u"?Bun.env[t]??e:e}var dr=Object.freeze({get BETTER_AUTH_SECRET(){return g("BETTER_AUTH_SECRET")},get AUTH_SECRET(){return g("AUTH_SECRET")},get BETTER_AUTH_TELEMETRY(){return g("BETTER_AUTH_TELEMETRY")},get BETTER_AUTH_TELEMETRY_ID(){return g("BETTER_AUTH_TELEMETRY_ID")},get NODE_ENV(){return g("NODE_ENV","development")},get PACKAGE_VERSION(){return g("PACKAGE_VERSION","0.0.0")},get BETTER_AUTH_TELEMETRY_ENDPOINT(){return g("BETTER_AUTH_TELEMETRY_ENDPOINT","https://telemetry.better-auth.com/v1/track")}}),W=1,b=4,U=8,S=24,_e={eterm:b,cons25:b,console:b,cygwin:b,dtterm:b,gnome:b,hurd:b,jfbterm:b,konsole:b,kterm:b,mlterm:b,mosh:S,putty:b,st:b,"rxvt-unicode-24bit":S,terminator:S,"xterm-kitty":S},gt=new Map(Object.entries({APPVEYOR:U,BUILDKITE:U,CIRCLECI:S,DRONE:U,GITEA_ACTIONS:S,GITHUB_ACTIONS:S,GITLAB_CI:U,TRAVIS:U})),yt=[/ansi/,/color/,/linux/,/direct/,/^con[0-9]*x[0-9]/,/^rxvt/,/^screen/,/^xterm/,/^vt100/,/^vt220/];function bt(){if(g("FORCE_COLOR")!==void 0)switch(g("FORCE_COLOR")){case"":case"1":case"true":return b;case"2":return U;case"3":return S;default:return W}if(g("NODE_DISABLE_COLORS")!==void 0&&g("NODE_DISABLE_COLORS")!==""||g("NO_COLOR")!==void 0&&g("NO_COLOR")!==""||g("TERM")==="dumb")return W;if(g("TMUX"))return S;if("TF_BUILD"in v&&"AGENT_NAME"in v)return b;if("CI"in v){for(let{0:t,1:e}of gt)if(t in v)return e;return g("CI_NAME")==="codeship"?U:W}if("TEAMCITY_VERSION"in v)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.exec(g("TEAMCITY_VERSION"))!==null?b:W;switch(g("TERM_PROGRAM")){case"iTerm.app":return!g("TERM_PROGRAM_VERSION")||/^[0-2]\./.exec(g("TERM_PROGRAM_VERSION"))!==null?U:S;case"HyperTerm":case"MacTerm":return S;case"Apple_Terminal":return U}if(g("COLORTERM")==="truecolor"||g("COLORTERM")==="24bit")return S;if(g("TERM")){if(/truecolor/.exec(g("TERM"))!==null)return S;if(/^xterm-256/.exec(g("TERM"))!==null)return U;let t=g("TERM").toLowerCase();if(_e[t])return _e[t];if(yt.some(e=>e.exec(t)!==null))return b}return g("COLORTERM")?b:W}var x={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",undim:"\x1B[22m",underscore:"\x1B[4m",blink:"\x1B[5m",reverse:"\x1B[7m",hidden:"\x1B[8m",fg:{black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"},bg:{black:"\x1B[40m",red:"\x1B[41m",green:"\x1B[42m",yellow:"\x1B[43m",blue:"\x1B[44m",magenta:"\x1B[45m",cyan:"\x1B[46m",white:"\x1B[47m"}},le=["info","success","warn","error","debug"];function Rt(t,e){return le.indexOf(e)<=le.indexOf(t)}var Et={info:x.fg.blue,success:x.fg.green,warn:x.fg.yellow,error:x.fg.red,debug:x.fg.magenta},Tt=(t,e,r)=>{let n=new Date().toISOString();return r?`${x.dim}${n}${x.reset} ${Et[t]}${t.toUpperCase()}${x.reset} ${x.bright}[Better Auth]:${x.reset} ${e}`:`${n} ${t.toUpperCase()} [Better Auth]: ${e}`},wt=t=>{let e=t?.disabled!==!0,r=t?.level??"error",s=t?.disableColors!==void 0?!t.disableColors:bt()!==1,o=(l,u,a=[])=>{if(!e||!Rt(r,l))return;let i=Tt(l,u,s);if(!t||typeof t.log!="function"){l==="error"?console.error(i,...a):l==="warn"?console.warn(i,...a):console.log(i,...a);return}t.log(l==="success"?"info":l,u,...a)};return{...Object.fromEntries(le.map(l=>[l,(...[u,...a])=>o(l,u,a)])),get level(){return r}}},fr=wt();var Rr={USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_USER:"Failed to create user",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_UPDATE_USER:"Failed to update user",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"Invalid token",ID_TOKEN_NOT_SUPPORTED:"id_token not supported",FAILED_TO_GET_USER_INFO:"Failed to get user info",USER_EMAIL_NOT_FOUND:"User email not found",EMAIL_NOT_VERIFIED:"Email not verified",PASSWORD_TOO_SHORT:"Password too short",PASSWORD_TOO_LONG:"Password too long",USER_ALREADY_EXISTS:"User already exists.",USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL:"User already exists. Use another email.",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found",SESSION_EXPIRED:"Session expired. Re-authenticate to perform this action.",FAILED_TO_UNLINK_LAST_ACCOUNT:"You can't unlink your last account",ACCOUNT_NOT_FOUND:"Account not found",USER_ALREADY_HAS_PASSWORD:"User already has a password. Provide that to delete the account."},$=class extends Error{constructor(e,r){super(e),this.name="BetterAuthError",this.message=e,this.cause=r,this.stack=""}};function St(t){try{return(new URL(t).pathname.replace(/\/+$/,"")||"/")!=="/"}catch{throw new $(`Invalid base URL: ${t}. Please provide a valid base URL.`)}}function V(t,e="/api/auth"){if(St(t))return t;let n=t.replace(/\/+$/,"");return!e||e==="/"?n:(e=e.startsWith("/")?e:`/${e}`,`${n}${e}`)}function Pe(t,e,r,n){if(t)return V(t,e);if(n!==!1){let c=v.BETTER_AUTH_URL||v.NEXT_PUBLIC_BETTER_AUTH_URL||v.PUBLIC_BETTER_AUTH_URL||v.NUXT_PUBLIC_BETTER_AUTH_URL||v.NUXT_PUBLIC_AUTH_URL||(v.BASE_URL!=="/"?v.BASE_URL:void 0);if(c)return V(c,e)}let s=r?.headers.get("x-forwarded-host"),o=r?.headers.get("x-forwarded-proto");if(s&&o)return V(`${o}://${s}`,e);if(r){let c=vt(r.url);if(!c)throw new $("Could not get origin from request. Please provide a valid base URL.");return V(c,e)}if(typeof window<"u"&&window.location)return V(window.location.origin,e)}function vt(t){try{return new URL(t).origin}catch{return null}}var G=Symbol("clean");var P=[],M=0,Z=4,At=0,z=t=>{let e=[],r={get(){return r.lc||r.listen(()=>{})(),r.value},lc:0,listen(n){return r.lc=e.push(n),()=>{for(let o=M+Z;o<P.length;)P[o]===n?P.splice(o,Z):o+=Z;let s=e.indexOf(n);~s&&(e.splice(s,1),--r.lc||r.off())}},notify(n,s){At++;let o=!P.length;for(let c of e)P.push(c,r.value,n,s);if(o){for(M=0;M<P.length;M+=Z)P[M](P[M+1],P[M+2],P[M+3]);P.length=0}},off(){},set(n){let s=r.value;s!==n&&(r.value=n,r.notify(s))},subscribe(n){let s=r.listen(n);return n(r.value),s},value:t};return process.env.NODE_ENV!=="production"&&(r[G]=()=>{e=[],r.lc=0,r.off()}),r};var Ot=5,q=6,ee=10,_t=(t,e,r,n)=>(t.events=t.events||{},t.events[r+ee]||(t.events[r+ee]=n(s=>{t.events[r].reduceRight((o,c)=>(c(o),o),{shared:{},...s})})),t.events[r]=t.events[r]||[],t.events[r].push(e),()=>{let s=t.events[r],o=s.indexOf(e);s.splice(o,1),s.length||(delete t.events[r],t.events[r+ee](),delete t.events[r+ee])});var Ie=1e3,ue=(t,e)=>_t(t,n=>{let s=e(n);s&&t.events[q].push(s)},Ot,n=>{let s=t.listen;t.listen=(...c)=>(!t.lc&&!t.active&&(t.active=!0,n()),s(...c));let o=t.off;if(t.events[q]=[],t.off=()=>{o(),setTimeout(()=>{if(t.active&&!t.lc){t.active=!1;for(let c of t.events[q])c();t.events[q]=[]}},Ie)},process.env.NODE_ENV!=="production"){let c=t[G];t[G]=()=>{for(let l of t.events[q])l();t.events[q]=[],t.active=!1,c()}}return()=>{t.listen=s,t.off=o}});var Pt=typeof window>"u",te=(t,e,r,n)=>{let s=z({data:null,error:null,isPending:!0,isRefetching:!1,refetch:l=>o(l)}),o=l=>{let u=typeof n=="function"?n({data:s.get().data,error:s.get().error,isPending:s.get().isPending}):n;r(e,{...u,query:{...u?.query,...l?.query},async onSuccess(a){s.set({data:a.data,error:null,isPending:!1,isRefetching:!1,refetch:s.value.refetch}),await u?.onSuccess?.(a)},async onError(a){let{request:i}=a,d=typeof i.retry=="number"?i.retry:i.retry?.attempts,m=i.retryAttempt||0;d&&m<d||(s.set({error:a.error,data:null,isPending:!1,isRefetching:!1,refetch:s.value.refetch}),await u?.onError?.(a))},async onRequest(a){let i=s.get();s.set({isPending:i.data===null,data:i.data,error:null,isRefetching:!0,refetch:s.value.refetch}),await u?.onRequest?.(a)}}).catch(a=>{s.set({error:a,data:null,isPending:!1,isRefetching:!1,refetch:s.value.refetch})})};t=Array.isArray(t)?t:[t];let c=!1;for(let l of t)l.subscribe(()=>{Pt||(c?o():ue(s,()=>{let u=setTimeout(()=>{c||(o(),c=!0)},0);return()=>{s.off(),l.off(),clearTimeout(u)}}))});return s};var It={proto:/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,constructor:/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,protoShort:/"__proto__"\s*:/,constructorShort:/"constructor"\s*:/},Ut=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,Ue={true:!0,false:!1,null:null,undefined:void 0,nan:Number.NaN,infinity:Number.POSITIVE_INFINITY,"-infinity":Number.NEGATIVE_INFINITY},xt=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function Ct(t){return t instanceof Date&&!isNaN(t.getTime())}function Nt(t){let e=xt.exec(t);if(!e)return null;let[,r,n,s,o,c,l,u,a,i,d]=e,m=new Date(Date.UTC(parseInt(r,10),parseInt(n,10)-1,parseInt(s,10),parseInt(o,10),parseInt(c,10),parseInt(l,10),u?parseInt(u.padEnd(3,"0"),10):0));if(a){let R=(parseInt(i,10)*60+parseInt(d,10))*(a==="+"?-1:1);m.setUTCMinutes(m.getUTCMinutes()+R)}return Ct(m)?m:null}function Lt(t,e={}){let{strict:r=!1,warnings:n=!1,reviver:s,parseDates:o=!0}=e;if(typeof t!="string")return t;let c=t.trim();if(c.length>0&&c[0]==='"'&&c.endsWith('"')&&!c.slice(1,-1).includes('"'))return c.slice(1,-1);let l=c.toLowerCase();if(l.length<=9&&l in Ue)return Ue[l];if(!Ut.test(c)){if(r)throw new SyntaxError("[better-json] Invalid JSON");return t}if(Object.entries(It).some(([a,i])=>{let d=i.test(c);return d&&n&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${a} pattern`),d})&&r)throw new Error("[better-json] Potential prototype pollution attempt detected");try{return JSON.parse(c,(i,d)=>{if(i==="__proto__"||i==="constructor"&&d&&typeof d=="object"&&"prototype"in d){n&&console.warn(`[better-json] Dropping "${i}" key to prevent prototype pollution`);return}if(o&&typeof d=="string"){let m=Nt(d);if(m)return m}return s?s(i,d):d})}catch(a){if(r)throw a;return t}}function xe(t,e={strict:!0}){return Lt(t,e)}var Dt={id:"redirect",name:"Redirect",hooks:{onSuccess(t){if(t.data?.url&&t.data?.redirect&&typeof window<"u"&&window.location&&window.location)try{window.location.href=t.data.url}catch{}}}};function kt(t){let e=z(!1);return{session:te(e,"/get-session",t,{method:"GET"}),$sessionSignal:e}}var Ce=(t,e)=>{let r="credentials"in Request.prototype,n=Pe(t?.baseURL,t?.basePath,void 0,e)??"/api/auth",s=t?.plugins?.flatMap(f=>f.fetchPlugins).filter(f=>f!==void 0)||[],o={id:"lifecycle-hooks",name:"lifecycle-hooks",hooks:{onSuccess:t?.fetchOptions?.onSuccess,onError:t?.fetchOptions?.onError,onRequest:t?.fetchOptions?.onRequest,onResponse:t?.fetchOptions?.onResponse}},{onSuccess:c,onError:l,onRequest:u,onResponse:a,...i}=t?.fetchOptions||{},d=Oe({baseURL:n,...r?{credentials:"include"}:{},method:"GET",jsonParser(f){return f?xe(f,{strict:!1}):null},customFetchImpl:fetch,...i,plugins:[o,...i.plugins||[],...t?.disableDefaultFetchPlugins?[]:[Dt],...s]}),{$sessionSignal:m,session:R}=kt(d),T=t?.plugins||[],D={},E={$sessionSignal:m,session:R},B={"/sign-out":"POST","/revoke-sessions":"POST","/revoke-other-sessions":"POST","/delete-user":"POST"},k=[{signal:"$sessionSignal",matcher(f){return f==="/sign-out"||f==="/update-user"||f.startsWith("/sign-in")||f.startsWith("/sign-up")||f==="/delete-user"||f==="/verify-email"}}];for(let f of T)f.getAtoms&&Object.assign(E,f.getAtoms?.(d)),f.pathMethods&&Object.assign(B,f.pathMethods),f.atomListeners&&k.push(...f.atomListeners);let C={notify:f=>{E[f].set(!E[f].get())},listen:(f,H)=>{E[f].subscribe(H)},atoms:E};for(let f of T)f.getActions&&Object.assign(D,f.getActions?.(d,C,t));return{get baseURL(){return n},pluginsActions:D,pluginsAtoms:E,pluginPathMethods:B,atomListeners:k,$fetch:d,$store:C}};function Mt(t){return typeof t=="object"&&t!==null&&"get"in t&&typeof t.get=="function"&&"lc"in t&&typeof t.lc=="number"}function Bt(t,e,r){let n=e[t],{fetchOptions:s,query:o,...c}=r||{};return n||(s?.method?s.method:c&&Object.keys(c).length>0?"POST":"GET")}function Ne(t,e,r,n,s){function o(c=[]){return new Proxy(function(){},{get(l,u){if(typeof u!="string"||u==="then"||u==="catch"||u==="finally")return;let a=[...c,u],i=t;for(let d of a)if(i&&typeof i=="object"&&d in i)i=i[d];else{i=void 0;break}return typeof i=="function"||Mt(i)?i:o(a)},apply:async(l,u,a)=>{let i="/"+c.map(k=>k.replace(/[A-Z]/g,C=>`-${C.toLowerCase()}`)).join("/"),d=a[0]||{},m=a[1]||{},{query:R,fetchOptions:T,...D}=d,E={...m,...T},B=Bt(i,r,d);return await e(i,{...E,body:B==="GET"?void 0:{...D,...E?.body||{}},query:R||E?.query,method:B,async onSuccess(k){if(await E?.onSuccess?.(k),!s)return;let C=s.filter(f=>f.matcher(i));if(C.length)for(let f of C){let H=n[f.signal];if(!H)return;let y=H.get();setTimeout(()=>{H.set(!y)},10)}}})}})}return o()}function Le(t){return t.charAt(0).toUpperCase()+t.slice(1)}function de(t){let{pluginPathMethods:e,pluginsActions:r,pluginsAtoms:n,$fetch:s,atomListeners:o,$store:c}=Ce(t),l={};for(let[i,d]of Object.entries(n))l[`use${Le(i)}`]=d;let u={...r,...l,$fetch:s,$store:c};return Ne(u,s,e,n,o)}function Ht(t){return{authorize(e,r="AND"){let n=!1;for(let[s,o]of Object.entries(e)){let c=t[s];if(!c)return{success:!1,error:`You are not allowed to access resource: ${s}`};if(Array.isArray(o))n=o.every(l=>c.includes(l));else if(typeof o=="object"){let l=o;l.connector==="OR"?n=l.actions.some(u=>c.includes(u)):n=l.actions.every(u=>c.includes(u))}else throw new $("Invalid access control request");if(n&&r==="OR")return{success:n};if(!n&&r==="AND")return{success:!1,error:`unauthorized to access resource "${s}"`}}return n?{success:n}:{success:!1,error:"Not authorized"}},statements:t}}function re(t){return{newRole(e){return Ht(e)},statements:t}}var $t={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"],team:["create","update","delete"],ac:["create","read","update","delete"]},fe=re($t),Ft=fe.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"],team:["create","update","delete"],ac:["create","read","update","delete"]}),qt=fe.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"],team:["create","update","delete"],ac:["create","read","update","delete"]}),jt=fe.newRole({organization:[],member:[],invitation:[],team:[],ac:["read"]});var pe=class{constructor(){Object.defineProperty(this,"controller",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}createNewAbortSignal(){if(this.controller){let r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}},Me=new pe;var Kt={user:["create","list","set-role","ban","impersonate","delete","set-password","get","update"],session:["list","revoke","delete"]},Be=re(Kt),Jt=Be.newRole({user:["create","list","set-role","ban","impersonate","delete","set-password","get","update"],session:["list","revoke","delete"]}),Yt=Be.newRole({user:[],session:[]});var He=()=>({id:"username",$InferServerPlugin:{}});var Qt="/auth",ne="nvwa_login_token",me="nvwa_user_profile",$e=class{constructor(e,r,n){this.storage=n,this.authClient=de({baseURL:e,basePath:Qt,fetchOptions:{customFetchImpl:r,auth:{type:"Bearer",token:()=>n.get(ne)},onSuccess:s=>{let o=s.response.headers.get("set-auth-token");o&&n.set(ne,o)}},plugins:[He()]})}async currentUser(){return await this.storage.get(me)}async signUp(e,r){let n=await this.authClient.signUp.email({email:e.email??`${e.username}@nvwa.app`,name:e.name,username:e.username,displayUsername:e.displayUsername,password:r});this.saveSession(n)}async signInWithUsername(e,r){let n=await this.authClient.signIn.username({username:e,password:r});this.saveSession(n)}saveSession(e){if(e.error)throw new Error(e.error.message);this.storage.set(ne,e.data?.token),this.storage.set(me,e.data?.user)}async signOut(){await this.storage.remove(ne),await this.storage.remove(me)}async updateUserPassword(e,r,n=!1){let s=await this.authClient.changePassword({currentPassword:e,newPassword:r,revokeOtherSessions:n});this.saveSession(s)}};var Fe=class{constructor(e){this.http=e}async invoke(e,r){return(await this.http.request("/functions/"+e,{method:r.method||"POST",data:r.body,headers:r.headers})).body}};var qe=class{constructor(e,r,n,s,o){this.ok=e,this.status=r,this.statusText=n,this.headers=s,this.body=o}async text(){return typeof this.body=="string"?this.body:JSON.stringify(this.body)}async json(){if(typeof this.body=="string")try{return JSON.parse(this.body)}catch{return this.body}return this.body}async arrayBuffer(){if(this.body instanceof ArrayBuffer)return this.body;if(typeof this.body=="string")return new TextEncoder().encode(this.body).buffer;throw new Error("Cannot convert body to ArrayBuffer")}async blob(){if(this.body instanceof Blob)return this.body;if(typeof this.body=="string")return new Blob([this.body],{type:this.headers["content-type"]||"text/plain"});throw new Error("Cannot convert body to Blob")}},je=class{async jsonRequest(e,r){let n={...r,headers:{"Content-Type":"application/json",...r.headers},data:typeof r.data=="object"?JSON.stringify(r.data):r.data};return this.request(e,n)}async jsonRequestWithAuth(e,r,n){let s={...r,headers:{"Content-Type":"application/json",...r.headers},data:typeof r.data=="object"?JSON.stringify(r.data):r.data};return this.requestWithAuth(e,s,n)}};var Xt="/storage",Zt=Xt+"/generateUploadUrl",We=class{constructor(e,r){this.baseUrl=e,this.http=r}async uploadFile(e){let r=await this.http.request(this.baseUrl+Zt,{method:"POST",data:{fileName:e.name||e.fileName,fileSize:e.size||e.fileSize,fileType:e.type||e.fileType}}),{url:n}=r.body;if(!n)throw new Error("\u83B7\u53D6\u4E0A\u4F20URL\u5931\u8D25");return{url:(await this.http.request(n,{method:"PUT",data:e,headers:{"Content-Type":e.type||e.fileType||"application/octet-stream"}})).body.url.split("?")[0]}}};import{PostgrestClient as tr}from"@supabase/postgrest-js";var O=class t{constructor(e){this.headerMap=new Map;if(e){if(e instanceof t)e.forEach((r,n)=>this.set(n,r));else if(Array.isArray(e))for(let[r,n]of e)this.set(r,String(n));else if(typeof e=="object")for(let r of Object.keys(e))this.set(r,String(e[r]))}}append(e,r){let n=e.toLowerCase(),s=this.headerMap.get(n);this.headerMap.set(n,s?`${s}, ${r}`:r)}set(e,r){this.headerMap.set(e.toLowerCase(),String(r))}get(e){let r=this.headerMap.get(e.toLowerCase());return r??null}has(e){return this.headerMap.has(e.toLowerCase())}delete(e){this.headerMap.delete(e.toLowerCase())}forEach(e){for(let[r,n]of this.headerMap.entries())e(n,r,this)}entries(){return this.headerMap.entries()}keys(){return this.headerMap.keys()}values(){return this.headerMap.values()}[Symbol.iterator](){return this.entries()}},K=class t{constructor(e){this.params=new Map;if(e){if(typeof e=="string")this.parseString(e);else if(e instanceof t)this.params=new Map(e.params);else if(Array.isArray(e))for(let[r,n]of e)this.append(r,n);else if(e&&typeof e=="object")for(let[r,n]of Object.entries(e))this.set(r,n)}}parseString(e){e.startsWith("?")&&(e=e.slice(1));let r=e.split("&");for(let n of r)if(n){let[s,o]=n.split("=");s&&this.append(decodeURIComponent(s),o?decodeURIComponent(o):"")}}append(e,r){let n=this.params.get(e)||[];n.push(r),this.params.set(e,n)}delete(e){this.params.delete(e)}get(e){let r=this.params.get(e);return r?r[0]:null}getAll(e){return this.params.get(e)||[]}has(e){return this.params.has(e)}set(e,r){this.params.set(e,[r])}sort(){let e=Array.from(this.params.entries()).sort(([r],[n])=>r.localeCompare(n));this.params=new Map(e)}toString(){let e=[];for(let[r,n]of this.params.entries())for(let s of n)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(s)}`);return e.join("&")}forEach(e){for(let[r,n]of this.params.entries())for(let s of n)e(s,r,this)}keys(){return this.params.keys()}values(){let e=[];for(let r of this.params.values())e.push(...r);return e[Symbol.iterator]()}entries(){let e=[];for(let[r,n]of this.params.entries())for(let s of n)e.push([r,s]);return e[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}},se=class t{constructor(e,r){let n;if(e instanceof t)n=e.href;else if(r){let o=r instanceof t?r.href:r;n=this.resolve(o,e)}else n=e;let s=this.parseUrl(n);this.href=n,this.origin=`${s.protocol}//${s.host}`,this.protocol=s.protocol,this.username=s.username,this.password=s.password,this.host=s.host,this.hostname=s.hostname,this.port=s.port,this.pathname=s.pathname,this.search=s.search,this.searchParams=new K(s.search),this.hash=s.hash}resolve(e,r){if(r.startsWith("http://")||r.startsWith("https://"))return r;if(r.startsWith("//"))return`${this.parseUrl(e).protocol}${r}`;if(r.startsWith("/")){let o=this.parseUrl(e);return`${o.protocol}//${o.host}${r}`}let n=this.parseUrl(e),s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return`${n.protocol}//${n.host}${s}${r}`}parseUrl(e){let r=e.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!r)throw new TypeError("Invalid URL");let n=r[2]||"",s=r[4]||"",o=r[5]||"/",c=r[7]?`?${r[7]}`:"",l=r[9]?`#${r[9]}`:"";if(!n&&!s&&!o.startsWith("/")&&!o.includes("/")&&!o.includes("."))throw new TypeError("Invalid URL");let u=s.match(/^([^@]*)@(.+)$/),a="",i="",d=s;if(u){let D=u[1];d=u[2];let E=D.match(/^([^:]*):?(.*)$/);E&&(a=E[1]||"",i=E[2]||"")}let m=d.match(/^([^:]+):?(\d*)$/),R=m?m[1]:d,T=m&&m[2]?m[2]:"";return{protocol:n?`${n}:`:"",username:a,password:i,host:d,hostname:R,port:T,pathname:o,search:c,hash:l}}toString(){let e=this.searchParams.toString(),r=e?`?${e}`:"";return`${this.protocol}//${this.host}${this.pathname}${r}${this.hash}`}toJSON(){return this.toString()}};var oe=class t{constructor(e,r){if(typeof e=="string")this.url=e;else if(e?.url)this.url=String(e.url);else if(typeof e?.toString=="function")this.url=String(e.toString());else throw new Error("Invalid input for Request");this.method=(r?.method||"GET").toUpperCase(),this.headers=r?.headers instanceof O?r.headers:new O(r?.headers),this.body=r?.body,this.timeout=r?.timeout,this.signal=r?.signal||void 0}clone(){return new t(this.url,{method:this.method,headers:this.headers,body:this.body,timeout:this.timeout})}toString(){return this.url}};var F=class{constructor(e,r){this.bodyData=e,this.status=r?.status??200,this.statusText=r?.statusText??"",this.headers=er(r?.headers),this.ok=this.status>=200&&this.status<300}async text(){return typeof this.bodyData=="string"?this.bodyData:this.bodyData==null?"":typeof this.bodyData=="object"?JSON.stringify(this.bodyData):String(this.bodyData)}async json(){if(typeof this.bodyData=="string")try{return JSON.parse(this.bodyData)}catch{}return this.bodyData}async arrayBuffer(){let e=await this.text();return new TextEncoder().encode(e).buffer}};function er(t){return t?new O(t):new O}var J=class{constructor(){this._aborted=!1;this.listeners=new Set;this.onabort=null}get aborted(){return this._aborted}_trigger(){if(!this._aborted){if(this._aborted=!0,typeof this.onabort=="function")try{this.onabort()}catch{}for(let e of Array.from(this.listeners))try{e()}catch{}this.listeners.clear()}}addEventListener(e,r){if(this._aborted){try{r()}catch{}return}this.listeners.add(r)}removeEventListener(e,r){this.listeners.delete(r)}toString(){return"[object AbortSignal]"}},ie=class{constructor(){this._signal=new J}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}};function jo(t){t.URL=se,t.URLSearchParams=K,t.Headers=O,t.Request=oe,t.Response=F,t.AbortController=ie,t.AbortSignal=J}var rr="/entities",nr=(t,e)=>async(n,s)=>{console.log("customFetch",n,s);let o;if(typeof n=="string")o=n;else if(n&&typeof n=="object")if(typeof n.toString=="function"&&!n.url)o=n.toString();else if(n.url)o=n.url,s||(s={}),s.method=n.method,s.headers=n.headers,s.body=n.body;else throw new Error("Unsupported input type for fetch");else throw new Error("Unsupported input type for fetch");let c=(s?.method||"GET").toUpperCase(),l={};if(s?.headers)if(s.headers&&typeof s.headers.forEach=="function")s.headers.forEach((R,T)=>{l[T]=R});else if(Array.isArray(s.headers))for(let[R,T]of s.headers)l[R]=T;else Object.assign(l,s.headers);let u=s?.body,a;try{a=await t.requestWithAuth(o,{method:c,data:u,headers:l},e)}catch(R){return new F(R?.message||"Internal Error",{status:500,statusText:"Internal Error"})}let i=a.body,d=null;return(a.headers["content-type"]||a.headers["Content-Type"]||"").startsWith("application/json")&&typeof i!="string"?d=JSON.stringify(i):typeof i=="string"||i&&(i.constructor===Blob||i.constructor===ArrayBuffer||typeof i.getReader=="function")?d=i:d=JSON.stringify(i),new F(d,{status:a.status,headers:new O(a.headers)})},oi=(t,e,r)=>new tr(t+rr,{fetch:nr(e,r)});export{Qt as AUTH_BASE_PATH,ie as AbortController,J as AbortSignal,rr as ENTITIES_BASE_PATH,Xt as FILE_STORAGE_BASE_PATH,qe as FetchResponse,Zt as GENERATE_UPLOAD_URL_PATH,O as Headers,ne as LOGIN_TOKEN_KEY,me as LOGIN_USER_PROFILE_KEY,$e as NvwaAuthClient,Fe as NvwaEdgeFunctions,We as NvwaFileStorage,je as NvwaHttpClient,oe as Request,F as Response,se as URL,K as URLSearchParams,oi as createPostgrestClient,jo as polyfill};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nvwa-app/sdk-core",
3
- "version": "0.4.5",
3
+ "version": "0.4.6",
4
4
  "description": "NVWA跨端通用工具类核心接口",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -29,9 +29,8 @@
29
29
  "directory": "packages/core"
30
30
  },
31
31
  "dependencies": {
32
- "@nvwa-app/postgrest-js": "^2.75.15",
33
- "better-auth": "^1.3.34",
34
- "jwt-decode": "^4.0.0"
32
+ "@supabase/postgrest-js": "^2.77.0",
33
+ "better-auth": "^1.3.34"
35
34
  },
36
35
  "devDependencies": {
37
36
  "@types/node": "^24.3.0",