@nvwa-app/sdk-web 6.45.0 → 6.47.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +3 -3
- package/dist/index.mjs +4 -4
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"use strict";var I=Object.defineProperty;var le=Object.getOwnPropertyDescriptor;var he=Object.getOwnPropertyNames;var ce=Object.prototype.hasOwnProperty;var ue=(t,e)=>{for(var r in e)I(t,r,{get:e[r],enumerable:!0})},de=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of he(e))!ce.call(t,a)&&a!==r&&I(t,a,{get:()=>e[a],enumerable:!(i=le(e,a))||i.enumerable});return t};var pe=t=>de(I({},"__esModule",{value:!0}),t);var Ve={};ue(Ve,{SocialLoginButtons:()=>Ke,default:()=>$,disableIframeHoverInspector:()=>We,enableIframeHoverInspector:()=>Me,getIframeSourceLocation:()=>Fe,localStorage:()=>R,setupIframeHoverInspector:()=>He,setupIframeSourceLocationListener:()=>qe,webFetch:()=>O});module.exports=pe(Ve);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(),a=this.headerMap.get(i);this.headerMap.set(i,a?`${a}, ${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()}},me=class B{constructor(e){if(this.params=new Map,e){if(typeof e=="string")this.parseString(e);else if(e instanceof B)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[a,s]=i.split("=");a&&this.append(decodeURIComponent(a),s?decodeURIComponent(s):"")}}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 a of i)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(a)}`);return e.join("&")}forEach(e){for(let[r,i]of this.params.entries())for(let a of i)e(a,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 a of i)e.push([r,a]);return e[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}},A=class N{constructor(e,r){let i;if(e instanceof N)i=e.href;else if(r){let s=r instanceof N?r.href:r;i=this.resolve(s,e)}else i=e;let a=this.parseUrl(i);this.href=i,this.origin=`${a.protocol}//${a.host}`,this.protocol=a.protocol,this.username=a.username,this.password=a.password,this.host=a.host,this.hostname=a.hostname,this.port=a.port,this.pathname=a.pathname,this.search=a.search,this.searchParams=new me(a.search),this.hash=a.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 s=this.parseUrl(e);return`${s.protocol}//${s.host}${r}`}let i=this.parseUrl(e),a=i.pathname.endsWith("/")?i.pathname:i.pathname+"/";return`${i.protocol}//${i.host}${a}${r}`}parseUrl(e){let r=e.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!r)throw new TypeError("Invalid URL");let i=r[2]||"",a=r[4]||"",s=r[5]||"/",o=r[7]?`?${r[7]}`:"",n=r[9]?`#${r[9]}`:"";if(!i&&!a&&!s.startsWith("/")&&!s.includes("/")&&!s.includes("."))throw new TypeError("Invalid URL");let c=a.match(/^([^@]*)@(.+)$/),h="",l="",u=a;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:s,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 G=class{constructor(t,e){this.bodyData=t,this.status=e?.status??200,this.statusText=e?.statusText??"",this.headers=ge(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 ge(t){return t?new y(t):new y}var fe=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]"}},ye=class{constructor(){this._signal=new fe}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}};function we(t){if(t!==void 0)return typeof t=="string"||t instanceof FormData||t instanceof Blob||t instanceof File||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||typeof ReadableStream<"u"&&t instanceof ReadableStream?t:typeof t=="object"&&t!==null?JSON.stringify(t):t}var 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.fetchWithAuth(r,{method:e.method||"POST",body:we(e.body),headers:e.headers})).json()}},g="nvwa_current_jwt",v="nvwa_login_token",b="nvwa_user_profile",ve="set-auth-token",be=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??be,this.storage=e.storage??null,this.credentials=e.credentials??"omit",this.integrationProviders=e.integrationProviders??{},this.defaultApplicationCode=e.applicationCode?.trim()||null,this.platformType=e.platformType,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,a=e?.returnUrl??(typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:"");switch(r.loginKind){case"google_openplatform":if(!a)throw new Error("startSocialLogin requires returnUrl for google");this.startGoogleOpenPlatformLogin(a,{applicationCode:i,platformCode:e?.platformCode});return;case"github_openplatform":if(!a)throw new Error("startSocialLogin requires returnUrl for github");this.startGithubOpenPlatformLogin(a,{applicationCode:i,platformCode:e?.platformCode});return;case"wechat_website_openplatform":if(!a)throw new Error("startSocialLogin requires returnUrl for wechat-website");this.startWechatWebsiteOpenPlatformLogin(a);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(ve)?.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:a}=await this.getToken(i??void 0);a?.token&&await this.storage.set(g,a.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 a=e?.platformCode?.trim()??"";a&&r.set("platform_code",a);let s=M(this.integrationProviders,"google");return s&&r.set("oauth_credential_source",s),`${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 s=await this.storage.get(g);s!=null&&(e.Authorization=`Bearer ${s}`)}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 a=i?JSON.parse(i):null;return!a?.token||!a.user?{error:{message:"invalid_google_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(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGoogleOpenPlatformIdentity(){try{let t={};if(this.storage){let a=await this.storage.get(g);a!=null&&(t.Authorization=`Bearer ${a}`)}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 a=e?.platformCode?.trim()??"";a&&r.set("platform_code",a);let s=M(this.integrationProviders,"github");return s&&r.set("oauth_credential_source",s),`${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 s=await this.storage.get(g);s!=null&&(e.Authorization=`Bearer ${s}`)}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 a=i?JSON.parse(i):null;return!a?.token||!a.user?{error:{message:"invalid_github_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(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGithubOpenPlatformIdentity(){try{let t={};if(this.storage){let a=await this.storage.get(g);a!=null&&(t.Authorization=`Bearer ${a}`)}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 s=await this.storage.get(g);s!=null&&(e.Authorization=`Bearer ${s}`)}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 a=i?JSON.parse(i):null;return!a?.token||!a.user?{error:{message:"invalid_wechat_website_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(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getWechatWebsiteOpenPlatformIdentity(){try{let t={};if(this.storage){let a=await this.storage.get(g);a!=null&&(t.Authorization=`Bearer ${a}`)}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 a=i?JSON.parse(i):void 0;return a&&await this.persistLogin({user:a.user,session:a.session},r),{data:a}}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 s=await this.storage.get(v)??await this.storage.get(g);s!=null&&(e.Authorization=`Bearer ${s}`)}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 a=i?JSON.parse(i):void 0;return{data:a?.token!=null?{token:a.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})}),a=await i.text();if(!i.ok)return{error:{message:a||i.statusText,status:i.status}};let s=a?JSON.parse(a):null;return!s?.token||!s.user?{error:{message:"invalid_wechat_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(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})}),a=await i.text();if(!i.ok)return{error:{message:a||i.statusText,status:i.status}};let s=a?JSON.parse(a):null;return!s?.token||!s.user?{error:{message:"invalid_alipay_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(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}:{}}),a=await i.text();if(!i.ok)return{error:{message:a||i.statusText,status:i.status}};let s=a?JSON.parse(a):null;return!s?.openid||!s.appId?{error:{message:"invalid_wechat_identity_response",status:502}}:{data:s}}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}:{}}),a=await i.text();if(!i.ok)return{error:{message:a||i.statusText,status:i.status}};let s=a?JSON.parse(a):null;return!s?.openid||!s.appId?{error:{message:"invalid_alipay_identity_response",status:502}}:{data:s}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getMiniProgramIdentity(t){let e=t?.applicationCode?.trim()||this.defaultApplicationCode||void 0;if(this.platformType==="WechatMiniProgram"){let r=await this.getWeChatOpenPlatformIdentity(e);if(!r.data)throw new Error(r.error?.message||"failed to get wechat open platform identity");return{platformType:this.platformType,appId:r.data.appId,platformUserId:r.data.openid,unionid:r.data.unionid}}else if(this.platformType==="AlipayMiniProgram"){let r=await this.getAlipayOpenPlatformIdentity(e);if(!r.data)throw new Error(r.error?.message||"failed to get wechat open platform identity");return{platformType:this.platformType,appId:r.data.appId,platformUserId:r.data.openid,unionid:r.data.unionid}}return null}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 a=i?JSON.parse(i):void 0;return{data:a?.data??a??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 a=e?.method||"GET";if((a==="POST"||a==="PUT"||a==="PATCH")&&e?.body){let o=i.get("Content-Type");(!o||o.includes("text/plain"))&&i.set("Content-Type","application/json")}let s=await this.customFetch(t,{...e,headers:i});if(s.status===401)throw this.handleUnauthorized(),new Error("\u672A\u767B\u5F55");return s}},Ee="/storage",Pe=Ee+"/generateUploadUrl",Y=class{constructor(t,e){this.baseUrl=t,this.http=e}async uploadFile(t){let e=await this.http.fetch(this.baseUrl+Pe,{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:a}=await i.json();return{url:a.split("?")[0]}}},Se=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},Le=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,a=i(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async s=>{let o=null,n=null,c=null,h=s.status,l=s.statusText;if(s.ok){var u,d;if(r.method!=="HEAD"){var m;let w=await s.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=s.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 s.text();try{o=JSON.parse(p),Array.isArray(o)&&s.status===404&&(n=[],o=null,h=200,l="OK")}catch{s.status===404&&p===""?(h=204,l="No Content"):o={message:p}}if(o&&r.shouldThrowOnError)throw new Se(o)}return{error:o,data:n,count:c,status:h,statusText:l}});return this.shouldThrowOnError||(a=a.catch(s=>{var o;let n="",c="",h="",l=s?.cause;if(l){var u,d,m,p;let oe=(u=l?.message)!==null&&u!==void 0?u:"",j=(d=l?.code)!==null&&d!==void 0?d:"";n=`${(m=s?.name)!==null&&m!==void 0?m:"FetchError"}: ${s?.message}`,n+=`
|
|
1
|
+
"use strict";var A=Object.defineProperty;var le=Object.getOwnPropertyDescriptor;var he=Object.getOwnPropertyNames;var ce=Object.prototype.hasOwnProperty;var ue=(t,e)=>{for(var r in e)A(t,r,{get:e[r],enumerable:!0})},de=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of he(e))!ce.call(t,a)&&a!==r&&A(t,a,{get:()=>e[a],enumerable:!(i=le(e,a))||i.enumerable});return t};var pe=t=>de(A({},"__esModule",{value:!0}),t);var Ve={};ue(Ve,{SocialLoginButtons:()=>Ke,default:()=>I,disableIframeHoverInspector:()=>We,enableIframeHoverInspector:()=>Me,getIframeSourceLocation:()=>Fe,localStorage:()=>R,setupIframeHoverInspector:()=>He,setupIframeSourceLocationListener:()=>qe,webFetch:()=>L});module.exports=pe(Ve);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(),a=this.headerMap.get(i);this.headerMap.set(i,a?`${a}, ${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()}},me=class B{constructor(e){if(this.params=new Map,e){if(typeof e=="string")this.parseString(e);else if(e instanceof B)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[a,s]=i.split("=");a&&this.append(decodeURIComponent(a),s?decodeURIComponent(s):"")}}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 a of i)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(a)}`);return e.join("&")}forEach(e){for(let[r,i]of this.params.entries())for(let a of i)e(a,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 a of i)e.push([r,a]);return e[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}},$=class N{constructor(e,r){let i;if(e instanceof N)i=e.href;else if(r){let s=r instanceof N?r.href:r;i=this.resolve(s,e)}else i=e;let a=this.parseUrl(i);this.href=i,this.origin=`${a.protocol}//${a.host}`,this.protocol=a.protocol,this.username=a.username,this.password=a.password,this.host=a.host,this.hostname=a.hostname,this.port=a.port,this.pathname=a.pathname,this.search=a.search,this.searchParams=new me(a.search),this.hash=a.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 s=this.parseUrl(e);return`${s.protocol}//${s.host}${r}`}let i=this.parseUrl(e),a=i.pathname.endsWith("/")?i.pathname:i.pathname+"/";return`${i.protocol}//${i.host}${a}${r}`}parseUrl(e){let r=e.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!r)throw new TypeError("Invalid URL");let i=r[2]||"",a=r[4]||"",s=r[5]||"/",o=r[7]?`?${r[7]}`:"",n=r[9]?`#${r[9]}`:"";if(!i&&!a&&!s.startsWith("/")&&!s.includes("/")&&!s.includes("."))throw new TypeError("Invalid URL");let c=a.match(/^([^@]*)@(.+)$/),h="",l="",u=a;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:s,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 G=class{constructor(t,e){this.bodyData=t,this.status=e?.status??200,this.statusText=e?.statusText??"",this.headers=ge(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 ge(t){return t?new y(t):new y}var fe=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]"}},ye=class{constructor(){this._signal=new fe}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}};function we(t){if(t!==void 0)return typeof t=="string"||t instanceof FormData||t instanceof Blob||t instanceof File||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||typeof ReadableStream<"u"&&t instanceof ReadableStream?t:typeof t=="object"&&t!==null?JSON.stringify(t):t}var 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.fetchWithAuth(r,{method:e.method||"POST",body:we(e.body),headers:e.headers})).json()}},g="nvwa_current_jwt",v="nvwa_login_token",b="nvwa_user_profile",ve="set-auth-token",be=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??be,this.storage=e.storage??null,this.credentials=e.credentials??"omit",this.integrationProviders=e.integrationProviders??{},this.defaultApplicationCode=e.applicationCode?.trim()||null,this.platformType=e.platformType,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,a=e?.returnUrl??(typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:"");switch(r.loginKind){case"google_openplatform":if(!a)throw new Error("startSocialLogin requires returnUrl for google");this.startGoogleOpenPlatformLogin(a,{applicationCode:i,platformCode:e?.platformCode});return;case"github_openplatform":if(!a)throw new Error("startSocialLogin requires returnUrl for github");this.startGithubOpenPlatformLogin(a,{applicationCode:i,platformCode:e?.platformCode});return;case"wechat_website_openplatform":if(!a)throw new Error("startSocialLogin requires returnUrl for wechat-website");this.startWechatWebsiteOpenPlatformLogin(a);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(ve)?.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:a}=await this.getToken(i??void 0);a?.token&&await this.storage.set(g,a.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 a=e?.platformCode?.trim()??"";a&&r.set("platform_code",a);let s=M(this.integrationProviders,"google");return s&&r.set("oauth_credential_source",s),`${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 s=await this.storage.get(g);s!=null&&(e.Authorization=`Bearer ${s}`)}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 a=i?JSON.parse(i):null;return!a?.token||!a.user?{error:{message:"invalid_google_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(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGoogleOpenPlatformIdentity(){try{let t={};if(this.storage){let a=await this.storage.get(g);a!=null&&(t.Authorization=`Bearer ${a}`)}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 a=e?.platformCode?.trim()??"";a&&r.set("platform_code",a);let s=M(this.integrationProviders,"github");return s&&r.set("oauth_credential_source",s),`${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 s=await this.storage.get(g);s!=null&&(e.Authorization=`Bearer ${s}`)}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 a=i?JSON.parse(i):null;return!a?.token||!a.user?{error:{message:"invalid_github_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(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGithubOpenPlatformIdentity(){try{let t={};if(this.storage){let a=await this.storage.get(g);a!=null&&(t.Authorization=`Bearer ${a}`)}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 s=await this.storage.get(g);s!=null&&(e.Authorization=`Bearer ${s}`)}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 a=i?JSON.parse(i):null;return!a?.token||!a.user?{error:{message:"invalid_wechat_website_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(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getWechatWebsiteOpenPlatformIdentity(){try{let t={};if(this.storage){let a=await this.storage.get(g);a!=null&&(t.Authorization=`Bearer ${a}`)}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 a=i?JSON.parse(i):void 0;return a&&await this.persistLogin({user:a.user,session:a.session},r),{data:a}}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 s=await this.storage.get(v)??await this.storage.get(g);s!=null&&(e.Authorization=`Bearer ${s}`)}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 a=i?JSON.parse(i):void 0;return{data:a?.token!=null?{token:a.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})}),a=await i.text();if(!i.ok)return{error:{message:a||i.statusText,status:i.status}};let s=a?JSON.parse(a):null;return!s?.token||!s.user?{error:{message:"invalid_wechat_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(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})}),a=await i.text();if(!i.ok)return{error:{message:a||i.statusText,status:i.status}};let s=a?JSON.parse(a):null;return!s?.token||!s.user?{error:{message:"invalid_alipay_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(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}:{}}),a=await i.text();if(!i.ok)return{error:{message:a||i.statusText,status:i.status}};let s=a?JSON.parse(a):null;return!s?.openid||!s.appId?{error:{message:"invalid_wechat_identity_response",status:502}}:{data:s}}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}:{}}),a=await i.text();if(!i.ok)return{error:{message:a||i.statusText,status:i.status}};let s=a?JSON.parse(a):null;return!s?.openid||!s.appId?{error:{message:"invalid_alipay_identity_response",status:502}}:{data:s}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getMiniProgramIdentity(t){let e=t?.applicationCode?.trim()||this.defaultApplicationCode||void 0;if(this.platformType==="WechatMiniProgram"){let r=await this.getWeChatOpenPlatformIdentity(e);if(!r.data)throw new Error(r.error?.message||"failed to get wechat open platform identity");return{platformType:this.platformType,appId:r.data.appId,platformUserId:r.data.openid,unionid:r.data.unionid}}else if(this.platformType==="AlipayMiniProgram"){let r=await this.getAlipayOpenPlatformIdentity(e);if(!r.data)throw new Error(r.error?.message||"failed to get wechat open platform identity");return{platformType:this.platformType,appId:r.data.appId,platformUserId:r.data.openid,unionid:r.data.unionid}}return null}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 a=i?JSON.parse(i):void 0;return{data:a?.data??a??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 a=e?.method||"GET";if((a==="POST"||a==="PUT"||a==="PATCH")&&e?.body){let o=i.get("Content-Type");(!o||o.includes("text/plain"))&&i.set("Content-Type","application/json")}let s=await this.customFetch(t,{...e,headers:i});if(s.status===401)throw this.handleUnauthorized(),new Error("\u672A\u767B\u5F55");return s}},Pe="/storage",Ee=Pe+"/generateUploadUrl",Y=class{constructor(t,e){this.baseUrl=t,this.http=e}async uploadFile(t){let e=await this.http.fetch(this.baseUrl+Ee,{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:a}=await i.json();return{url:a.split("?")[0]}}},Se=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},Oe=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,a=i(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async s=>{let o=null,n=null,c=null,h=s.status,l=s.statusText;if(s.ok){var u,d;if(r.method!=="HEAD"){var m;let w=await s.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=s.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 s.text();try{o=JSON.parse(p),Array.isArray(o)&&s.status===404&&(n=[],o=null,h=200,l="OK")}catch{s.status===404&&p===""?(h=204,l="No Content"):o={message:p}}if(o&&r.shouldThrowOnError)throw new Se(o)}return{error:o,data:n,count:c,status:h,statusText:l}});return this.shouldThrowOnError||(a=a.catch(s=>{var o;let n="",c="",h="",l=s?.cause;if(l){var u,d,m,p;let oe=(u=l?.message)!==null&&u!==void 0?u:"",j=(d=l?.code)!==null&&d!==void 0?d:"";n=`${(m=s?.name)!==null&&m!==void 0?m:"FetchError"}: ${s?.message}`,n+=`
|
|
2
2
|
|
|
3
3
|
Caused by: ${(p=l?.name)!==null&&p!==void 0?p:"Error"}: ${oe}`,j&&(n+=` (${j})`),l?.stack&&(n+=`
|
|
4
|
-
${l.stack}`)}else{var f;n=(f=s?.stack)!==null&&f!==void 0?f:""}let w=this.url.toString().length;return s?.name==="AbortError"||s?.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=s?.name)!==null&&o!==void 0?o:"FetchError"}: ${s?.message}`,details:n,hint:c,code:h},data:null,count:null,status:0,statusText:""}})),a.then(t,e)}returns(){return this}overrideTypes(){return this}},Oe=class extends Le{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:a=i}={}){let s=a?`${a}.order`:"order",o=this.url.searchParams.get(s);return this.url.searchParams.set(s,`${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 a=typeof i>"u"?"offset":`${i}.offset`,s=typeof i>"u"?"limit":`${i}.limit`;return this.url.searchParams.set(a,`${t}`),this.url.searchParams.set(s,`${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:a=!1,format:s="text"}={}){var o;let n=[t?"analyze":null,e?"verbose":null,r?"settings":null,i?"buffers":null,a?"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+${s}; for="${c}"; options=${n};`),s==="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 Oe{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 a="";i==="plain"?a="pl":i==="phrase"?a="ph":i==="websearch"&&(a="w");let s=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${a}fts${s}.${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}},Ce=class{constructor(t,{headers:e={},schema:r,fetch:i,urlLengthLimit:a=8e3}){this.url=t,this.headers=new y(e),this.schema=r,this.fetch=i,this.urlLengthLimit=a}cloneRequestState(){return{url:new A(this.url.toString()),headers:new y(this.headers)}}select(t,e){let{head:r=!1,count:i}=e??{},a=r?"HEAD":"GET",s=!1,o=(t??"*").split("").map(h=>/\s/.test(h)&&!s?"":(h==='"'&&(s=!s),h)).join(""),{url:n,headers:c}=this.cloneRequestState();return n.searchParams.set("select",o),i&&c.append("Prefer",`count=${i}`),new P({method:a,url:n,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var i;let a="POST",{url:s,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}"`);s.searchParams.set("columns",c.join(","))}}return new P({method:a,url:s,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:a=!0}={}){var s;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}`),a||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:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;let i="PATCH",{url:a,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new P({method:i,url:a,headers:s,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:a}=this.cloneRequestState();return t&&a.append("Prefer",`count=${t}`),new P({method:r,url:i,headers:a,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 Te(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 _e(t){var e=Te(t,"string");return L(e)=="symbol"?e:e+""}function $e(t,e,r){return(e=_e(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(a){return Object.getOwnPropertyDescriptor(t,a).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){$e(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 Ie=class Q{constructor(e,{headers:r={},schema:i,fetch:a,timeout:s,urlLengthLimit:o=8e3}={}){this.url=e,this.headers=new y(r),this.schemaName=i,this.urlLengthLimit=o;let n=a??globalThis.fetch;s!==void 0&&s>0?this.fetch=(c,h)=>{let l=new ye,u=setTimeout(()=>l.abort(),s),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 Ce(new A(`${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:a=!1,count:s}={}){var o;let n,c=new A(`${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||a?(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",s?`count=${s},return=minimal`:"return=minimal"):s&&d.set("Prefer",`count=${s}`),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})}},Ae="/entities",X=(t,e)=>new Ie(t+Ae,{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=s?.stack)!==null&&f!==void 0?f:""}let w=this.url.toString().length;return s?.name==="AbortError"||s?.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=s?.name)!==null&&o!==void 0?o:"FetchError"}: ${s?.message}`,details:n,hint:c,code:h},data:null,count:null,status:0,statusText:""}})),a.then(t,e)}returns(){return this}overrideTypes(){return this}},Le=class extends Oe{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:a=i}={}){let s=a?`${a}.order`:"order",o=this.url.searchParams.get(s);return this.url.searchParams.set(s,`${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 a=typeof i>"u"?"offset":`${i}.offset`,s=typeof i>"u"?"limit":`${i}.limit`;return this.url.searchParams.set(a,`${t}`),this.url.searchParams.set(s,`${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:a=!1,format:s="text"}={}){var o;let n=[t?"analyze":null,e?"verbose":null,r?"settings":null,i?"buffers":null,a?"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+${s}; for="${c}"; options=${n};`),s==="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("[,()]"),E=class extends Le{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 a="";i==="plain"?a="pl":i==="phrase"?a="ph":i==="websearch"&&(a="w");let s=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${a}fts${s}.${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}},Ce=class{constructor(t,{headers:e={},schema:r,fetch:i,urlLengthLimit:a=8e3}){this.url=t,this.headers=new y(e),this.schema=r,this.fetch=i,this.urlLengthLimit=a}cloneRequestState(){return{url:new $(this.url.toString()),headers:new y(this.headers)}}select(t,e){let{head:r=!1,count:i}=e??{},a=r?"HEAD":"GET",s=!1,o=(t??"*").split("").map(h=>/\s/.test(h)&&!s?"":(h==='"'&&(s=!s),h)).join(""),{url:n,headers:c}=this.cloneRequestState();return n.searchParams.set("select",o),i&&c.append("Prefer",`count=${i}`),new E({method:a,url:n,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var i;let a="POST",{url:s,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}"`);s.searchParams.set("columns",c.join(","))}}return new E({method:a,url:s,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:a=!0}={}){var s;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}`),a||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:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;let i="PATCH",{url:a,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new E({method:i,url:a,headers:s,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:a}=this.cloneRequestState();return t&&a.append("Prefer",`count=${t}`),new E({method:r,url:i,headers:a,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function O(t){"@babel/helpers - typeof";return O=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},O(t)}function Te(t,e){if(O(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var i=r.call(t,e||"default");if(O(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function _e(t){var e=Te(t,"string");return O(e)=="symbol"?e:e+""}function Ie(t,e,r){return(e=_e(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(a){return Object.getOwnPropertyDescriptor(t,a).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){Ie(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 Ae=class Q{constructor(e,{headers:r={},schema:i,fetch:a,timeout:s,urlLengthLimit:o=8e3}={}){this.url=e,this.headers=new y(r),this.schemaName=i,this.urlLengthLimit=o;let n=a??globalThis.fetch;s!==void 0&&s>0?this.fetch=(c,h)=>{let l=new ye,u=setTimeout(()=>l.abort(),s),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 Ce(new $(`${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:a=!1,count:s}={}){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||a?(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",s?`count=${s},return=minimal`:"return=minimal"):s&&d.set("Prefer",`count=${s}`),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})}},$e="/entities",X=(t,e)=>new Ae(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=s?.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,a=window.scrollY||window.pageYOffset;r.width>0&&r.height>0?(t.style.left=`${r.left+i}px`,t.style.top=`${r.top+a}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 a=this.createTooltip();e?a.textContent=e:a.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,a.style.display="block";let s=t.getBoundingClientRect();a.style.left=`${s.left+window.scrollX}px`,a.style.top=`${s.top+window.scrollY-a.offsetHeight-8}px`,s.top<a.offsetHeight+8&&(a.style.top=`${s.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 Ne={"wechat-pay":{id:"wechat-pay",name:"WeChat Pay",description:"WeChat payment for web and miniapp."},"wechat-platform":{id:"wechat-platform",name:"WeChat Partner",description:"WeChat partner merchant onboarding."},"alipay-web":{id:"alipay-web",name:"Alipay Web",description:"Alipay page pay (ISV)."},"alipay-mobile-web":{id:"alipay-mobile-web",name:"Alipay Mobile Web",description:"Alipay WAP pay (ISV)."},"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 a=Ne[i]??{id:i,name:i,description:""};return{...a,type:a.id}})}function T(t){return t&&typeof t=="object"?t:{}}function xe(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[a,s]of Object.entries(r))i[a]=xe(s);return{providers:i}}function x(t){let e=T(t);return{socialLogin:q(e.socialLogin),payment:q(e.payment)}}var Ue=["DesktopWeb","MobileWeb","AndroidApp","IosApp","HarmonyApp","WechatMiniProgram","AlipayMiniProgram","DouyinMiniProgram"];function ke(t){return Ue.includes(t)}async function ie(t){let{platformType:e,getMiniProgramIdentity:r}=t;if(e!=="WechatMiniProgram"&&e!=="AlipayMiniProgram")return{platformType:e};if(!r)return{platformType:e};let i=await r();return i?{platformType:i.platformType,platformUserId:i.platformUserId,appId:i.appId,unionid:i.unionid}:{platformType:e}}function ae(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(!ke(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 a=JSON.parse(i);return a.expires&&Date.now()>a.expires?(await this.remove(e),null):a.value}catch(r){return console.error("WebStorageService get error:",r),null}}async set(e,r,i){try{let a=this.getKey(e),s={value:r,expires:i?Date.now()+i*1e3:null,timestamp:Date.now()};localStorage.setItem(a,JSON.stringify(s))}catch(a){throw console.error("WebStorageService set error:",a),a}}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 Re=(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 s=e.headers;if(s instanceof y){let o={};s.forEach((n,c)=>{o[c]=n}),i=o}else if(Array.isArray(s)){let o=[];for(let n of s)Array.isArray(n)&&n.length>=2&&o.push([String(n[0]),String(n[1])]);i=o}else typeof s=="object"&&(i=s)}let a={method:e?.method||"GET",headers:i,body:e?.body,credentials:e?.credentials};return e?.signal&&(a.signal=e.signal),globalThis.fetch(r,a).then(async s=>{let o=s.headers.get("content-type")||"",n;if(o.includes("application/json"))n=await s.json();else{let h=await s.text();try{n=JSON.parse(h)}catch{n=h}}let c=new y;return s.headers.forEach((h,l)=>{c.set(l,h)}),new G(n,{status:s.status,statusText:s.statusText,headers:c})})},O=Re;function je(t){return`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(t)}`}var U={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 a=je(r.codeUrl);window.open(a,"_blank","noopener,noreferrer");return}if(r?.kind==="alipay_page"){let a=window.open("","_blank");a&&(a.document.write(r.formHtml),a.document.close());return}let i=new Error("requestPayment: unsupported payParams for Desktop-web");throw e?.onFailure?.(i),i}};function ne(t){let e=async r=>await re(t,r);return{...U,getAvailableProviders:e,getProviders:e}}function He(){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 a=null;function s(h){t&&(a!==null&&cancelAnimationFrame(a),a=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",s),document.addEventListener("mouseleave",o),document.addEventListener("click",n,!0)):h.data?.type==="HOVER_INSPECTOR_DISABLE"&&(t=!1,document.removeEventListener("mousemove",s),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",s),document.removeEventListener("mouseleave",o),document.removeEventListener("click",n,!0),e.cleanup()}}function Me(t,e){if(!t||!t.contentWindow)throw new Error("Invalid iframe element");let r={type:"HOVER_INSPECTOR_ENABLE"};t.contentWindow.postMessage(r,e)}function We(t,e){if(!t||!t.contentWindow)return;let r={type:"HOVER_INSPECTOR_DISABLE"};t.contentWindow.postMessage(r,e)}function Fe(t,e,r=5e3){return new Promise((i,a)=>{if(!t||!t.contentWindow){a(new Error("Invalid iframe element"));return}let s=`source-location-${Date.now()}-${Math.random()}`,o=setTimeout(()=>{window.removeEventListener("message",n),a(new Error("Request timeout"))},r),n=h=>{h.origin===e&&h.data?.type==="GET_SOURCE_LOCATION_RESPONSE"&&h.data?.requestId===s&&(clearTimeout(o),window.removeEventListener("message",n),h.data.error?a(new Error(h.data.error)):i(h.data.sourceLocation||null))};window.addEventListener("message",n);let c={type:"GET_SOURCE_LOCATION_REQUEST",requestId:s};try{t.contentWindow.postMessage(c,e)}catch(h){clearTimeout(o),window.removeEventListener("message",n),a(h)}})}function qe(){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:De(),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 De(){return ee("root")}var E=require("react"),k=require("react"),Be="nvwa-social-login-list",Ge="nvwa-social-login-button";async function ze(t){return await t.getSocialProviderDescriptors()}function Je(t){return t?.trim()?t.trim():typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:""}function Ke(t){let[e,r]=(0,E.useState)(t.providers??[]),[i,a]=(0,E.useState)(!t.providers);(0,E.useEffect)(()=>{if(t.providers){r(t.providers),a(!1);return}let n=!1;return a(!0),ze(t.auth).then(c=>{n||r(c)}).catch(c=>{n||t.onError?.(c instanceof Error?c:new Error(String(c)))}).finally(()=>{n||a(!1)}),()=>{n=!0}},[t.auth,t.providers,t.onError]);let s=(0,E.useMemo)(()=>Je(t.returnUrl),[t.returnUrl]),o=(0,E.useMemo)(()=>e.filter(n=>n.loginKind!=="unsupported"),[e]);return i||o.length===0?null:(0,k.createElement)("div",{className:t.className??Be},...o.map(n=>{let c=async()=>{try{t.onBeforeLogin?.(n),await t.auth.startSocialLogin(n.id,{returnUrl:s,applicationCode:t.applicationCode,platformCode:t.platformCode})}catch(l){t.onError?.(l instanceof Error?l:new Error(String(l)))}},h=(0,k.createElement)("button",{key:n.id,type:"button",className:Ge,onClick:c},n.name);return t.onRenderButton?t.onRenderButton(n,h):h}))}var R=new _,$=class{constructor(e){this.payment=U;let{handleUnauthorized:r,appConfig:i,integrationProviders:a}=e,s=se(i);this.applicationCode=s.applicationCode,this.platformType=s.platformType,this.integrationProviders=x(a??ae(i)),this.auth=new K(s.baseUrl,{fetchImpl:O,storage:R,integrationProviders:this.integrationProviders,applicationCode:this.applicationCode,platformType:s.platformType}),this.httpClient=new V(R,O,r),this.fileStorage=new Y(s.baseUrl,this.httpClient),this.entities=X(s.baseUrl,this.httpClient),this.functions=new z(this.httpClient,s.baseUrl);let o=ne(this.integrationProviders);this.payment={...o,collectPaymentClientContext:()=>ie({platformType:this.platformType,getMiniProgramIdentity:()=>this.auth.getMiniProgramIdentity()})}}};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,a=window.scrollY||window.pageYOffset;r.width>0&&r.height>0?(t.style.left=`${r.left+i}px`,t.style.top=`${r.top+a}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 a=this.createTooltip();e?a.textContent=e:a.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,a.style.display="block";let s=t.getBoundingClientRect();a.style.left=`${s.left+window.scrollX}px`,a.style.top=`${s.top+window.scrollY-a.offsetHeight-8}px`,s.top<a.offsetHeight+8&&(a.style.top=`${s.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 Ne={"wechat-pay":{id:"wechat-pay",name:"WeChat Pay",description:"WeChat payment for web and miniapp."},"wechat-platform":{id:"wechat-platform",name:"WeChat Partner",description:"WeChat partner merchant onboarding."},"alipay-web":{id:"alipay-web",name:"Alipay Web",description:"Alipay page pay (ISV)."},"alipay-mobile-web":{id:"alipay-mobile-web",name:"Alipay Mobile Web",description:"Alipay WAP pay (ISV)."},"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 a=Ne[i]??{id:i,name:i,description:""};return{...a,type:a.id}})}function T(t){return t&&typeof t=="object"?t:{}}function xe(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[a,s]of Object.entries(r))i[a]=xe(s);return{providers:i}}function x(t){let e=T(t);return{socialLogin:q(e.socialLogin),payment:q(e.payment)}}var ke=["DesktopWeb","MobileWeb","AndroidApp","IosApp","HarmonyApp","WechatMiniProgram","AlipayMiniProgram","DouyinMiniProgram"];function Ue(t){return ke.includes(t)}async function ie(t){let{platformType:e,getMiniProgramIdentity:r}=t;if(e!=="WechatMiniProgram"&&e!=="AlipayMiniProgram")return{platformType:e};if(!r)return{platformType:e};let i=await r();return i?{platformType:i.platformType,platformUserId:i.platformUserId,appId:i.appId,unionid:i.unionid}:{platformType:e}}function ae(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(!Ue(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 a=JSON.parse(i);return a.expires&&Date.now()>a.expires?(await this.remove(e),null):a.value}catch(r){return console.error("WebStorageService get error:",r),null}}async set(e,r,i){try{let a=this.getKey(e),s={value:r,expires:i?Date.now()+i*1e3:null,timestamp:Date.now()};localStorage.setItem(a,JSON.stringify(s))}catch(a){throw console.error("WebStorageService set error:",a),a}}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 Re=(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 s=e.headers;if(s instanceof y){let o={};s.forEach((n,c)=>{o[c]=n}),i=o}else if(Array.isArray(s)){let o=[];for(let n of s)Array.isArray(n)&&n.length>=2&&o.push([String(n[0]),String(n[1])]);i=o}else typeof s=="object"&&(i=s)}let a={method:e?.method||"GET",headers:i,body:e?.body,credentials:e?.credentials};return e?.signal&&(a.signal=e.signal),globalThis.fetch(r,a).then(async s=>{let o=s.headers.get("content-type")||"",n;if(o.includes("application/json"))n=await s.json();else{let h=await s.text();try{n=JSON.parse(h)}catch{n=h}}let c=new y;return s.headers.forEach((h,l)=>{c.set(l,h)}),new G(n,{status:s.status,statusText:s.statusText,headers:c})})},L=Re;function je(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 a=je(r.codeUrl);window.open(a,"_blank","noopener,noreferrer");return}if(r?.kind==="alipay_page"){let a=window.open("","_blank");a&&(a.document.write(r.formHtml),a.document.close());return}let i=new Error("requestPayment: unsupported payParams for Desktop-web");throw e?.onFailure?.(i),i}};function ne(t){let e=async r=>await re(t,r);return{...k,getAvailableProviders:e,getProviders:e}}function He(){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 a=null;function s(h){t&&(a!==null&&cancelAnimationFrame(a),a=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",s),document.addEventListener("mouseleave",o),document.addEventListener("click",n,!0)):h.data?.type==="HOVER_INSPECTOR_DISABLE"&&(t=!1,document.removeEventListener("mousemove",s),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",s),document.removeEventListener("mouseleave",o),document.removeEventListener("click",n,!0),e.cleanup()}}function Me(t,e){if(!t||!t.contentWindow)throw new Error("Invalid iframe element");let r={type:"HOVER_INSPECTOR_ENABLE"};t.contentWindow.postMessage(r,e)}function We(t,e){if(!t||!t.contentWindow)return;let r={type:"HOVER_INSPECTOR_DISABLE"};t.contentWindow.postMessage(r,e)}function Fe(t,e,r=5e3){return new Promise((i,a)=>{if(!t||!t.contentWindow){a(new Error("Invalid iframe element"));return}let s=`source-location-${Date.now()}-${Math.random()}`,o=setTimeout(()=>{window.removeEventListener("message",n),a(new Error("Request timeout"))},r),n=h=>{h.origin===e&&h.data?.type==="GET_SOURCE_LOCATION_RESPONSE"&&h.data?.requestId===s&&(clearTimeout(o),window.removeEventListener("message",n),h.data.error?a(new Error(h.data.error)):i(h.data.sourceLocation||null))};window.addEventListener("message",n);let c={type:"GET_SOURCE_LOCATION_REQUEST",requestId:s};try{t.contentWindow.postMessage(c,e)}catch(h){clearTimeout(o),window.removeEventListener("message",n),a(h)}})}function qe(){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:De(),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 De(){return ee("root")}var P=require("react"),U=require("react"),Be="nvwa-social-login-list",Ge="nvwa-social-login-button";async function ze(t){return await t.getSocialProviderDescriptors()}function Je(t){return t?.trim()?t.trim():typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:""}function Ke(t){let[e,r]=(0,P.useState)(t.providers??[]),[i,a]=(0,P.useState)(!t.providers);(0,P.useEffect)(()=>{if(t.providers){r(t.providers),a(!1);return}let n=!1;return a(!0),ze(t.auth).then(c=>{n||r(c)}).catch(c=>{n||t.onError?.(c instanceof Error?c:new Error(String(c)))}).finally(()=>{n||a(!1)}),()=>{n=!0}},[t.auth,t.providers,t.onError]);let s=(0,P.useMemo)(()=>Je(t.returnUrl),[t.returnUrl]),o=(0,P.useMemo)(()=>e.filter(n=>n.loginKind!=="unsupported"),[e]);return i||o.length===0?null:(0,U.createElement)("div",{className:t.className??Be},...o.map(n=>{let c=async()=>{try{t.onBeforeLogin?.(n),await t.auth.startSocialLogin(n.id,{returnUrl:s,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:Ge,onClick:c},n.name);return t.onRenderButton?t.onRenderButton(n,h):h}))}var R=new _,I=class{constructor(e){this.payment=k;let{handleUnauthorized:r,appConfig:i,integrationProviders:a}=e,s=se(i);this.applicationCode=s.applicationCode,this.platformType=s.platformType,this.integrationProviders=x(a??ae(i)),this.auth=new K(s.baseUrl,{fetchImpl:L,storage:R,integrationProviders:this.integrationProviders,applicationCode:this.applicationCode,platformType:s.platformType}),this.httpClient=new V(R,L,r),this.fileStorage=new Y(s.baseUrl,this.httpClient),this.entities=X(s.baseUrl,this.httpClient),this.functions=new z(this.httpClient,s.baseUrl);let o=ne(this.integrationProviders);this.payment={...o,collectPaymentClientContext:()=>ie({platformType:this.platformType,getMiniProgramIdentity:()=>this.auth.getMiniProgramIdentity()})}}};0&&(module.exports={SocialLoginButtons,disableIframeHoverInspector,enableIframeHoverInspector,getIframeSourceLocation,localStorage,setupIframeHoverInspector,setupIframeSourceLocationListener,webFetch});
|
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
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(),a=this.headerMap.get(i);this.headerMap.set(i,a?`${a}, ${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()}},he=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[a,s]=i.split("=");a&&this.append(decodeURIComponent(a),s?decodeURIComponent(s):"")}}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 a of i)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(a)}`);return e.join("&")}forEach(e){for(let[r,i]of this.params.entries())for(let a of i)e(a,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 a of i)e.push([r,a]);return e[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}},$=class I{constructor(e,r){let i;if(e instanceof I)i=e.href;else if(r){let s=r instanceof I?r.href:r;i=this.resolve(s,e)}else i=e;let a=this.parseUrl(i);this.href=i,this.origin=`${a.protocol}//${a.host}`,this.protocol=a.protocol,this.username=a.username,this.password=a.password,this.host=a.host,this.hostname=a.hostname,this.port=a.port,this.pathname=a.pathname,this.search=a.search,this.searchParams=new he(a.search),this.hash=a.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 s=this.parseUrl(e);return`${s.protocol}//${s.host}${r}`}let i=this.parseUrl(e),a=i.pathname.endsWith("/")?i.pathname:i.pathname+"/";return`${i.protocol}//${i.host}${a}${r}`}parseUrl(e){let r=e.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!r)throw new TypeError("Invalid URL");let i=r[2]||"",a=r[4]||"",s=r[5]||"/",o=r[7]?`?${r[7]}`:"",n=r[9]?`#${r[9]}`:"";if(!i&&!a&&!s.startsWith("/")&&!s.includes("/")&&!s.includes("."))throw new TypeError("Invalid URL");let c=a.match(/^([^@]*)@(.+)$/),h="",l="",u=a;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:s,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=ce(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 ce(t){return t?new y(t):new y}var ue=class{constructor(){this._aborted=!1,this.listeners=new Set,this.onabort=null}get aborted(){return this._aborted}_trigger(){if(!this._aborted){if(this._aborted=!0,typeof this.onabort=="function")try{this.onabort()}catch{}for(let 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]"}},de=class{constructor(){this._signal=new ue}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}};function pe(t){if(t!==void 0)return typeof t=="string"||t instanceof FormData||t instanceof Blob||t instanceof File||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||typeof ReadableStream<"u"&&t instanceof ReadableStream?t:typeof t=="object"&&t!==null?JSON.stringify(t):t}var 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.fetchWithAuth(r,{method:e.method||"POST",body:pe(e.body),headers:e.headers})).json()}},g="nvwa_current_jwt",v="nvwa_login_token",b="nvwa_user_profile",me="set-auth-token",ge=typeof fetch<"u"?(t,e)=>fetch(t,e):()=>{throw new Error("AuthClient requires fetch")},B={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 k(t){let e=B[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 G=class{constructor(t,e={}){this.baseUrl=t.replace(/\/$/,""),this.authPath=(e.authPath??"/auth").replace(/^\//,""),this.fetchImpl=e.fetchImpl??ge,this.storage=e.storage??null,this.credentials=e.credentials??"omit",this.integrationProviders=e.integrationProviders??{},this.defaultApplicationCode=e.applicationCode?.trim()||null,this.platformType=e.platformType,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=B[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])=>k(r))}async getAvailableProviders(t){return this.getSocialProviders(t)}async startSocialLogin(t,e){let r=k(t),i=e?.applicationCode?.trim()||this.defaultApplicationCode||void 0,a=e?.returnUrl??(typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:"");switch(r.loginKind){case"google_openplatform":if(!a)throw new Error("startSocialLogin requires returnUrl for google");this.startGoogleOpenPlatformLogin(a,{applicationCode:i,platformCode:e?.platformCode});return;case"github_openplatform":if(!a)throw new Error("startSocialLogin requires returnUrl for github");this.startGithubOpenPlatformLogin(a,{applicationCode:i,platformCode:e?.platformCode});return;case"wechat_website_openplatform":if(!a)throw new Error("startSocialLogin requires returnUrl for wechat-website");this.startWechatWebsiteOpenPlatformLogin(a);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(me)?.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:a}=await this.getToken(i??void 0);a?.token&&await this.storage.set(g,a.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 a=e?.platformCode?.trim()??"";a&&r.set("platform_code",a);let s=R(this.integrationProviders,"google");return s&&r.set("oauth_credential_source",s),`${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 s=await this.storage.get(g);s!=null&&(e.Authorization=`Bearer ${s}`)}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 a=i?JSON.parse(i):null;return!a?.token||!a.user?{error:{message:"invalid_google_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(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGoogleOpenPlatformIdentity(){try{let t={};if(this.storage){let a=await this.storage.get(g);a!=null&&(t.Authorization=`Bearer ${a}`)}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 a=e?.platformCode?.trim()??"";a&&r.set("platform_code",a);let s=R(this.integrationProviders,"github");return s&&r.set("oauth_credential_source",s),`${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 s=await this.storage.get(g);s!=null&&(e.Authorization=`Bearer ${s}`)}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 a=i?JSON.parse(i):null;return!a?.token||!a.user?{error:{message:"invalid_github_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(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGithubOpenPlatformIdentity(){try{let t={};if(this.storage){let a=await this.storage.get(g);a!=null&&(t.Authorization=`Bearer ${a}`)}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 s=await this.storage.get(g);s!=null&&(e.Authorization=`Bearer ${s}`)}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 a=i?JSON.parse(i):null;return!a?.token||!a.user?{error:{message:"invalid_wechat_website_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(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getWechatWebsiteOpenPlatformIdentity(){try{let t={};if(this.storage){let a=await this.storage.get(g);a!=null&&(t.Authorization=`Bearer ${a}`)}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 a=i?JSON.parse(i):void 0;return a&&await this.persistLogin({user:a.user,session:a.session},r),{data:a}}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 s=await this.storage.get(v)??await this.storage.get(g);s!=null&&(e.Authorization=`Bearer ${s}`)}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 a=i?JSON.parse(i):void 0;return{data:a?.token!=null?{token:a.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})}),a=await i.text();if(!i.ok)return{error:{message:a||i.statusText,status:i.status}};let s=a?JSON.parse(a):null;return!s?.token||!s.user?{error:{message:"invalid_wechat_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(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})}),a=await i.text();if(!i.ok)return{error:{message:a||i.statusText,status:i.status}};let s=a?JSON.parse(a):null;return!s?.token||!s.user?{error:{message:"invalid_alipay_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(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}:{}}),a=await i.text();if(!i.ok)return{error:{message:a||i.statusText,status:i.status}};let s=a?JSON.parse(a):null;return!s?.openid||!s.appId?{error:{message:"invalid_wechat_identity_response",status:502}}:{data:s}}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}:{}}),a=await i.text();if(!i.ok)return{error:{message:a||i.statusText,status:i.status}};let s=a?JSON.parse(a):null;return!s?.openid||!s.appId?{error:{message:"invalid_alipay_identity_response",status:502}}:{data:s}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getMiniProgramIdentity(t){let e=t?.applicationCode?.trim()||this.defaultApplicationCode||void 0;if(this.platformType==="WechatMiniProgram"){let r=await this.getWeChatOpenPlatformIdentity(e);if(!r.data)throw new Error(r.error?.message||"failed to get wechat open platform identity");return{platformType:this.platformType,appId:r.data.appId,platformUserId:r.data.openid,unionid:r.data.unionid}}else if(this.platformType==="AlipayMiniProgram"){let r=await this.getAlipayOpenPlatformIdentity(e);if(!r.data)throw new Error(r.error?.message||"failed to get wechat open platform identity");return{platformType:this.platformType,appId:r.data.appId,platformUserId:r.data.openid,unionid:r.data.unionid}}return null}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 a=i?JSON.parse(i):void 0;return{data:a?.data??a??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 a=e?.method||"GET";if((a==="POST"||a==="PUT"||a==="PATCH")&&e?.body){let o=i.get("Content-Type");(!o||o.includes("text/plain"))&&i.set("Content-Type","application/json")}let s=await this.customFetch(t,{...e,headers:i});if(s.status===401)throw this.handleUnauthorized(),new Error("\u672A\u767B\u5F55");return s}},fe="/storage",ye=fe+"/generateUploadUrl",J=class{constructor(t,e){this.baseUrl=t,this.http=e}async uploadFile(t){let e=await this.http.fetch(this.baseUrl+ye,{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:a}=await i.json();return{url:a.split("?")[0]}}},we=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},ve=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,a=i(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async s=>{let o=null,n=null,c=null,h=s.status,l=s.statusText;if(s.ok){var u,d;if(r.method!=="HEAD"){var m;let w=await s.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=s.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 s.text();try{o=JSON.parse(p),Array.isArray(o)&&s.status===404&&(n=[],o=null,h=200,l="OK")}catch{s.status===404&&p===""?(h=204,l="No Content"):o={message:p}}if(o&&r.shouldThrowOnError)throw new we(o)}return{error:o,data:n,count:c,status:h,statusText:l}});return this.shouldThrowOnError||(a=a.catch(s=>{var o;let n="",c="",h="",l=s?.cause;if(l){var u,d,m,p;let le=(u=l?.message)!==null&&u!==void 0?u:"",U=(d=l?.code)!==null&&d!==void 0?d:"";n=`${(m=s?.name)!==null&&m!==void 0?m:"FetchError"}: ${s?.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(),a=this.headerMap.get(i);this.headerMap.set(i,a?`${a}, ${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()}},he=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[a,s]=i.split("=");a&&this.append(decodeURIComponent(a),s?decodeURIComponent(s):"")}}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 a of i)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(a)}`);return e.join("&")}forEach(e){for(let[r,i]of this.params.entries())for(let a of i)e(a,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 a of i)e.push([r,a]);return e[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}},I=class A{constructor(e,r){let i;if(e instanceof A)i=e.href;else if(r){let s=r instanceof A?r.href:r;i=this.resolve(s,e)}else i=e;let a=this.parseUrl(i);this.href=i,this.origin=`${a.protocol}//${a.host}`,this.protocol=a.protocol,this.username=a.username,this.password=a.password,this.host=a.host,this.hostname=a.hostname,this.port=a.port,this.pathname=a.pathname,this.search=a.search,this.searchParams=new he(a.search),this.hash=a.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 s=this.parseUrl(e);return`${s.protocol}//${s.host}${r}`}let i=this.parseUrl(e),a=i.pathname.endsWith("/")?i.pathname:i.pathname+"/";return`${i.protocol}//${i.host}${a}${r}`}parseUrl(e){let r=e.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!r)throw new TypeError("Invalid URL");let i=r[2]||"",a=r[4]||"",s=r[5]||"/",o=r[7]?`?${r[7]}`:"",n=r[9]?`#${r[9]}`:"";if(!i&&!a&&!s.startsWith("/")&&!s.includes("/")&&!s.includes("."))throw new TypeError("Invalid URL");let c=a.match(/^([^@]*)@(.+)$/),h="",l="",u=a;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:s,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=ce(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 ce(t){return t?new y(t):new y}var ue=class{constructor(){this._aborted=!1,this.listeners=new Set,this.onabort=null}get aborted(){return this._aborted}_trigger(){if(!this._aborted){if(this._aborted=!0,typeof this.onabort=="function")try{this.onabort()}catch{}for(let 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]"}},de=class{constructor(){this._signal=new ue}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}};function pe(t){if(t!==void 0)return typeof t=="string"||t instanceof FormData||t instanceof Blob||t instanceof File||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||typeof ReadableStream<"u"&&t instanceof ReadableStream?t:typeof t=="object"&&t!==null?JSON.stringify(t):t}var 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.fetchWithAuth(r,{method:e.method||"POST",body:pe(e.body),headers:e.headers})).json()}},g="nvwa_current_jwt",v="nvwa_login_token",b="nvwa_user_profile",me="set-auth-token",ge=typeof fetch<"u"?(t,e)=>fetch(t,e):()=>{throw new Error("AuthClient requires fetch")},B={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=B[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 G=class{constructor(t,e={}){this.baseUrl=t.replace(/\/$/,""),this.authPath=(e.authPath??"/auth").replace(/^\//,""),this.fetchImpl=e.fetchImpl??ge,this.storage=e.storage??null,this.credentials=e.credentials??"omit",this.integrationProviders=e.integrationProviders??{},this.defaultApplicationCode=e.applicationCode?.trim()||null,this.platformType=e.platformType,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=B[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,a=e?.returnUrl??(typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:"");switch(r.loginKind){case"google_openplatform":if(!a)throw new Error("startSocialLogin requires returnUrl for google");this.startGoogleOpenPlatformLogin(a,{applicationCode:i,platformCode:e?.platformCode});return;case"github_openplatform":if(!a)throw new Error("startSocialLogin requires returnUrl for github");this.startGithubOpenPlatformLogin(a,{applicationCode:i,platformCode:e?.platformCode});return;case"wechat_website_openplatform":if(!a)throw new Error("startSocialLogin requires returnUrl for wechat-website");this.startWechatWebsiteOpenPlatformLogin(a);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(me)?.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:a}=await this.getToken(i??void 0);a?.token&&await this.storage.set(g,a.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 a=e?.platformCode?.trim()??"";a&&r.set("platform_code",a);let s=R(this.integrationProviders,"google");return s&&r.set("oauth_credential_source",s),`${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 s=await this.storage.get(g);s!=null&&(e.Authorization=`Bearer ${s}`)}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 a=i?JSON.parse(i):null;return!a?.token||!a.user?{error:{message:"invalid_google_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(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGoogleOpenPlatformIdentity(){try{let t={};if(this.storage){let a=await this.storage.get(g);a!=null&&(t.Authorization=`Bearer ${a}`)}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 a=e?.platformCode?.trim()??"";a&&r.set("platform_code",a);let s=R(this.integrationProviders,"github");return s&&r.set("oauth_credential_source",s),`${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 s=await this.storage.get(g);s!=null&&(e.Authorization=`Bearer ${s}`)}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 a=i?JSON.parse(i):null;return!a?.token||!a.user?{error:{message:"invalid_github_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(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGithubOpenPlatformIdentity(){try{let t={};if(this.storage){let a=await this.storage.get(g);a!=null&&(t.Authorization=`Bearer ${a}`)}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 s=await this.storage.get(g);s!=null&&(e.Authorization=`Bearer ${s}`)}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 a=i?JSON.parse(i):null;return!a?.token||!a.user?{error:{message:"invalid_wechat_website_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(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getWechatWebsiteOpenPlatformIdentity(){try{let t={};if(this.storage){let a=await this.storage.get(g);a!=null&&(t.Authorization=`Bearer ${a}`)}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 a=i?JSON.parse(i):void 0;return a&&await this.persistLogin({user:a.user,session:a.session},r),{data:a}}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 s=await this.storage.get(v)??await this.storage.get(g);s!=null&&(e.Authorization=`Bearer ${s}`)}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 a=i?JSON.parse(i):void 0;return{data:a?.token!=null?{token:a.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})}),a=await i.text();if(!i.ok)return{error:{message:a||i.statusText,status:i.status}};let s=a?JSON.parse(a):null;return!s?.token||!s.user?{error:{message:"invalid_wechat_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(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})}),a=await i.text();if(!i.ok)return{error:{message:a||i.statusText,status:i.status}};let s=a?JSON.parse(a):null;return!s?.token||!s.user?{error:{message:"invalid_alipay_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(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}:{}}),a=await i.text();if(!i.ok)return{error:{message:a||i.statusText,status:i.status}};let s=a?JSON.parse(a):null;return!s?.openid||!s.appId?{error:{message:"invalid_wechat_identity_response",status:502}}:{data:s}}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}:{}}),a=await i.text();if(!i.ok)return{error:{message:a||i.statusText,status:i.status}};let s=a?JSON.parse(a):null;return!s?.openid||!s.appId?{error:{message:"invalid_alipay_identity_response",status:502}}:{data:s}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getMiniProgramIdentity(t){let e=t?.applicationCode?.trim()||this.defaultApplicationCode||void 0;if(this.platformType==="WechatMiniProgram"){let r=await this.getWeChatOpenPlatformIdentity(e);if(!r.data)throw new Error(r.error?.message||"failed to get wechat open platform identity");return{platformType:this.platformType,appId:r.data.appId,platformUserId:r.data.openid,unionid:r.data.unionid}}else if(this.platformType==="AlipayMiniProgram"){let r=await this.getAlipayOpenPlatformIdentity(e);if(!r.data)throw new Error(r.error?.message||"failed to get wechat open platform identity");return{platformType:this.platformType,appId:r.data.appId,platformUserId:r.data.openid,unionid:r.data.unionid}}return null}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 a=i?JSON.parse(i):void 0;return{data:a?.data??a??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 a=e?.method||"GET";if((a==="POST"||a==="PUT"||a==="PATCH")&&e?.body){let o=i.get("Content-Type");(!o||o.includes("text/plain"))&&i.set("Content-Type","application/json")}let s=await this.customFetch(t,{...e,headers:i});if(s.status===401)throw this.handleUnauthorized(),new Error("\u672A\u767B\u5F55");return s}},fe="/storage",ye=fe+"/generateUploadUrl",J=class{constructor(t,e){this.baseUrl=t,this.http=e}async uploadFile(t){let e=await this.http.fetch(this.baseUrl+ye,{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:a}=await i.json();return{url:a.split("?")[0]}}},we=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},ve=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,a=i(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async s=>{let o=null,n=null,c=null,h=s.status,l=s.statusText;if(s.ok){var u,d;if(r.method!=="HEAD"){var m;let w=await s.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=s.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 s.text();try{o=JSON.parse(p),Array.isArray(o)&&s.status===404&&(n=[],o=null,h=200,l="OK")}catch{s.status===404&&p===""?(h=204,l="No Content"):o={message:p}}if(o&&r.shouldThrowOnError)throw new we(o)}return{error:o,data:n,count:c,status:h,statusText:l}});return this.shouldThrowOnError||(a=a.catch(s=>{var o;let n="",c="",h="",l=s?.cause;if(l){var u,d,m,p;let le=(u=l?.message)!==null&&u!==void 0?u:"",k=(d=l?.code)!==null&&d!==void 0?d:"";n=`${(m=s?.name)!==null&&m!==void 0?m:"FetchError"}: ${s?.message}`,n+=`
|
|
2
2
|
|
|
3
|
-
Caused by: ${(p=l?.name)!==null&&p!==void 0?p:"Error"}: ${le}`,
|
|
4
|
-
${l.stack}`)}else{var f;n=(f=s?.stack)!==null&&f!==void 0?f:""}let w=this.url.toString().length;return s?.name==="AbortError"||s?.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=s?.name)!==null&&o!==void 0?o:"FetchError"}: ${s?.message}`,details:n,hint:c,code:h},data:null,count:null,status:0,statusText:""}})),a.then(t,e)}returns(){return this}overrideTypes(){return this}},be=class extends ve{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:a=i}={}){let s=a?`${a}.order`:"order",o=this.url.searchParams.get(s);return this.url.searchParams.set(s,`${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 a=typeof i>"u"?"offset":`${i}.offset`,s=typeof i>"u"?"limit":`${i}.limit`;return this.url.searchParams.set(a,`${t}`),this.url.searchParams.set(s,`${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:a=!1,format:s="text"}={}){var o;let n=[t?"analyze":null,e?"verbose":null,r?"settings":null,i?"buffers":null,a?"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+${s}; for="${c}"; options=${n};`),s==="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 be{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 a="";i==="plain"?a="pl":i==="phrase"?a="ph":i==="websearch"&&(a="w");let s=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${a}fts${s}.${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}},Ee=class{constructor(t,{headers:e={},schema:r,fetch:i,urlLengthLimit:a=8e3}){this.url=t,this.headers=new y(e),this.schema=r,this.fetch=i,this.urlLengthLimit=a}cloneRequestState(){return{url:new $(this.url.toString()),headers:new y(this.headers)}}select(t,e){let{head:r=!1,count:i}=e??{},a=r?"HEAD":"GET",s=!1,o=(t??"*").split("").map(h=>/\s/.test(h)&&!s?"":(h==='"'&&(s=!s),h)).join(""),{url:n,headers:c}=this.cloneRequestState();return n.searchParams.set("select",o),i&&c.append("Prefer",`count=${i}`),new E({method:a,url:n,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var i;let a="POST",{url:s,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}"`);s.searchParams.set("columns",c.join(","))}}return new E({method:a,url:s,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:a=!0}={}){var s;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}`),a||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:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;let i="PATCH",{url:a,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new E({method:i,url:a,headers:s,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:a}=this.cloneRequestState();return t&&a.append("Prefer",`count=${t}`),new E({method:r,url:i,headers:a,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 Pe(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 Se(t){var e=Pe(t,"string");return L(e)=="symbol"?e:e+""}function Le(t,e,r){return(e=Se(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(a){return Object.getOwnPropertyDescriptor(t,a).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){Le(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 Oe=class K{constructor(e,{headers:r={},schema:i,fetch:a,timeout:s,urlLengthLimit:o=8e3}={}){this.url=e,this.headers=new y(r),this.schemaName=i,this.urlLengthLimit=o;let n=a??globalThis.fetch;s!==void 0&&s>0?this.fetch=(c,h)=>{let l=new de,u=setTimeout(()=>l.abort(),s),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 Ee(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:a=!1,count:s}={}){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||a?(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",s?`count=${s},return=minimal`:"return=minimal"):s&&d.set("Prefer",`count=${s}`),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})}},Ce="/entities",V=(t,e)=>new Oe(t+Ce,{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=`
|
|
3
|
+
Caused by: ${(p=l?.name)!==null&&p!==void 0?p:"Error"}: ${le}`,k&&(n+=` (${k})`),l?.stack&&(n+=`
|
|
4
|
+
${l.stack}`)}else{var f;n=(f=s?.stack)!==null&&f!==void 0?f:""}let w=this.url.toString().length;return s?.name==="AbortError"||s?.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=s?.name)!==null&&o!==void 0?o:"FetchError"}: ${s?.message}`,details:n,hint:c,code:h},data:null,count:null,status:0,statusText:""}})),a.then(t,e)}returns(){return this}overrideTypes(){return this}},be=class extends ve{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:a=i}={}){let s=a?`${a}.order`:"order",o=this.url.searchParams.get(s);return this.url.searchParams.set(s,`${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 a=typeof i>"u"?"offset":`${i}.offset`,s=typeof i>"u"?"limit":`${i}.limit`;return this.url.searchParams.set(a,`${t}`),this.url.searchParams.set(s,`${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:a=!1,format:s="text"}={}){var o;let n=[t?"analyze":null,e?"verbose":null,r?"settings":null,i?"buffers":null,a?"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+${s}; for="${c}"; options=${n};`),s==="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("[,()]"),P=class extends be{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 a="";i==="plain"?a="pl":i==="phrase"?a="ph":i==="websearch"&&(a="w");let s=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${a}fts${s}.${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}},Pe=class{constructor(t,{headers:e={},schema:r,fetch:i,urlLengthLimit:a=8e3}){this.url=t,this.headers=new y(e),this.schema=r,this.fetch=i,this.urlLengthLimit=a}cloneRequestState(){return{url:new I(this.url.toString()),headers:new y(this.headers)}}select(t,e){let{head:r=!1,count:i}=e??{},a=r?"HEAD":"GET",s=!1,o=(t??"*").split("").map(h=>/\s/.test(h)&&!s?"":(h==='"'&&(s=!s),h)).join(""),{url:n,headers:c}=this.cloneRequestState();return n.searchParams.set("select",o),i&&c.append("Prefer",`count=${i}`),new P({method:a,url:n,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var i;let a="POST",{url:s,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}"`);s.searchParams.set("columns",c.join(","))}}return new P({method:a,url:s,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:a=!0}={}){var s;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}`),a||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:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;let i="PATCH",{url:a,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new P({method:i,url:a,headers:s,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:a}=this.cloneRequestState();return t&&a.append("Prefer",`count=${t}`),new P({method:r,url:i,headers:a,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function O(t){"@babel/helpers - typeof";return O=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},O(t)}function Ee(t,e){if(O(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var i=r.call(t,e||"default");if(O(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Se(t){var e=Ee(t,"string");return O(e)=="symbol"?e:e+""}function Oe(t,e,r){return(e=Se(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(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),r.push.apply(r,i)}return r}function L(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){Oe(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 Le=class K{constructor(e,{headers:r={},schema:i,fetch:a,timeout:s,urlLengthLimit:o=8e3}={}){this.url=e,this.headers=new y(r),this.schemaName=i,this.urlLengthLimit=o;let n=a??globalThis.fetch;s!==void 0&&s>0?this.fetch=(c,h)=>{let l=new de,u=setTimeout(()=>l.abort(),s),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,L(L({},h),{},{signal:l.signal})).finally(()=>{clearTimeout(u),d.removeEventListener("abort",m)})}return n(c,L(L({},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 Pe(new I(`${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:a=!1,count:s}={}){var o;let n,c=new I(`${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||a?(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",s?`count=${s},return=minimal`:"return=minimal"):s&&d.set("Prefer",`count=${s}`),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})}},Ce="/entities",V=(t,e)=>new Le(t+Ce,{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=`
|
|
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=s?.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,a=window.scrollY||window.pageYOffset;r.width>0&&r.height>0?(t.style.left=`${r.left+i}px`,t.style.top=`${r.top+a}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 a=this.createTooltip();e?a.textContent=e:a.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,a.style.display="block";let s=t.getBoundingClientRect();a.style.left=`${s.left+window.scrollX}px`,a.style.top=`${s.top+window.scrollY-a.offsetHeight-8}px`,s.top<a.offsetHeight+8&&(a.style.top=`${s.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 Te={"wechat-pay":{id:"wechat-pay",name:"WeChat Pay",description:"WeChat payment for web and miniapp."},"wechat-platform":{id:"wechat-platform",name:"WeChat Partner",description:"WeChat partner merchant onboarding."},"alipay-web":{id:"alipay-web",name:"Alipay Web",description:"Alipay page pay (ISV)."},"alipay-mobile-web":{id:"alipay-mobile-web",name:"Alipay Mobile Web",description:"Alipay WAP pay (ISV)."},"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 a=Te[i]??{id:i,name:i,description:""};return{...a,type:a.id}})}function C(t){return t&&typeof t=="object"?t:{}}function _e(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[a,s]of Object.entries(r))i[a]=_e(s);return{providers:i}}function A(t){let e=C(t);return{socialLogin:M(e.socialLogin),payment:M(e.payment)}}var $e=["DesktopWeb","MobileWeb","AndroidApp","IosApp","HarmonyApp","WechatMiniProgram","AlipayMiniProgram","DouyinMiniProgram"];function Ie(t){return $e.includes(t)}async function ee(t){let{platformType:e,getMiniProgramIdentity:r}=t;if(e!=="WechatMiniProgram"&&e!=="AlipayMiniProgram")return{platformType:e};if(!r)return{platformType:e};let i=await r();return i?{platformType:i.platformType,platformUserId:i.platformUserId,appId:i.appId,unionid:i.unionid}:{platformType:e}}function te(t){return A(t.integrationProviders??{})}function re(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(!Ie(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 a=JSON.parse(i);return a.expires&&Date.now()>a.expires?(await this.remove(e),null):a.value}catch(r){return console.error("WebStorageService get error:",r),null}}async set(e,r,i){try{let a=this.getKey(e),s={value:r,expires:i?Date.now()+i*1e3:null,timestamp:Date.now()};localStorage.setItem(a,JSON.stringify(s))}catch(a){throw console.error("WebStorageService set error:",a),a}}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 Ae=(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 s=e.headers;if(s instanceof y){let o={};s.forEach((n,c)=>{o[c]=n}),i=o}else if(Array.isArray(s)){let o=[];for(let n of s)Array.isArray(n)&&n.length>=2&&o.push([String(n[0]),String(n[1])]);i=o}else typeof s=="object"&&(i=s)}let a={method:e?.method||"GET",headers:i,body:e?.body,credentials:e?.credentials};return e?.signal&&(a.signal=e.signal),globalThis.fetch(r,a).then(async s=>{let o=s.headers.get("content-type")||"",n;if(o.includes("application/json"))n=await s.json();else{let h=await s.text();try{n=JSON.parse(h)}catch{n=h}}let c=new y;return s.headers.forEach((h,l)=>{c.set(l,h)}),new q(n,{status:s.status,statusText:s.statusText,headers:c})})},_=Ae;function Ne(t){return`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(t)}`}var N={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 a=Ne(r.codeUrl);window.open(a,"_blank","noopener,noreferrer");return}if(r?.kind==="alipay_page"){let a=window.open("","_blank");a&&(a.document.write(r.formHtml),a.document.close());return}let i=new Error("requestPayment: unsupported payParams for Desktop-web");throw e?.onFailure?.(i),i}};function ie(t){let e=async r=>await Z(t,r);return{...N,getAvailableProviders:e,getProviders:e}}function mt(){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 a=null;function s(h){t&&(a!==null&&cancelAnimationFrame(a),a=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",s),document.addEventListener("mouseleave",o),document.addEventListener("click",n,!0)):h.data?.type==="HOVER_INSPECTOR_DISABLE"&&(t=!1,document.removeEventListener("mousemove",s),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",s),document.removeEventListener("mouseleave",o),document.removeEventListener("click",n,!0),e.cleanup()}}function gt(t,e){if(!t||!t.contentWindow)throw new Error("Invalid iframe element");let r={type:"HOVER_INSPECTOR_ENABLE"};t.contentWindow.postMessage(r,e)}function ft(t,e){if(!t||!t.contentWindow)return;let r={type:"HOVER_INSPECTOR_DISABLE"};t.contentWindow.postMessage(r,e)}function yt(t,e,r=5e3){return new Promise((i,a)=>{if(!t||!t.contentWindow){a(new Error("Invalid iframe element"));return}let s=`source-location-${Date.now()}-${Math.random()}`,o=setTimeout(()=>{window.removeEventListener("message",n),a(new Error("Request timeout"))},r),n=h=>{h.origin===e&&h.data?.type==="GET_SOURCE_LOCATION_RESPONSE"&&h.data?.requestId===s&&(clearTimeout(o),window.removeEventListener("message",n),h.data.error?a(new Error(h.data.error)):i(h.data.sourceLocation||null))};window.addEventListener("message",n);let c={type:"GET_SOURCE_LOCATION_REQUEST",requestId:s};try{t.contentWindow.postMessage(c,e)}catch(h){clearTimeout(o),window.removeEventListener("message",n),a(h)}})}function wt(){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:xe(),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 xe(){return Q("root")}import{useEffect as Ue,useMemo as ae,useState as se}from"react";import{createElement as ne}from"react";var ke="nvwa-social-login-list",Re="nvwa-social-login-button";async function je(t){return await t.getSocialProviderDescriptors()}function He(t){return t?.trim()?t.trim():typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:""}function St(t){let[e,r]=se(t.providers??[]),[i,a]=se(!t.providers);Ue(()=>{if(t.providers){r(t.providers),a(!1);return}let n=!1;return a(!0),je(t.auth).then(c=>{n||r(c)}).catch(c=>{n||t.onError?.(c instanceof Error?c:new Error(String(c)))}).finally(()=>{n||a(!1)}),()=>{n=!0}},[t.auth,t.providers,t.onError]);let s=ae(()=>He(t.returnUrl),[t.returnUrl]),o=ae(()=>e.filter(n=>n.loginKind!=="unsupported"),[e]);return i||o.length===0?null:ne("div",{className:t.className??ke},...o.map(n=>{let c=async()=>{try{t.onBeforeLogin?.(n),await t.auth.startSocialLogin(n.id,{returnUrl:s,applicationCode:t.applicationCode,platformCode:t.platformCode})}catch(l){t.onError?.(l instanceof Error?l:new Error(String(l)))}},h=ne("button",{key:n.id,type:"button",className:Re,onClick:c},n.name);return t.onRenderButton?t.onRenderButton(n,h):h}))}var oe=new T,x=class{constructor(e){this.payment=N;let{handleUnauthorized:r,appConfig:i,integrationProviders:a}=e,s=re(i);this.applicationCode=s.applicationCode,this.platformType=s.platformType,this.integrationProviders=A(a??te(i)),this.auth=new G(s.baseUrl,{fetchImpl:_,storage:oe,integrationProviders:this.integrationProviders,applicationCode:this.applicationCode,platformType:s.platformType}),this.httpClient=new z(oe,_,r),this.fileStorage=new J(s.baseUrl,this.httpClient),this.entities=V(s.baseUrl,this.httpClient),this.functions=new D(this.httpClient,s.baseUrl);let o=ie(this.integrationProviders);this.payment={...o,collectPaymentClientContext:()=>ee({platformType:this.platformType,getMiniProgramIdentity:()=>this.auth.getMiniProgramIdentity()})}}};export{St as SocialLoginButtons,x as default,ft as disableIframeHoverInspector,gt as enableIframeHoverInspector,yt as getIframeSourceLocation,oe as localStorage,mt as setupIframeHoverInspector,wt 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,a=window.scrollY||window.pageYOffset;r.width>0&&r.height>0?(t.style.left=`${r.left+i}px`,t.style.top=`${r.top+a}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 a=this.createTooltip();e?a.textContent=e:a.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,a.style.display="block";let s=t.getBoundingClientRect();a.style.left=`${s.left+window.scrollX}px`,a.style.top=`${s.top+window.scrollY-a.offsetHeight-8}px`,s.top<a.offsetHeight+8&&(a.style.top=`${s.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 Te={"wechat-pay":{id:"wechat-pay",name:"WeChat Pay",description:"WeChat payment for web and miniapp."},"wechat-platform":{id:"wechat-platform",name:"WeChat Partner",description:"WeChat partner merchant onboarding."},"alipay-web":{id:"alipay-web",name:"Alipay Web",description:"Alipay page pay (ISV)."},"alipay-mobile-web":{id:"alipay-mobile-web",name:"Alipay Mobile Web",description:"Alipay WAP pay (ISV)."},"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 a=Te[i]??{id:i,name:i,description:""};return{...a,type:a.id}})}function C(t){return t&&typeof t=="object"?t:{}}function _e(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[a,s]of Object.entries(r))i[a]=_e(s);return{providers:i}}function $(t){let e=C(t);return{socialLogin:M(e.socialLogin),payment:M(e.payment)}}var Ie=["DesktopWeb","MobileWeb","AndroidApp","IosApp","HarmonyApp","WechatMiniProgram","AlipayMiniProgram","DouyinMiniProgram"];function Ae(t){return Ie.includes(t)}async function ee(t){let{platformType:e,getMiniProgramIdentity:r}=t;if(e!=="WechatMiniProgram"&&e!=="AlipayMiniProgram")return{platformType:e};if(!r)return{platformType:e};let i=await r();return i?{platformType:i.platformType,platformUserId:i.platformUserId,appId:i.appId,unionid:i.unionid}:{platformType:e}}function te(t){return $(t.integrationProviders??{})}function re(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(!Ae(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 a=JSON.parse(i);return a.expires&&Date.now()>a.expires?(await this.remove(e),null):a.value}catch(r){return console.error("WebStorageService get error:",r),null}}async set(e,r,i){try{let a=this.getKey(e),s={value:r,expires:i?Date.now()+i*1e3:null,timestamp:Date.now()};localStorage.setItem(a,JSON.stringify(s))}catch(a){throw console.error("WebStorageService set error:",a),a}}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 s=e.headers;if(s instanceof y){let o={};s.forEach((n,c)=>{o[c]=n}),i=o}else if(Array.isArray(s)){let o=[];for(let n of s)Array.isArray(n)&&n.length>=2&&o.push([String(n[0]),String(n[1])]);i=o}else typeof s=="object"&&(i=s)}let a={method:e?.method||"GET",headers:i,body:e?.body,credentials:e?.credentials};return e?.signal&&(a.signal=e.signal),globalThis.fetch(r,a).then(async s=>{let o=s.headers.get("content-type")||"",n;if(o.includes("application/json"))n=await s.json();else{let h=await s.text();try{n=JSON.parse(h)}catch{n=h}}let c=new y;return s.headers.forEach((h,l)=>{c.set(l,h)}),new q(n,{status:s.status,statusText:s.statusText,headers:c})})},_=$e;function Ne(t){return`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(t)}`}var N={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 a=Ne(r.codeUrl);window.open(a,"_blank","noopener,noreferrer");return}if(r?.kind==="alipay_page"){let a=window.open("","_blank");a&&(a.document.write(r.formHtml),a.document.close());return}let i=new Error("requestPayment: unsupported payParams for Desktop-web");throw e?.onFailure?.(i),i}};function ie(t){let e=async r=>await Z(t,r);return{...N,getAvailableProviders:e,getProviders:e}}function mt(){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 a=null;function s(h){t&&(a!==null&&cancelAnimationFrame(a),a=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",s),document.addEventListener("mouseleave",o),document.addEventListener("click",n,!0)):h.data?.type==="HOVER_INSPECTOR_DISABLE"&&(t=!1,document.removeEventListener("mousemove",s),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",s),document.removeEventListener("mouseleave",o),document.removeEventListener("click",n,!0),e.cleanup()}}function gt(t,e){if(!t||!t.contentWindow)throw new Error("Invalid iframe element");let r={type:"HOVER_INSPECTOR_ENABLE"};t.contentWindow.postMessage(r,e)}function ft(t,e){if(!t||!t.contentWindow)return;let r={type:"HOVER_INSPECTOR_DISABLE"};t.contentWindow.postMessage(r,e)}function yt(t,e,r=5e3){return new Promise((i,a)=>{if(!t||!t.contentWindow){a(new Error("Invalid iframe element"));return}let s=`source-location-${Date.now()}-${Math.random()}`,o=setTimeout(()=>{window.removeEventListener("message",n),a(new Error("Request timeout"))},r),n=h=>{h.origin===e&&h.data?.type==="GET_SOURCE_LOCATION_RESPONSE"&&h.data?.requestId===s&&(clearTimeout(o),window.removeEventListener("message",n),h.data.error?a(new Error(h.data.error)):i(h.data.sourceLocation||null))};window.addEventListener("message",n);let c={type:"GET_SOURCE_LOCATION_REQUEST",requestId:s};try{t.contentWindow.postMessage(c,e)}catch(h){clearTimeout(o),window.removeEventListener("message",n),a(h)}})}function wt(){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:xe(),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 xe(){return Q("root")}import{useEffect as ke,useMemo as ae,useState as se}from"react";import{createElement as ne}from"react";var Ue="nvwa-social-login-list",Re="nvwa-social-login-button";async function je(t){return await t.getSocialProviderDescriptors()}function He(t){return t?.trim()?t.trim():typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:""}function St(t){let[e,r]=se(t.providers??[]),[i,a]=se(!t.providers);ke(()=>{if(t.providers){r(t.providers),a(!1);return}let n=!1;return a(!0),je(t.auth).then(c=>{n||r(c)}).catch(c=>{n||t.onError?.(c instanceof Error?c:new Error(String(c)))}).finally(()=>{n||a(!1)}),()=>{n=!0}},[t.auth,t.providers,t.onError]);let s=ae(()=>He(t.returnUrl),[t.returnUrl]),o=ae(()=>e.filter(n=>n.loginKind!=="unsupported"),[e]);return i||o.length===0?null:ne("div",{className:t.className??Ue},...o.map(n=>{let c=async()=>{try{t.onBeforeLogin?.(n),await t.auth.startSocialLogin(n.id,{returnUrl:s,applicationCode:t.applicationCode,platformCode:t.platformCode})}catch(l){t.onError?.(l instanceof Error?l:new Error(String(l)))}},h=ne("button",{key:n.id,type:"button",className:Re,onClick:c},n.name);return t.onRenderButton?t.onRenderButton(n,h):h}))}var oe=new T,x=class{constructor(e){this.payment=N;let{handleUnauthorized:r,appConfig:i,integrationProviders:a}=e,s=re(i);this.applicationCode=s.applicationCode,this.platformType=s.platformType,this.integrationProviders=$(a??te(i)),this.auth=new G(s.baseUrl,{fetchImpl:_,storage:oe,integrationProviders:this.integrationProviders,applicationCode:this.applicationCode,platformType:s.platformType}),this.httpClient=new z(oe,_,r),this.fileStorage=new J(s.baseUrl,this.httpClient),this.entities=V(s.baseUrl,this.httpClient),this.functions=new D(this.httpClient,s.baseUrl);let o=ie(this.integrationProviders);this.payment={...o,collectPaymentClientContext:()=>ee({platformType:this.platformType,getMiniProgramIdentity:()=>this.auth.getMiniProgramIdentity()})}}};export{St as SocialLoginButtons,x as default,ft as disableIframeHoverInspector,gt as enableIframeHoverInspector,yt as getIframeSourceLocation,oe as localStorage,mt as setupIframeHoverInspector,wt as setupIframeSourceLocationListener,_ as webFetch};
|