@nvwa-app/sdk-web 6.29.0 → 6.31.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.d.mts +0 -1
- package/dist/index.d.ts +0 -1
- package/dist/index.js +3 -3
- package/dist/index.mjs +2 -2
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
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 Je={};ce(Je,{SocialLoginButtons:()=>ze,default:()=>$,disableIframeHoverInspector:()=>He,enableIframeHoverInspector:()=>je,getIframeSourceLocation:()=>Me,localStorage:()=>R,setupIframeHoverInspector:()=>Re,setupIframeSourceLocationListener:()=>We,webFetch:()=>O});module.exports=de(Je);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 M(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=M(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=M(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
|
-
${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=`
|
|
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}},W=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"&&W.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"&&W.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=`
|
|
5
5
|
.__nvwa-inspector-overlay {
|
|
6
6
|
position: absolute;
|
|
7
7
|
pointer-events: none;
|
|
@@ -33,4 +33,4 @@ ${l.stack}`)}else{var f;n=(f=a?.stack)!==null&&f!==void 0?f:""}let w=this.url.to
|
|
|
33
33
|
max-width: 400px;
|
|
34
34
|
word-break: break-all;
|
|
35
35
|
}
|
|
36
|
-
`,document.head.appendChild(t)}createTooltip(){return this.tooltip?this.tooltip:(this.tooltip=document.createElement("div"),this.tooltip.id="__nvwa-inspector-tooltip",document.body.appendChild(this.tooltip),this.tooltip)}createOverlay(t){let e=document.createElement("div");return e.className=`__nvwa-inspector-overlay __nvwa-inspector-overlay-${t}`,document.body.appendChild(e),e}updateOverlayPosition(t,e){if(!e.isConnected)return;let r=e.getBoundingClientRect(),i=window.scrollX||window.pageXOffset,s=window.scrollY||window.pageYOffset;r.width>0&&r.height>0?(t.style.left=`${r.left+i}px`,t.style.top=`${r.top+s}px`,t.style.width=`${r.width}px`,t.style.height=`${r.height}px`,t.style.display="block"):t.style.display="none"}removeOverlay(t){t&&t.parentNode&&t.parentNode.removeChild(t)}highlightElement(t,e){if(!t.isConnected)return;if(this.hoverElement===t&&this.hoverOverlay){this.updateOverlayPosition(this.hoverOverlay,t);let o=this.createTooltip();e?o.textContent=e:o.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,o.style.display="block";let n=t.getBoundingClientRect();o.style.left=`${n.left+window.scrollX}px`,o.style.top=`${n.top+window.scrollY-o.offsetHeight-8}px`,n.top<o.offsetHeight+8&&(o.style.top=`${n.bottom+window.scrollY+8}px`);return}this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null);let r=this.createOverlay("hover");this.updateOverlayPosition(r,t),this.hoverOverlay=r,this.hoverElement=t;let i=()=>{this.hoverOverlay&&this.hoverElement&&this.hoverElement.isConnected&&this.updateOverlayPosition(this.hoverOverlay,this.hoverElement)};this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler)),this.hoverUpdateHandler=i,window.addEventListener("scroll",i,!0),window.addEventListener("resize",i);let s=this.createTooltip();e?s.textContent=e:s.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,s.style.display="block";let a=t.getBoundingClientRect();s.style.left=`${a.left+window.scrollX}px`,s.style.top=`${a.top+window.scrollY-s.offsetHeight-8}px`,a.top<s.offsetHeight+8&&(s.style.top=`${a.bottom+window.scrollY+8}px`)}selectElement(t,e){if(!t.isConnected)return;if(this.selectedElement===t&&this.selectedOverlay){this.updateOverlayPosition(this.selectedOverlay,t);return}this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null);let r=this.createOverlay("selected");this.updateOverlayPosition(r,t),this.selectedOverlay=r,this.selectedElement=t;let i=()=>{this.selectedOverlay&&this.selectedElement&&this.selectedElement.isConnected&&this.updateOverlayPosition(this.selectedOverlay,this.selectedElement)};this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler)),this.selectedUpdateHandler=i,window.addEventListener("scroll",i,!0),window.addEventListener("resize",i)}removeHighlight(){this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null),this.hoverElement&&(this.hoverElement=null),this.tooltip&&(this.tooltip.style.display="none"),this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler),this.hoverUpdateHandler=null)}clearSelection(){this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null),this.selectedElement&&(this.selectedElement=null),this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler),this.selectedUpdateHandler=null)}cleanup(){this.removeHighlight(),this.clearSelection(),this.tooltip&&this.tooltip.parentNode&&(this.tooltip.parentNode.removeChild(this.tooltip),this.tooltip=null);let t=document.getElementById("__nvwa-inspector-overlay-style");t&&t.parentNode&&t.parentNode.removeChild(t)}};function ee(t="root"){if(typeof document>"u")return null;let e=document.getElementById(t)||document.body;if(!e)return null;let r=e.querySelector("[data-source-location]");if(r){let i=r.getAttribute("data-source-location");if(i)return i}if(e.firstElementChild){let i=e.firstElementChild.getAttribute("data-source-location");if(i)return i}return null}var Ae={"wechat-pay":{id:"wechat-pay",name:"WeChat Pay",description:"WeChat payment for web and miniapp."},wechat_partner:{id:"wechat_partner",name:"WeChat Partner",description:"WeChat partner merchant onboarding."},alipay:{id:"alipay",name:"Alipay",description:"Alipay payment."},"alipay-miniprogram":{id:"alipay-miniprogram",name:"Alipay Mini Program",description:"Alipay mini program payment."},stripe:{id:"stripe",name:"Stripe",description:"Stripe payment."}};function te(t){let e=t;if(typeof e.kind=="string")return e;if(typeof e.tradeNO=="string")return{kind:"alipay_miniprogram",tradeNO:e.tradeNO};if(typeof e.clientSecret=="string")return{kind:"stripe_client_secret",clientSecret:e.clientSecret};if(typeof e.redirectUrl=="string")return{kind:"redirect_url",redirectUrl:e.redirectUrl};if(typeof e.formHtml=="string")return{kind:"alipay_page",formHtml:e.formHtml};if(typeof e.codeUrl=="string")return{kind:"wechat_native_qr",codeUrl:e.codeUrl};let r=e.jsapiPayParams??e;return typeof r.timeStamp=="string"&&typeof r.nonceStr=="string"&&typeof r.package=="string"&&typeof r.paySign=="string"&&typeof r.appId=="string"?{kind:"wechat_jsapi",mode:"jsapi",jsapiPayParams:{appId:r.appId,timeStamp:r.timeStamp,nonceStr:r.nonceStr,package:r.package,signType:r.signType??"RSA",paySign:r.paySign}}:null}async function re(t,e){let r=t.payment?.providers??{};return Object.entries(r).filter(([,i])=>i.enabled).map(([i])=>{let s=Ae[i]??{id:i,name:i,description:""};return{...s,type:s.id}})}function T(t){return t&&typeof t=="object"?t:{}}function Ne(t){let e=T(t),r=e.enabled===!0,i=String(e.oauthCredentialSource??"").toLowerCase();return i?{enabled:r,oauthCredentialSource:i==="custom"?"custom":"nvwa_default"}:{enabled:r}}function q(t){let e=T(t),r=T(e.providers),i={};for(let[s,a]of Object.entries(r))i[s]=Ne(a);return{providers:i}}function x(t){let e=T(t);return{socialLogin:q(e.socialLogin),payment:q(e.payment)}}function ie(t){return x(t.integrationProviders??{})}function se(t){let e=t.baseUrl?.trim()??"";if(!e)throw new Error("Nvwa: appConfig.baseUrl is required");let r=t.applicationCode?.trim()??"";if(!r)throw new Error("Nvwa: appConfig.applicationCode is required");let i=t.platformType?.trim()??"";if(!i)throw new Error("Nvwa: appConfig.platformType is required");return{baseUrl:e,applicationCode:r,platformType:i}}var _=class{constructor(){this.prefix="nvwa_"}getKey(e){return`${this.prefix}${e}`}async get(e){try{let r=this.getKey(e),i=localStorage.getItem(r);if(!i)return null;let s=JSON.parse(i);return s.expires&&Date.now()>s.expires?(await this.remove(e),null):s.value}catch(r){return console.error("WebStorageService get error:",r),null}}async set(e,r,i){try{let s=this.getKey(e),a={value:r,expires:i?Date.now()+i*1e3:null,timestamp:Date.now()};localStorage.setItem(s,JSON.stringify(a))}catch(s){throw console.error("WebStorageService set error:",s),s}}async remove(e){try{let r=this.getKey(e);localStorage.removeItem(r)}catch(r){throw console.error("WebStorageService remove error:",r),r}}async clear(){try{Object.keys(localStorage).filter(i=>i.startsWith(this.prefix)).forEach(i=>{localStorage.removeItem(i)})}catch(e){throw console.error("WebStorageService clear error:",e),e}}};var Ie=(t,e)=>{let r;if(typeof t=="string")r=t;else if(t&&typeof t.toString=="function")r=t.toString();else if(t?.url)r=t.url;else throw new Error("Invalid input for webFetch");let i;if(e?.headers){let a=e.headers;if(a instanceof y){let o={};a.forEach((n,c)=>{o[c]=n}),i=o}else if(Array.isArray(a)){let o=[];for(let n of a)Array.isArray(n)&&n.length>=2&&o.push([String(n[0]),String(n[1])]);i=o}else typeof a=="object"&&(i=a)}let s={method:e?.method||"GET",headers:i,body:e?.body,credentials:e?.credentials};return e?.signal&&(s.signal=e.signal),globalThis.fetch(r,s).then(async a=>{let o=a.headers.get("content-type")||"",n;if(o.includes("application/json"))n=await a.json();else{let h=await a.text();try{n=JSON.parse(h)}catch{n=h}}let c=new y;return a.headers.forEach((h,l)=>{c.set(l,h)}),new B(n,{status:a.status,statusText:a.statusText,headers:c})})},O=Ie;function xe(t){return`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(t)}`}var k={async requestPayment(t,e){let r=te(t);if(r?.kind==="redirect_url"){window.location.href=r.redirectUrl;return}if(r?.kind==="wechat_native_qr"){let s=xe(r.codeUrl);window.open(s,"_blank","noopener,noreferrer");return}if(r?.kind==="alipay_page"){let s=window.open("","_blank");s&&(s.document.write(r.formHtml),s.document.close());return}let i=new Error("requestPayment: unsupported payParams for Desktop-web");throw e?.onFailure?.(i),i}};function ae(t){let e=async r=>await re(t,r);return{...k,getAvailableProviders:e,getProviders:e}}function ke(){if(typeof window>"u"||window===window.parent)return;let t=!1,e=new Z;function r(h){if(!h)return!1;let l=h.toLowerCase();return l.includes("/components/")||l.includes("\\components\\")}function i(h){let l=h,u=null;for(;l;){let d=l.getAttribute("data-source-location");if(d)if(r(d)){u||(u=d),l=l.parentElement;continue}else return d;l=l.parentElement}return u}let s=null;function a(h){t&&(s!==null&&cancelAnimationFrame(s),s=requestAnimationFrame(()=>{let l=h.target;if(!l||l===document.body||l===document.documentElement){e.removeHighlight();return}if(l.tagName.toLowerCase()==="img"){let p=i(l);e.highlightElement(l,p);let f={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:p,elementInfo:{tagName:l.tagName.toLowerCase(),className:l.className||"",id:l.id||""}};window.parent.postMessage(f,"*");return}let u=l,d=i(l);if(!d){let p=l.parentElement;for(;p&&p!==document.body&&p!==document.documentElement;){let f=i(p);if(f){u=p,d=f;break}p=p.parentElement}}e.highlightElement(u,d);let m={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:d,elementInfo:{tagName:u.tagName.toLowerCase(),className:u.className||"",id:u.id||""}};window.parent.postMessage(m,"*")}))}function o(){if(!t)return;e.removeHighlight();let h={type:"HOVER_INSPECTOR_ELEMENT_LEAVE"};window.parent.postMessage(h,"*")}function n(h){if(!t)return;h.preventDefault(),h.stopPropagation();let l=h.target;if(!l||l===document.body||l===document.documentElement)return;let u=i(l);e.selectElement(l,u);let d={type:"HOVER_INSPECTOR_ELEMENT_SELECT",sourceLocation:u,elementInfo:{tagName:l.tagName.toLowerCase(),className:l.className||"",id:l.id||""}};window.parent.postMessage(d,"*")}function c(h){h.data?.type==="HOVER_INSPECTOR_ENABLE"?(t=!0,document.addEventListener("mousemove",a),document.addEventListener("mouseleave",o),document.addEventListener("click",n,!0)):h.data?.type==="HOVER_INSPECTOR_DISABLE"&&(t=!1,document.removeEventListener("mousemove",a),document.removeEventListener("mouseleave",o),document.removeEventListener("click",n,!0),e.removeHighlight(),e.clearSelection())}return window.addEventListener("message",c),()=>{window.removeEventListener("message",c),document.removeEventListener("mousemove",a),document.removeEventListener("mouseleave",o),document.removeEventListener("click",n,!0),e.cleanup()}}function Ue(t,e){if(!t||!t.contentWindow)throw new Error("Invalid iframe element");let r={type:"HOVER_INSPECTOR_ENABLE"};t.contentWindow.postMessage(r,e)}function Re(t,e){if(!t||!t.contentWindow)return;let r={type:"HOVER_INSPECTOR_DISABLE"};t.contentWindow.postMessage(r,e)}function je(t,e,r=5e3){return new Promise((i,s)=>{if(!t||!t.contentWindow){s(new Error("Invalid iframe element"));return}let a=`source-location-${Date.now()}-${Math.random()}`,o=setTimeout(()=>{window.removeEventListener("message",n),s(new Error("Request timeout"))},r),n=h=>{h.origin===e&&h.data?.type==="GET_SOURCE_LOCATION_RESPONSE"&&h.data?.requestId===a&&(clearTimeout(o),window.removeEventListener("message",n),h.data.error?s(new Error(h.data.error)):i(h.data.sourceLocation||null))};window.addEventListener("message",n);let c={type:"GET_SOURCE_LOCATION_REQUEST",requestId:a};try{t.contentWindow.postMessage(c,e)}catch(h){clearTimeout(o),window.removeEventListener("message",n),s(h)}})}function He(){if(typeof window>"u"||window===window.parent)return;let t=e=>{if(e.data?.type==="GET_SOURCE_LOCATION_REQUEST")try{let i={type:"GET_SOURCE_LOCATION_RESPONSE",sourceLocation:We(),requestId:e.data.requestId};window.parent.postMessage(i,e.origin)}catch(r){let i={type:"GET_SOURCE_LOCATION_RESPONSE",sourceLocation:null,error:r instanceof Error?r.message:"Unknown error",requestId:e.data.requestId};window.parent.postMessage(i,e.origin)}};return window.addEventListener("message",t),()=>{window.removeEventListener("message",t)}}function We(){return ee("root")}var E=require("react"),U=require("react"),Me="nvwa-social-login-list",Fe="nvwa-social-login-button";async function qe(t){return await t.getSocialProviderDescriptors()}function De(t){return t?.trim()?t.trim():typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:""}function Ge(t){let[e,r]=(0,E.useState)(t.providers??[]),[i,s]=(0,E.useState)(!t.providers);(0,E.useEffect)(()=>{if(t.providers){r(t.providers),s(!1);return}let n=!1;return s(!0),qe(t.auth).then(c=>{n||r(c)}).catch(c=>{n||t.onError?.(c instanceof Error?c:new Error(String(c)))}).finally(()=>{n||s(!1)}),()=>{n=!0}},[t.auth,t.providers,t.onError]);let a=(0,E.useMemo)(()=>De(t.returnUrl),[t.returnUrl]),o=(0,E.useMemo)(()=>e.filter(n=>n.loginKind!=="unsupported"),[e]);return i||o.length===0?null:(0,U.createElement)("div",{className:t.className??Me},...o.map(n=>{let c=async()=>{try{t.onBeforeLogin?.(n),await t.auth.startSocialLogin(n.id,{returnUrl:a,applicationCode:t.applicationCode,platformCode:t.platformCode})}catch(l){t.onError?.(l instanceof Error?l:new Error(String(l)))}},h=(0,U.createElement)("button",{key:n.id,type:"button",className:Fe,onClick:c},n.name);return t.onRenderButton?t.onRenderButton(n,h):h}))}var R=new _,$=class{constructor(e){this.endpointType="Desktop-web";this.payment=k;let{handleUnauthorized:r,appConfig:i,integrationProviders:s}=e,a=se(i);this.applicationCode=a.applicationCode,this.platformType=a.platformType,this.integrationProviders=x(s??ie(i)),this.auth=new K(a.baseUrl,{fetchImpl:O,storage:R,integrationProviders:this.integrationProviders,applicationCode:this.applicationCode}),this.httpClient=new V(R,O,r),this.fileStorage=new Y(a.baseUrl,this.httpClient),this.entities=X(a.baseUrl,this.httpClient),this.functions=new z(this.httpClient,a.baseUrl),this.payment=ae(this.integrationProviders)}};0&&(module.exports={SocialLoginButtons,disableIframeHoverInspector,enableIframeHoverInspector,getIframeSourceLocation,localStorage,setupIframeHoverInspector,setupIframeSourceLocationListener,webFetch});
|
|
36
|
+
`,document.head.appendChild(t)}createTooltip(){return this.tooltip?this.tooltip:(this.tooltip=document.createElement("div"),this.tooltip.id="__nvwa-inspector-tooltip",document.body.appendChild(this.tooltip),this.tooltip)}createOverlay(t){let e=document.createElement("div");return e.className=`__nvwa-inspector-overlay __nvwa-inspector-overlay-${t}`,document.body.appendChild(e),e}updateOverlayPosition(t,e){if(!e.isConnected)return;let r=e.getBoundingClientRect(),i=window.scrollX||window.pageXOffset,s=window.scrollY||window.pageYOffset;r.width>0&&r.height>0?(t.style.left=`${r.left+i}px`,t.style.top=`${r.top+s}px`,t.style.width=`${r.width}px`,t.style.height=`${r.height}px`,t.style.display="block"):t.style.display="none"}removeOverlay(t){t&&t.parentNode&&t.parentNode.removeChild(t)}highlightElement(t,e){if(!t.isConnected)return;if(this.hoverElement===t&&this.hoverOverlay){this.updateOverlayPosition(this.hoverOverlay,t);let o=this.createTooltip();e?o.textContent=e:o.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,o.style.display="block";let n=t.getBoundingClientRect();o.style.left=`${n.left+window.scrollX}px`,o.style.top=`${n.top+window.scrollY-o.offsetHeight-8}px`,n.top<o.offsetHeight+8&&(o.style.top=`${n.bottom+window.scrollY+8}px`);return}this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null);let r=this.createOverlay("hover");this.updateOverlayPosition(r,t),this.hoverOverlay=r,this.hoverElement=t;let i=()=>{this.hoverOverlay&&this.hoverElement&&this.hoverElement.isConnected&&this.updateOverlayPosition(this.hoverOverlay,this.hoverElement)};this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler)),this.hoverUpdateHandler=i,window.addEventListener("scroll",i,!0),window.addEventListener("resize",i);let s=this.createTooltip();e?s.textContent=e:s.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,s.style.display="block";let a=t.getBoundingClientRect();s.style.left=`${a.left+window.scrollX}px`,s.style.top=`${a.top+window.scrollY-s.offsetHeight-8}px`,a.top<s.offsetHeight+8&&(s.style.top=`${a.bottom+window.scrollY+8}px`)}selectElement(t,e){if(!t.isConnected)return;if(this.selectedElement===t&&this.selectedOverlay){this.updateOverlayPosition(this.selectedOverlay,t);return}this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null);let r=this.createOverlay("selected");this.updateOverlayPosition(r,t),this.selectedOverlay=r,this.selectedElement=t;let i=()=>{this.selectedOverlay&&this.selectedElement&&this.selectedElement.isConnected&&this.updateOverlayPosition(this.selectedOverlay,this.selectedElement)};this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler)),this.selectedUpdateHandler=i,window.addEventListener("scroll",i,!0),window.addEventListener("resize",i)}removeHighlight(){this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null),this.hoverElement&&(this.hoverElement=null),this.tooltip&&(this.tooltip.style.display="none"),this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler),this.hoverUpdateHandler=null)}clearSelection(){this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null),this.selectedElement&&(this.selectedElement=null),this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler),this.selectedUpdateHandler=null)}cleanup(){this.removeHighlight(),this.clearSelection(),this.tooltip&&this.tooltip.parentNode&&(this.tooltip.parentNode.removeChild(this.tooltip),this.tooltip=null);let t=document.getElementById("__nvwa-inspector-overlay-style");t&&t.parentNode&&t.parentNode.removeChild(t)}};function ee(t="root"){if(typeof document>"u")return null;let e=document.getElementById(t)||document.body;if(!e)return null;let r=e.querySelector("[data-source-location]");if(r){let i=r.getAttribute("data-source-location");if(i)return i}if(e.firstElementChild){let i=e.firstElementChild.getAttribute("data-source-location");if(i)return i}return null}var Ae={"wechat-pay":{id:"wechat-pay",name:"WeChat Pay",description:"WeChat payment for web and miniapp."},wechat_partner:{id:"wechat_partner",name:"WeChat Partner",description:"WeChat partner merchant onboarding."},alipay:{id:"alipay",name:"Alipay",description:"Alipay payment."},"alipay-miniprogram":{id:"alipay-miniprogram",name:"Alipay Mini Program",description:"Alipay mini program payment."},stripe:{id:"stripe",name:"Stripe",description:"Stripe payment."}};function te(t){let e=t;if(typeof e.kind=="string")return e;if(typeof e.tradeNO=="string")return{kind:"alipay_miniprogram",tradeNO:e.tradeNO};if(typeof e.clientSecret=="string")return{kind:"stripe_client_secret",clientSecret:e.clientSecret};if(typeof e.redirectUrl=="string")return{kind:"redirect_url",redirectUrl:e.redirectUrl};if(typeof e.formHtml=="string")return{kind:"alipay_page",formHtml:e.formHtml};if(typeof e.codeUrl=="string")return{kind:"wechat_native_qr",codeUrl:e.codeUrl};let r=e.jsapiPayParams??e;return typeof r.timeStamp=="string"&&typeof r.nonceStr=="string"&&typeof r.package=="string"&&typeof r.paySign=="string"&&typeof r.appId=="string"?{kind:"wechat_jsapi",mode:"jsapi",jsapiPayParams:{appId:r.appId,timeStamp:r.timeStamp,nonceStr:r.nonceStr,package:r.package,signType:r.signType??"RSA",paySign:r.paySign}}:null}async function re(t,e){let r=t.payment?.providers??{};return Object.entries(r).filter(([,i])=>i.enabled).map(([i])=>{let s=Ae[i]??{id:i,name:i,description:""};return{...s,type:s.id}})}function T(t){return t&&typeof t=="object"?t:{}}function Ne(t){let e=T(t),r=e.enabled===!0,i=String(e.oauthCredentialSource??"").toLowerCase();return i?{enabled:r,oauthCredentialSource:i==="custom"?"custom":"nvwa_default"}:{enabled:r}}function q(t){let e=T(t),r=T(e.providers),i={};for(let[s,a]of Object.entries(r))i[s]=Ne(a);return{providers:i}}function x(t){let e=T(t);return{socialLogin:q(e.socialLogin),payment:q(e.payment)}}var Ie=["DesktopWeb","MobileWeb","AndroidApp","IosApp","HarmonyApp","WechatMiniProgram","AlipayMiniProgram","DouyinMiniProgram"];function xe(t){return Ie.includes(t)}function ie(t){return x(t.integrationProviders??{})}function se(t){let e=t.baseUrl?.trim()??"";if(!e)throw new Error("Nvwa: appConfig.baseUrl is required");let r=t.applicationCode?.trim()??"";if(!r)throw new Error("Nvwa: appConfig.applicationCode is required");let i=t.platformType?.trim()??"";if(!i)throw new Error("Nvwa: appConfig.platformType is required");if(!xe(i))throw new Error("Nvwa: appConfig.platformType is invalid");return{baseUrl:e,applicationCode:r,platformType:i}}var _=class{constructor(){this.prefix="nvwa_"}getKey(e){return`${this.prefix}${e}`}async get(e){try{let r=this.getKey(e),i=localStorage.getItem(r);if(!i)return null;let s=JSON.parse(i);return s.expires&&Date.now()>s.expires?(await this.remove(e),null):s.value}catch(r){return console.error("WebStorageService get error:",r),null}}async set(e,r,i){try{let s=this.getKey(e),a={value:r,expires:i?Date.now()+i*1e3:null,timestamp:Date.now()};localStorage.setItem(s,JSON.stringify(a))}catch(s){throw console.error("WebStorageService set error:",s),s}}async remove(e){try{let r=this.getKey(e);localStorage.removeItem(r)}catch(r){throw console.error("WebStorageService remove error:",r),r}}async clear(){try{Object.keys(localStorage).filter(i=>i.startsWith(this.prefix)).forEach(i=>{localStorage.removeItem(i)})}catch(e){throw console.error("WebStorageService clear error:",e),e}}};var ke=(t,e)=>{let r;if(typeof t=="string")r=t;else if(t&&typeof t.toString=="function")r=t.toString();else if(t?.url)r=t.url;else throw new Error("Invalid input for webFetch");let i;if(e?.headers){let a=e.headers;if(a instanceof y){let o={};a.forEach((n,c)=>{o[c]=n}),i=o}else if(Array.isArray(a)){let o=[];for(let n of a)Array.isArray(n)&&n.length>=2&&o.push([String(n[0]),String(n[1])]);i=o}else typeof a=="object"&&(i=a)}let s={method:e?.method||"GET",headers:i,body:e?.body,credentials:e?.credentials};return e?.signal&&(s.signal=e.signal),globalThis.fetch(r,s).then(async a=>{let o=a.headers.get("content-type")||"",n;if(o.includes("application/json"))n=await a.json();else{let h=await a.text();try{n=JSON.parse(h)}catch{n=h}}let c=new y;return a.headers.forEach((h,l)=>{c.set(l,h)}),new B(n,{status:a.status,statusText:a.statusText,headers:c})})},O=ke;function Ue(t){return`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(t)}`}var k={async requestPayment(t,e){let r=te(t);if(r?.kind==="redirect_url"){window.location.href=r.redirectUrl;return}if(r?.kind==="wechat_native_qr"){let s=Ue(r.codeUrl);window.open(s,"_blank","noopener,noreferrer");return}if(r?.kind==="alipay_page"){let s=window.open("","_blank");s&&(s.document.write(r.formHtml),s.document.close());return}let i=new Error("requestPayment: unsupported payParams for Desktop-web");throw e?.onFailure?.(i),i}};function ae(t){let e=async r=>await re(t,r);return{...k,getAvailableProviders:e,getProviders:e}}function Re(){if(typeof window>"u"||window===window.parent)return;let t=!1,e=new Z;function r(h){if(!h)return!1;let l=h.toLowerCase();return l.includes("/components/")||l.includes("\\components\\")}function i(h){let l=h,u=null;for(;l;){let d=l.getAttribute("data-source-location");if(d)if(r(d)){u||(u=d),l=l.parentElement;continue}else return d;l=l.parentElement}return u}let s=null;function a(h){t&&(s!==null&&cancelAnimationFrame(s),s=requestAnimationFrame(()=>{let l=h.target;if(!l||l===document.body||l===document.documentElement){e.removeHighlight();return}if(l.tagName.toLowerCase()==="img"){let p=i(l);e.highlightElement(l,p);let f={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:p,elementInfo:{tagName:l.tagName.toLowerCase(),className:l.className||"",id:l.id||""}};window.parent.postMessage(f,"*");return}let u=l,d=i(l);if(!d){let p=l.parentElement;for(;p&&p!==document.body&&p!==document.documentElement;){let f=i(p);if(f){u=p,d=f;break}p=p.parentElement}}e.highlightElement(u,d);let m={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:d,elementInfo:{tagName:u.tagName.toLowerCase(),className:u.className||"",id:u.id||""}};window.parent.postMessage(m,"*")}))}function o(){if(!t)return;e.removeHighlight();let h={type:"HOVER_INSPECTOR_ELEMENT_LEAVE"};window.parent.postMessage(h,"*")}function n(h){if(!t)return;h.preventDefault(),h.stopPropagation();let l=h.target;if(!l||l===document.body||l===document.documentElement)return;let u=i(l);e.selectElement(l,u);let d={type:"HOVER_INSPECTOR_ELEMENT_SELECT",sourceLocation:u,elementInfo:{tagName:l.tagName.toLowerCase(),className:l.className||"",id:l.id||""}};window.parent.postMessage(d,"*")}function c(h){h.data?.type==="HOVER_INSPECTOR_ENABLE"?(t=!0,document.addEventListener("mousemove",a),document.addEventListener("mouseleave",o),document.addEventListener("click",n,!0)):h.data?.type==="HOVER_INSPECTOR_DISABLE"&&(t=!1,document.removeEventListener("mousemove",a),document.removeEventListener("mouseleave",o),document.removeEventListener("click",n,!0),e.removeHighlight(),e.clearSelection())}return window.addEventListener("message",c),()=>{window.removeEventListener("message",c),document.removeEventListener("mousemove",a),document.removeEventListener("mouseleave",o),document.removeEventListener("click",n,!0),e.cleanup()}}function je(t,e){if(!t||!t.contentWindow)throw new Error("Invalid iframe element");let r={type:"HOVER_INSPECTOR_ENABLE"};t.contentWindow.postMessage(r,e)}function He(t,e){if(!t||!t.contentWindow)return;let r={type:"HOVER_INSPECTOR_DISABLE"};t.contentWindow.postMessage(r,e)}function Me(t,e,r=5e3){return new Promise((i,s)=>{if(!t||!t.contentWindow){s(new Error("Invalid iframe element"));return}let a=`source-location-${Date.now()}-${Math.random()}`,o=setTimeout(()=>{window.removeEventListener("message",n),s(new Error("Request timeout"))},r),n=h=>{h.origin===e&&h.data?.type==="GET_SOURCE_LOCATION_RESPONSE"&&h.data?.requestId===a&&(clearTimeout(o),window.removeEventListener("message",n),h.data.error?s(new Error(h.data.error)):i(h.data.sourceLocation||null))};window.addEventListener("message",n);let c={type:"GET_SOURCE_LOCATION_REQUEST",requestId:a};try{t.contentWindow.postMessage(c,e)}catch(h){clearTimeout(o),window.removeEventListener("message",n),s(h)}})}function We(){if(typeof window>"u"||window===window.parent)return;let t=e=>{if(e.data?.type==="GET_SOURCE_LOCATION_REQUEST")try{let i={type:"GET_SOURCE_LOCATION_RESPONSE",sourceLocation:Fe(),requestId:e.data.requestId};window.parent.postMessage(i,e.origin)}catch(r){let i={type:"GET_SOURCE_LOCATION_RESPONSE",sourceLocation:null,error:r instanceof Error?r.message:"Unknown error",requestId:e.data.requestId};window.parent.postMessage(i,e.origin)}};return window.addEventListener("message",t),()=>{window.removeEventListener("message",t)}}function Fe(){return ee("root")}var E=require("react"),U=require("react"),qe="nvwa-social-login-list",De="nvwa-social-login-button";async function Ge(t){return await t.getSocialProviderDescriptors()}function Be(t){return t?.trim()?t.trim():typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:""}function ze(t){let[e,r]=(0,E.useState)(t.providers??[]),[i,s]=(0,E.useState)(!t.providers);(0,E.useEffect)(()=>{if(t.providers){r(t.providers),s(!1);return}let n=!1;return s(!0),Ge(t.auth).then(c=>{n||r(c)}).catch(c=>{n||t.onError?.(c instanceof Error?c:new Error(String(c)))}).finally(()=>{n||s(!1)}),()=>{n=!0}},[t.auth,t.providers,t.onError]);let a=(0,E.useMemo)(()=>Be(t.returnUrl),[t.returnUrl]),o=(0,E.useMemo)(()=>e.filter(n=>n.loginKind!=="unsupported"),[e]);return i||o.length===0?null:(0,U.createElement)("div",{className:t.className??qe},...o.map(n=>{let c=async()=>{try{t.onBeforeLogin?.(n),await t.auth.startSocialLogin(n.id,{returnUrl:a,applicationCode:t.applicationCode,platformCode:t.platformCode})}catch(l){t.onError?.(l instanceof Error?l:new Error(String(l)))}},h=(0,U.createElement)("button",{key:n.id,type:"button",className:De,onClick:c},n.name);return t.onRenderButton?t.onRenderButton(n,h):h}))}var R=new _,$=class{constructor(e){this.payment=k;let{handleUnauthorized:r,appConfig:i,integrationProviders:s}=e,a=se(i);this.applicationCode=a.applicationCode,this.platformType=a.platformType,this.integrationProviders=x(s??ie(i)),this.auth=new K(a.baseUrl,{fetchImpl:O,storage:R,integrationProviders:this.integrationProviders,applicationCode:this.applicationCode}),this.httpClient=new V(R,O,r),this.fileStorage=new Y(a.baseUrl,this.httpClient),this.entities=X(a.baseUrl,this.httpClient),this.functions=new z(this.httpClient,a.baseUrl),this.payment=ae(this.integrationProviders)}};0&&(module.exports={SocialLoginButtons,disableIframeHoverInspector,enableIframeHoverInspector,getIframeSourceLocation,localStorage,setupIframeHoverInspector,setupIframeSourceLocationListener,webFetch});
|
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 W{constructor(e){if(this.headerMap=new Map,e){if(e instanceof W)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=`
|
|
@@ -33,4 +33,4 @@ ${l.stack}`)}else{var f;n=(f=a?.stack)!==null&&f!==void 0?f:""}let w=this.url.to
|
|
|
33
33
|
max-width: 400px;
|
|
34
34
|
word-break: break-all;
|
|
35
35
|
}
|
|
36
|
-
`,document.head.appendChild(t)}createTooltip(){return this.tooltip?this.tooltip:(this.tooltip=document.createElement("div"),this.tooltip.id="__nvwa-inspector-tooltip",document.body.appendChild(this.tooltip),this.tooltip)}createOverlay(t){let e=document.createElement("div");return e.className=`__nvwa-inspector-overlay __nvwa-inspector-overlay-${t}`,document.body.appendChild(e),e}updateOverlayPosition(t,e){if(!e.isConnected)return;let r=e.getBoundingClientRect(),i=window.scrollX||window.pageXOffset,s=window.scrollY||window.pageYOffset;r.width>0&&r.height>0?(t.style.left=`${r.left+i}px`,t.style.top=`${r.top+s}px`,t.style.width=`${r.width}px`,t.style.height=`${r.height}px`,t.style.display="block"):t.style.display="none"}removeOverlay(t){t&&t.parentNode&&t.parentNode.removeChild(t)}highlightElement(t,e){if(!t.isConnected)return;if(this.hoverElement===t&&this.hoverOverlay){this.updateOverlayPosition(this.hoverOverlay,t);let o=this.createTooltip();e?o.textContent=e:o.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,o.style.display="block";let n=t.getBoundingClientRect();o.style.left=`${n.left+window.scrollX}px`,o.style.top=`${n.top+window.scrollY-o.offsetHeight-8}px`,n.top<o.offsetHeight+8&&(o.style.top=`${n.bottom+window.scrollY+8}px`);return}this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null);let r=this.createOverlay("hover");this.updateOverlayPosition(r,t),this.hoverOverlay=r,this.hoverElement=t;let i=()=>{this.hoverOverlay&&this.hoverElement&&this.hoverElement.isConnected&&this.updateOverlayPosition(this.hoverOverlay,this.hoverElement)};this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler)),this.hoverUpdateHandler=i,window.addEventListener("scroll",i,!0),window.addEventListener("resize",i);let s=this.createTooltip();e?s.textContent=e:s.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,s.style.display="block";let a=t.getBoundingClientRect();s.style.left=`${a.left+window.scrollX}px`,s.style.top=`${a.top+window.scrollY-s.offsetHeight-8}px`,a.top<s.offsetHeight+8&&(s.style.top=`${a.bottom+window.scrollY+8}px`)}selectElement(t,e){if(!t.isConnected)return;if(this.selectedElement===t&&this.selectedOverlay){this.updateOverlayPosition(this.selectedOverlay,t);return}this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null);let r=this.createOverlay("selected");this.updateOverlayPosition(r,t),this.selectedOverlay=r,this.selectedElement=t;let i=()=>{this.selectedOverlay&&this.selectedElement&&this.selectedElement.isConnected&&this.updateOverlayPosition(this.selectedOverlay,this.selectedElement)};this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler)),this.selectedUpdateHandler=i,window.addEventListener("scroll",i,!0),window.addEventListener("resize",i)}removeHighlight(){this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null),this.hoverElement&&(this.hoverElement=null),this.tooltip&&(this.tooltip.style.display="none"),this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler),this.hoverUpdateHandler=null)}clearSelection(){this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null),this.selectedElement&&(this.selectedElement=null),this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler),this.selectedUpdateHandler=null)}cleanup(){this.removeHighlight(),this.clearSelection(),this.tooltip&&this.tooltip.parentNode&&(this.tooltip.parentNode.removeChild(this.tooltip),this.tooltip=null);let t=document.getElementById("__nvwa-inspector-overlay-style");t&&t.parentNode&&t.parentNode.removeChild(t)}};function Q(t="root"){if(typeof document>"u")return null;let e=document.getElementById(t)||document.body;if(!e)return null;let r=e.querySelector("[data-source-location]");if(r){let i=r.getAttribute("data-source-location");if(i)return i}if(e.firstElementChild){let i=e.firstElementChild.getAttribute("data-source-location");if(i)return i}return null}var Oe={"wechat-pay":{id:"wechat-pay",name:"WeChat Pay",description:"WeChat payment for web and miniapp."},wechat_partner:{id:"wechat_partner",name:"WeChat Partner",description:"WeChat partner merchant onboarding."},alipay:{id:"alipay",name:"Alipay",description:"Alipay payment."},"alipay-miniprogram":{id:"alipay-miniprogram",name:"Alipay Mini Program",description:"Alipay mini program payment."},stripe:{id:"stripe",name:"Stripe",description:"Stripe payment."}};function X(t){let e=t;if(typeof e.kind=="string")return e;if(typeof e.tradeNO=="string")return{kind:"alipay_miniprogram",tradeNO:e.tradeNO};if(typeof e.clientSecret=="string")return{kind:"stripe_client_secret",clientSecret:e.clientSecret};if(typeof e.redirectUrl=="string")return{kind:"redirect_url",redirectUrl:e.redirectUrl};if(typeof e.formHtml=="string")return{kind:"alipay_page",formHtml:e.formHtml};if(typeof e.codeUrl=="string")return{kind:"wechat_native_qr",codeUrl:e.codeUrl};let r=e.jsapiPayParams??e;return typeof r.timeStamp=="string"&&typeof r.nonceStr=="string"&&typeof r.package=="string"&&typeof r.paySign=="string"&&typeof r.appId=="string"?{kind:"wechat_jsapi",mode:"jsapi",jsapiPayParams:{appId:r.appId,timeStamp:r.timeStamp,nonceStr:r.nonceStr,package:r.package,signType:r.signType??"RSA",paySign:r.paySign}}:null}async function Z(t,e){let r=t.payment?.providers??{};return Object.entries(r).filter(([,i])=>i.enabled).map(([i])=>{let s=Oe[i]??{id:i,name:i,description:""};return{...s,type:s.id}})}function C(t){return t&&typeof t=="object"?t:{}}function Ce(t){let e=C(t),r=e.enabled===!0,i=String(e.oauthCredentialSource??"").toLowerCase();return i?{enabled:r,oauthCredentialSource:i==="custom"?"custom":"nvwa_default"}:{enabled:r}}function W(t){let e=C(t),r=C(e.providers),i={};for(let[s,a]of Object.entries(r))i[s]=Ce(a);return{providers:i}}function N(t){let e=C(t);return{socialLogin:W(e.socialLogin),payment:W(e.payment)}}function ee(t){return N(t.integrationProviders??{})}function te(t){let e=t.baseUrl?.trim()??"";if(!e)throw new Error("Nvwa: appConfig.baseUrl is required");let r=t.applicationCode?.trim()??"";if(!r)throw new Error("Nvwa: appConfig.applicationCode is required");let i=t.platformType?.trim()??"";if(!i)throw new Error("Nvwa: appConfig.platformType is required");return{baseUrl:e,applicationCode:r,platformType:i}}var T=class{constructor(){this.prefix="nvwa_"}getKey(e){return`${this.prefix}${e}`}async get(e){try{let r=this.getKey(e),i=localStorage.getItem(r);if(!i)return null;let s=JSON.parse(i);return s.expires&&Date.now()>s.expires?(await this.remove(e),null):s.value}catch(r){return console.error("WebStorageService get error:",r),null}}async set(e,r,i){try{let s=this.getKey(e),a={value:r,expires:i?Date.now()+i*1e3:null,timestamp:Date.now()};localStorage.setItem(s,JSON.stringify(a))}catch(s){throw console.error("WebStorageService set error:",s),s}}async remove(e){try{let r=this.getKey(e);localStorage.removeItem(r)}catch(r){throw console.error("WebStorageService remove error:",r),r}}async clear(){try{Object.keys(localStorage).filter(i=>i.startsWith(this.prefix)).forEach(i=>{localStorage.removeItem(i)})}catch(e){throw console.error("WebStorageService clear error:",e),e}}};var Te=(t,e)=>{let r;if(typeof t=="string")r=t;else if(t&&typeof t.toString=="function")r=t.toString();else if(t?.url)r=t.url;else throw new Error("Invalid input for webFetch");let i;if(e?.headers){let a=e.headers;if(a instanceof y){let o={};a.forEach((n,c)=>{o[c]=n}),i=o}else if(Array.isArray(a)){let o=[];for(let n of a)Array.isArray(n)&&n.length>=2&&o.push([String(n[0]),String(n[1])]);i=o}else typeof a=="object"&&(i=a)}let s={method:e?.method||"GET",headers:i,body:e?.body,credentials:e?.credentials};return e?.signal&&(s.signal=e.signal),globalThis.fetch(r,s).then(async a=>{let o=a.headers.get("content-type")||"",n;if(o.includes("application/json"))n=await a.json();else{let h=await a.text();try{n=JSON.parse(h)}catch{n=h}}let c=new y;return a.headers.forEach((h,l)=>{c.set(l,h)}),new q(n,{status:a.status,statusText:a.statusText,headers:c})})},_=Te;function _e(t){return`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(t)}`}var I={async requestPayment(t,e){let r=X(t);if(r?.kind==="redirect_url"){window.location.href=r.redirectUrl;return}if(r?.kind==="wechat_native_qr"){let s=_e(r.codeUrl);window.open(s,"_blank","noopener,noreferrer");return}if(r?.kind==="alipay_page"){let s=window.open("","_blank");s&&(s.document.write(r.formHtml),s.document.close());return}let i=new Error("requestPayment: unsupported payParams for Desktop-web");throw e?.onFailure?.(i),i}};function re(t){let e=async r=>await Z(t,r);return{...I,getAvailableProviders:e,getProviders:e}}function ct(){if(typeof window>"u"||window===window.parent)return;let t=!1,e=new Y;function r(h){if(!h)return!1;let l=h.toLowerCase();return l.includes("/components/")||l.includes("\\components\\")}function i(h){let l=h,u=null;for(;l;){let d=l.getAttribute("data-source-location");if(d)if(r(d)){u||(u=d),l=l.parentElement;continue}else return d;l=l.parentElement}return u}let s=null;function a(h){t&&(s!==null&&cancelAnimationFrame(s),s=requestAnimationFrame(()=>{let l=h.target;if(!l||l===document.body||l===document.documentElement){e.removeHighlight();return}if(l.tagName.toLowerCase()==="img"){let p=i(l);e.highlightElement(l,p);let f={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:p,elementInfo:{tagName:l.tagName.toLowerCase(),className:l.className||"",id:l.id||""}};window.parent.postMessage(f,"*");return}let u=l,d=i(l);if(!d){let p=l.parentElement;for(;p&&p!==document.body&&p!==document.documentElement;){let f=i(p);if(f){u=p,d=f;break}p=p.parentElement}}e.highlightElement(u,d);let m={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:d,elementInfo:{tagName:u.tagName.toLowerCase(),className:u.className||"",id:u.id||""}};window.parent.postMessage(m,"*")}))}function o(){if(!t)return;e.removeHighlight();let h={type:"HOVER_INSPECTOR_ELEMENT_LEAVE"};window.parent.postMessage(h,"*")}function n(h){if(!t)return;h.preventDefault(),h.stopPropagation();let l=h.target;if(!l||l===document.body||l===document.documentElement)return;let u=i(l);e.selectElement(l,u);let d={type:"HOVER_INSPECTOR_ELEMENT_SELECT",sourceLocation:u,elementInfo:{tagName:l.tagName.toLowerCase(),className:l.className||"",id:l.id||""}};window.parent.postMessage(d,"*")}function c(h){h.data?.type==="HOVER_INSPECTOR_ENABLE"?(t=!0,document.addEventListener("mousemove",a),document.addEventListener("mouseleave",o),document.addEventListener("click",n,!0)):h.data?.type==="HOVER_INSPECTOR_DISABLE"&&(t=!1,document.removeEventListener("mousemove",a),document.removeEventListener("mouseleave",o),document.removeEventListener("click",n,!0),e.removeHighlight(),e.clearSelection())}return window.addEventListener("message",c),()=>{window.removeEventListener("message",c),document.removeEventListener("mousemove",a),document.removeEventListener("mouseleave",o),document.removeEventListener("click",n,!0),e.cleanup()}}function ut(t,e){if(!t||!t.contentWindow)throw new Error("Invalid iframe element");let r={type:"HOVER_INSPECTOR_ENABLE"};t.contentWindow.postMessage(r,e)}function dt(t,e){if(!t||!t.contentWindow)return;let r={type:"HOVER_INSPECTOR_DISABLE"};t.contentWindow.postMessage(r,e)}function pt(t,e,r=5e3){return new Promise((i,s)=>{if(!t||!t.contentWindow){s(new Error("Invalid iframe element"));return}let a=`source-location-${Date.now()}-${Math.random()}`,o=setTimeout(()=>{window.removeEventListener("message",n),s(new Error("Request timeout"))},r),n=h=>{h.origin===e&&h.data?.type==="GET_SOURCE_LOCATION_RESPONSE"&&h.data?.requestId===a&&(clearTimeout(o),window.removeEventListener("message",n),h.data.error?s(new Error(h.data.error)):i(h.data.sourceLocation||null))};window.addEventListener("message",n);let c={type:"GET_SOURCE_LOCATION_REQUEST",requestId:a};try{t.contentWindow.postMessage(c,e)}catch(h){clearTimeout(o),window.removeEventListener("message",n),s(h)}})}function mt(){if(typeof window>"u"||window===window.parent)return;let t=e=>{if(e.data?.type==="GET_SOURCE_LOCATION_REQUEST")try{let i={type:"GET_SOURCE_LOCATION_RESPONSE",sourceLocation:$e(),requestId:e.data.requestId};window.parent.postMessage(i,e.origin)}catch(r){let i={type:"GET_SOURCE_LOCATION_RESPONSE",sourceLocation:null,error:r instanceof Error?r.message:"Unknown error",requestId:e.data.requestId};window.parent.postMessage(i,e.origin)}};return window.addEventListener("message",t),()=>{window.removeEventListener("message",t)}}function $e(){return Q("root")}import{useEffect as Ae,useMemo as ie,useState as se}from"react";import{createElement as ae}from"react";var Ne="nvwa-social-login-list",Ie="nvwa-social-login-button";async function xe(t){return await t.getSocialProviderDescriptors()}function ke(t){return t?.trim()?t.trim():typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:""}function vt(t){let[e,r]=se(t.providers??[]),[i,s]=se(!t.providers);Ae(()=>{if(t.providers){r(t.providers),s(!1);return}let n=!1;return s(!0),xe(t.auth).then(c=>{n||r(c)}).catch(c=>{n||t.onError?.(c instanceof Error?c:new Error(String(c)))}).finally(()=>{n||s(!1)}),()=>{n=!0}},[t.auth,t.providers,t.onError]);let a=ie(()=>ke(t.returnUrl),[t.returnUrl]),o=ie(()=>e.filter(n=>n.loginKind!=="unsupported"),[e]);return i||o.length===0?null:ae("div",{className:t.className??Ne},...o.map(n=>{let c=async()=>{try{t.onBeforeLogin?.(n),await t.auth.startSocialLogin(n.id,{returnUrl:a,applicationCode:t.applicationCode,platformCode:t.platformCode})}catch(l){t.onError?.(l instanceof Error?l:new Error(String(l)))}},h=ae("button",{key:n.id,type:"button",className:Ie,onClick:c},n.name);return t.onRenderButton?t.onRenderButton(n,h):h}))}var ne=new T,x=class{constructor(e){this.endpointType="Desktop-web";this.payment=I;let{handleUnauthorized:r,appConfig:i,integrationProviders:s}=e,a=te(i);this.applicationCode=a.applicationCode,this.platformType=a.platformType,this.integrationProviders=N(s??ee(i)),this.auth=new B(a.baseUrl,{fetchImpl:_,storage:ne,integrationProviders:this.integrationProviders,applicationCode:this.applicationCode}),this.httpClient=new z(ne,_,r),this.fileStorage=new J(a.baseUrl,this.httpClient),this.entities=V(a.baseUrl,this.httpClient),this.functions=new D(this.httpClient,a.baseUrl),this.payment=re(this.integrationProviders)}};export{vt as SocialLoginButtons,x as default,dt as disableIframeHoverInspector,ut as enableIframeHoverInspector,pt as getIframeSourceLocation,ne as localStorage,ct as setupIframeHoverInspector,mt as setupIframeSourceLocationListener,_ as webFetch};
|
|
36
|
+
`,document.head.appendChild(t)}createTooltip(){return this.tooltip?this.tooltip:(this.tooltip=document.createElement("div"),this.tooltip.id="__nvwa-inspector-tooltip",document.body.appendChild(this.tooltip),this.tooltip)}createOverlay(t){let e=document.createElement("div");return e.className=`__nvwa-inspector-overlay __nvwa-inspector-overlay-${t}`,document.body.appendChild(e),e}updateOverlayPosition(t,e){if(!e.isConnected)return;let r=e.getBoundingClientRect(),i=window.scrollX||window.pageXOffset,s=window.scrollY||window.pageYOffset;r.width>0&&r.height>0?(t.style.left=`${r.left+i}px`,t.style.top=`${r.top+s}px`,t.style.width=`${r.width}px`,t.style.height=`${r.height}px`,t.style.display="block"):t.style.display="none"}removeOverlay(t){t&&t.parentNode&&t.parentNode.removeChild(t)}highlightElement(t,e){if(!t.isConnected)return;if(this.hoverElement===t&&this.hoverOverlay){this.updateOverlayPosition(this.hoverOverlay,t);let o=this.createTooltip();e?o.textContent=e:o.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,o.style.display="block";let n=t.getBoundingClientRect();o.style.left=`${n.left+window.scrollX}px`,o.style.top=`${n.top+window.scrollY-o.offsetHeight-8}px`,n.top<o.offsetHeight+8&&(o.style.top=`${n.bottom+window.scrollY+8}px`);return}this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null);let r=this.createOverlay("hover");this.updateOverlayPosition(r,t),this.hoverOverlay=r,this.hoverElement=t;let i=()=>{this.hoverOverlay&&this.hoverElement&&this.hoverElement.isConnected&&this.updateOverlayPosition(this.hoverOverlay,this.hoverElement)};this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler)),this.hoverUpdateHandler=i,window.addEventListener("scroll",i,!0),window.addEventListener("resize",i);let s=this.createTooltip();e?s.textContent=e:s.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,s.style.display="block";let a=t.getBoundingClientRect();s.style.left=`${a.left+window.scrollX}px`,s.style.top=`${a.top+window.scrollY-s.offsetHeight-8}px`,a.top<s.offsetHeight+8&&(s.style.top=`${a.bottom+window.scrollY+8}px`)}selectElement(t,e){if(!t.isConnected)return;if(this.selectedElement===t&&this.selectedOverlay){this.updateOverlayPosition(this.selectedOverlay,t);return}this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null);let r=this.createOverlay("selected");this.updateOverlayPosition(r,t),this.selectedOverlay=r,this.selectedElement=t;let i=()=>{this.selectedOverlay&&this.selectedElement&&this.selectedElement.isConnected&&this.updateOverlayPosition(this.selectedOverlay,this.selectedElement)};this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler)),this.selectedUpdateHandler=i,window.addEventListener("scroll",i,!0),window.addEventListener("resize",i)}removeHighlight(){this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null),this.hoverElement&&(this.hoverElement=null),this.tooltip&&(this.tooltip.style.display="none"),this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler),this.hoverUpdateHandler=null)}clearSelection(){this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null),this.selectedElement&&(this.selectedElement=null),this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler),this.selectedUpdateHandler=null)}cleanup(){this.removeHighlight(),this.clearSelection(),this.tooltip&&this.tooltip.parentNode&&(this.tooltip.parentNode.removeChild(this.tooltip),this.tooltip=null);let t=document.getElementById("__nvwa-inspector-overlay-style");t&&t.parentNode&&t.parentNode.removeChild(t)}};function Q(t="root"){if(typeof document>"u")return null;let e=document.getElementById(t)||document.body;if(!e)return null;let r=e.querySelector("[data-source-location]");if(r){let i=r.getAttribute("data-source-location");if(i)return i}if(e.firstElementChild){let i=e.firstElementChild.getAttribute("data-source-location");if(i)return i}return null}var Oe={"wechat-pay":{id:"wechat-pay",name:"WeChat Pay",description:"WeChat payment for web and miniapp."},wechat_partner:{id:"wechat_partner",name:"WeChat Partner",description:"WeChat partner merchant onboarding."},alipay:{id:"alipay",name:"Alipay",description:"Alipay payment."},"alipay-miniprogram":{id:"alipay-miniprogram",name:"Alipay Mini Program",description:"Alipay mini program payment."},stripe:{id:"stripe",name:"Stripe",description:"Stripe payment."}};function X(t){let e=t;if(typeof e.kind=="string")return e;if(typeof e.tradeNO=="string")return{kind:"alipay_miniprogram",tradeNO:e.tradeNO};if(typeof e.clientSecret=="string")return{kind:"stripe_client_secret",clientSecret:e.clientSecret};if(typeof e.redirectUrl=="string")return{kind:"redirect_url",redirectUrl:e.redirectUrl};if(typeof e.formHtml=="string")return{kind:"alipay_page",formHtml:e.formHtml};if(typeof e.codeUrl=="string")return{kind:"wechat_native_qr",codeUrl:e.codeUrl};let r=e.jsapiPayParams??e;return typeof r.timeStamp=="string"&&typeof r.nonceStr=="string"&&typeof r.package=="string"&&typeof r.paySign=="string"&&typeof r.appId=="string"?{kind:"wechat_jsapi",mode:"jsapi",jsapiPayParams:{appId:r.appId,timeStamp:r.timeStamp,nonceStr:r.nonceStr,package:r.package,signType:r.signType??"RSA",paySign:r.paySign}}:null}async function Z(t,e){let r=t.payment?.providers??{};return Object.entries(r).filter(([,i])=>i.enabled).map(([i])=>{let s=Oe[i]??{id:i,name:i,description:""};return{...s,type:s.id}})}function C(t){return t&&typeof t=="object"?t:{}}function Ce(t){let e=C(t),r=e.enabled===!0,i=String(e.oauthCredentialSource??"").toLowerCase();return i?{enabled:r,oauthCredentialSource:i==="custom"?"custom":"nvwa_default"}:{enabled:r}}function M(t){let e=C(t),r=C(e.providers),i={};for(let[s,a]of Object.entries(r))i[s]=Ce(a);return{providers:i}}function N(t){let e=C(t);return{socialLogin:M(e.socialLogin),payment:M(e.payment)}}var Te=["DesktopWeb","MobileWeb","AndroidApp","IosApp","HarmonyApp","WechatMiniProgram","AlipayMiniProgram","DouyinMiniProgram"];function _e(t){return Te.includes(t)}function ee(t){return N(t.integrationProviders??{})}function te(t){let e=t.baseUrl?.trim()??"";if(!e)throw new Error("Nvwa: appConfig.baseUrl is required");let r=t.applicationCode?.trim()??"";if(!r)throw new Error("Nvwa: appConfig.applicationCode is required");let i=t.platformType?.trim()??"";if(!i)throw new Error("Nvwa: appConfig.platformType is required");if(!_e(i))throw new Error("Nvwa: appConfig.platformType is invalid");return{baseUrl:e,applicationCode:r,platformType:i}}var T=class{constructor(){this.prefix="nvwa_"}getKey(e){return`${this.prefix}${e}`}async get(e){try{let r=this.getKey(e),i=localStorage.getItem(r);if(!i)return null;let s=JSON.parse(i);return s.expires&&Date.now()>s.expires?(await this.remove(e),null):s.value}catch(r){return console.error("WebStorageService get error:",r),null}}async set(e,r,i){try{let s=this.getKey(e),a={value:r,expires:i?Date.now()+i*1e3:null,timestamp:Date.now()};localStorage.setItem(s,JSON.stringify(a))}catch(s){throw console.error("WebStorageService set error:",s),s}}async remove(e){try{let r=this.getKey(e);localStorage.removeItem(r)}catch(r){throw console.error("WebStorageService remove error:",r),r}}async clear(){try{Object.keys(localStorage).filter(i=>i.startsWith(this.prefix)).forEach(i=>{localStorage.removeItem(i)})}catch(e){throw console.error("WebStorageService clear error:",e),e}}};var $e=(t,e)=>{let r;if(typeof t=="string")r=t;else if(t&&typeof t.toString=="function")r=t.toString();else if(t?.url)r=t.url;else throw new Error("Invalid input for webFetch");let i;if(e?.headers){let a=e.headers;if(a instanceof y){let o={};a.forEach((n,c)=>{o[c]=n}),i=o}else if(Array.isArray(a)){let o=[];for(let n of a)Array.isArray(n)&&n.length>=2&&o.push([String(n[0]),String(n[1])]);i=o}else typeof a=="object"&&(i=a)}let s={method:e?.method||"GET",headers:i,body:e?.body,credentials:e?.credentials};return e?.signal&&(s.signal=e.signal),globalThis.fetch(r,s).then(async a=>{let o=a.headers.get("content-type")||"",n;if(o.includes("application/json"))n=await a.json();else{let h=await a.text();try{n=JSON.parse(h)}catch{n=h}}let c=new y;return a.headers.forEach((h,l)=>{c.set(l,h)}),new q(n,{status:a.status,statusText:a.statusText,headers:c})})},_=$e;function Ae(t){return`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(t)}`}var I={async requestPayment(t,e){let r=X(t);if(r?.kind==="redirect_url"){window.location.href=r.redirectUrl;return}if(r?.kind==="wechat_native_qr"){let s=Ae(r.codeUrl);window.open(s,"_blank","noopener,noreferrer");return}if(r?.kind==="alipay_page"){let s=window.open("","_blank");s&&(s.document.write(r.formHtml),s.document.close());return}let i=new Error("requestPayment: unsupported payParams for Desktop-web");throw e?.onFailure?.(i),i}};function re(t){let e=async r=>await Z(t,r);return{...I,getAvailableProviders:e,getProviders:e}}function dt(){if(typeof window>"u"||window===window.parent)return;let t=!1,e=new Y;function r(h){if(!h)return!1;let l=h.toLowerCase();return l.includes("/components/")||l.includes("\\components\\")}function i(h){let l=h,u=null;for(;l;){let d=l.getAttribute("data-source-location");if(d)if(r(d)){u||(u=d),l=l.parentElement;continue}else return d;l=l.parentElement}return u}let s=null;function a(h){t&&(s!==null&&cancelAnimationFrame(s),s=requestAnimationFrame(()=>{let l=h.target;if(!l||l===document.body||l===document.documentElement){e.removeHighlight();return}if(l.tagName.toLowerCase()==="img"){let p=i(l);e.highlightElement(l,p);let f={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:p,elementInfo:{tagName:l.tagName.toLowerCase(),className:l.className||"",id:l.id||""}};window.parent.postMessage(f,"*");return}let u=l,d=i(l);if(!d){let p=l.parentElement;for(;p&&p!==document.body&&p!==document.documentElement;){let f=i(p);if(f){u=p,d=f;break}p=p.parentElement}}e.highlightElement(u,d);let m={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:d,elementInfo:{tagName:u.tagName.toLowerCase(),className:u.className||"",id:u.id||""}};window.parent.postMessage(m,"*")}))}function o(){if(!t)return;e.removeHighlight();let h={type:"HOVER_INSPECTOR_ELEMENT_LEAVE"};window.parent.postMessage(h,"*")}function n(h){if(!t)return;h.preventDefault(),h.stopPropagation();let l=h.target;if(!l||l===document.body||l===document.documentElement)return;let u=i(l);e.selectElement(l,u);let d={type:"HOVER_INSPECTOR_ELEMENT_SELECT",sourceLocation:u,elementInfo:{tagName:l.tagName.toLowerCase(),className:l.className||"",id:l.id||""}};window.parent.postMessage(d,"*")}function c(h){h.data?.type==="HOVER_INSPECTOR_ENABLE"?(t=!0,document.addEventListener("mousemove",a),document.addEventListener("mouseleave",o),document.addEventListener("click",n,!0)):h.data?.type==="HOVER_INSPECTOR_DISABLE"&&(t=!1,document.removeEventListener("mousemove",a),document.removeEventListener("mouseleave",o),document.removeEventListener("click",n,!0),e.removeHighlight(),e.clearSelection())}return window.addEventListener("message",c),()=>{window.removeEventListener("message",c),document.removeEventListener("mousemove",a),document.removeEventListener("mouseleave",o),document.removeEventListener("click",n,!0),e.cleanup()}}function pt(t,e){if(!t||!t.contentWindow)throw new Error("Invalid iframe element");let r={type:"HOVER_INSPECTOR_ENABLE"};t.contentWindow.postMessage(r,e)}function mt(t,e){if(!t||!t.contentWindow)return;let r={type:"HOVER_INSPECTOR_DISABLE"};t.contentWindow.postMessage(r,e)}function gt(t,e,r=5e3){return new Promise((i,s)=>{if(!t||!t.contentWindow){s(new Error("Invalid iframe element"));return}let a=`source-location-${Date.now()}-${Math.random()}`,o=setTimeout(()=>{window.removeEventListener("message",n),s(new Error("Request timeout"))},r),n=h=>{h.origin===e&&h.data?.type==="GET_SOURCE_LOCATION_RESPONSE"&&h.data?.requestId===a&&(clearTimeout(o),window.removeEventListener("message",n),h.data.error?s(new Error(h.data.error)):i(h.data.sourceLocation||null))};window.addEventListener("message",n);let c={type:"GET_SOURCE_LOCATION_REQUEST",requestId:a};try{t.contentWindow.postMessage(c,e)}catch(h){clearTimeout(o),window.removeEventListener("message",n),s(h)}})}function ft(){if(typeof window>"u"||window===window.parent)return;let t=e=>{if(e.data?.type==="GET_SOURCE_LOCATION_REQUEST")try{let i={type:"GET_SOURCE_LOCATION_RESPONSE",sourceLocation:Ne(),requestId:e.data.requestId};window.parent.postMessage(i,e.origin)}catch(r){let i={type:"GET_SOURCE_LOCATION_RESPONSE",sourceLocation:null,error:r instanceof Error?r.message:"Unknown error",requestId:e.data.requestId};window.parent.postMessage(i,e.origin)}};return window.addEventListener("message",t),()=>{window.removeEventListener("message",t)}}function Ne(){return Q("root")}import{useEffect as Ie,useMemo as ie,useState as se}from"react";import{createElement as ae}from"react";var xe="nvwa-social-login-list",ke="nvwa-social-login-button";async function Ue(t){return await t.getSocialProviderDescriptors()}function Re(t){return t?.trim()?t.trim():typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:""}function Et(t){let[e,r]=se(t.providers??[]),[i,s]=se(!t.providers);Ie(()=>{if(t.providers){r(t.providers),s(!1);return}let n=!1;return s(!0),Ue(t.auth).then(c=>{n||r(c)}).catch(c=>{n||t.onError?.(c instanceof Error?c:new Error(String(c)))}).finally(()=>{n||s(!1)}),()=>{n=!0}},[t.auth,t.providers,t.onError]);let a=ie(()=>Re(t.returnUrl),[t.returnUrl]),o=ie(()=>e.filter(n=>n.loginKind!=="unsupported"),[e]);return i||o.length===0?null:ae("div",{className:t.className??xe},...o.map(n=>{let c=async()=>{try{t.onBeforeLogin?.(n),await t.auth.startSocialLogin(n.id,{returnUrl:a,applicationCode:t.applicationCode,platformCode:t.platformCode})}catch(l){t.onError?.(l instanceof Error?l:new Error(String(l)))}},h=ae("button",{key:n.id,type:"button",className:ke,onClick:c},n.name);return t.onRenderButton?t.onRenderButton(n,h):h}))}var ne=new T,x=class{constructor(e){this.payment=I;let{handleUnauthorized:r,appConfig:i,integrationProviders:s}=e,a=te(i);this.applicationCode=a.applicationCode,this.platformType=a.platformType,this.integrationProviders=N(s??ee(i)),this.auth=new B(a.baseUrl,{fetchImpl:_,storage:ne,integrationProviders:this.integrationProviders,applicationCode:this.applicationCode}),this.httpClient=new z(ne,_,r),this.fileStorage=new J(a.baseUrl,this.httpClient),this.entities=V(a.baseUrl,this.httpClient),this.functions=new D(this.httpClient,a.baseUrl),this.payment=re(this.integrationProviders)}};export{Et as SocialLoginButtons,x as default,mt as disableIframeHoverInspector,pt as enableIframeHoverInspector,gt as getIframeSourceLocation,ne as localStorage,dt as setupIframeHoverInspector,ft as setupIframeSourceLocationListener,_ as webFetch};
|