@nvwa-app/sdk-uniapp 0.4.4 → 0.4.7

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,4 @@
1
- import { NvwaHttpClient, HttpRequest, HttpResponse, RequestInit, Response, NvwaLocalStorage, INvwa, NvwaAuthClient, NvwaFileStorage, NvwaEdgeFunctions } from '@nvwa-app/sdk-core';
2
- import { PostgrestClient } from '@nvwa-app/postgrest-js';
1
+ import { NvwaHttpClient, HttpRequest, HttpResponse, RequestInit, Response, NvwaLocalStorage, INvwa, NvwaAuthClient, NvwaFileStorage, createPostgrestClient, NvwaEdgeFunctions } from '@nvwa-app/sdk-core';
3
2
 
4
3
  declare class UniAppNvwaHttpClient extends NvwaHttpClient {
5
4
  request<T>(url: string | URL, request: HttpRequest): Promise<HttpResponse<T>>;
@@ -21,7 +20,7 @@ declare const httpClient: UniAppNvwaHttpClient;
21
20
  declare class Nvwa implements INvwa {
22
21
  auth: NvwaAuthClient;
23
22
  fileStorage: NvwaFileStorage;
24
- entities: PostgrestClient;
23
+ entities: ReturnType<typeof createPostgrestClient>;
25
24
  functions: NvwaEdgeFunctions;
26
25
  constructor(baseUrl: string, handleUnauthorized: () => void);
27
26
  }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,4 @@
1
- import { NvwaHttpClient, HttpRequest, HttpResponse, RequestInit, Response, NvwaLocalStorage, INvwa, NvwaAuthClient, NvwaFileStorage, NvwaEdgeFunctions } from '@nvwa-app/sdk-core';
2
- import { PostgrestClient } from '@nvwa-app/postgrest-js';
1
+ import { NvwaHttpClient, HttpRequest, HttpResponse, RequestInit, Response, NvwaLocalStorage, INvwa, NvwaAuthClient, NvwaFileStorage, createPostgrestClient, NvwaEdgeFunctions } from '@nvwa-app/sdk-core';
3
2
 
4
3
  declare class UniAppNvwaHttpClient extends NvwaHttpClient {
5
4
  request<T>(url: string | URL, request: HttpRequest): Promise<HttpResponse<T>>;
@@ -21,7 +20,7 @@ declare const httpClient: UniAppNvwaHttpClient;
21
20
  declare class Nvwa implements INvwa {
22
21
  auth: NvwaAuthClient;
23
22
  fileStorage: NvwaFileStorage;
24
- entities: PostgrestClient;
23
+ entities: ReturnType<typeof createPostgrestClient>;
25
24
  functions: NvwaEdgeFunctions;
26
25
  constructor(baseUrl: string, handleUnauthorized: () => void);
27
26
  }
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var S=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var I=Object.getOwnPropertyNames;var T=Object.prototype.hasOwnProperty;var U=(o,e)=>{for(var t in e)S(o,t,{get:e[t],enumerable:!0})},K=(o,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of I(e))!T.call(o,r)&&r!==t&&S(o,r,{get:()=>e[r],enumerable:!(s=C(e,r))||s.enumerable});return o};var j=o=>K(S({},"__esModule",{value:!0}),o);var D={};U(D,{default:()=>v,httpClient:()=>w,localStorage:()=>H});module.exports=j(D);var l=require("@nvwa-app/sdk-core");var P=require("@nvwa-app/sdk-core"),E=require("@nvwa-app/sdk-core");var y=require("@nvwa-app/sdk-core"),O=(o,e)=>{let t;if(typeof o=="string")t=o;else if(o&&typeof o.toString=="function")t=o.toString();else if(o?.url)t=o.url;else throw new Error("Invalid input for uniappFetch");let s=(e?.method||"GET").toUpperCase(),r={};if(e?.headers){let n=e.headers;if(typeof n?.forEach=="function")n.forEach((c,i)=>{r[i]=c});else if(Array.isArray(n))for(let[c,i]of n)r[c]=i;else Object.assign(r,n)}let f;if(e?.body!==void 0){let n=e.body;if(typeof n=="string")f=n;else if(n&&typeof n=="object"&&typeof n.forEach=="function"){let c={};n.forEach((i,u)=>{c[u]=i}),f=c}else f=n}let F=e?.timeout||3e4;return new Promise((n,c)=>{let i=e?.signal;if(i?.aborted){let a=new Error("The operation was aborted");a.name="AbortError",c(a);return}let u=!1,L=[],q=uni.request({url:t,method:s,data:f,header:r,timeout:F,success:a=>{if(u)return;u=!0;let p=a.statusCode,d="",A=new y.Headers,N=a.header||a.headers||{};Object.keys(N).forEach(x=>{let b=N[x];A.set(x,typeof b=="string"?b:String(b))}),n(new y.Response(a.data,{status:p,statusText:d,headers:A}))},fail:a=>{if(u)return;u=!0;let p=a?.errMsg||a?.message||"Network Error",d=new Error(p);/(abort|aborted|canceled|cancelled)/i.test(String(p))&&(d.name="AbortError"),c(d)}});if(i&&typeof i.addEventListener=="function"){let a=()=>{if(u)return;try{q?.abort?.()}catch{}let p=new Error("The operation was aborted");p.name="AbortError",u=!0,c(p)};i.addEventListener("abort",a),L.push(()=>{try{i.removeEventListener?.("abort",a)}catch{}})}})},h=O;var m=class extends P.NvwaHttpClient{async request(e,t){let s=await h(e,{method:t.method,headers:new E.Headers(t.headers),body:t.data});return{status:s.status,body:await s.json(),headers:Object.fromEntries(s.headers.entries())}}async requestWithAuth(e,t,s){let r=await this.fetchWithAuth(s,e,{method:t.method,headers:new E.Headers(t.headers),body:t.data});return{status:r.status,body:await r.json(),headers:Object.fromEntries(r.headers.entries())}}async fetchWithAuth(e,t,s){let r=await h(t,s);if(r.status===401)throw e(),new Error("\u672A\u767B\u5F55");return r}};var g=class{constructor(){this.prefix="nvwa_"}getKey(e){return`${this.prefix}${e}`}async get(e){try{let t=this.getKey(e),s=uni.getStorageSync(t);return s?s.expires&&Date.now()>s.expires?(await this.remove(e),null):s.value:null}catch(t){return console.error("UniAppStorageService get error:",t),null}}async set(e,t,s){try{let r=this.getKey(e),f={value:t,expires:s?Date.now()+s*1e3:null,timestamp:Date.now()};uni.setStorageSync(r,f)}catch(r){throw console.error("UniAppStorageService set error:",r),r}}async remove(e){try{let t=this.getKey(e);uni.removeStorageSync(t)}catch(t){throw console.error("UniAppStorageService remove error:",t),t}}async clear(){try{uni.clearStorageSync()}catch(e){throw console.error("UniAppStorageService clear error:",e),e}}};var H=new g,w=new m,v=class{constructor(e,t){this.auth=new l.NvwaAuthClient(e,h,H),this.fileStorage=new l.NvwaFileStorage(e,w),this.entities=(0,l.createPostgrestClient)(e,w,t),this.functions=new l.NvwaEdgeFunctions(w)}};0&&(module.exports={httpClient,localStorage});
1
+ "use strict";var ie=Object.defineProperty;var Ve=Object.getOwnPropertyDescriptor;var Ke=Object.getOwnPropertyNames;var Ye=Object.prototype.hasOwnProperty;var Xe=(e,t)=>{for(var r in t)ie(e,r,{get:t[r],enumerable:!0})},Qe=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Ke(t))!Ye.call(e,n)&&n!==r&&ie(e,n,{get:()=>t[n],enumerable:!(i=Ve(t,n))||i.enumerable});return e};var Ze=e=>Qe(ie({},"__esModule",{value:!0}),e);var Sr={};Xe(Sr,{default:()=>ae,httpClient:()=>ne,localStorage:()=>Je});module.exports=Ze(Sr);var et=Object.create,Oe=Object.defineProperty,tt=Object.getOwnPropertyDescriptor,rt=Object.getOwnPropertyNames,st=Object.getPrototypeOf,nt=Object.prototype.hasOwnProperty,at=(e,t)=>()=>(e&&(t=e(e=0)),t),C=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ot=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of rt(t))!nt.call(e,n)&&n!==r&&Oe(e,n,{get:()=>t[n],enumerable:!(i=tt(t,n))||i.enumerable});return e},it=(e,t,r)=>(r=e!=null?et(st(e)):{},ot(t||!e||!e.__esModule?Oe(r,"default",{value:e,enumerable:!0}):r,e)),p=at(()=>{"use strict"}),te=C(e=>{"use strict";p(),Object.defineProperty(e,"__esModule",{value:!0}),e.File=e.FormData=e.Blob=e.FetchResponse=e.URL=e.URLSearchParams=e.FetchHeaders=void 0;var t=class{constructor(l){if(this.map=new Map,l)for(let[s,o]of Object.entries(l))this.set(s,o)}get(l){var s;return(s=this.map.get(l))!==null&&s!==void 0?s:null}set(l,s){this.map.set(l,s)}has(l){return this.map.has(l)}append(l,s){let o=this.map.get(l);o?this.map.set(l,`${o}${s}`):this.map.set(l,s)}delete(l){this.map.delete(l)}forEach(l){this.map.forEach(l)}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]()}};e.FetchHeaders=t;var r=class Pe{constructor(s){if(this.params=new Map,s){if(typeof s=="string")this.parseString(s);else if(s instanceof Pe)this.params=new Map(s.params);else if(Array.isArray(s))for(let[o,c]of s)this.append(o,c);else if(s&&typeof s=="object")for(let[o,c]of Object.entries(s))this.set(o,c)}}parseString(s){s.startsWith("?")&&(s=s.slice(1));let o=s.split("&");for(let c of o)if(c){let[d,m]=c.split("=");d&&this.append(decodeURIComponent(d),m?decodeURIComponent(m):"")}}append(s,o){let c=this.params.get(s)||[];c.push(o),this.params.set(s,c)}delete(s){this.params.delete(s)}get(s){let o=this.params.get(s);return o?o[0]:null}getAll(s){return this.params.get(s)||[]}has(s){return this.params.has(s)}set(s,o){this.params.set(s,[o])}sort(){let s=Array.from(this.params.entries()).sort(([o],[c])=>o.localeCompare(c));this.params=new Map(s)}toString(){let s=[];for(let[o,c]of this.params.entries())for(let d of c)s.push(`${encodeURIComponent(o)}=${encodeURIComponent(d)}`);return s.join("&")}forEach(s){for(let[o,c]of this.params.entries())for(let d of c)s(d,o,this)}keys(){return this.params.keys()}values(){let s=[];for(let o of this.params.values())s.push(...o);return s[Symbol.iterator]()}entries(){let s=[];for(let[o,c]of this.params.entries())for(let d of c)s.push([o,d]);return s[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}};e.URLSearchParams=r;var i=class ue{constructor(s,o){let c;if(s instanceof ue)c=s.href;else if(o){let m=o instanceof ue?o.href:o;c=this.resolve(m,s)}else c=s;let d=this.parseUrl(c);this.href=c,this.origin=`${d.protocol}//${d.host}`,this.protocol=d.protocol,this.username=d.username,this.password=d.password,this.host=d.host,this.hostname=d.hostname,this.port=d.port,this.pathname=d.pathname,this.search=d.search,this.searchParams=new r(d.search),this.hash=d.hash}resolve(s,o){if(o.startsWith("http://")||o.startsWith("https://"))return o;if(o.startsWith("//"))return`${this.parseUrl(s).protocol}${o}`;if(o.startsWith("/")){let m=this.parseUrl(s);return`${m.protocol}//${m.host}${o}`}let c=this.parseUrl(s),d=c.pathname.endsWith("/")?c.pathname:c.pathname+"/";return`${c.protocol}//${c.host}${d}${o}`}parseUrl(s){let o=s.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!o)throw new TypeError("Invalid URL");let c=o[2]||"",d=o[4]||"",m=o[5]||"/",y=o[7]?`?${o[7]}`:"",g=o[9]?`#${o[9]}`:"";if(!c&&!d&&!m.startsWith("/")&&!m.includes("/")&&!m.includes("."))throw new TypeError("Invalid URL");let v=d.match(/^([^@]*)@(.+)$/),T="",b="",R=d;if(v){let z=v[1];R=v[2];let k=z.match(/^([^:]*):?(.*)$/);k&&(T=k[1]||"",b=k[2]||"")}let f=R.match(/^([^:]+):?(\d*)$/),A=f?f[1]:R,w=f&&f[2]?f[2]:"";return{protocol:c?`${c}:`:"",username:T,password:b,host:R,hostname:A,port:w,pathname:m,search:y,hash:g}}toString(){let s=this.searchParams.toString(),o=s?`?${s}`:"";return`${this.protocol}//${this.host}${this.pathname}${o}${this.hash}`}toJSON(){return this.toString()}};e.URL=i;var n=class G{constructor(s,o){var c,d;this.status=(c=o?.status)!==null&&c!==void 0?c:200,this.statusText=(d=o?.statusText)!==null&&d!==void 0?d:"",this.headers=new t(o?.headers),this.ok=this.status>=200&&this.status<300,this.redirected=!1,this.url="",this.bodyUsed=!1,this.body=s||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 a([this.body||""])}async formData(){if(this.bodyUsed)throw new TypeError("Body has already been consumed");return this.bodyUsed=!0,new u}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 G(this.body,{status:this.status,statusText:this.statusText,headers:this.headers.headers()})}static error(){let s=new G(null,{status:0,statusText:""});return Object.defineProperty(s,"type",{value:"error",writable:!1}),s}static redirect(s,o=302){let c=s instanceof i?s.href:s,d=new G(null,{status:o,statusText:"Found"});return d.headers.set("Location",c),d}static json(s,o){let c=JSON.stringify(s),d=new t(o?.headers);return d.set("Content-Type","application/json"),new G(c,Object.assign(Object.assign({},o),{headers:d.headers()}))}};e.FetchResponse=n;var a=class Ae{constructor(s,o){this._content=s||[],this.type=o?.type||"";let c=0;for(let d of this._content)typeof d=="string"?c+=new TextEncoder().encode(d).length:d instanceof ArrayBuffer?c+=d.byteLength:d instanceof Uint8Array&&(c+=d.length);this.size=c}async text(){let s="";for(let o of this._content)typeof o=="string"?s+=o:o instanceof ArrayBuffer?s+=new TextDecoder().decode(o):o instanceof Uint8Array&&(s+=new TextDecoder().decode(o));return s}async arrayBuffer(){let s=await this.text();return new TextEncoder().encode(s).buffer}slice(s,o,c){return new Ae(this._content.slice(s,o),{type:c})}};e.Blob=a;var u=class{constructor(){this._entries=[]}append(l,s,o){this._entries.push([l,s])}delete(l){this._entries=this._entries.filter(([s])=>s!==l)}get(l){let s=this._entries.find(([o])=>o===l);return s?s[1]:null}getAll(l){return this._entries.filter(([s])=>s===l).map(([,s])=>s)}has(l){return this._entries.some(([s])=>s===l)}set(l,s,o){this.delete(l),this.append(l,s,o)}forEach(l){for(let[s,o]of this._entries)l(o,s,this)}keys(){return this._entries.map(([l])=>l)[Symbol.iterator]()}values(){return this._entries.map(([,l])=>l)[Symbol.iterator]()}entries(){return this._entries[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}};e.FormData=u;var h=class extends a{constructor(l,s,o){super(l,o),this.name=s,this.lastModified=o?.lastModified||Date.now()}};e.File=h}),_e=C(e=>{"use strict";p(),Object.defineProperty(e,"__esModule",{value:!0});var t=class extends Error{constructor(r){super(r.message),this.name="PostgrestError",this.details=r.details,this.hint=r.hint,this.code=r.code}};e.default=t}),$e=C(e=>{"use strict";p();var t=e&&e.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(e,"__esModule",{value:!0});var r=t(_e()),i=te(),n=class{constructor(a){var u,h;this.shouldThrowOnError=!1,this.method=a.method,this.url=a.url,this.headers=new i.FetchHeaders(a.headers),this.schema=a.schema,this.body=a.body,this.shouldThrowOnError=(u=a.shouldThrowOnError)!==null&&u!==void 0?u:!1,this.signal=a.signal,this.isMaybeSingle=(h=a.isMaybeSingle)!==null&&h!==void 0?h:!1,a.fetch?this.fetch=a.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(a,u){return this.headers=new i.FetchHeaders(this.headers),this.headers.set(a,u),this}then(a,u){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 h=this.fetch,l=h(this.url.toString(),{method:this.method,headers:this.headers.headers(),body:JSON.stringify(this.body),signal:this.signal}).then(async s=>{var o,c,d,m;let y=null,g=null,v=null,T=s.status,b=s.statusText;if(s.ok){if(this.method!=="HEAD"){let A=await s.text();A===""||(this.headers.get("Accept")==="text/csv"||this.headers.get("Accept")&&!((o=this.headers.get("Accept"))===null||o===void 0)&&o.includes("application/vnd.pgrst.plan+text")?g=A:g=JSON.parse(A))}let R=(c=this.headers.get("Prefer"))===null||c===void 0?void 0:c.match(/count=(exact|planned|estimated)/),f=(d=s.headers.get("content-range"))===null||d===void 0?void 0:d.split("/");R&&f&&f.length>1&&(v=parseInt(f[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(g)&&(g.length>1?(y={code:"PGRST116",details:`Results contain ${g.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},g=null,v=null,T=406,b="Not Acceptable"):g.length===1?g=g[0]:g=null)}else{let R=await s.text();try{y=JSON.parse(R),Array.isArray(y)&&s.status===404&&(g=[],y=null,T=200,b="OK")}catch{s.status===404&&R===""?(T=204,b="No Content"):y={message:R}}if(y&&this.isMaybeSingle&&!((m=y?.details)===null||m===void 0)&&m.includes("0 rows")&&(y=null,T=200,b="OK"),y&&this.shouldThrowOnError)throw new r.default(y)}return{error:y,data:g,count:v,status:T,statusText:b}});return this.shouldThrowOnError||(l=l.catch(s=>{var o,c,d;return{error:{message:`${(o=s?.name)!==null&&o!==void 0?o:"FetchError"}: ${s?.message}`,details:`${(c=s?.stack)!==null&&c!==void 0?c:""}`,hint:"",code:`${(d=s?.code)!==null&&d!==void 0?d:""}`},data:null,count:null,status:0,statusText:""}})),l.then(a,u)}returns(){return this}overrideTypes(){return this}};e.default=n}),Ue=C(e=>{"use strict";p();var t=e&&e.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(e,"__esModule",{value:!0});var r=t($e()),i=class extends r.default{select(n){let a=!1,u=(n??"*").split("").map(h=>/\s/.test(h)&&!a?"":(h==='"'&&(a=!a),h)).join("");return this.url.searchParams.set("select",u),this.headers.append("Prefer","return=representation"),this}order(n,{ascending:a=!0,nullsFirst:u,foreignTable:h,referencedTable:l=h}={}){let s=l?`${l}.order`:"order",o=this.url.searchParams.get(s);return this.url.searchParams.set(s,`${o?`${o},`:""}${n}.${a?"asc":"desc"}${u===void 0?"":u?".nullsfirst":".nullslast"}`),this}limit(n,{foreignTable:a,referencedTable:u=a}={}){let h=typeof u>"u"?"limit":`${u}.limit`;return this.url.searchParams.set(h,`${n}`),this}range(n,a,{foreignTable:u,referencedTable:h=u}={}){let l=typeof h>"u"?"offset":`${h}.offset`,s=typeof h>"u"?"limit":`${h}.limit`;return this.url.searchParams.set(l,`${n}`),this.url.searchParams.set(s,`${a-n+1}`),this}abortSignal(n){return this.signal=n,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:n=!1,verbose:a=!1,settings:u=!1,buffers:h=!1,wal:l=!1,format:s="text"}={}){var o;let c=[n?"analyze":null,a?"verbose":null,u?"settings":null,h?"buffers":null,l?"wal":null].filter(Boolean).join("|"),d=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${s}; for="${d}"; options=${c};`),s==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(n){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${n}`),this}};e.default=i}),pe=C(e=>{"use strict";p();var t=e&&e.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(e,"__esModule",{value:!0});var r=t(Ue()),i=class extends r.default{eq(n,a){return this.url.searchParams.append(n,`eq.${a}`),this}neq(n,a){return this.url.searchParams.append(n,`neq.${a}`),this}gt(n,a){return this.url.searchParams.append(n,`gt.${a}`),this}gte(n,a){return this.url.searchParams.append(n,`gte.${a}`),this}lt(n,a){return this.url.searchParams.append(n,`lt.${a}`),this}lte(n,a){return this.url.searchParams.append(n,`lte.${a}`),this}like(n,a){return this.url.searchParams.append(n,`like.${a}`),this}likeAllOf(n,a){return this.url.searchParams.append(n,`like(all).{${a.join(",")}}`),this}likeAnyOf(n,a){return this.url.searchParams.append(n,`like(any).{${a.join(",")}}`),this}ilike(n,a){return this.url.searchParams.append(n,`ilike.${a}`),this}ilikeAllOf(n,a){return this.url.searchParams.append(n,`ilike(all).{${a.join(",")}}`),this}ilikeAnyOf(n,a){return this.url.searchParams.append(n,`ilike(any).{${a.join(",")}}`),this}is(n,a){return this.url.searchParams.append(n,`is.${a}`),this}in(n,a){let u=Array.from(new Set(a)).map(h=>typeof h=="string"&&new RegExp("[,()]").test(h)?`"${h}"`:`${h}`).join(",");return this.url.searchParams.append(n,`in.(${u})`),this}contains(n,a){return typeof a=="string"?this.url.searchParams.append(n,`cs.${a}`):Array.isArray(a)?this.url.searchParams.append(n,`cs.{${a.join(",")}}`):this.url.searchParams.append(n,`cs.${JSON.stringify(a)}`),this}containedBy(n,a){return typeof a=="string"?this.url.searchParams.append(n,`cd.${a}`):Array.isArray(a)?this.url.searchParams.append(n,`cd.{${a.join(",")}}`):this.url.searchParams.append(n,`cd.${JSON.stringify(a)}`),this}rangeGt(n,a){return this.url.searchParams.append(n,`sr.${a}`),this}rangeGte(n,a){return this.url.searchParams.append(n,`nxl.${a}`),this}rangeLt(n,a){return this.url.searchParams.append(n,`sl.${a}`),this}rangeLte(n,a){return this.url.searchParams.append(n,`nxr.${a}`),this}rangeAdjacent(n,a){return this.url.searchParams.append(n,`adj.${a}`),this}overlaps(n,a){return typeof a=="string"?this.url.searchParams.append(n,`ov.${a}`):this.url.searchParams.append(n,`ov.{${a.join(",")}}`),this}textSearch(n,a,{config:u,type:h}={}){let l="";h==="plain"?l="pl":h==="phrase"?l="ph":h==="websearch"&&(l="w");let s=u===void 0?"":`(${u})`;return this.url.searchParams.append(n,`${l}fts${s}.${a}`),this}match(n){return Object.entries(n).forEach(([a,u])=>{this.url.searchParams.append(a,`eq.${u}`)}),this}not(n,a,u){return this.url.searchParams.append(n,`not.${a}.${u}`),this}or(n,{foreignTable:a,referencedTable:u=a}={}){let h=u?`${u}.or`:"or";return this.url.searchParams.append(h,`(${n})`),this}filter(n,a,u){return this.url.searchParams.append(n,`${a}.${u}`),this}};e.default=i}),xe=C(e=>{"use strict";p();var t=e&&e.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(e,"__esModule",{value:!0});var r=te(),i=t(pe()),n=class{constructor(a,{headers:u={},schema:h,fetch:l}){this.url=a,this.headers=new r.FetchHeaders(u),this.schema=h,this.fetch=l}select(a,u){let{head:h=!1,count:l}=u??{},s=h?"HEAD":"GET",o=!1,c=(a??"*").split("").map(d=>/\s/.test(d)&&!o?"":(d==='"'&&(o=!o),d)).join("");return this.url.searchParams.set("select",c),l&&this.headers.append("Prefer",`count=${l}`),new i.default({method:s,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch})}insert(a,{count:u,defaultToNull:h=!0}={}){var l;let s="POST";if(u&&this.headers.append("Prefer",`count=${u}`),h||this.headers.append("Prefer","missing=default"),Array.isArray(a)){let o=a.reduce((c,d)=>c.concat(Object.keys(d)),[]);if(o.length>0){let c=[...new Set(o)].map(d=>`"${d}"`);this.url.searchParams.set("columns",c.join(","))}}return new i.default({method:s,url:this.url,headers:this.headers,schema:this.schema,body:a,fetch:(l=this.fetch)!==null&&l!==void 0?l:fetch})}upsert(a,{onConflict:u,ignoreDuplicates:h=!1,count:l,defaultToNull:s=!0}={}){var o;let c="POST";if(this.headers.append("Prefer",`resolution=${h?"ignore":"merge"}-duplicates`),u!==void 0&&this.url.searchParams.set("on_conflict",u),l&&this.headers.append("Prefer",`count=${l}`),s||this.headers.append("Prefer","missing=default"),Array.isArray(a)){let d=a.reduce((m,y)=>m.concat(Object.keys(y)),[]);if(d.length>0){let m=[...new Set(d)].map(y=>`"${y}"`);this.url.searchParams.set("columns",m.join(","))}}return new i.default({method:c,url:this.url,headers:this.headers,schema:this.schema,body:a,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch})}update(a,{count:u}={}){var h;let l="PATCH";return u&&this.headers.append("Prefer",`count=${u}`),new i.default({method:l,url:this.url,headers:this.headers,schema:this.schema,body:a,fetch:(h=this.fetch)!==null&&h!==void 0?h:fetch})}delete({count:a}={}){var u;let h="DELETE";return a&&this.headers.append("Prefer",`count=${a}`),new i.default({method:h,url:this.url,headers:this.headers,schema:this.schema,fetch:(u=this.fetch)!==null&&u!==void 0?u:fetch})}};e.default=n}),lt=C(e=>{"use strict";p();var t=e&&e.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(e,"__esModule",{value:!0});var r=t(xe()),i=t(pe()),n=te(),a=class Ne{constructor(h,{headers:l={},schema:s,fetch:o}={}){this.url=h,this.headers=new n.FetchHeaders(l),this.schemaName=s,this.fetch=o}from(h){let l=new n.URL(`${this.url}/${h}`);return new r.default(l,{headers:new n.FetchHeaders(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(h){return new Ne(this.url,{headers:this.headers,schema:h,fetch:this.fetch})}rpc(h,l={},{head:s=!1,get:o=!1,count:c}={}){var d;let m,y=new n.URL(`${this.url}/rpc/${h}`),g;s||o?(m=s?"HEAD":"GET",Object.entries(l).filter(([T,b])=>b!==void 0).map(([T,b])=>[T,Array.isArray(b)?`{${b.join(",")}}`:`${b}`]).forEach(([T,b])=>{y.searchParams.append(T,b)})):(m="POST",g=l);let v=new n.FetchHeaders(this.headers);return c&&v.set("Prefer",`count=${c}`),new i.default({method:m,url:y,headers:v,schema:this.schemaName,body:g,fetch:(d=this.fetch)!==null&&d!==void 0?d:fetch})}};e.default=a}),ut=C(e=>{"use strict";p();var t=e&&e.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(e,"__esModule",{value:!0}),e.File=e.FormData=e.Blob=e.FetchResponse=e.FetchHeaders=e.URLSearchParams=e.URL=e.PostgrestError=e.PostgrestBuilder=e.PostgrestTransformBuilder=e.PostgrestFilterBuilder=e.PostgrestQueryBuilder=e.PostgrestClient=void 0;var r=t(lt());e.PostgrestClient=r.default;var i=t(xe());e.PostgrestQueryBuilder=i.default;var n=t(pe());e.PostgrestFilterBuilder=n.default;var a=t(Ue());e.PostgrestTransformBuilder=a.default;var u=t($e());e.PostgrestBuilder=u.default;var h=t(_e());e.PostgrestError=h.default;var l=te();Object.defineProperty(e,"FetchHeaders",{enumerable:!0,get:function(){return l.FetchHeaders}}),Object.defineProperty(e,"FetchResponse",{enumerable:!0,get:function(){return l.FetchResponse}}),Object.defineProperty(e,"URL",{enumerable:!0,get:function(){return l.URL}}),Object.defineProperty(e,"URLSearchParams",{enumerable:!0,get:function(){return l.URLSearchParams}}),Object.defineProperty(e,"Blob",{enumerable:!0,get:function(){return l.Blob}}),Object.defineProperty(e,"FormData",{enumerable:!0,get:function(){return l.FormData}}),Object.defineProperty(e,"File",{enumerable:!0,get:function(){return l.File}}),e.default={PostgrestClient:r.default,PostgrestQueryBuilder:i.default,PostgrestFilterBuilder:n.default,PostgrestTransformBuilder:a.default,PostgrestBuilder:u.default,PostgrestError:h.default,URLSearchParams:l.URLSearchParams,FetchHeaders:l.FetchHeaders,FetchResponse:l.FetchResponse}});p();p();p();p();p();p();var ht=Object.defineProperty,ct=Object.defineProperties,dt=Object.getOwnPropertyDescriptors,ge=Object.getOwnPropertySymbols,pt=Object.prototype.hasOwnProperty,ft=Object.prototype.propertyIsEnumerable,be=(e,t,r)=>t in e?ht(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,x=(e,t)=>{for(var r in t||(t={}))pt.call(t,r)&&be(e,r,t[r]);if(ge)for(var r of ge(t))ft.call(t,r)&&be(e,r,t[r]);return e},N=(e,t)=>ct(e,dt(t)),mt=class extends Error{constructor(e,t,r){super(t||e.toString(),{cause:r}),this.status=e,this.statusText=t,this.error=r}},yt=async(e,t)=>{var r,i,n,a,u,h;let l=t||{},s={onRequest:[t?.onRequest],onResponse:[t?.onResponse],onSuccess:[t?.onSuccess],onError:[t?.onError],onRetry:[t?.onRetry]};if(!t||!t?.plugins)return{url:e,options:l,hooks:s};for(let o of t?.plugins||[]){if(o.init){let c=await((r=o.init)==null?void 0:r.call(o,e.toString(),t));l=c.options||l,e=c.url}s.onRequest.push((i=o.hooks)==null?void 0:i.onRequest),s.onResponse.push((n=o.hooks)==null?void 0:n.onResponse),s.onSuccess.push((a=o.hooks)==null?void 0:a.onSuccess),s.onError.push((u=o.hooks)==null?void 0:u.onError),s.onRetry.push((h=o.hooks)==null?void 0:h.onRetry)}return{url:e,options:l,hooks:s}},ve=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(){return this.options.delay}},gt=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(e){return Math.min(this.options.maxDelay,this.options.baseDelay*2**e)}};function bt(e){if(typeof e=="number")return new ve({type:"linear",attempts:e,delay:1e3});switch(e.type){case"linear":return new ve(e);case"exponential":return new gt(e);default:throw new Error("Invalid retry strategy")}}var vt=async e=>{let t={},r=async i=>typeof i=="function"?await i():i;if(e?.auth){if(e.auth.type==="Bearer"){let i=await r(e.auth.token);if(!i)return t;t.authorization=`Bearer ${i}`}else if(e.auth.type==="Basic"){let i=r(e.auth.username),n=r(e.auth.password);if(!i||!n)return t;t.authorization=`Basic ${btoa(`${i}:${n}`)}`}else if(e.auth.type==="Custom"){let i=r(e.auth.value);if(!i)return t;t.authorization=`${r(e.auth.prefix)} ${i}`}}return t},wt=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function Et(e){let t=e.headers.get("content-type"),r=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!t)return"json";let i=t.split(";").shift()||"";return wt.test(i)?"json":r.has(i)||i.startsWith("text/")?"text":"blob"}function Tt(e){try{return JSON.parse(e),!0}catch{return!1}}function je(e){if(e===void 0)return!1;let t=typeof e;return t==="string"||t==="number"||t==="boolean"||t===null?!0:t!=="object"?!1:Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name==="Object"||typeof e.toJSON=="function"}function we(e){try{return JSON.parse(e)}catch{return e}}function Ee(e){return typeof e=="function"}function Rt(e){if(e?.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<"u"&&Ee(globalThis.fetch))return globalThis.fetch;if(typeof window<"u"&&Ee(window.fetch))return window.fetch;throw new Error("No fetch implementation found")}async function St(e){let t=new Headers(e?.headers),r=await vt(e);for(let[i,n]of Object.entries(r||{}))t.set(i,n);if(!t.has("content-type")){let i=Ot(e?.body);i&&t.set("content-type",i)}return t}function Ot(e){return je(e)?"application/json":null}function Pt(e){if(!e?.body)return null;let t=new Headers(e?.headers);if(je(e.body)&&!t.has("content-type")){for(let[r,i]of Object.entries(e?.body))i instanceof Date&&(e.body[r]=i.toISOString());return JSON.stringify(e.body)}return e.body}function At(e,t){var r;if(t?.method)return t.method.toUpperCase();if(e.startsWith("@")){let i=(r=e.split("@")[1])==null?void 0:r.split("/")[0];return Le.includes(i)?i.toUpperCase():t?.body?"POST":"GET"}return t?.body?"POST":"GET"}function _t(e,t){let r;return!e?.signal&&e?.timeout&&(r=setTimeout(()=>t?.abort(),e?.timeout)),{abortTimeout:r,clearTimeout:()=>{r&&clearTimeout(r)}}}var $t=class Ie extends Error{constructor(t,r){super(r||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,Ie.prototype)}};async function Q(e,t){let r=await e["~standard"].validate(t);if(r.issues)throw new $t(r.issues);return r.value}var Le=["get","post","put","patch","delete"],Ut=e=>({id:"apply-schema",name:"Apply Schema",version:"1.0.0",async init(t,r){var i,n,a,u;let h=((n=(i=e.plugins)==null?void 0:i.find(l=>{var s;return(s=l.schema)!=null&&s.config?t.startsWith(l.schema.config.baseURL||"")||t.startsWith(l.schema.config.prefix||""):!1}))==null?void 0:n.schema)||e.schema;if(h){let l=t;(a=h.config)!=null&&a.prefix&&l.startsWith(h.config.prefix)&&(l=l.replace(h.config.prefix,""),h.config.baseURL&&(t=t.replace(h.config.prefix,h.config.baseURL))),(u=h.config)!=null&&u.baseURL&&l.startsWith(h.config.baseURL)&&(l=l.replace(h.config.baseURL,""));let s=h.schema[l];if(s){let o=N(x({},r),{method:s.method,output:s.output});return r?.disableValidation||(o=N(x({},o),{body:s.input?await Q(s.input,r?.body):r?.body,params:s.params?await Q(s.params,r?.params):r?.params,query:s.query?await Q(s.query,r?.query):r?.query})),{url:t,options:o}}}return{url:t,options:r}}}),xt=e=>{async function t(r,i){let n=N(x(x({},e),i),{plugins:[...e?.plugins||[],Ut(e||{})]});if(e?.catchAllError)try{return await he(r,n)}catch(a){return{data:null,error:{status:500,statusText:"Fetch Error",message:"Fetch related error. Captured by catchAllError option. See error property for more details.",error:a}}}return await he(r,n)}return t};function Nt(e,t){let{baseURL:r,params:i,query:n}=t||{query:{},params:{},baseURL:""},a=e.startsWith("http")?e.split("/").slice(0,3).join("/"):r||"";if(e.startsWith("@")){let o=e.toString().split("@")[1].split("/")[0];Le.includes(o)&&(e=e.replace(`@${o}/`,"/"))}a.endsWith("/")||(a+="/");let[u,h]=e.replace(a,"").split("?"),l=new URLSearchParams(h);for(let[o,c]of Object.entries(n||{}))c!=null&&l.set(o,String(c));if(i)if(Array.isArray(i)){let o=u.split("/").filter(c=>c.startsWith(":"));for(let[c,d]of o.entries()){let m=i[c];u=u.replace(d,m)}}else for(let[o,c]of Object.entries(i))u=u.replace(`:${o}`,String(c));u=u.split("/").map(encodeURIComponent).join("/"),u.startsWith("/")&&(u=u.slice(1));let s=l.toString();return s=s.length>0?`?${s}`.replace(/\+/g,"%20"):"",a.startsWith("http")?new URL(`${u}${s}`,a):`${a}${u}${s}`}var he=async(e,t)=>{var r,i,n,a,u,h,l,s;let{hooks:o,url:c,options:d}=await yt(e,t),m=Rt(d),y=new AbortController,g=(r=d.signal)!=null?r:y.signal,v=Nt(c,d),T=Pt(d),b=await St(d),R=At(c,d),f=N(x({},d),{url:v,headers:b,body:T,method:R,signal:g});for(let P of o.onRequest)if(P){let S=await P(f);S instanceof Object&&(f=S)}("pipeTo"in f&&typeof f.pipeTo=="function"||typeof((i=t?.body)==null?void 0:i.pipe)=="function")&&("duplex"in f||(f.duplex="half"));let{clearTimeout:A}=_t(d,y),w=await m(f.url,f);A();let z={response:w,request:f};for(let P of o.onResponse)if(P){let S=await P(N(x({},z),{response:(n=t?.hookOptions)!=null&&n.cloneResponse?w.clone():w}));S instanceof Response?w=S:S instanceof Object&&(w=S.response)}if(w.ok){if(f.method==="HEAD")return{data:"",error:null};let P=Et(w),S={data:"",response:w,request:f};if(P==="json"||P==="text"){let B=await w.text(),F=await((a=f.jsonParser)!=null?a:we)(B);S.data=F}else S.data=await w[P]();f?.output&&f.output&&!f.disableValidation&&(S.data=await Q(f.output,S.data));for(let B of o.onSuccess)B&&await B(N(x({},S),{response:(u=t?.hookOptions)!=null&&u.cloneResponse?w.clone():w}));return t?.throw?S.data:{data:S.data,error:null}}let k=(h=t?.jsonParser)!=null?h:we,V=await w.text(),ye=Tt(V),oe=ye?await k(V):null,ze={response:w,responseText:V,request:f,error:N(x({},oe),{status:w.status,statusText:w.statusText})};for(let P of o.onError)P&&await P(N(x({},ze),{response:(l=t?.hookOptions)!=null&&l.cloneResponse?w.clone():w}));if(t?.retry){let P=bt(t.retry),S=(s=t.retryAttempt)!=null?s:0;if(await P.shouldAttemptRetry(S,w)){for(let F of o.onRetry)F&&await F(z);let B=P.getDelay(S);return await new Promise(F=>setTimeout(F,B)),await he(e,N(x({},t),{retryAttempt:S+1}))}}if(t?.throw)throw new mt(w.status,w.statusText,ye?oe:V);return{data:null,error:N(x({},oe),{status:w.status,statusText:w.statusText})}};p();p();var Z=Object.create(null),H=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?Z:globalThis),$=new Proxy(Z,{get(e,t){return H()[t]??Z[t]},has(e,t){let r=H();return t in r||t in Z},set(e,t,r){let i=H(!0);return i[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=H(!0);return delete r[t],!0},ownKeys(){let e=H(!0);return Object.keys(e)}}),Pr=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";function E(e,t){return typeof process<"u"&&process.env?process.env[e]??t:typeof Deno<"u"?Deno.env.get(e)??t:typeof Bun<"u"?Bun.env[e]??t:t}var Ar=Object.freeze({get BETTER_AUTH_SECRET(){return E("BETTER_AUTH_SECRET")},get AUTH_SECRET(){return E("AUTH_SECRET")},get BETTER_AUTH_TELEMETRY(){return E("BETTER_AUTH_TELEMETRY")},get BETTER_AUTH_TELEMETRY_ID(){return E("BETTER_AUTH_TELEMETRY_ID")},get NODE_ENV(){return E("NODE_ENV","development")},get PACKAGE_VERSION(){return E("PACKAGE_VERSION","0.0.0")},get BETTER_AUTH_TELEMETRY_ENDPOINT(){return E("BETTER_AUTH_TELEMETRY_ENDPOINT","https://telemetry.better-auth.com/v1/track")}}),q=1,O=4,j=8,_=24,Te={eterm:O,cons25:O,console:O,cygwin:O,dtterm:O,gnome:O,hurd:O,jfbterm:O,konsole:O,kterm:O,mlterm:O,mosh:_,putty:O,st:O,"rxvt-unicode-24bit":_,terminator:_,"xterm-kitty":_},jt=new Map(Object.entries({APPVEYOR:j,BUILDKITE:j,CIRCLECI:_,DRONE:j,GITEA_ACTIONS:_,GITHUB_ACTIONS:_,GITLAB_CI:j,TRAVIS:j})),It=[/ansi/,/color/,/linux/,/direct/,/^con[0-9]*x[0-9]/,/^rxvt/,/^screen/,/^xterm/,/^vt100/,/^vt220/];function Lt(){if(E("FORCE_COLOR")!==void 0)switch(E("FORCE_COLOR")){case"":case"1":case"true":return O;case"2":return j;case"3":return _;default:return q}if(E("NODE_DISABLE_COLORS")!==void 0&&E("NODE_DISABLE_COLORS")!==""||E("NO_COLOR")!==void 0&&E("NO_COLOR")!==""||E("TERM")==="dumb")return q;if(E("TMUX"))return _;if("TF_BUILD"in $&&"AGENT_NAME"in $)return O;if("CI"in $){for(let{0:e,1:t}of jt)if(e in $)return t;return E("CI_NAME")==="codeship"?j:q}if("TEAMCITY_VERSION"in $)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.exec(E("TEAMCITY_VERSION"))!==null?O:q;switch(E("TERM_PROGRAM")){case"iTerm.app":return!E("TERM_PROGRAM_VERSION")||/^[0-2]\./.exec(E("TERM_PROGRAM_VERSION"))!==null?j:_;case"HyperTerm":case"MacTerm":return _;case"Apple_Terminal":return j}if(E("COLORTERM")==="truecolor"||E("COLORTERM")==="24bit")return _;if(E("TERM")){if(/truecolor/.exec(E("TERM"))!==null)return _;if(/^xterm-256/.exec(E("TERM"))!==null)return j;let e=E("TERM").toLowerCase();if(Te[e])return Te[e];if(It.some(t=>t.exec(e)!==null))return O}return E("COLORTERM")?O:q}var I={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"}},ce=["info","success","warn","error","debug"];function Ct(e,t){return ce.indexOf(t)<=ce.indexOf(e)}var Dt={info:I.fg.blue,success:I.fg.green,warn:I.fg.yellow,error:I.fg.red,debug:I.fg.magenta},Bt=(e,t,r)=>{let i=new Date().toISOString();return r?`${I.dim}${i}${I.reset} ${Dt[e]}${e.toUpperCase()}${I.reset} ${I.bright}[Better Auth]:${I.reset} ${t}`:`${i} ${e.toUpperCase()} [Better Auth]: ${t}`},Ft=e=>{let t=e?.disabled!==!0,r=e?.level??"error",i=e?.disableColors!==void 0?!e.disableColors:Lt()!==1,n=(a,u,h=[])=>{if(!t||!Ct(r,a))return;let l=Bt(a,u,i);if(!e||typeof e.log!="function"){a==="error"?console.error(l,...h):a==="warn"?console.warn(l,...h):console.log(l,...h);return}e.log(a==="success"?"info":a,u,...h)};return{...Object.fromEntries(ce.map(a=>[a,(...[u,...h])=>n(a,u,h)])),get level(){return r}}},_r=Ft();p();p();var fe=class extends Error{constructor(e,t){super(e),this.name="BetterAuthError",this.message=e,this.cause=t,this.stack=""}};function Mt(e){try{return(new URL(e).pathname.replace(/\/+$/,"")||"/")!=="/"}catch{throw new fe(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function W(e,t="/api/auth"){if(Mt(e))return e;let r=e.replace(/\/+$/,"");return!t||t==="/"?r:(t=t.startsWith("/")?t:`/${t}`,`${r}${t}`)}function kt(e,t,r,i){if(e)return W(e,t);if(i!==!1){let u=$.BETTER_AUTH_URL||$.NEXT_PUBLIC_BETTER_AUTH_URL||$.PUBLIC_BETTER_AUTH_URL||$.NUXT_PUBLIC_BETTER_AUTH_URL||$.NUXT_PUBLIC_AUTH_URL||($.BASE_URL!=="/"?$.BASE_URL:void 0);if(u)return W(u,t)}let n=r?.headers.get("x-forwarded-host"),a=r?.headers.get("x-forwarded-proto");if(n&&a)return W(`${a}://${n}`,t);if(r){let u=Ht(r.url);if(!u)throw new fe("Could not get origin from request. Please provide a valid base URL.");return W(u,t)}if(typeof window<"u"&&window.location)return W(window.location.origin,t)}function Ht(e){try{return new URL(e).origin}catch{return null}}p();p();p();var de=Symbol("clean"),U=[],L=0,K=4,qt=0,Ce=e=>{let t=[],r={get(){return r.lc||r.listen(()=>{})(),r.value},lc:0,listen(i){return r.lc=t.push(i),()=>{for(let a=L+K;a<U.length;)U[a]===i?U.splice(a,K):a+=K;let n=t.indexOf(i);~n&&(t.splice(n,1),--r.lc||r.off())}},notify(i,n){qt++;let a=!U.length;for(let u of t)U.push(u,r.value,i,n);if(a){for(L=0;L<U.length;L+=K)U[L](U[L+1],U[L+2],U[L+3]);U.length=0}},off(){},set(i){let n=r.value;n!==i&&(r.value=i,r.notify(n))},subscribe(i){let n=r.listen(i);return i(r.value),n},value:e};return process.env.NODE_ENV!=="production"&&(r[de]=()=>{t=[],r.lc=0,r.off()}),r};p();var Wt=5,M=6,Y=10,Gt=(e,t,r,i)=>(e.events=e.events||{},e.events[r+Y]||(e.events[r+Y]=i(n=>{e.events[r].reduceRight((a,u)=>(u(a),a),{shared:{},...n})})),e.events[r]=e.events[r]||[],e.events[r].push(t),()=>{let n=e.events[r],a=n.indexOf(t);n.splice(a,1),n.length||(delete e.events[r],e.events[r+Y](),delete e.events[r+Y])}),Jt=1e3,zt=(e,t)=>Gt(e,r=>{let i=t(r);i&&e.events[M].push(i)},Wt,r=>{let i=e.listen;e.listen=(...a)=>(!e.lc&&!e.active&&(e.active=!0,r()),i(...a));let n=e.off;if(e.events[M]=[],e.off=()=>{n(),setTimeout(()=>{if(e.active&&!e.lc){e.active=!1;for(let a of e.events[M])a();e.events[M]=[]}},Jt)},process.env.NODE_ENV!=="production"){let a=e[de];e[de]=()=>{for(let u of e.events[M])u();e.events[M]=[],e.active=!1,a()}}return()=>{e.listen=i,e.off=n}});p();var Vt=typeof window>"u",Kt=(e,t,r,i)=>{let n=Ce({data:null,error:null,isPending:!0,isRefetching:!1,refetch:h=>a(h)}),a=h=>{let l=typeof i=="function"?i({data:n.get().data,error:n.get().error,isPending:n.get().isPending}):i;r(t,{...l,query:{...l?.query,...h?.query},async onSuccess(s){n.set({data:s.data,error:null,isPending:!1,isRefetching:!1,refetch:n.value.refetch}),await l?.onSuccess?.(s)},async onError(s){let{request:o}=s,c=typeof o.retry=="number"?o.retry:o.retry?.attempts,d=o.retryAttempt||0;c&&d<c||(n.set({error:s.error,data:null,isPending:!1,isRefetching:!1,refetch:n.value.refetch}),await l?.onError?.(s))},async onRequest(s){let o=n.get();n.set({isPending:o.data===null,data:o.data,error:null,isRefetching:!0,refetch:n.value.refetch}),await l?.onRequest?.(s)}}).catch(s=>{n.set({error:s,data:null,isPending:!1,isRefetching:!1,refetch:n.value.refetch})})};e=Array.isArray(e)?e:[e];let u=!1;for(let h of e)h.subscribe(()=>{Vt||(u?a():zt(n,()=>{let l=setTimeout(()=>{u||(a(),u=!0)},0);return()=>{n.off(),h.off(),clearTimeout(l)}}))});return n};p();var Yt={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*:/},Xt=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,Re={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 Zt(e){return e instanceof Date&&!isNaN(e.getTime())}function er(e){let t=Qt.exec(e);if(!t)return null;let[,r,i,n,a,u,h,l,s,o,c]=t,d=new Date(Date.UTC(parseInt(r,10),parseInt(i,10)-1,parseInt(n,10),parseInt(a,10),parseInt(u,10),parseInt(h,10),l?parseInt(l.padEnd(3,"0"),10):0));if(s){let m=(parseInt(o,10)*60+parseInt(c,10))*(s==="+"?-1:1);d.setUTCMinutes(d.getUTCMinutes()+m)}return Zt(d)?d:null}function tr(e,t={}){let{strict:r=!1,warnings:i=!1,reviver:n,parseDates:a=!0}=t;if(typeof e!="string")return e;let u=e.trim();if(u.length>0&&u[0]==='"'&&u.endsWith('"')&&!u.slice(1,-1).includes('"'))return u.slice(1,-1);let h=u.toLowerCase();if(h.length<=9&&h in Re)return Re[h];if(!Xt.test(u)){if(r)throw new SyntaxError("[better-json] Invalid JSON");return e}if(Object.entries(Yt).some(([l,s])=>{let o=s.test(u);return o&&i&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${l} pattern`),o})&&r)throw new Error("[better-json] Potential prototype pollution attempt detected");try{return JSON.parse(u,(l,s)=>{if(l==="__proto__"||l==="constructor"&&s&&typeof s=="object"&&"prototype"in s){i&&console.warn(`[better-json] Dropping "${l}" key to prevent prototype pollution`);return}if(a&&typeof s=="string"){let o=er(s);if(o)return o}return n?n(l,s):s})}catch(l){if(r)throw l;return e}}function rr(e,t={strict:!0}){return tr(e,t)}var sr={id:"redirect",name:"Redirect",hooks:{onSuccess(e){if(e.data?.url&&e.data?.redirect&&typeof window<"u"&&window.location&&window.location)try{window.location.href=e.data.url}catch{}}}};function nr(e){let t=Ce(!1);return{session:Kt(t,"/get-session",e,{method:"GET"}),$sessionSignal:t}}var ar=(e,t)=>{let r="credentials"in Request.prototype,i=kt(e?.baseURL,e?.basePath,void 0,t)??"/api/auth",n=e?.plugins?.flatMap(f=>f.fetchPlugins).filter(f=>f!==void 0)||[],a={id:"lifecycle-hooks",name:"lifecycle-hooks",hooks:{onSuccess:e?.fetchOptions?.onSuccess,onError:e?.fetchOptions?.onError,onRequest:e?.fetchOptions?.onRequest,onResponse:e?.fetchOptions?.onResponse}},{onSuccess:u,onError:h,onRequest:l,onResponse:s,...o}=e?.fetchOptions||{},c=xt({baseURL:i,...r?{credentials:"include"}:{},method:"GET",jsonParser(f){return f?rr(f,{strict:!1}):null},customFetchImpl:fetch,...o,plugins:[a,...o.plugins||[],...e?.disableDefaultFetchPlugins?[]:[sr],...n]}),{$sessionSignal:d,session:m}=nr(c),y=e?.plugins||[],g={},v={$sessionSignal:d,session:m},T={"/sign-out":"POST","/revoke-sessions":"POST","/revoke-other-sessions":"POST","/delete-user":"POST"},b=[{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 y)f.getAtoms&&Object.assign(v,f.getAtoms?.(c)),f.pathMethods&&Object.assign(T,f.pathMethods),f.atomListeners&&b.push(...f.atomListeners);let R={notify:f=>{v[f].set(!v[f].get())},listen:(f,A)=>{v[f].subscribe(A)},atoms:v};for(let f of y)f.getActions&&Object.assign(g,f.getActions?.(c,R,e));return{get baseURL(){return i},pluginsActions:g,pluginsAtoms:v,pluginPathMethods:T,atomListeners:b,$fetch:c,$store:R}};function or(e){return typeof e=="object"&&e!==null&&"get"in e&&typeof e.get=="function"&&"lc"in e&&typeof e.lc=="number"}function ir(e,t,r){let i=t[e],{fetchOptions:n,query:a,...u}=r||{};return i||(n?.method?n.method:u&&Object.keys(u).length>0?"POST":"GET")}function lr(e,t,r,i,n){function a(u=[]){return new Proxy(function(){},{get(h,l){if(typeof l!="string"||l==="then"||l==="catch"||l==="finally")return;let s=[...u,l],o=e;for(let c of s)if(o&&typeof o=="object"&&c in o)o=o[c];else{o=void 0;break}return typeof o=="function"||or(o)?o:a(s)},apply:async(h,l,s)=>{let o="/"+u.map(b=>b.replace(/[A-Z]/g,R=>`-${R.toLowerCase()}`)).join("/"),c=s[0]||{},d=s[1]||{},{query:m,fetchOptions:y,...g}=c,v={...d,...y},T=ir(o,r,c);return await t(o,{...v,body:T==="GET"?void 0:{...g,...v?.body||{}},query:m||v?.query,method:T,async onSuccess(b){if(await v?.onSuccess?.(b),!n)return;let R=n.filter(f=>f.matcher(o));if(R.length)for(let f of R){let A=i[f.signal];if(!A)return;let w=A.get();setTimeout(()=>{A.set(!w)},10)}}})}})}return a()}p();function ur(e){return e.charAt(0).toUpperCase()+e.slice(1)}function hr(e){let{pluginPathMethods:t,pluginsActions:r,pluginsAtoms:i,$fetch:n,atomListeners:a,$store:u}=ar(e),h={};for(let[s,o]of Object.entries(i))h[`use${ur(s)}`]=o;let l={...r,...h,$fetch:n,$store:u};return lr(l,n,t,i,a)}p();p();p();function cr(e){return{authorize(t,r="AND"){let i=!1;for(let[n,a]of Object.entries(t)){let u=e[n];if(!u)return{success:!1,error:`You are not allowed to access resource: ${n}`};if(Array.isArray(a))i=a.every(h=>u.includes(h));else if(typeof a=="object"){let h=a;h.connector==="OR"?i=h.actions.some(l=>u.includes(l)):i=h.actions.every(l=>u.includes(l))}else throw new fe("Invalid access control request");if(i&&r==="OR")return{success:i};if(!i&&r==="AND")return{success:!1,error:`unauthorized to access resource "${n}"`}}return i?{success:i}:{success:!1,error:"Not authorized"}},statements:e}}function De(e){return{newRole(t){return cr(t)},statements:e}}var dr={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"],team:["create","update","delete"],ac:["create","read","update","delete"]},me=De(dr),$r=me.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"],team:["create","update","delete"],ac:["create","read","update","delete"]}),Ur=me.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"],team:["create","update","delete"],ac:["create","read","update","delete"]}),xr=me.newRole({organization:[],member:[],invitation:[],team:[],ac:["read"]});p();p();p();p();p();p();p();p();p();p();p();var pr=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}}},Nr=new pr;p();p();p();p();p();p();p();p();var fr={user:["create","list","set-role","ban","impersonate","delete","set-password","get","update"],session:["list","revoke","delete"]},Be=De(fr),jr=Be.newRole({user:["create","list","set-role","ban","impersonate","delete","set-password","get","update"],session:["list","revoke","delete"]}),Ir=Be.newRole({user:[],session:[]});p();p();var mr=()=>({id:"username",$InferServerPlugin:{}});var X="nvwa_login_token",le="nvwa_user_profile",Fe=class{constructor(e,t,r){this.storage=r,this.authClient=hr({baseUrl:e,fetchOptions:{customFetchImpl:t,auth:{type:"Bearer",token:()=>r.get(X)},onSuccess:i=>{let n=i.response.headers.get("set-auth-token");n&&r.set(X,n)}},plugins:[mr()]})}async currentUser(){return await this.storage.get(le)}async signUp(e,t){let r=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(r)}async signInWithUsername(e,t){let r=await this.authClient.signIn.username({username:e,password:t});this.saveSession(r)}saveSession(e){if(e.error)throw new Error(e.error.message);this.storage.set(X,e.data?.token),this.storage.set(le,e.data?.user)}async signOut(){await this.storage.remove(X),await this.storage.remove(le)}async updateUserPassword(e,t,r=!1){let i=await this.authClient.changePassword({currentPassword:e,newPassword:t,revokeOtherSessions:r});this.saveSession(i)}};p();var Me=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}};p();var ke=class{async jsonRequest(e,t){let r={...t,headers:{"Content-Type":"application/json",...t.headers},data:typeof t.data=="object"?JSON.stringify(t.data):t.data};return this.request(e,r)}async jsonRequestWithAuth(e,t,r){let i={...t,headers:{"Content-Type":"application/json",...t.headers},data:typeof t.data=="object"?JSON.stringify(t.data):t.data};return this.requestWithAuth(e,i,r)}};p();var yr="/storage",gr=yr+"/generateUploadUrl",He=class{constructor(e,t){this.baseUrl=e,this.http=t}async uploadFile(e){let t=await this.http.request(this.baseUrl+gr,{method:"POST",data:{fileName:e.name||e.fileName,fileSize:e.size||e.fileSize,fileType:e.type||e.fileType}}),{url:r}=t.body;if(!r)throw new Error("\u83B7\u53D6\u4E0A\u4F20URL\u5931\u8D25");return{url:(await this.http.request(r,{method:"PUT",data:e,headers:{"Content-Type":e.type||e.fileType||"application/octet-stream"}})).body.url.split("?")[0]}}};p();p();p();var br=it(ut(),1),{PostgrestClient:vr,PostgrestQueryBuilder:Lr,PostgrestFilterBuilder:Cr,PostgrestTransformBuilder:Dr,PostgrestBuilder:Br,PostgrestError:Fr,FetchHeaders:Mr,FetchResponse:Se,PostgrestFetch:kr,URL:Hr,URLSearchParams:qr}=br.default,wr="/entities",Er=(e,t)=>async(r,i)=>{console.log("customFetch",r,i);let n;if(typeof r=="string")n=r;else if(r&&typeof r=="object")if(typeof r.toString=="function"&&!r.url)n=r.toString();else if(r.url)n=r.url,i||(i={}),i.method=r.method,i.headers=r.headers,i.body=r.body;else throw new Error("Unsupported input type for fetch");else throw new Error("Unsupported input type for fetch");let a=(i?.method||"GET").toUpperCase(),u={};if(i?.headers)if(i.headers&&typeof i.headers.forEach=="function")i.headers.forEach((c,d)=>{u[d]=c});else if(Array.isArray(i.headers))for(let[c,d]of i.headers)u[c]=d;else Object.assign(u,i.headers);let h=i?.body,l;try{l=await e.requestWithAuth(n,{method:a,data:h,headers:u},t)}catch(c){return new Se(c?.message||"Internal Error",{status:500,statusText:"Internal Error"})}let s=l.body,o=null;return(l.headers["content-type"]||l.headers["Content-Type"]||"").startsWith("application/json")&&typeof s!="string"?o=JSON.stringify(s):typeof s=="string"||s&&(s.constructor===Blob||s.constructor===ArrayBuffer||typeof s.getReader=="function")?o=s:o=JSON.stringify(s),new Se(o,{status:l.status,headers:l.headers})},qe=(e,t,r)=>new vr(e+wr,{fetch:Er(t,r)});p();p();var D=class We{constructor(t){if(this.headerMap=new Map,t){if(t instanceof We)t.forEach((r,i)=>this.set(i,r));else if(Array.isArray(t))for(let[r,i]of t)this.set(r,String(i));else if(typeof t=="object")for(let r of Object.keys(t))this.set(r,String(t[r]))}}append(t,r){let i=t.toLowerCase(),n=this.headerMap.get(i);this.headerMap.set(i,n?`${n}, ${r}`:r)}set(t,r){this.headerMap.set(t.toLowerCase(),String(r))}get(t){return this.headerMap.get(t.toLowerCase())??null}has(t){return this.headerMap.has(t.toLowerCase())}delete(t){this.headerMap.delete(t.toLowerCase())}forEach(t){for(let[r,i]of this.headerMap.entries())t(i,r,this)}entries(){return this.headerMap.entries()}keys(){return this.headerMap.keys()}values(){return this.headerMap.values()}[Symbol.iterator](){return this.entries()}};p();p();var Ge=class{constructor(e,t){this.bodyData=e,this.status=t?.status??200,this.statusText=t?.statusText??"",this.headers=Tr(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 Tr(e){return e?new D(e):new D}p();p();var Rr=(e,t)=>{let r;if(typeof e=="string")r=e;else if(e&&typeof e.toString=="function")r=e.toString();else if(e?.url)r=e.url;else throw new Error("Invalid input for uniappFetch");let i=(t?.method||"GET").toUpperCase(),n={};if(t?.headers){let h=t.headers;if(typeof h?.forEach=="function")h.forEach((l,s)=>{n[s]=l});else if(Array.isArray(h))for(let[l,s]of h)n[l]=s;else Object.assign(n,h)}let a;if(t?.body!==void 0){let h=t.body;if(typeof h=="string")a=h;else if(h&&typeof h=="object"&&typeof h.forEach=="function"){let l={};h.forEach((s,o)=>{l[o]=s}),a=l}else a=h}let u=t?.timeout||3e4;return new Promise((h,l)=>{let s=t?.signal;if(s?.aborted){let m=new Error("The operation was aborted");m.name="AbortError",l(m);return}let o=!1,c=[],d=uni.request({url:r,method:i,data:a,header:n,timeout:u,success:m=>{if(o)return;o=!0;let y=m.statusCode,g="",v=new D,T=m.header||m.headers||{};Object.keys(T).forEach(b=>{let R=T[b];v.set(b,typeof R=="string"?R:String(R))}),h(new Ge(m.data,{status:y,statusText:g,headers:v}))},fail:m=>{if(o)return;o=!0;let y=m?.errMsg||m?.message||"Network Error",g=new Error(y);/(abort|aborted|canceled|cancelled)/i.test(String(y))&&(g.name="AbortError"),l(g)}});if(s&&typeof s.addEventListener=="function"){let m=()=>{if(o)return;try{d?.abort?.()}catch{}let y=new Error("The operation was aborted");y.name="AbortError",o=!0,l(y)};s.addEventListener("abort",m),c.push(()=>{try{s.removeEventListener?.("abort",m)}catch{}})}})},J=Rr;var re=class extends ke{async request(t,r){let i=await J(t,{method:r.method,headers:new D(r.headers),body:r.data});return{status:i.status,body:await i.json(),headers:Object.fromEntries(i.headers.entries())}}async requestWithAuth(t,r,i){let n=await this.fetchWithAuth(i,t,{method:r.method,headers:new D(r.headers),body:r.data});return{status:n.status,body:await n.json(),headers:Object.fromEntries(n.headers.entries())}}async fetchWithAuth(t,r,i){let n=await J(r,i);if(n.status===401)throw t(),new Error("\u672A\u767B\u5F55");return n}};var se=class{constructor(){this.prefix="nvwa_"}getKey(t){return`${this.prefix}${t}`}async get(t){try{let r=this.getKey(t),i=uni.getStorageSync(r);return i?i.expires&&Date.now()>i.expires?(await this.remove(t),null):i.value:null}catch(r){return console.error("UniAppStorageService get error:",r),null}}async set(t,r,i){try{let n=this.getKey(t),a={value:r,expires:i?Date.now()+i*1e3:null,timestamp:Date.now()};uni.setStorageSync(n,a)}catch(n){throw console.error("UniAppStorageService set error:",n),n}}async remove(t){try{let r=this.getKey(t);uni.removeStorageSync(r)}catch(r){throw console.error("UniAppStorageService remove error:",r),r}}async clear(){try{uni.clearStorageSync()}catch(t){throw console.error("UniAppStorageService clear error:",t),t}}};var Je=new se,ne=new re,ae=class{constructor(t,r){this.auth=new Fe(t,J,Je),this.fileStorage=new He(t,ne),this.entities=qe(t,ne,r),this.functions=new Me(ne)}};0&&(module.exports={httpClient,localStorage});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{NvwaAuthClient as C,NvwaEdgeFunctions as I,NvwaFileStorage as T,createPostgrestClient as U}from"@nvwa-app/sdk-core";import{NvwaHttpClient as q}from"@nvwa-app/sdk-core";import{Headers as A}from"@nvwa-app/sdk-core";import{Response as H,Headers as F}from"@nvwa-app/sdk-core";var L=(i,e)=>{let t;if(typeof i=="string")t=i;else if(i&&typeof i.toString=="function")t=i.toString();else if(i?.url)t=i.url;else throw new Error("Invalid input for uniappFetch");let r=(e?.method||"GET").toUpperCase(),s={};if(e?.headers){let o=e.headers;if(typeof o?.forEach=="function")o.forEach((c,a)=>{s[a]=c});else if(Array.isArray(o))for(let[c,a]of o)s[c]=a;else Object.assign(s,o)}let p;if(e?.body!==void 0){let o=e.body;if(typeof o=="string")p=o;else if(o&&typeof o=="object"&&typeof o.forEach=="function"){let c={};o.forEach((a,u)=>{c[u]=a}),p=c}else p=o}let N=e?.timeout||3e4;return new Promise((o,c)=>{let a=e?.signal;if(a?.aborted){let n=new Error("The operation was aborted");n.name="AbortError",c(n);return}let u=!1,x=[],P=uni.request({url:t,method:r,data:p,header:s,timeout:N,success:n=>{if(u)return;u=!0;let l=n.statusCode,h="",S=new F,R=n.header||n.headers||{};Object.keys(R).forEach(E=>{let m=R[E];S.set(E,typeof m=="string"?m:String(m))}),o(new H(n.data,{status:l,statusText:h,headers:S}))},fail:n=>{if(u)return;u=!0;let l=n?.errMsg||n?.message||"Network Error",h=new Error(l);/(abort|aborted|canceled|cancelled)/i.test(String(l))&&(h.name="AbortError"),c(h)}});if(a&&typeof a.addEventListener=="function"){let n=()=>{if(u)return;try{P?.abort?.()}catch{}let l=new Error("The operation was aborted");l.name="AbortError",u=!0,c(l)};a.addEventListener("abort",n),x.push(()=>{try{a.removeEventListener?.("abort",n)}catch{}})}})},f=L;var d=class extends q{async request(e,t){let r=await f(e,{method:t.method,headers:new A(t.headers),body:t.data});return{status:r.status,body:await r.json(),headers:Object.fromEntries(r.headers.entries())}}async requestWithAuth(e,t,r){let s=await this.fetchWithAuth(r,e,{method:t.method,headers:new A(t.headers),body:t.data});return{status:s.status,body:await s.json(),headers:Object.fromEntries(s.headers.entries())}}async fetchWithAuth(e,t,r){let s=await f(t,r);if(s.status===401)throw e(),new Error("\u672A\u767B\u5F55");return s}};var y=class{constructor(){this.prefix="nvwa_"}getKey(e){return`${this.prefix}${e}`}async get(e){try{let t=this.getKey(e),r=uni.getStorageSync(t);return r?r.expires&&Date.now()>r.expires?(await this.remove(e),null):r.value:null}catch(t){return console.error("UniAppStorageService get error:",t),null}}async set(e,t,r){try{let s=this.getKey(e),p={value:t,expires:r?Date.now()+r*1e3:null,timestamp:Date.now()};uni.setStorageSync(s,p)}catch(s){throw console.error("UniAppStorageService set error:",s),s}}async remove(e){try{let t=this.getKey(e);uni.removeStorageSync(t)}catch(t){throw console.error("UniAppStorageService remove error:",t),t}}async clear(){try{uni.clearStorageSync()}catch(e){throw console.error("UniAppStorageService clear error:",e),e}}};var K=new y,v=new d,b=class{constructor(e,t){this.auth=new C(e,f,K),this.fileStorage=new T(e,v),this.entities=U(e,v,t),this.functions=new I(v)}};export{b as default,v as httpClient,K as localStorage};
1
+ var ze=Object.create,Oe=Object.defineProperty,Ve=Object.getOwnPropertyDescriptor,Ke=Object.getOwnPropertyNames,Ye=Object.getPrototypeOf,Xe=Object.prototype.hasOwnProperty,Qe=(e,t)=>()=>(e&&(t=e(e=0)),t),C=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ze=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Ke(t))!Xe.call(e,n)&&n!==r&&Oe(e,n,{get:()=>t[n],enumerable:!(i=Ve(t,n))||i.enumerable});return e},et=(e,t,r)=>(r=e!=null?ze(Ye(e)):{},Ze(t||!e||!e.__esModule?Oe(r,"default",{value:e,enumerable:!0}):r,e)),p=Qe(()=>{"use strict"}),re=C(e=>{"use strict";p(),Object.defineProperty(e,"__esModule",{value:!0}),e.File=e.FormData=e.Blob=e.FetchResponse=e.URL=e.URLSearchParams=e.FetchHeaders=void 0;var t=class{constructor(l){if(this.map=new Map,l)for(let[s,o]of Object.entries(l))this.set(s,o)}get(l){var s;return(s=this.map.get(l))!==null&&s!==void 0?s:null}set(l,s){this.map.set(l,s)}has(l){return this.map.has(l)}append(l,s){let o=this.map.get(l);o?this.map.set(l,`${o}${s}`):this.map.set(l,s)}delete(l){this.map.delete(l)}forEach(l){this.map.forEach(l)}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]()}};e.FetchHeaders=t;var r=class Pe{constructor(s){if(this.params=new Map,s){if(typeof s=="string")this.parseString(s);else if(s instanceof Pe)this.params=new Map(s.params);else if(Array.isArray(s))for(let[o,c]of s)this.append(o,c);else if(s&&typeof s=="object")for(let[o,c]of Object.entries(s))this.set(o,c)}}parseString(s){s.startsWith("?")&&(s=s.slice(1));let o=s.split("&");for(let c of o)if(c){let[d,m]=c.split("=");d&&this.append(decodeURIComponent(d),m?decodeURIComponent(m):"")}}append(s,o){let c=this.params.get(s)||[];c.push(o),this.params.set(s,c)}delete(s){this.params.delete(s)}get(s){let o=this.params.get(s);return o?o[0]:null}getAll(s){return this.params.get(s)||[]}has(s){return this.params.has(s)}set(s,o){this.params.set(s,[o])}sort(){let s=Array.from(this.params.entries()).sort(([o],[c])=>o.localeCompare(c));this.params=new Map(s)}toString(){let s=[];for(let[o,c]of this.params.entries())for(let d of c)s.push(`${encodeURIComponent(o)}=${encodeURIComponent(d)}`);return s.join("&")}forEach(s){for(let[o,c]of this.params.entries())for(let d of c)s(d,o,this)}keys(){return this.params.keys()}values(){let s=[];for(let o of this.params.values())s.push(...o);return s[Symbol.iterator]()}entries(){let s=[];for(let[o,c]of this.params.entries())for(let d of c)s.push([o,d]);return s[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}};e.URLSearchParams=r;var i=class ie{constructor(s,o){let c;if(s instanceof ie)c=s.href;else if(o){let m=o instanceof ie?o.href:o;c=this.resolve(m,s)}else c=s;let d=this.parseUrl(c);this.href=c,this.origin=`${d.protocol}//${d.host}`,this.protocol=d.protocol,this.username=d.username,this.password=d.password,this.host=d.host,this.hostname=d.hostname,this.port=d.port,this.pathname=d.pathname,this.search=d.search,this.searchParams=new r(d.search),this.hash=d.hash}resolve(s,o){if(o.startsWith("http://")||o.startsWith("https://"))return o;if(o.startsWith("//"))return`${this.parseUrl(s).protocol}${o}`;if(o.startsWith("/")){let m=this.parseUrl(s);return`${m.protocol}//${m.host}${o}`}let c=this.parseUrl(s),d=c.pathname.endsWith("/")?c.pathname:c.pathname+"/";return`${c.protocol}//${c.host}${d}${o}`}parseUrl(s){let o=s.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!o)throw new TypeError("Invalid URL");let c=o[2]||"",d=o[4]||"",m=o[5]||"/",y=o[7]?`?${o[7]}`:"",g=o[9]?`#${o[9]}`:"";if(!c&&!d&&!m.startsWith("/")&&!m.includes("/")&&!m.includes("."))throw new TypeError("Invalid URL");let v=d.match(/^([^@]*)@(.+)$/),T="",b="",R=d;if(v){let z=v[1];R=v[2];let k=z.match(/^([^:]*):?(.*)$/);k&&(T=k[1]||"",b=k[2]||"")}let f=R.match(/^([^:]+):?(\d*)$/),A=f?f[1]:R,w=f&&f[2]?f[2]:"";return{protocol:c?`${c}:`:"",username:T,password:b,host:R,hostname:A,port:w,pathname:m,search:y,hash:g}}toString(){let s=this.searchParams.toString(),o=s?`?${s}`:"";return`${this.protocol}//${this.host}${this.pathname}${o}${this.hash}`}toJSON(){return this.toString()}};e.URL=i;var n=class G{constructor(s,o){var c,d;this.status=(c=o?.status)!==null&&c!==void 0?c:200,this.statusText=(d=o?.statusText)!==null&&d!==void 0?d:"",this.headers=new t(o?.headers),this.ok=this.status>=200&&this.status<300,this.redirected=!1,this.url="",this.bodyUsed=!1,this.body=s||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 a([this.body||""])}async formData(){if(this.bodyUsed)throw new TypeError("Body has already been consumed");return this.bodyUsed=!0,new u}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 G(this.body,{status:this.status,statusText:this.statusText,headers:this.headers.headers()})}static error(){let s=new G(null,{status:0,statusText:""});return Object.defineProperty(s,"type",{value:"error",writable:!1}),s}static redirect(s,o=302){let c=s instanceof i?s.href:s,d=new G(null,{status:o,statusText:"Found"});return d.headers.set("Location",c),d}static json(s,o){let c=JSON.stringify(s),d=new t(o?.headers);return d.set("Content-Type","application/json"),new G(c,Object.assign(Object.assign({},o),{headers:d.headers()}))}};e.FetchResponse=n;var a=class Ae{constructor(s,o){this._content=s||[],this.type=o?.type||"";let c=0;for(let d of this._content)typeof d=="string"?c+=new TextEncoder().encode(d).length:d instanceof ArrayBuffer?c+=d.byteLength:d instanceof Uint8Array&&(c+=d.length);this.size=c}async text(){let s="";for(let o of this._content)typeof o=="string"?s+=o:o instanceof ArrayBuffer?s+=new TextDecoder().decode(o):o instanceof Uint8Array&&(s+=new TextDecoder().decode(o));return s}async arrayBuffer(){let s=await this.text();return new TextEncoder().encode(s).buffer}slice(s,o,c){return new Ae(this._content.slice(s,o),{type:c})}};e.Blob=a;var u=class{constructor(){this._entries=[]}append(l,s,o){this._entries.push([l,s])}delete(l){this._entries=this._entries.filter(([s])=>s!==l)}get(l){let s=this._entries.find(([o])=>o===l);return s?s[1]:null}getAll(l){return this._entries.filter(([s])=>s===l).map(([,s])=>s)}has(l){return this._entries.some(([s])=>s===l)}set(l,s,o){this.delete(l),this.append(l,s,o)}forEach(l){for(let[s,o]of this._entries)l(o,s,this)}keys(){return this._entries.map(([l])=>l)[Symbol.iterator]()}values(){return this._entries.map(([,l])=>l)[Symbol.iterator]()}entries(){return this._entries[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}};e.FormData=u;var h=class extends a{constructor(l,s,o){super(l,o),this.name=s,this.lastModified=o?.lastModified||Date.now()}};e.File=h}),_e=C(e=>{"use strict";p(),Object.defineProperty(e,"__esModule",{value:!0});var t=class extends Error{constructor(r){super(r.message),this.name="PostgrestError",this.details=r.details,this.hint=r.hint,this.code=r.code}};e.default=t}),$e=C(e=>{"use strict";p();var t=e&&e.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(e,"__esModule",{value:!0});var r=t(_e()),i=re(),n=class{constructor(a){var u,h;this.shouldThrowOnError=!1,this.method=a.method,this.url=a.url,this.headers=new i.FetchHeaders(a.headers),this.schema=a.schema,this.body=a.body,this.shouldThrowOnError=(u=a.shouldThrowOnError)!==null&&u!==void 0?u:!1,this.signal=a.signal,this.isMaybeSingle=(h=a.isMaybeSingle)!==null&&h!==void 0?h:!1,a.fetch?this.fetch=a.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(a,u){return this.headers=new i.FetchHeaders(this.headers),this.headers.set(a,u),this}then(a,u){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 h=this.fetch,l=h(this.url.toString(),{method:this.method,headers:this.headers.headers(),body:JSON.stringify(this.body),signal:this.signal}).then(async s=>{var o,c,d,m;let y=null,g=null,v=null,T=s.status,b=s.statusText;if(s.ok){if(this.method!=="HEAD"){let A=await s.text();A===""||(this.headers.get("Accept")==="text/csv"||this.headers.get("Accept")&&!((o=this.headers.get("Accept"))===null||o===void 0)&&o.includes("application/vnd.pgrst.plan+text")?g=A:g=JSON.parse(A))}let R=(c=this.headers.get("Prefer"))===null||c===void 0?void 0:c.match(/count=(exact|planned|estimated)/),f=(d=s.headers.get("content-range"))===null||d===void 0?void 0:d.split("/");R&&f&&f.length>1&&(v=parseInt(f[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(g)&&(g.length>1?(y={code:"PGRST116",details:`Results contain ${g.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},g=null,v=null,T=406,b="Not Acceptable"):g.length===1?g=g[0]:g=null)}else{let R=await s.text();try{y=JSON.parse(R),Array.isArray(y)&&s.status===404&&(g=[],y=null,T=200,b="OK")}catch{s.status===404&&R===""?(T=204,b="No Content"):y={message:R}}if(y&&this.isMaybeSingle&&!((m=y?.details)===null||m===void 0)&&m.includes("0 rows")&&(y=null,T=200,b="OK"),y&&this.shouldThrowOnError)throw new r.default(y)}return{error:y,data:g,count:v,status:T,statusText:b}});return this.shouldThrowOnError||(l=l.catch(s=>{var o,c,d;return{error:{message:`${(o=s?.name)!==null&&o!==void 0?o:"FetchError"}: ${s?.message}`,details:`${(c=s?.stack)!==null&&c!==void 0?c:""}`,hint:"",code:`${(d=s?.code)!==null&&d!==void 0?d:""}`},data:null,count:null,status:0,statusText:""}})),l.then(a,u)}returns(){return this}overrideTypes(){return this}};e.default=n}),Ue=C(e=>{"use strict";p();var t=e&&e.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(e,"__esModule",{value:!0});var r=t($e()),i=class extends r.default{select(n){let a=!1,u=(n??"*").split("").map(h=>/\s/.test(h)&&!a?"":(h==='"'&&(a=!a),h)).join("");return this.url.searchParams.set("select",u),this.headers.append("Prefer","return=representation"),this}order(n,{ascending:a=!0,nullsFirst:u,foreignTable:h,referencedTable:l=h}={}){let s=l?`${l}.order`:"order",o=this.url.searchParams.get(s);return this.url.searchParams.set(s,`${o?`${o},`:""}${n}.${a?"asc":"desc"}${u===void 0?"":u?".nullsfirst":".nullslast"}`),this}limit(n,{foreignTable:a,referencedTable:u=a}={}){let h=typeof u>"u"?"limit":`${u}.limit`;return this.url.searchParams.set(h,`${n}`),this}range(n,a,{foreignTable:u,referencedTable:h=u}={}){let l=typeof h>"u"?"offset":`${h}.offset`,s=typeof h>"u"?"limit":`${h}.limit`;return this.url.searchParams.set(l,`${n}`),this.url.searchParams.set(s,`${a-n+1}`),this}abortSignal(n){return this.signal=n,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:n=!1,verbose:a=!1,settings:u=!1,buffers:h=!1,wal:l=!1,format:s="text"}={}){var o;let c=[n?"analyze":null,a?"verbose":null,u?"settings":null,h?"buffers":null,l?"wal":null].filter(Boolean).join("|"),d=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${s}; for="${d}"; options=${c};`),s==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(n){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${n}`),this}};e.default=i}),ce=C(e=>{"use strict";p();var t=e&&e.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(e,"__esModule",{value:!0});var r=t(Ue()),i=class extends r.default{eq(n,a){return this.url.searchParams.append(n,`eq.${a}`),this}neq(n,a){return this.url.searchParams.append(n,`neq.${a}`),this}gt(n,a){return this.url.searchParams.append(n,`gt.${a}`),this}gte(n,a){return this.url.searchParams.append(n,`gte.${a}`),this}lt(n,a){return this.url.searchParams.append(n,`lt.${a}`),this}lte(n,a){return this.url.searchParams.append(n,`lte.${a}`),this}like(n,a){return this.url.searchParams.append(n,`like.${a}`),this}likeAllOf(n,a){return this.url.searchParams.append(n,`like(all).{${a.join(",")}}`),this}likeAnyOf(n,a){return this.url.searchParams.append(n,`like(any).{${a.join(",")}}`),this}ilike(n,a){return this.url.searchParams.append(n,`ilike.${a}`),this}ilikeAllOf(n,a){return this.url.searchParams.append(n,`ilike(all).{${a.join(",")}}`),this}ilikeAnyOf(n,a){return this.url.searchParams.append(n,`ilike(any).{${a.join(",")}}`),this}is(n,a){return this.url.searchParams.append(n,`is.${a}`),this}in(n,a){let u=Array.from(new Set(a)).map(h=>typeof h=="string"&&new RegExp("[,()]").test(h)?`"${h}"`:`${h}`).join(",");return this.url.searchParams.append(n,`in.(${u})`),this}contains(n,a){return typeof a=="string"?this.url.searchParams.append(n,`cs.${a}`):Array.isArray(a)?this.url.searchParams.append(n,`cs.{${a.join(",")}}`):this.url.searchParams.append(n,`cs.${JSON.stringify(a)}`),this}containedBy(n,a){return typeof a=="string"?this.url.searchParams.append(n,`cd.${a}`):Array.isArray(a)?this.url.searchParams.append(n,`cd.{${a.join(",")}}`):this.url.searchParams.append(n,`cd.${JSON.stringify(a)}`),this}rangeGt(n,a){return this.url.searchParams.append(n,`sr.${a}`),this}rangeGte(n,a){return this.url.searchParams.append(n,`nxl.${a}`),this}rangeLt(n,a){return this.url.searchParams.append(n,`sl.${a}`),this}rangeLte(n,a){return this.url.searchParams.append(n,`nxr.${a}`),this}rangeAdjacent(n,a){return this.url.searchParams.append(n,`adj.${a}`),this}overlaps(n,a){return typeof a=="string"?this.url.searchParams.append(n,`ov.${a}`):this.url.searchParams.append(n,`ov.{${a.join(",")}}`),this}textSearch(n,a,{config:u,type:h}={}){let l="";h==="plain"?l="pl":h==="phrase"?l="ph":h==="websearch"&&(l="w");let s=u===void 0?"":`(${u})`;return this.url.searchParams.append(n,`${l}fts${s}.${a}`),this}match(n){return Object.entries(n).forEach(([a,u])=>{this.url.searchParams.append(a,`eq.${u}`)}),this}not(n,a,u){return this.url.searchParams.append(n,`not.${a}.${u}`),this}or(n,{foreignTable:a,referencedTable:u=a}={}){let h=u?`${u}.or`:"or";return this.url.searchParams.append(h,`(${n})`),this}filter(n,a,u){return this.url.searchParams.append(n,`${a}.${u}`),this}};e.default=i}),xe=C(e=>{"use strict";p();var t=e&&e.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(e,"__esModule",{value:!0});var r=re(),i=t(ce()),n=class{constructor(a,{headers:u={},schema:h,fetch:l}){this.url=a,this.headers=new r.FetchHeaders(u),this.schema=h,this.fetch=l}select(a,u){let{head:h=!1,count:l}=u??{},s=h?"HEAD":"GET",o=!1,c=(a??"*").split("").map(d=>/\s/.test(d)&&!o?"":(d==='"'&&(o=!o),d)).join("");return this.url.searchParams.set("select",c),l&&this.headers.append("Prefer",`count=${l}`),new i.default({method:s,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch})}insert(a,{count:u,defaultToNull:h=!0}={}){var l;let s="POST";if(u&&this.headers.append("Prefer",`count=${u}`),h||this.headers.append("Prefer","missing=default"),Array.isArray(a)){let o=a.reduce((c,d)=>c.concat(Object.keys(d)),[]);if(o.length>0){let c=[...new Set(o)].map(d=>`"${d}"`);this.url.searchParams.set("columns",c.join(","))}}return new i.default({method:s,url:this.url,headers:this.headers,schema:this.schema,body:a,fetch:(l=this.fetch)!==null&&l!==void 0?l:fetch})}upsert(a,{onConflict:u,ignoreDuplicates:h=!1,count:l,defaultToNull:s=!0}={}){var o;let c="POST";if(this.headers.append("Prefer",`resolution=${h?"ignore":"merge"}-duplicates`),u!==void 0&&this.url.searchParams.set("on_conflict",u),l&&this.headers.append("Prefer",`count=${l}`),s||this.headers.append("Prefer","missing=default"),Array.isArray(a)){let d=a.reduce((m,y)=>m.concat(Object.keys(y)),[]);if(d.length>0){let m=[...new Set(d)].map(y=>`"${y}"`);this.url.searchParams.set("columns",m.join(","))}}return new i.default({method:c,url:this.url,headers:this.headers,schema:this.schema,body:a,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch})}update(a,{count:u}={}){var h;let l="PATCH";return u&&this.headers.append("Prefer",`count=${u}`),new i.default({method:l,url:this.url,headers:this.headers,schema:this.schema,body:a,fetch:(h=this.fetch)!==null&&h!==void 0?h:fetch})}delete({count:a}={}){var u;let h="DELETE";return a&&this.headers.append("Prefer",`count=${a}`),new i.default({method:h,url:this.url,headers:this.headers,schema:this.schema,fetch:(u=this.fetch)!==null&&u!==void 0?u:fetch})}};e.default=n}),tt=C(e=>{"use strict";p();var t=e&&e.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(e,"__esModule",{value:!0});var r=t(xe()),i=t(ce()),n=re(),a=class Ne{constructor(h,{headers:l={},schema:s,fetch:o}={}){this.url=h,this.headers=new n.FetchHeaders(l),this.schemaName=s,this.fetch=o}from(h){let l=new n.URL(`${this.url}/${h}`);return new r.default(l,{headers:new n.FetchHeaders(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(h){return new Ne(this.url,{headers:this.headers,schema:h,fetch:this.fetch})}rpc(h,l={},{head:s=!1,get:o=!1,count:c}={}){var d;let m,y=new n.URL(`${this.url}/rpc/${h}`),g;s||o?(m=s?"HEAD":"GET",Object.entries(l).filter(([T,b])=>b!==void 0).map(([T,b])=>[T,Array.isArray(b)?`{${b.join(",")}}`:`${b}`]).forEach(([T,b])=>{y.searchParams.append(T,b)})):(m="POST",g=l);let v=new n.FetchHeaders(this.headers);return c&&v.set("Prefer",`count=${c}`),new i.default({method:m,url:y,headers:v,schema:this.schemaName,body:g,fetch:(d=this.fetch)!==null&&d!==void 0?d:fetch})}};e.default=a}),rt=C(e=>{"use strict";p();var t=e&&e.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(e,"__esModule",{value:!0}),e.File=e.FormData=e.Blob=e.FetchResponse=e.FetchHeaders=e.URLSearchParams=e.URL=e.PostgrestError=e.PostgrestBuilder=e.PostgrestTransformBuilder=e.PostgrestFilterBuilder=e.PostgrestQueryBuilder=e.PostgrestClient=void 0;var r=t(tt());e.PostgrestClient=r.default;var i=t(xe());e.PostgrestQueryBuilder=i.default;var n=t(ce());e.PostgrestFilterBuilder=n.default;var a=t(Ue());e.PostgrestTransformBuilder=a.default;var u=t($e());e.PostgrestBuilder=u.default;var h=t(_e());e.PostgrestError=h.default;var l=re();Object.defineProperty(e,"FetchHeaders",{enumerable:!0,get:function(){return l.FetchHeaders}}),Object.defineProperty(e,"FetchResponse",{enumerable:!0,get:function(){return l.FetchResponse}}),Object.defineProperty(e,"URL",{enumerable:!0,get:function(){return l.URL}}),Object.defineProperty(e,"URLSearchParams",{enumerable:!0,get:function(){return l.URLSearchParams}}),Object.defineProperty(e,"Blob",{enumerable:!0,get:function(){return l.Blob}}),Object.defineProperty(e,"FormData",{enumerable:!0,get:function(){return l.FormData}}),Object.defineProperty(e,"File",{enumerable:!0,get:function(){return l.File}}),e.default={PostgrestClient:r.default,PostgrestQueryBuilder:i.default,PostgrestFilterBuilder:n.default,PostgrestTransformBuilder:a.default,PostgrestBuilder:u.default,PostgrestError:h.default,URLSearchParams:l.URLSearchParams,FetchHeaders:l.FetchHeaders,FetchResponse:l.FetchResponse}});p();p();p();p();p();p();var st=Object.defineProperty,nt=Object.defineProperties,at=Object.getOwnPropertyDescriptors,ge=Object.getOwnPropertySymbols,ot=Object.prototype.hasOwnProperty,it=Object.prototype.propertyIsEnumerable,be=(e,t,r)=>t in e?st(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,x=(e,t)=>{for(var r in t||(t={}))ot.call(t,r)&&be(e,r,t[r]);if(ge)for(var r of ge(t))it.call(t,r)&&be(e,r,t[r]);return e},N=(e,t)=>nt(e,at(t)),lt=class extends Error{constructor(e,t,r){super(t||e.toString(),{cause:r}),this.status=e,this.statusText=t,this.error=r}},ut=async(e,t)=>{var r,i,n,a,u,h;let l=t||{},s={onRequest:[t?.onRequest],onResponse:[t?.onResponse],onSuccess:[t?.onSuccess],onError:[t?.onError],onRetry:[t?.onRetry]};if(!t||!t?.plugins)return{url:e,options:l,hooks:s};for(let o of t?.plugins||[]){if(o.init){let c=await((r=o.init)==null?void 0:r.call(o,e.toString(),t));l=c.options||l,e=c.url}s.onRequest.push((i=o.hooks)==null?void 0:i.onRequest),s.onResponse.push((n=o.hooks)==null?void 0:n.onResponse),s.onSuccess.push((a=o.hooks)==null?void 0:a.onSuccess),s.onError.push((u=o.hooks)==null?void 0:u.onError),s.onRetry.push((h=o.hooks)==null?void 0:h.onRetry)}return{url:e,options:l,hooks:s}},ve=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(){return this.options.delay}},ht=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(e){return Math.min(this.options.maxDelay,this.options.baseDelay*2**e)}};function ct(e){if(typeof e=="number")return new ve({type:"linear",attempts:e,delay:1e3});switch(e.type){case"linear":return new ve(e);case"exponential":return new ht(e);default:throw new Error("Invalid retry strategy")}}var dt=async e=>{let t={},r=async i=>typeof i=="function"?await i():i;if(e?.auth){if(e.auth.type==="Bearer"){let i=await r(e.auth.token);if(!i)return t;t.authorization=`Bearer ${i}`}else if(e.auth.type==="Basic"){let i=r(e.auth.username),n=r(e.auth.password);if(!i||!n)return t;t.authorization=`Basic ${btoa(`${i}:${n}`)}`}else if(e.auth.type==="Custom"){let i=r(e.auth.value);if(!i)return t;t.authorization=`${r(e.auth.prefix)} ${i}`}}return t},pt=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function ft(e){let t=e.headers.get("content-type"),r=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!t)return"json";let i=t.split(";").shift()||"";return pt.test(i)?"json":r.has(i)||i.startsWith("text/")?"text":"blob"}function mt(e){try{return JSON.parse(e),!0}catch{return!1}}function je(e){if(e===void 0)return!1;let t=typeof e;return t==="string"||t==="number"||t==="boolean"||t===null?!0:t!=="object"?!1:Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name==="Object"||typeof e.toJSON=="function"}function we(e){try{return JSON.parse(e)}catch{return e}}function Ee(e){return typeof e=="function"}function yt(e){if(e?.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<"u"&&Ee(globalThis.fetch))return globalThis.fetch;if(typeof window<"u"&&Ee(window.fetch))return window.fetch;throw new Error("No fetch implementation found")}async function gt(e){let t=new Headers(e?.headers),r=await dt(e);for(let[i,n]of Object.entries(r||{}))t.set(i,n);if(!t.has("content-type")){let i=bt(e?.body);i&&t.set("content-type",i)}return t}function bt(e){return je(e)?"application/json":null}function vt(e){if(!e?.body)return null;let t=new Headers(e?.headers);if(je(e.body)&&!t.has("content-type")){for(let[r,i]of Object.entries(e?.body))i instanceof Date&&(e.body[r]=i.toISOString());return JSON.stringify(e.body)}return e.body}function wt(e,t){var r;if(t?.method)return t.method.toUpperCase();if(e.startsWith("@")){let i=(r=e.split("@")[1])==null?void 0:r.split("/")[0];return Le.includes(i)?i.toUpperCase():t?.body?"POST":"GET"}return t?.body?"POST":"GET"}function Et(e,t){let r;return!e?.signal&&e?.timeout&&(r=setTimeout(()=>t?.abort(),e?.timeout)),{abortTimeout:r,clearTimeout:()=>{r&&clearTimeout(r)}}}var Tt=class Ie extends Error{constructor(t,r){super(r||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,Ie.prototype)}};async function Q(e,t){let r=await e["~standard"].validate(t);if(r.issues)throw new Tt(r.issues);return r.value}var Le=["get","post","put","patch","delete"],Rt=e=>({id:"apply-schema",name:"Apply Schema",version:"1.0.0",async init(t,r){var i,n,a,u;let h=((n=(i=e.plugins)==null?void 0:i.find(l=>{var s;return(s=l.schema)!=null&&s.config?t.startsWith(l.schema.config.baseURL||"")||t.startsWith(l.schema.config.prefix||""):!1}))==null?void 0:n.schema)||e.schema;if(h){let l=t;(a=h.config)!=null&&a.prefix&&l.startsWith(h.config.prefix)&&(l=l.replace(h.config.prefix,""),h.config.baseURL&&(t=t.replace(h.config.prefix,h.config.baseURL))),(u=h.config)!=null&&u.baseURL&&l.startsWith(h.config.baseURL)&&(l=l.replace(h.config.baseURL,""));let s=h.schema[l];if(s){let o=N(x({},r),{method:s.method,output:s.output});return r?.disableValidation||(o=N(x({},o),{body:s.input?await Q(s.input,r?.body):r?.body,params:s.params?await Q(s.params,r?.params):r?.params,query:s.query?await Q(s.query,r?.query):r?.query})),{url:t,options:o}}}return{url:t,options:r}}}),St=e=>{async function t(r,i){let n=N(x(x({},e),i),{plugins:[...e?.plugins||[],Rt(e||{})]});if(e?.catchAllError)try{return await le(r,n)}catch(a){return{data:null,error:{status:500,statusText:"Fetch Error",message:"Fetch related error. Captured by catchAllError option. See error property for more details.",error:a}}}return await le(r,n)}return t};function Ot(e,t){let{baseURL:r,params:i,query:n}=t||{query:{},params:{},baseURL:""},a=e.startsWith("http")?e.split("/").slice(0,3).join("/"):r||"";if(e.startsWith("@")){let o=e.toString().split("@")[1].split("/")[0];Le.includes(o)&&(e=e.replace(`@${o}/`,"/"))}a.endsWith("/")||(a+="/");let[u,h]=e.replace(a,"").split("?"),l=new URLSearchParams(h);for(let[o,c]of Object.entries(n||{}))c!=null&&l.set(o,String(c));if(i)if(Array.isArray(i)){let o=u.split("/").filter(c=>c.startsWith(":"));for(let[c,d]of o.entries()){let m=i[c];u=u.replace(d,m)}}else for(let[o,c]of Object.entries(i))u=u.replace(`:${o}`,String(c));u=u.split("/").map(encodeURIComponent).join("/"),u.startsWith("/")&&(u=u.slice(1));let s=l.toString();return s=s.length>0?`?${s}`.replace(/\+/g,"%20"):"",a.startsWith("http")?new URL(`${u}${s}`,a):`${a}${u}${s}`}var le=async(e,t)=>{var r,i,n,a,u,h,l,s;let{hooks:o,url:c,options:d}=await ut(e,t),m=yt(d),y=new AbortController,g=(r=d.signal)!=null?r:y.signal,v=Ot(c,d),T=vt(d),b=await gt(d),R=wt(c,d),f=N(x({},d),{url:v,headers:b,body:T,method:R,signal:g});for(let P of o.onRequest)if(P){let S=await P(f);S instanceof Object&&(f=S)}("pipeTo"in f&&typeof f.pipeTo=="function"||typeof((i=t?.body)==null?void 0:i.pipe)=="function")&&("duplex"in f||(f.duplex="half"));let{clearTimeout:A}=Et(d,y),w=await m(f.url,f);A();let z={response:w,request:f};for(let P of o.onResponse)if(P){let S=await P(N(x({},z),{response:(n=t?.hookOptions)!=null&&n.cloneResponse?w.clone():w}));S instanceof Response?w=S:S instanceof Object&&(w=S.response)}if(w.ok){if(f.method==="HEAD")return{data:"",error:null};let P=ft(w),S={data:"",response:w,request:f};if(P==="json"||P==="text"){let B=await w.text(),F=await((a=f.jsonParser)!=null?a:we)(B);S.data=F}else S.data=await w[P]();f?.output&&f.output&&!f.disableValidation&&(S.data=await Q(f.output,S.data));for(let B of o.onSuccess)B&&await B(N(x({},S),{response:(u=t?.hookOptions)!=null&&u.cloneResponse?w.clone():w}));return t?.throw?S.data:{data:S.data,error:null}}let k=(h=t?.jsonParser)!=null?h:we,V=await w.text(),ye=mt(V),ae=ye?await k(V):null,Je={response:w,responseText:V,request:f,error:N(x({},ae),{status:w.status,statusText:w.statusText})};for(let P of o.onError)P&&await P(N(x({},Je),{response:(l=t?.hookOptions)!=null&&l.cloneResponse?w.clone():w}));if(t?.retry){let P=ct(t.retry),S=(s=t.retryAttempt)!=null?s:0;if(await P.shouldAttemptRetry(S,w)){for(let F of o.onRetry)F&&await F(z);let B=P.getDelay(S);return await new Promise(F=>setTimeout(F,B)),await le(e,N(x({},t),{retryAttempt:S+1}))}}if(t?.throw)throw new lt(w.status,w.statusText,ye?ae:V);return{data:null,error:N(x({},ae),{status:w.status,statusText:w.statusText})}};p();p();var Z=Object.create(null),H=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?Z:globalThis),$=new Proxy(Z,{get(e,t){return H()[t]??Z[t]},has(e,t){let r=H();return t in r||t in Z},set(e,t,r){let i=H(!0);return i[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=H(!0);return delete r[t],!0},ownKeys(){let e=H(!0);return Object.keys(e)}}),br=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";function E(e,t){return typeof process<"u"&&process.env?process.env[e]??t:typeof Deno<"u"?Deno.env.get(e)??t:typeof Bun<"u"?Bun.env[e]??t:t}var vr=Object.freeze({get BETTER_AUTH_SECRET(){return E("BETTER_AUTH_SECRET")},get AUTH_SECRET(){return E("AUTH_SECRET")},get BETTER_AUTH_TELEMETRY(){return E("BETTER_AUTH_TELEMETRY")},get BETTER_AUTH_TELEMETRY_ID(){return E("BETTER_AUTH_TELEMETRY_ID")},get NODE_ENV(){return E("NODE_ENV","development")},get PACKAGE_VERSION(){return E("PACKAGE_VERSION","0.0.0")},get BETTER_AUTH_TELEMETRY_ENDPOINT(){return E("BETTER_AUTH_TELEMETRY_ENDPOINT","https://telemetry.better-auth.com/v1/track")}}),q=1,O=4,j=8,_=24,Te={eterm:O,cons25:O,console:O,cygwin:O,dtterm:O,gnome:O,hurd:O,jfbterm:O,konsole:O,kterm:O,mlterm:O,mosh:_,putty:O,st:O,"rxvt-unicode-24bit":_,terminator:_,"xterm-kitty":_},Pt=new Map(Object.entries({APPVEYOR:j,BUILDKITE:j,CIRCLECI:_,DRONE:j,GITEA_ACTIONS:_,GITHUB_ACTIONS:_,GITLAB_CI:j,TRAVIS:j})),At=[/ansi/,/color/,/linux/,/direct/,/^con[0-9]*x[0-9]/,/^rxvt/,/^screen/,/^xterm/,/^vt100/,/^vt220/];function _t(){if(E("FORCE_COLOR")!==void 0)switch(E("FORCE_COLOR")){case"":case"1":case"true":return O;case"2":return j;case"3":return _;default:return q}if(E("NODE_DISABLE_COLORS")!==void 0&&E("NODE_DISABLE_COLORS")!==""||E("NO_COLOR")!==void 0&&E("NO_COLOR")!==""||E("TERM")==="dumb")return q;if(E("TMUX"))return _;if("TF_BUILD"in $&&"AGENT_NAME"in $)return O;if("CI"in $){for(let{0:e,1:t}of Pt)if(e in $)return t;return E("CI_NAME")==="codeship"?j:q}if("TEAMCITY_VERSION"in $)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.exec(E("TEAMCITY_VERSION"))!==null?O:q;switch(E("TERM_PROGRAM")){case"iTerm.app":return!E("TERM_PROGRAM_VERSION")||/^[0-2]\./.exec(E("TERM_PROGRAM_VERSION"))!==null?j:_;case"HyperTerm":case"MacTerm":return _;case"Apple_Terminal":return j}if(E("COLORTERM")==="truecolor"||E("COLORTERM")==="24bit")return _;if(E("TERM")){if(/truecolor/.exec(E("TERM"))!==null)return _;if(/^xterm-256/.exec(E("TERM"))!==null)return j;let e=E("TERM").toLowerCase();if(Te[e])return Te[e];if(At.some(t=>t.exec(e)!==null))return O}return E("COLORTERM")?O:q}var I={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 $t(e,t){return ue.indexOf(t)<=ue.indexOf(e)}var Ut={info:I.fg.blue,success:I.fg.green,warn:I.fg.yellow,error:I.fg.red,debug:I.fg.magenta},xt=(e,t,r)=>{let i=new Date().toISOString();return r?`${I.dim}${i}${I.reset} ${Ut[e]}${e.toUpperCase()}${I.reset} ${I.bright}[Better Auth]:${I.reset} ${t}`:`${i} ${e.toUpperCase()} [Better Auth]: ${t}`},Nt=e=>{let t=e?.disabled!==!0,r=e?.level??"error",i=e?.disableColors!==void 0?!e.disableColors:_t()!==1,n=(a,u,h=[])=>{if(!t||!$t(r,a))return;let l=xt(a,u,i);if(!e||typeof e.log!="function"){a==="error"?console.error(l,...h):a==="warn"?console.warn(l,...h):console.log(l,...h);return}e.log(a==="success"?"info":a,u,...h)};return{...Object.fromEntries(ue.map(a=>[a,(...[u,...h])=>n(a,u,h)])),get level(){return r}}},wr=Nt();p();p();var de=class extends Error{constructor(e,t){super(e),this.name="BetterAuthError",this.message=e,this.cause=t,this.stack=""}};function jt(e){try{return(new URL(e).pathname.replace(/\/+$/,"")||"/")!=="/"}catch{throw new de(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function W(e,t="/api/auth"){if(jt(e))return e;let r=e.replace(/\/+$/,"");return!t||t==="/"?r:(t=t.startsWith("/")?t:`/${t}`,`${r}${t}`)}function It(e,t,r,i){if(e)return W(e,t);if(i!==!1){let u=$.BETTER_AUTH_URL||$.NEXT_PUBLIC_BETTER_AUTH_URL||$.PUBLIC_BETTER_AUTH_URL||$.NUXT_PUBLIC_BETTER_AUTH_URL||$.NUXT_PUBLIC_AUTH_URL||($.BASE_URL!=="/"?$.BASE_URL:void 0);if(u)return W(u,t)}let n=r?.headers.get("x-forwarded-host"),a=r?.headers.get("x-forwarded-proto");if(n&&a)return W(`${a}://${n}`,t);if(r){let u=Lt(r.url);if(!u)throw new de("Could not get origin from request. Please provide a valid base URL.");return W(u,t)}if(typeof window<"u"&&window.location)return W(window.location.origin,t)}function Lt(e){try{return new URL(e).origin}catch{return null}}p();p();p();var he=Symbol("clean"),U=[],L=0,K=4,Ct=0,Ce=e=>{let t=[],r={get(){return r.lc||r.listen(()=>{})(),r.value},lc:0,listen(i){return r.lc=t.push(i),()=>{for(let a=L+K;a<U.length;)U[a]===i?U.splice(a,K):a+=K;let n=t.indexOf(i);~n&&(t.splice(n,1),--r.lc||r.off())}},notify(i,n){Ct++;let a=!U.length;for(let u of t)U.push(u,r.value,i,n);if(a){for(L=0;L<U.length;L+=K)U[L](U[L+1],U[L+2],U[L+3]);U.length=0}},off(){},set(i){let n=r.value;n!==i&&(r.value=i,r.notify(n))},subscribe(i){let n=r.listen(i);return i(r.value),n},value:e};return process.env.NODE_ENV!=="production"&&(r[he]=()=>{t=[],r.lc=0,r.off()}),r};p();var Dt=5,M=6,Y=10,Bt=(e,t,r,i)=>(e.events=e.events||{},e.events[r+Y]||(e.events[r+Y]=i(n=>{e.events[r].reduceRight((a,u)=>(u(a),a),{shared:{},...n})})),e.events[r]=e.events[r]||[],e.events[r].push(t),()=>{let n=e.events[r],a=n.indexOf(t);n.splice(a,1),n.length||(delete e.events[r],e.events[r+Y](),delete e.events[r+Y])}),Ft=1e3,Mt=(e,t)=>Bt(e,r=>{let i=t(r);i&&e.events[M].push(i)},Dt,r=>{let i=e.listen;e.listen=(...a)=>(!e.lc&&!e.active&&(e.active=!0,r()),i(...a));let n=e.off;if(e.events[M]=[],e.off=()=>{n(),setTimeout(()=>{if(e.active&&!e.lc){e.active=!1;for(let a of e.events[M])a();e.events[M]=[]}},Ft)},process.env.NODE_ENV!=="production"){let a=e[he];e[he]=()=>{for(let u of e.events[M])u();e.events[M]=[],e.active=!1,a()}}return()=>{e.listen=i,e.off=n}});p();var kt=typeof window>"u",Ht=(e,t,r,i)=>{let n=Ce({data:null,error:null,isPending:!0,isRefetching:!1,refetch:h=>a(h)}),a=h=>{let l=typeof i=="function"?i({data:n.get().data,error:n.get().error,isPending:n.get().isPending}):i;r(t,{...l,query:{...l?.query,...h?.query},async onSuccess(s){n.set({data:s.data,error:null,isPending:!1,isRefetching:!1,refetch:n.value.refetch}),await l?.onSuccess?.(s)},async onError(s){let{request:o}=s,c=typeof o.retry=="number"?o.retry:o.retry?.attempts,d=o.retryAttempt||0;c&&d<c||(n.set({error:s.error,data:null,isPending:!1,isRefetching:!1,refetch:n.value.refetch}),await l?.onError?.(s))},async onRequest(s){let o=n.get();n.set({isPending:o.data===null,data:o.data,error:null,isRefetching:!0,refetch:n.value.refetch}),await l?.onRequest?.(s)}}).catch(s=>{n.set({error:s,data:null,isPending:!1,isRefetching:!1,refetch:n.value.refetch})})};e=Array.isArray(e)?e:[e];let u=!1;for(let h of e)h.subscribe(()=>{kt||(u?a():Mt(n,()=>{let l=setTimeout(()=>{u||(a(),u=!0)},0);return()=>{n.off(),h.off(),clearTimeout(l)}}))});return n};p();var qt={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*:/},Wt=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,Re={true:!0,false:!1,null:null,undefined:void 0,nan:Number.NaN,infinity:Number.POSITIVE_INFINITY,"-infinity":Number.NEGATIVE_INFINITY},Gt=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function Jt(e){return e instanceof Date&&!isNaN(e.getTime())}function zt(e){let t=Gt.exec(e);if(!t)return null;let[,r,i,n,a,u,h,l,s,o,c]=t,d=new Date(Date.UTC(parseInt(r,10),parseInt(i,10)-1,parseInt(n,10),parseInt(a,10),parseInt(u,10),parseInt(h,10),l?parseInt(l.padEnd(3,"0"),10):0));if(s){let m=(parseInt(o,10)*60+parseInt(c,10))*(s==="+"?-1:1);d.setUTCMinutes(d.getUTCMinutes()+m)}return Jt(d)?d:null}function Vt(e,t={}){let{strict:r=!1,warnings:i=!1,reviver:n,parseDates:a=!0}=t;if(typeof e!="string")return e;let u=e.trim();if(u.length>0&&u[0]==='"'&&u.endsWith('"')&&!u.slice(1,-1).includes('"'))return u.slice(1,-1);let h=u.toLowerCase();if(h.length<=9&&h in Re)return Re[h];if(!Wt.test(u)){if(r)throw new SyntaxError("[better-json] Invalid JSON");return e}if(Object.entries(qt).some(([l,s])=>{let o=s.test(u);return o&&i&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${l} pattern`),o})&&r)throw new Error("[better-json] Potential prototype pollution attempt detected");try{return JSON.parse(u,(l,s)=>{if(l==="__proto__"||l==="constructor"&&s&&typeof s=="object"&&"prototype"in s){i&&console.warn(`[better-json] Dropping "${l}" key to prevent prototype pollution`);return}if(a&&typeof s=="string"){let o=zt(s);if(o)return o}return n?n(l,s):s})}catch(l){if(r)throw l;return e}}function Kt(e,t={strict:!0}){return Vt(e,t)}var Yt={id:"redirect",name:"Redirect",hooks:{onSuccess(e){if(e.data?.url&&e.data?.redirect&&typeof window<"u"&&window.location&&window.location)try{window.location.href=e.data.url}catch{}}}};function Xt(e){let t=Ce(!1);return{session:Ht(t,"/get-session",e,{method:"GET"}),$sessionSignal:t}}var Qt=(e,t)=>{let r="credentials"in Request.prototype,i=It(e?.baseURL,e?.basePath,void 0,t)??"/api/auth",n=e?.plugins?.flatMap(f=>f.fetchPlugins).filter(f=>f!==void 0)||[],a={id:"lifecycle-hooks",name:"lifecycle-hooks",hooks:{onSuccess:e?.fetchOptions?.onSuccess,onError:e?.fetchOptions?.onError,onRequest:e?.fetchOptions?.onRequest,onResponse:e?.fetchOptions?.onResponse}},{onSuccess:u,onError:h,onRequest:l,onResponse:s,...o}=e?.fetchOptions||{},c=St({baseURL:i,...r?{credentials:"include"}:{},method:"GET",jsonParser(f){return f?Kt(f,{strict:!1}):null},customFetchImpl:fetch,...o,plugins:[a,...o.plugins||[],...e?.disableDefaultFetchPlugins?[]:[Yt],...n]}),{$sessionSignal:d,session:m}=Xt(c),y=e?.plugins||[],g={},v={$sessionSignal:d,session:m},T={"/sign-out":"POST","/revoke-sessions":"POST","/revoke-other-sessions":"POST","/delete-user":"POST"},b=[{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 y)f.getAtoms&&Object.assign(v,f.getAtoms?.(c)),f.pathMethods&&Object.assign(T,f.pathMethods),f.atomListeners&&b.push(...f.atomListeners);let R={notify:f=>{v[f].set(!v[f].get())},listen:(f,A)=>{v[f].subscribe(A)},atoms:v};for(let f of y)f.getActions&&Object.assign(g,f.getActions?.(c,R,e));return{get baseURL(){return i},pluginsActions:g,pluginsAtoms:v,pluginPathMethods:T,atomListeners:b,$fetch:c,$store:R}};function Zt(e){return typeof e=="object"&&e!==null&&"get"in e&&typeof e.get=="function"&&"lc"in e&&typeof e.lc=="number"}function er(e,t,r){let i=t[e],{fetchOptions:n,query:a,...u}=r||{};return i||(n?.method?n.method:u&&Object.keys(u).length>0?"POST":"GET")}function tr(e,t,r,i,n){function a(u=[]){return new Proxy(function(){},{get(h,l){if(typeof l!="string"||l==="then"||l==="catch"||l==="finally")return;let s=[...u,l],o=e;for(let c of s)if(o&&typeof o=="object"&&c in o)o=o[c];else{o=void 0;break}return typeof o=="function"||Zt(o)?o:a(s)},apply:async(h,l,s)=>{let o="/"+u.map(b=>b.replace(/[A-Z]/g,R=>`-${R.toLowerCase()}`)).join("/"),c=s[0]||{},d=s[1]||{},{query:m,fetchOptions:y,...g}=c,v={...d,...y},T=er(o,r,c);return await t(o,{...v,body:T==="GET"?void 0:{...g,...v?.body||{}},query:m||v?.query,method:T,async onSuccess(b){if(await v?.onSuccess?.(b),!n)return;let R=n.filter(f=>f.matcher(o));if(R.length)for(let f of R){let A=i[f.signal];if(!A)return;let w=A.get();setTimeout(()=>{A.set(!w)},10)}}})}})}return a()}p();function rr(e){return e.charAt(0).toUpperCase()+e.slice(1)}function sr(e){let{pluginPathMethods:t,pluginsActions:r,pluginsAtoms:i,$fetch:n,atomListeners:a,$store:u}=Qt(e),h={};for(let[s,o]of Object.entries(i))h[`use${rr(s)}`]=o;let l={...r,...h,$fetch:n,$store:u};return tr(l,n,t,i,a)}p();p();p();function nr(e){return{authorize(t,r="AND"){let i=!1;for(let[n,a]of Object.entries(t)){let u=e[n];if(!u)return{success:!1,error:`You are not allowed to access resource: ${n}`};if(Array.isArray(a))i=a.every(h=>u.includes(h));else if(typeof a=="object"){let h=a;h.connector==="OR"?i=h.actions.some(l=>u.includes(l)):i=h.actions.every(l=>u.includes(l))}else throw new de("Invalid access control request");if(i&&r==="OR")return{success:i};if(!i&&r==="AND")return{success:!1,error:`unauthorized to access resource "${n}"`}}return i?{success:i}:{success:!1,error:"Not authorized"}},statements:e}}function De(e){return{newRole(t){return nr(t)},statements:e}}var ar={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"],team:["create","update","delete"],ac:["create","read","update","delete"]},pe=De(ar),Er=pe.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"],team:["create","update","delete"],ac:["create","read","update","delete"]}),Tr=pe.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"],team:["create","update","delete"],ac:["create","read","update","delete"]}),Rr=pe.newRole({organization:[],member:[],invitation:[],team:[],ac:["read"]});p();p();p();p();p();p();p();p();p();p();p();var or=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}}},Sr=new or;p();p();p();p();p();p();p();p();var ir={user:["create","list","set-role","ban","impersonate","delete","set-password","get","update"],session:["list","revoke","delete"]},Be=De(ir),Or=Be.newRole({user:["create","list","set-role","ban","impersonate","delete","set-password","get","update"],session:["list","revoke","delete"]}),Pr=Be.newRole({user:[],session:[]});p();p();var lr=()=>({id:"username",$InferServerPlugin:{}});var X="nvwa_login_token",oe="nvwa_user_profile",Fe=class{constructor(e,t,r){this.storage=r,this.authClient=sr({baseUrl:e,fetchOptions:{customFetchImpl:t,auth:{type:"Bearer",token:()=>r.get(X)},onSuccess:i=>{let n=i.response.headers.get("set-auth-token");n&&r.set(X,n)}},plugins:[lr()]})}async currentUser(){return await this.storage.get(oe)}async signUp(e,t){let r=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(r)}async signInWithUsername(e,t){let r=await this.authClient.signIn.username({username:e,password:t});this.saveSession(r)}saveSession(e){if(e.error)throw new Error(e.error.message);this.storage.set(X,e.data?.token),this.storage.set(oe,e.data?.user)}async signOut(){await this.storage.remove(X),await this.storage.remove(oe)}async updateUserPassword(e,t,r=!1){let i=await this.authClient.changePassword({currentPassword:e,newPassword:t,revokeOtherSessions:r});this.saveSession(i)}};p();var Me=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}};p();var ke=class{async jsonRequest(e,t){let r={...t,headers:{"Content-Type":"application/json",...t.headers},data:typeof t.data=="object"?JSON.stringify(t.data):t.data};return this.request(e,r)}async jsonRequestWithAuth(e,t,r){let i={...t,headers:{"Content-Type":"application/json",...t.headers},data:typeof t.data=="object"?JSON.stringify(t.data):t.data};return this.requestWithAuth(e,i,r)}};p();var ur="/storage",hr=ur+"/generateUploadUrl",He=class{constructor(e,t){this.baseUrl=e,this.http=t}async uploadFile(e){let t=await this.http.request(this.baseUrl+hr,{method:"POST",data:{fileName:e.name||e.fileName,fileSize:e.size||e.fileSize,fileType:e.type||e.fileType}}),{url:r}=t.body;if(!r)throw new Error("\u83B7\u53D6\u4E0A\u4F20URL\u5931\u8D25");return{url:(await this.http.request(r,{method:"PUT",data:e,headers:{"Content-Type":e.type||e.fileType||"application/octet-stream"}})).body.url.split("?")[0]}}};p();p();p();var cr=et(rt(),1),{PostgrestClient:dr,PostgrestQueryBuilder:Ar,PostgrestFilterBuilder:_r,PostgrestTransformBuilder:$r,PostgrestBuilder:Ur,PostgrestError:xr,FetchHeaders:Nr,FetchResponse:Se,PostgrestFetch:jr,URL:Ir,URLSearchParams:Lr}=cr.default,pr="/entities",fr=(e,t)=>async(r,i)=>{console.log("customFetch",r,i);let n;if(typeof r=="string")n=r;else if(r&&typeof r=="object")if(typeof r.toString=="function"&&!r.url)n=r.toString();else if(r.url)n=r.url,i||(i={}),i.method=r.method,i.headers=r.headers,i.body=r.body;else throw new Error("Unsupported input type for fetch");else throw new Error("Unsupported input type for fetch");let a=(i?.method||"GET").toUpperCase(),u={};if(i?.headers)if(i.headers&&typeof i.headers.forEach=="function")i.headers.forEach((c,d)=>{u[d]=c});else if(Array.isArray(i.headers))for(let[c,d]of i.headers)u[c]=d;else Object.assign(u,i.headers);let h=i?.body,l;try{l=await e.requestWithAuth(n,{method:a,data:h,headers:u},t)}catch(c){return new Se(c?.message||"Internal Error",{status:500,statusText:"Internal Error"})}let s=l.body,o=null;return(l.headers["content-type"]||l.headers["Content-Type"]||"").startsWith("application/json")&&typeof s!="string"?o=JSON.stringify(s):typeof s=="string"||s&&(s.constructor===Blob||s.constructor===ArrayBuffer||typeof s.getReader=="function")?o=s:o=JSON.stringify(s),new Se(o,{status:l.status,headers:l.headers})},qe=(e,t,r)=>new dr(e+pr,{fetch:fr(t,r)});p();p();var D=class We{constructor(t){if(this.headerMap=new Map,t){if(t instanceof We)t.forEach((r,i)=>this.set(i,r));else if(Array.isArray(t))for(let[r,i]of t)this.set(r,String(i));else if(typeof t=="object")for(let r of Object.keys(t))this.set(r,String(t[r]))}}append(t,r){let i=t.toLowerCase(),n=this.headerMap.get(i);this.headerMap.set(i,n?`${n}, ${r}`:r)}set(t,r){this.headerMap.set(t.toLowerCase(),String(r))}get(t){return this.headerMap.get(t.toLowerCase())??null}has(t){return this.headerMap.has(t.toLowerCase())}delete(t){this.headerMap.delete(t.toLowerCase())}forEach(t){for(let[r,i]of this.headerMap.entries())t(i,r,this)}entries(){return this.headerMap.entries()}keys(){return this.headerMap.keys()}values(){return this.headerMap.values()}[Symbol.iterator](){return this.entries()}};p();p();var Ge=class{constructor(e,t){this.bodyData=e,this.status=t?.status??200,this.statusText=t?.statusText??"",this.headers=mr(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 mr(e){return e?new D(e):new D}p();p();var yr=(e,t)=>{let r;if(typeof e=="string")r=e;else if(e&&typeof e.toString=="function")r=e.toString();else if(e?.url)r=e.url;else throw new Error("Invalid input for uniappFetch");let i=(t?.method||"GET").toUpperCase(),n={};if(t?.headers){let h=t.headers;if(typeof h?.forEach=="function")h.forEach((l,s)=>{n[s]=l});else if(Array.isArray(h))for(let[l,s]of h)n[l]=s;else Object.assign(n,h)}let a;if(t?.body!==void 0){let h=t.body;if(typeof h=="string")a=h;else if(h&&typeof h=="object"&&typeof h.forEach=="function"){let l={};h.forEach((s,o)=>{l[o]=s}),a=l}else a=h}let u=t?.timeout||3e4;return new Promise((h,l)=>{let s=t?.signal;if(s?.aborted){let m=new Error("The operation was aborted");m.name="AbortError",l(m);return}let o=!1,c=[],d=uni.request({url:r,method:i,data:a,header:n,timeout:u,success:m=>{if(o)return;o=!0;let y=m.statusCode,g="",v=new D,T=m.header||m.headers||{};Object.keys(T).forEach(b=>{let R=T[b];v.set(b,typeof R=="string"?R:String(R))}),h(new Ge(m.data,{status:y,statusText:g,headers:v}))},fail:m=>{if(o)return;o=!0;let y=m?.errMsg||m?.message||"Network Error",g=new Error(y);/(abort|aborted|canceled|cancelled)/i.test(String(y))&&(g.name="AbortError"),l(g)}});if(s&&typeof s.addEventListener=="function"){let m=()=>{if(o)return;try{d?.abort?.()}catch{}let y=new Error("The operation was aborted");y.name="AbortError",o=!0,l(y)};s.addEventListener("abort",m),c.push(()=>{try{s.removeEventListener?.("abort",m)}catch{}})}})},J=yr;var se=class extends ke{async request(t,r){let i=await J(t,{method:r.method,headers:new D(r.headers),body:r.data});return{status:i.status,body:await i.json(),headers:Object.fromEntries(i.headers.entries())}}async requestWithAuth(t,r,i){let n=await this.fetchWithAuth(i,t,{method:r.method,headers:new D(r.headers),body:r.data});return{status:n.status,body:await n.json(),headers:Object.fromEntries(n.headers.entries())}}async fetchWithAuth(t,r,i){let n=await J(r,i);if(n.status===401)throw t(),new Error("\u672A\u767B\u5F55");return n}};var ne=class{constructor(){this.prefix="nvwa_"}getKey(t){return`${this.prefix}${t}`}async get(t){try{let r=this.getKey(t),i=uni.getStorageSync(r);return i?i.expires&&Date.now()>i.expires?(await this.remove(t),null):i.value:null}catch(r){return console.error("UniAppStorageService get error:",r),null}}async set(t,r,i){try{let n=this.getKey(t),a={value:r,expires:i?Date.now()+i*1e3:null,timestamp:Date.now()};uni.setStorageSync(n,a)}catch(n){throw console.error("UniAppStorageService set error:",n),n}}async remove(t){try{let r=this.getKey(t);uni.removeStorageSync(r)}catch(r){throw console.error("UniAppStorageService remove error:",r),r}}async clear(){try{uni.clearStorageSync()}catch(t){throw console.error("UniAppStorageService clear error:",t),t}}};var gr=new ne,fe=new se,me=class{constructor(t,r){this.auth=new Fe(t,J,gr),this.fileStorage=new He(t,fe),this.entities=qe(t,fe,r),this.functions=new Me(fe)}};export{me as default,fe as httpClient,gr as localStorage};
package/package.json CHANGED
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "name": "@nvwa-app/sdk-uniapp",
3
- "version": "0.4.4",
3
+ "version": "0.4.7",
4
4
  "description": "NVWA跨端通用工具类UniApp端实现",
5
- "main": "dist/index.cjs",
5
+ "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
7
7
  "types": "dist/index.d.ts",
8
8
  "exports": {
9
9
  ".": {
10
10
  "import": "./dist/index.mjs",
11
- "require": "./dist/index.cjs",
11
+ "require": "./dist/index.js",
12
12
  "types": "./dist/index.d.ts"
13
13
  }
14
14
  },
@@ -29,8 +29,7 @@
29
29
  "directory": "packages/uniapp"
30
30
  },
31
31
  "dependencies": {
32
- "@nvwa-app/sdk-core": "0.4.4",
33
- "@nvwa-app/postgrest-js": "^2.75.15"
32
+ "@nvwa-app/sdk-core": "0.4.7"
34
33
  },
35
34
  "devDependencies": {
36
35
  "@types/node": "^24.3.0",
@@ -46,7 +45,7 @@
46
45
  "minify": true,
47
46
  "splitting": false,
48
47
  "shims": true,
49
- "noExternal": ["@nvwa-app/postgrest-js"]
48
+ "noExternal": ["@nvwa-app/sdk-core"]
50
49
  },
51
50
  "keywords": [
52
51
  "nvwa",