@nvwa-app/sdk-web 6.29.0 → 6.30.0
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.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var A=Object.defineProperty;var oe=Object.getOwnPropertyDescriptor;var le=Object.getOwnPropertyNames;var he=Object.prototype.hasOwnProperty;var ce=(t,e)=>{for(var r in e)A(t,r,{get:e[r],enumerable:!0})},ue=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of le(e))!he.call(t,s)&&s!==r&&A(t,s,{get:()=>e[s],enumerable:!(i=oe(e,s))||i.enumerable});return t};var de=t=>ue(A({},"__esModule",{value:!0}),t);var Be={};ce(Be,{SocialLoginButtons:()=>Ge,default:()=>$,disableIframeHoverInspector:()=>Re,enableIframeHoverInspector:()=>Ue,getIframeSourceLocation:()=>je,localStorage:()=>R,setupIframeHoverInspector:()=>ke,setupIframeSourceLocationListener:()=>He,webFetch:()=>O});module.exports=de(Be);var y=class D{constructor(e){if(this.headerMap=new Map,e){if(e instanceof D)e.forEach((r,i)=>this.set(i,r));else if(Array.isArray(e))for(let[r,i]of e)this.set(r,String(i));else if(typeof e=="object")for(let r of Object.keys(e))this.set(r,String(e[r]))}}append(e,r){let i=e.toLowerCase(),s=this.headerMap.get(i);this.headerMap.set(i,s?`${s}, ${r}`:r)}set(e,r){this.headerMap.set(e.toLowerCase(),String(r))}get(e){return this.headerMap.get(e.toLowerCase())??null}has(e){return this.headerMap.has(e.toLowerCase())}delete(e){this.headerMap.delete(e.toLowerCase())}forEach(e){for(let[r,i]of this.headerMap.entries())e(i,r,this)}entries(){return this.headerMap.entries()}keys(){return this.headerMap.keys()}values(){return this.headerMap.values()}[Symbol.iterator](){return this.entries()}},pe=class G{constructor(e){if(this.params=new Map,e){if(typeof e=="string")this.parseString(e);else if(e instanceof G)this.params=new Map(e.params);else if(Array.isArray(e))for(let[r,i]of e)this.append(r,i);else if(e&&typeof e=="object")for(let[r,i]of Object.entries(e))this.set(r,i)}}parseString(e){e.startsWith("?")&&(e=e.slice(1));let r=e.split("&");for(let i of r)if(i){let[s,a]=i.split("=");s&&this.append(decodeURIComponent(s),a?decodeURIComponent(a):"")}}append(e,r){let i=this.params.get(e)||[];i.push(r),this.params.set(e,i)}delete(e){this.params.delete(e)}get(e){let r=this.params.get(e);return r?r[0]:null}getAll(e){return this.params.get(e)||[]}has(e){return this.params.has(e)}set(e,r){this.params.set(e,[r])}sort(){let e=Array.from(this.params.entries()).sort(([r],[i])=>r.localeCompare(i));this.params=new Map(e)}toString(){let e=[];for(let[r,i]of this.params.entries())for(let s of i)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(s)}`);return e.join("&")}forEach(e){for(let[r,i]of this.params.entries())for(let s of i)e(s,r,this)}keys(){return this.params.keys()}values(){let e=[];for(let r of this.params.values())e.push(...r);return e[Symbol.iterator]()}entries(){let e=[];for(let[r,i]of this.params.entries())for(let s of i)e.push([r,s]);return e[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}},N=class I{constructor(e,r){let i;if(e instanceof I)i=e.href;else if(r){let a=r instanceof I?r.href:r;i=this.resolve(a,e)}else i=e;let s=this.parseUrl(i);this.href=i,this.origin=`${s.protocol}//${s.host}`,this.protocol=s.protocol,this.username=s.username,this.password=s.password,this.host=s.host,this.hostname=s.hostname,this.port=s.port,this.pathname=s.pathname,this.search=s.search,this.searchParams=new pe(s.search),this.hash=s.hash}resolve(e,r){if(r.startsWith("http://")||r.startsWith("https://"))return r;if(r.startsWith("//"))return`${this.parseUrl(e).protocol}${r}`;if(r.startsWith("/")){let a=this.parseUrl(e);return`${a.protocol}//${a.host}${r}`}let i=this.parseUrl(e),s=i.pathname.endsWith("/")?i.pathname:i.pathname+"/";return`${i.protocol}//${i.host}${s}${r}`}parseUrl(e){let r=e.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!r)throw new TypeError("Invalid URL");let i=r[2]||"",s=r[4]||"",a=r[5]||"/",o=r[7]?`?${r[7]}`:"",n=r[9]?`#${r[9]}`:"";if(!i&&!s&&!a.startsWith("/")&&!a.includes("/")&&!a.includes("."))throw new TypeError("Invalid URL");let c=s.match(/^([^@]*)@(.+)$/),h="",l="",u=s;if(c){let f=c[1];u=c[2];let w=f.match(/^([^:]*):?(.*)$/);w&&(h=w[1]||"",l=w[2]||"")}let d=u.match(/^([^:]+):?(\d*)$/),m=d?d[1]:u,p=d&&d[2]?d[2]:"";return{protocol:i?`${i}:`:"",username:h,password:l,host:u,hostname:m,port:p,pathname:a,search:o,hash:n}}toString(){let e=this.searchParams.toString(),r=e?`?${e}`:"";return`${this.protocol}//${this.host}${this.pathname}${r}${this.hash}`}toJSON(){return this.toString()}};var B=class{constructor(t,e){this.bodyData=t,this.status=e?.status??200,this.statusText=e?.statusText??"",this.headers=me(e?.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 t=await this.text();return new TextEncoder().encode(t).buffer}};function me(t){return t?new y(t):new y}var ge=class{constructor(){this._aborted=!1,this.listeners=new Set,this.onabort=null}get aborted(){return this._aborted}_trigger(){if(!this._aborted){if(this._aborted=!0,typeof this.onabort=="function")try{this.onabort()}catch{}for(let t of Array.from(this.listeners))try{t()}catch{}this.listeners.clear()}}addEventListener(t,e){if(this._aborted){try{e()}catch{}return}this.listeners.add(e)}removeEventListener(t,e){this.listeners.delete(e)}toString(){return"[object AbortSignal]"}},fe=class{constructor(){this._signal=new ge}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}},z=class{constructor(t,e=""){this.http=t,this.baseUrl=e.replace(/\/$/,"")}async invoke(t,e){let r=this.baseUrl?`${this.baseUrl}/functions/${t}`:`/functions/${t}`;return await(await this.http.fetch(r,{method:e.method||"POST",body:e.body,headers:e.headers})).json()}},g="nvwa_current_jwt",v="nvwa_login_token",b="nvwa_user_profile",ye="set-auth-token",we=typeof fetch<"u"?(t,e)=>fetch(t,e):()=>{throw new Error("AuthClient requires fetch")},J={google:{id:"google",name:"Google Login",description:"Sign in with Google account."},github:{id:"github",name:"GitHub Login",description:"Sign in with GitHub account."},"wechat-website":{id:"wechat-website",name:"WeChat QR Login",description:"Sign in with WeChat website QR code."},"wechat-miniprogram":{id:"wechat-miniprogram",name:"WeChat Mini Program Login",description:"Sign in with WeChat mini program code."},"alipay-miniprogram":{id:"alipay-miniprogram",name:"Alipay Mini Program Login",description:"Sign in with Alipay mini program code."},"douyin-miniprogram":{id:"douyin-miniprogram",name:"Douyin Mini Program Login",description:"Sign in with Douyin mini program code."}};function H(t){let e=J[t]??{id:t,name:t,description:""},r="unsupported";switch(t){case"google":r="google_openplatform";break;case"github":r="github_openplatform";break;case"wechat-website":r="wechat_website_openplatform";break;case"wechat-miniprogram":r="wechat_miniprogram_code";break;case"alipay-miniprogram":r="alipay_miniprogram_code";break;case"douyin-miniprogram":r="douyin_miniprogram_code";break;default:break}return{id:e.id,type:e.id,name:e.name,description:e.description,loginKind:r}}function W(t,e){let r=t.socialLogin?.providers?.[e];return r?.enabled?r.oauthCredentialSource==="custom"?"custom":"nvwa_default":null}var K=class{constructor(t,e={}){this.baseUrl=t.replace(/\/$/,""),this.authPath=(e.authPath??"/auth").replace(/^\//,""),this.fetchImpl=e.fetchImpl??we,this.storage=e.storage??null,this.credentials=e.credentials??"omit",this.integrationProviders=e.integrationProviders??{},this.defaultApplicationCode=e.applicationCode?.trim()||null,typeof console<"u"&&(console.warn("[NvwaAuth] init baseUrl:",this.baseUrl||"(empty)"),(!this.baseUrl||!this.baseUrl.startsWith("http://")&&!this.baseUrl.startsWith("https://"))&&console.warn("[NvwaAuth] baseUrl \u5E94\u4E3A\u5B8C\u6574\u5730\u5740\uFF08\u5982 https://xxx.nvwa.app\uFF09\uFF0C\u5426\u5219\u5C0F\u7A0B\u5E8F request \u4F1A\u62A5 invalid url"))}async getSocialProviders(t){let e=this.integrationProviders.socialLogin?.providers??{};return Object.entries(e).filter(([,r])=>r.enabled).map(([r])=>{let i=J[r]??{id:r,name:r,description:""};return{...i,type:i.id}})}async getSocialProviderDescriptors(t){let e=this.integrationProviders.socialLogin?.providers??{};return Object.entries(e).filter(([,r])=>!!r?.enabled).map(([r])=>H(r))}async getAvailableProviders(t){return this.getSocialProviders(t)}async startSocialLogin(t,e){let r=H(t),i=e?.applicationCode?.trim()||this.defaultApplicationCode||void 0,s=e?.returnUrl??(typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:"");switch(r.loginKind){case"google_openplatform":if(!s)throw new Error("startSocialLogin requires returnUrl for google");this.startGoogleOpenPlatformLogin(s,{applicationCode:i,platformCode:e?.platformCode});return;case"github_openplatform":if(!s)throw new Error("startSocialLogin requires returnUrl for github");this.startGithubOpenPlatformLogin(s,{applicationCode:i,platformCode:e?.platformCode});return;case"wechat_website_openplatform":if(!s)throw new Error("startSocialLogin requires returnUrl for wechat-website");this.startWechatWebsiteOpenPlatformLogin(s);return;case"wechat_miniprogram_code":if(!e?.miniProgramCode?.trim()||!i)throw new Error("startSocialLogin requires miniProgramCode and applicationCode for wechat-miniprogram");await this.loginWithWeChatCode(e.miniProgramCode.trim(),i);return;case"alipay_miniprogram_code":if(!e?.miniProgramCode?.trim()||!i)throw new Error("startSocialLogin requires miniProgramCode and applicationCode for alipay-miniprogram");await this.loginWithAlipayCode(e.miniProgramCode.trim(),i);return;case"douyin_miniprogram_code":throw new Error("startSocialLogin does not support douyin-miniprogram yet");default:throw new Error(`startSocialLogin unsupported provider: ${t}`)}}async currentUser(){if(this.storage){let r=await this.storage.get(b);if(r!=null)return r}let{data:t}=await this.getSession(),e=t?.user??null;return e&&this.storage&&await this.storage.set(b,e),e}async getCurrentJwt(){if(this.storage){let e=await this.storage.get(g);if(e!=null)return e;let r=await this.storage.get(v),{data:i}=await this.getToken(r??void 0);return i?.token?(await this.storage.set(g,i.token),i.token):null}let{data:t}=await this.getToken();return t?.token??null}async persistLogin(t,e){if(!this.storage)return;let r=e?.headers.get(ye)?.trim()||t.token||t.session?.token;r&&await this.storage.set(v,r),t.user&&await this.storage.set(b,t.user);let i=r??await this.storage.get(v),{data:s}=await this.getToken(i??void 0);s?.token&&await this.storage.set(g,s.token)}async clearLogin(){this.storage&&(await this.storage.remove(v),await this.storage.remove(b),await this.storage.remove(g))}getGoogleOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t}),i=e?.applicationCode?.trim()||this.defaultApplicationCode||"";i&&r.set("application_code",i);let s=e?.platformCode?.trim()??"";s&&r.set("platform_code",s);let a=W(this.integrationProviders,"google");return a&&r.set("oauth_credential_source",a),`${this.url("google/openplatform/login")}?${r.toString()}`}startGoogleOpenPlatformLogin(t,e){let r=this.getGoogleOpenPlatformLoginUrl(t,e);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=r;return}throw new Error("startGoogleOpenPlatformLogin requires a browser environment with location")}async completeGoogleOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeGoogleOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithGoogleExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithGoogleExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(g);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("google/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let s=i?JSON.parse(i):null;return!s?.token||!s.user?{error:{message:"invalid_google_login_response",status:502}}:(this.storage&&(await this.storage.set(g,s.token),await this.storage.set(v,s.token),await this.storage.set(b,s.user)),{data:s})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGoogleOpenPlatformIdentity(){try{let t={};if(this.storage){let s=await this.storage.get(g);s!=null&&(t.Authorization=`Bearer ${s}`)}let e=await this.fetchImpl(this.url("google/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_google_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getGithubOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t}),i=e?.applicationCode?.trim()||this.defaultApplicationCode||"";i&&r.set("application_code",i);let s=e?.platformCode?.trim()??"";s&&r.set("platform_code",s);let a=W(this.integrationProviders,"github");return a&&r.set("oauth_credential_source",a),`${this.url("github/openplatform/login")}?${r.toString()}`}startGithubOpenPlatformLogin(t,e){let r=this.getGithubOpenPlatformLoginUrl(t,e);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=r;return}throw new Error("startGithubOpenPlatformLogin requires a browser environment with location")}async completeGithubOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeGithubOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithGithubExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithGithubExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(g);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("github/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let s=i?JSON.parse(i):null;return!s?.token||!s.user?{error:{message:"invalid_github_login_response",status:502}}:(this.storage&&(await this.storage.set(g,s.token),await this.storage.set(v,s.token),await this.storage.set(b,s.user)),{data:s})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGithubOpenPlatformIdentity(){try{let t={};if(this.storage){let s=await this.storage.get(g);s!=null&&(t.Authorization=`Bearer ${s}`)}let e=await this.fetchImpl(this.url("github/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_github_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getWechatWebsiteOpenPlatformLoginUrl(t){let e=new URLSearchParams({return_url:t});return`${this.url("wechat-website/openplatform/login")}?${e.toString()}`}startWechatWebsiteOpenPlatformLogin(t){let e=this.getWechatWebsiteOpenPlatformLoginUrl(t);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=e;return}throw new Error("startWechatWebsiteOpenPlatformLogin requires a browser environment with location")}async completeWechatWebsiteOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeWechatWebsiteOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithWechatWebsiteExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithWechatWebsiteExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(g);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("wechat-website/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let s=i?JSON.parse(i):null;return!s?.token||!s.user?{error:{message:"invalid_wechat_website_login_response",status:502}}:(this.storage&&(await this.storage.set(g,s.token),await this.storage.set(v,s.token),await this.storage.set(b,s.user)),{data:s})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getWechatWebsiteOpenPlatformIdentity(){try{let t={};if(this.storage){let s=await this.storage.get(g);s!=null&&(t.Authorization=`Bearer ${s}`)}let e=await this.fetchImpl(this.url("wechat-website/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_wechat_website_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}url(t){let e=`${`${this.baseUrl.replace(/\/+$/,"")}/${this.authPath.replace(/^\/+/,"")}`}/${t.replace(/^\/+/,"")}`;return typeof console<"u"&&(console.warn("[NvwaAuth] request URL:",e),!e.startsWith("http://")&&!e.startsWith("https://")&&console.warn("[NvwaAuth] URL \u975E\u5B8C\u6574\u5730\u5740\uFF0C\u5C0F\u7A0B\u5E8F\u4F1A\u62A5 invalid url\uFF0C\u8BF7\u68C0\u67E5 Nvwa \u6784\u9020\u65F6\u4F20\u5165\u7684 baseUrl")),e}async getSession(){try{let t={};if(this.storage){let r=await this.storage.get(v)??await this.storage.get(g);r!=null&&(t.Authorization=`Bearer ${r}`)}let e=await this.fetchImpl(this.url("session"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}});return e.ok?{data:await e.json()}:{data:null,error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{data:null,error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signInWithEmail(t,e){try{let r=await this.fetchImpl(this.url("sign-in/email"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify({email:t,password:e})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let s=i?JSON.parse(i):void 0;return s&&await this.persistLogin({user:s.user,session:s.session},r),{data:s}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async signOut(){try{let t={"Content-Type":"application/json"};if(this.storage){let r=await this.storage.get(v)??await this.storage.get(g);r!=null&&(t.Authorization=`Bearer ${r}`)}let e=await this.fetchImpl(this.url("sign-out"),{method:"POST",credentials:this.credentials,headers:t,body:"{}"});return await this.clearLogin(),e.ok?{}:{error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signUp(t){let e=await this.postJson("sign-up/email",t);return e.data&&await this.persistLogin(e.data,e.response),e}async getToken(t){try{let e={};if(t)e.Authorization=`Bearer ${t}`;else if(this.storage){let a=await this.storage.get(v)??await this.storage.get(g);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("token"),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let s=i?JSON.parse(i):void 0;return{data:s?.token!=null?{token:s.token}:void 0}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async signInWithUsername(t,e){let r=await this.postJson("sign-in/username",{username:t,password:e});return r.data&&await this.persistLogin(r.data,r.response),r}async signInWithPhoneNumber(t,e,r){let i=await this.postJson("sign-in/phone-number",{phoneNumber:t,password:e,rememberMe:r});return i.data&&await this.persistLogin(i.data,i.response),i}async sendPhoneNumberOtp(t){let e=await this.postJson("phone-number/send-otp",{phoneNumber:t});return e.error?{error:e.error}:{}}async verifyPhoneNumber(t,e){let r=await this.postJson("phone-number/verify",{phoneNumber:t,code:e});return r.data&&await this.persistLogin(r.data,r.response),r}async loginWithWeChatCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let o=await this.storage.get(g);o!=null&&(r.Authorization=`Bearer ${o}`)}let i=await this.fetchImpl(this.url("wechat/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),s=await i.text();if(!i.ok)return{error:{message:s||i.statusText,status:i.status}};let a=s?JSON.parse(s):null;return!a?.token||!a.user?{error:{message:"invalid_wechat_login_response",status:502}}:(this.storage&&(await this.storage.set(g,a.token),await this.storage.set(v,a.token),await this.storage.set(b,a.user)),{data:a})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async loginWithAlipayCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let o=await this.storage.get(g);o!=null&&(r.Authorization=`Bearer ${o}`)}let i=await this.fetchImpl(this.url("alipay/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),s=await i.text();if(!i.ok)return{error:{message:s||i.statusText,status:i.status}};let a=s?JSON.parse(s):null;return!a?.token||!a.user?{error:{message:"invalid_alipay_login_response",status:502}}:(this.storage&&(await this.storage.set(g,a.token),await this.storage.set(v,a.token),await this.storage.set(b,a.user)),{data:a})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async getWeChatOpenPlatformIdentity(t){try{let e={};if(this.storage){let o=await this.storage.get(g);o!=null&&(e.Authorization=`Bearer ${o}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",i=await this.fetchImpl(this.url(`wechat/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),s=await i.text();if(!i.ok)return{error:{message:s||i.statusText,status:i.status}};let a=s?JSON.parse(s):null;return!a?.openid||!a.appId?{error:{message:"invalid_wechat_identity_response",status:502}}:{data:a}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getAlipayOpenPlatformIdentity(t){try{let e={};if(this.storage){let o=await this.storage.get(g);o!=null&&(e.Authorization=`Bearer ${o}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",i=await this.fetchImpl(this.url(`alipay/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),s=await i.text();if(!i.ok)return{error:{message:s||i.statusText,status:i.status}};let a=s?JSON.parse(s):null;return!a?.openid||!a.appId?{error:{message:"invalid_alipay_identity_response",status:502}}:{data:a}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async postJson(t,e){try{let r=await this.fetchImpl(this.url(t),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify(e)}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let s=i?JSON.parse(i):void 0;return{data:s?.data??s??void 0,response:r}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}},V=class{constructor(t,e,r){this.storage=t,this.customFetch=e,this.handleUnauthorized=r}async fetch(t,e){return await this.customFetch(t,e)}async fetchWithAuth(t,e){let r=await this.storage.get(g),i=new y(e?.headers);r&&i.set("Authorization",`Bearer ${r}`);let s=e?.method||"GET";if((s==="POST"||s==="PUT"||s==="PATCH")&&e?.body){let o=i.get("Content-Type");(!o||o.includes("text/plain"))&&i.set("Content-Type","application/json")}let a=await this.customFetch(t,{...e,headers:i});if(a.status===401)throw this.handleUnauthorized(),new Error("\u672A\u767B\u5F55");return a}},ve="/storage",be=ve+"/generateUploadUrl",Y=class{constructor(t,e){this.baseUrl=t,this.http=e}async uploadFile(t){let e=await this.http.fetch(this.baseUrl+be,{method:"POST",body:{fileName:t.name||t.fileName,fileSize:t.size||t.fileSize,fileType:t.type||t.fileType}}),{url:r}=await e.json();if(!r)throw new Error("\u83B7\u53D6\u4E0A\u4F20URL\u5931\u8D25");let i=await this.http.fetch(r,{method:"PUT",body:t,headers:new y({"Content-Type":t.type||t.fileType||"application/octet-stream"})}),{url:s}=await i.json();return{url:s.split("?")[0]}}},Ee=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},Pe=class{constructor(t){var e,r,i;this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=new y(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.urlLengthLimit=(i=t.urlLengthLimit)!==null&&i!==void 0?i:8e3,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=new y(this.headers),this.headers.set(t,e),this}then(t,e){var r=this;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 i=this.fetch,s=i(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async a=>{let o=null,n=null,c=null,h=a.status,l=a.statusText;if(a.ok){var u,d;if(r.method!=="HEAD"){var m;let w=await a.text();w===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&!((m=r.headers.get("Accept"))===null||m===void 0)&&m.includes("application/vnd.pgrst.plan+text")?n=w:n=JSON.parse(w))}let p=(u=r.headers.get("Prefer"))===null||u===void 0?void 0:u.match(/count=(exact|planned|estimated)/),f=(d=a.headers.get("content-range"))===null||d===void 0?void 0:d.split("/");p&&f&&f.length>1&&(c=parseInt(f[1])),r.isMaybeSingle&&Array.isArray(n)&&(n.length>1?(o={code:"PGRST116",details:`Results contain ${n.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},n=null,c=null,h=406,l="Not Acceptable"):n.length===1?n=n[0]:n=null)}else{let p=await a.text();try{o=JSON.parse(p),Array.isArray(o)&&a.status===404&&(n=[],o=null,h=200,l="OK")}catch{a.status===404&&p===""?(h=204,l="No Content"):o={message:p}}if(o&&r.shouldThrowOnError)throw new Ee(o)}return{error:o,data:n,count:c,status:h,statusText:l}});return this.shouldThrowOnError||(s=s.catch(a=>{var o;let n="",c="",h="",l=a?.cause;if(l){var u,d,m,p;let ne=(u=l?.message)!==null&&u!==void 0?u:"",j=(d=l?.code)!==null&&d!==void 0?d:"";n=`${(m=a?.name)!==null&&m!==void 0?m:"FetchError"}: ${a?.message}`,n+=`
|
|
1
|
+
"use strict";var A=Object.defineProperty;var oe=Object.getOwnPropertyDescriptor;var le=Object.getOwnPropertyNames;var he=Object.prototype.hasOwnProperty;var ce=(t,e)=>{for(var r in e)A(t,r,{get:e[r],enumerable:!0})},ue=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of le(e))!he.call(t,s)&&s!==r&&A(t,s,{get:()=>e[s],enumerable:!(i=oe(e,s))||i.enumerable});return t};var de=t=>ue(A({},"__esModule",{value:!0}),t);var Be={};ce(Be,{SocialLoginButtons:()=>Ge,default:()=>$,disableIframeHoverInspector:()=>Re,enableIframeHoverInspector:()=>Ue,getIframeSourceLocation:()=>je,localStorage:()=>R,setupIframeHoverInspector:()=>ke,setupIframeSourceLocationListener:()=>He,webFetch:()=>O});module.exports=de(Be);var y=class D{constructor(e){if(this.headerMap=new Map,e){if(e instanceof D)e.forEach((r,i)=>this.set(i,r));else if(Array.isArray(e))for(let[r,i]of e)this.set(r,String(i));else if(typeof e=="object")for(let r of Object.keys(e))this.set(r,String(e[r]))}}append(e,r){let i=e.toLowerCase(),s=this.headerMap.get(i);this.headerMap.set(i,s?`${s}, ${r}`:r)}set(e,r){this.headerMap.set(e.toLowerCase(),String(r))}get(e){return this.headerMap.get(e.toLowerCase())??null}has(e){return this.headerMap.has(e.toLowerCase())}delete(e){this.headerMap.delete(e.toLowerCase())}forEach(e){for(let[r,i]of this.headerMap.entries())e(i,r,this)}entries(){return this.headerMap.entries()}keys(){return this.headerMap.keys()}values(){return this.headerMap.values()}[Symbol.iterator](){return this.entries()}},pe=class G{constructor(e){if(this.params=new Map,e){if(typeof e=="string")this.parseString(e);else if(e instanceof G)this.params=new Map(e.params);else if(Array.isArray(e))for(let[r,i]of e)this.append(r,i);else if(e&&typeof e=="object")for(let[r,i]of Object.entries(e))this.set(r,i)}}parseString(e){e.startsWith("?")&&(e=e.slice(1));let r=e.split("&");for(let i of r)if(i){let[s,a]=i.split("=");s&&this.append(decodeURIComponent(s),a?decodeURIComponent(a):"")}}append(e,r){let i=this.params.get(e)||[];i.push(r),this.params.set(e,i)}delete(e){this.params.delete(e)}get(e){let r=this.params.get(e);return r?r[0]:null}getAll(e){return this.params.get(e)||[]}has(e){return this.params.has(e)}set(e,r){this.params.set(e,[r])}sort(){let e=Array.from(this.params.entries()).sort(([r],[i])=>r.localeCompare(i));this.params=new Map(e)}toString(){let e=[];for(let[r,i]of this.params.entries())for(let s of i)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(s)}`);return e.join("&")}forEach(e){for(let[r,i]of this.params.entries())for(let s of i)e(s,r,this)}keys(){return this.params.keys()}values(){let e=[];for(let r of this.params.values())e.push(...r);return e[Symbol.iterator]()}entries(){let e=[];for(let[r,i]of this.params.entries())for(let s of i)e.push([r,s]);return e[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}},N=class I{constructor(e,r){let i;if(e instanceof I)i=e.href;else if(r){let a=r instanceof I?r.href:r;i=this.resolve(a,e)}else i=e;let s=this.parseUrl(i);this.href=i,this.origin=`${s.protocol}//${s.host}`,this.protocol=s.protocol,this.username=s.username,this.password=s.password,this.host=s.host,this.hostname=s.hostname,this.port=s.port,this.pathname=s.pathname,this.search=s.search,this.searchParams=new pe(s.search),this.hash=s.hash}resolve(e,r){if(r.startsWith("http://")||r.startsWith("https://"))return r;if(r.startsWith("//"))return`${this.parseUrl(e).protocol}${r}`;if(r.startsWith("/")){let a=this.parseUrl(e);return`${a.protocol}//${a.host}${r}`}let i=this.parseUrl(e),s=i.pathname.endsWith("/")?i.pathname:i.pathname+"/";return`${i.protocol}//${i.host}${s}${r}`}parseUrl(e){let r=e.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!r)throw new TypeError("Invalid URL");let i=r[2]||"",s=r[4]||"",a=r[5]||"/",o=r[7]?`?${r[7]}`:"",n=r[9]?`#${r[9]}`:"";if(!i&&!s&&!a.startsWith("/")&&!a.includes("/")&&!a.includes("."))throw new TypeError("Invalid URL");let c=s.match(/^([^@]*)@(.+)$/),h="",l="",u=s;if(c){let f=c[1];u=c[2];let w=f.match(/^([^:]*):?(.*)$/);w&&(h=w[1]||"",l=w[2]||"")}let d=u.match(/^([^:]+):?(\d*)$/),m=d?d[1]:u,p=d&&d[2]?d[2]:"";return{protocol:i?`${i}:`:"",username:h,password:l,host:u,hostname:m,port:p,pathname:a,search:o,hash:n}}toString(){let e=this.searchParams.toString(),r=e?`?${e}`:"";return`${this.protocol}//${this.host}${this.pathname}${r}${this.hash}`}toJSON(){return this.toString()}};var B=class{constructor(t,e){this.bodyData=t,this.status=e?.status??200,this.statusText=e?.statusText??"",this.headers=me(e?.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 t=await this.text();return new TextEncoder().encode(t).buffer}};function me(t){return t?new y(t):new y}var ge=class{constructor(){this._aborted=!1,this.listeners=new Set,this.onabort=null}get aborted(){return this._aborted}_trigger(){if(!this._aborted){if(this._aborted=!0,typeof this.onabort=="function")try{this.onabort()}catch{}for(let t of Array.from(this.listeners))try{t()}catch{}this.listeners.clear()}}addEventListener(t,e){if(this._aborted){try{e()}catch{}return}this.listeners.add(e)}removeEventListener(t,e){this.listeners.delete(e)}toString(){return"[object AbortSignal]"}},fe=class{constructor(){this._signal=new ge}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}},z=class{constructor(t,e=""){this.http=t,this.baseUrl=e.replace(/\/$/,"")}async invoke(t,e){let r=this.baseUrl?`${this.baseUrl}/functions/${t}`:`/functions/${t}`;return await(await this.http.fetch(r,{method:e.method||"POST",body:e.body,headers:e.headers})).json()}},g="nvwa_current_jwt",v="nvwa_login_token",b="nvwa_user_profile",ye="set-auth-token",we=typeof fetch<"u"?(t,e)=>fetch(t,e):()=>{throw new Error("AuthClient requires fetch")},J={google:{id:"google",name:"Google Login",description:"Sign in with Google account."},github:{id:"github",name:"GitHub Login",description:"Sign in with GitHub account."},"wechat-website":{id:"wechat-website",name:"WeChat QR Login",description:"Sign in with WeChat website QR code."},"wechat-miniprogram":{id:"wechat-miniprogram",name:"WeChat Mini Program Login",description:"Sign in with WeChat mini program code."},"alipay-miniprogram":{id:"alipay-miniprogram",name:"Alipay Mini Program Login",description:"Sign in with Alipay mini program code."},"douyin-miniprogram":{id:"douyin-miniprogram",name:"Douyin Mini Program Login",description:"Sign in with Douyin mini program code."}};function H(t){let e=J[t]??{id:t,name:t,description:""},r="unsupported";switch(t){case"google":r="google_openplatform";break;case"github":r="github_openplatform";break;case"wechat-website":r="wechat_website_openplatform";break;case"wechat-miniprogram":r="wechat_miniprogram_code";break;case"alipay-miniprogram":r="alipay_miniprogram_code";break;case"douyin-miniprogram":r="douyin_miniprogram_code";break;default:break}return{id:e.id,type:e.id,name:e.name,description:e.description,loginKind:r}}function W(t,e){let r=t.socialLogin?.providers?.[e];return r?.enabled?r.oauthCredentialSource==="custom"?"custom":"nvwa_default":null}var K=class{constructor(t,e={}){this.baseUrl=t.replace(/\/$/,""),this.authPath=(e.authPath??"/auth").replace(/^\//,""),this.fetchImpl=e.fetchImpl??we,this.storage=e.storage??null,this.credentials=e.credentials??"omit",this.integrationProviders=e.integrationProviders??{},this.defaultApplicationCode=e.applicationCode?.trim()||null,typeof console<"u"&&(console.warn("[NvwaAuth] init baseUrl:",this.baseUrl||"(empty)"),(!this.baseUrl||!this.baseUrl.startsWith("http://")&&!this.baseUrl.startsWith("https://"))&&console.warn("[NvwaAuth] baseUrl \u5E94\u4E3A\u5B8C\u6574\u5730\u5740\uFF08\u5982 https://xxx.nvwa.app\uFF09\uFF0C\u5426\u5219\u5C0F\u7A0B\u5E8F request \u4F1A\u62A5 invalid url"))}async getSocialProviders(t){let e=this.integrationProviders.socialLogin?.providers??{};return Object.entries(e).filter(([,r])=>r.enabled).map(([r])=>{let i=J[r]??{id:r,name:r,description:""};return{...i,type:i.id}})}async getSocialProviderDescriptors(t){let e=this.integrationProviders.socialLogin?.providers??{};return Object.entries(e).filter(([,r])=>!!r?.enabled).map(([r])=>H(r))}async getAvailableProviders(t){return this.getSocialProviders(t)}async startSocialLogin(t,e){let r=H(t),i=e?.applicationCode?.trim()||this.defaultApplicationCode||void 0,s=e?.returnUrl??(typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:"");switch(r.loginKind){case"google_openplatform":if(!s)throw new Error("startSocialLogin requires returnUrl for google");this.startGoogleOpenPlatformLogin(s,{applicationCode:i,platformCode:e?.platformCode});return;case"github_openplatform":if(!s)throw new Error("startSocialLogin requires returnUrl for github");this.startGithubOpenPlatformLogin(s,{applicationCode:i,platformCode:e?.platformCode});return;case"wechat_website_openplatform":if(!s)throw new Error("startSocialLogin requires returnUrl for wechat-website");this.startWechatWebsiteOpenPlatformLogin(s);return;case"wechat_miniprogram_code":if(!e?.miniProgramCode?.trim()||!i)throw new Error("startSocialLogin requires miniProgramCode and applicationCode for wechat-miniprogram");await this.loginWithWeChatCode(e.miniProgramCode.trim(),i);return;case"alipay_miniprogram_code":if(!e?.miniProgramCode?.trim()||!i)throw new Error("startSocialLogin requires miniProgramCode and applicationCode for alipay-miniprogram");await this.loginWithAlipayCode(e.miniProgramCode.trim(),i);return;case"douyin_miniprogram_code":throw new Error("startSocialLogin does not support douyin-miniprogram yet");default:throw new Error(`startSocialLogin unsupported provider: ${t}`)}}async currentUser(){if(this.storage){let r=await this.storage.get(b);if(r!=null)return r}let{data:t}=await this.getSession(),e=t?.user??null;return e&&this.storage&&await this.storage.set(b,e),e}async getCurrentJwt(){if(this.storage){let e=await this.storage.get(g);if(e!=null)return e;let r=await this.storage.get(v),{data:i}=await this.getToken(r??void 0);return i?.token?(await this.storage.set(g,i.token),i.token):null}let{data:t}=await this.getToken();return t?.token??null}async persistLogin(t,e){if(!this.storage)return;let r=e?.headers.get(ye)?.trim()||t.token||t.session?.token;r&&await this.storage.set(v,r),t.user&&await this.storage.set(b,t.user);let i=r??await this.storage.get(v),{data:s}=await this.getToken(i??void 0);s?.token&&await this.storage.set(g,s.token)}async clearLogin(){this.storage&&(await this.storage.remove(v),await this.storage.remove(b),await this.storage.remove(g))}getGoogleOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t}),i=e?.applicationCode?.trim()||this.defaultApplicationCode||"";i&&r.set("application_code",i);let s=e?.platformCode?.trim()??"";s&&r.set("platform_code",s);let a=W(this.integrationProviders,"google");return a&&r.set("oauth_credential_source",a),`${this.url("google/openplatform/login")}?${r.toString()}`}startGoogleOpenPlatformLogin(t,e){let r=this.getGoogleOpenPlatformLoginUrl(t,e);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=r;return}throw new Error("startGoogleOpenPlatformLogin requires a browser environment with location")}async completeGoogleOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeGoogleOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithGoogleExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithGoogleExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(g);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("google/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let s=i?JSON.parse(i):null;return!s?.token||!s.user?{error:{message:"invalid_google_login_response",status:502}}:(this.storage&&(await this.storage.set(g,s.token),await this.storage.set(v,s.token),await this.storage.set(b,s.user)),{data:s})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGoogleOpenPlatformIdentity(){try{let t={};if(this.storage){let s=await this.storage.get(g);s!=null&&(t.Authorization=`Bearer ${s}`)}let e=await this.fetchImpl(this.url("google/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_google_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getGithubOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t}),i=e?.applicationCode?.trim()||this.defaultApplicationCode||"";i&&r.set("application_code",i);let s=e?.platformCode?.trim()??"";s&&r.set("platform_code",s);let a=W(this.integrationProviders,"github");return a&&r.set("oauth_credential_source",a),`${this.url("github/openplatform/login")}?${r.toString()}`}startGithubOpenPlatformLogin(t,e){let r=this.getGithubOpenPlatformLoginUrl(t,e);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=r;return}throw new Error("startGithubOpenPlatformLogin requires a browser environment with location")}async completeGithubOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeGithubOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithGithubExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithGithubExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(g);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("github/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let s=i?JSON.parse(i):null;return!s?.token||!s.user?{error:{message:"invalid_github_login_response",status:502}}:(this.storage&&(await this.storage.set(g,s.token),await this.storage.set(v,s.token),await this.storage.set(b,s.user)),{data:s})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGithubOpenPlatformIdentity(){try{let t={};if(this.storage){let s=await this.storage.get(g);s!=null&&(t.Authorization=`Bearer ${s}`)}let e=await this.fetchImpl(this.url("github/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_github_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getWechatWebsiteOpenPlatformLoginUrl(t){let e=new URLSearchParams({return_url:t});return`${this.url("wechat-website/openplatform/login")}?${e.toString()}`}startWechatWebsiteOpenPlatformLogin(t){let e=this.getWechatWebsiteOpenPlatformLoginUrl(t);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=e;return}throw new Error("startWechatWebsiteOpenPlatformLogin requires a browser environment with location")}async completeWechatWebsiteOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeWechatWebsiteOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithWechatWebsiteExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithWechatWebsiteExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(g);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("wechat-website/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let s=i?JSON.parse(i):null;return!s?.token||!s.user?{error:{message:"invalid_wechat_website_login_response",status:502}}:(this.storage&&(await this.storage.set(g,s.token),await this.storage.set(v,s.token),await this.storage.set(b,s.user)),{data:s})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getWechatWebsiteOpenPlatformIdentity(){try{let t={};if(this.storage){let s=await this.storage.get(g);s!=null&&(t.Authorization=`Bearer ${s}`)}let e=await this.fetchImpl(this.url("wechat-website/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_wechat_website_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}url(t){let e=`${`${this.baseUrl.replace(/\/+$/,"")}/${this.authPath.replace(/^\/+/,"")}`}/${t.replace(/^\/+/,"")}`;return typeof console<"u"&&(console.warn("[NvwaAuth] request URL:",e),!e.startsWith("http://")&&!e.startsWith("https://")&&console.warn("[NvwaAuth] URL \u975E\u5B8C\u6574\u5730\u5740\uFF0C\u5C0F\u7A0B\u5E8F\u4F1A\u62A5 invalid url\uFF0C\u8BF7\u68C0\u67E5 Nvwa \u6784\u9020\u65F6\u4F20\u5165\u7684 baseUrl")),e}async getSession(){try{let t={};if(this.storage){let r=await this.storage.get(v)??await this.storage.get(g);r!=null&&(t.Authorization=`Bearer ${r}`)}let e=await this.fetchImpl(this.url("session"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}});return e.ok?{data:await e.json()}:{data:null,error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{data:null,error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signInWithEmail(t,e){try{let r=await this.fetchImpl(this.url("sign-in/email"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify({email:t,password:e})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let s=i?JSON.parse(i):void 0;return s&&await this.persistLogin({user:s.user,session:s.session},r),{data:s}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async signOut(){try{let t={"Content-Type":"application/json"};if(this.storage){let r=await this.storage.get(v)??await this.storage.get(g);r!=null&&(t.Authorization=`Bearer ${r}`)}await this.clearLogin();let e=await this.fetchImpl(this.url("sign-out"),{method:"POST",credentials:this.credentials,headers:t,body:"{}"});return e.ok?{}:{error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signUp(t){let e=await this.postJson("sign-up/email",t);return e.data&&await this.persistLogin(e.data,e.response),e}async getToken(t){try{let e={};if(t)e.Authorization=`Bearer ${t}`;else if(this.storage){let a=await this.storage.get(v)??await this.storage.get(g);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("token"),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let s=i?JSON.parse(i):void 0;return{data:s?.token!=null?{token:s.token}:void 0}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async signInWithUsername(t,e){let r=await this.postJson("sign-in/username",{username:t,password:e});return r.data&&await this.persistLogin(r.data,r.response),r}async signInWithPhoneNumber(t,e,r){let i=await this.postJson("sign-in/phone-number",{phoneNumber:t,password:e,rememberMe:r});return i.data&&await this.persistLogin(i.data,i.response),i}async sendPhoneNumberOtp(t){let e=await this.postJson("phone-number/send-otp",{phoneNumber:t});return e.error?{error:e.error}:{}}async verifyPhoneNumber(t,e){let r=await this.postJson("phone-number/verify",{phoneNumber:t,code:e});return r.data&&await this.persistLogin(r.data,r.response),r}async loginWithWeChatCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let o=await this.storage.get(g);o!=null&&(r.Authorization=`Bearer ${o}`)}let i=await this.fetchImpl(this.url("wechat/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),s=await i.text();if(!i.ok)return{error:{message:s||i.statusText,status:i.status}};let a=s?JSON.parse(s):null;return!a?.token||!a.user?{error:{message:"invalid_wechat_login_response",status:502}}:(this.storage&&(await this.storage.set(g,a.token),await this.storage.set(v,a.token),await this.storage.set(b,a.user)),{data:a})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async loginWithAlipayCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let o=await this.storage.get(g);o!=null&&(r.Authorization=`Bearer ${o}`)}let i=await this.fetchImpl(this.url("alipay/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),s=await i.text();if(!i.ok)return{error:{message:s||i.statusText,status:i.status}};let a=s?JSON.parse(s):null;return!a?.token||!a.user?{error:{message:"invalid_alipay_login_response",status:502}}:(this.storage&&(await this.storage.set(g,a.token),await this.storage.set(v,a.token),await this.storage.set(b,a.user)),{data:a})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async getWeChatOpenPlatformIdentity(t){try{let e={};if(this.storage){let o=await this.storage.get(g);o!=null&&(e.Authorization=`Bearer ${o}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",i=await this.fetchImpl(this.url(`wechat/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),s=await i.text();if(!i.ok)return{error:{message:s||i.statusText,status:i.status}};let a=s?JSON.parse(s):null;return!a?.openid||!a.appId?{error:{message:"invalid_wechat_identity_response",status:502}}:{data:a}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getAlipayOpenPlatformIdentity(t){try{let e={};if(this.storage){let o=await this.storage.get(g);o!=null&&(e.Authorization=`Bearer ${o}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",i=await this.fetchImpl(this.url(`alipay/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),s=await i.text();if(!i.ok)return{error:{message:s||i.statusText,status:i.status}};let a=s?JSON.parse(s):null;return!a?.openid||!a.appId?{error:{message:"invalid_alipay_identity_response",status:502}}:{data:a}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async postJson(t,e){try{let r=await this.fetchImpl(this.url(t),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify(e)}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let s=i?JSON.parse(i):void 0;return{data:s?.data??s??void 0,response:r}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}},V=class{constructor(t,e,r){this.storage=t,this.customFetch=e,this.handleUnauthorized=r}async fetch(t,e){return await this.customFetch(t,e)}async fetchWithAuth(t,e){let r=await this.storage.get(g),i=new y(e?.headers);r&&i.set("Authorization",`Bearer ${r}`);let s=e?.method||"GET";if((s==="POST"||s==="PUT"||s==="PATCH")&&e?.body){let o=i.get("Content-Type");(!o||o.includes("text/plain"))&&i.set("Content-Type","application/json")}let a=await this.customFetch(t,{...e,headers:i});if(a.status===401)throw this.handleUnauthorized(),new Error("\u672A\u767B\u5F55");return a}},ve="/storage",be=ve+"/generateUploadUrl",Y=class{constructor(t,e){this.baseUrl=t,this.http=e}async uploadFile(t){let e=await this.http.fetch(this.baseUrl+be,{method:"POST",body:{fileName:t.name||t.fileName,fileSize:t.size||t.fileSize,fileType:t.type||t.fileType}}),{url:r}=await e.json();if(!r)throw new Error("\u83B7\u53D6\u4E0A\u4F20URL\u5931\u8D25");let i=await this.http.fetch(r,{method:"PUT",body:t,headers:new y({"Content-Type":t.type||t.fileType||"application/octet-stream"})}),{url:s}=await i.json();return{url:s.split("?")[0]}}},Ee=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},Pe=class{constructor(t){var e,r,i;this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=new y(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.urlLengthLimit=(i=t.urlLengthLimit)!==null&&i!==void 0?i:8e3,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=new y(this.headers),this.headers.set(t,e),this}then(t,e){var r=this;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 i=this.fetch,s=i(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async a=>{let o=null,n=null,c=null,h=a.status,l=a.statusText;if(a.ok){var u,d;if(r.method!=="HEAD"){var m;let w=await a.text();w===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&!((m=r.headers.get("Accept"))===null||m===void 0)&&m.includes("application/vnd.pgrst.plan+text")?n=w:n=JSON.parse(w))}let p=(u=r.headers.get("Prefer"))===null||u===void 0?void 0:u.match(/count=(exact|planned|estimated)/),f=(d=a.headers.get("content-range"))===null||d===void 0?void 0:d.split("/");p&&f&&f.length>1&&(c=parseInt(f[1])),r.isMaybeSingle&&Array.isArray(n)&&(n.length>1?(o={code:"PGRST116",details:`Results contain ${n.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},n=null,c=null,h=406,l="Not Acceptable"):n.length===1?n=n[0]:n=null)}else{let p=await a.text();try{o=JSON.parse(p),Array.isArray(o)&&a.status===404&&(n=[],o=null,h=200,l="OK")}catch{a.status===404&&p===""?(h=204,l="No Content"):o={message:p}}if(o&&r.shouldThrowOnError)throw new Ee(o)}return{error:o,data:n,count:c,status:h,statusText:l}});return this.shouldThrowOnError||(s=s.catch(a=>{var o;let n="",c="",h="",l=a?.cause;if(l){var u,d,m,p;let ne=(u=l?.message)!==null&&u!==void 0?u:"",j=(d=l?.code)!==null&&d!==void 0?d:"";n=`${(m=a?.name)!==null&&m!==void 0?m:"FetchError"}: ${a?.message}`,n+=`
|
|
2
2
|
|
|
3
3
|
Caused by: ${(p=l?.name)!==null&&p!==void 0?p:"Error"}: ${ne}`,j&&(n+=` (${j})`),l?.stack&&(n+=`
|
|
4
4
|
${l.stack}`)}else{var f;n=(f=a?.stack)!==null&&f!==void 0?f:""}let w=this.url.toString().length;return a?.name==="AbortError"||a?.code==="ABORT_ERR"?(h="",c="Request was aborted (timeout or manual cancellation)",w>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${w} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):(l?.name==="HeadersOverflowError"||l?.code==="UND_ERR_HEADERS_OVERFLOW")&&(h="",c="HTTP headers exceeded server limits (typically 16KB)",w>this.urlLengthLimit&&(c+=`. Your request URL is ${w} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{error:{message:`${(o=a?.name)!==null&&o!==void 0?o:"FetchError"}: ${a?.message}`,details:n,hint:c,code:h},data:null,count:null,status:0,statusText:""}})),s.then(t,e)}returns(){return this}overrideTypes(){return this}},Se=class extends Pe{select(t){let e=!1,r=(t??"*").split("").map(i=>/\s/.test(i)&&!e?"":(i==='"'&&(e=!e),i)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:i,referencedTable:s=i}={}){let a=s?`${s}.order`:"order",o=this.url.searchParams.get(a);return this.url.searchParams.set(a,`${o?`${o},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){let i=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:i=r}={}){let s=typeof i>"u"?"offset":`${i}.offset`,a=typeof i>"u"?"limit":`${i}.limit`;return this.url.searchParams.set(s,`${t}`),this.url.searchParams.set(a,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return 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:t=!1,verbose:e=!1,settings:r=!1,buffers:i=!1,wal:s=!1,format:a="text"}={}){var o;let n=[t?"analyze":null,e?"verbose":null,r?"settings":null,i?"buffers":null,s?"wal":null].filter(Boolean).join("|"),c=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${a}; for="${c}"; options=${n};`),a==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}},M=new RegExp("[,()]"),P=class extends Se{eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){let r=Array.from(new Set(e)).map(i=>typeof i=="string"&&M.test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(i=>typeof i=="string"&&M.test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:i}={}){let s="";i==="plain"?s="pl":i==="phrase"?s="ph":i==="websearch"&&(s="w");let a=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${s}fts${a}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){let i=r?`${r}.or`:"or";return this.url.searchParams.append(i,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},Le=class{constructor(t,{headers:e={},schema:r,fetch:i,urlLengthLimit:s=8e3}){this.url=t,this.headers=new y(e),this.schema=r,this.fetch=i,this.urlLengthLimit=s}cloneRequestState(){return{url:new N(this.url.toString()),headers:new y(this.headers)}}select(t,e){let{head:r=!1,count:i}=e??{},s=r?"HEAD":"GET",a=!1,o=(t??"*").split("").map(h=>/\s/.test(h)&&!a?"":(h==='"'&&(a=!a),h)).join(""),{url:n,headers:c}=this.cloneRequestState();return n.searchParams.set("select",o),i&&c.append("Prefer",`count=${i}`),new P({method:s,url:n,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var i;let s="POST",{url:a,headers:o}=this.cloneRequestState();if(e&&o.append("Prefer",`count=${e}`),r||o.append("Prefer","missing=default"),Array.isArray(t)){let n=t.reduce((c,h)=>c.concat(Object.keys(h)),[]);if(n.length>0){let c=[...new Set(n)].map(h=>`"${h}"`);a.searchParams.set("columns",c.join(","))}}return new P({method:s,url:a,headers:o,schema:this.schema,body:t,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:i,defaultToNull:s=!0}={}){var a;let o="POST",{url:n,headers:c}=this.cloneRequestState();if(c.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&n.searchParams.set("on_conflict",e),i&&c.append("Prefer",`count=${i}`),s||c.append("Prefer","missing=default"),Array.isArray(t)){let h=t.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(h.length>0){let l=[...new Set(h)].map(u=>`"${u}"`);n.searchParams.set("columns",l.join(","))}}return new P({method:o,url:n,headers:c,schema:this.schema,body:t,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;let i="PATCH",{url:s,headers:a}=this.cloneRequestState();return e&&a.append("Prefer",`count=${e}`),new P({method:i,url:s,headers:a,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:t}={}){var e;let r="DELETE",{url:i,headers:s}=this.cloneRequestState();return t&&s.append("Prefer",`count=${t}`),new P({method:r,url:i,headers:s,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function L(t){"@babel/helpers - typeof";return L=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},L(t)}function Oe(t,e){if(L(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var i=r.call(t,e||"default");if(L(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Ce(t){var e=Oe(t,"string");return L(e)=="symbol"?e:e+""}function Te(t,e,r){return(e=Ce(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function F(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);e&&(i=i.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),r.push.apply(r,i)}return r}function C(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?F(Object(r),!0).forEach(function(i){Te(t,i,r[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):F(Object(r)).forEach(function(i){Object.defineProperty(t,i,Object.getOwnPropertyDescriptor(r,i))})}return t}var _e=class Q{constructor(e,{headers:r={},schema:i,fetch:s,timeout:a,urlLengthLimit:o=8e3}={}){this.url=e,this.headers=new y(r),this.schemaName=i,this.urlLengthLimit=o;let n=s??globalThis.fetch;a!==void 0&&a>0?this.fetch=(c,h)=>{let l=new fe,u=setTimeout(()=>l.abort(),a),d=h?.signal;if(d){if(d.aborted)return clearTimeout(u),n(c,h);let m=()=>{clearTimeout(u),l.abort()};return d.addEventListener("abort",m,{once:!0}),n(c,C(C({},h),{},{signal:l.signal})).finally(()=>{clearTimeout(u),d.removeEventListener("abort",m)})}return n(c,C(C({},h),{},{signal:l.signal})).finally(()=>clearTimeout(u))}:this.fetch=n}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new Le(new N(`${this.url}/${e}`),{headers:new y(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new Q(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:i=!1,get:s=!1,count:a}={}){var o;let n,c=new N(`${this.url}/rpc/${e}`),h,l=m=>m!==null&&typeof m=="object"&&(!Array.isArray(m)||m.some(l)),u=i&&Object.values(r).some(l);u?(n="POST",h=r):i||s?(n=i?"HEAD":"GET",Object.entries(r).filter(([m,p])=>p!==void 0).map(([m,p])=>[m,Array.isArray(p)?`{${p.join(",")}}`:`${p}`]).forEach(([m,p])=>{c.searchParams.append(m,p)})):(n="POST",h=r);let d=new y(this.headers);return u?d.set("Prefer",a?`count=${a},return=minimal`:"return=minimal"):a&&d.set("Prefer",`count=${a}`),new P({method:n,url:c,headers:d,schema:this.schemaName,body:h,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit})}},$e="/entities",X=(t,e)=>new _e(t+$e,{fetch:e.fetchWithAuth.bind(e)}),Z=class{constructor(){this.hoverOverlay=null,this.selectedOverlay=null,this.tooltip=null,this.hoverElement=null,this.selectedElement=null,this.hoverUpdateHandler=null,this.selectedUpdateHandler=null,this.createStyles()}createStyles(){if(document.getElementById("__nvwa-inspector-overlay-style"))return;let t=document.createElement("style");t.id="__nvwa-inspector-overlay-style",t.textContent=`
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var y=class M{constructor(e){if(this.headerMap=new Map,e){if(e instanceof M)e.forEach((r,i)=>this.set(i,r));else if(Array.isArray(e))for(let[r,i]of e)this.set(r,String(i));else if(typeof e=="object")for(let r of Object.keys(e))this.set(r,String(e[r]))}}append(e,r){let i=e.toLowerCase(),s=this.headerMap.get(i);this.headerMap.set(i,s?`${s}, ${r}`:r)}set(e,r){this.headerMap.set(e.toLowerCase(),String(r))}get(e){return this.headerMap.get(e.toLowerCase())??null}has(e){return this.headerMap.has(e.toLowerCase())}delete(e){this.headerMap.delete(e.toLowerCase())}forEach(e){for(let[r,i]of this.headerMap.entries())e(i,r,this)}entries(){return this.headerMap.entries()}keys(){return this.headerMap.keys()}values(){return this.headerMap.values()}[Symbol.iterator](){return this.entries()}},le=class F{constructor(e){if(this.params=new Map,e){if(typeof e=="string")this.parseString(e);else if(e instanceof F)this.params=new Map(e.params);else if(Array.isArray(e))for(let[r,i]of e)this.append(r,i);else if(e&&typeof e=="object")for(let[r,i]of Object.entries(e))this.set(r,i)}}parseString(e){e.startsWith("?")&&(e=e.slice(1));let r=e.split("&");for(let i of r)if(i){let[s,a]=i.split("=");s&&this.append(decodeURIComponent(s),a?decodeURIComponent(a):"")}}append(e,r){let i=this.params.get(e)||[];i.push(r),this.params.set(e,i)}delete(e){this.params.delete(e)}get(e){let r=this.params.get(e);return r?r[0]:null}getAll(e){return this.params.get(e)||[]}has(e){return this.params.has(e)}set(e,r){this.params.set(e,[r])}sort(){let e=Array.from(this.params.entries()).sort(([r],[i])=>r.localeCompare(i));this.params=new Map(e)}toString(){let e=[];for(let[r,i]of this.params.entries())for(let s of i)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(s)}`);return e.join("&")}forEach(e){for(let[r,i]of this.params.entries())for(let s of i)e(s,r,this)}keys(){return this.params.keys()}values(){let e=[];for(let r of this.params.values())e.push(...r);return e[Symbol.iterator]()}entries(){let e=[];for(let[r,i]of this.params.entries())for(let s of i)e.push([r,s]);return e[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}},$=class A{constructor(e,r){let i;if(e instanceof A)i=e.href;else if(r){let a=r instanceof A?r.href:r;i=this.resolve(a,e)}else i=e;let s=this.parseUrl(i);this.href=i,this.origin=`${s.protocol}//${s.host}`,this.protocol=s.protocol,this.username=s.username,this.password=s.password,this.host=s.host,this.hostname=s.hostname,this.port=s.port,this.pathname=s.pathname,this.search=s.search,this.searchParams=new le(s.search),this.hash=s.hash}resolve(e,r){if(r.startsWith("http://")||r.startsWith("https://"))return r;if(r.startsWith("//"))return`${this.parseUrl(e).protocol}${r}`;if(r.startsWith("/")){let a=this.parseUrl(e);return`${a.protocol}//${a.host}${r}`}let i=this.parseUrl(e),s=i.pathname.endsWith("/")?i.pathname:i.pathname+"/";return`${i.protocol}//${i.host}${s}${r}`}parseUrl(e){let r=e.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!r)throw new TypeError("Invalid URL");let i=r[2]||"",s=r[4]||"",a=r[5]||"/",o=r[7]?`?${r[7]}`:"",n=r[9]?`#${r[9]}`:"";if(!i&&!s&&!a.startsWith("/")&&!a.includes("/")&&!a.includes("."))throw new TypeError("Invalid URL");let c=s.match(/^([^@]*)@(.+)$/),h="",l="",u=s;if(c){let f=c[1];u=c[2];let w=f.match(/^([^:]*):?(.*)$/);w&&(h=w[1]||"",l=w[2]||"")}let d=u.match(/^([^:]+):?(\d*)$/),m=d?d[1]:u,p=d&&d[2]?d[2]:"";return{protocol:i?`${i}:`:"",username:h,password:l,host:u,hostname:m,port:p,pathname:a,search:o,hash:n}}toString(){let e=this.searchParams.toString(),r=e?`?${e}`:"";return`${this.protocol}//${this.host}${this.pathname}${r}${this.hash}`}toJSON(){return this.toString()}};var q=class{constructor(t,e){this.bodyData=t,this.status=e?.status??200,this.statusText=e?.statusText??"",this.headers=he(e?.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 t=await this.text();return new TextEncoder().encode(t).buffer}};function he(t){return t?new y(t):new y}var ce=class{constructor(){this._aborted=!1,this.listeners=new Set,this.onabort=null}get aborted(){return this._aborted}_trigger(){if(!this._aborted){if(this._aborted=!0,typeof this.onabort=="function")try{this.onabort()}catch{}for(let t of Array.from(this.listeners))try{t()}catch{}this.listeners.clear()}}addEventListener(t,e){if(this._aborted){try{e()}catch{}return}this.listeners.add(e)}removeEventListener(t,e){this.listeners.delete(e)}toString(){return"[object AbortSignal]"}},ue=class{constructor(){this._signal=new ce}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}},D=class{constructor(t,e=""){this.http=t,this.baseUrl=e.replace(/\/$/,"")}async invoke(t,e){let r=this.baseUrl?`${this.baseUrl}/functions/${t}`:`/functions/${t}`;return await(await this.http.fetch(r,{method:e.method||"POST",body:e.body,headers:e.headers})).json()}},g="nvwa_current_jwt",v="nvwa_login_token",b="nvwa_user_profile",de="set-auth-token",pe=typeof fetch<"u"?(t,e)=>fetch(t,e):()=>{throw new Error("AuthClient requires fetch")},G={google:{id:"google",name:"Google Login",description:"Sign in with Google account."},github:{id:"github",name:"GitHub Login",description:"Sign in with GitHub account."},"wechat-website":{id:"wechat-website",name:"WeChat QR Login",description:"Sign in with WeChat website QR code."},"wechat-miniprogram":{id:"wechat-miniprogram",name:"WeChat Mini Program Login",description:"Sign in with WeChat mini program code."},"alipay-miniprogram":{id:"alipay-miniprogram",name:"Alipay Mini Program Login",description:"Sign in with Alipay mini program code."},"douyin-miniprogram":{id:"douyin-miniprogram",name:"Douyin Mini Program Login",description:"Sign in with Douyin mini program code."}};function U(t){let e=G[t]??{id:t,name:t,description:""},r="unsupported";switch(t){case"google":r="google_openplatform";break;case"github":r="github_openplatform";break;case"wechat-website":r="wechat_website_openplatform";break;case"wechat-miniprogram":r="wechat_miniprogram_code";break;case"alipay-miniprogram":r="alipay_miniprogram_code";break;case"douyin-miniprogram":r="douyin_miniprogram_code";break;default:break}return{id:e.id,type:e.id,name:e.name,description:e.description,loginKind:r}}function R(t,e){let r=t.socialLogin?.providers?.[e];return r?.enabled?r.oauthCredentialSource==="custom"?"custom":"nvwa_default":null}var B=class{constructor(t,e={}){this.baseUrl=t.replace(/\/$/,""),this.authPath=(e.authPath??"/auth").replace(/^\//,""),this.fetchImpl=e.fetchImpl??pe,this.storage=e.storage??null,this.credentials=e.credentials??"omit",this.integrationProviders=e.integrationProviders??{},this.defaultApplicationCode=e.applicationCode?.trim()||null,typeof console<"u"&&(console.warn("[NvwaAuth] init baseUrl:",this.baseUrl||"(empty)"),(!this.baseUrl||!this.baseUrl.startsWith("http://")&&!this.baseUrl.startsWith("https://"))&&console.warn("[NvwaAuth] baseUrl \u5E94\u4E3A\u5B8C\u6574\u5730\u5740\uFF08\u5982 https://xxx.nvwa.app\uFF09\uFF0C\u5426\u5219\u5C0F\u7A0B\u5E8F request \u4F1A\u62A5 invalid url"))}async getSocialProviders(t){let e=this.integrationProviders.socialLogin?.providers??{};return Object.entries(e).filter(([,r])=>r.enabled).map(([r])=>{let i=G[r]??{id:r,name:r,description:""};return{...i,type:i.id}})}async getSocialProviderDescriptors(t){let e=this.integrationProviders.socialLogin?.providers??{};return Object.entries(e).filter(([,r])=>!!r?.enabled).map(([r])=>U(r))}async getAvailableProviders(t){return this.getSocialProviders(t)}async startSocialLogin(t,e){let r=U(t),i=e?.applicationCode?.trim()||this.defaultApplicationCode||void 0,s=e?.returnUrl??(typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:"");switch(r.loginKind){case"google_openplatform":if(!s)throw new Error("startSocialLogin requires returnUrl for google");this.startGoogleOpenPlatformLogin(s,{applicationCode:i,platformCode:e?.platformCode});return;case"github_openplatform":if(!s)throw new Error("startSocialLogin requires returnUrl for github");this.startGithubOpenPlatformLogin(s,{applicationCode:i,platformCode:e?.platformCode});return;case"wechat_website_openplatform":if(!s)throw new Error("startSocialLogin requires returnUrl for wechat-website");this.startWechatWebsiteOpenPlatformLogin(s);return;case"wechat_miniprogram_code":if(!e?.miniProgramCode?.trim()||!i)throw new Error("startSocialLogin requires miniProgramCode and applicationCode for wechat-miniprogram");await this.loginWithWeChatCode(e.miniProgramCode.trim(),i);return;case"alipay_miniprogram_code":if(!e?.miniProgramCode?.trim()||!i)throw new Error("startSocialLogin requires miniProgramCode and applicationCode for alipay-miniprogram");await this.loginWithAlipayCode(e.miniProgramCode.trim(),i);return;case"douyin_miniprogram_code":throw new Error("startSocialLogin does not support douyin-miniprogram yet");default:throw new Error(`startSocialLogin unsupported provider: ${t}`)}}async currentUser(){if(this.storage){let r=await this.storage.get(b);if(r!=null)return r}let{data:t}=await this.getSession(),e=t?.user??null;return e&&this.storage&&await this.storage.set(b,e),e}async getCurrentJwt(){if(this.storage){let e=await this.storage.get(g);if(e!=null)return e;let r=await this.storage.get(v),{data:i}=await this.getToken(r??void 0);return i?.token?(await this.storage.set(g,i.token),i.token):null}let{data:t}=await this.getToken();return t?.token??null}async persistLogin(t,e){if(!this.storage)return;let r=e?.headers.get(de)?.trim()||t.token||t.session?.token;r&&await this.storage.set(v,r),t.user&&await this.storage.set(b,t.user);let i=r??await this.storage.get(v),{data:s}=await this.getToken(i??void 0);s?.token&&await this.storage.set(g,s.token)}async clearLogin(){this.storage&&(await this.storage.remove(v),await this.storage.remove(b),await this.storage.remove(g))}getGoogleOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t}),i=e?.applicationCode?.trim()||this.defaultApplicationCode||"";i&&r.set("application_code",i);let s=e?.platformCode?.trim()??"";s&&r.set("platform_code",s);let a=R(this.integrationProviders,"google");return a&&r.set("oauth_credential_source",a),`${this.url("google/openplatform/login")}?${r.toString()}`}startGoogleOpenPlatformLogin(t,e){let r=this.getGoogleOpenPlatformLoginUrl(t,e);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=r;return}throw new Error("startGoogleOpenPlatformLogin requires a browser environment with location")}async completeGoogleOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeGoogleOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithGoogleExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithGoogleExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(g);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("google/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let s=i?JSON.parse(i):null;return!s?.token||!s.user?{error:{message:"invalid_google_login_response",status:502}}:(this.storage&&(await this.storage.set(g,s.token),await this.storage.set(v,s.token),await this.storage.set(b,s.user)),{data:s})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGoogleOpenPlatformIdentity(){try{let t={};if(this.storage){let s=await this.storage.get(g);s!=null&&(t.Authorization=`Bearer ${s}`)}let e=await this.fetchImpl(this.url("google/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_google_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getGithubOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t}),i=e?.applicationCode?.trim()||this.defaultApplicationCode||"";i&&r.set("application_code",i);let s=e?.platformCode?.trim()??"";s&&r.set("platform_code",s);let a=R(this.integrationProviders,"github");return a&&r.set("oauth_credential_source",a),`${this.url("github/openplatform/login")}?${r.toString()}`}startGithubOpenPlatformLogin(t,e){let r=this.getGithubOpenPlatformLoginUrl(t,e);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=r;return}throw new Error("startGithubOpenPlatformLogin requires a browser environment with location")}async completeGithubOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeGithubOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithGithubExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithGithubExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(g);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("github/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let s=i?JSON.parse(i):null;return!s?.token||!s.user?{error:{message:"invalid_github_login_response",status:502}}:(this.storage&&(await this.storage.set(g,s.token),await this.storage.set(v,s.token),await this.storage.set(b,s.user)),{data:s})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGithubOpenPlatformIdentity(){try{let t={};if(this.storage){let s=await this.storage.get(g);s!=null&&(t.Authorization=`Bearer ${s}`)}let e=await this.fetchImpl(this.url("github/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_github_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getWechatWebsiteOpenPlatformLoginUrl(t){let e=new URLSearchParams({return_url:t});return`${this.url("wechat-website/openplatform/login")}?${e.toString()}`}startWechatWebsiteOpenPlatformLogin(t){let e=this.getWechatWebsiteOpenPlatformLoginUrl(t);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=e;return}throw new Error("startWechatWebsiteOpenPlatformLogin requires a browser environment with location")}async completeWechatWebsiteOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeWechatWebsiteOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithWechatWebsiteExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithWechatWebsiteExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(g);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("wechat-website/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let s=i?JSON.parse(i):null;return!s?.token||!s.user?{error:{message:"invalid_wechat_website_login_response",status:502}}:(this.storage&&(await this.storage.set(g,s.token),await this.storage.set(v,s.token),await this.storage.set(b,s.user)),{data:s})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getWechatWebsiteOpenPlatformIdentity(){try{let t={};if(this.storage){let s=await this.storage.get(g);s!=null&&(t.Authorization=`Bearer ${s}`)}let e=await this.fetchImpl(this.url("wechat-website/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_wechat_website_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}url(t){let e=`${`${this.baseUrl.replace(/\/+$/,"")}/${this.authPath.replace(/^\/+/,"")}`}/${t.replace(/^\/+/,"")}`;return typeof console<"u"&&(console.warn("[NvwaAuth] request URL:",e),!e.startsWith("http://")&&!e.startsWith("https://")&&console.warn("[NvwaAuth] URL \u975E\u5B8C\u6574\u5730\u5740\uFF0C\u5C0F\u7A0B\u5E8F\u4F1A\u62A5 invalid url\uFF0C\u8BF7\u68C0\u67E5 Nvwa \u6784\u9020\u65F6\u4F20\u5165\u7684 baseUrl")),e}async getSession(){try{let t={};if(this.storage){let r=await this.storage.get(v)??await this.storage.get(g);r!=null&&(t.Authorization=`Bearer ${r}`)}let e=await this.fetchImpl(this.url("session"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}});return e.ok?{data:await e.json()}:{data:null,error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{data:null,error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signInWithEmail(t,e){try{let r=await this.fetchImpl(this.url("sign-in/email"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify({email:t,password:e})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let s=i?JSON.parse(i):void 0;return s&&await this.persistLogin({user:s.user,session:s.session},r),{data:s}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async signOut(){try{let t={"Content-Type":"application/json"};if(this.storage){let r=await this.storage.get(v)??await this.storage.get(g);r!=null&&(t.Authorization=`Bearer ${r}`)}let e=await this.fetchImpl(this.url("sign-out"),{method:"POST",credentials:this.credentials,headers:t,body:"{}"});return await this.clearLogin(),e.ok?{}:{error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signUp(t){let e=await this.postJson("sign-up/email",t);return e.data&&await this.persistLogin(e.data,e.response),e}async getToken(t){try{let e={};if(t)e.Authorization=`Bearer ${t}`;else if(this.storage){let a=await this.storage.get(v)??await this.storage.get(g);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("token"),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let s=i?JSON.parse(i):void 0;return{data:s?.token!=null?{token:s.token}:void 0}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async signInWithUsername(t,e){let r=await this.postJson("sign-in/username",{username:t,password:e});return r.data&&await this.persistLogin(r.data,r.response),r}async signInWithPhoneNumber(t,e,r){let i=await this.postJson("sign-in/phone-number",{phoneNumber:t,password:e,rememberMe:r});return i.data&&await this.persistLogin(i.data,i.response),i}async sendPhoneNumberOtp(t){let e=await this.postJson("phone-number/send-otp",{phoneNumber:t});return e.error?{error:e.error}:{}}async verifyPhoneNumber(t,e){let r=await this.postJson("phone-number/verify",{phoneNumber:t,code:e});return r.data&&await this.persistLogin(r.data,r.response),r}async loginWithWeChatCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let o=await this.storage.get(g);o!=null&&(r.Authorization=`Bearer ${o}`)}let i=await this.fetchImpl(this.url("wechat/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),s=await i.text();if(!i.ok)return{error:{message:s||i.statusText,status:i.status}};let a=s?JSON.parse(s):null;return!a?.token||!a.user?{error:{message:"invalid_wechat_login_response",status:502}}:(this.storage&&(await this.storage.set(g,a.token),await this.storage.set(v,a.token),await this.storage.set(b,a.user)),{data:a})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async loginWithAlipayCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let o=await this.storage.get(g);o!=null&&(r.Authorization=`Bearer ${o}`)}let i=await this.fetchImpl(this.url("alipay/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),s=await i.text();if(!i.ok)return{error:{message:s||i.statusText,status:i.status}};let a=s?JSON.parse(s):null;return!a?.token||!a.user?{error:{message:"invalid_alipay_login_response",status:502}}:(this.storage&&(await this.storage.set(g,a.token),await this.storage.set(v,a.token),await this.storage.set(b,a.user)),{data:a})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async getWeChatOpenPlatformIdentity(t){try{let e={};if(this.storage){let o=await this.storage.get(g);o!=null&&(e.Authorization=`Bearer ${o}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",i=await this.fetchImpl(this.url(`wechat/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),s=await i.text();if(!i.ok)return{error:{message:s||i.statusText,status:i.status}};let a=s?JSON.parse(s):null;return!a?.openid||!a.appId?{error:{message:"invalid_wechat_identity_response",status:502}}:{data:a}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getAlipayOpenPlatformIdentity(t){try{let e={};if(this.storage){let o=await this.storage.get(g);o!=null&&(e.Authorization=`Bearer ${o}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",i=await this.fetchImpl(this.url(`alipay/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),s=await i.text();if(!i.ok)return{error:{message:s||i.statusText,status:i.status}};let a=s?JSON.parse(s):null;return!a?.openid||!a.appId?{error:{message:"invalid_alipay_identity_response",status:502}}:{data:a}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async postJson(t,e){try{let r=await this.fetchImpl(this.url(t),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify(e)}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let s=i?JSON.parse(i):void 0;return{data:s?.data??s??void 0,response:r}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}},z=class{constructor(t,e,r){this.storage=t,this.customFetch=e,this.handleUnauthorized=r}async fetch(t,e){return await this.customFetch(t,e)}async fetchWithAuth(t,e){let r=await this.storage.get(g),i=new y(e?.headers);r&&i.set("Authorization",`Bearer ${r}`);let s=e?.method||"GET";if((s==="POST"||s==="PUT"||s==="PATCH")&&e?.body){let o=i.get("Content-Type");(!o||o.includes("text/plain"))&&i.set("Content-Type","application/json")}let a=await this.customFetch(t,{...e,headers:i});if(a.status===401)throw this.handleUnauthorized(),new Error("\u672A\u767B\u5F55");return a}},me="/storage",ge=me+"/generateUploadUrl",J=class{constructor(t,e){this.baseUrl=t,this.http=e}async uploadFile(t){let e=await this.http.fetch(this.baseUrl+ge,{method:"POST",body:{fileName:t.name||t.fileName,fileSize:t.size||t.fileSize,fileType:t.type||t.fileType}}),{url:r}=await e.json();if(!r)throw new Error("\u83B7\u53D6\u4E0A\u4F20URL\u5931\u8D25");let i=await this.http.fetch(r,{method:"PUT",body:t,headers:new y({"Content-Type":t.type||t.fileType||"application/octet-stream"})}),{url:s}=await i.json();return{url:s.split("?")[0]}}},fe=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},ye=class{constructor(t){var e,r,i;this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=new y(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.urlLengthLimit=(i=t.urlLengthLimit)!==null&&i!==void 0?i:8e3,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=new y(this.headers),this.headers.set(t,e),this}then(t,e){var r=this;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 i=this.fetch,s=i(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async a=>{let o=null,n=null,c=null,h=a.status,l=a.statusText;if(a.ok){var u,d;if(r.method!=="HEAD"){var m;let w=await a.text();w===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&!((m=r.headers.get("Accept"))===null||m===void 0)&&m.includes("application/vnd.pgrst.plan+text")?n=w:n=JSON.parse(w))}let p=(u=r.headers.get("Prefer"))===null||u===void 0?void 0:u.match(/count=(exact|planned|estimated)/),f=(d=a.headers.get("content-range"))===null||d===void 0?void 0:d.split("/");p&&f&&f.length>1&&(c=parseInt(f[1])),r.isMaybeSingle&&Array.isArray(n)&&(n.length>1?(o={code:"PGRST116",details:`Results contain ${n.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},n=null,c=null,h=406,l="Not Acceptable"):n.length===1?n=n[0]:n=null)}else{let p=await a.text();try{o=JSON.parse(p),Array.isArray(o)&&a.status===404&&(n=[],o=null,h=200,l="OK")}catch{a.status===404&&p===""?(h=204,l="No Content"):o={message:p}}if(o&&r.shouldThrowOnError)throw new fe(o)}return{error:o,data:n,count:c,status:h,statusText:l}});return this.shouldThrowOnError||(s=s.catch(a=>{var o;let n="",c="",h="",l=a?.cause;if(l){var u,d,m,p;let oe=(u=l?.message)!==null&&u!==void 0?u:"",k=(d=l?.code)!==null&&d!==void 0?d:"";n=`${(m=a?.name)!==null&&m!==void 0?m:"FetchError"}: ${a?.message}`,n+=`
|
|
1
|
+
var y=class M{constructor(e){if(this.headerMap=new Map,e){if(e instanceof M)e.forEach((r,i)=>this.set(i,r));else if(Array.isArray(e))for(let[r,i]of e)this.set(r,String(i));else if(typeof e=="object")for(let r of Object.keys(e))this.set(r,String(e[r]))}}append(e,r){let i=e.toLowerCase(),s=this.headerMap.get(i);this.headerMap.set(i,s?`${s}, ${r}`:r)}set(e,r){this.headerMap.set(e.toLowerCase(),String(r))}get(e){return this.headerMap.get(e.toLowerCase())??null}has(e){return this.headerMap.has(e.toLowerCase())}delete(e){this.headerMap.delete(e.toLowerCase())}forEach(e){for(let[r,i]of this.headerMap.entries())e(i,r,this)}entries(){return this.headerMap.entries()}keys(){return this.headerMap.keys()}values(){return this.headerMap.values()}[Symbol.iterator](){return this.entries()}},le=class F{constructor(e){if(this.params=new Map,e){if(typeof e=="string")this.parseString(e);else if(e instanceof F)this.params=new Map(e.params);else if(Array.isArray(e))for(let[r,i]of e)this.append(r,i);else if(e&&typeof e=="object")for(let[r,i]of Object.entries(e))this.set(r,i)}}parseString(e){e.startsWith("?")&&(e=e.slice(1));let r=e.split("&");for(let i of r)if(i){let[s,a]=i.split("=");s&&this.append(decodeURIComponent(s),a?decodeURIComponent(a):"")}}append(e,r){let i=this.params.get(e)||[];i.push(r),this.params.set(e,i)}delete(e){this.params.delete(e)}get(e){let r=this.params.get(e);return r?r[0]:null}getAll(e){return this.params.get(e)||[]}has(e){return this.params.has(e)}set(e,r){this.params.set(e,[r])}sort(){let e=Array.from(this.params.entries()).sort(([r],[i])=>r.localeCompare(i));this.params=new Map(e)}toString(){let e=[];for(let[r,i]of this.params.entries())for(let s of i)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(s)}`);return e.join("&")}forEach(e){for(let[r,i]of this.params.entries())for(let s of i)e(s,r,this)}keys(){return this.params.keys()}values(){let e=[];for(let r of this.params.values())e.push(...r);return e[Symbol.iterator]()}entries(){let e=[];for(let[r,i]of this.params.entries())for(let s of i)e.push([r,s]);return e[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}},$=class A{constructor(e,r){let i;if(e instanceof A)i=e.href;else if(r){let a=r instanceof A?r.href:r;i=this.resolve(a,e)}else i=e;let s=this.parseUrl(i);this.href=i,this.origin=`${s.protocol}//${s.host}`,this.protocol=s.protocol,this.username=s.username,this.password=s.password,this.host=s.host,this.hostname=s.hostname,this.port=s.port,this.pathname=s.pathname,this.search=s.search,this.searchParams=new le(s.search),this.hash=s.hash}resolve(e,r){if(r.startsWith("http://")||r.startsWith("https://"))return r;if(r.startsWith("//"))return`${this.parseUrl(e).protocol}${r}`;if(r.startsWith("/")){let a=this.parseUrl(e);return`${a.protocol}//${a.host}${r}`}let i=this.parseUrl(e),s=i.pathname.endsWith("/")?i.pathname:i.pathname+"/";return`${i.protocol}//${i.host}${s}${r}`}parseUrl(e){let r=e.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!r)throw new TypeError("Invalid URL");let i=r[2]||"",s=r[4]||"",a=r[5]||"/",o=r[7]?`?${r[7]}`:"",n=r[9]?`#${r[9]}`:"";if(!i&&!s&&!a.startsWith("/")&&!a.includes("/")&&!a.includes("."))throw new TypeError("Invalid URL");let c=s.match(/^([^@]*)@(.+)$/),h="",l="",u=s;if(c){let f=c[1];u=c[2];let w=f.match(/^([^:]*):?(.*)$/);w&&(h=w[1]||"",l=w[2]||"")}let d=u.match(/^([^:]+):?(\d*)$/),m=d?d[1]:u,p=d&&d[2]?d[2]:"";return{protocol:i?`${i}:`:"",username:h,password:l,host:u,hostname:m,port:p,pathname:a,search:o,hash:n}}toString(){let e=this.searchParams.toString(),r=e?`?${e}`:"";return`${this.protocol}//${this.host}${this.pathname}${r}${this.hash}`}toJSON(){return this.toString()}};var q=class{constructor(t,e){this.bodyData=t,this.status=e?.status??200,this.statusText=e?.statusText??"",this.headers=he(e?.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 t=await this.text();return new TextEncoder().encode(t).buffer}};function he(t){return t?new y(t):new y}var ce=class{constructor(){this._aborted=!1,this.listeners=new Set,this.onabort=null}get aborted(){return this._aborted}_trigger(){if(!this._aborted){if(this._aborted=!0,typeof this.onabort=="function")try{this.onabort()}catch{}for(let t of Array.from(this.listeners))try{t()}catch{}this.listeners.clear()}}addEventListener(t,e){if(this._aborted){try{e()}catch{}return}this.listeners.add(e)}removeEventListener(t,e){this.listeners.delete(e)}toString(){return"[object AbortSignal]"}},ue=class{constructor(){this._signal=new ce}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}},D=class{constructor(t,e=""){this.http=t,this.baseUrl=e.replace(/\/$/,"")}async invoke(t,e){let r=this.baseUrl?`${this.baseUrl}/functions/${t}`:`/functions/${t}`;return await(await this.http.fetch(r,{method:e.method||"POST",body:e.body,headers:e.headers})).json()}},g="nvwa_current_jwt",v="nvwa_login_token",b="nvwa_user_profile",de="set-auth-token",pe=typeof fetch<"u"?(t,e)=>fetch(t,e):()=>{throw new Error("AuthClient requires fetch")},G={google:{id:"google",name:"Google Login",description:"Sign in with Google account."},github:{id:"github",name:"GitHub Login",description:"Sign in with GitHub account."},"wechat-website":{id:"wechat-website",name:"WeChat QR Login",description:"Sign in with WeChat website QR code."},"wechat-miniprogram":{id:"wechat-miniprogram",name:"WeChat Mini Program Login",description:"Sign in with WeChat mini program code."},"alipay-miniprogram":{id:"alipay-miniprogram",name:"Alipay Mini Program Login",description:"Sign in with Alipay mini program code."},"douyin-miniprogram":{id:"douyin-miniprogram",name:"Douyin Mini Program Login",description:"Sign in with Douyin mini program code."}};function U(t){let e=G[t]??{id:t,name:t,description:""},r="unsupported";switch(t){case"google":r="google_openplatform";break;case"github":r="github_openplatform";break;case"wechat-website":r="wechat_website_openplatform";break;case"wechat-miniprogram":r="wechat_miniprogram_code";break;case"alipay-miniprogram":r="alipay_miniprogram_code";break;case"douyin-miniprogram":r="douyin_miniprogram_code";break;default:break}return{id:e.id,type:e.id,name:e.name,description:e.description,loginKind:r}}function R(t,e){let r=t.socialLogin?.providers?.[e];return r?.enabled?r.oauthCredentialSource==="custom"?"custom":"nvwa_default":null}var B=class{constructor(t,e={}){this.baseUrl=t.replace(/\/$/,""),this.authPath=(e.authPath??"/auth").replace(/^\//,""),this.fetchImpl=e.fetchImpl??pe,this.storage=e.storage??null,this.credentials=e.credentials??"omit",this.integrationProviders=e.integrationProviders??{},this.defaultApplicationCode=e.applicationCode?.trim()||null,typeof console<"u"&&(console.warn("[NvwaAuth] init baseUrl:",this.baseUrl||"(empty)"),(!this.baseUrl||!this.baseUrl.startsWith("http://")&&!this.baseUrl.startsWith("https://"))&&console.warn("[NvwaAuth] baseUrl \u5E94\u4E3A\u5B8C\u6574\u5730\u5740\uFF08\u5982 https://xxx.nvwa.app\uFF09\uFF0C\u5426\u5219\u5C0F\u7A0B\u5E8F request \u4F1A\u62A5 invalid url"))}async getSocialProviders(t){let e=this.integrationProviders.socialLogin?.providers??{};return Object.entries(e).filter(([,r])=>r.enabled).map(([r])=>{let i=G[r]??{id:r,name:r,description:""};return{...i,type:i.id}})}async getSocialProviderDescriptors(t){let e=this.integrationProviders.socialLogin?.providers??{};return Object.entries(e).filter(([,r])=>!!r?.enabled).map(([r])=>U(r))}async getAvailableProviders(t){return this.getSocialProviders(t)}async startSocialLogin(t,e){let r=U(t),i=e?.applicationCode?.trim()||this.defaultApplicationCode||void 0,s=e?.returnUrl??(typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:"");switch(r.loginKind){case"google_openplatform":if(!s)throw new Error("startSocialLogin requires returnUrl for google");this.startGoogleOpenPlatformLogin(s,{applicationCode:i,platformCode:e?.platformCode});return;case"github_openplatform":if(!s)throw new Error("startSocialLogin requires returnUrl for github");this.startGithubOpenPlatformLogin(s,{applicationCode:i,platformCode:e?.platformCode});return;case"wechat_website_openplatform":if(!s)throw new Error("startSocialLogin requires returnUrl for wechat-website");this.startWechatWebsiteOpenPlatformLogin(s);return;case"wechat_miniprogram_code":if(!e?.miniProgramCode?.trim()||!i)throw new Error("startSocialLogin requires miniProgramCode and applicationCode for wechat-miniprogram");await this.loginWithWeChatCode(e.miniProgramCode.trim(),i);return;case"alipay_miniprogram_code":if(!e?.miniProgramCode?.trim()||!i)throw new Error("startSocialLogin requires miniProgramCode and applicationCode for alipay-miniprogram");await this.loginWithAlipayCode(e.miniProgramCode.trim(),i);return;case"douyin_miniprogram_code":throw new Error("startSocialLogin does not support douyin-miniprogram yet");default:throw new Error(`startSocialLogin unsupported provider: ${t}`)}}async currentUser(){if(this.storage){let r=await this.storage.get(b);if(r!=null)return r}let{data:t}=await this.getSession(),e=t?.user??null;return e&&this.storage&&await this.storage.set(b,e),e}async getCurrentJwt(){if(this.storage){let e=await this.storage.get(g);if(e!=null)return e;let r=await this.storage.get(v),{data:i}=await this.getToken(r??void 0);return i?.token?(await this.storage.set(g,i.token),i.token):null}let{data:t}=await this.getToken();return t?.token??null}async persistLogin(t,e){if(!this.storage)return;let r=e?.headers.get(de)?.trim()||t.token||t.session?.token;r&&await this.storage.set(v,r),t.user&&await this.storage.set(b,t.user);let i=r??await this.storage.get(v),{data:s}=await this.getToken(i??void 0);s?.token&&await this.storage.set(g,s.token)}async clearLogin(){this.storage&&(await this.storage.remove(v),await this.storage.remove(b),await this.storage.remove(g))}getGoogleOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t}),i=e?.applicationCode?.trim()||this.defaultApplicationCode||"";i&&r.set("application_code",i);let s=e?.platformCode?.trim()??"";s&&r.set("platform_code",s);let a=R(this.integrationProviders,"google");return a&&r.set("oauth_credential_source",a),`${this.url("google/openplatform/login")}?${r.toString()}`}startGoogleOpenPlatformLogin(t,e){let r=this.getGoogleOpenPlatformLoginUrl(t,e);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=r;return}throw new Error("startGoogleOpenPlatformLogin requires a browser environment with location")}async completeGoogleOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeGoogleOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithGoogleExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithGoogleExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(g);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("google/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let s=i?JSON.parse(i):null;return!s?.token||!s.user?{error:{message:"invalid_google_login_response",status:502}}:(this.storage&&(await this.storage.set(g,s.token),await this.storage.set(v,s.token),await this.storage.set(b,s.user)),{data:s})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGoogleOpenPlatformIdentity(){try{let t={};if(this.storage){let s=await this.storage.get(g);s!=null&&(t.Authorization=`Bearer ${s}`)}let e=await this.fetchImpl(this.url("google/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_google_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getGithubOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t}),i=e?.applicationCode?.trim()||this.defaultApplicationCode||"";i&&r.set("application_code",i);let s=e?.platformCode?.trim()??"";s&&r.set("platform_code",s);let a=R(this.integrationProviders,"github");return a&&r.set("oauth_credential_source",a),`${this.url("github/openplatform/login")}?${r.toString()}`}startGithubOpenPlatformLogin(t,e){let r=this.getGithubOpenPlatformLoginUrl(t,e);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=r;return}throw new Error("startGithubOpenPlatformLogin requires a browser environment with location")}async completeGithubOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeGithubOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithGithubExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithGithubExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(g);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("github/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let s=i?JSON.parse(i):null;return!s?.token||!s.user?{error:{message:"invalid_github_login_response",status:502}}:(this.storage&&(await this.storage.set(g,s.token),await this.storage.set(v,s.token),await this.storage.set(b,s.user)),{data:s})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGithubOpenPlatformIdentity(){try{let t={};if(this.storage){let s=await this.storage.get(g);s!=null&&(t.Authorization=`Bearer ${s}`)}let e=await this.fetchImpl(this.url("github/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_github_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getWechatWebsiteOpenPlatformLoginUrl(t){let e=new URLSearchParams({return_url:t});return`${this.url("wechat-website/openplatform/login")}?${e.toString()}`}startWechatWebsiteOpenPlatformLogin(t){let e=this.getWechatWebsiteOpenPlatformLoginUrl(t);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=e;return}throw new Error("startWechatWebsiteOpenPlatformLogin requires a browser environment with location")}async completeWechatWebsiteOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeWechatWebsiteOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithWechatWebsiteExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithWechatWebsiteExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(g);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("wechat-website/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let s=i?JSON.parse(i):null;return!s?.token||!s.user?{error:{message:"invalid_wechat_website_login_response",status:502}}:(this.storage&&(await this.storage.set(g,s.token),await this.storage.set(v,s.token),await this.storage.set(b,s.user)),{data:s})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getWechatWebsiteOpenPlatformIdentity(){try{let t={};if(this.storage){let s=await this.storage.get(g);s!=null&&(t.Authorization=`Bearer ${s}`)}let e=await this.fetchImpl(this.url("wechat-website/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_wechat_website_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}url(t){let e=`${`${this.baseUrl.replace(/\/+$/,"")}/${this.authPath.replace(/^\/+/,"")}`}/${t.replace(/^\/+/,"")}`;return typeof console<"u"&&(console.warn("[NvwaAuth] request URL:",e),!e.startsWith("http://")&&!e.startsWith("https://")&&console.warn("[NvwaAuth] URL \u975E\u5B8C\u6574\u5730\u5740\uFF0C\u5C0F\u7A0B\u5E8F\u4F1A\u62A5 invalid url\uFF0C\u8BF7\u68C0\u67E5 Nvwa \u6784\u9020\u65F6\u4F20\u5165\u7684 baseUrl")),e}async getSession(){try{let t={};if(this.storage){let r=await this.storage.get(v)??await this.storage.get(g);r!=null&&(t.Authorization=`Bearer ${r}`)}let e=await this.fetchImpl(this.url("session"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}});return e.ok?{data:await e.json()}:{data:null,error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{data:null,error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signInWithEmail(t,e){try{let r=await this.fetchImpl(this.url("sign-in/email"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify({email:t,password:e})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let s=i?JSON.parse(i):void 0;return s&&await this.persistLogin({user:s.user,session:s.session},r),{data:s}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async signOut(){try{let t={"Content-Type":"application/json"};if(this.storage){let r=await this.storage.get(v)??await this.storage.get(g);r!=null&&(t.Authorization=`Bearer ${r}`)}await this.clearLogin();let e=await this.fetchImpl(this.url("sign-out"),{method:"POST",credentials:this.credentials,headers:t,body:"{}"});return e.ok?{}:{error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signUp(t){let e=await this.postJson("sign-up/email",t);return e.data&&await this.persistLogin(e.data,e.response),e}async getToken(t){try{let e={};if(t)e.Authorization=`Bearer ${t}`;else if(this.storage){let a=await this.storage.get(v)??await this.storage.get(g);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("token"),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let s=i?JSON.parse(i):void 0;return{data:s?.token!=null?{token:s.token}:void 0}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async signInWithUsername(t,e){let r=await this.postJson("sign-in/username",{username:t,password:e});return r.data&&await this.persistLogin(r.data,r.response),r}async signInWithPhoneNumber(t,e,r){let i=await this.postJson("sign-in/phone-number",{phoneNumber:t,password:e,rememberMe:r});return i.data&&await this.persistLogin(i.data,i.response),i}async sendPhoneNumberOtp(t){let e=await this.postJson("phone-number/send-otp",{phoneNumber:t});return e.error?{error:e.error}:{}}async verifyPhoneNumber(t,e){let r=await this.postJson("phone-number/verify",{phoneNumber:t,code:e});return r.data&&await this.persistLogin(r.data,r.response),r}async loginWithWeChatCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let o=await this.storage.get(g);o!=null&&(r.Authorization=`Bearer ${o}`)}let i=await this.fetchImpl(this.url("wechat/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),s=await i.text();if(!i.ok)return{error:{message:s||i.statusText,status:i.status}};let a=s?JSON.parse(s):null;return!a?.token||!a.user?{error:{message:"invalid_wechat_login_response",status:502}}:(this.storage&&(await this.storage.set(g,a.token),await this.storage.set(v,a.token),await this.storage.set(b,a.user)),{data:a})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async loginWithAlipayCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let o=await this.storage.get(g);o!=null&&(r.Authorization=`Bearer ${o}`)}let i=await this.fetchImpl(this.url("alipay/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),s=await i.text();if(!i.ok)return{error:{message:s||i.statusText,status:i.status}};let a=s?JSON.parse(s):null;return!a?.token||!a.user?{error:{message:"invalid_alipay_login_response",status:502}}:(this.storage&&(await this.storage.set(g,a.token),await this.storage.set(v,a.token),await this.storage.set(b,a.user)),{data:a})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async getWeChatOpenPlatformIdentity(t){try{let e={};if(this.storage){let o=await this.storage.get(g);o!=null&&(e.Authorization=`Bearer ${o}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",i=await this.fetchImpl(this.url(`wechat/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),s=await i.text();if(!i.ok)return{error:{message:s||i.statusText,status:i.status}};let a=s?JSON.parse(s):null;return!a?.openid||!a.appId?{error:{message:"invalid_wechat_identity_response",status:502}}:{data:a}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getAlipayOpenPlatformIdentity(t){try{let e={};if(this.storage){let o=await this.storage.get(g);o!=null&&(e.Authorization=`Bearer ${o}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",i=await this.fetchImpl(this.url(`alipay/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),s=await i.text();if(!i.ok)return{error:{message:s||i.statusText,status:i.status}};let a=s?JSON.parse(s):null;return!a?.openid||!a.appId?{error:{message:"invalid_alipay_identity_response",status:502}}:{data:a}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async postJson(t,e){try{let r=await this.fetchImpl(this.url(t),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify(e)}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let s=i?JSON.parse(i):void 0;return{data:s?.data??s??void 0,response:r}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}},z=class{constructor(t,e,r){this.storage=t,this.customFetch=e,this.handleUnauthorized=r}async fetch(t,e){return await this.customFetch(t,e)}async fetchWithAuth(t,e){let r=await this.storage.get(g),i=new y(e?.headers);r&&i.set("Authorization",`Bearer ${r}`);let s=e?.method||"GET";if((s==="POST"||s==="PUT"||s==="PATCH")&&e?.body){let o=i.get("Content-Type");(!o||o.includes("text/plain"))&&i.set("Content-Type","application/json")}let a=await this.customFetch(t,{...e,headers:i});if(a.status===401)throw this.handleUnauthorized(),new Error("\u672A\u767B\u5F55");return a}},me="/storage",ge=me+"/generateUploadUrl",J=class{constructor(t,e){this.baseUrl=t,this.http=e}async uploadFile(t){let e=await this.http.fetch(this.baseUrl+ge,{method:"POST",body:{fileName:t.name||t.fileName,fileSize:t.size||t.fileSize,fileType:t.type||t.fileType}}),{url:r}=await e.json();if(!r)throw new Error("\u83B7\u53D6\u4E0A\u4F20URL\u5931\u8D25");let i=await this.http.fetch(r,{method:"PUT",body:t,headers:new y({"Content-Type":t.type||t.fileType||"application/octet-stream"})}),{url:s}=await i.json();return{url:s.split("?")[0]}}},fe=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},ye=class{constructor(t){var e,r,i;this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=new y(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.urlLengthLimit=(i=t.urlLengthLimit)!==null&&i!==void 0?i:8e3,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=new y(this.headers),this.headers.set(t,e),this}then(t,e){var r=this;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 i=this.fetch,s=i(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async a=>{let o=null,n=null,c=null,h=a.status,l=a.statusText;if(a.ok){var u,d;if(r.method!=="HEAD"){var m;let w=await a.text();w===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&!((m=r.headers.get("Accept"))===null||m===void 0)&&m.includes("application/vnd.pgrst.plan+text")?n=w:n=JSON.parse(w))}let p=(u=r.headers.get("Prefer"))===null||u===void 0?void 0:u.match(/count=(exact|planned|estimated)/),f=(d=a.headers.get("content-range"))===null||d===void 0?void 0:d.split("/");p&&f&&f.length>1&&(c=parseInt(f[1])),r.isMaybeSingle&&Array.isArray(n)&&(n.length>1?(o={code:"PGRST116",details:`Results contain ${n.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},n=null,c=null,h=406,l="Not Acceptable"):n.length===1?n=n[0]:n=null)}else{let p=await a.text();try{o=JSON.parse(p),Array.isArray(o)&&a.status===404&&(n=[],o=null,h=200,l="OK")}catch{a.status===404&&p===""?(h=204,l="No Content"):o={message:p}}if(o&&r.shouldThrowOnError)throw new fe(o)}return{error:o,data:n,count:c,status:h,statusText:l}});return this.shouldThrowOnError||(s=s.catch(a=>{var o;let n="",c="",h="",l=a?.cause;if(l){var u,d,m,p;let oe=(u=l?.message)!==null&&u!==void 0?u:"",k=(d=l?.code)!==null&&d!==void 0?d:"";n=`${(m=a?.name)!==null&&m!==void 0?m:"FetchError"}: ${a?.message}`,n+=`
|
|
2
2
|
|
|
3
3
|
Caused by: ${(p=l?.name)!==null&&p!==void 0?p:"Error"}: ${oe}`,k&&(n+=` (${k})`),l?.stack&&(n+=`
|
|
4
4
|
${l.stack}`)}else{var f;n=(f=a?.stack)!==null&&f!==void 0?f:""}let w=this.url.toString().length;return a?.name==="AbortError"||a?.code==="ABORT_ERR"?(h="",c="Request was aborted (timeout or manual cancellation)",w>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${w} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):(l?.name==="HeadersOverflowError"||l?.code==="UND_ERR_HEADERS_OVERFLOW")&&(h="",c="HTTP headers exceeded server limits (typically 16KB)",w>this.urlLengthLimit&&(c+=`. Your request URL is ${w} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{error:{message:`${(o=a?.name)!==null&&o!==void 0?o:"FetchError"}: ${a?.message}`,details:n,hint:c,code:h},data:null,count:null,status:0,statusText:""}})),s.then(t,e)}returns(){return this}overrideTypes(){return this}},we=class extends ye{select(t){let e=!1,r=(t??"*").split("").map(i=>/\s/.test(i)&&!e?"":(i==='"'&&(e=!e),i)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:i,referencedTable:s=i}={}){let a=s?`${s}.order`:"order",o=this.url.searchParams.get(a);return this.url.searchParams.set(a,`${o?`${o},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){let i=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:i=r}={}){let s=typeof i>"u"?"offset":`${i}.offset`,a=typeof i>"u"?"limit":`${i}.limit`;return this.url.searchParams.set(s,`${t}`),this.url.searchParams.set(a,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return 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:t=!1,verbose:e=!1,settings:r=!1,buffers:i=!1,wal:s=!1,format:a="text"}={}){var o;let n=[t?"analyze":null,e?"verbose":null,r?"settings":null,i?"buffers":null,s?"wal":null].filter(Boolean).join("|"),c=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${a}; for="${c}"; options=${n};`),a==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}},j=new RegExp("[,()]"),E=class extends we{eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){let r=Array.from(new Set(e)).map(i=>typeof i=="string"&&j.test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(i=>typeof i=="string"&&j.test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:i}={}){let s="";i==="plain"?s="pl":i==="phrase"?s="ph":i==="websearch"&&(s="w");let a=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${s}fts${a}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){let i=r?`${r}.or`:"or";return this.url.searchParams.append(i,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},ve=class{constructor(t,{headers:e={},schema:r,fetch:i,urlLengthLimit:s=8e3}){this.url=t,this.headers=new y(e),this.schema=r,this.fetch=i,this.urlLengthLimit=s}cloneRequestState(){return{url:new $(this.url.toString()),headers:new y(this.headers)}}select(t,e){let{head:r=!1,count:i}=e??{},s=r?"HEAD":"GET",a=!1,o=(t??"*").split("").map(h=>/\s/.test(h)&&!a?"":(h==='"'&&(a=!a),h)).join(""),{url:n,headers:c}=this.cloneRequestState();return n.searchParams.set("select",o),i&&c.append("Prefer",`count=${i}`),new E({method:s,url:n,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var i;let s="POST",{url:a,headers:o}=this.cloneRequestState();if(e&&o.append("Prefer",`count=${e}`),r||o.append("Prefer","missing=default"),Array.isArray(t)){let n=t.reduce((c,h)=>c.concat(Object.keys(h)),[]);if(n.length>0){let c=[...new Set(n)].map(h=>`"${h}"`);a.searchParams.set("columns",c.join(","))}}return new E({method:s,url:a,headers:o,schema:this.schema,body:t,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:i,defaultToNull:s=!0}={}){var a;let o="POST",{url:n,headers:c}=this.cloneRequestState();if(c.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&n.searchParams.set("on_conflict",e),i&&c.append("Prefer",`count=${i}`),s||c.append("Prefer","missing=default"),Array.isArray(t)){let h=t.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(h.length>0){let l=[...new Set(h)].map(u=>`"${u}"`);n.searchParams.set("columns",l.join(","))}}return new E({method:o,url:n,headers:c,schema:this.schema,body:t,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;let i="PATCH",{url:s,headers:a}=this.cloneRequestState();return e&&a.append("Prefer",`count=${e}`),new E({method:i,url:s,headers:a,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:t}={}){var e;let r="DELETE",{url:i,headers:s}=this.cloneRequestState();return t&&s.append("Prefer",`count=${t}`),new E({method:r,url:i,headers:s,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function L(t){"@babel/helpers - typeof";return L=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},L(t)}function be(t,e){if(L(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var i=r.call(t,e||"default");if(L(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Ee(t){var e=be(t,"string");return L(e)=="symbol"?e:e+""}function Pe(t,e,r){return(e=Ee(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function H(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);e&&(i=i.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),r.push.apply(r,i)}return r}function O(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?H(Object(r),!0).forEach(function(i){Pe(t,i,r[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):H(Object(r)).forEach(function(i){Object.defineProperty(t,i,Object.getOwnPropertyDescriptor(r,i))})}return t}var Se=class K{constructor(e,{headers:r={},schema:i,fetch:s,timeout:a,urlLengthLimit:o=8e3}={}){this.url=e,this.headers=new y(r),this.schemaName=i,this.urlLengthLimit=o;let n=s??globalThis.fetch;a!==void 0&&a>0?this.fetch=(c,h)=>{let l=new ue,u=setTimeout(()=>l.abort(),a),d=h?.signal;if(d){if(d.aborted)return clearTimeout(u),n(c,h);let m=()=>{clearTimeout(u),l.abort()};return d.addEventListener("abort",m,{once:!0}),n(c,O(O({},h),{},{signal:l.signal})).finally(()=>{clearTimeout(u),d.removeEventListener("abort",m)})}return n(c,O(O({},h),{},{signal:l.signal})).finally(()=>clearTimeout(u))}:this.fetch=n}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new ve(new $(`${this.url}/${e}`),{headers:new y(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new K(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:i=!1,get:s=!1,count:a}={}){var o;let n,c=new $(`${this.url}/rpc/${e}`),h,l=m=>m!==null&&typeof m=="object"&&(!Array.isArray(m)||m.some(l)),u=i&&Object.values(r).some(l);u?(n="POST",h=r):i||s?(n=i?"HEAD":"GET",Object.entries(r).filter(([m,p])=>p!==void 0).map(([m,p])=>[m,Array.isArray(p)?`{${p.join(",")}}`:`${p}`]).forEach(([m,p])=>{c.searchParams.append(m,p)})):(n="POST",h=r);let d=new y(this.headers);return u?d.set("Prefer",a?`count=${a},return=minimal`:"return=minimal"):a&&d.set("Prefer",`count=${a}`),new E({method:n,url:c,headers:d,schema:this.schemaName,body:h,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit})}},Le="/entities",V=(t,e)=>new Se(t+Le,{fetch:e.fetchWithAuth.bind(e)}),Y=class{constructor(){this.hoverOverlay=null,this.selectedOverlay=null,this.tooltip=null,this.hoverElement=null,this.selectedElement=null,this.hoverUpdateHandler=null,this.selectedUpdateHandler=null,this.createStyles()}createStyles(){if(document.getElementById("__nvwa-inspector-overlay-style"))return;let t=document.createElement("style");t.id="__nvwa-inspector-overlay-style",t.textContent=`
|