@nvwa-app/sdk-uniapp 6.19.0 → 6.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +34 -2
- package/dist/index.d.ts +34 -2
- package/dist/index.js +4 -4
- package/dist/index.mjs +4 -4
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { NvwaLocalStorage, INvwa, NvwaFileStorage, createPostgrestClient, NvwaEdgeFunctions, NvwaHttpClient,
|
|
1
|
+
import { NvwaLocalStorage, AuthClient, SocialProviderDescriptor, INvwa, NvwaFileStorage, createPostgrestClient, NvwaEdgeFunctions, NvwaHttpClient, IntegrationProvidersConfig, IPaymentLauncher } from '@nvwa-app/sdk-core';
|
|
2
2
|
|
|
3
3
|
declare class UniAppLocalStorage implements NvwaLocalStorage {
|
|
4
4
|
private prefix;
|
|
@@ -31,6 +31,38 @@ declare function getIframeSourceLocation(iframe: HTMLIFrameElement | null, targe
|
|
|
31
31
|
*/
|
|
32
32
|
declare function setupIframeSourceLocationListener(): (() => void) | undefined;
|
|
33
33
|
|
|
34
|
+
interface UniappSocialLoginComponentOptions {
|
|
35
|
+
name?: string;
|
|
36
|
+
auth: AuthClient;
|
|
37
|
+
applicationCode?: string;
|
|
38
|
+
returnUrl?: string;
|
|
39
|
+
providerClass?: string;
|
|
40
|
+
containerClass?: string;
|
|
41
|
+
providers?: SocialProviderDescriptor[];
|
|
42
|
+
onError?: (error: Error) => void;
|
|
43
|
+
onBeforeLogin?: (provider: SocialProviderDescriptor) => void;
|
|
44
|
+
resolveMiniProgramCode?: (providerId: string) => Promise<string>;
|
|
45
|
+
}
|
|
46
|
+
type SocialLoginComponentInstance = {
|
|
47
|
+
providers: SocialProviderDescriptor[];
|
|
48
|
+
loading: boolean;
|
|
49
|
+
};
|
|
50
|
+
declare function createSocialLoginComponent(options: UniappSocialLoginComponentOptions): {
|
|
51
|
+
name: string;
|
|
52
|
+
data(): {
|
|
53
|
+
providers: SocialProviderDescriptor[];
|
|
54
|
+
loading: boolean;
|
|
55
|
+
};
|
|
56
|
+
created(this: SocialLoginComponentInstance): Promise<void>;
|
|
57
|
+
methods: {
|
|
58
|
+
handleProviderTap(provider: SocialProviderDescriptor): Promise<void>;
|
|
59
|
+
};
|
|
60
|
+
render(this: SocialLoginComponentInstance & {
|
|
61
|
+
handleProviderTap: (provider: SocialProviderDescriptor) => Promise<void>;
|
|
62
|
+
$createElement: (...args: unknown[]) => unknown;
|
|
63
|
+
}): unknown;
|
|
64
|
+
};
|
|
65
|
+
|
|
34
66
|
/** 构造 Nvwa(UniApp)时的唯一入参 */
|
|
35
67
|
type NvwaUniappInit = {
|
|
36
68
|
baseUrl: string;
|
|
@@ -57,4 +89,4 @@ declare class Nvwa implements INvwa {
|
|
|
57
89
|
constructor(init: NvwaUniappInit);
|
|
58
90
|
}
|
|
59
91
|
|
|
60
|
-
export { type NvwaUniappInit, Nvwa as default, disableIframeHoverInspector, enableIframeHoverInspector, getIframeSourceLocation, localStorage, setupIframeHoverInspector, setupIframeSourceLocationListener };
|
|
92
|
+
export { type NvwaUniappInit, type UniappSocialLoginComponentOptions, createSocialLoginComponent, Nvwa as default, disableIframeHoverInspector, enableIframeHoverInspector, getIframeSourceLocation, localStorage, setupIframeHoverInspector, setupIframeSourceLocationListener };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { NvwaLocalStorage, INvwa, NvwaFileStorage, createPostgrestClient, NvwaEdgeFunctions, NvwaHttpClient,
|
|
1
|
+
import { NvwaLocalStorage, AuthClient, SocialProviderDescriptor, INvwa, NvwaFileStorage, createPostgrestClient, NvwaEdgeFunctions, NvwaHttpClient, IntegrationProvidersConfig, IPaymentLauncher } from '@nvwa-app/sdk-core';
|
|
2
2
|
|
|
3
3
|
declare class UniAppLocalStorage implements NvwaLocalStorage {
|
|
4
4
|
private prefix;
|
|
@@ -31,6 +31,38 @@ declare function getIframeSourceLocation(iframe: HTMLIFrameElement | null, targe
|
|
|
31
31
|
*/
|
|
32
32
|
declare function setupIframeSourceLocationListener(): (() => void) | undefined;
|
|
33
33
|
|
|
34
|
+
interface UniappSocialLoginComponentOptions {
|
|
35
|
+
name?: string;
|
|
36
|
+
auth: AuthClient;
|
|
37
|
+
applicationCode?: string;
|
|
38
|
+
returnUrl?: string;
|
|
39
|
+
providerClass?: string;
|
|
40
|
+
containerClass?: string;
|
|
41
|
+
providers?: SocialProviderDescriptor[];
|
|
42
|
+
onError?: (error: Error) => void;
|
|
43
|
+
onBeforeLogin?: (provider: SocialProviderDescriptor) => void;
|
|
44
|
+
resolveMiniProgramCode?: (providerId: string) => Promise<string>;
|
|
45
|
+
}
|
|
46
|
+
type SocialLoginComponentInstance = {
|
|
47
|
+
providers: SocialProviderDescriptor[];
|
|
48
|
+
loading: boolean;
|
|
49
|
+
};
|
|
50
|
+
declare function createSocialLoginComponent(options: UniappSocialLoginComponentOptions): {
|
|
51
|
+
name: string;
|
|
52
|
+
data(): {
|
|
53
|
+
providers: SocialProviderDescriptor[];
|
|
54
|
+
loading: boolean;
|
|
55
|
+
};
|
|
56
|
+
created(this: SocialLoginComponentInstance): Promise<void>;
|
|
57
|
+
methods: {
|
|
58
|
+
handleProviderTap(provider: SocialProviderDescriptor): Promise<void>;
|
|
59
|
+
};
|
|
60
|
+
render(this: SocialLoginComponentInstance & {
|
|
61
|
+
handleProviderTap: (provider: SocialProviderDescriptor) => Promise<void>;
|
|
62
|
+
$createElement: (...args: unknown[]) => unknown;
|
|
63
|
+
}): unknown;
|
|
64
|
+
};
|
|
65
|
+
|
|
34
66
|
/** 构造 Nvwa(UniApp)时的唯一入参 */
|
|
35
67
|
type NvwaUniappInit = {
|
|
36
68
|
baseUrl: string;
|
|
@@ -57,4 +89,4 @@ declare class Nvwa implements INvwa {
|
|
|
57
89
|
constructor(init: NvwaUniappInit);
|
|
58
90
|
}
|
|
59
91
|
|
|
60
|
-
export { type NvwaUniappInit, Nvwa as default, disableIframeHoverInspector, enableIframeHoverInspector, getIframeSourceLocation, localStorage, setupIframeHoverInspector, setupIframeSourceLocationListener };
|
|
92
|
+
export { type NvwaUniappInit, type UniappSocialLoginComponentOptions, createSocialLoginComponent, Nvwa as default, disableIframeHoverInspector, enableIframeHoverInspector, getIframeSourceLocation, localStorage, setupIframeHoverInspector, setupIframeSourceLocationListener };
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"use strict";var N=Object.defineProperty;var ae=Object.getOwnPropertyDescriptor;var ie=Object.getOwnPropertyNames;var ne=Object.prototype.hasOwnProperty;var oe=(t,e)=>{for(var r in e)N(t,r,{get:e[r],enumerable:!0})},le=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of ie(e))!ne.call(t,a)&&a!==r&&N(t,a,{get:()=>e[a],enumerable:!(s=ae(e,a))||s.enumerable});return t};var he=t=>le(N({},"__esModule",{value:!0}),t);var Fe={};oe(Fe,{default:()=>I,disableIframeHoverInspector:()=>je,enableIframeHoverInspector:()=>He,getIframeSourceLocation:()=>Me,localStorage:()=>H,setupIframeHoverInspector:()=>Re,setupIframeSourceLocationListener:()=>We});module.exports=he(Fe);var w=class F{constructor(e){if(this.headerMap=new Map,e){if(e instanceof F)e.forEach((r,s)=>this.set(s,r));else if(Array.isArray(e))for(let[r,s]of e)this.set(r,String(s));else if(typeof e=="object")for(let r of Object.keys(e))this.set(r,String(e[r]))}}append(e,r){let s=e.toLowerCase(),a=this.headerMap.get(s);this.headerMap.set(s,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,s]of this.headerMap.entries())e(s,r,this)}entries(){return this.headerMap.entries()}keys(){return this.headerMap.keys()}values(){return this.headerMap.values()}[Symbol.iterator](){return this.entries()}},ce=class G{constructor(e){if(this.params=new Map,e){if(typeof e=="string")this.parseString(e);else if(e instanceof G)this.params=new Map(e.params);else if(Array.isArray(e))for(let[r,s]of e)this.append(r,s);else if(e&&typeof e=="object")for(let[r,s]of Object.entries(e))this.set(r,s)}}parseString(e){e.startsWith("?")&&(e=e.slice(1));let r=e.split("&");for(let s of r)if(s){let[a,i]=s.split("=");a&&this.append(decodeURIComponent(a),i?decodeURIComponent(i):"")}}append(e,r){let s=this.params.get(e)||[];s.push(r),this.params.set(e,s)}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],[s])=>r.localeCompare(s));this.params=new Map(e)}toString(){let e=[];for(let[r,s]of this.params.entries())for(let a of s)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(a)}`);return e.join("&")}forEach(e){for(let[r,s]of this.params.entries())for(let a of s)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,s]of this.params.entries())for(let a of s)e.push([r,a]);return e[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}},k=class U{constructor(e,r){let s;if(e instanceof U)s=e.href;else if(r){let i=r instanceof U?r.href:r;s=this.resolve(i,e)}else s=e;let a=this.parseUrl(s);this.href=s,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 ce(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 i=this.parseUrl(e);return`${i.protocol}//${i.host}${r}`}let s=this.parseUrl(e),a=s.pathname.endsWith("/")?s.pathname:s.pathname+"/";return`${s.protocol}//${s.host}${a}${r}`}parseUrl(e){let r=e.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!r)throw new TypeError("Invalid URL");let s=r[2]||"",a=r[4]||"",i=r[5]||"/",o=r[7]?`?${r[7]}`:"",n=r[9]?`#${r[9]}`:"";if(!s&&!a&&!i.startsWith("/")&&!i.includes("/")&&!i.includes("."))throw new TypeError("Invalid URL");let c=a.match(/^([^@]*)@(.+)$/),h="",l="",u=a;if(c){let f=c[1];u=c[2];let y=f.match(/^([^:]*):?(.*)$/);y&&(h=y[1]||"",l=y[2]||"")}let m=u.match(/^([^:]+):?(\d*)$/),d=m?m[1]:u,p=m&&m[2]?m[2]:"";return{protocol:s?`${s}:`:"",username:h,password:l,host:u,hostname:d,port:p,pathname:i,search:o,hash:n}}toString(){let e=this.searchParams.toString(),r=e?`?${e}`:"";return`${this.protocol}//${this.host}${this.pathname}${r}${this.hash}`}toJSON(){return this.toString()}};var B=class{constructor(t,e){this.bodyData=t,this.status=e?.status??200,this.statusText=e?.statusText??"",this.headers=ue(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 ue(t){return t?new w(t):new w}var de=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]"}},pe=class{constructor(){this._signal=new de}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}},D=class{constructor(t,e=""){this.http=t,this.baseUrl=e.replace(/\/$/,"")}async invoke(t,e){let r=this.baseUrl?`${this.baseUrl}/functions/${t}`:`/functions/${t}`;return await(await this.http.fetch(r,{method:e.method||"POST",body:e.body,headers:e.headers})).json()}},g="nvwa_current_jwt",v="nvwa_login_token",E="nvwa_user_profile",me="set-auth-token",ge=typeof fetch<"u"?(t,e)=>fetch(t,e):()=>{throw new Error("AuthClient requires fetch")},fe={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."}};function j(t,e){let r=t.socialLogin?.providers?.[e];return r?.enabled?r.oauthCredentialSource==="custom"?"custom":"nvwa_default":null}var J=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??{},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])=>fe[r]??{id:r,name:r,description:""})}async currentUser(){if(this.storage){let r=await this.storage.get(E);if(r!=null)return r}let{data:t}=await this.getSession(),e=t?.user??null;return e&&this.storage&&await this.storage.set(E,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:s}=await this.getToken(r??void 0);return s?.token?(await this.storage.set(g,s.token),s.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(E,t.user);let s=r??await this.storage.get(v),{data:a}=await this.getToken(s??void 0);a?.token&&await this.storage.set(g,a.token)}async clearLogin(){this.storage&&(await this.storage.remove(v),await this.storage.remove(E),await this.storage.remove(g))}getGoogleOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t});e?.applicationCode?.trim()&&r.set("application_code",e.applicationCode.trim()),e?.platformCode?.trim()&&r.set("platform_code",e.platformCode.trim());let s=j(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 i=await this.storage.get(g);i!=null&&(e.Authorization=`Bearer ${i}`)}let r=await this.fetchImpl(this.url("google/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let a=s?JSON.parse(s):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(E,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 s=r?JSON.parse(r):null;return s?.sub?{data:s}:{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});e?.applicationCode?.trim()&&r.set("application_code",e.applicationCode.trim()),e?.platformCode?.trim()&&r.set("platform_code",e.platformCode.trim());let s=j(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 i=await this.storage.get(g);i!=null&&(e.Authorization=`Bearer ${i}`)}let r=await this.fetchImpl(this.url("github/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let a=s?JSON.parse(s):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(E,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 s=r?JSON.parse(r):null;return s?.sub?{data:s}:{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 i=await this.storage.get(g);i!=null&&(e.Authorization=`Bearer ${i}`)}let r=await this.fetchImpl(this.url("wechat-website/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let a=s?JSON.parse(s):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(E,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 s=r?JSON.parse(r):null;return s?.sub?{data:s}:{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})}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let a=s?JSON.parse(s):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={};if(this.storage){let r=await this.storage.get(v)??await this.storage.get(g);r!=null&&(t.Authorization=`Bearer ${r}`)}let e=await this.fetchImpl(this.url("sign-out"),{method:"POST",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}});return await this.clearLogin(),e.ok?{}:{error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signUp(t){let e=await this.postJson("sign-up/email",t);return e.data&&await this.persistLogin(e.data,e.response),e}async getToken(t){try{let e={};if(t)e.Authorization=`Bearer ${t}`;else if(this.storage){let i=await this.storage.get(v)??await this.storage.get(g);i!=null&&(e.Authorization=`Bearer ${i}`)}let r=await this.fetchImpl(this.url("token"),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let a=s?JSON.parse(s):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 s=await this.postJson("sign-in/phone-number",{phoneNumber:t,password:e,rememberMe:r});return s.data&&await this.persistLogin(s.data,s.response),s}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 s=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 s.text();if(!s.ok)return{error:{message:a||s.statusText,status:s.status}};let i=a?JSON.parse(a):null;return!i?.token||!i.user?{error:{message:"invalid_wechat_login_response",status:502}}:(this.storage&&(await this.storage.set(g,i.token),await this.storage.set(v,i.token),await this.storage.set(E,i.user)),{data:i})}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 s=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 s.text();if(!s.ok)return{error:{message:a||s.statusText,status:s.status}};let i=a?JSON.parse(a):null;return!i?.token||!i.user?{error:{message:"invalid_alipay_login_response",status:502}}:(this.storage&&(await this.storage.set(g,i.token),await this.storage.set(v,i.token),await this.storage.set(E,i.user)),{data:i})}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())}`:"",s=await this.fetchImpl(this.url(`wechat/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),a=await s.text();if(!s.ok)return{error:{message:a||s.statusText,status:s.status}};let i=a?JSON.parse(a):null;return!i?.openid||!i.appId?{error:{message:"invalid_wechat_identity_response",status:502}}:{data:i}}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())}`:"",s=await this.fetchImpl(this.url(`alipay/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),a=await s.text();if(!s.ok)return{error:{message:a||s.statusText,status:s.status}};let i=a?JSON.parse(a):null;return!i?.openid||!i.appId?{error:{message:"invalid_alipay_identity_response",status:502}}:{data:i}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async postJson(t,e){try{let r=await this.fetchImpl(this.url(t),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify(e)}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let a=s?JSON.parse(s):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),s=new w(e?.headers);r&&s.set("Authorization",`Bearer ${r}`);let a=e?.method||"GET";if((a==="POST"||a==="PUT"||a==="PATCH")&&e?.body){let o=s.get("Content-Type");(!o||o.includes("text/plain"))&&s.set("Content-Type","application/json")}let i=await this.customFetch(t,{...e,headers:s});if(i.status===401)throw this.handleUnauthorized(),new Error("\u672A\u767B\u5F55");return i}},ye="/storage",we=ye+"/generateUploadUrl",K=class{constructor(t,e){this.baseUrl=t,this.http=e}async uploadFile(t){let e=await this.http.fetch(this.baseUrl+we,{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 s=await this.http.fetch(r,{method:"PUT",body:t,headers:new w({"Content-Type":t.type||t.fileType||"application/octet-stream"})}),{url:a}=await s.json();return{url:a.split("?")[0]}}},ve=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},be=class{constructor(t){var e,r,s;this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=new w(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=(s=t.urlLengthLimit)!==null&&s!==void 0?s:8e3,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=new w(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 s=this.fetch,a=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{let o=null,n=null,c=null,h=i.status,l=i.statusText;if(i.ok){var u,m;if(r.method!=="HEAD"){var d;let y=await i.text();y===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&!((d=r.headers.get("Accept"))===null||d===void 0)&&d.includes("application/vnd.pgrst.plan+text")?n=y:n=JSON.parse(y))}let p=(u=r.headers.get("Prefer"))===null||u===void 0?void 0:u.match(/count=(exact|planned|estimated)/),f=(m=i.headers.get("content-range"))===null||m===void 0?void 0:m.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 i.text();try{o=JSON.parse(p),Array.isArray(o)&&i.status===404&&(n=[],o=null,h=200,l="OK")}catch{i.status===404&&p===""?(h=204,l="No Content"):o={message:p}}if(o&&r.shouldThrowOnError)throw new ve(o)}return{error:o,data:n,count:c,status:h,statusText:l}});return this.shouldThrowOnError||(a=a.catch(i=>{var o;let n="",c="",h="",l=i?.cause;if(l){var u,m,d,p;let T=(u=l?.message)!==null&&u!==void 0?u:"",O=(m=l?.code)!==null&&m!==void 0?m:"";n=`${(d=i?.name)!==null&&d!==void 0?d:"FetchError"}: ${i?.message}`,n+=`
|
|
1
|
+
"use strict";var x=Object.defineProperty;var oe=Object.getOwnPropertyDescriptor;var le=Object.getOwnPropertyNames;var he=Object.prototype.hasOwnProperty;var ce=(t,e)=>{for(var r in e)x(t,r,{get:e[r],enumerable:!0})},ue=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of le(e))!he.call(t,a)&&a!==r&&x(t,a,{get:()=>e[a],enumerable:!(i=oe(e,a))||i.enumerable});return t};var de=t=>ue(x({},"__esModule",{value:!0}),t);var ze={};ce(ze,{createSocialLoginComponent:()=>Je,default:()=>k,disableIframeHoverInspector:()=>We,enableIframeHoverInspector:()=>He,getIframeSourceLocation:()=>qe,localStorage:()=>M,setupIframeHoverInspector:()=>je,setupIframeSourceLocationListener:()=>Fe});module.exports=de(ze);var w=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()}},pe=class G{constructor(e){if(this.params=new Map,e){if(typeof e=="string")this.parseString(e);else if(e instanceof G)this.params=new Map(e.params);else if(Array.isArray(e))for(let[r,i]of e)this.append(r,i);else if(e&&typeof e=="object")for(let[r,i]of Object.entries(e))this.set(r,i)}}parseString(e){e.startsWith("?")&&(e=e.slice(1));let r=e.split("&");for(let i of r)if(i){let[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 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 pe(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]||"/",h=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(/^([^@]*)@(.+)$/),o="",l="",u=a;if(c){let f=c[1];u=c[2];let y=f.match(/^([^:]*):?(.*)$/);y&&(o=y[1]||"",l=y[2]||"")}let m=u.match(/^([^:]+):?(\d*)$/),d=m?m[1]:u,p=m&&m[2]?m[2]:"";return{protocol:i?`${i}:`:"",username:o,password:l,host:u,hostname:d,port:p,pathname:s,search:h,hash:n}}toString(){let e=this.searchParams.toString(),r=e?`?${e}`:"";return`${this.protocol}//${this.host}${this.pathname}${r}${this.hash}`}toJSON(){return this.toString()}};var B=class{constructor(t,e){this.bodyData=t,this.status=e?.status??200,this.statusText=e?.statusText??"",this.headers=me(e?.headers),this.ok=this.status>=200&&this.status<300}async text(){return typeof this.bodyData=="string"?this.bodyData:this.bodyData==null?"":typeof this.bodyData=="object"?JSON.stringify(this.bodyData):String(this.bodyData)}async json(){if(typeof this.bodyData=="string")try{return JSON.parse(this.bodyData)}catch{}return this.bodyData}async arrayBuffer(){let t=await this.text();return new TextEncoder().encode(t).buffer}};function me(t){return t?new w(t):new w}var ge=class{constructor(){this._aborted=!1,this.listeners=new Set,this.onabort=null}get aborted(){return this._aborted}_trigger(){if(!this._aborted){if(this._aborted=!0,typeof this.onabort=="function")try{this.onabort()}catch{}for(let t of Array.from(this.listeners))try{t()}catch{}this.listeners.clear()}}addEventListener(t,e){if(this._aborted){try{e()}catch{}return}this.listeners.add(e)}removeEventListener(t,e){this.listeners.delete(e)}toString(){return"[object AbortSignal]"}},fe=class{constructor(){this._signal=new ge}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}},J=class{constructor(t,e=""){this.http=t,this.baseUrl=e.replace(/\/$/,"")}async invoke(t,e){let r=this.baseUrl?`${this.baseUrl}/functions/${t}`:`/functions/${t}`;return await(await this.http.fetch(r,{method:e.method||"POST",body:e.body,headers:e.headers})).json()}},g="nvwa_current_jwt",v="nvwa_login_token",E="nvwa_user_profile",ye="set-auth-token",we=typeof fetch<"u"?(t,e)=>fetch(t,e):()=>{throw new Error("AuthClient requires fetch")},z={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 j(t){let e=z[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 H(t,e){let r=t.socialLogin?.providers?.[e];return r?.enabled?r.oauthCredentialSource==="custom"?"custom":"nvwa_default":null}var K=class{constructor(t,e={}){this.baseUrl=t.replace(/\/$/,""),this.authPath=(e.authPath??"/auth").replace(/^\//,""),this.fetchImpl=e.fetchImpl??we,this.storage=e.storage??null,this.credentials=e.credentials??"omit",this.integrationProviders=e.integrationProviders??{},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=z[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])=>j(r))}async getAvailableProviders(t){return this.getSocialProviders(t)}async startSocialLogin(t,e){let r=j(t),i=e?.returnUrl??(typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:"");switch(r.loginKind){case"google_openplatform":if(!i)throw new Error("startSocialLogin requires returnUrl for google");this.startGoogleOpenPlatformLogin(i,{applicationCode:e?.applicationCode,platformCode:e?.platformCode});return;case"github_openplatform":if(!i)throw new Error("startSocialLogin requires returnUrl for github");this.startGithubOpenPlatformLogin(i,{applicationCode:e?.applicationCode,platformCode:e?.platformCode});return;case"wechat_website_openplatform":if(!i)throw new Error("startSocialLogin requires returnUrl for wechat-website");this.startWechatWebsiteOpenPlatformLogin(i);return;case"wechat_miniprogram_code":if(!e?.miniProgramCode?.trim()||!e.applicationCode?.trim())throw new Error("startSocialLogin requires miniProgramCode and applicationCode for wechat-miniprogram");await this.loginWithWeChatCode(e.miniProgramCode.trim(),e.applicationCode.trim());return;case"alipay_miniprogram_code":if(!e?.miniProgramCode?.trim()||!e.applicationCode?.trim())throw new Error("startSocialLogin requires miniProgramCode and applicationCode for alipay-miniprogram");await this.loginWithAlipayCode(e.miniProgramCode.trim(),e.applicationCode.trim());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(E);if(r!=null)return r}let{data:t}=await this.getSession(),e=t?.user??null;return e&&this.storage&&await this.storage.set(E,e),e}async getCurrentJwt(){if(this.storage){let e=await this.storage.get(g);if(e!=null)return e;let r=await this.storage.get(v),{data:i}=await this.getToken(r??void 0);return i?.token?(await this.storage.set(g,i.token),i.token):null}let{data:t}=await this.getToken();return t?.token??null}async persistLogin(t,e){if(!this.storage)return;let r=e?.headers.get(ye)?.trim()||t.token||t.session?.token;r&&await this.storage.set(v,r),t.user&&await this.storage.set(E,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(E),await this.storage.remove(g))}getGoogleOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t});e?.applicationCode?.trim()&&r.set("application_code",e.applicationCode.trim()),e?.platformCode?.trim()&&r.set("platform_code",e.platformCode.trim());let i=H(this.integrationProviders,"google");return i&&r.set("oauth_credential_source",i),`${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(E,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});e?.applicationCode?.trim()&&r.set("application_code",e.applicationCode.trim()),e?.platformCode?.trim()&&r.set("platform_code",e.platformCode.trim());let i=H(this.integrationProviders,"github");return i&&r.set("oauth_credential_source",i),`${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(E,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(E,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={};if(this.storage){let r=await this.storage.get(v)??await this.storage.get(g);r!=null&&(t.Authorization=`Bearer ${r}`)}let e=await this.fetchImpl(this.url("sign-out"),{method:"POST",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}});return await this.clearLogin(),e.ok?{}:{error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signUp(t){let e=await this.postJson("sign-up/email",t);return e.data&&await this.persistLogin(e.data,e.response),e}async getToken(t){try{let e={};if(t)e.Authorization=`Bearer ${t}`;else if(this.storage){let 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 h=await this.storage.get(g);h!=null&&(r.Authorization=`Bearer ${h}`)}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(E,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 h=await this.storage.get(g);h!=null&&(r.Authorization=`Bearer ${h}`)}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(E,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 h=await this.storage.get(g);h!=null&&(e.Authorization=`Bearer ${h}`)}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 h=await this.storage.get(g);h!=null&&(e.Authorization=`Bearer ${h}`)}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 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 w(e?.headers);r&&i.set("Authorization",`Bearer ${r}`);let a=e?.method||"GET";if((a==="POST"||a==="PUT"||a==="PATCH")&&e?.body){let h=i.get("Content-Type");(!h||h.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}},ve="/storage",be=ve+"/generateUploadUrl",Y=class{constructor(t,e){this.baseUrl=t,this.http=e}async uploadFile(t){let e=await this.http.fetch(this.baseUrl+be,{method:"POST",body:{fileName:t.name||t.fileName,fileSize:t.size||t.fileSize,fileType:t.type||t.fileType}}),{url:r}=await e.json();if(!r)throw new Error("\u83B7\u53D6\u4E0A\u4F20URL\u5931\u8D25");let i=await this.http.fetch(r,{method:"PUT",body:t,headers:new w({"Content-Type":t.type||t.fileType||"application/octet-stream"})}),{url:a}=await i.json();return{url:a.split("?")[0]}}},Ee=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},Pe=class{constructor(t){var e,r,i;this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=new w(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 w(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 h=null,n=null,c=null,o=s.status,l=s.statusText;if(s.ok){var u,m;if(r.method!=="HEAD"){var d;let y=await s.text();y===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&!((d=r.headers.get("Accept"))===null||d===void 0)&&d.includes("application/vnd.pgrst.plan+text")?n=y:n=JSON.parse(y))}let p=(u=r.headers.get("Prefer"))===null||u===void 0?void 0:u.match(/count=(exact|planned|estimated)/),f=(m=s.headers.get("content-range"))===null||m===void 0?void 0:m.split("/");p&&f&&f.length>1&&(c=parseInt(f[1])),r.isMaybeSingle&&Array.isArray(n)&&(n.length>1?(h={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,o=406,l="Not Acceptable"):n.length===1?n=n[0]:n=null)}else{let p=await s.text();try{h=JSON.parse(p),Array.isArray(h)&&s.status===404&&(n=[],h=null,o=200,l="OK")}catch{s.status===404&&p===""?(o=204,l="No Content"):h={message:p}}if(h&&r.shouldThrowOnError)throw new Ee(h)}return{error:h,data:n,count:c,status:o,statusText:l}});return this.shouldThrowOnError||(a=a.catch(s=>{var h;let n="",c="",o="",l=s?.cause;if(l){var u,m,d,p;let C=(u=l?.message)!==null&&u!==void 0?u:"",L=(m=l?.code)!==null&&m!==void 0?m:"";n=`${(d=s?.name)!==null&&d!==void 0?d:"FetchError"}: ${s?.message}`,n+=`
|
|
2
2
|
|
|
3
|
-
Caused by: ${(p=l?.name)!==null&&p!==void 0?p:"Error"}: ${
|
|
4
|
-
${l.stack}`)}else{var f;n=(f=i?.stack)!==null&&f!==void 0?f:""}let y=this.url.toString().length;return i?.name==="AbortError"||i?.code==="ABORT_ERR"?(h="",c="Request was aborted (timeout or manual cancellation)",y>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${y} 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)",y>this.urlLengthLimit&&(c+=`. Your request URL is ${y} 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=i?.name)!==null&&o!==void 0?o:"FetchError"}: ${i?.message}`,details:n,hint:c,code:h},data:null,count:null,status:0,statusText:""}})),a.then(t,e)}returns(){return this}overrideTypes(){return this}},Ee=class extends be{select(t){let e=!1,r=(t??"*").split("").map(s=>/\s/.test(s)&&!e?"":(s==='"'&&(e=!e),s)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:s,referencedTable:a=s}={}){let i=a?`${a}.order`:"order",o=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${o?`${o},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){let s=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:s=r}={}){let a=typeof s>"u"?"offset":`${s}.offset`,i=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(a,`${t}`),this.url.searchParams.set(i,`${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:s=!1,wal:a=!1,format:i="text"}={}){var o;let n=[t?"analyze":null,e?"verbose":null,r?"settings":null,s?"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+${i}; for="${c}"; options=${n};`),i==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}},M=new RegExp("[,()]"),P=class extends Ee{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(s=>typeof s=="string"&&M.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(s=>typeof s=="string"&&M.test(s)?`"${s}"`:`${s}`).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:s}={}){let a="";s==="plain"?a="pl":s==="phrase"?a="ph":s==="websearch"&&(a="w");let i=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${a}fts${i}.${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 s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},Pe=class{constructor(t,{headers:e={},schema:r,fetch:s,urlLengthLimit:a=8e3}){this.url=t,this.headers=new w(e),this.schema=r,this.fetch=s,this.urlLengthLimit=a}cloneRequestState(){return{url:new k(this.url.toString()),headers:new w(this.headers)}}select(t,e){let{head:r=!1,count:s}=e??{},a=r?"HEAD":"GET",i=!1,o=(t??"*").split("").map(h=>/\s/.test(h)&&!i?"":(h==='"'&&(i=!i),h)).join(""),{url:n,headers:c}=this.cloneRequestState();return n.searchParams.set("select",o),s&&c.append("Prefer",`count=${s}`),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 s;let a="POST",{url:i,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}"`);i.searchParams.set("columns",c.join(","))}}return new P({method:a,url:i,headers:o,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:s,defaultToNull:a=!0}={}){var i;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),s&&c.append("Prefer",`count=${s}`),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:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;let s="PATCH",{url:a,headers:i}=this.cloneRequestState();return e&&i.append("Prefer",`count=${e}`),new P({method:s,url:a,headers:i,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:s,headers:a}=this.cloneRequestState();return t&&a.append("Prefer",`count=${t}`),new P({method:r,url:s,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 Se(t,e){if(L(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e||"default");if(L(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Oe(t){var e=Se(t,"string");return L(e)=="symbol"?e:e+""}function Le(t,e,r){return(e=Oe(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function W(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),r.push.apply(r,s)}return r}function _(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?W(Object(r),!0).forEach(function(s){Le(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):W(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var Te=class V{constructor(e,{headers:r={},schema:s,fetch:a,timeout:i,urlLengthLimit:o=8e3}={}){this.url=e,this.headers=new w(r),this.schemaName=s,this.urlLengthLimit=o;let n=a??globalThis.fetch;i!==void 0&&i>0?this.fetch=(c,h)=>{let l=new pe,u=setTimeout(()=>l.abort(),i),m=h?.signal;if(m){if(m.aborted)return clearTimeout(u),n(c,h);let d=()=>{clearTimeout(u),l.abort()};return m.addEventListener("abort",d,{once:!0}),n(c,_(_({},h),{},{signal:l.signal})).finally(()=>{clearTimeout(u),m.removeEventListener("abort",d)})}return n(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 Pe(new k(`${this.url}/${e}`),{headers:new w(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new V(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:s=!1,get:a=!1,count:i}={}){var o;let n,c=new k(`${this.url}/rpc/${e}`),h,l=d=>d!==null&&typeof d=="object"&&(!Array.isArray(d)||d.some(l)),u=s&&Object.values(r).some(l);u?(n="POST",h=r):s||a?(n=s?"HEAD":"GET",Object.entries(r).filter(([d,p])=>p!==void 0).map(([d,p])=>[d,Array.isArray(p)?`{${p.join(",")}}`:`${p}`]).forEach(([d,p])=>{c.searchParams.append(d,p)})):(n="POST",h=r);let m=new w(this.headers);return u?m.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&m.set("Prefer",`count=${i}`),new P({method:n,url:c,headers:m,schema:this.schemaName,body:h,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit})}},_e="/entities",Y=(t,e)=>new Te(t+_e,{fetch:e.fetchWithAuth.bind(e)}),Q=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"}: ${C}`,L&&(n+=` (${L})`),l?.stack&&(n+=`
|
|
4
|
+
${l.stack}`)}else{var f;n=(f=s?.stack)!==null&&f!==void 0?f:""}let y=this.url.toString().length;return s?.name==="AbortError"||s?.code==="ABORT_ERR"?(o="",c="Request was aborted (timeout or manual cancellation)",y>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${y} 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")&&(o="",c="HTTP headers exceeded server limits (typically 16KB)",y>this.urlLengthLimit&&(c+=`. Your request URL is ${y} 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:`${(h=s?.name)!==null&&h!==void 0?h:"FetchError"}: ${s?.message}`,details:n,hint:c,code:o},data:null,count:null,status:0,statusText:""}})),a.then(t,e)}returns(){return this}overrideTypes(){return this}},Se=class extends Pe{select(t){let e=!1,r=(t??"*").split("").map(i=>/\s/.test(i)&&!e?"":(i==='"'&&(e=!e),i)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:i,referencedTable:a=i}={}){let s=a?`${a}.order`:"order",h=this.url.searchParams.get(s);return this.url.searchParams.set(s,`${h?`${h},`:""}${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 h;let n=[t?"analyze":null,e?"verbose":null,r?"settings":null,i?"buffers":null,a?"wal":null].filter(Boolean).join("|"),c=(h=this.headers.get("Accept"))!==null&&h!==void 0?h:"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("[,()]"),S=class extends Se{eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){let r=Array.from(new Set(e)).map(i=>typeof i=="string"&&W.test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(i=>typeof i=="string"&&W.test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:i}={}){let 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}},Le=class{constructor(t,{headers:e={},schema:r,fetch:i,urlLengthLimit:a=8e3}){this.url=t,this.headers=new w(e),this.schema=r,this.fetch=i,this.urlLengthLimit=a}cloneRequestState(){return{url:new I(this.url.toString()),headers:new w(this.headers)}}select(t,e){let{head:r=!1,count:i}=e??{},a=r?"HEAD":"GET",s=!1,h=(t??"*").split("").map(o=>/\s/.test(o)&&!s?"":(o==='"'&&(s=!s),o)).join(""),{url:n,headers:c}=this.cloneRequestState();return n.searchParams.set("select",h),i&&c.append("Prefer",`count=${i}`),new S({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:h}=this.cloneRequestState();if(e&&h.append("Prefer",`count=${e}`),r||h.append("Prefer","missing=default"),Array.isArray(t)){let n=t.reduce((c,o)=>c.concat(Object.keys(o)),[]);if(n.length>0){let c=[...new Set(n)].map(o=>`"${o}"`);s.searchParams.set("columns",c.join(","))}}return new S({method:a,url:s,headers:h,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 h="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 o=t.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(o.length>0){let l=[...new Set(o)].map(u=>`"${u}"`);n.searchParams.set("columns",l.join(","))}}return new S({method:h,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 S({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 S({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 Oe(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 Ce(t){var e=Oe(t,"string");return O(e)=="symbol"?e:e+""}function Te(t,e,r){return(e=Ce(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function q(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 T(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?q(Object(r),!0).forEach(function(i){Te(t,i,r[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):q(Object(r)).forEach(function(i){Object.defineProperty(t,i,Object.getOwnPropertyDescriptor(r,i))})}return t}var _e=class Q{constructor(e,{headers:r={},schema:i,fetch:a,timeout:s,urlLengthLimit:h=8e3}={}){this.url=e,this.headers=new w(r),this.schemaName=i,this.urlLengthLimit=h;let n=a??globalThis.fetch;s!==void 0&&s>0?this.fetch=(c,o)=>{let l=new fe,u=setTimeout(()=>l.abort(),s),m=o?.signal;if(m){if(m.aborted)return clearTimeout(u),n(c,o);let d=()=>{clearTimeout(u),l.abort()};return m.addEventListener("abort",d,{once:!0}),n(c,T(T({},o),{},{signal:l.signal})).finally(()=>{clearTimeout(u),m.removeEventListener("abort",d)})}return n(c,T(T({},o),{},{signal:l.signal})).finally(()=>clearTimeout(u))}:this.fetch=n}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new Le(new I(`${this.url}/${e}`),{headers:new w(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 h;let n,c=new I(`${this.url}/rpc/${e}`),o,l=d=>d!==null&&typeof d=="object"&&(!Array.isArray(d)||d.some(l)),u=i&&Object.values(r).some(l);u?(n="POST",o=r):i||a?(n=i?"HEAD":"GET",Object.entries(r).filter(([d,p])=>p!==void 0).map(([d,p])=>[d,Array.isArray(p)?`{${p.join(",")}}`:`${p}`]).forEach(([d,p])=>{c.searchParams.append(d,p)})):(n="POST",o=r);let m=new w(this.headers);return u?m.set("Prefer",s?`count=${s},return=minimal`:"return=minimal"):s&&m.set("Prefer",`count=${s}`),new S({method:n,url:c,headers:m,schema:this.schemaName,body:o,fetch:(h=this.fetch)!==null&&h!==void 0?h:fetch,urlLengthLimit:this.urlLengthLimit})}},$e="/entities",X=(t,e)=>new _e(t+$e,{fetch:e.fetchWithAuth.bind(e)}),Z=class{constructor(){this.hoverOverlay=null,this.selectedOverlay=null,this.tooltip=null,this.hoverElement=null,this.selectedElement=null,this.hoverUpdateHandler=null,this.selectedUpdateHandler=null,this.createStyles()}createStyles(){if(document.getElementById("__nvwa-inspector-overlay-style"))return;let t=document.createElement("style");t.id="__nvwa-inspector-overlay-style",t.textContent=`
|
|
5
5
|
.__nvwa-inspector-overlay {
|
|
6
6
|
position: absolute;
|
|
7
7
|
pointer-events: none;
|
|
@@ -33,4 +33,4 @@ ${l.stack}`)}else{var f;n=(f=i?.stack)!==null&&f!==void 0?f:""}let y=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(),s=window.scrollX||window.pageXOffset,a=window.scrollY||window.pageYOffset;r.width>0&&r.height>0?(t.style.left=`${r.left+s}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 s=()=>{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=s,window.addEventListener("scroll",s,!0),window.addEventListener("resize",s);let a=this.createTooltip();e?a.textContent=e:a.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,a.style.display="block";let i=t.getBoundingClientRect();a.style.left=`${i.left+window.scrollX}px`,a.style.top=`${i.top+window.scrollY-a.offsetHeight-8}px`,i.top<a.offsetHeight+8&&(a.style.top=`${i.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 s=()=>{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=s,window.addEventListener("scroll",s,!0),window.addEventListener("resize",s)}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 X(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 s=r.getAttribute("data-source-location");if(s)return s}if(e.firstElementChild){let s=e.firstElementChild.getAttribute("data-source-location");if(s)return s}return null}var $e={"wechat-pay":{id:"wechat-pay",name:"WeChat Pay",description:"WeChat payment for web and miniapp."},wechat_partner:{id:"wechat_partner",name:"WeChat Partner",description:"WeChat partner merchant onboarding."},alipay:{id:"alipay",name:"Alipay",description:"Alipay payment."},"alipay-miniprogram":{id:"alipay-miniprogram",name:"Alipay Mini Program",description:"Alipay mini program payment."},stripe:{id:"stripe",name:"Stripe",description:"Stripe payment."}};function Z(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 ee(t,e){let r=t.payment?.providers??{};return Object.entries(r).filter(([,s])=>s.enabled).map(([s])=>$e[s]??{id:s,name:s,description:""})}function $(t){return t&&typeof t=="object"?t:{}}function Ce(t){let e=$(t),r=e.enabled===!0,s=String(e.oauthCredentialSource??"").toLowerCase();return s?{enabled:r,oauthCredentialSource:s==="custom"?"custom":"nvwa_default"}:{enabled:r}}function q(t){let e=$(t),r=$(e.providers),s={};for(let[a,i]of Object.entries(r))s[a]=Ce(i);return{providers:s}}function te(t){let e=$(t);return{socialLogin:q(e.socialLogin),payment:q(e.payment)}}var C=class{constructor(){this.prefix="nvwa_"}getKey(e){return`${this.prefix}${e}`}async get(e){try{let r=this.getKey(e),s=uni.getStorageSync(r);return s?s.expires&&Date.now()>s.expires?(await this.remove(e),null):s.value:null}catch(r){return console.error("UniAppStorageService get error:",r),null}}async set(e,r,s){try{let a=this.getKey(e),i={value:r,expires:s?Date.now()+s*1e3:null,timestamp:Date.now()};uni.setStorageSync(a,i)}catch(a){throw console.error("UniAppStorageService set error:",a),a}}async remove(e){try{let r=this.getKey(e);uni.removeStorageSync(r)}catch(r){throw console.error("UniAppStorageService remove error:",r),r}}async clear(){try{uni.clearStorageSync()}catch(e){throw console.error("UniAppStorageService clear error:",e),e}}};var A=(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 uniappFetch");typeof console<"u"&&(console.warn("[NvwaUni] request url:",r,"method:",(e?.method||"GET").toUpperCase()),!r.startsWith("http://")&&!r.startsWith("https://")&&console.warn("[NvwaUni] url \u975E\u5B8C\u6574\u5730\u5740\uFF0C\u5C0F\u7A0B\u5E8F uni.request \u4F1A\u62A5 invalid url\uFF0C\u8BF7\u68C0\u67E5 baseUrl \u662F\u5426\u4F20\u5165\u5B8C\u6574\u57DF\u540D"));let s=(e?.method||"GET").toUpperCase(),a={};if(e?.headers){let n=e.headers;if(typeof n?.forEach=="function")n.forEach((c,h)=>{a[h]=c});else if(Array.isArray(n))for(let[c,h]of n)a[c]=h;else Object.assign(a,n)}let i;if(e?.body!==void 0){let n=e.body;if(typeof n=="string")i=n;else if(n&&typeof n=="object"&&typeof n.forEach=="function"){let c={};n.forEach((h,l)=>{c[l]=h}),i=c}else i=n}let o=e?.timeout||3e4;return new Promise((n,c)=>{let h=e?.signal;if(h?.aborted){let d=new Error("The operation was aborted");d.name="AbortError",c(d);return}let l=!1,u=[],m=uni.request({url:r,method:s,data:i,header:a,timeout:o,success:d=>{if(l)return;l=!0;let p=d.statusCode,f="",y=new w,T=d.header||d.headers||{};Object.keys(T).forEach(O=>{let x=T[O];y.set(O,typeof x=="string"?x:String(x))}),n(new B(d.data,{status:p,statusText:f,headers:y}))},fail:d=>{if(l)return;l=!0;let p=d?.errMsg||d?.message||"Network Error",f=new Error(p);/(abort|aborted|canceled|cancelled)/i.test(String(p))&&(f.name="AbortError"),c(f)}});if(h&&typeof h.addEventListener=="function"){let d=()=>{if(l)return;try{m?.abort?.()}catch{}let p=new Error("The operation was aborted");p.name="AbortError",l=!0,c(p)};h.addEventListener("abort",d),u.push(()=>{try{h.removeEventListener?.("abort",d)}catch{}})}})};globalThis&&typeof globalThis.fetch!="function"&&(globalThis.fetch=A);var b="Mobile-web";try{if(typeof uni<"u"&&typeof uni?.getSystemInfoSync=="function"){let t=uni.getSystemInfoSync()??{},e=t.uniPlatform,r=t.osName,s=t.ua??(typeof navigator<"u"?navigator.userAgent:"");e==="mp-weixin"?b="MP-Wechat":e==="mp-alipay"?b="MP-Alipay":e==="app"?r==="ios"?b="IOS":r==="android"?b="Android":r==="harmonyos"&&(b="Harmony"):(e==="web"||e==="h5")&&(b=s&&/MicroMessenger/i.test(s)?"Wechat-H5":"Mobile-web")}else typeof navigator<"u"&&/MicroMessenger/i.test(navigator.userAgent)&&(b="Wechat-H5")}catch{b="Mobile-web"}function Ae(t){return`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(t)}`}function re(t){if(typeof window<"u"){window.open(t,"_blank");return}globalThis.plus?.runtime?.openURL?.(t)}async function Ie(t){if(t.kind!=="alipay_miniprogram")throw new Error("requestPayment: invalid payParams for alipay miniprogram");await new Promise((e,r)=>{let s=globalThis.my;if(!s?.tradePay){r(new Error("requestPayment: my.tradePay is unavailable"));return}s.tradePay({tradeNO:t.tradeNO,success:()=>e(),fail:a=>r(a)})})}async function xe(t){if(t.kind!=="wechat_jsapi")throw new Error("requestPayment: invalid payParams for wechat jsapi");let e=t.jsapiPayParams;await new Promise((r,s)=>{uni.requestPayment({provider:"wxpay",timeStamp:e.timeStamp,nonceStr:e.nonceStr,package:e.package,signType:e.signType??"RSA",paySign:e.paySign,success:()=>r(),fail:a=>s(a)})})}function Ne(t){if(t.kind!=="redirect_url")throw new Error("requestPayment: invalid payParams for redirect");typeof window<"u"?window.location.href=t.redirectUrl:re(t.redirectUrl)}function ke(t){if(t.kind!=="wechat_native_qr")throw new Error("requestPayment: invalid payParams for wechat qr");let e=Ae(t.codeUrl);re(e)}async function Ue(t){if(!t)return!1;switch(t.kind){case"alipay_miniprogram":return await Ie(t),!0;case"wechat_jsapi":return await xe(t),!0;case"redirect_url":return Ne(t),!0;case"wechat_native_qr":return ke(t),!0;default:return!1}}var R={async requestPayment(t,e){try{let r=Z(t);if(!await Ue(r))throw new Error("requestPayment: unsupported payParams for current endpoint");e?.onSuccess?.()}catch(r){throw e?.onFailure?.(r),r}}};function se(t){let e=async r=>await ee(t,r);return{...R,getAvailableProviders:e,getProviders:e}}function Re(){if(typeof window>"u"||window===window.parent)return;let t=!1,e=new Q;function r(h){if(!h)return!1;let l=h.toLowerCase();return l.includes("/components/")||l.includes("\\components\\")}function s(h){let l=h,u=null;for(;l;){let m=l.getAttribute("data-source-location");if(m)if(r(m)){u||(u=m),l=l.parentElement;continue}else return m;l=l.parentElement}return u}let a=null;function i(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=s(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,m=s(l);if(!m){let p=l.parentElement;for(;p&&p!==document.body&&p!==document.documentElement;){let f=s(p);if(f){u=p,m=f;break}p=p.parentElement}}e.highlightElement(u,m);let d={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:m,elementInfo:{tagName:u.tagName.toLowerCase(),className:u.className||"",id:u.id||""}};window.parent.postMessage(d,"*")}))}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=s(l);e.selectElement(l,u);let m={type:"HOVER_INSPECTOR_ELEMENT_SELECT",sourceLocation:u,elementInfo:{tagName:l.tagName.toLowerCase(),className:l.className||"",id:l.id||""}};window.parent.postMessage(m,"*")}function c(h){h.data?.type==="HOVER_INSPECTOR_ENABLE"?(t=!0,document.addEventListener("mousemove",i),document.addEventListener("mouseleave",o),document.addEventListener("click",n,!0)):h.data?.type==="HOVER_INSPECTOR_DISABLE"&&(t=!1,document.removeEventListener("mousemove",i),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",i),document.removeEventListener("mouseleave",o),document.removeEventListener("click",n,!0),e.cleanup()}}function He(t,e){if(!t||!t.contentWindow)throw new Error("Invalid iframe element");let r={type:"HOVER_INSPECTOR_ENABLE"};t.contentWindow.postMessage(r,e)}function je(t,e){if(!t||!t.contentWindow)return;let r={type:"HOVER_INSPECTOR_DISABLE"};t.contentWindow.postMessage(r,e)}function Me(t,e,r=5e3){return new Promise((s,a)=>{if(!t||!t.contentWindow){a(new Error("Invalid iframe element"));return}let i=`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===i&&(clearTimeout(o),window.removeEventListener("message",n),h.data.error?a(new Error(h.data.error)):s(h.data.sourceLocation||null))};window.addEventListener("message",n);let c={type:"GET_SOURCE_LOCATION_REQUEST",requestId:i};try{t.contentWindow.postMessage(c,e)}catch(h){clearTimeout(o),window.removeEventListener("message",n),a(h)}})}function We(){if(typeof window>"u"||window===window.parent)return;let t=e=>{if(e.data?.type==="GET_SOURCE_LOCATION_REQUEST")try{let s={type:"GET_SOURCE_LOCATION_RESPONSE",sourceLocation:qe(),requestId:e.data.requestId};window.parent.postMessage(s,e.origin)}catch(r){let s={type:"GET_SOURCE_LOCATION_RESPONSE",sourceLocation:null,error:r instanceof Error?r.message:"Unknown error",requestId:e.data.requestId};window.parent.postMessage(s,e.origin)}};return window.addEventListener("message",t),()=>{window.removeEventListener("message",t)}}function qe(){return X("app")}var H=new C,I=class{constructor(e){this.payment=R;this.endpointType=b;let{baseUrl:r,handleUnauthorized:s,applicationCode:a,platformType:i,integrationProviders:o}=e;typeof console<"u"&&console.warn("[Nvwa] uniapp init baseUrl:",r||"(empty)");let n=a.trim();if(!n)throw new Error("Nvwa: applicationCode \u4E0D\u80FD\u4E3A\u7A7A");this.applicationCode=n;let c=i.trim();if(!c)throw new Error("Nvwa: platformType \u4E0D\u80FD\u4E3A\u7A7A");this.platformType=c,this.integrationProviders=te(o),this.auth=new J(r,{fetchImpl:A,storage:H,integrationProviders:this.integrationProviders}),this.httpClient=new z(H,A,s),this.fileStorage=new K(r,this.httpClient),this.entities=Y(r,this.httpClient),this.functions=new D(this.httpClient,r),this.payment=se(this.integrationProviders)}};0&&(module.exports={disableIframeHoverInspector,enableIframeHoverInspector,getIframeSourceLocation,localStorage,setupIframeHoverInspector,setupIframeSourceLocationListener});
|
|
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 h=this.createTooltip();e?h.textContent=e:h.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,h.style.display="block";let n=t.getBoundingClientRect();h.style.left=`${n.left+window.scrollX}px`,h.style.top=`${n.top+window.scrollY-h.offsetHeight-8}px`,n.top<h.offsetHeight+8&&(h.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 Ae={"wechat-pay":{id:"wechat-pay",name:"WeChat Pay",description:"WeChat payment for web and miniapp."},wechat_partner:{id:"wechat_partner",name:"WeChat Partner",description:"WeChat partner merchant onboarding."},alipay:{id:"alipay",name:"Alipay",description:"Alipay payment."},"alipay-miniprogram":{id:"alipay-miniprogram",name:"Alipay Mini Program",description:"Alipay mini program payment."},stripe:{id:"stripe",name:"Stripe",description:"Stripe payment."}};function te(t){let e=t;if(typeof e.kind=="string")return e;if(typeof e.tradeNO=="string")return{kind:"alipay_miniprogram",tradeNO:e.tradeNO};if(typeof e.clientSecret=="string")return{kind:"stripe_client_secret",clientSecret:e.clientSecret};if(typeof e.redirectUrl=="string")return{kind:"redirect_url",redirectUrl:e.redirectUrl};if(typeof e.formHtml=="string")return{kind:"alipay_page",formHtml:e.formHtml};if(typeof e.codeUrl=="string")return{kind:"wechat_native_qr",codeUrl:e.codeUrl};let r=e.jsapiPayParams??e;return typeof r.timeStamp=="string"&&typeof r.nonceStr=="string"&&typeof r.package=="string"&&typeof r.paySign=="string"&&typeof r.appId=="string"?{kind:"wechat_jsapi",mode:"jsapi",jsapiPayParams:{appId:r.appId,timeStamp:r.timeStamp,nonceStr:r.nonceStr,package:r.package,signType:r.signType??"RSA",paySign:r.paySign}}:null}async function re(t,e){let r=t.payment?.providers??{};return Object.entries(r).filter(([,i])=>i.enabled).map(([i])=>{let a=Ae[i]??{id:i,name:i,description:""};return{...a,type:a.id}})}function _(t){return t&&typeof t=="object"?t:{}}function ke(t){let e=_(t),r=e.enabled===!0,i=String(e.oauthCredentialSource??"").toLowerCase();return i?{enabled:r,oauthCredentialSource:i==="custom"?"custom":"nvwa_default"}:{enabled:r}}function F(t){let e=_(t),r=_(e.providers),i={};for(let[a,s]of Object.entries(r))i[a]=ke(s);return{providers:i}}function ie(t){let e=_(t);return{socialLogin:F(e.socialLogin),payment:F(e.payment)}}var $=class{constructor(){this.prefix="nvwa_"}getKey(e){return`${this.prefix}${e}`}async get(e){try{let r=this.getKey(e),i=uni.getStorageSync(r);return i?i.expires&&Date.now()>i.expires?(await this.remove(e),null):i.value:null}catch(r){return console.error("UniAppStorageService 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()};uni.setStorageSync(a,s)}catch(a){throw console.error("UniAppStorageService set error:",a),a}}async remove(e){try{let r=this.getKey(e);uni.removeStorageSync(r)}catch(r){throw console.error("UniAppStorageService remove error:",r),r}}async clear(){try{uni.clearStorageSync()}catch(e){throw console.error("UniAppStorageService clear error:",e),e}}};var A=(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 uniappFetch");typeof console<"u"&&(console.warn("[NvwaUni] request url:",r,"method:",(e?.method||"GET").toUpperCase()),!r.startsWith("http://")&&!r.startsWith("https://")&&console.warn("[NvwaUni] url \u975E\u5B8C\u6574\u5730\u5740\uFF0C\u5C0F\u7A0B\u5E8F uni.request \u4F1A\u62A5 invalid url\uFF0C\u8BF7\u68C0\u67E5 baseUrl \u662F\u5426\u4F20\u5165\u5B8C\u6574\u57DF\u540D"));let i=(e?.method||"GET").toUpperCase(),a={};if(e?.headers){let n=e.headers;if(typeof n?.forEach=="function")n.forEach((c,o)=>{a[o]=c});else if(Array.isArray(n))for(let[c,o]of n)a[c]=o;else Object.assign(a,n)}let s;if(e?.body!==void 0){let n=e.body;if(typeof n=="string")s=n;else if(n&&typeof n=="object"&&typeof n.forEach=="function"){let c={};n.forEach((o,l)=>{c[l]=o}),s=c}else s=n}let h=e?.timeout||3e4;return new Promise((n,c)=>{let o=e?.signal;if(o?.aborted){let d=new Error("The operation was aborted");d.name="AbortError",c(d);return}let l=!1,u=[],m=uni.request({url:r,method:i,data:s,header:a,timeout:h,success:d=>{if(l)return;l=!0;let p=d.statusCode,f="",y=new w,C=d.header||d.headers||{};Object.keys(C).forEach(L=>{let U=C[L];y.set(L,typeof U=="string"?U:String(U))}),n(new B(d.data,{status:p,statusText:f,headers:y}))},fail:d=>{if(l)return;l=!0;let p=d?.errMsg||d?.message||"Network Error",f=new Error(p);/(abort|aborted|canceled|cancelled)/i.test(String(p))&&(f.name="AbortError"),c(f)}});if(o&&typeof o.addEventListener=="function"){let d=()=>{if(l)return;try{m?.abort?.()}catch{}let p=new Error("The operation was aborted");p.name="AbortError",l=!0,c(p)};o.addEventListener("abort",d),u.push(()=>{try{o.removeEventListener?.("abort",d)}catch{}})}})};globalThis&&typeof globalThis.fetch!="function"&&(globalThis.fetch=A);var b="Mobile-web";try{if(typeof uni<"u"&&typeof uni?.getSystemInfoSync=="function"){let t=uni.getSystemInfoSync()??{},e=t.uniPlatform,r=t.osName,i=t.ua??(typeof navigator<"u"?navigator.userAgent:"");e==="mp-weixin"?b="MP-Wechat":e==="mp-alipay"?b="MP-Alipay":e==="app"?r==="ios"?b="IOS":r==="android"?b="Android":r==="harmonyos"&&(b="Harmony"):(e==="web"||e==="h5")&&(b=i&&/MicroMessenger/i.test(i)?"Wechat-H5":"Mobile-web")}else typeof navigator<"u"&&/MicroMessenger/i.test(navigator.userAgent)&&(b="Wechat-H5")}catch{b="Mobile-web"}function Ue(t){return`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(t)}`}function ae(t){if(typeof window<"u"){window.open(t,"_blank");return}globalThis.plus?.runtime?.openURL?.(t)}async function xe(t){if(t.kind!=="alipay_miniprogram")throw new Error("requestPayment: invalid payParams for alipay miniprogram");await new Promise((e,r)=>{let i=globalThis.my;if(!i?.tradePay){r(new Error("requestPayment: my.tradePay is unavailable"));return}i.tradePay({tradeNO:t.tradeNO,success:()=>e(),fail:a=>r(a)})})}async function Ie(t){if(t.kind!=="wechat_jsapi")throw new Error("requestPayment: invalid payParams for wechat jsapi");let e=t.jsapiPayParams;await new Promise((r,i)=>{uni.requestPayment({provider:"wxpay",timeStamp:e.timeStamp,nonceStr:e.nonceStr,package:e.package,signType:e.signType??"RSA",paySign:e.paySign,success:()=>r(),fail:a=>i(a)})})}function Ne(t){if(t.kind!=="redirect_url")throw new Error("requestPayment: invalid payParams for redirect");typeof window<"u"?window.location.href=t.redirectUrl:ae(t.redirectUrl)}function Re(t){if(t.kind!=="wechat_native_qr")throw new Error("requestPayment: invalid payParams for wechat qr");let e=Ue(t.codeUrl);ae(e)}async function Me(t){if(!t)return!1;switch(t.kind){case"alipay_miniprogram":return await xe(t),!0;case"wechat_jsapi":return await Ie(t),!0;case"redirect_url":return Ne(t),!0;case"wechat_native_qr":return Re(t),!0;default:return!1}}var R={async requestPayment(t,e){try{let r=te(t);if(!await Me(r))throw new Error("requestPayment: unsupported payParams for current endpoint");e?.onSuccess?.()}catch(r){throw e?.onFailure?.(r),r}}};function se(t){let e=async r=>await re(t,r);return{...R,getAvailableProviders:e,getProviders:e}}function je(){if(typeof window>"u"||window===window.parent)return;let t=!1,e=new Z;function r(o){if(!o)return!1;let l=o.toLowerCase();return l.includes("/components/")||l.includes("\\components\\")}function i(o){let l=o,u=null;for(;l;){let m=l.getAttribute("data-source-location");if(m)if(r(m)){u||(u=m),l=l.parentElement;continue}else return m;l=l.parentElement}return u}let a=null;function s(o){t&&(a!==null&&cancelAnimationFrame(a),a=requestAnimationFrame(()=>{let l=o.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,m=i(l);if(!m){let p=l.parentElement;for(;p&&p!==document.body&&p!==document.documentElement;){let f=i(p);if(f){u=p,m=f;break}p=p.parentElement}}e.highlightElement(u,m);let d={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:m,elementInfo:{tagName:u.tagName.toLowerCase(),className:u.className||"",id:u.id||""}};window.parent.postMessage(d,"*")}))}function h(){if(!t)return;e.removeHighlight();let o={type:"HOVER_INSPECTOR_ELEMENT_LEAVE"};window.parent.postMessage(o,"*")}function n(o){if(!t)return;o.preventDefault(),o.stopPropagation();let l=o.target;if(!l||l===document.body||l===document.documentElement)return;let u=i(l);e.selectElement(l,u);let m={type:"HOVER_INSPECTOR_ELEMENT_SELECT",sourceLocation:u,elementInfo:{tagName:l.tagName.toLowerCase(),className:l.className||"",id:l.id||""}};window.parent.postMessage(m,"*")}function c(o){o.data?.type==="HOVER_INSPECTOR_ENABLE"?(t=!0,document.addEventListener("mousemove",s),document.addEventListener("mouseleave",h),document.addEventListener("click",n,!0)):o.data?.type==="HOVER_INSPECTOR_DISABLE"&&(t=!1,document.removeEventListener("mousemove",s),document.removeEventListener("mouseleave",h),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",h),document.removeEventListener("click",n,!0),e.cleanup()}}function He(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 qe(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()}`,h=setTimeout(()=>{window.removeEventListener("message",n),a(new Error("Request timeout"))},r),n=o=>{o.origin===e&&o.data?.type==="GET_SOURCE_LOCATION_RESPONSE"&&o.data?.requestId===s&&(clearTimeout(h),window.removeEventListener("message",n),o.data.error?a(new Error(o.data.error)):i(o.data.sourceLocation||null))};window.addEventListener("message",n);let c={type:"GET_SOURCE_LOCATION_REQUEST",requestId:s};try{t.contentWindow.postMessage(c,e)}catch(o){clearTimeout(h),window.removeEventListener("message",n),a(o)}})}function Fe(){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("app")}function Ge(t){let e=t==="wechat-miniprogram"?"weixin":t==="alipay-miniprogram"?"alipay":t==="douyin-miniprogram"?"toutiao":void 0;return e?new Promise((r,i)=>{uni.login({provider:e,success:a=>{if(!a.code?.trim()){i(new Error(`login code missing for ${t}`));return}r(a.code.trim())},fail:a=>{i(a instanceof Error?a:new Error(`uni.login failed: ${String(a)}`))}})}):Promise.reject(new Error(`unsupported miniprogram provider: ${t}`))}async function Be(t,e){return e??await t.getSocialProviderDescriptors()}function ne(t){return t?.trim()?t.trim():typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:""}function Je(t){let{name:e="NvwaSocialLoginButtons",auth:r,applicationCode:i,providers:a,containerClass:s="nvwa-social-login-list",providerClass:h="nvwa-social-login-button"}=t,n=t.resolveMiniProgramCode??Ge;return{name:e,data(){return{providers:[],loading:!0}},async created(){try{this.providers=await Be(r,a)}catch(c){t.onError?.(c instanceof Error?c:new Error(String(c)))}finally{this.loading=!1}},methods:{async handleProviderTap(c){try{if(t.onBeforeLogin?.(c),c.loginKind==="wechat_miniprogram_code"||c.loginKind==="alipay_miniprogram_code"){let o=await n(c.id);await r.startSocialLogin(c.id,{miniProgramCode:o,applicationCode:i,returnUrl:ne(t.returnUrl)});return}await r.startSocialLogin(c.id,{returnUrl:ne(t.returnUrl),applicationCode:i})}catch(o){t.onError?.(o instanceof Error?o:new Error(String(o)))}}},render(){if(this.loading||this.providers.length===0)return null;let c=this.$createElement,o=this.providers.filter(l=>l.loginKind!=="unsupported").map(l=>c("button",{key:l.id,class:h,attrs:{type:"button"},on:{click:()=>this.handleProviderTap(l)}},l.name));return c("view",{class:s},o)}}}var M=new $,k=class{constructor(e){this.payment=R;this.endpointType=b;let{baseUrl:r,handleUnauthorized:i,applicationCode:a,platformType:s,integrationProviders:h}=e;typeof console<"u"&&console.warn("[Nvwa] uniapp init baseUrl:",r||"(empty)");let n=a.trim();if(!n)throw new Error("Nvwa: applicationCode \u4E0D\u80FD\u4E3A\u7A7A");this.applicationCode=n;let c=s.trim();if(!c)throw new Error("Nvwa: platformType \u4E0D\u80FD\u4E3A\u7A7A");this.platformType=c,this.integrationProviders=ie(h),this.auth=new K(r,{fetchImpl:A,storage:M,integrationProviders:this.integrationProviders}),this.httpClient=new V(M,A,i),this.fileStorage=new Y(r,this.httpClient),this.entities=X(r,this.httpClient),this.functions=new J(this.httpClient,r),this.payment=se(this.integrationProviders)}};0&&(module.exports={createSocialLoginComponent,disableIframeHoverInspector,enableIframeHoverInspector,getIframeSourceLocation,localStorage,setupIframeHoverInspector,setupIframeSourceLocationListener});
|
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var w=class q{constructor(e){if(this.headerMap=new Map,e){if(e instanceof q)e.forEach((r,s)=>this.set(s,r));else if(Array.isArray(e))for(let[r,s]of e)this.set(r,String(s));else if(typeof e=="object")for(let r of Object.keys(e))this.set(r,String(e[r]))}}append(e,r){let s=e.toLowerCase(),a=this.headerMap.get(s);this.headerMap.set(s,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,s]of this.headerMap.entries())e(s,r,this)}entries(){return this.headerMap.entries()}keys(){return this.headerMap.keys()}values(){return this.headerMap.values()}[Symbol.iterator](){return this.entries()}},ae=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,s]of e)this.append(r,s);else if(e&&typeof e=="object")for(let[r,s]of Object.entries(e))this.set(r,s)}}parseString(e){e.startsWith("?")&&(e=e.slice(1));let r=e.split("&");for(let s of r)if(s){let[a,i]=s.split("=");a&&this.append(decodeURIComponent(a),i?decodeURIComponent(i):"")}}append(e,r){let s=this.params.get(e)||[];s.push(r),this.params.set(e,s)}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],[s])=>r.localeCompare(s));this.params=new Map(e)}toString(){let e=[];for(let[r,s]of this.params.entries())for(let a of s)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(a)}`);return e.join("&")}forEach(e){for(let[r,s]of this.params.entries())for(let a of s)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,s]of this.params.entries())for(let a of s)e.push([r,a]);return e[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}},N=class k{constructor(e,r){let s;if(e instanceof k)s=e.href;else if(r){let i=r instanceof k?r.href:r;s=this.resolve(i,e)}else s=e;let a=this.parseUrl(s);this.href=s,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 ae(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 i=this.parseUrl(e);return`${i.protocol}//${i.host}${r}`}let s=this.parseUrl(e),a=s.pathname.endsWith("/")?s.pathname:s.pathname+"/";return`${s.protocol}//${s.host}${a}${r}`}parseUrl(e){let r=e.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!r)throw new TypeError("Invalid URL");let s=r[2]||"",a=r[4]||"",i=r[5]||"/",o=r[7]?`?${r[7]}`:"",n=r[9]?`#${r[9]}`:"";if(!s&&!a&&!i.startsWith("/")&&!i.includes("/")&&!i.includes("."))throw new TypeError("Invalid URL");let c=a.match(/^([^@]*)@(.+)$/),h="",l="",u=a;if(c){let f=c[1];u=c[2];let y=f.match(/^([^:]*):?(.*)$/);y&&(h=y[1]||"",l=y[2]||"")}let m=u.match(/^([^:]+):?(\d*)$/),d=m?m[1]:u,p=m&&m[2]?m[2]:"";return{protocol:s?`${s}:`:"",username:h,password:l,host:u,hostname:d,port:p,pathname:i,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=ie(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 ie(t){return t?new w(t):new w}var ne=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]"}},oe=class{constructor(){this._signal=new ne}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}},B=class{constructor(t,e=""){this.http=t,this.baseUrl=e.replace(/\/$/,"")}async invoke(t,e){let r=this.baseUrl?`${this.baseUrl}/functions/${t}`:`/functions/${t}`;return await(await this.http.fetch(r,{method:e.method||"POST",body:e.body,headers:e.headers})).json()}},g="nvwa_current_jwt",v="nvwa_login_token",E="nvwa_user_profile",le="set-auth-token",he=typeof fetch<"u"?(t,e)=>fetch(t,e):()=>{throw new Error("AuthClient requires fetch")},ce={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."}};function H(t,e){let r=t.socialLogin?.providers?.[e];return r?.enabled?r.oauthCredentialSource==="custom"?"custom":"nvwa_default":null}var D=class{constructor(t,e={}){this.baseUrl=t.replace(/\/$/,""),this.authPath=(e.authPath??"/auth").replace(/^\//,""),this.fetchImpl=e.fetchImpl??he,this.storage=e.storage??null,this.credentials=e.credentials??"omit",this.integrationProviders=e.integrationProviders??{},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])=>ce[r]??{id:r,name:r,description:""})}async currentUser(){if(this.storage){let r=await this.storage.get(E);if(r!=null)return r}let{data:t}=await this.getSession(),e=t?.user??null;return e&&this.storage&&await this.storage.set(E,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:s}=await this.getToken(r??void 0);return s?.token?(await this.storage.set(g,s.token),s.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(le)?.trim()||t.token||t.session?.token;r&&await this.storage.set(v,r),t.user&&await this.storage.set(E,t.user);let s=r??await this.storage.get(v),{data:a}=await this.getToken(s??void 0);a?.token&&await this.storage.set(g,a.token)}async clearLogin(){this.storage&&(await this.storage.remove(v),await this.storage.remove(E),await this.storage.remove(g))}getGoogleOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t});e?.applicationCode?.trim()&&r.set("application_code",e.applicationCode.trim()),e?.platformCode?.trim()&&r.set("platform_code",e.platformCode.trim());let s=H(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 i=await this.storage.get(g);i!=null&&(e.Authorization=`Bearer ${i}`)}let r=await this.fetchImpl(this.url("google/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let a=s?JSON.parse(s):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(E,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 s=r?JSON.parse(r):null;return s?.sub?{data:s}:{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});e?.applicationCode?.trim()&&r.set("application_code",e.applicationCode.trim()),e?.platformCode?.trim()&&r.set("platform_code",e.platformCode.trim());let s=H(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 i=await this.storage.get(g);i!=null&&(e.Authorization=`Bearer ${i}`)}let r=await this.fetchImpl(this.url("github/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let a=s?JSON.parse(s):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(E,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 s=r?JSON.parse(r):null;return s?.sub?{data:s}:{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 i=await this.storage.get(g);i!=null&&(e.Authorization=`Bearer ${i}`)}let r=await this.fetchImpl(this.url("wechat-website/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let a=s?JSON.parse(s):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(E,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 s=r?JSON.parse(r):null;return s?.sub?{data:s}:{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})}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let a=s?JSON.parse(s):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={};if(this.storage){let r=await this.storage.get(v)??await this.storage.get(g);r!=null&&(t.Authorization=`Bearer ${r}`)}let e=await this.fetchImpl(this.url("sign-out"),{method:"POST",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}});return await this.clearLogin(),e.ok?{}:{error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signUp(t){let e=await this.postJson("sign-up/email",t);return e.data&&await this.persistLogin(e.data,e.response),e}async getToken(t){try{let e={};if(t)e.Authorization=`Bearer ${t}`;else if(this.storage){let i=await this.storage.get(v)??await this.storage.get(g);i!=null&&(e.Authorization=`Bearer ${i}`)}let r=await this.fetchImpl(this.url("token"),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let a=s?JSON.parse(s):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 s=await this.postJson("sign-in/phone-number",{phoneNumber:t,password:e,rememberMe:r});return s.data&&await this.persistLogin(s.data,s.response),s}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 s=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 s.text();if(!s.ok)return{error:{message:a||s.statusText,status:s.status}};let i=a?JSON.parse(a):null;return!i?.token||!i.user?{error:{message:"invalid_wechat_login_response",status:502}}:(this.storage&&(await this.storage.set(g,i.token),await this.storage.set(v,i.token),await this.storage.set(E,i.user)),{data:i})}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 s=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 s.text();if(!s.ok)return{error:{message:a||s.statusText,status:s.status}};let i=a?JSON.parse(a):null;return!i?.token||!i.user?{error:{message:"invalid_alipay_login_response",status:502}}:(this.storage&&(await this.storage.set(g,i.token),await this.storage.set(v,i.token),await this.storage.set(E,i.user)),{data:i})}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())}`:"",s=await this.fetchImpl(this.url(`wechat/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),a=await s.text();if(!s.ok)return{error:{message:a||s.statusText,status:s.status}};let i=a?JSON.parse(a):null;return!i?.openid||!i.appId?{error:{message:"invalid_wechat_identity_response",status:502}}:{data:i}}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())}`:"",s=await this.fetchImpl(this.url(`alipay/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),a=await s.text();if(!s.ok)return{error:{message:a||s.statusText,status:s.status}};let i=a?JSON.parse(a):null;return!i?.openid||!i.appId?{error:{message:"invalid_alipay_identity_response",status:502}}:{data:i}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async postJson(t,e){try{let r=await this.fetchImpl(this.url(t),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify(e)}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let a=s?JSON.parse(s):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}}}}},J=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),s=new w(e?.headers);r&&s.set("Authorization",`Bearer ${r}`);let a=e?.method||"GET";if((a==="POST"||a==="PUT"||a==="PATCH")&&e?.body){let o=s.get("Content-Type");(!o||o.includes("text/plain"))&&s.set("Content-Type","application/json")}let i=await this.customFetch(t,{...e,headers:s});if(i.status===401)throw this.handleUnauthorized(),new Error("\u672A\u767B\u5F55");return i}},ue="/storage",de=ue+"/generateUploadUrl",z=class{constructor(t,e){this.baseUrl=t,this.http=e}async uploadFile(t){let e=await this.http.fetch(this.baseUrl+de,{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 s=await this.http.fetch(r,{method:"PUT",body:t,headers:new w({"Content-Type":t.type||t.fileType||"application/octet-stream"})}),{url:a}=await s.json();return{url:a.split("?")[0]}}},pe=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},me=class{constructor(t){var e,r,s;this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=new w(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=(s=t.urlLengthLimit)!==null&&s!==void 0?s:8e3,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=new w(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 s=this.fetch,a=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{let o=null,n=null,c=null,h=i.status,l=i.statusText;if(i.ok){var u,m;if(r.method!=="HEAD"){var d;let y=await i.text();y===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&!((d=r.headers.get("Accept"))===null||d===void 0)&&d.includes("application/vnd.pgrst.plan+text")?n=y:n=JSON.parse(y))}let p=(u=r.headers.get("Prefer"))===null||u===void 0?void 0:u.match(/count=(exact|planned|estimated)/),f=(m=i.headers.get("content-range"))===null||m===void 0?void 0:m.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 i.text();try{o=JSON.parse(p),Array.isArray(o)&&i.status===404&&(n=[],o=null,h=200,l="OK")}catch{i.status===404&&p===""?(h=204,l="No Content"):o={message:p}}if(o&&r.shouldThrowOnError)throw new pe(o)}return{error:o,data:n,count:c,status:h,statusText:l}});return this.shouldThrowOnError||(a=a.catch(i=>{var o;let n="",c="",h="",l=i?.cause;if(l){var u,m,d,p;let _=(u=l?.message)!==null&&u!==void 0?u:"",L=(m=l?.code)!==null&&m!==void 0?m:"";n=`${(d=i?.name)!==null&&d!==void 0?d:"FetchError"}: ${i?.message}`,n+=`
|
|
1
|
+
var w=class F{constructor(e){if(this.headerMap=new Map,e){if(e instanceof F)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()}},oe=class D{constructor(e){if(this.params=new Map,e){if(typeof e=="string")this.parseString(e);else if(e instanceof D)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}},x=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 oe(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]||"/",h=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(/^([^@]*)@(.+)$/),o="",l="",u=a;if(c){let f=c[1];u=c[2];let y=f.match(/^([^:]*):?(.*)$/);y&&(o=y[1]||"",l=y[2]||"")}let m=u.match(/^([^:]+):?(\d*)$/),d=m?m[1]:u,p=m&&m[2]?m[2]:"";return{protocol:i?`${i}:`:"",username:o,password:l,host:u,hostname:d,port:p,pathname:s,search:h,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=le(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 le(t){return t?new w(t):new w}var he=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]"}},ce=class{constructor(){this._signal=new he}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}},B=class{constructor(t,e=""){this.http=t,this.baseUrl=e.replace(/\/$/,"")}async invoke(t,e){let r=this.baseUrl?`${this.baseUrl}/functions/${t}`:`/functions/${t}`;return await(await this.http.fetch(r,{method:e.method||"POST",body:e.body,headers:e.headers})).json()}},g="nvwa_current_jwt",v="nvwa_login_token",E="nvwa_user_profile",ue="set-auth-token",de=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 M(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 j(t,e){let r=t.socialLogin?.providers?.[e];return r?.enabled?r.oauthCredentialSource==="custom"?"custom":"nvwa_default":null}var z=class{constructor(t,e={}){this.baseUrl=t.replace(/\/$/,""),this.authPath=(e.authPath??"/auth").replace(/^\//,""),this.fetchImpl=e.fetchImpl??de,this.storage=e.storage??null,this.credentials=e.credentials??"omit",this.integrationProviders=e.integrationProviders??{},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])=>M(r))}async getAvailableProviders(t){return this.getSocialProviders(t)}async startSocialLogin(t,e){let r=M(t),i=e?.returnUrl??(typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:"");switch(r.loginKind){case"google_openplatform":if(!i)throw new Error("startSocialLogin requires returnUrl for google");this.startGoogleOpenPlatformLogin(i,{applicationCode:e?.applicationCode,platformCode:e?.platformCode});return;case"github_openplatform":if(!i)throw new Error("startSocialLogin requires returnUrl for github");this.startGithubOpenPlatformLogin(i,{applicationCode:e?.applicationCode,platformCode:e?.platformCode});return;case"wechat_website_openplatform":if(!i)throw new Error("startSocialLogin requires returnUrl for wechat-website");this.startWechatWebsiteOpenPlatformLogin(i);return;case"wechat_miniprogram_code":if(!e?.miniProgramCode?.trim()||!e.applicationCode?.trim())throw new Error("startSocialLogin requires miniProgramCode and applicationCode for wechat-miniprogram");await this.loginWithWeChatCode(e.miniProgramCode.trim(),e.applicationCode.trim());return;case"alipay_miniprogram_code":if(!e?.miniProgramCode?.trim()||!e.applicationCode?.trim())throw new Error("startSocialLogin requires miniProgramCode and applicationCode for alipay-miniprogram");await this.loginWithAlipayCode(e.miniProgramCode.trim(),e.applicationCode.trim());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(E);if(r!=null)return r}let{data:t}=await this.getSession(),e=t?.user??null;return e&&this.storage&&await this.storage.set(E,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(ue)?.trim()||t.token||t.session?.token;r&&await this.storage.set(v,r),t.user&&await this.storage.set(E,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(E),await this.storage.remove(g))}getGoogleOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t});e?.applicationCode?.trim()&&r.set("application_code",e.applicationCode.trim()),e?.platformCode?.trim()&&r.set("platform_code",e.platformCode.trim());let i=j(this.integrationProviders,"google");return i&&r.set("oauth_credential_source",i),`${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(E,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});e?.applicationCode?.trim()&&r.set("application_code",e.applicationCode.trim()),e?.platformCode?.trim()&&r.set("platform_code",e.platformCode.trim());let i=j(this.integrationProviders,"github");return i&&r.set("oauth_credential_source",i),`${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(E,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(E,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={};if(this.storage){let r=await this.storage.get(v)??await this.storage.get(g);r!=null&&(t.Authorization=`Bearer ${r}`)}let e=await this.fetchImpl(this.url("sign-out"),{method:"POST",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}});return await this.clearLogin(),e.ok?{}:{error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signUp(t){let e=await this.postJson("sign-up/email",t);return e.data&&await this.persistLogin(e.data,e.response),e}async getToken(t){try{let e={};if(t)e.Authorization=`Bearer ${t}`;else if(this.storage){let 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 h=await this.storage.get(g);h!=null&&(r.Authorization=`Bearer ${h}`)}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(E,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 h=await this.storage.get(g);h!=null&&(r.Authorization=`Bearer ${h}`)}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(E,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 h=await this.storage.get(g);h!=null&&(e.Authorization=`Bearer ${h}`)}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 h=await this.storage.get(g);h!=null&&(e.Authorization=`Bearer ${h}`)}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 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}}}}},K=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 w(e?.headers);r&&i.set("Authorization",`Bearer ${r}`);let a=e?.method||"GET";if((a==="POST"||a==="PUT"||a==="PATCH")&&e?.body){let h=i.get("Content-Type");(!h||h.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",me=pe+"/generateUploadUrl",V=class{constructor(t,e){this.baseUrl=t,this.http=e}async uploadFile(t){let e=await this.http.fetch(this.baseUrl+me,{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 w({"Content-Type":t.type||t.fileType||"application/octet-stream"})}),{url:a}=await i.json();return{url:a.split("?")[0]}}},ge=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},fe=class{constructor(t){var e,r,i;this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=new w(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 w(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 h=null,n=null,c=null,o=s.status,l=s.statusText;if(s.ok){var u,m;if(r.method!=="HEAD"){var d;let y=await s.text();y===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&!((d=r.headers.get("Accept"))===null||d===void 0)&&d.includes("application/vnd.pgrst.plan+text")?n=y:n=JSON.parse(y))}let p=(u=r.headers.get("Prefer"))===null||u===void 0?void 0:u.match(/count=(exact|planned|estimated)/),f=(m=s.headers.get("content-range"))===null||m===void 0?void 0:m.split("/");p&&f&&f.length>1&&(c=parseInt(f[1])),r.isMaybeSingle&&Array.isArray(n)&&(n.length>1?(h={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,o=406,l="Not Acceptable"):n.length===1?n=n[0]:n=null)}else{let p=await s.text();try{h=JSON.parse(p),Array.isArray(h)&&s.status===404&&(n=[],h=null,o=200,l="OK")}catch{s.status===404&&p===""?(o=204,l="No Content"):h={message:p}}if(h&&r.shouldThrowOnError)throw new ge(h)}return{error:h,data:n,count:c,status:o,statusText:l}});return this.shouldThrowOnError||(a=a.catch(s=>{var h;let n="",c="",o="",l=s?.cause;if(l){var u,m,d,p;let T=(u=l?.message)!==null&&u!==void 0?u:"",O=(m=l?.code)!==null&&m!==void 0?m:"";n=`${(d=s?.name)!==null&&d!==void 0?d:"FetchError"}: ${s?.message}`,n+=`
|
|
2
2
|
|
|
3
|
-
Caused by: ${(p=l?.name)!==null&&p!==void 0?p:"Error"}: ${
|
|
4
|
-
${l.stack}`)}else{var f;n=(f=i?.stack)!==null&&f!==void 0?f:""}let y=this.url.toString().length;return i?.name==="AbortError"||i?.code==="ABORT_ERR"?(h="",c="Request was aborted (timeout or manual cancellation)",y>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${y} 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)",y>this.urlLengthLimit&&(c+=`. Your request URL is ${y} 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=i?.name)!==null&&o!==void 0?o:"FetchError"}: ${i?.message}`,details:n,hint:c,code:h},data:null,count:null,status:0,statusText:""}})),a.then(t,e)}returns(){return this}overrideTypes(){return this}},ge=class extends me{select(t){let e=!1,r=(t??"*").split("").map(s=>/\s/.test(s)&&!e?"":(s==='"'&&(e=!e),s)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:s,referencedTable:a=s}={}){let i=a?`${a}.order`:"order",o=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${o?`${o},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){let s=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:s=r}={}){let a=typeof s>"u"?"offset":`${s}.offset`,i=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(a,`${t}`),this.url.searchParams.set(i,`${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:s=!1,wal:a=!1,format:i="text"}={}){var o;let n=[t?"analyze":null,e?"verbose":null,r?"settings":null,s?"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+${i}; for="${c}"; options=${n};`),i==="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 ge{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(s=>typeof s=="string"&&j.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(s=>typeof s=="string"&&j.test(s)?`"${s}"`:`${s}`).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:s}={}){let a="";s==="plain"?a="pl":s==="phrase"?a="ph":s==="websearch"&&(a="w");let i=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${a}fts${i}.${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 s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},fe=class{constructor(t,{headers:e={},schema:r,fetch:s,urlLengthLimit:a=8e3}){this.url=t,this.headers=new w(e),this.schema=r,this.fetch=s,this.urlLengthLimit=a}cloneRequestState(){return{url:new N(this.url.toString()),headers:new w(this.headers)}}select(t,e){let{head:r=!1,count:s}=e??{},a=r?"HEAD":"GET",i=!1,o=(t??"*").split("").map(h=>/\s/.test(h)&&!i?"":(h==='"'&&(i=!i),h)).join(""),{url:n,headers:c}=this.cloneRequestState();return n.searchParams.set("select",o),s&&c.append("Prefer",`count=${s}`),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 s;let a="POST",{url:i,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}"`);i.searchParams.set("columns",c.join(","))}}return new P({method:a,url:i,headers:o,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:s,defaultToNull:a=!0}={}){var i;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),s&&c.append("Prefer",`count=${s}`),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:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;let s="PATCH",{url:a,headers:i}=this.cloneRequestState();return e&&i.append("Prefer",`count=${e}`),new P({method:s,url:a,headers:i,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:s,headers:a}=this.cloneRequestState();return t&&a.append("Prefer",`count=${t}`),new P({method:r,url:s,headers:a,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function T(t){"@babel/helpers - typeof";return T=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},T(t)}function ye(t,e){if(T(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e||"default");if(T(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function we(t){var e=ye(t,"string");return T(e)=="symbol"?e:e+""}function ve(t,e,r){return(e=we(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function M(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),r.push.apply(r,s)}return r}function $(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?M(Object(r),!0).forEach(function(s){ve(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):M(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var be=class K{constructor(e,{headers:r={},schema:s,fetch:a,timeout:i,urlLengthLimit:o=8e3}={}){this.url=e,this.headers=new w(r),this.schemaName=s,this.urlLengthLimit=o;let n=a??globalThis.fetch;i!==void 0&&i>0?this.fetch=(c,h)=>{let l=new oe,u=setTimeout(()=>l.abort(),i),m=h?.signal;if(m){if(m.aborted)return clearTimeout(u),n(c,h);let d=()=>{clearTimeout(u),l.abort()};return m.addEventListener("abort",d,{once:!0}),n(c,$($({},h),{},{signal:l.signal})).finally(()=>{clearTimeout(u),m.removeEventListener("abort",d)})}return n(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 fe(new N(`${this.url}/${e}`),{headers:new w(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:s=!1,get:a=!1,count:i}={}){var o;let n,c=new N(`${this.url}/rpc/${e}`),h,l=d=>d!==null&&typeof d=="object"&&(!Array.isArray(d)||d.some(l)),u=s&&Object.values(r).some(l);u?(n="POST",h=r):s||a?(n=s?"HEAD":"GET",Object.entries(r).filter(([d,p])=>p!==void 0).map(([d,p])=>[d,Array.isArray(p)?`{${p.join(",")}}`:`${p}`]).forEach(([d,p])=>{c.searchParams.append(d,p)})):(n="POST",h=r);let m=new w(this.headers);return u?m.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&m.set("Prefer",`count=${i}`),new P({method:n,url:c,headers:m,schema:this.schemaName,body:h,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit})}},Ee="/entities",V=(t,e)=>new be(t+Ee,{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"}: ${T}`,O&&(n+=` (${O})`),l?.stack&&(n+=`
|
|
4
|
+
${l.stack}`)}else{var f;n=(f=s?.stack)!==null&&f!==void 0?f:""}let y=this.url.toString().length;return s?.name==="AbortError"||s?.code==="ABORT_ERR"?(o="",c="Request was aborted (timeout or manual cancellation)",y>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${y} 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")&&(o="",c="HTTP headers exceeded server limits (typically 16KB)",y>this.urlLengthLimit&&(c+=`. Your request URL is ${y} 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:`${(h=s?.name)!==null&&h!==void 0?h:"FetchError"}: ${s?.message}`,details:n,hint:c,code:o},data:null,count:null,status:0,statusText:""}})),a.then(t,e)}returns(){return this}overrideTypes(){return this}},ye=class extends fe{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",h=this.url.searchParams.get(s);return this.url.searchParams.set(s,`${h?`${h},`:""}${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 h;let n=[t?"analyze":null,e?"verbose":null,r?"settings":null,i?"buffers":null,a?"wal":null].filter(Boolean).join("|"),c=(h=this.headers.get("Accept"))!==null&&h!==void 0?h:"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}},H=new RegExp("[,()]"),L=class extends ye{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"&&H.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"&&H.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}},we=class{constructor(t,{headers:e={},schema:r,fetch:i,urlLengthLimit:a=8e3}){this.url=t,this.headers=new w(e),this.schema=r,this.fetch=i,this.urlLengthLimit=a}cloneRequestState(){return{url:new x(this.url.toString()),headers:new w(this.headers)}}select(t,e){let{head:r=!1,count:i}=e??{},a=r?"HEAD":"GET",s=!1,h=(t??"*").split("").map(o=>/\s/.test(o)&&!s?"":(o==='"'&&(s=!s),o)).join(""),{url:n,headers:c}=this.cloneRequestState();return n.searchParams.set("select",h),i&&c.append("Prefer",`count=${i}`),new L({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:h}=this.cloneRequestState();if(e&&h.append("Prefer",`count=${e}`),r||h.append("Prefer","missing=default"),Array.isArray(t)){let n=t.reduce((c,o)=>c.concat(Object.keys(o)),[]);if(n.length>0){let c=[...new Set(n)].map(o=>`"${o}"`);s.searchParams.set("columns",c.join(","))}}return new L({method:a,url:s,headers:h,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 h="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 o=t.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(o.length>0){let l=[...new Set(o)].map(u=>`"${u}"`);n.searchParams.set("columns",l.join(","))}}return new L({method:h,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 L({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 L({method:r,url:i,headers:a,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function C(t){"@babel/helpers - typeof";return C=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},C(t)}function ve(t,e){if(C(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var i=r.call(t,e||"default");if(C(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function be(t){var e=ve(t,"string");return C(e)=="symbol"?e:e+""}function Ee(t,e,r){return(e=be(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function W(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 _(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?W(Object(r),!0).forEach(function(i){Ee(t,i,r[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):W(Object(r)).forEach(function(i){Object.defineProperty(t,i,Object.getOwnPropertyDescriptor(r,i))})}return t}var Pe=class Y{constructor(e,{headers:r={},schema:i,fetch:a,timeout:s,urlLengthLimit:h=8e3}={}){this.url=e,this.headers=new w(r),this.schemaName=i,this.urlLengthLimit=h;let n=a??globalThis.fetch;s!==void 0&&s>0?this.fetch=(c,o)=>{let l=new ce,u=setTimeout(()=>l.abort(),s),m=o?.signal;if(m){if(m.aborted)return clearTimeout(u),n(c,o);let d=()=>{clearTimeout(u),l.abort()};return m.addEventListener("abort",d,{once:!0}),n(c,_(_({},o),{},{signal:l.signal})).finally(()=>{clearTimeout(u),m.removeEventListener("abort",d)})}return n(c,_(_({},o),{},{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 we(new x(`${this.url}/${e}`),{headers:new w(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new Y(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 h;let n,c=new x(`${this.url}/rpc/${e}`),o,l=d=>d!==null&&typeof d=="object"&&(!Array.isArray(d)||d.some(l)),u=i&&Object.values(r).some(l);u?(n="POST",o=r):i||a?(n=i?"HEAD":"GET",Object.entries(r).filter(([d,p])=>p!==void 0).map(([d,p])=>[d,Array.isArray(p)?`{${p.join(",")}}`:`${p}`]).forEach(([d,p])=>{c.searchParams.append(d,p)})):(n="POST",o=r);let m=new w(this.headers);return u?m.set("Prefer",s?`count=${s},return=minimal`:"return=minimal"):s&&m.set("Prefer",`count=${s}`),new L({method:n,url:c,headers:m,schema:this.schemaName,body:o,fetch:(h=this.fetch)!==null&&h!==void 0?h:fetch,urlLengthLimit:this.urlLengthLimit})}},Se="/entities",Q=(t,e)=>new Pe(t+Se,{fetch:e.fetchWithAuth.bind(e)}),X=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=i?.stack)!==null&&f!==void 0?f:""}let y=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(),s=window.scrollX||window.pageXOffset,a=window.scrollY||window.pageYOffset;r.width>0&&r.height>0?(t.style.left=`${r.left+s}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 s=()=>{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=s,window.addEventListener("scroll",s,!0),window.addEventListener("resize",s);let a=this.createTooltip();e?a.textContent=e:a.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,a.style.display="block";let i=t.getBoundingClientRect();a.style.left=`${i.left+window.scrollX}px`,a.style.top=`${i.top+window.scrollY-a.offsetHeight-8}px`,i.top<a.offsetHeight+8&&(a.style.top=`${i.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 s=()=>{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=s,window.addEventListener("scroll",s,!0),window.addEventListener("resize",s)}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 s=r.getAttribute("data-source-location");if(s)return s}if(e.firstElementChild){let s=e.firstElementChild.getAttribute("data-source-location");if(s)return s}return null}var Pe={"wechat-pay":{id:"wechat-pay",name:"WeChat Pay",description:"WeChat payment for web and miniapp."},wechat_partner:{id:"wechat_partner",name:"WeChat Partner",description:"WeChat partner merchant onboarding."},alipay:{id:"alipay",name:"Alipay",description:"Alipay payment."},"alipay-miniprogram":{id:"alipay-miniprogram",name:"Alipay Mini Program",description:"Alipay mini program payment."},stripe:{id:"stripe",name:"Stripe",description:"Stripe payment."}};function X(t){let e=t;if(typeof e.kind=="string")return e;if(typeof e.tradeNO=="string")return{kind:"alipay_miniprogram",tradeNO:e.tradeNO};if(typeof e.clientSecret=="string")return{kind:"stripe_client_secret",clientSecret:e.clientSecret};if(typeof e.redirectUrl=="string")return{kind:"redirect_url",redirectUrl:e.redirectUrl};if(typeof e.formHtml=="string")return{kind:"alipay_page",formHtml:e.formHtml};if(typeof e.codeUrl=="string")return{kind:"wechat_native_qr",codeUrl:e.codeUrl};let r=e.jsapiPayParams??e;return typeof r.timeStamp=="string"&&typeof r.nonceStr=="string"&&typeof r.package=="string"&&typeof r.paySign=="string"&&typeof r.appId=="string"?{kind:"wechat_jsapi",mode:"jsapi",jsapiPayParams:{appId:r.appId,timeStamp:r.timeStamp,nonceStr:r.nonceStr,package:r.package,signType:r.signType??"RSA",paySign:r.paySign}}:null}async function Z(t,e){let r=t.payment?.providers??{};return Object.entries(r).filter(([,s])=>s.enabled).map(([s])=>Pe[s]??{id:s,name:s,description:""})}function C(t){return t&&typeof t=="object"?t:{}}function Se(t){let e=C(t),r=e.enabled===!0,s=String(e.oauthCredentialSource??"").toLowerCase();return s?{enabled:r,oauthCredentialSource:s==="custom"?"custom":"nvwa_default"}:{enabled:r}}function W(t){let e=C(t),r=C(e.providers),s={};for(let[a,i]of Object.entries(r))s[a]=Se(i);return{providers:s}}function ee(t){let e=C(t);return{socialLogin:W(e.socialLogin),payment:W(e.payment)}}var A=class{constructor(){this.prefix="nvwa_"}getKey(e){return`${this.prefix}${e}`}async get(e){try{let r=this.getKey(e),s=uni.getStorageSync(r);return s?s.expires&&Date.now()>s.expires?(await this.remove(e),null):s.value:null}catch(r){return console.error("UniAppStorageService get error:",r),null}}async set(e,r,s){try{let a=this.getKey(e),i={value:r,expires:s?Date.now()+s*1e3:null,timestamp:Date.now()};uni.setStorageSync(a,i)}catch(a){throw console.error("UniAppStorageService set error:",a),a}}async remove(e){try{let r=this.getKey(e);uni.removeStorageSync(r)}catch(r){throw console.error("UniAppStorageService remove error:",r),r}}async clear(){try{uni.clearStorageSync()}catch(e){throw console.error("UniAppStorageService clear error:",e),e}}};var I=(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 uniappFetch");typeof console<"u"&&(console.warn("[NvwaUni] request url:",r,"method:",(e?.method||"GET").toUpperCase()),!r.startsWith("http://")&&!r.startsWith("https://")&&console.warn("[NvwaUni] url \u975E\u5B8C\u6574\u5730\u5740\uFF0C\u5C0F\u7A0B\u5E8F uni.request \u4F1A\u62A5 invalid url\uFF0C\u8BF7\u68C0\u67E5 baseUrl \u662F\u5426\u4F20\u5165\u5B8C\u6574\u57DF\u540D"));let s=(e?.method||"GET").toUpperCase(),a={};if(e?.headers){let n=e.headers;if(typeof n?.forEach=="function")n.forEach((c,h)=>{a[h]=c});else if(Array.isArray(n))for(let[c,h]of n)a[c]=h;else Object.assign(a,n)}let i;if(e?.body!==void 0){let n=e.body;if(typeof n=="string")i=n;else if(n&&typeof n=="object"&&typeof n.forEach=="function"){let c={};n.forEach((h,l)=>{c[l]=h}),i=c}else i=n}let o=e?.timeout||3e4;return new Promise((n,c)=>{let h=e?.signal;if(h?.aborted){let d=new Error("The operation was aborted");d.name="AbortError",c(d);return}let l=!1,u=[],m=uni.request({url:r,method:s,data:i,header:a,timeout:o,success:d=>{if(l)return;l=!0;let p=d.statusCode,f="",y=new w,_=d.header||d.headers||{};Object.keys(_).forEach(L=>{let x=_[L];y.set(L,typeof x=="string"?x:String(x))}),n(new G(d.data,{status:p,statusText:f,headers:y}))},fail:d=>{if(l)return;l=!0;let p=d?.errMsg||d?.message||"Network Error",f=new Error(p);/(abort|aborted|canceled|cancelled)/i.test(String(p))&&(f.name="AbortError"),c(f)}});if(h&&typeof h.addEventListener=="function"){let d=()=>{if(l)return;try{m?.abort?.()}catch{}let p=new Error("The operation was aborted");p.name="AbortError",l=!0,c(p)};h.addEventListener("abort",d),u.push(()=>{try{h.removeEventListener?.("abort",d)}catch{}})}})};globalThis&&typeof globalThis.fetch!="function"&&(globalThis.fetch=I);var b="Mobile-web";try{if(typeof uni<"u"&&typeof uni?.getSystemInfoSync=="function"){let t=uni.getSystemInfoSync()??{},e=t.uniPlatform,r=t.osName,s=t.ua??(typeof navigator<"u"?navigator.userAgent:"");e==="mp-weixin"?b="MP-Wechat":e==="mp-alipay"?b="MP-Alipay":e==="app"?r==="ios"?b="IOS":r==="android"?b="Android":r==="harmonyos"&&(b="Harmony"):(e==="web"||e==="h5")&&(b=s&&/MicroMessenger/i.test(s)?"Wechat-H5":"Mobile-web")}else typeof navigator<"u"&&/MicroMessenger/i.test(navigator.userAgent)&&(b="Wechat-H5")}catch{b="Mobile-web"}function Oe(t){return`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(t)}`}function te(t){if(typeof window<"u"){window.open(t,"_blank");return}globalThis.plus?.runtime?.openURL?.(t)}async function Le(t){if(t.kind!=="alipay_miniprogram")throw new Error("requestPayment: invalid payParams for alipay miniprogram");await new Promise((e,r)=>{let s=globalThis.my;if(!s?.tradePay){r(new Error("requestPayment: my.tradePay is unavailable"));return}s.tradePay({tradeNO:t.tradeNO,success:()=>e(),fail:a=>r(a)})})}async function Te(t){if(t.kind!=="wechat_jsapi")throw new Error("requestPayment: invalid payParams for wechat jsapi");let e=t.jsapiPayParams;await new Promise((r,s)=>{uni.requestPayment({provider:"wxpay",timeStamp:e.timeStamp,nonceStr:e.nonceStr,package:e.package,signType:e.signType??"RSA",paySign:e.paySign,success:()=>r(),fail:a=>s(a)})})}function _e(t){if(t.kind!=="redirect_url")throw new Error("requestPayment: invalid payParams for redirect");typeof window<"u"?window.location.href=t.redirectUrl:te(t.redirectUrl)}function $e(t){if(t.kind!=="wechat_native_qr")throw new Error("requestPayment: invalid payParams for wechat qr");let e=Oe(t.codeUrl);te(e)}async function Ce(t){if(!t)return!1;switch(t.kind){case"alipay_miniprogram":return await Le(t),!0;case"wechat_jsapi":return await Te(t),!0;case"redirect_url":return _e(t),!0;case"wechat_native_qr":return $e(t),!0;default:return!1}}var U={async requestPayment(t,e){try{let r=X(t);if(!await Ce(r))throw new Error("requestPayment: unsupported payParams for current endpoint");e?.onSuccess?.()}catch(r){throw e?.onFailure?.(r),r}}};function re(t){let e=async r=>await Z(t,r);return{...U,getAvailableProviders:e,getProviders:e}}function lt(){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 s(h){let l=h,u=null;for(;l;){let m=l.getAttribute("data-source-location");if(m)if(r(m)){u||(u=m),l=l.parentElement;continue}else return m;l=l.parentElement}return u}let a=null;function i(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=s(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,m=s(l);if(!m){let p=l.parentElement;for(;p&&p!==document.body&&p!==document.documentElement;){let f=s(p);if(f){u=p,m=f;break}p=p.parentElement}}e.highlightElement(u,m);let d={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:m,elementInfo:{tagName:u.tagName.toLowerCase(),className:u.className||"",id:u.id||""}};window.parent.postMessage(d,"*")}))}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=s(l);e.selectElement(l,u);let m={type:"HOVER_INSPECTOR_ELEMENT_SELECT",sourceLocation:u,elementInfo:{tagName:l.tagName.toLowerCase(),className:l.className||"",id:l.id||""}};window.parent.postMessage(m,"*")}function c(h){h.data?.type==="HOVER_INSPECTOR_ENABLE"?(t=!0,document.addEventListener("mousemove",i),document.addEventListener("mouseleave",o),document.addEventListener("click",n,!0)):h.data?.type==="HOVER_INSPECTOR_DISABLE"&&(t=!1,document.removeEventListener("mousemove",i),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",i),document.removeEventListener("mouseleave",o),document.removeEventListener("click",n,!0),e.cleanup()}}function ht(t,e){if(!t||!t.contentWindow)throw new Error("Invalid iframe element");let r={type:"HOVER_INSPECTOR_ENABLE"};t.contentWindow.postMessage(r,e)}function ct(t,e){if(!t||!t.contentWindow)return;let r={type:"HOVER_INSPECTOR_DISABLE"};t.contentWindow.postMessage(r,e)}function ut(t,e,r=5e3){return new Promise((s,a)=>{if(!t||!t.contentWindow){a(new Error("Invalid iframe element"));return}let i=`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===i&&(clearTimeout(o),window.removeEventListener("message",n),h.data.error?a(new Error(h.data.error)):s(h.data.sourceLocation||null))};window.addEventListener("message",n);let c={type:"GET_SOURCE_LOCATION_REQUEST",requestId:i};try{t.contentWindow.postMessage(c,e)}catch(h){clearTimeout(o),window.removeEventListener("message",n),a(h)}})}function dt(){if(typeof window>"u"||window===window.parent)return;let t=e=>{if(e.data?.type==="GET_SOURCE_LOCATION_REQUEST")try{let s={type:"GET_SOURCE_LOCATION_RESPONSE",sourceLocation:Ae(),requestId:e.data.requestId};window.parent.postMessage(s,e.origin)}catch(r){let s={type:"GET_SOURCE_LOCATION_RESPONSE",sourceLocation:null,error:r instanceof Error?r.message:"Unknown error",requestId:e.data.requestId};window.parent.postMessage(s,e.origin)}};return window.addEventListener("message",t),()=>{window.removeEventListener("message",t)}}function Ae(){return Q("app")}var se=new A,R=class{constructor(e){this.payment=U;this.endpointType=b;let{baseUrl:r,handleUnauthorized:s,applicationCode:a,platformType:i,integrationProviders:o}=e;typeof console<"u"&&console.warn("[Nvwa] uniapp init baseUrl:",r||"(empty)");let n=a.trim();if(!n)throw new Error("Nvwa: applicationCode \u4E0D\u80FD\u4E3A\u7A7A");this.applicationCode=n;let c=i.trim();if(!c)throw new Error("Nvwa: platformType \u4E0D\u80FD\u4E3A\u7A7A");this.platformType=c,this.integrationProviders=ee(o),this.auth=new D(r,{fetchImpl:I,storage:se,integrationProviders:this.integrationProviders}),this.httpClient=new J(se,I,s),this.fileStorage=new z(r,this.httpClient),this.entities=V(r,this.httpClient),this.functions=new B(this.httpClient,r),this.payment=re(this.integrationProviders)}};export{R as default,ct as disableIframeHoverInspector,ht as enableIframeHoverInspector,ut as getIframeSourceLocation,se as localStorage,lt as setupIframeHoverInspector,dt as setupIframeSourceLocationListener};
|
|
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 h=this.createTooltip();e?h.textContent=e:h.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,h.style.display="block";let n=t.getBoundingClientRect();h.style.left=`${n.left+window.scrollX}px`,h.style.top=`${n.top+window.scrollY-h.offsetHeight-8}px`,n.top<h.offsetHeight+8&&(h.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 Z(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 Le={"wechat-pay":{id:"wechat-pay",name:"WeChat Pay",description:"WeChat payment for web and miniapp."},wechat_partner:{id:"wechat_partner",name:"WeChat Partner",description:"WeChat partner merchant onboarding."},alipay:{id:"alipay",name:"Alipay",description:"Alipay payment."},"alipay-miniprogram":{id:"alipay-miniprogram",name:"Alipay Mini Program",description:"Alipay mini program payment."},stripe:{id:"stripe",name:"Stripe",description:"Stripe payment."}};function ee(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 te(t,e){let r=t.payment?.providers??{};return Object.entries(r).filter(([,i])=>i.enabled).map(([i])=>{let a=Le[i]??{id:i,name:i,description:""};return{...a,type:a.id}})}function $(t){return t&&typeof t=="object"?t:{}}function Oe(t){let e=$(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),r=$(e.providers),i={};for(let[a,s]of Object.entries(r))i[a]=Oe(s);return{providers:i}}function re(t){let e=$(t);return{socialLogin:q(e.socialLogin),payment:q(e.payment)}}var A=class{constructor(){this.prefix="nvwa_"}getKey(e){return`${this.prefix}${e}`}async get(e){try{let r=this.getKey(e),i=uni.getStorageSync(r);return i?i.expires&&Date.now()>i.expires?(await this.remove(e),null):i.value:null}catch(r){return console.error("UniAppStorageService 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()};uni.setStorageSync(a,s)}catch(a){throw console.error("UniAppStorageService set error:",a),a}}async remove(e){try{let r=this.getKey(e);uni.removeStorageSync(r)}catch(r){throw console.error("UniAppStorageService remove error:",r),r}}async clear(){try{uni.clearStorageSync()}catch(e){throw console.error("UniAppStorageService clear error:",e),e}}};var k=(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 uniappFetch");typeof console<"u"&&(console.warn("[NvwaUni] request url:",r,"method:",(e?.method||"GET").toUpperCase()),!r.startsWith("http://")&&!r.startsWith("https://")&&console.warn("[NvwaUni] url \u975E\u5B8C\u6574\u5730\u5740\uFF0C\u5C0F\u7A0B\u5E8F uni.request \u4F1A\u62A5 invalid url\uFF0C\u8BF7\u68C0\u67E5 baseUrl \u662F\u5426\u4F20\u5165\u5B8C\u6574\u57DF\u540D"));let i=(e?.method||"GET").toUpperCase(),a={};if(e?.headers){let n=e.headers;if(typeof n?.forEach=="function")n.forEach((c,o)=>{a[o]=c});else if(Array.isArray(n))for(let[c,o]of n)a[c]=o;else Object.assign(a,n)}let s;if(e?.body!==void 0){let n=e.body;if(typeof n=="string")s=n;else if(n&&typeof n=="object"&&typeof n.forEach=="function"){let c={};n.forEach((o,l)=>{c[l]=o}),s=c}else s=n}let h=e?.timeout||3e4;return new Promise((n,c)=>{let o=e?.signal;if(o?.aborted){let d=new Error("The operation was aborted");d.name="AbortError",c(d);return}let l=!1,u=[],m=uni.request({url:r,method:i,data:s,header:a,timeout:h,success:d=>{if(l)return;l=!0;let p=d.statusCode,f="",y=new w,T=d.header||d.headers||{};Object.keys(T).forEach(O=>{let U=T[O];y.set(O,typeof U=="string"?U:String(U))}),n(new G(d.data,{status:p,statusText:f,headers:y}))},fail:d=>{if(l)return;l=!0;let p=d?.errMsg||d?.message||"Network Error",f=new Error(p);/(abort|aborted|canceled|cancelled)/i.test(String(p))&&(f.name="AbortError"),c(f)}});if(o&&typeof o.addEventListener=="function"){let d=()=>{if(l)return;try{m?.abort?.()}catch{}let p=new Error("The operation was aborted");p.name="AbortError",l=!0,c(p)};o.addEventListener("abort",d),u.push(()=>{try{o.removeEventListener?.("abort",d)}catch{}})}})};globalThis&&typeof globalThis.fetch!="function"&&(globalThis.fetch=k);var b="Mobile-web";try{if(typeof uni<"u"&&typeof uni?.getSystemInfoSync=="function"){let t=uni.getSystemInfoSync()??{},e=t.uniPlatform,r=t.osName,i=t.ua??(typeof navigator<"u"?navigator.userAgent:"");e==="mp-weixin"?b="MP-Wechat":e==="mp-alipay"?b="MP-Alipay":e==="app"?r==="ios"?b="IOS":r==="android"?b="Android":r==="harmonyos"&&(b="Harmony"):(e==="web"||e==="h5")&&(b=i&&/MicroMessenger/i.test(i)?"Wechat-H5":"Mobile-web")}else typeof navigator<"u"&&/MicroMessenger/i.test(navigator.userAgent)&&(b="Wechat-H5")}catch{b="Mobile-web"}function Ce(t){return`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(t)}`}function ie(t){if(typeof window<"u"){window.open(t,"_blank");return}globalThis.plus?.runtime?.openURL?.(t)}async function Te(t){if(t.kind!=="alipay_miniprogram")throw new Error("requestPayment: invalid payParams for alipay miniprogram");await new Promise((e,r)=>{let i=globalThis.my;if(!i?.tradePay){r(new Error("requestPayment: my.tradePay is unavailable"));return}i.tradePay({tradeNO:t.tradeNO,success:()=>e(),fail:a=>r(a)})})}async function _e(t){if(t.kind!=="wechat_jsapi")throw new Error("requestPayment: invalid payParams for wechat jsapi");let e=t.jsapiPayParams;await new Promise((r,i)=>{uni.requestPayment({provider:"wxpay",timeStamp:e.timeStamp,nonceStr:e.nonceStr,package:e.package,signType:e.signType??"RSA",paySign:e.paySign,success:()=>r(),fail:a=>i(a)})})}function $e(t){if(t.kind!=="redirect_url")throw new Error("requestPayment: invalid payParams for redirect");typeof window<"u"?window.location.href=t.redirectUrl:ie(t.redirectUrl)}function Ae(t){if(t.kind!=="wechat_native_qr")throw new Error("requestPayment: invalid payParams for wechat qr");let e=Ce(t.codeUrl);ie(e)}async function ke(t){if(!t)return!1;switch(t.kind){case"alipay_miniprogram":return await Te(t),!0;case"wechat_jsapi":return await _e(t),!0;case"redirect_url":return $e(t),!0;case"wechat_native_qr":return Ae(t),!0;default:return!1}}var N={async requestPayment(t,e){try{let r=ee(t);if(!await ke(r))throw new Error("requestPayment: unsupported payParams for current endpoint");e?.onSuccess?.()}catch(r){throw e?.onFailure?.(r),r}}};function ae(t){let e=async r=>await te(t,r);return{...N,getAvailableProviders:e,getProviders:e}}function dt(){if(typeof window>"u"||window===window.parent)return;let t=!1,e=new X;function r(o){if(!o)return!1;let l=o.toLowerCase();return l.includes("/components/")||l.includes("\\components\\")}function i(o){let l=o,u=null;for(;l;){let m=l.getAttribute("data-source-location");if(m)if(r(m)){u||(u=m),l=l.parentElement;continue}else return m;l=l.parentElement}return u}let a=null;function s(o){t&&(a!==null&&cancelAnimationFrame(a),a=requestAnimationFrame(()=>{let l=o.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,m=i(l);if(!m){let p=l.parentElement;for(;p&&p!==document.body&&p!==document.documentElement;){let f=i(p);if(f){u=p,m=f;break}p=p.parentElement}}e.highlightElement(u,m);let d={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:m,elementInfo:{tagName:u.tagName.toLowerCase(),className:u.className||"",id:u.id||""}};window.parent.postMessage(d,"*")}))}function h(){if(!t)return;e.removeHighlight();let o={type:"HOVER_INSPECTOR_ELEMENT_LEAVE"};window.parent.postMessage(o,"*")}function n(o){if(!t)return;o.preventDefault(),o.stopPropagation();let l=o.target;if(!l||l===document.body||l===document.documentElement)return;let u=i(l);e.selectElement(l,u);let m={type:"HOVER_INSPECTOR_ELEMENT_SELECT",sourceLocation:u,elementInfo:{tagName:l.tagName.toLowerCase(),className:l.className||"",id:l.id||""}};window.parent.postMessage(m,"*")}function c(o){o.data?.type==="HOVER_INSPECTOR_ENABLE"?(t=!0,document.addEventListener("mousemove",s),document.addEventListener("mouseleave",h),document.addEventListener("click",n,!0)):o.data?.type==="HOVER_INSPECTOR_DISABLE"&&(t=!1,document.removeEventListener("mousemove",s),document.removeEventListener("mouseleave",h),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",h),document.removeEventListener("click",n,!0),e.cleanup()}}function pt(t,e){if(!t||!t.contentWindow)throw new Error("Invalid iframe element");let r={type:"HOVER_INSPECTOR_ENABLE"};t.contentWindow.postMessage(r,e)}function mt(t,e){if(!t||!t.contentWindow)return;let r={type:"HOVER_INSPECTOR_DISABLE"};t.contentWindow.postMessage(r,e)}function gt(t,e,r=5e3){return new Promise((i,a)=>{if(!t||!t.contentWindow){a(new Error("Invalid iframe element"));return}let s=`source-location-${Date.now()}-${Math.random()}`,h=setTimeout(()=>{window.removeEventListener("message",n),a(new Error("Request timeout"))},r),n=o=>{o.origin===e&&o.data?.type==="GET_SOURCE_LOCATION_RESPONSE"&&o.data?.requestId===s&&(clearTimeout(h),window.removeEventListener("message",n),o.data.error?a(new Error(o.data.error)):i(o.data.sourceLocation||null))};window.addEventListener("message",n);let c={type:"GET_SOURCE_LOCATION_REQUEST",requestId:s};try{t.contentWindow.postMessage(c,e)}catch(o){clearTimeout(h),window.removeEventListener("message",n),a(o)}})}function ft(){if(typeof window>"u"||window===window.parent)return;let t=e=>{if(e.data?.type==="GET_SOURCE_LOCATION_REQUEST")try{let i={type:"GET_SOURCE_LOCATION_RESPONSE",sourceLocation:Ue(),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 Ue(){return Z("app")}function xe(t){let e=t==="wechat-miniprogram"?"weixin":t==="alipay-miniprogram"?"alipay":t==="douyin-miniprogram"?"toutiao":void 0;return e?new Promise((r,i)=>{uni.login({provider:e,success:a=>{if(!a.code?.trim()){i(new Error(`login code missing for ${t}`));return}r(a.code.trim())},fail:a=>{i(a instanceof Error?a:new Error(`uni.login failed: ${String(a)}`))}})}):Promise.reject(new Error(`unsupported miniprogram provider: ${t}`))}async function Ie(t,e){return e??await t.getSocialProviderDescriptors()}function se(t){return t?.trim()?t.trim():typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:""}function vt(t){let{name:e="NvwaSocialLoginButtons",auth:r,applicationCode:i,providers:a,containerClass:s="nvwa-social-login-list",providerClass:h="nvwa-social-login-button"}=t,n=t.resolveMiniProgramCode??xe;return{name:e,data(){return{providers:[],loading:!0}},async created(){try{this.providers=await Ie(r,a)}catch(c){t.onError?.(c instanceof Error?c:new Error(String(c)))}finally{this.loading=!1}},methods:{async handleProviderTap(c){try{if(t.onBeforeLogin?.(c),c.loginKind==="wechat_miniprogram_code"||c.loginKind==="alipay_miniprogram_code"){let o=await n(c.id);await r.startSocialLogin(c.id,{miniProgramCode:o,applicationCode:i,returnUrl:se(t.returnUrl)});return}await r.startSocialLogin(c.id,{returnUrl:se(t.returnUrl),applicationCode:i})}catch(o){t.onError?.(o instanceof Error?o:new Error(String(o)))}}},render(){if(this.loading||this.providers.length===0)return null;let c=this.$createElement,o=this.providers.filter(l=>l.loginKind!=="unsupported").map(l=>c("button",{key:l.id,class:h,attrs:{type:"button"},on:{click:()=>this.handleProviderTap(l)}},l.name));return c("view",{class:s},o)}}}var ne=new A,R=class{constructor(e){this.payment=N;this.endpointType=b;let{baseUrl:r,handleUnauthorized:i,applicationCode:a,platformType:s,integrationProviders:h}=e;typeof console<"u"&&console.warn("[Nvwa] uniapp init baseUrl:",r||"(empty)");let n=a.trim();if(!n)throw new Error("Nvwa: applicationCode \u4E0D\u80FD\u4E3A\u7A7A");this.applicationCode=n;let c=s.trim();if(!c)throw new Error("Nvwa: platformType \u4E0D\u80FD\u4E3A\u7A7A");this.platformType=c,this.integrationProviders=re(h),this.auth=new z(r,{fetchImpl:k,storage:ne,integrationProviders:this.integrationProviders}),this.httpClient=new K(ne,k,i),this.fileStorage=new V(r,this.httpClient),this.entities=Q(r,this.httpClient),this.functions=new B(this.httpClient,r),this.payment=ae(this.integrationProviders)}};export{vt as createSocialLoginComponent,R as default,mt as disableIframeHoverInspector,pt as enableIframeHoverInspector,gt as getIframeSourceLocation,ne as localStorage,dt as setupIframeHoverInspector,ft as setupIframeSourceLocationListener};
|