@nvwa-app/sdk-core 6.47.0 → 6.48.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 CHANGED
@@ -155,6 +155,16 @@ declare class NvwaFileStorage {
155
155
  uploadFile(file: any): Promise<HttpUploadFileResponse>;
156
156
  }
157
157
 
158
+ /** Edge Function 调用失败(HTTP 非 2xx 或响应体非法 JSON)。 */
159
+ declare class NvwaFunctionInvokeError extends Error {
160
+ readonly status: number;
161
+ /** 原始响应正文(若有),便于日志或二次解析 */
162
+ readonly bodyText?: string;
163
+ constructor(message: string, status: number, bodyText?: string);
164
+ }
165
+ /** 从错误响应正文中提取可读说明(优先 JSON 的 `error` / `message`)。 */
166
+ declare function edgeFunctionInvokeErrorMessage(status: number, bodyText: string): string;
167
+
158
168
  type FunctionInvokeOptions = {
159
169
  headers?: Headers;
160
170
  method?: "POST" | "GET" | "PUT" | "PATCH" | "DELETE";
@@ -165,7 +175,11 @@ declare class NvwaEdgeFunctions {
165
175
  /** 项目 backend 根地址(如 https://xxx.nvwa.app),请求会发往此 host 而非当前页 origin */
166
176
  protected baseUrl: string;
167
177
  constructor(http: NvwaHttpClient, baseUrl?: string);
168
- invoke<T = any>(name: string, options: FunctionInvokeOptions): Promise<T>;
178
+ /**
179
+ * 调用项目 Edge Function,返回解析后的 JSON 对象。
180
+ * HTTP 非 2xx 或 JSON 解析失败时抛出 {@link NvwaFunctionInvokeError}。
181
+ */
182
+ invoke<T = unknown>(name: string, options: FunctionInvokeOptions): Promise<T>;
169
183
  }
170
184
 
171
185
  /**
@@ -680,4 +694,4 @@ interface INvwa {
680
694
  integrationProviders: IntegrationProvidersConfig;
681
695
  }
682
696
 
683
- export { type AlipayCodeLoginResult, type AlipayOpenPlatformIdentity, AuthClient, type AuthClientOptions, type AuthResult, type AuthSession, type AuthUser, CURRENT_JWT_KEY, type CreatePaymentResponse, ENTITIES_BASE_PATH, FILE_STORAGE_BASE_PATH, type FunctionInvokeOptions, GENERATE_UPLOAD_URL_PATH, type GithubOpenPlatformIdentity, type GithubOpenPlatformLoginResult, type GoogleOpenPlatformIdentity, type GoogleOpenPlatformLoginResult, type HoverInspectorMessage, type HttpMethod, type HttpUploadFileResponse, type INvwa, type IPaymentLauncher, type IframeSourceLocationMessage, type IntegrationProviderConfig, type IntegrationProvidersConfig, type IntegrationProvidersEntry, LOGIN_TOKEN_KEY, LOGIN_USER_PROFILE_KEY, type LegacyPayParams, type MiniProgramIdentity, type NvwaAppConfig, NvwaEdgeFunctions, NvwaFileStorage, NvwaHttpClient, type NvwaLocalStorage, type OAuthCredentialSource, OverlayManager, type PayParams, type PaymentProvider, type PaymentRequestCallbacks, type RequiredNvwaAppConfig, SET_AUTH_TOKEN_HEADER, type SignUpBody, type SocialLoginProviderKind, type SocialProvider, type SocialProviderDescriptor, type TypedPayParams, type WeChatCodeLoginResult, type WeChatOpenPlatformIdentity, type WechatJsapiPayParams, type WechatWebsiteOpenPlatformIdentity, type WechatWebsiteOpenPlatformLoginResult, createPostgrestClient, getEnabledProvidersByIntegration, getPaymentProvidersFromIntegrationProviders, getSourceLocationFromDOM, normalizeIntegrationProvidersConfig, normalizePayParams, parseNvwaAppConfig, requestPaymentFromOrderResult, requireNvwaAppConfig, resolveIntegrationProvidersFromAppConfig };
697
+ export { type AlipayCodeLoginResult, type AlipayOpenPlatformIdentity, AuthClient, type AuthClientOptions, type AuthResult, type AuthSession, type AuthUser, CURRENT_JWT_KEY, type CreatePaymentResponse, ENTITIES_BASE_PATH, FILE_STORAGE_BASE_PATH, type FunctionInvokeOptions, GENERATE_UPLOAD_URL_PATH, type GithubOpenPlatformIdentity, type GithubOpenPlatformLoginResult, type GoogleOpenPlatformIdentity, type GoogleOpenPlatformLoginResult, type HoverInspectorMessage, type HttpMethod, type HttpUploadFileResponse, type INvwa, type IPaymentLauncher, type IframeSourceLocationMessage, type IntegrationProviderConfig, type IntegrationProvidersConfig, type IntegrationProvidersEntry, LOGIN_TOKEN_KEY, LOGIN_USER_PROFILE_KEY, type LegacyPayParams, type MiniProgramIdentity, type NvwaAppConfig, NvwaEdgeFunctions, NvwaFileStorage, NvwaFunctionInvokeError, NvwaHttpClient, type NvwaLocalStorage, type OAuthCredentialSource, OverlayManager, type PayParams, type PaymentProvider, type PaymentRequestCallbacks, type RequiredNvwaAppConfig, SET_AUTH_TOKEN_HEADER, type SignUpBody, type SocialLoginProviderKind, type SocialProvider, type SocialProviderDescriptor, type TypedPayParams, type WeChatCodeLoginResult, type WeChatOpenPlatformIdentity, type WechatJsapiPayParams, type WechatWebsiteOpenPlatformIdentity, type WechatWebsiteOpenPlatformLoginResult, createPostgrestClient, edgeFunctionInvokeErrorMessage, getEnabledProvidersByIntegration, getPaymentProvidersFromIntegrationProviders, getSourceLocationFromDOM, normalizeIntegrationProvidersConfig, normalizePayParams, parseNvwaAppConfig, requestPaymentFromOrderResult, requireNvwaAppConfig, resolveIntegrationProvidersFromAppConfig };
package/dist/index.d.ts CHANGED
@@ -155,6 +155,16 @@ declare class NvwaFileStorage {
155
155
  uploadFile(file: any): Promise<HttpUploadFileResponse>;
156
156
  }
157
157
 
158
+ /** Edge Function 调用失败(HTTP 非 2xx 或响应体非法 JSON)。 */
159
+ declare class NvwaFunctionInvokeError extends Error {
160
+ readonly status: number;
161
+ /** 原始响应正文(若有),便于日志或二次解析 */
162
+ readonly bodyText?: string;
163
+ constructor(message: string, status: number, bodyText?: string);
164
+ }
165
+ /** 从错误响应正文中提取可读说明(优先 JSON 的 `error` / `message`)。 */
166
+ declare function edgeFunctionInvokeErrorMessage(status: number, bodyText: string): string;
167
+
158
168
  type FunctionInvokeOptions = {
159
169
  headers?: Headers;
160
170
  method?: "POST" | "GET" | "PUT" | "PATCH" | "DELETE";
@@ -165,7 +175,11 @@ declare class NvwaEdgeFunctions {
165
175
  /** 项目 backend 根地址(如 https://xxx.nvwa.app),请求会发往此 host 而非当前页 origin */
166
176
  protected baseUrl: string;
167
177
  constructor(http: NvwaHttpClient, baseUrl?: string);
168
- invoke<T = any>(name: string, options: FunctionInvokeOptions): Promise<T>;
178
+ /**
179
+ * 调用项目 Edge Function,返回解析后的 JSON 对象。
180
+ * HTTP 非 2xx 或 JSON 解析失败时抛出 {@link NvwaFunctionInvokeError}。
181
+ */
182
+ invoke<T = unknown>(name: string, options: FunctionInvokeOptions): Promise<T>;
169
183
  }
170
184
 
171
185
  /**
@@ -680,4 +694,4 @@ interface INvwa {
680
694
  integrationProviders: IntegrationProvidersConfig;
681
695
  }
682
696
 
683
- export { type AlipayCodeLoginResult, type AlipayOpenPlatformIdentity, AuthClient, type AuthClientOptions, type AuthResult, type AuthSession, type AuthUser, CURRENT_JWT_KEY, type CreatePaymentResponse, ENTITIES_BASE_PATH, FILE_STORAGE_BASE_PATH, type FunctionInvokeOptions, GENERATE_UPLOAD_URL_PATH, type GithubOpenPlatformIdentity, type GithubOpenPlatformLoginResult, type GoogleOpenPlatformIdentity, type GoogleOpenPlatformLoginResult, type HoverInspectorMessage, type HttpMethod, type HttpUploadFileResponse, type INvwa, type IPaymentLauncher, type IframeSourceLocationMessage, type IntegrationProviderConfig, type IntegrationProvidersConfig, type IntegrationProvidersEntry, LOGIN_TOKEN_KEY, LOGIN_USER_PROFILE_KEY, type LegacyPayParams, type MiniProgramIdentity, type NvwaAppConfig, NvwaEdgeFunctions, NvwaFileStorage, NvwaHttpClient, type NvwaLocalStorage, type OAuthCredentialSource, OverlayManager, type PayParams, type PaymentProvider, type PaymentRequestCallbacks, type RequiredNvwaAppConfig, SET_AUTH_TOKEN_HEADER, type SignUpBody, type SocialLoginProviderKind, type SocialProvider, type SocialProviderDescriptor, type TypedPayParams, type WeChatCodeLoginResult, type WeChatOpenPlatformIdentity, type WechatJsapiPayParams, type WechatWebsiteOpenPlatformIdentity, type WechatWebsiteOpenPlatformLoginResult, createPostgrestClient, getEnabledProvidersByIntegration, getPaymentProvidersFromIntegrationProviders, getSourceLocationFromDOM, normalizeIntegrationProvidersConfig, normalizePayParams, parseNvwaAppConfig, requestPaymentFromOrderResult, requireNvwaAppConfig, resolveIntegrationProvidersFromAppConfig };
697
+ export { type AlipayCodeLoginResult, type AlipayOpenPlatformIdentity, AuthClient, type AuthClientOptions, type AuthResult, type AuthSession, type AuthUser, CURRENT_JWT_KEY, type CreatePaymentResponse, ENTITIES_BASE_PATH, FILE_STORAGE_BASE_PATH, type FunctionInvokeOptions, GENERATE_UPLOAD_URL_PATH, type GithubOpenPlatformIdentity, type GithubOpenPlatformLoginResult, type GoogleOpenPlatformIdentity, type GoogleOpenPlatformLoginResult, type HoverInspectorMessage, type HttpMethod, type HttpUploadFileResponse, type INvwa, type IPaymentLauncher, type IframeSourceLocationMessage, type IntegrationProviderConfig, type IntegrationProvidersConfig, type IntegrationProvidersEntry, LOGIN_TOKEN_KEY, LOGIN_USER_PROFILE_KEY, type LegacyPayParams, type MiniProgramIdentity, type NvwaAppConfig, NvwaEdgeFunctions, NvwaFileStorage, NvwaFunctionInvokeError, NvwaHttpClient, type NvwaLocalStorage, type OAuthCredentialSource, OverlayManager, type PayParams, type PaymentProvider, type PaymentRequestCallbacks, type RequiredNvwaAppConfig, SET_AUTH_TOKEN_HEADER, type SignUpBody, type SocialLoginProviderKind, type SocialProvider, type SocialProviderDescriptor, type TypedPayParams, type WeChatCodeLoginResult, type WeChatOpenPlatformIdentity, type WechatJsapiPayParams, type WechatWebsiteOpenPlatformIdentity, type WechatWebsiteOpenPlatformLoginResult, createPostgrestClient, edgeFunctionInvokeErrorMessage, getEnabledProvidersByIntegration, getPaymentProvidersFromIntegrationProviders, getSourceLocationFromDOM, normalizeIntegrationProvidersConfig, normalizePayParams, parseNvwaAppConfig, requestPaymentFromOrderResult, requireNvwaAppConfig, resolveIntegrationProvidersFromAppConfig };
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- "use strict";var _=Object.defineProperty;var it=Object.getOwnPropertyDescriptor;var nt=Object.getOwnPropertyNames;var at=Object.prototype.hasOwnProperty;var ot=(s,t)=>{for(var e in t)_(s,e,{get:t[e],enumerable:!0})},lt=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of nt(t))!at.call(s,i)&&i!==e&&_(s,i,{get:()=>t[i],enumerable:!(r=it(t,i))||r.enumerable});return s};var ct=s=>lt(_({},"__esModule",{value:!0}),s);var Nt={};ot(Nt,{AuthClient:()=>T,CURRENT_JWT_KEY:()=>u,ENTITIES_BASE_PATH:()=>tt,FILE_STORAGE_BASE_PATH:()=>K,GENERATE_UPLOAD_URL_PATH:()=>Y,Headers:()=>f,LOGIN_TOKEN_KEY:()=>w,LOGIN_USER_PROFILE_KEY:()=>b,NvwaEdgeFunctions:()=>U,NvwaFileStorage:()=>j,NvwaHttpClient:()=>N,OverlayManager:()=>W,PROJECT_PLATFORM_TYPES:()=>rt,Request:()=>I,Response:()=>k,SET_AUTH_TOKEN_HEADER:()=>$,URL:()=>C,collectPaymentClientContext:()=>At,createPostgrestClient:()=>Ot,getEnabledProvidersByIntegration:()=>xt,getPaymentProvidersFromIntegrationProviders:()=>Et,getSourceLocationFromDOM:()=>Ct,isProjectPlatformType:()=>x,normalizeIntegrationProvidersConfig:()=>H,normalizePayParams:()=>Lt,parseCreatePaymentOrderRequest:()=>It,parseNvwaAppConfig:()=>kt,requestPaymentFromOrderResult:()=>Tt,requireNvwaAppConfig:()=>$t,resolveIntegrationProvidersFromAppConfig:()=>Ut,toPaymentOrderResultFromGateway:()=>_t});module.exports=ct(Nt);var f=class G{constructor(t){if(this.headerMap=new Map,t){if(t instanceof G)t.forEach((e,r)=>this.set(r,e));else if(Array.isArray(t))for(let[e,r]of t)this.set(e,String(r));else if(typeof t=="object")for(let e of Object.keys(t))this.set(e,String(t[e]))}}append(t,e){let r=t.toLowerCase(),i=this.headerMap.get(r);this.headerMap.set(r,i?`${i}, ${e}`:e)}set(t,e){this.headerMap.set(t.toLowerCase(),String(e))}get(t){return this.headerMap.get(t.toLowerCase())??null}has(t){return this.headerMap.has(t.toLowerCase())}delete(t){this.headerMap.delete(t.toLowerCase())}forEach(t){for(let[e,r]of this.headerMap.entries())t(r,e,this)}entries(){return this.headerMap.entries()}keys(){return this.headerMap.keys()}values(){return this.headerMap.values()}[Symbol.iterator](){return this.entries()}},ht=class M{constructor(t){if(this.params=new Map,t){if(typeof t=="string")this.parseString(t);else if(t instanceof M)this.params=new Map(t.params);else if(Array.isArray(t))for(let[e,r]of t)this.append(e,r);else if(t&&typeof t=="object")for(let[e,r]of Object.entries(t))this.set(e,r)}}parseString(t){t.startsWith("?")&&(t=t.slice(1));let e=t.split("&");for(let r of e)if(r){let[i,n]=r.split("=");i&&this.append(decodeURIComponent(i),n?decodeURIComponent(n):"")}}append(t,e){let r=this.params.get(t)||[];r.push(e),this.params.set(t,r)}delete(t){this.params.delete(t)}get(t){let e=this.params.get(t);return e?e[0]:null}getAll(t){return this.params.get(t)||[]}has(t){return this.params.has(t)}set(t,e){this.params.set(t,[e])}sort(){let t=Array.from(this.params.entries()).sort(([e],[r])=>e.localeCompare(r));this.params=new Map(t)}toString(){let t=[];for(let[e,r]of this.params.entries())for(let i of r)t.push(`${encodeURIComponent(e)}=${encodeURIComponent(i)}`);return t.join("&")}forEach(t){for(let[e,r]of this.params.entries())for(let i of r)t(i,e,this)}keys(){return this.params.keys()}values(){let t=[];for(let e of this.params.values())t.push(...e);return t[Symbol.iterator]()}entries(){let t=[];for(let[e,r]of this.params.entries())for(let i of r)t.push([e,i]);return t[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}},C=class A{constructor(t,e){let r;if(t instanceof A)r=t.href;else if(e){let n=e instanceof A?e.href:e;r=this.resolve(n,t)}else r=t;let i=this.parseUrl(r);this.href=r,this.origin=`${i.protocol}//${i.host}`,this.protocol=i.protocol,this.username=i.username,this.password=i.password,this.host=i.host,this.hostname=i.hostname,this.port=i.port,this.pathname=i.pathname,this.search=i.search,this.searchParams=new ht(i.search),this.hash=i.hash}resolve(t,e){if(e.startsWith("http://")||e.startsWith("https://"))return e;if(e.startsWith("//"))return`${this.parseUrl(t).protocol}${e}`;if(e.startsWith("/")){let n=this.parseUrl(t);return`${n.protocol}//${n.host}${e}`}let r=this.parseUrl(t),i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/";return`${r.protocol}//${r.host}${i}${e}`}parseUrl(t){let e=t.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!e)throw new TypeError("Invalid URL");let r=e[2]||"",i=e[4]||"",n=e[5]||"/",a=e[7]?`?${e[7]}`:"",o=e[9]?`#${e[9]}`:"";if(!r&&!i&&!n.startsWith("/")&&!n.includes("/")&&!n.includes("."))throw new TypeError("Invalid URL");let c=i.match(/^([^@]*)@(.+)$/),h="",l="",p=i;if(c){let P=c[1];p=c[2];let v=P.match(/^([^:]*):?(.*)$/);v&&(h=v[1]||"",l=v[2]||"")}let d=p.match(/^([^:]+):?(\d*)$/),g=d?d[1]:p,m=d&&d[2]?d[2]:"";return{protocol:r?`${r}:`:"",username:h,password:l,host:p,hostname:g,port:m,pathname:n,search:a,hash:o}}toString(){let t=this.searchParams.toString(),e=t?`?${t}`:"";return`${this.protocol}//${this.host}${this.pathname}${e}${this.hash}`}toJSON(){return this.toString()}},I=class F{constructor(t,e){if(typeof t=="string")this.url=t;else if(t?.url)this.url=String(t.url);else if(typeof t?.toString=="function")this.url=String(t.toString());else throw new Error("Invalid input for Request");this.method=(e?.method||"GET").toUpperCase(),this.headers=e?.headers instanceof f?e.headers:new f(e?.headers),this.body=e?.body,this.timeout=e?.timeout,this.signal=e?.signal||void 0}clone(){return new F(this.url,{method:this.method,headers:this.headers,body:this.body,timeout:this.timeout})}toString(){return this.url}},k=class{constructor(s,t){this.bodyData=s,this.status=t?.status??200,this.statusText=t?.statusText??"",this.headers=pt(t?.headers),this.ok=this.status>=200&&this.status<300}async text(){return typeof this.bodyData=="string"?this.bodyData:this.bodyData==null?"":typeof this.bodyData=="object"?JSON.stringify(this.bodyData):String(this.bodyData)}async json(){if(typeof this.bodyData=="string")try{return JSON.parse(this.bodyData)}catch{}return this.bodyData}async arrayBuffer(){let s=await this.text();return new TextEncoder().encode(s).buffer}};function pt(s){return s?new f(s):new f}var ut=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 s of Array.from(this.listeners))try{s()}catch{}this.listeners.clear()}}addEventListener(s,t){if(this._aborted){try{t()}catch{}return}this.listeners.add(t)}removeEventListener(s,t){this.listeners.delete(t)}toString(){return"[object AbortSignal]"}},D=class{constructor(){this._signal=new ut}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}};function dt(s){if(s!==void 0)return typeof s=="string"||s instanceof FormData||s instanceof Blob||s instanceof File||s instanceof ArrayBuffer||ArrayBuffer.isView(s)||typeof ReadableStream<"u"&&s instanceof ReadableStream?s:typeof s=="object"&&s!==null?JSON.stringify(s):s}var U=class{constructor(t,e=""){this.http=t,this.baseUrl=e.replace(/\/$/,"")}async invoke(t,e){let r=this.baseUrl?`${this.baseUrl}/functions/${t}`:`/functions/${t}`;return await(await this.http.fetchWithAuth(r,{method:e.method||"POST",body:dt(e.body),headers:e.headers})).json()}};var u="nvwa_current_jwt",w="nvwa_login_token",b="nvwa_user_profile",$="set-auth-token",gt=typeof fetch<"u"?(s,t)=>fetch(s,t):()=>{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 B(s){let t=z[s]??{id:s,name:s,description:""},e="unsupported";switch(s){case"google":e="google_openplatform";break;case"github":e="github_openplatform";break;case"wechat-website":e="wechat_website_openplatform";break;case"wechat-miniprogram":e="wechat_miniprogram_code";break;case"alipay-miniprogram":e="alipay_miniprogram_code";break;case"douyin-miniprogram":e="douyin_miniprogram_code";break;default:break}return{id:t.id,type:t.id,name:t.name,description:t.description,loginKind:e}}function J(s,t){let e=s.socialLogin?.providers?.[t];return e?.enabled?e.oauthCredentialSource==="custom"?"custom":"nvwa_default":null}var T=class{constructor(t,e={}){this.baseUrl=t.replace(/\/$/,""),this.authPath=(e.authPath??"/auth").replace(/^\//,""),this.fetchImpl=e.fetchImpl??gt,this.storage=e.storage??null,this.credentials=e.credentials??"omit",this.integrationProviders=e.integrationProviders??{},this.defaultApplicationCode=e.applicationCode?.trim()||null,this.platformType=e.platformType,typeof console<"u"&&(console.warn("[NvwaAuth] init baseUrl:",this.baseUrl||"(empty)"),(!this.baseUrl||!this.baseUrl.startsWith("http://")&&!this.baseUrl.startsWith("https://"))&&console.warn("[NvwaAuth] baseUrl \u5E94\u4E3A\u5B8C\u6574\u5730\u5740\uFF08\u5982 https://xxx.nvwa.app\uFF09\uFF0C\u5426\u5219\u5C0F\u7A0B\u5E8F request \u4F1A\u62A5 invalid url"))}async getSocialProviders(t){let e=this.integrationProviders.socialLogin?.providers??{};return Object.entries(e).filter(([,r])=>r.enabled).map(([r])=>{let i=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])=>B(r))}async getAvailableProviders(t){return this.getSocialProviders(t)}async startSocialLogin(t,e){let r=B(t),i=e?.applicationCode?.trim()||this.defaultApplicationCode||void 0,n=e?.returnUrl??(typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:"");switch(r.loginKind){case"google_openplatform":if(!n)throw new Error("startSocialLogin requires returnUrl for google");this.startGoogleOpenPlatformLogin(n,{applicationCode:i,platformCode:e?.platformCode});return;case"github_openplatform":if(!n)throw new Error("startSocialLogin requires returnUrl for github");this.startGithubOpenPlatformLogin(n,{applicationCode:i,platformCode:e?.platformCode});return;case"wechat_website_openplatform":if(!n)throw new Error("startSocialLogin requires returnUrl for wechat-website");this.startWechatWebsiteOpenPlatformLogin(n);return;case"wechat_miniprogram_code":if(!e?.miniProgramCode?.trim()||!i)throw new Error("startSocialLogin requires miniProgramCode and applicationCode for wechat-miniprogram");await this.loginWithWeChatCode(e.miniProgramCode.trim(),i);return;case"alipay_miniprogram_code":if(!e?.miniProgramCode?.trim()||!i)throw new Error("startSocialLogin requires miniProgramCode and applicationCode for alipay-miniprogram");await this.loginWithAlipayCode(e.miniProgramCode.trim(),i);return;case"douyin_miniprogram_code":throw new Error("startSocialLogin does not support douyin-miniprogram yet");default:throw new Error(`startSocialLogin unsupported provider: ${t}`)}}async currentUser(){if(this.storage){let r=await this.storage.get(b);if(r!=null)return r}let{data:t}=await this.getSession(),e=t?.user??null;return e&&this.storage&&await this.storage.set(b,e),e}async getCurrentJwt(){if(this.storage){let e=await this.storage.get(u);if(e!=null)return e;let r=await this.storage.get(w),{data:i}=await this.getToken(r??void 0);return i?.token?(await this.storage.set(u,i.token),i.token):null}let{data:t}=await this.getToken();return t?.token??null}async persistLogin(t,e){if(!this.storage)return;let i=e?.headers.get($)?.trim()||t.token||t.session?.token;i&&await this.storage.set(w,i),t.user&&await this.storage.set(b,t.user);let n=i??await this.storage.get(w),{data:a}=await this.getToken(n??void 0);a?.token&&await this.storage.set(u,a.token)}async clearLogin(){this.storage&&(await this.storage.remove(w),await this.storage.remove(b),await this.storage.remove(u))}getGoogleOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t}),i=e?.applicationCode?.trim()||this.defaultApplicationCode||"";i&&r.set("application_code",i);let n=e?.platformCode?.trim()??"";n&&r.set("platform_code",n);let a=J(this.integrationProviders,"google");return a&&r.set("oauth_credential_source",a),`${this.url("google/openplatform/login")}?${r.toString()}`}startGoogleOpenPlatformLogin(t,e){let r=this.getGoogleOpenPlatformLoginUrl(t,e);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=r;return}throw new Error("startGoogleOpenPlatformLogin requires a browser environment with location")}async completeGoogleOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeGoogleOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithGoogleExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithGoogleExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(u);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("google/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):null;return!n?.token||!n.user?{error:{message:"invalid_google_login_response",status:502}}:(this.storage&&(await this.storage.set(u,n.token),await this.storage.set(w,n.token),await this.storage.set(b,n.user)),{data:n})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGoogleOpenPlatformIdentity(){try{let t={};if(this.storage){let n=await this.storage.get(u);n!=null&&(t.Authorization=`Bearer ${n}`)}let e=await this.fetchImpl(this.url("google/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_google_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getGithubOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t}),i=e?.applicationCode?.trim()||this.defaultApplicationCode||"";i&&r.set("application_code",i);let n=e?.platformCode?.trim()??"";n&&r.set("platform_code",n);let a=J(this.integrationProviders,"github");return a&&r.set("oauth_credential_source",a),`${this.url("github/openplatform/login")}?${r.toString()}`}startGithubOpenPlatformLogin(t,e){let r=this.getGithubOpenPlatformLoginUrl(t,e);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=r;return}throw new Error("startGithubOpenPlatformLogin requires a browser environment with location")}async completeGithubOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeGithubOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithGithubExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithGithubExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(u);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("github/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):null;return!n?.token||!n.user?{error:{message:"invalid_github_login_response",status:502}}:(this.storage&&(await this.storage.set(u,n.token),await this.storage.set(w,n.token),await this.storage.set(b,n.user)),{data:n})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGithubOpenPlatformIdentity(){try{let t={};if(this.storage){let n=await this.storage.get(u);n!=null&&(t.Authorization=`Bearer ${n}`)}let e=await this.fetchImpl(this.url("github/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_github_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getWechatWebsiteOpenPlatformLoginUrl(t){let e=new URLSearchParams({return_url:t});return`${this.url("wechat-website/openplatform/login")}?${e.toString()}`}startWechatWebsiteOpenPlatformLogin(t){let e=this.getWechatWebsiteOpenPlatformLoginUrl(t);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=e;return}throw new Error("startWechatWebsiteOpenPlatformLogin requires a browser environment with location")}async completeWechatWebsiteOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeWechatWebsiteOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithWechatWebsiteExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithWechatWebsiteExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(u);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("wechat-website/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):null;return!n?.token||!n.user?{error:{message:"invalid_wechat_website_login_response",status:502}}:(this.storage&&(await this.storage.set(u,n.token),await this.storage.set(w,n.token),await this.storage.set(b,n.user)),{data:n})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getWechatWebsiteOpenPlatformIdentity(){try{let t={};if(this.storage){let n=await this.storage.get(u);n!=null&&(t.Authorization=`Bearer ${n}`)}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 r=`${`${this.baseUrl.replace(/\/+$/,"")}/${this.authPath.replace(/^\/+/,"")}`}/${t.replace(/^\/+/,"")}`;return typeof console<"u"&&(console.warn("[NvwaAuth] request URL:",r),!r.startsWith("http://")&&!r.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")),r}async getSession(){try{let t={};if(this.storage){let i=await this.storage.get(w)??await this.storage.get(u);i!=null&&(t.Authorization=`Bearer ${i}`)}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 n=i?JSON.parse(i):void 0;return n&&await this.persistLogin({user:n.user,session:n.session},r),{data:n}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async signOut(){try{let t={"Content-Type":"application/json"};if(this.storage){let r=await this.storage.get(w)??await this.storage.get(u);r!=null&&(t.Authorization=`Bearer ${r}`)}await this.clearLogin();let e=await this.fetchImpl(this.url("sign-out"),{method:"POST",credentials:this.credentials,headers:t,body:"{}"});return e.ok?{}:{error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signUp(t){let e=await this.postJson("sign-up/email",t);return e.data&&await this.persistLogin(e.data,e.response),e}async getToken(t){try{let e={};if(t)e.Authorization=`Bearer ${t}`;else if(this.storage){let a=await this.storage.get(w)??await this.storage.get(u);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("token"),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):void 0;return{data:n?.token!=null?{token:n.token}:void 0}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async signInWithUsername(t,e){let r=await this.postJson("sign-in/username",{username:t,password:e});return r.data&&await this.persistLogin(r.data,r.response),r}async signInWithPhoneNumber(t,e,r){let i=await this.postJson("sign-in/phone-number",{phoneNumber:t,password:e,rememberMe:r});return i.data&&await this.persistLogin(i.data,i.response),i}async sendPhoneNumberOtp(t){let e=await this.postJson("phone-number/send-otp",{phoneNumber:t});return e.error?{error:e.error}:{}}async verifyPhoneNumber(t,e){let r=await this.postJson("phone-number/verify",{phoneNumber:t,code:e});return r.data&&await this.persistLogin(r.data,r.response),r}async loginWithWeChatCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let o=await this.storage.get(u);o!=null&&(r.Authorization=`Bearer ${o}`)}let i=await this.fetchImpl(this.url("wechat/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),n=await i.text();if(!i.ok)return{error:{message:n||i.statusText,status:i.status}};let a=n?JSON.parse(n):null;return!a?.token||!a.user?{error:{message:"invalid_wechat_login_response",status:502}}:(this.storage&&(await this.storage.set(u,a.token),await this.storage.set(w,a.token),await this.storage.set(b,a.user)),{data:a})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async loginWithAlipayCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let o=await this.storage.get(u);o!=null&&(r.Authorization=`Bearer ${o}`)}let i=await this.fetchImpl(this.url("alipay/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),n=await i.text();if(!i.ok)return{error:{message:n||i.statusText,status:i.status}};let a=n?JSON.parse(n):null;return!a?.token||!a.user?{error:{message:"invalid_alipay_login_response",status:502}}:(this.storage&&(await this.storage.set(u,a.token),await this.storage.set(w,a.token),await this.storage.set(b,a.user)),{data:a})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async getWeChatOpenPlatformIdentity(t){try{let e={};if(this.storage){let o=await this.storage.get(u);o!=null&&(e.Authorization=`Bearer ${o}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",i=await this.fetchImpl(this.url(`wechat/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),n=await i.text();if(!i.ok)return{error:{message:n||i.statusText,status:i.status}};let a=n?JSON.parse(n):null;return!a?.openid||!a.appId?{error:{message:"invalid_wechat_identity_response",status:502}}:{data:a}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getAlipayOpenPlatformIdentity(t){try{let e={};if(this.storage){let o=await this.storage.get(u);o!=null&&(e.Authorization=`Bearer ${o}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",i=await this.fetchImpl(this.url(`alipay/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),n=await i.text();if(!i.ok)return{error:{message:n||i.statusText,status:i.status}};let a=n?JSON.parse(n):null;return!a?.openid||!a.appId?{error:{message:"invalid_alipay_identity_response",status:502}}:{data:a}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getMiniProgramIdentity(t){let e=t?.applicationCode?.trim()||this.defaultApplicationCode||void 0;if(this.platformType==="WechatMiniProgram"){let r=await this.getWeChatOpenPlatformIdentity(e);if(!r.data)throw new Error(r.error?.message||"failed to get wechat open platform identity");return{platformType:this.platformType,appId:r.data.appId,platformUserId:r.data.openid,unionid:r.data.unionid}}else if(this.platformType==="AlipayMiniProgram"){let r=await this.getAlipayOpenPlatformIdentity(e);if(!r.data)throw new Error(r.error?.message||"failed to get wechat open platform identity");return{platformType:this.platformType,appId:r.data.appId,platformUserId:r.data.openid,unionid:r.data.unionid}}return null}async postJson(t,e){try{let r=await this.fetchImpl(this.url(t),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify(e)}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):void 0;return{data:n?.data??n??void 0,response:r}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}};var N=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(u),i=new f(e?.headers);r&&i.set("Authorization",`Bearer ${r}`);let n=e?.method||"GET";if((n==="POST"||n==="PUT"||n==="PATCH")&&e?.body){let o=i.get("Content-Type");(!o||o.includes("text/plain"))&&i.set("Content-Type","application/json")}let a=await this.customFetch(t,{...e,headers:i});if(a.status===401)throw this.handleUnauthorized(),new Error("\u672A\u767B\u5F55");return a}};var K="/storage",Y=K+"/generateUploadUrl",j=class{constructor(t,e){this.baseUrl=t,this.http=e}async uploadFile(t){let e=await this.http.fetch(this.baseUrl+Y,{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 f({"Content-Type":t.type||t.fileType||"application/octet-stream"})}),{url:n}=await i.json();return{url:n.split("?")[0]}}};var mt=class extends Error{constructor(s){super(s.message),this.name="PostgrestError",this.details=s.details,this.hint=s.hint,this.code=s.code}},ft=class{constructor(s){var t,e,r;this.shouldThrowOnError=!1,this.method=s.method,this.url=s.url,this.headers=new f(s.headers),this.schema=s.schema,this.body=s.body,this.shouldThrowOnError=(t=s.shouldThrowOnError)!==null&&t!==void 0?t:!1,this.signal=s.signal,this.isMaybeSingle=(e=s.isMaybeSingle)!==null&&e!==void 0?e:!1,this.urlLengthLimit=(r=s.urlLengthLimit)!==null&&r!==void 0?r:8e3,s.fetch?this.fetch=s.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(s,t){return this.headers=new f(this.headers),this.headers.set(s,t),this}then(s,t){var e=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 r=this.fetch,i=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{let a=null,o=null,c=null,h=n.status,l=n.statusText;if(n.ok){var p,d;if(e.method!=="HEAD"){var g;let v=await n.text();v===""||(e.headers.get("Accept")==="text/csv"||e.headers.get("Accept")&&(!((g=e.headers.get("Accept"))===null||g===void 0)&&g.includes("application/vnd.pgrst.plan+text"))?o=v:o=JSON.parse(v))}let m=(p=e.headers.get("Prefer"))===null||p===void 0?void 0:p.match(/count=(exact|planned|estimated)/),P=(d=n.headers.get("content-range"))===null||d===void 0?void 0:d.split("/");m&&P&&P.length>1&&(c=parseInt(P[1])),e.isMaybeSingle&&Array.isArray(o)&&(o.length>1?(a={code:"PGRST116",details:`Results contain ${o.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},o=null,c=null,h=406,l="Not Acceptable"):o.length===1?o=o[0]:o=null)}else{let m=await n.text();try{a=JSON.parse(m),Array.isArray(a)&&n.status===404&&(o=[],a=null,h=200,l="OK")}catch{n.status===404&&m===""?(h=204,l="No Content"):a={message:m}}if(a&&e.shouldThrowOnError)throw new mt(a)}return{error:a,data:o,count:c,status:h,statusText:l}});return this.shouldThrowOnError||(i=i.catch(n=>{var a;let o="",c="",h="",l=n?.cause;if(l){var p,d,g,m;let st=(p=l?.message)!==null&&p!==void 0?p:"",q=(d=l?.code)!==null&&d!==void 0?d:"";o=`${(g=n?.name)!==null&&g!==void 0?g:"FetchError"}: ${n?.message}`,o+=`
1
+ "use strict";var k=Object.defineProperty;var at=Object.getOwnPropertyDescriptor;var ot=Object.getOwnPropertyNames;var lt=Object.prototype.hasOwnProperty;var ct=(s,t)=>{for(var e in t)k(s,e,{get:t[e],enumerable:!0})},ht=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ot(t))!lt.call(s,i)&&i!==e&&k(s,i,{get:()=>t[i],enumerable:!(r=at(t,i))||r.enumerable});return s};var pt=s=>ht(k({},"__esModule",{value:!0}),s);var Ht={};ct(Ht,{AuthClient:()=>x,CURRENT_JWT_KEY:()=>u,ENTITIES_BASE_PATH:()=>rt,FILE_STORAGE_BASE_PATH:()=>V,GENERATE_UPLOAD_URL_PATH:()=>Q,Headers:()=>f,LOGIN_TOKEN_KEY:()=>w,LOGIN_USER_PROFILE_KEY:()=>b,NvwaEdgeFunctions:()=>$,NvwaFileStorage:()=>H,NvwaFunctionInvokeError:()=>S,NvwaHttpClient:()=>W,OverlayManager:()=>q,PROJECT_PLATFORM_TYPES:()=>it,Request:()=>U,Response:()=>N,SET_AUTH_TOKEN_HEADER:()=>j,URL:()=>C,collectPaymentClientContext:()=>Ut,createPostgrestClient:()=>Lt,edgeFunctionInvokeErrorMessage:()=>E,getEnabledProvidersByIntegration:()=>kt,getPaymentProvidersFromIntegrationProviders:()=>_t,getSourceLocationFromDOM:()=>Tt,isProjectPlatformType:()=>A,normalizeIntegrationProvidersConfig:()=>M,normalizePayParams:()=>xt,parseCreatePaymentOrderRequest:()=>Nt,parseNvwaAppConfig:()=>$t,requestPaymentFromOrderResult:()=>Rt,requireNvwaAppConfig:()=>Wt,resolveIntegrationProvidersFromAppConfig:()=>jt,toPaymentOrderResultFromGateway:()=>It});module.exports=pt(Ht);var f=class F{constructor(t){if(this.headerMap=new Map,t){if(t instanceof F)t.forEach((e,r)=>this.set(r,e));else if(Array.isArray(t))for(let[e,r]of t)this.set(e,String(r));else if(typeof t=="object")for(let e of Object.keys(t))this.set(e,String(t[e]))}}append(t,e){let r=t.toLowerCase(),i=this.headerMap.get(r);this.headerMap.set(r,i?`${i}, ${e}`:e)}set(t,e){this.headerMap.set(t.toLowerCase(),String(e))}get(t){return this.headerMap.get(t.toLowerCase())??null}has(t){return this.headerMap.has(t.toLowerCase())}delete(t){this.headerMap.delete(t.toLowerCase())}forEach(t){for(let[e,r]of this.headerMap.entries())t(r,e,this)}entries(){return this.headerMap.entries()}keys(){return this.headerMap.keys()}values(){return this.headerMap.values()}[Symbol.iterator](){return this.entries()}},ut=class D{constructor(t){if(this.params=new Map,t){if(typeof t=="string")this.parseString(t);else if(t instanceof D)this.params=new Map(t.params);else if(Array.isArray(t))for(let[e,r]of t)this.append(e,r);else if(t&&typeof t=="object")for(let[e,r]of Object.entries(t))this.set(e,r)}}parseString(t){t.startsWith("?")&&(t=t.slice(1));let e=t.split("&");for(let r of e)if(r){let[i,n]=r.split("=");i&&this.append(decodeURIComponent(i),n?decodeURIComponent(n):"")}}append(t,e){let r=this.params.get(t)||[];r.push(e),this.params.set(t,r)}delete(t){this.params.delete(t)}get(t){let e=this.params.get(t);return e?e[0]:null}getAll(t){return this.params.get(t)||[]}has(t){return this.params.has(t)}set(t,e){this.params.set(t,[e])}sort(){let t=Array.from(this.params.entries()).sort(([e],[r])=>e.localeCompare(r));this.params=new Map(t)}toString(){let t=[];for(let[e,r]of this.params.entries())for(let i of r)t.push(`${encodeURIComponent(e)}=${encodeURIComponent(i)}`);return t.join("&")}forEach(t){for(let[e,r]of this.params.entries())for(let i of r)t(i,e,this)}keys(){return this.params.keys()}values(){let t=[];for(let e of this.params.values())t.push(...e);return t[Symbol.iterator]()}entries(){let t=[];for(let[e,r]of this.params.entries())for(let i of r)t.push([e,i]);return t[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}},C=class I{constructor(t,e){let r;if(t instanceof I)r=t.href;else if(e){let n=e instanceof I?e.href:e;r=this.resolve(n,t)}else r=t;let i=this.parseUrl(r);this.href=r,this.origin=`${i.protocol}//${i.host}`,this.protocol=i.protocol,this.username=i.username,this.password=i.password,this.host=i.host,this.hostname=i.hostname,this.port=i.port,this.pathname=i.pathname,this.search=i.search,this.searchParams=new ut(i.search),this.hash=i.hash}resolve(t,e){if(e.startsWith("http://")||e.startsWith("https://"))return e;if(e.startsWith("//"))return`${this.parseUrl(t).protocol}${e}`;if(e.startsWith("/")){let n=this.parseUrl(t);return`${n.protocol}//${n.host}${e}`}let r=this.parseUrl(t),i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/";return`${r.protocol}//${r.host}${i}${e}`}parseUrl(t){let e=t.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!e)throw new TypeError("Invalid URL");let r=e[2]||"",i=e[4]||"",n=e[5]||"/",a=e[7]?`?${e[7]}`:"",o=e[9]?`#${e[9]}`:"";if(!r&&!i&&!n.startsWith("/")&&!n.includes("/")&&!n.includes("."))throw new TypeError("Invalid URL");let c=i.match(/^([^@]*)@(.+)$/),h="",l="",p=i;if(c){let P=c[1];p=c[2];let v=P.match(/^([^:]*):?(.*)$/);v&&(h=v[1]||"",l=v[2]||"")}let d=p.match(/^([^:]+):?(\d*)$/),g=d?d[1]:p,m=d&&d[2]?d[2]:"";return{protocol:r?`${r}:`:"",username:h,password:l,host:p,hostname:g,port:m,pathname:n,search:a,hash:o}}toString(){let t=this.searchParams.toString(),e=t?`?${t}`:"";return`${this.protocol}//${this.host}${this.pathname}${e}${this.hash}`}toJSON(){return this.toString()}},U=class B{constructor(t,e){if(typeof t=="string")this.url=t;else if(t?.url)this.url=String(t.url);else if(typeof t?.toString=="function")this.url=String(t.toString());else throw new Error("Invalid input for Request");this.method=(e?.method||"GET").toUpperCase(),this.headers=e?.headers instanceof f?e.headers:new f(e?.headers),this.body=e?.body,this.timeout=e?.timeout,this.signal=e?.signal||void 0}clone(){return new B(this.url,{method:this.method,headers:this.headers,body:this.body,timeout:this.timeout})}toString(){return this.url}},N=class{constructor(s,t){this.bodyData=s,this.status=t?.status??200,this.statusText=t?.statusText??"",this.headers=dt(t?.headers),this.ok=this.status>=200&&this.status<300}async text(){return typeof this.bodyData=="string"?this.bodyData:this.bodyData==null?"":typeof this.bodyData=="object"?JSON.stringify(this.bodyData):String(this.bodyData)}async json(){if(typeof this.bodyData=="string")try{return JSON.parse(this.bodyData)}catch{}return this.bodyData}async arrayBuffer(){let s=await this.text();return new TextEncoder().encode(s).buffer}};function dt(s){return s?new f(s):new f}var gt=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 s of Array.from(this.listeners))try{s()}catch{}this.listeners.clear()}}addEventListener(s,t){if(this._aborted){try{t()}catch{}return}this.listeners.add(t)}removeEventListener(s,t){this.listeners.delete(t)}toString(){return"[object AbortSignal]"}},J=class{constructor(){this._signal=new gt}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}};var S=class extends Error{constructor(t,e,r){super(t),this.name="NvwaFunctionInvokeError",this.status=e,this.bodyText=r}};function mt(s){if(!s||typeof s!="object")return null;let t=s;return typeof t.error=="string"&&t.error.length>0?t.error:typeof t.message=="string"&&t.message.length>0?t.message:null}function E(s,t){let e=t.trim();if(!e)return`Request failed with status ${s}`;try{let r=JSON.parse(e);return mt(r)??e}catch{return e}}function ft(s){if(s!==void 0)return typeof s=="string"||s instanceof FormData||s instanceof Blob||s instanceof File||s instanceof ArrayBuffer||ArrayBuffer.isView(s)||typeof ReadableStream<"u"&&s instanceof ReadableStream?s:typeof s=="object"&&s!==null?JSON.stringify(s):s}var $=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}`,i=await this.http.fetchWithAuth(r,{method:e.method||"POST",body:ft(e.body),headers:e.headers});if(!i.ok){let n=await i.text();throw new S(E(i.status,n),i.status,n)}try{return await i.json()}catch(n){let a=n instanceof Error?n.message:String(n);throw new S(`Invalid JSON in function response: ${a}`,i.status)}}};var u="nvwa_current_jwt",w="nvwa_login_token",b="nvwa_user_profile",j="set-auth-token",yt=typeof fetch<"u"?(s,t)=>fetch(s,t):()=>{throw new Error("AuthClient requires fetch")},Y={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 z(s){let t=Y[s]??{id:s,name:s,description:""},e="unsupported";switch(s){case"google":e="google_openplatform";break;case"github":e="github_openplatform";break;case"wechat-website":e="wechat_website_openplatform";break;case"wechat-miniprogram":e="wechat_miniprogram_code";break;case"alipay-miniprogram":e="alipay_miniprogram_code";break;case"douyin-miniprogram":e="douyin_miniprogram_code";break;default:break}return{id:t.id,type:t.id,name:t.name,description:t.description,loginKind:e}}function K(s,t){let e=s.socialLogin?.providers?.[t];return e?.enabled?e.oauthCredentialSource==="custom"?"custom":"nvwa_default":null}var x=class{constructor(t,e={}){this.baseUrl=t.replace(/\/$/,""),this.authPath=(e.authPath??"/auth").replace(/^\//,""),this.fetchImpl=e.fetchImpl??yt,this.storage=e.storage??null,this.credentials=e.credentials??"omit",this.integrationProviders=e.integrationProviders??{},this.defaultApplicationCode=e.applicationCode?.trim()||null,this.platformType=e.platformType,typeof console<"u"&&(console.warn("[NvwaAuth] init baseUrl:",this.baseUrl||"(empty)"),(!this.baseUrl||!this.baseUrl.startsWith("http://")&&!this.baseUrl.startsWith("https://"))&&console.warn("[NvwaAuth] baseUrl \u5E94\u4E3A\u5B8C\u6574\u5730\u5740\uFF08\u5982 https://xxx.nvwa.app\uFF09\uFF0C\u5426\u5219\u5C0F\u7A0B\u5E8F request \u4F1A\u62A5 invalid url"))}async getSocialProviders(t){let e=this.integrationProviders.socialLogin?.providers??{};return Object.entries(e).filter(([,r])=>r.enabled).map(([r])=>{let i=Y[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])=>z(r))}async getAvailableProviders(t){return this.getSocialProviders(t)}async startSocialLogin(t,e){let r=z(t),i=e?.applicationCode?.trim()||this.defaultApplicationCode||void 0,n=e?.returnUrl??(typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:"");switch(r.loginKind){case"google_openplatform":if(!n)throw new Error("startSocialLogin requires returnUrl for google");this.startGoogleOpenPlatformLogin(n,{applicationCode:i,platformCode:e?.platformCode});return;case"github_openplatform":if(!n)throw new Error("startSocialLogin requires returnUrl for github");this.startGithubOpenPlatformLogin(n,{applicationCode:i,platformCode:e?.platformCode});return;case"wechat_website_openplatform":if(!n)throw new Error("startSocialLogin requires returnUrl for wechat-website");this.startWechatWebsiteOpenPlatformLogin(n);return;case"wechat_miniprogram_code":if(!e?.miniProgramCode?.trim()||!i)throw new Error("startSocialLogin requires miniProgramCode and applicationCode for wechat-miniprogram");await this.loginWithWeChatCode(e.miniProgramCode.trim(),i);return;case"alipay_miniprogram_code":if(!e?.miniProgramCode?.trim()||!i)throw new Error("startSocialLogin requires miniProgramCode and applicationCode for alipay-miniprogram");await this.loginWithAlipayCode(e.miniProgramCode.trim(),i);return;case"douyin_miniprogram_code":throw new Error("startSocialLogin does not support douyin-miniprogram yet");default:throw new Error(`startSocialLogin unsupported provider: ${t}`)}}async currentUser(){if(this.storage){let r=await this.storage.get(b);if(r!=null)return r}let{data:t}=await this.getSession(),e=t?.user??null;return e&&this.storage&&await this.storage.set(b,e),e}async getCurrentJwt(){if(this.storage){let e=await this.storage.get(u);if(e!=null)return e;let r=await this.storage.get(w),{data:i}=await this.getToken(r??void 0);return i?.token?(await this.storage.set(u,i.token),i.token):null}let{data:t}=await this.getToken();return t?.token??null}async persistLogin(t,e){if(!this.storage)return;let i=e?.headers.get(j)?.trim()||t.token||t.session?.token;i&&await this.storage.set(w,i),t.user&&await this.storage.set(b,t.user);let n=i??await this.storage.get(w),{data:a}=await this.getToken(n??void 0);a?.token&&await this.storage.set(u,a.token)}async clearLogin(){this.storage&&(await this.storage.remove(w),await this.storage.remove(b),await this.storage.remove(u))}getGoogleOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t}),i=e?.applicationCode?.trim()||this.defaultApplicationCode||"";i&&r.set("application_code",i);let n=e?.platformCode?.trim()??"";n&&r.set("platform_code",n);let a=K(this.integrationProviders,"google");return a&&r.set("oauth_credential_source",a),`${this.url("google/openplatform/login")}?${r.toString()}`}startGoogleOpenPlatformLogin(t,e){let r=this.getGoogleOpenPlatformLoginUrl(t,e);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=r;return}throw new Error("startGoogleOpenPlatformLogin requires a browser environment with location")}async completeGoogleOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeGoogleOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithGoogleExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithGoogleExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(u);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("google/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):null;return!n?.token||!n.user?{error:{message:"invalid_google_login_response",status:502}}:(this.storage&&(await this.storage.set(u,n.token),await this.storage.set(w,n.token),await this.storage.set(b,n.user)),{data:n})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGoogleOpenPlatformIdentity(){try{let t={};if(this.storage){let n=await this.storage.get(u);n!=null&&(t.Authorization=`Bearer ${n}`)}let e=await this.fetchImpl(this.url("google/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_google_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getGithubOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t}),i=e?.applicationCode?.trim()||this.defaultApplicationCode||"";i&&r.set("application_code",i);let n=e?.platformCode?.trim()??"";n&&r.set("platform_code",n);let a=K(this.integrationProviders,"github");return a&&r.set("oauth_credential_source",a),`${this.url("github/openplatform/login")}?${r.toString()}`}startGithubOpenPlatformLogin(t,e){let r=this.getGithubOpenPlatformLoginUrl(t,e);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=r;return}throw new Error("startGithubOpenPlatformLogin requires a browser environment with location")}async completeGithubOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeGithubOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithGithubExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithGithubExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(u);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("github/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):null;return!n?.token||!n.user?{error:{message:"invalid_github_login_response",status:502}}:(this.storage&&(await this.storage.set(u,n.token),await this.storage.set(w,n.token),await this.storage.set(b,n.user)),{data:n})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGithubOpenPlatformIdentity(){try{let t={};if(this.storage){let n=await this.storage.get(u);n!=null&&(t.Authorization=`Bearer ${n}`)}let e=await this.fetchImpl(this.url("github/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_github_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getWechatWebsiteOpenPlatformLoginUrl(t){let e=new URLSearchParams({return_url:t});return`${this.url("wechat-website/openplatform/login")}?${e.toString()}`}startWechatWebsiteOpenPlatformLogin(t){let e=this.getWechatWebsiteOpenPlatformLoginUrl(t);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=e;return}throw new Error("startWechatWebsiteOpenPlatformLogin requires a browser environment with location")}async completeWechatWebsiteOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeWechatWebsiteOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithWechatWebsiteExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithWechatWebsiteExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(u);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("wechat-website/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):null;return!n?.token||!n.user?{error:{message:"invalid_wechat_website_login_response",status:502}}:(this.storage&&(await this.storage.set(u,n.token),await this.storage.set(w,n.token),await this.storage.set(b,n.user)),{data:n})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getWechatWebsiteOpenPlatformIdentity(){try{let t={};if(this.storage){let n=await this.storage.get(u);n!=null&&(t.Authorization=`Bearer ${n}`)}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 r=`${`${this.baseUrl.replace(/\/+$/,"")}/${this.authPath.replace(/^\/+/,"")}`}/${t.replace(/^\/+/,"")}`;return typeof console<"u"&&(console.warn("[NvwaAuth] request URL:",r),!r.startsWith("http://")&&!r.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")),r}async getSession(){try{let t={};if(this.storage){let i=await this.storage.get(w)??await this.storage.get(u);i!=null&&(t.Authorization=`Bearer ${i}`)}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 n=i?JSON.parse(i):void 0;return n&&await this.persistLogin({user:n.user,session:n.session},r),{data:n}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async signOut(){try{let t={"Content-Type":"application/json"};if(this.storage){let r=await this.storage.get(w)??await this.storage.get(u);r!=null&&(t.Authorization=`Bearer ${r}`)}await this.clearLogin();let e=await this.fetchImpl(this.url("sign-out"),{method:"POST",credentials:this.credentials,headers:t,body:"{}"});return e.ok?{}:{error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signUp(t){let e=await this.postJson("sign-up/email",t);return e.data&&await this.persistLogin(e.data,e.response),e}async getToken(t){try{let e={};if(t)e.Authorization=`Bearer ${t}`;else if(this.storage){let a=await this.storage.get(w)??await this.storage.get(u);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("token"),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):void 0;return{data:n?.token!=null?{token:n.token}:void 0}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async signInWithUsername(t,e){let r=await this.postJson("sign-in/username",{username:t,password:e});return r.data&&await this.persistLogin(r.data,r.response),r}async signInWithPhoneNumber(t,e,r){let i=await this.postJson("sign-in/phone-number",{phoneNumber:t,password:e,rememberMe:r});return i.data&&await this.persistLogin(i.data,i.response),i}async sendPhoneNumberOtp(t){let e=await this.postJson("phone-number/send-otp",{phoneNumber:t});return e.error?{error:e.error}:{}}async verifyPhoneNumber(t,e){let r=await this.postJson("phone-number/verify",{phoneNumber:t,code:e});return r.data&&await this.persistLogin(r.data,r.response),r}async loginWithWeChatCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let o=await this.storage.get(u);o!=null&&(r.Authorization=`Bearer ${o}`)}let i=await this.fetchImpl(this.url("wechat/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),n=await i.text();if(!i.ok)return{error:{message:n||i.statusText,status:i.status}};let a=n?JSON.parse(n):null;return!a?.token||!a.user?{error:{message:"invalid_wechat_login_response",status:502}}:(this.storage&&(await this.storage.set(u,a.token),await this.storage.set(w,a.token),await this.storage.set(b,a.user)),{data:a})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async loginWithAlipayCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let o=await this.storage.get(u);o!=null&&(r.Authorization=`Bearer ${o}`)}let i=await this.fetchImpl(this.url("alipay/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),n=await i.text();if(!i.ok)return{error:{message:n||i.statusText,status:i.status}};let a=n?JSON.parse(n):null;return!a?.token||!a.user?{error:{message:"invalid_alipay_login_response",status:502}}:(this.storage&&(await this.storage.set(u,a.token),await this.storage.set(w,a.token),await this.storage.set(b,a.user)),{data:a})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async getWeChatOpenPlatformIdentity(t){try{let e={};if(this.storage){let o=await this.storage.get(u);o!=null&&(e.Authorization=`Bearer ${o}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",i=await this.fetchImpl(this.url(`wechat/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),n=await i.text();if(!i.ok)return{error:{message:n||i.statusText,status:i.status}};let a=n?JSON.parse(n):null;return!a?.openid||!a.appId?{error:{message:"invalid_wechat_identity_response",status:502}}:{data:a}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getAlipayOpenPlatformIdentity(t){try{let e={};if(this.storage){let o=await this.storage.get(u);o!=null&&(e.Authorization=`Bearer ${o}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",i=await this.fetchImpl(this.url(`alipay/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),n=await i.text();if(!i.ok)return{error:{message:n||i.statusText,status:i.status}};let a=n?JSON.parse(n):null;return!a?.openid||!a.appId?{error:{message:"invalid_alipay_identity_response",status:502}}:{data:a}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getMiniProgramIdentity(t){let e=t?.applicationCode?.trim()||this.defaultApplicationCode||void 0;if(this.platformType==="WechatMiniProgram"){let r=await this.getWeChatOpenPlatformIdentity(e);if(!r.data)throw new Error(r.error?.message||"failed to get wechat open platform identity");return{platformType:this.platformType,appId:r.data.appId,platformUserId:r.data.openid,unionid:r.data.unionid}}else if(this.platformType==="AlipayMiniProgram"){let r=await this.getAlipayOpenPlatformIdentity(e);if(!r.data)throw new Error(r.error?.message||"failed to get wechat open platform identity");return{platformType:this.platformType,appId:r.data.appId,platformUserId:r.data.openid,unionid:r.data.unionid}}return null}async postJson(t,e){try{let r=await this.fetchImpl(this.url(t),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify(e)}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):void 0;return{data:n?.data??n??void 0,response:r}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}};var W=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(u),i=new f(e?.headers);r&&i.set("Authorization",`Bearer ${r}`);let n=e?.method||"GET";if((n==="POST"||n==="PUT"||n==="PATCH")&&e?.body){let o=i.get("Content-Type");(!o||o.includes("text/plain"))&&i.set("Content-Type","application/json")}let a=await this.customFetch(t,{...e,headers:i});if(a.status===401)throw this.handleUnauthorized(),new Error("\u672A\u767B\u5F55");return a}};var V="/storage",Q=V+"/generateUploadUrl",H=class{constructor(t,e){this.baseUrl=t,this.http=e}async uploadFile(t){let e=await this.http.fetch(this.baseUrl+Q,{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 f({"Content-Type":t.type||t.fileType||"application/octet-stream"})}),{url:n}=await i.json();return{url:n.split("?")[0]}}};var wt=class extends Error{constructor(s){super(s.message),this.name="PostgrestError",this.details=s.details,this.hint=s.hint,this.code=s.code}},vt=class{constructor(s){var t,e,r;this.shouldThrowOnError=!1,this.method=s.method,this.url=s.url,this.headers=new f(s.headers),this.schema=s.schema,this.body=s.body,this.shouldThrowOnError=(t=s.shouldThrowOnError)!==null&&t!==void 0?t:!1,this.signal=s.signal,this.isMaybeSingle=(e=s.isMaybeSingle)!==null&&e!==void 0?e:!1,this.urlLengthLimit=(r=s.urlLengthLimit)!==null&&r!==void 0?r:8e3,s.fetch?this.fetch=s.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(s,t){return this.headers=new f(this.headers),this.headers.set(s,t),this}then(s,t){var e=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 r=this.fetch,i=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{let a=null,o=null,c=null,h=n.status,l=n.statusText;if(n.ok){var p,d;if(e.method!=="HEAD"){var g;let v=await n.text();v===""||(e.headers.get("Accept")==="text/csv"||e.headers.get("Accept")&&(!((g=e.headers.get("Accept"))===null||g===void 0)&&g.includes("application/vnd.pgrst.plan+text"))?o=v:o=JSON.parse(v))}let m=(p=e.headers.get("Prefer"))===null||p===void 0?void 0:p.match(/count=(exact|planned|estimated)/),P=(d=n.headers.get("content-range"))===null||d===void 0?void 0:d.split("/");m&&P&&P.length>1&&(c=parseInt(P[1])),e.isMaybeSingle&&Array.isArray(o)&&(o.length>1?(a={code:"PGRST116",details:`Results contain ${o.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},o=null,c=null,h=406,l="Not Acceptable"):o.length===1?o=o[0]:o=null)}else{let m=await n.text();try{a=JSON.parse(m),Array.isArray(a)&&n.status===404&&(o=[],a=null,h=200,l="OK")}catch{n.status===404&&m===""?(h=204,l="No Content"):a={message:m}}if(a&&e.shouldThrowOnError)throw new wt(a)}return{error:a,data:o,count:c,status:h,statusText:l}});return this.shouldThrowOnError||(i=i.catch(n=>{var a;let o="",c="",h="",l=n?.cause;if(l){var p,d,g,m;let nt=(p=l?.message)!==null&&p!==void 0?p:"",G=(d=l?.code)!==null&&d!==void 0?d:"";o=`${(g=n?.name)!==null&&g!==void 0?g:"FetchError"}: ${n?.message}`,o+=`
2
2
 
3
- Caused by: ${(m=l?.name)!==null&&m!==void 0?m:"Error"}: ${st}`,q&&(o+=` (${q})`),l?.stack&&(o+=`
4
- ${l.stack}`)}else{var P;o=(P=n?.stack)!==null&&P!==void 0?P:""}let v=this.url.toString().length;return n?.name==="AbortError"||n?.code==="ABORT_ERR"?(h="",c="Request was aborted (timeout or manual cancellation)",v>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${v} 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)",v>this.urlLengthLimit&&(c+=`. Your request URL is ${v} 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:`${(a=n?.name)!==null&&a!==void 0?a:"FetchError"}: ${n?.message}`,details:o,hint:c,code:h},data:null,count:null,status:0,statusText:""}})),i.then(s,t)}returns(){return this}overrideTypes(){return this}},yt=class extends ft{select(s){let t=!1,e=(s??"*").split("").map(r=>/\s/.test(r)&&!t?"":(r==='"'&&(t=!t),r)).join("");return this.url.searchParams.set("select",e),this.headers.append("Prefer","return=representation"),this}order(s,{ascending:t=!0,nullsFirst:e,foreignTable:r,referencedTable:i=r}={}){let n=i?`${i}.order`:"order",a=this.url.searchParams.get(n);return this.url.searchParams.set(n,`${a?`${a},`:""}${s}.${t?"asc":"desc"}${e===void 0?"":e?".nullsfirst":".nullslast"}`),this}limit(s,{foreignTable:t,referencedTable:e=t}={}){let r=typeof e>"u"?"limit":`${e}.limit`;return this.url.searchParams.set(r,`${s}`),this}range(s,t,{foreignTable:e,referencedTable:r=e}={}){let i=typeof r>"u"?"offset":`${r}.offset`,n=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${s}`),this.url.searchParams.set(n,`${t-s+1}`),this}abortSignal(s){return this.signal=s,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:s=!1,verbose:t=!1,settings:e=!1,buffers:r=!1,wal:i=!1,format:n="text"}={}){var a;let o=[s?"analyze":null,t?"verbose":null,e?"settings":null,r?"buffers":null,i?"wal":null].filter(Boolean).join("|"),c=(a=this.headers.get("Accept"))!==null&&a!==void 0?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${n}; for="${c}"; options=${o};`),n==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(s){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${s}`),this}},V=new RegExp("[,()]"),S=class extends yt{eq(s,t){return this.url.searchParams.append(s,`eq.${t}`),this}neq(s,t){return this.url.searchParams.append(s,`neq.${t}`),this}gt(s,t){return this.url.searchParams.append(s,`gt.${t}`),this}gte(s,t){return this.url.searchParams.append(s,`gte.${t}`),this}lt(s,t){return this.url.searchParams.append(s,`lt.${t}`),this}lte(s,t){return this.url.searchParams.append(s,`lte.${t}`),this}like(s,t){return this.url.searchParams.append(s,`like.${t}`),this}likeAllOf(s,t){return this.url.searchParams.append(s,`like(all).{${t.join(",")}}`),this}likeAnyOf(s,t){return this.url.searchParams.append(s,`like(any).{${t.join(",")}}`),this}ilike(s,t){return this.url.searchParams.append(s,`ilike.${t}`),this}ilikeAllOf(s,t){return this.url.searchParams.append(s,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(s,t){return this.url.searchParams.append(s,`ilike(any).{${t.join(",")}}`),this}regexMatch(s,t){return this.url.searchParams.append(s,`match.${t}`),this}regexIMatch(s,t){return this.url.searchParams.append(s,`imatch.${t}`),this}is(s,t){return this.url.searchParams.append(s,`is.${t}`),this}isDistinct(s,t){return this.url.searchParams.append(s,`isdistinct.${t}`),this}in(s,t){let e=Array.from(new Set(t)).map(r=>typeof r=="string"&&V.test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(s,`in.(${e})`),this}notIn(s,t){let e=Array.from(new Set(t)).map(r=>typeof r=="string"&&V.test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(s,`not.in.(${e})`),this}contains(s,t){return typeof t=="string"?this.url.searchParams.append(s,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(s,`cs.{${t.join(",")}}`):this.url.searchParams.append(s,`cs.${JSON.stringify(t)}`),this}containedBy(s,t){return typeof t=="string"?this.url.searchParams.append(s,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(s,`cd.{${t.join(",")}}`):this.url.searchParams.append(s,`cd.${JSON.stringify(t)}`),this}rangeGt(s,t){return this.url.searchParams.append(s,`sr.${t}`),this}rangeGte(s,t){return this.url.searchParams.append(s,`nxl.${t}`),this}rangeLt(s,t){return this.url.searchParams.append(s,`sl.${t}`),this}rangeLte(s,t){return this.url.searchParams.append(s,`nxr.${t}`),this}rangeAdjacent(s,t){return this.url.searchParams.append(s,`adj.${t}`),this}overlaps(s,t){return typeof t=="string"?this.url.searchParams.append(s,`ov.${t}`):this.url.searchParams.append(s,`ov.{${t.join(",")}}`),this}textSearch(s,t,{config:e,type:r}={}){let i="";r==="plain"?i="pl":r==="phrase"?i="ph":r==="websearch"&&(i="w");let n=e===void 0?"":`(${e})`;return this.url.searchParams.append(s,`${i}fts${n}.${t}`),this}match(s){return Object.entries(s).filter(([t,e])=>e!==void 0).forEach(([t,e])=>{this.url.searchParams.append(t,`eq.${e}`)}),this}not(s,t,e){return this.url.searchParams.append(s,`not.${t}.${e}`),this}or(s,{foreignTable:t,referencedTable:e=t}={}){let r=e?`${e}.or`:"or";return this.url.searchParams.append(r,`(${s})`),this}filter(s,t,e){return this.url.searchParams.append(s,`${t}.${e}`),this}},wt=class{constructor(s,{headers:t={},schema:e,fetch:r,urlLengthLimit:i=8e3}){this.url=s,this.headers=new f(t),this.schema=e,this.fetch=r,this.urlLengthLimit=i}cloneRequestState(){return{url:new C(this.url.toString()),headers:new f(this.headers)}}select(s,t){let{head:e=!1,count:r}=t??{},i=e?"HEAD":"GET",n=!1,a=(s??"*").split("").map(h=>/\s/.test(h)&&!n?"":(h==='"'&&(n=!n),h)).join(""),{url:o,headers:c}=this.cloneRequestState();return o.searchParams.set("select",a),r&&c.append("Prefer",`count=${r}`),new S({method:i,url:o,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(s,{count:t,defaultToNull:e=!0}={}){var r;let i="POST",{url:n,headers:a}=this.cloneRequestState();if(t&&a.append("Prefer",`count=${t}`),e||a.append("Prefer","missing=default"),Array.isArray(s)){let o=s.reduce((c,h)=>c.concat(Object.keys(h)),[]);if(o.length>0){let c=[...new Set(o)].map(h=>`"${h}"`);n.searchParams.set("columns",c.join(","))}}return new S({method:i,url:n,headers:a,schema:this.schema,body:s,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(s,{onConflict:t,ignoreDuplicates:e=!1,count:r,defaultToNull:i=!0}={}){var n;let a="POST",{url:o,headers:c}=this.cloneRequestState();if(c.append("Prefer",`resolution=${e?"ignore":"merge"}-duplicates`),t!==void 0&&o.searchParams.set("on_conflict",t),r&&c.append("Prefer",`count=${r}`),i||c.append("Prefer","missing=default"),Array.isArray(s)){let h=s.reduce((l,p)=>l.concat(Object.keys(p)),[]);if(h.length>0){let l=[...new Set(h)].map(p=>`"${p}"`);o.searchParams.set("columns",l.join(","))}}return new S({method:a,url:o,headers:c,schema:this.schema,body:s,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}update(s,{count:t}={}){var e;let r="PATCH",{url:i,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new S({method:r,url:i,headers:n,schema:this.schema,body:s,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:s}={}){var t;let e="DELETE",{url:r,headers:i}=this.cloneRequestState();return s&&i.append("Prefer",`count=${s}`),new S({method:e,url:r,headers:i,schema:this.schema,fetch:(t=this.fetch)!==null&&t!==void 0?t:fetch,urlLengthLimit:this.urlLengthLimit})}};function L(s){"@babel/helpers - typeof";return L=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},L(s)}function vt(s,t){if(L(s)!="object"||!s)return s;var e=s[Symbol.toPrimitive];if(e!==void 0){var r=e.call(s,t||"default");if(L(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(s)}function Pt(s){var t=vt(s,"string");return L(t)=="symbol"?t:t+""}function bt(s,t,e){return(t=Pt(t))in s?Object.defineProperty(s,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):s[t]=e,s}function Q(s,t){var e=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(s,i).enumerable})),e.push.apply(e,r)}return e}function E(s){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?Q(Object(e),!0).forEach(function(r){bt(s,r,e[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(e)):Q(Object(e)).forEach(function(r){Object.defineProperty(s,r,Object.getOwnPropertyDescriptor(e,r))})}return s}var X=class Z{constructor(t,{headers:e={},schema:r,fetch:i,timeout:n,urlLengthLimit:a=8e3}={}){this.url=t,this.headers=new f(e),this.schemaName=r,this.urlLengthLimit=a;let o=i??globalThis.fetch;n!==void 0&&n>0?this.fetch=(c,h)=>{let l=new D,p=setTimeout(()=>l.abort(),n),d=h?.signal;if(d){if(d.aborted)return clearTimeout(p),o(c,h);let g=()=>{clearTimeout(p),l.abort()};return d.addEventListener("abort",g,{once:!0}),o(c,E(E({},h),{},{signal:l.signal})).finally(()=>{clearTimeout(p),d.removeEventListener("abort",g)})}return o(c,E(E({},h),{},{signal:l.signal})).finally(()=>clearTimeout(p))}:this.fetch=o}from(t){if(!t||typeof t!="string"||t.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new wt(new C(`${this.url}/${t}`),{headers:new f(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(t){return new Z(this.url,{headers:this.headers,schema:t,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(t,e={},{head:r=!1,get:i=!1,count:n}={}){var a;let o,c=new C(`${this.url}/rpc/${t}`),h,l=g=>g!==null&&typeof g=="object"&&(!Array.isArray(g)||g.some(l)),p=r&&Object.values(e).some(l);p?(o="POST",h=e):r||i?(o=r?"HEAD":"GET",Object.entries(e).filter(([g,m])=>m!==void 0).map(([g,m])=>[g,Array.isArray(m)?`{${m.join(",")}}`:`${m}`]).forEach(([g,m])=>{c.searchParams.append(g,m)})):(o="POST",h=e);let d=new f(this.headers);return p?d.set("Prefer",n?`count=${n},return=minimal`:"return=minimal"):n&&d.set("Prefer",`count=${n}`),new S({method:o,url:c,headers:d,schema:this.schemaName,body:h,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit})}};var tt="/entities",Ot=(s,t)=>new X(s+tt,{fetch:t.fetchWithAuth.bind(t)});var W=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: ${(m=l?.name)!==null&&m!==void 0?m:"Error"}: ${nt}`,G&&(o+=` (${G})`),l?.stack&&(o+=`
4
+ ${l.stack}`)}else{var P;o=(P=n?.stack)!==null&&P!==void 0?P:""}let v=this.url.toString().length;return n?.name==="AbortError"||n?.code==="ABORT_ERR"?(h="",c="Request was aborted (timeout or manual cancellation)",v>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${v} 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)",v>this.urlLengthLimit&&(c+=`. Your request URL is ${v} 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:`${(a=n?.name)!==null&&a!==void 0?a:"FetchError"}: ${n?.message}`,details:o,hint:c,code:h},data:null,count:null,status:0,statusText:""}})),i.then(s,t)}returns(){return this}overrideTypes(){return this}},Pt=class extends vt{select(s){let t=!1,e=(s??"*").split("").map(r=>/\s/.test(r)&&!t?"":(r==='"'&&(t=!t),r)).join("");return this.url.searchParams.set("select",e),this.headers.append("Prefer","return=representation"),this}order(s,{ascending:t=!0,nullsFirst:e,foreignTable:r,referencedTable:i=r}={}){let n=i?`${i}.order`:"order",a=this.url.searchParams.get(n);return this.url.searchParams.set(n,`${a?`${a},`:""}${s}.${t?"asc":"desc"}${e===void 0?"":e?".nullsfirst":".nullslast"}`),this}limit(s,{foreignTable:t,referencedTable:e=t}={}){let r=typeof e>"u"?"limit":`${e}.limit`;return this.url.searchParams.set(r,`${s}`),this}range(s,t,{foreignTable:e,referencedTable:r=e}={}){let i=typeof r>"u"?"offset":`${r}.offset`,n=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${s}`),this.url.searchParams.set(n,`${t-s+1}`),this}abortSignal(s){return this.signal=s,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:s=!1,verbose:t=!1,settings:e=!1,buffers:r=!1,wal:i=!1,format:n="text"}={}){var a;let o=[s?"analyze":null,t?"verbose":null,e?"settings":null,r?"buffers":null,i?"wal":null].filter(Boolean).join("|"),c=(a=this.headers.get("Accept"))!==null&&a!==void 0?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${n}; for="${c}"; options=${o};`),n==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(s){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${s}`),this}},X=new RegExp("[,()]"),L=class extends Pt{eq(s,t){return this.url.searchParams.append(s,`eq.${t}`),this}neq(s,t){return this.url.searchParams.append(s,`neq.${t}`),this}gt(s,t){return this.url.searchParams.append(s,`gt.${t}`),this}gte(s,t){return this.url.searchParams.append(s,`gte.${t}`),this}lt(s,t){return this.url.searchParams.append(s,`lt.${t}`),this}lte(s,t){return this.url.searchParams.append(s,`lte.${t}`),this}like(s,t){return this.url.searchParams.append(s,`like.${t}`),this}likeAllOf(s,t){return this.url.searchParams.append(s,`like(all).{${t.join(",")}}`),this}likeAnyOf(s,t){return this.url.searchParams.append(s,`like(any).{${t.join(",")}}`),this}ilike(s,t){return this.url.searchParams.append(s,`ilike.${t}`),this}ilikeAllOf(s,t){return this.url.searchParams.append(s,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(s,t){return this.url.searchParams.append(s,`ilike(any).{${t.join(",")}}`),this}regexMatch(s,t){return this.url.searchParams.append(s,`match.${t}`),this}regexIMatch(s,t){return this.url.searchParams.append(s,`imatch.${t}`),this}is(s,t){return this.url.searchParams.append(s,`is.${t}`),this}isDistinct(s,t){return this.url.searchParams.append(s,`isdistinct.${t}`),this}in(s,t){let e=Array.from(new Set(t)).map(r=>typeof r=="string"&&X.test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(s,`in.(${e})`),this}notIn(s,t){let e=Array.from(new Set(t)).map(r=>typeof r=="string"&&X.test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(s,`not.in.(${e})`),this}contains(s,t){return typeof t=="string"?this.url.searchParams.append(s,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(s,`cs.{${t.join(",")}}`):this.url.searchParams.append(s,`cs.${JSON.stringify(t)}`),this}containedBy(s,t){return typeof t=="string"?this.url.searchParams.append(s,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(s,`cd.{${t.join(",")}}`):this.url.searchParams.append(s,`cd.${JSON.stringify(t)}`),this}rangeGt(s,t){return this.url.searchParams.append(s,`sr.${t}`),this}rangeGte(s,t){return this.url.searchParams.append(s,`nxl.${t}`),this}rangeLt(s,t){return this.url.searchParams.append(s,`sl.${t}`),this}rangeLte(s,t){return this.url.searchParams.append(s,`nxr.${t}`),this}rangeAdjacent(s,t){return this.url.searchParams.append(s,`adj.${t}`),this}overlaps(s,t){return typeof t=="string"?this.url.searchParams.append(s,`ov.${t}`):this.url.searchParams.append(s,`ov.{${t.join(",")}}`),this}textSearch(s,t,{config:e,type:r}={}){let i="";r==="plain"?i="pl":r==="phrase"?i="ph":r==="websearch"&&(i="w");let n=e===void 0?"":`(${e})`;return this.url.searchParams.append(s,`${i}fts${n}.${t}`),this}match(s){return Object.entries(s).filter(([t,e])=>e!==void 0).forEach(([t,e])=>{this.url.searchParams.append(t,`eq.${e}`)}),this}not(s,t,e){return this.url.searchParams.append(s,`not.${t}.${e}`),this}or(s,{foreignTable:t,referencedTable:e=t}={}){let r=e?`${e}.or`:"or";return this.url.searchParams.append(r,`(${s})`),this}filter(s,t,e){return this.url.searchParams.append(s,`${t}.${e}`),this}},bt=class{constructor(s,{headers:t={},schema:e,fetch:r,urlLengthLimit:i=8e3}){this.url=s,this.headers=new f(t),this.schema=e,this.fetch=r,this.urlLengthLimit=i}cloneRequestState(){return{url:new C(this.url.toString()),headers:new f(this.headers)}}select(s,t){let{head:e=!1,count:r}=t??{},i=e?"HEAD":"GET",n=!1,a=(s??"*").split("").map(h=>/\s/.test(h)&&!n?"":(h==='"'&&(n=!n),h)).join(""),{url:o,headers:c}=this.cloneRequestState();return o.searchParams.set("select",a),r&&c.append("Prefer",`count=${r}`),new L({method:i,url:o,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(s,{count:t,defaultToNull:e=!0}={}){var r;let i="POST",{url:n,headers:a}=this.cloneRequestState();if(t&&a.append("Prefer",`count=${t}`),e||a.append("Prefer","missing=default"),Array.isArray(s)){let o=s.reduce((c,h)=>c.concat(Object.keys(h)),[]);if(o.length>0){let c=[...new Set(o)].map(h=>`"${h}"`);n.searchParams.set("columns",c.join(","))}}return new L({method:i,url:n,headers:a,schema:this.schema,body:s,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(s,{onConflict:t,ignoreDuplicates:e=!1,count:r,defaultToNull:i=!0}={}){var n;let a="POST",{url:o,headers:c}=this.cloneRequestState();if(c.append("Prefer",`resolution=${e?"ignore":"merge"}-duplicates`),t!==void 0&&o.searchParams.set("on_conflict",t),r&&c.append("Prefer",`count=${r}`),i||c.append("Prefer","missing=default"),Array.isArray(s)){let h=s.reduce((l,p)=>l.concat(Object.keys(p)),[]);if(h.length>0){let l=[...new Set(h)].map(p=>`"${p}"`);o.searchParams.set("columns",l.join(","))}}return new L({method:a,url:o,headers:c,schema:this.schema,body:s,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}update(s,{count:t}={}){var e;let r="PATCH",{url:i,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new L({method:r,url:i,headers:n,schema:this.schema,body:s,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:s}={}){var t;let e="DELETE",{url:r,headers:i}=this.cloneRequestState();return s&&i.append("Prefer",`count=${s}`),new L({method:e,url:r,headers:i,schema:this.schema,fetch:(t=this.fetch)!==null&&t!==void 0?t:fetch,urlLengthLimit:this.urlLengthLimit})}};function T(s){"@babel/helpers - typeof";return T=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},T(s)}function Ot(s,t){if(T(s)!="object"||!s)return s;var e=s[Symbol.toPrimitive];if(e!==void 0){var r=e.call(s,t||"default");if(T(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(s)}function Ct(s){var t=Ot(s,"string");return T(t)=="symbol"?t:t+""}function St(s,t,e){return(t=Ct(t))in s?Object.defineProperty(s,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):s[t]=e,s}function Z(s,t){var e=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(s,i).enumerable})),e.push.apply(e,r)}return e}function R(s){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?Z(Object(e),!0).forEach(function(r){St(s,r,e[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(e)):Z(Object(e)).forEach(function(r){Object.defineProperty(s,r,Object.getOwnPropertyDescriptor(e,r))})}return s}var tt=class et{constructor(t,{headers:e={},schema:r,fetch:i,timeout:n,urlLengthLimit:a=8e3}={}){this.url=t,this.headers=new f(e),this.schemaName=r,this.urlLengthLimit=a;let o=i??globalThis.fetch;n!==void 0&&n>0?this.fetch=(c,h)=>{let l=new J,p=setTimeout(()=>l.abort(),n),d=h?.signal;if(d){if(d.aborted)return clearTimeout(p),o(c,h);let g=()=>{clearTimeout(p),l.abort()};return d.addEventListener("abort",g,{once:!0}),o(c,R(R({},h),{},{signal:l.signal})).finally(()=>{clearTimeout(p),d.removeEventListener("abort",g)})}return o(c,R(R({},h),{},{signal:l.signal})).finally(()=>clearTimeout(p))}:this.fetch=o}from(t){if(!t||typeof t!="string"||t.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new bt(new C(`${this.url}/${t}`),{headers:new f(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(t){return new et(this.url,{headers:this.headers,schema:t,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(t,e={},{head:r=!1,get:i=!1,count:n}={}){var a;let o,c=new C(`${this.url}/rpc/${t}`),h,l=g=>g!==null&&typeof g=="object"&&(!Array.isArray(g)||g.some(l)),p=r&&Object.values(e).some(l);p?(o="POST",h=e):r||i?(o=r?"HEAD":"GET",Object.entries(e).filter(([g,m])=>m!==void 0).map(([g,m])=>[g,Array.isArray(m)?`{${m.join(",")}}`:`${m}`]).forEach(([g,m])=>{c.searchParams.append(g,m)})):(o="POST",h=e);let d=new f(this.headers);return p?d.set("Prefer",n?`count=${n},return=minimal`:"return=minimal"):n&&d.set("Prefer",`count=${n}`),new L({method:o,url:c,headers:d,schema:this.schemaName,body:h,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit})}};var rt="/entities",Lt=(s,t)=>new tt(s+rt,{fetch:t.fetchWithAuth.bind(t)});var 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=`
5
5
  .__nvwa-inspector-overlay {
6
6
  position: absolute;
7
7
  pointer-events: none;
@@ -33,4 +33,4 @@ ${l.stack}`)}else{var P;o=(P=n?.stack)!==null&&P!==void 0?P:""}let v=this.url.to
33
33
  max-width: 400px;
34
34
  word-break: break-all;
35
35
  }
36
- `,document.head.appendChild(t)}createTooltip(){return this.tooltip?this.tooltip:(this.tooltip=document.createElement("div"),this.tooltip.id="__nvwa-inspector-tooltip",document.body.appendChild(this.tooltip),this.tooltip)}createOverlay(t){let e=document.createElement("div");return e.className=`__nvwa-inspector-overlay __nvwa-inspector-overlay-${t}`,document.body.appendChild(e),e}updateOverlayPosition(t,e){if(!e.isConnected)return;let r=e.getBoundingClientRect(),i=window.scrollX||window.pageXOffset,n=window.scrollY||window.pageYOffset;r.width>0&&r.height>0?(t.style.left=`${r.left+i}px`,t.style.top=`${r.top+n}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 c=t.getBoundingClientRect();o.style.left=`${c.left+window.scrollX}px`,o.style.top=`${c.top+window.scrollY-o.offsetHeight-8}px`,c.top<o.offsetHeight+8&&(o.style.top=`${c.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 n=this.createTooltip();e?n.textContent=e:n.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,n.style.display="block";let a=t.getBoundingClientRect();n.style.left=`${a.left+window.scrollX}px`,n.style.top=`${a.top+window.scrollY-n.offsetHeight-8}px`,a.top<n.offsetHeight+8&&(n.style.top=`${a.bottom+window.scrollY+8}px`)}selectElement(t,e){if(!t.isConnected)return;if(this.selectedElement===t&&this.selectedOverlay){this.updateOverlayPosition(this.selectedOverlay,t);return}this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null);let r=this.createOverlay("selected");this.updateOverlayPosition(r,t),this.selectedOverlay=r,this.selectedElement=t;let i=()=>{this.selectedOverlay&&this.selectedElement&&this.selectedElement.isConnected&&this.updateOverlayPosition(this.selectedOverlay,this.selectedElement)};this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler)),this.selectedUpdateHandler=i,window.addEventListener("scroll",i,!0),window.addEventListener("resize",i)}removeHighlight(){this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null),this.hoverElement&&(this.hoverElement=null),this.tooltip&&(this.tooltip.style.display="none"),this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler),this.hoverUpdateHandler=null)}clearSelection(){this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null),this.selectedElement&&(this.selectedElement=null),this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler),this.selectedUpdateHandler=null)}cleanup(){this.removeHighlight(),this.clearSelection(),this.tooltip&&this.tooltip.parentNode&&(this.tooltip.parentNode.removeChild(this.tooltip),this.tooltip=null);let t=document.getElementById("__nvwa-inspector-overlay-style");t&&t.parentNode&&t.parentNode.removeChild(t)}};function Ct(s="root"){if(typeof document>"u")return null;let t=document.getElementById(s)||document.body;if(!t)return null;let e=t.querySelector("[data-source-location]");if(e){let r=e.getAttribute("data-source-location");if(r)return r}if(t.firstElementChild){let i=t.firstElementChild.getAttribute("data-source-location");if(i)return i}return null}var St={"wechat-pay":{id:"wechat-pay",name:"WeChat Pay",description:"WeChat payment for web and miniapp."},"wechat-platform":{id:"wechat-platform",name:"WeChat Partner",description:"WeChat partner merchant onboarding."},"alipay-web":{id:"alipay-web",name:"Alipay Web",description:"Alipay page pay (ISV)."},"alipay-mobile-web":{id:"alipay-mobile-web",name:"Alipay Mobile Web",description:"Alipay WAP pay (ISV)."},"alipay-miniprogram":{id:"alipay-miniprogram",name:"Alipay Mini Program",description:"Alipay mini program payment."},stripe:{id:"stripe",name:"Stripe",description:"Stripe payment."}};function Lt(s){let t=s;if(typeof t.kind=="string")return t;if(typeof t.tradeNO=="string")return{kind:"alipay_miniprogram",tradeNO:t.tradeNO};if(typeof t.clientSecret=="string")return{kind:"stripe_client_secret",clientSecret:t.clientSecret};if(typeof t.redirectUrl=="string")return{kind:"redirect_url",redirectUrl:t.redirectUrl};if(typeof t.formHtml=="string")return{kind:"alipay_page",formHtml:t.formHtml};if(typeof t.codeUrl=="string")return{kind:"wechat_native_qr",codeUrl:t.codeUrl};let e=t.jsapiPayParams??t;return typeof e.timeStamp=="string"&&typeof e.nonceStr=="string"&&typeof e.package=="string"&&typeof e.paySign=="string"&&typeof e.appId=="string"?{kind:"wechat_jsapi",mode:"jsapi",jsapiPayParams:{appId:e.appId,timeStamp:e.timeStamp,nonceStr:e.nonceStr,package:e.package,signType:e.signType??"RSA",paySign:e.paySign}}:null}function Tt(s,t,e){return t.requestPayment(s.payParams,e)}async function Et(s,t){let e=s.payment?.providers??{};return Object.entries(e).filter(([,r])=>r.enabled).map(([r])=>{let i=St[r]??{id:r,name:r,description:""};return{...i,type:i.id}})}function R(s){return s&&typeof s=="object"?s:{}}function Rt(s){let t=R(s),e=t.enabled===!0,r=String(t.oauthCredentialSource??"").toLowerCase();return r?{enabled:e,oauthCredentialSource:r==="custom"?"custom":"nvwa_default"}:{enabled:e}}function et(s){let t=R(s),e=R(t.providers),r={};for(let[i,n]of Object.entries(e))r[i]=Rt(n);return{providers:r}}function H(s){let t=R(s);return{socialLogin:et(t.socialLogin),payment:et(t.payment)}}function xt(s,t){let e=s[t];return e?Object.entries(e.providers).filter(([,r])=>r.enabled).map(([r])=>r):[]}var rt=["DesktopWeb","MobileWeb","AndroidApp","IosApp","HarmonyApp","WechatMiniProgram","AlipayMiniProgram","DouyinMiniProgram"];function x(s){return rt.includes(s)}function _t(s,t){let e=s.payParams;return{orderId:t?.orderId,platformOrderId:s.platformOrderId,payParams:e,codeUrl:typeof e.codeUrl=="string"?e.codeUrl:void 0,formHtml:typeof e.formHtml=="string"?e.formHtml:void 0,order:t?.order}}async function At(s){let{platformType:t,getMiniProgramIdentity:e}=s;if(t!=="WechatMiniProgram"&&t!=="AlipayMiniProgram")return{platformType:t};if(!e)return{platformType:t};let r=await e();return r?{platformType:r.platformType,platformUserId:r.platformUserId,appId:r.appId,unionid:r.unionid}:{platformType:t}}function O(s){return typeof s=="string"?s.trim():""}function It(s){if(!s||typeof s!="object"||Array.isArray(s))return{ok:!1,error:"Request body must be a JSON object"};let t=s,e=t.client;if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,error:"client is required and must be an object with platformType (use collectPaymentClientContext / nvwa.payment.collectPaymentClientContext)"};let r=e,i=O(r.platformType);if(!i)return{ok:!1,error:"client.platformType is required and must be non-empty"};if(!x(i))return{ok:!1,error:"client.platformType is invalid; use a valid ProjectPlatformType (e.g. DesktopWeb, MobileWeb, WechatMiniProgram)"};let n={platformType:i},a=O(r.platformUserId);a&&(n.platformUserId=a);let o=O(r.appId);o&&(n.appId=o);let c=O(r.unionid);c&&(n.unionid=c);let h=O(t.providerId);if(!h)return{ok:!1,error:"providerId is required"};let l=O(t.bizOrderId);if(!l)return{ok:!1,error:"bizOrderId is required"};let p=t.amount;if(typeof p!="number"||!Number.isFinite(p)||p<=0)return{ok:!1,error:"amount must be a positive number"};let d=O(t.currency),g=O(t.returnUrl),m;if(t.metadata!=null){if(typeof t.metadata!="object"||Array.isArray(t.metadata))return{ok:!1,error:"metadata must be a plain object when provided"};m={...t.metadata}}return{ok:!0,request:{client:n,bizOrderId:l,amount:p,providerId:h,...d?{currency:d}:{},...g?{returnUrl:g}:{},...m?{metadata:m}:{}}}}function kt(s){if(!s?.trim())return{};try{return JSON.parse(s)}catch{return{}}}function Ut(s){return H(s.integrationProviders??{})}function $t(s){let t=s.baseUrl?.trim()??"";if(!t)throw new Error("Nvwa: appConfig.baseUrl is required");let e=s.applicationCode?.trim()??"";if(!e)throw new Error("Nvwa: appConfig.applicationCode is required");let r=s.platformType?.trim()??"";if(!r)throw new Error("Nvwa: appConfig.platformType is required");if(!x(r))throw new Error("Nvwa: appConfig.platformType is invalid");return{baseUrl:t,applicationCode:e,platformType:r}}0&&(module.exports={AuthClient,CURRENT_JWT_KEY,ENTITIES_BASE_PATH,FILE_STORAGE_BASE_PATH,GENERATE_UPLOAD_URL_PATH,Headers,LOGIN_TOKEN_KEY,LOGIN_USER_PROFILE_KEY,NvwaEdgeFunctions,NvwaFileStorage,NvwaHttpClient,OverlayManager,PROJECT_PLATFORM_TYPES,Request,Response,SET_AUTH_TOKEN_HEADER,URL,collectPaymentClientContext,createPostgrestClient,getEnabledProvidersByIntegration,getPaymentProvidersFromIntegrationProviders,getSourceLocationFromDOM,isProjectPlatformType,normalizeIntegrationProvidersConfig,normalizePayParams,parseCreatePaymentOrderRequest,parseNvwaAppConfig,requestPaymentFromOrderResult,requireNvwaAppConfig,resolveIntegrationProvidersFromAppConfig,toPaymentOrderResultFromGateway});
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,n=window.scrollY||window.pageYOffset;r.width>0&&r.height>0?(t.style.left=`${r.left+i}px`,t.style.top=`${r.top+n}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 c=t.getBoundingClientRect();o.style.left=`${c.left+window.scrollX}px`,o.style.top=`${c.top+window.scrollY-o.offsetHeight-8}px`,c.top<o.offsetHeight+8&&(o.style.top=`${c.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 n=this.createTooltip();e?n.textContent=e:n.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,n.style.display="block";let a=t.getBoundingClientRect();n.style.left=`${a.left+window.scrollX}px`,n.style.top=`${a.top+window.scrollY-n.offsetHeight-8}px`,a.top<n.offsetHeight+8&&(n.style.top=`${a.bottom+window.scrollY+8}px`)}selectElement(t,e){if(!t.isConnected)return;if(this.selectedElement===t&&this.selectedOverlay){this.updateOverlayPosition(this.selectedOverlay,t);return}this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null);let r=this.createOverlay("selected");this.updateOverlayPosition(r,t),this.selectedOverlay=r,this.selectedElement=t;let i=()=>{this.selectedOverlay&&this.selectedElement&&this.selectedElement.isConnected&&this.updateOverlayPosition(this.selectedOverlay,this.selectedElement)};this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler)),this.selectedUpdateHandler=i,window.addEventListener("scroll",i,!0),window.addEventListener("resize",i)}removeHighlight(){this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null),this.hoverElement&&(this.hoverElement=null),this.tooltip&&(this.tooltip.style.display="none"),this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler),this.hoverUpdateHandler=null)}clearSelection(){this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null),this.selectedElement&&(this.selectedElement=null),this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler),this.selectedUpdateHandler=null)}cleanup(){this.removeHighlight(),this.clearSelection(),this.tooltip&&this.tooltip.parentNode&&(this.tooltip.parentNode.removeChild(this.tooltip),this.tooltip=null);let t=document.getElementById("__nvwa-inspector-overlay-style");t&&t.parentNode&&t.parentNode.removeChild(t)}};function Tt(s="root"){if(typeof document>"u")return null;let t=document.getElementById(s)||document.body;if(!t)return null;let e=t.querySelector("[data-source-location]");if(e){let r=e.getAttribute("data-source-location");if(r)return r}if(t.firstElementChild){let i=t.firstElementChild.getAttribute("data-source-location");if(i)return i}return null}var Et={"wechat-pay":{id:"wechat-pay",name:"WeChat Pay",description:"WeChat payment for web and miniapp."},"wechat-platform":{id:"wechat-platform",name:"WeChat Partner",description:"WeChat partner merchant onboarding."},"alipay-web":{id:"alipay-web",name:"Alipay Web",description:"Alipay page pay (ISV)."},"alipay-mobile-web":{id:"alipay-mobile-web",name:"Alipay Mobile Web",description:"Alipay WAP pay (ISV)."},"alipay-miniprogram":{id:"alipay-miniprogram",name:"Alipay Mini Program",description:"Alipay mini program payment."},stripe:{id:"stripe",name:"Stripe",description:"Stripe payment."}};function xt(s){let t=s;if(typeof t.kind=="string")return t;if(typeof t.tradeNO=="string")return{kind:"alipay_miniprogram",tradeNO:t.tradeNO};if(typeof t.clientSecret=="string")return{kind:"stripe_client_secret",clientSecret:t.clientSecret};if(typeof t.redirectUrl=="string")return{kind:"redirect_url",redirectUrl:t.redirectUrl};if(typeof t.formHtml=="string")return{kind:"alipay_page",formHtml:t.formHtml};if(typeof t.codeUrl=="string")return{kind:"wechat_native_qr",codeUrl:t.codeUrl};let e=t.jsapiPayParams??t;return typeof e.timeStamp=="string"&&typeof e.nonceStr=="string"&&typeof e.package=="string"&&typeof e.paySign=="string"&&typeof e.appId=="string"?{kind:"wechat_jsapi",mode:"jsapi",jsapiPayParams:{appId:e.appId,timeStamp:e.timeStamp,nonceStr:e.nonceStr,package:e.package,signType:e.signType??"RSA",paySign:e.paySign}}:null}function Rt(s,t,e){return t.requestPayment(s.payParams,e)}async function _t(s,t){let e=s.payment?.providers??{};return Object.entries(e).filter(([,r])=>r.enabled).map(([r])=>{let i=Et[r]??{id:r,name:r,description:""};return{...i,type:i.id}})}function _(s){return s&&typeof s=="object"?s:{}}function At(s){let t=_(s),e=t.enabled===!0,r=String(t.oauthCredentialSource??"").toLowerCase();return r?{enabled:e,oauthCredentialSource:r==="custom"?"custom":"nvwa_default"}:{enabled:e}}function st(s){let t=_(s),e=_(t.providers),r={};for(let[i,n]of Object.entries(e))r[i]=At(n);return{providers:r}}function M(s){let t=_(s);return{socialLogin:st(t.socialLogin),payment:st(t.payment)}}function kt(s,t){let e=s[t];return e?Object.entries(e.providers).filter(([,r])=>r.enabled).map(([r])=>r):[]}var it=["DesktopWeb","MobileWeb","AndroidApp","IosApp","HarmonyApp","WechatMiniProgram","AlipayMiniProgram","DouyinMiniProgram"];function A(s){return it.includes(s)}function It(s,t){let e=s.payParams;return{orderId:t?.orderId,platformOrderId:s.platformOrderId,payParams:e,codeUrl:typeof e.codeUrl=="string"?e.codeUrl:void 0,formHtml:typeof e.formHtml=="string"?e.formHtml:void 0,order:t?.order}}async function Ut(s){let{platformType:t,getMiniProgramIdentity:e}=s;if(t!=="WechatMiniProgram"&&t!=="AlipayMiniProgram")return{platformType:t};if(!e)return{platformType:t};let r=await e();return r?{platformType:r.platformType,platformUserId:r.platformUserId,appId:r.appId,unionid:r.unionid}:{platformType:t}}function O(s){return typeof s=="string"?s.trim():""}function Nt(s){if(!s||typeof s!="object"||Array.isArray(s))return{ok:!1,error:"Request body must be a JSON object"};let t=s,e=t.client;if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,error:"client is required and must be an object with platformType (use collectPaymentClientContext / nvwa.payment.collectPaymentClientContext)"};let r=e,i=O(r.platformType);if(!i)return{ok:!1,error:"client.platformType is required and must be non-empty"};if(!A(i))return{ok:!1,error:"client.platformType is invalid; use a valid ProjectPlatformType (e.g. DesktopWeb, MobileWeb, WechatMiniProgram)"};let n={platformType:i},a=O(r.platformUserId);a&&(n.platformUserId=a);let o=O(r.appId);o&&(n.appId=o);let c=O(r.unionid);c&&(n.unionid=c);let h=O(t.providerId);if(!h)return{ok:!1,error:"providerId is required"};let l=O(t.bizOrderId);if(!l)return{ok:!1,error:"bizOrderId is required"};let p=t.amount;if(typeof p!="number"||!Number.isFinite(p)||p<=0)return{ok:!1,error:"amount must be a positive number"};let d=O(t.currency),g=O(t.returnUrl),m;if(t.metadata!=null){if(typeof t.metadata!="object"||Array.isArray(t.metadata))return{ok:!1,error:"metadata must be a plain object when provided"};m={...t.metadata}}return{ok:!0,request:{client:n,bizOrderId:l,amount:p,providerId:h,...d?{currency:d}:{},...g?{returnUrl:g}:{},...m?{metadata:m}:{}}}}function $t(s){if(!s?.trim())return{};try{return JSON.parse(s)}catch{return{}}}function jt(s){return M(s.integrationProviders??{})}function Wt(s){let t=s.baseUrl?.trim()??"";if(!t)throw new Error("Nvwa: appConfig.baseUrl is required");let e=s.applicationCode?.trim()??"";if(!e)throw new Error("Nvwa: appConfig.applicationCode is required");let r=s.platformType?.trim()??"";if(!r)throw new Error("Nvwa: appConfig.platformType is required");if(!A(r))throw new Error("Nvwa: appConfig.platformType is invalid");return{baseUrl:t,applicationCode:e,platformType:r}}0&&(module.exports={AuthClient,CURRENT_JWT_KEY,ENTITIES_BASE_PATH,FILE_STORAGE_BASE_PATH,GENERATE_UPLOAD_URL_PATH,Headers,LOGIN_TOKEN_KEY,LOGIN_USER_PROFILE_KEY,NvwaEdgeFunctions,NvwaFileStorage,NvwaFunctionInvokeError,NvwaHttpClient,OverlayManager,PROJECT_PLATFORM_TYPES,Request,Response,SET_AUTH_TOKEN_HEADER,URL,collectPaymentClientContext,createPostgrestClient,edgeFunctionInvokeErrorMessage,getEnabledProvidersByIntegration,getPaymentProvidersFromIntegrationProviders,getSourceLocationFromDOM,isProjectPlatformType,normalizeIntegrationProvidersConfig,normalizePayParams,parseCreatePaymentOrderRequest,parseNvwaAppConfig,requestPaymentFromOrderResult,requireNvwaAppConfig,resolveIntegrationProvidersFromAppConfig,toPaymentOrderResultFromGateway});
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
- var f=class k{constructor(t){if(this.headerMap=new Map,t){if(t instanceof k)t.forEach((e,r)=>this.set(r,e));else if(Array.isArray(t))for(let[e,r]of t)this.set(e,String(r));else if(typeof t=="object")for(let e of Object.keys(t))this.set(e,String(t[e]))}}append(t,e){let r=t.toLowerCase(),i=this.headerMap.get(r);this.headerMap.set(r,i?`${i}, ${e}`:e)}set(t,e){this.headerMap.set(t.toLowerCase(),String(e))}get(t){return this.headerMap.get(t.toLowerCase())??null}has(t){return this.headerMap.has(t.toLowerCase())}delete(t){this.headerMap.delete(t.toLowerCase())}forEach(t){for(let[e,r]of this.headerMap.entries())t(r,e,this)}entries(){return this.headerMap.entries()}keys(){return this.headerMap.keys()}values(){return this.headerMap.values()}[Symbol.iterator](){return this.entries()}},tt=class U{constructor(t){if(this.params=new Map,t){if(typeof t=="string")this.parseString(t);else if(t instanceof U)this.params=new Map(t.params);else if(Array.isArray(t))for(let[e,r]of t)this.append(e,r);else if(t&&typeof t=="object")for(let[e,r]of Object.entries(t))this.set(e,r)}}parseString(t){t.startsWith("?")&&(t=t.slice(1));let e=t.split("&");for(let r of e)if(r){let[i,n]=r.split("=");i&&this.append(decodeURIComponent(i),n?decodeURIComponent(n):"")}}append(t,e){let r=this.params.get(t)||[];r.push(e),this.params.set(t,r)}delete(t){this.params.delete(t)}get(t){let e=this.params.get(t);return e?e[0]:null}getAll(t){return this.params.get(t)||[]}has(t){return this.params.has(t)}set(t,e){this.params.set(t,[e])}sort(){let t=Array.from(this.params.entries()).sort(([e],[r])=>e.localeCompare(r));this.params=new Map(t)}toString(){let t=[];for(let[e,r]of this.params.entries())for(let i of r)t.push(`${encodeURIComponent(e)}=${encodeURIComponent(i)}`);return t.join("&")}forEach(t){for(let[e,r]of this.params.entries())for(let i of r)t(i,e,this)}keys(){return this.params.keys()}values(){let t=[];for(let e of this.params.values())t.push(...e);return t[Symbol.iterator]()}entries(){let t=[];for(let[e,r]of this.params.entries())for(let i of r)t.push([e,i]);return t[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}},S=class x{constructor(t,e){let r;if(t instanceof x)r=t.href;else if(e){let n=e instanceof x?e.href:e;r=this.resolve(n,t)}else r=t;let i=this.parseUrl(r);this.href=r,this.origin=`${i.protocol}//${i.host}`,this.protocol=i.protocol,this.username=i.username,this.password=i.password,this.host=i.host,this.hostname=i.hostname,this.port=i.port,this.pathname=i.pathname,this.search=i.search,this.searchParams=new tt(i.search),this.hash=i.hash}resolve(t,e){if(e.startsWith("http://")||e.startsWith("https://"))return e;if(e.startsWith("//"))return`${this.parseUrl(t).protocol}${e}`;if(e.startsWith("/")){let n=this.parseUrl(t);return`${n.protocol}//${n.host}${e}`}let r=this.parseUrl(t),i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/";return`${r.protocol}//${r.host}${i}${e}`}parseUrl(t){let e=t.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!e)throw new TypeError("Invalid URL");let r=e[2]||"",i=e[4]||"",n=e[5]||"/",a=e[7]?`?${e[7]}`:"",o=e[9]?`#${e[9]}`:"";if(!r&&!i&&!n.startsWith("/")&&!n.includes("/")&&!n.includes("."))throw new TypeError("Invalid URL");let c=i.match(/^([^@]*)@(.+)$/),h="",l="",p=i;if(c){let b=c[1];p=c[2];let v=b.match(/^([^:]*):?(.*)$/);v&&(h=v[1]||"",l=v[2]||"")}let u=p.match(/^([^:]+):?(\d*)$/),d=u?u[1]:p,m=u&&u[2]?u[2]:"";return{protocol:r?`${r}:`:"",username:h,password:l,host:p,hostname:d,port:m,pathname:n,search:a,hash:o}}toString(){let t=this.searchParams.toString(),e=t?`?${t}`:"";return`${this.protocol}//${this.host}${this.pathname}${e}${this.hash}`}toJSON(){return this.toString()}},$=class N{constructor(t,e){if(typeof t=="string")this.url=t;else if(t?.url)this.url=String(t.url);else if(typeof t?.toString=="function")this.url=String(t.toString());else throw new Error("Invalid input for Request");this.method=(e?.method||"GET").toUpperCase(),this.headers=e?.headers instanceof f?e.headers:new f(e?.headers),this.body=e?.body,this.timeout=e?.timeout,this.signal=e?.signal||void 0}clone(){return new N(this.url,{method:this.method,headers:this.headers,body:this.body,timeout:this.timeout})}toString(){return this.url}},j=class{constructor(s,t){this.bodyData=s,this.status=t?.status??200,this.statusText=t?.statusText??"",this.headers=et(t?.headers),this.ok=this.status>=200&&this.status<300}async text(){return typeof this.bodyData=="string"?this.bodyData:this.bodyData==null?"":typeof this.bodyData=="object"?JSON.stringify(this.bodyData):String(this.bodyData)}async json(){if(typeof this.bodyData=="string")try{return JSON.parse(this.bodyData)}catch{}return this.bodyData}async arrayBuffer(){let s=await this.text();return new TextEncoder().encode(s).buffer}};function et(s){return s?new f(s):new f}var rt=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 s of Array.from(this.listeners))try{s()}catch{}this.listeners.clear()}}addEventListener(s,t){if(this._aborted){try{t()}catch{}return}this.listeners.add(t)}removeEventListener(s,t){this.listeners.delete(t)}toString(){return"[object AbortSignal]"}},W=class{constructor(){this._signal=new rt}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}};function st(s){if(s!==void 0)return typeof s=="string"||s instanceof FormData||s instanceof Blob||s instanceof File||s instanceof ArrayBuffer||ArrayBuffer.isView(s)||typeof ReadableStream<"u"&&s instanceof ReadableStream?s:typeof s=="object"&&s!==null?JSON.stringify(s):s}var H=class{constructor(t,e=""){this.http=t,this.baseUrl=e.replace(/\/$/,"")}async invoke(t,e){let r=this.baseUrl?`${this.baseUrl}/functions/${t}`:`/functions/${t}`;return await(await this.http.fetchWithAuth(r,{method:e.method||"POST",body:st(e.body),headers:e.headers})).json()}};var g="nvwa_current_jwt",P="nvwa_login_token",O="nvwa_user_profile",M="set-auth-token",it=typeof fetch<"u"?(s,t)=>fetch(s,t):()=>{throw new Error("AuthClient requires fetch")},F={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 q(s){let t=F[s]??{id:s,name:s,description:""},e="unsupported";switch(s){case"google":e="google_openplatform";break;case"github":e="github_openplatform";break;case"wechat-website":e="wechat_website_openplatform";break;case"wechat-miniprogram":e="wechat_miniprogram_code";break;case"alipay-miniprogram":e="alipay_miniprogram_code";break;case"douyin-miniprogram":e="douyin_miniprogram_code";break;default:break}return{id:t.id,type:t.id,name:t.name,description:t.description,loginKind:e}}function G(s,t){let e=s.socialLogin?.providers?.[t];return e?.enabled?e.oauthCredentialSource==="custom"?"custom":"nvwa_default":null}var _=class{constructor(t,e={}){this.baseUrl=t.replace(/\/$/,""),this.authPath=(e.authPath??"/auth").replace(/^\//,""),this.fetchImpl=e.fetchImpl??it,this.storage=e.storage??null,this.credentials=e.credentials??"omit",this.integrationProviders=e.integrationProviders??{},this.defaultApplicationCode=e.applicationCode?.trim()||null,this.platformType=e.platformType,typeof console<"u"&&(console.warn("[NvwaAuth] init baseUrl:",this.baseUrl||"(empty)"),(!this.baseUrl||!this.baseUrl.startsWith("http://")&&!this.baseUrl.startsWith("https://"))&&console.warn("[NvwaAuth] baseUrl \u5E94\u4E3A\u5B8C\u6574\u5730\u5740\uFF08\u5982 https://xxx.nvwa.app\uFF09\uFF0C\u5426\u5219\u5C0F\u7A0B\u5E8F request \u4F1A\u62A5 invalid url"))}async getSocialProviders(t){let e=this.integrationProviders.socialLogin?.providers??{};return Object.entries(e).filter(([,r])=>r.enabled).map(([r])=>{let i=F[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])=>q(r))}async getAvailableProviders(t){return this.getSocialProviders(t)}async startSocialLogin(t,e){let r=q(t),i=e?.applicationCode?.trim()||this.defaultApplicationCode||void 0,n=e?.returnUrl??(typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:"");switch(r.loginKind){case"google_openplatform":if(!n)throw new Error("startSocialLogin requires returnUrl for google");this.startGoogleOpenPlatformLogin(n,{applicationCode:i,platformCode:e?.platformCode});return;case"github_openplatform":if(!n)throw new Error("startSocialLogin requires returnUrl for github");this.startGithubOpenPlatformLogin(n,{applicationCode:i,platformCode:e?.platformCode});return;case"wechat_website_openplatform":if(!n)throw new Error("startSocialLogin requires returnUrl for wechat-website");this.startWechatWebsiteOpenPlatformLogin(n);return;case"wechat_miniprogram_code":if(!e?.miniProgramCode?.trim()||!i)throw new Error("startSocialLogin requires miniProgramCode and applicationCode for wechat-miniprogram");await this.loginWithWeChatCode(e.miniProgramCode.trim(),i);return;case"alipay_miniprogram_code":if(!e?.miniProgramCode?.trim()||!i)throw new Error("startSocialLogin requires miniProgramCode and applicationCode for alipay-miniprogram");await this.loginWithAlipayCode(e.miniProgramCode.trim(),i);return;case"douyin_miniprogram_code":throw new Error("startSocialLogin does not support douyin-miniprogram yet");default:throw new Error(`startSocialLogin unsupported provider: ${t}`)}}async currentUser(){if(this.storage){let r=await this.storage.get(O);if(r!=null)return r}let{data:t}=await this.getSession(),e=t?.user??null;return e&&this.storage&&await this.storage.set(O,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(P),{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 i=e?.headers.get(M)?.trim()||t.token||t.session?.token;i&&await this.storage.set(P,i),t.user&&await this.storage.set(O,t.user);let n=i??await this.storage.get(P),{data:a}=await this.getToken(n??void 0);a?.token&&await this.storage.set(g,a.token)}async clearLogin(){this.storage&&(await this.storage.remove(P),await this.storage.remove(O),await this.storage.remove(g))}getGoogleOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t}),i=e?.applicationCode?.trim()||this.defaultApplicationCode||"";i&&r.set("application_code",i);let n=e?.platformCode?.trim()??"";n&&r.set("platform_code",n);let a=G(this.integrationProviders,"google");return a&&r.set("oauth_credential_source",a),`${this.url("google/openplatform/login")}?${r.toString()}`}startGoogleOpenPlatformLogin(t,e){let r=this.getGoogleOpenPlatformLoginUrl(t,e);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=r;return}throw new Error("startGoogleOpenPlatformLogin requires a browser environment with location")}async completeGoogleOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeGoogleOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithGoogleExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithGoogleExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(g);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("google/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):null;return!n?.token||!n.user?{error:{message:"invalid_google_login_response",status:502}}:(this.storage&&(await this.storage.set(g,n.token),await this.storage.set(P,n.token),await this.storage.set(O,n.user)),{data:n})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGoogleOpenPlatformIdentity(){try{let t={};if(this.storage){let n=await this.storage.get(g);n!=null&&(t.Authorization=`Bearer ${n}`)}let e=await this.fetchImpl(this.url("google/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_google_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getGithubOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t}),i=e?.applicationCode?.trim()||this.defaultApplicationCode||"";i&&r.set("application_code",i);let n=e?.platformCode?.trim()??"";n&&r.set("platform_code",n);let a=G(this.integrationProviders,"github");return a&&r.set("oauth_credential_source",a),`${this.url("github/openplatform/login")}?${r.toString()}`}startGithubOpenPlatformLogin(t,e){let r=this.getGithubOpenPlatformLoginUrl(t,e);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=r;return}throw new Error("startGithubOpenPlatformLogin requires a browser environment with location")}async completeGithubOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeGithubOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithGithubExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithGithubExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(g);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("github/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):null;return!n?.token||!n.user?{error:{message:"invalid_github_login_response",status:502}}:(this.storage&&(await this.storage.set(g,n.token),await this.storage.set(P,n.token),await this.storage.set(O,n.user)),{data:n})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGithubOpenPlatformIdentity(){try{let t={};if(this.storage){let n=await this.storage.get(g);n!=null&&(t.Authorization=`Bearer ${n}`)}let e=await this.fetchImpl(this.url("github/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_github_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getWechatWebsiteOpenPlatformLoginUrl(t){let e=new URLSearchParams({return_url:t});return`${this.url("wechat-website/openplatform/login")}?${e.toString()}`}startWechatWebsiteOpenPlatformLogin(t){let e=this.getWechatWebsiteOpenPlatformLoginUrl(t);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=e;return}throw new Error("startWechatWebsiteOpenPlatformLogin requires a browser environment with location")}async completeWechatWebsiteOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeWechatWebsiteOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithWechatWebsiteExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithWechatWebsiteExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(g);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("wechat-website/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):null;return!n?.token||!n.user?{error:{message:"invalid_wechat_website_login_response",status:502}}:(this.storage&&(await this.storage.set(g,n.token),await this.storage.set(P,n.token),await this.storage.set(O,n.user)),{data:n})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getWechatWebsiteOpenPlatformIdentity(){try{let t={};if(this.storage){let n=await this.storage.get(g);n!=null&&(t.Authorization=`Bearer ${n}`)}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 r=`${`${this.baseUrl.replace(/\/+$/,"")}/${this.authPath.replace(/^\/+/,"")}`}/${t.replace(/^\/+/,"")}`;return typeof console<"u"&&(console.warn("[NvwaAuth] request URL:",r),!r.startsWith("http://")&&!r.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")),r}async getSession(){try{let t={};if(this.storage){let i=await this.storage.get(P)??await this.storage.get(g);i!=null&&(t.Authorization=`Bearer ${i}`)}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 n=i?JSON.parse(i):void 0;return n&&await this.persistLogin({user:n.user,session:n.session},r),{data:n}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async signOut(){try{let t={"Content-Type":"application/json"};if(this.storage){let r=await this.storage.get(P)??await this.storage.get(g);r!=null&&(t.Authorization=`Bearer ${r}`)}await this.clearLogin();let e=await this.fetchImpl(this.url("sign-out"),{method:"POST",credentials:this.credentials,headers:t,body:"{}"});return e.ok?{}:{error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signUp(t){let e=await this.postJson("sign-up/email",t);return e.data&&await this.persistLogin(e.data,e.response),e}async getToken(t){try{let e={};if(t)e.Authorization=`Bearer ${t}`;else if(this.storage){let a=await this.storage.get(P)??await this.storage.get(g);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("token"),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):void 0;return{data:n?.token!=null?{token:n.token}:void 0}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async signInWithUsername(t,e){let r=await this.postJson("sign-in/username",{username:t,password:e});return r.data&&await this.persistLogin(r.data,r.response),r}async signInWithPhoneNumber(t,e,r){let i=await this.postJson("sign-in/phone-number",{phoneNumber:t,password:e,rememberMe:r});return i.data&&await this.persistLogin(i.data,i.response),i}async sendPhoneNumberOtp(t){let e=await this.postJson("phone-number/send-otp",{phoneNumber:t});return e.error?{error:e.error}:{}}async verifyPhoneNumber(t,e){let r=await this.postJson("phone-number/verify",{phoneNumber:t,code:e});return r.data&&await this.persistLogin(r.data,r.response),r}async loginWithWeChatCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let o=await this.storage.get(g);o!=null&&(r.Authorization=`Bearer ${o}`)}let i=await this.fetchImpl(this.url("wechat/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),n=await i.text();if(!i.ok)return{error:{message:n||i.statusText,status:i.status}};let a=n?JSON.parse(n):null;return!a?.token||!a.user?{error:{message:"invalid_wechat_login_response",status:502}}:(this.storage&&(await this.storage.set(g,a.token),await this.storage.set(P,a.token),await this.storage.set(O,a.user)),{data:a})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async loginWithAlipayCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let o=await this.storage.get(g);o!=null&&(r.Authorization=`Bearer ${o}`)}let i=await this.fetchImpl(this.url("alipay/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),n=await i.text();if(!i.ok)return{error:{message:n||i.statusText,status:i.status}};let a=n?JSON.parse(n):null;return!a?.token||!a.user?{error:{message:"invalid_alipay_login_response",status:502}}:(this.storage&&(await this.storage.set(g,a.token),await this.storage.set(P,a.token),await this.storage.set(O,a.user)),{data:a})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async getWeChatOpenPlatformIdentity(t){try{let e={};if(this.storage){let o=await this.storage.get(g);o!=null&&(e.Authorization=`Bearer ${o}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",i=await this.fetchImpl(this.url(`wechat/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),n=await i.text();if(!i.ok)return{error:{message:n||i.statusText,status:i.status}};let a=n?JSON.parse(n):null;return!a?.openid||!a.appId?{error:{message:"invalid_wechat_identity_response",status:502}}:{data:a}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getAlipayOpenPlatformIdentity(t){try{let e={};if(this.storage){let o=await this.storage.get(g);o!=null&&(e.Authorization=`Bearer ${o}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",i=await this.fetchImpl(this.url(`alipay/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),n=await i.text();if(!i.ok)return{error:{message:n||i.statusText,status:i.status}};let a=n?JSON.parse(n):null;return!a?.openid||!a.appId?{error:{message:"invalid_alipay_identity_response",status:502}}:{data:a}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getMiniProgramIdentity(t){let e=t?.applicationCode?.trim()||this.defaultApplicationCode||void 0;if(this.platformType==="WechatMiniProgram"){let r=await this.getWeChatOpenPlatformIdentity(e);if(!r.data)throw new Error(r.error?.message||"failed to get wechat open platform identity");return{platformType:this.platformType,appId:r.data.appId,platformUserId:r.data.openid,unionid:r.data.unionid}}else if(this.platformType==="AlipayMiniProgram"){let r=await this.getAlipayOpenPlatformIdentity(e);if(!r.data)throw new Error(r.error?.message||"failed to get wechat open platform identity");return{platformType:this.platformType,appId:r.data.appId,platformUserId:r.data.openid,unionid:r.data.unionid}}return null}async postJson(t,e){try{let r=await this.fetchImpl(this.url(t),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify(e)}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):void 0;return{data:n?.data??n??void 0,response:r}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}};var D=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 f(e?.headers);r&&i.set("Authorization",`Bearer ${r}`);let n=e?.method||"GET";if((n==="POST"||n==="PUT"||n==="PATCH")&&e?.body){let o=i.get("Content-Type");(!o||o.includes("text/plain"))&&i.set("Content-Type","application/json")}let a=await this.customFetch(t,{...e,headers:i});if(a.status===401)throw this.handleUnauthorized(),new Error("\u672A\u767B\u5F55");return a}};var nt="/storage",at=nt+"/generateUploadUrl",B=class{constructor(t,e){this.baseUrl=t,this.http=e}async uploadFile(t){let e=await this.http.fetch(this.baseUrl+at,{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 f({"Content-Type":t.type||t.fileType||"application/octet-stream"})}),{url:n}=await i.json();return{url:n.split("?")[0]}}};var ot=class extends Error{constructor(s){super(s.message),this.name="PostgrestError",this.details=s.details,this.hint=s.hint,this.code=s.code}},lt=class{constructor(s){var t,e,r;this.shouldThrowOnError=!1,this.method=s.method,this.url=s.url,this.headers=new f(s.headers),this.schema=s.schema,this.body=s.body,this.shouldThrowOnError=(t=s.shouldThrowOnError)!==null&&t!==void 0?t:!1,this.signal=s.signal,this.isMaybeSingle=(e=s.isMaybeSingle)!==null&&e!==void 0?e:!1,this.urlLengthLimit=(r=s.urlLengthLimit)!==null&&r!==void 0?r:8e3,s.fetch?this.fetch=s.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(s,t){return this.headers=new f(this.headers),this.headers.set(s,t),this}then(s,t){var e=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 r=this.fetch,i=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{let a=null,o=null,c=null,h=n.status,l=n.statusText;if(n.ok){var p,u;if(e.method!=="HEAD"){var d;let v=await n.text();v===""||(e.headers.get("Accept")==="text/csv"||e.headers.get("Accept")&&(!((d=e.headers.get("Accept"))===null||d===void 0)&&d.includes("application/vnd.pgrst.plan+text"))?o=v:o=JSON.parse(v))}let m=(p=e.headers.get("Prefer"))===null||p===void 0?void 0:p.match(/count=(exact|planned|estimated)/),b=(u=n.headers.get("content-range"))===null||u===void 0?void 0:u.split("/");m&&b&&b.length>1&&(c=parseInt(b[1])),e.isMaybeSingle&&Array.isArray(o)&&(o.length>1?(a={code:"PGRST116",details:`Results contain ${o.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},o=null,c=null,h=406,l="Not Acceptable"):o.length===1?o=o[0]:o=null)}else{let m=await n.text();try{a=JSON.parse(m),Array.isArray(a)&&n.status===404&&(o=[],a=null,h=200,l="OK")}catch{n.status===404&&m===""?(h=204,l="No Content"):a={message:m}}if(a&&e.shouldThrowOnError)throw new ot(a)}return{error:a,data:o,count:c,status:h,statusText:l}});return this.shouldThrowOnError||(i=i.catch(n=>{var a;let o="",c="",h="",l=n?.cause;if(l){var p,u,d,m;let Z=(p=l?.message)!==null&&p!==void 0?p:"",I=(u=l?.code)!==null&&u!==void 0?u:"";o=`${(d=n?.name)!==null&&d!==void 0?d:"FetchError"}: ${n?.message}`,o+=`
1
+ var f=class N{constructor(t){if(this.headerMap=new Map,t){if(t instanceof N)t.forEach((e,r)=>this.set(r,e));else if(Array.isArray(t))for(let[e,r]of t)this.set(e,String(r));else if(typeof t=="object")for(let e of Object.keys(t))this.set(e,String(t[e]))}}append(t,e){let r=t.toLowerCase(),i=this.headerMap.get(r);this.headerMap.set(r,i?`${i}, ${e}`:e)}set(t,e){this.headerMap.set(t.toLowerCase(),String(e))}get(t){return this.headerMap.get(t.toLowerCase())??null}has(t){return this.headerMap.has(t.toLowerCase())}delete(t){this.headerMap.delete(t.toLowerCase())}forEach(t){for(let[e,r]of this.headerMap.entries())t(r,e,this)}entries(){return this.headerMap.entries()}keys(){return this.headerMap.keys()}values(){return this.headerMap.values()}[Symbol.iterator](){return this.entries()}},rt=class ${constructor(t){if(this.params=new Map,t){if(typeof t=="string")this.parseString(t);else if(t instanceof $)this.params=new Map(t.params);else if(Array.isArray(t))for(let[e,r]of t)this.append(e,r);else if(t&&typeof t=="object")for(let[e,r]of Object.entries(t))this.set(e,r)}}parseString(t){t.startsWith("?")&&(t=t.slice(1));let e=t.split("&");for(let r of e)if(r){let[i,n]=r.split("=");i&&this.append(decodeURIComponent(i),n?decodeURIComponent(n):"")}}append(t,e){let r=this.params.get(t)||[];r.push(e),this.params.set(t,r)}delete(t){this.params.delete(t)}get(t){let e=this.params.get(t);return e?e[0]:null}getAll(t){return this.params.get(t)||[]}has(t){return this.params.has(t)}set(t,e){this.params.set(t,[e])}sort(){let t=Array.from(this.params.entries()).sort(([e],[r])=>e.localeCompare(r));this.params=new Map(t)}toString(){let t=[];for(let[e,r]of this.params.entries())for(let i of r)t.push(`${encodeURIComponent(e)}=${encodeURIComponent(i)}`);return t.join("&")}forEach(t){for(let[e,r]of this.params.entries())for(let i of r)t(i,e,this)}keys(){return this.params.keys()}values(){let t=[];for(let e of this.params.values())t.push(...e);return t[Symbol.iterator]()}entries(){let t=[];for(let[e,r]of this.params.entries())for(let i of r)t.push([e,i]);return t[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}},S=class _{constructor(t,e){let r;if(t instanceof _)r=t.href;else if(e){let n=e instanceof _?e.href:e;r=this.resolve(n,t)}else r=t;let i=this.parseUrl(r);this.href=r,this.origin=`${i.protocol}//${i.host}`,this.protocol=i.protocol,this.username=i.username,this.password=i.password,this.host=i.host,this.hostname=i.hostname,this.port=i.port,this.pathname=i.pathname,this.search=i.search,this.searchParams=new rt(i.search),this.hash=i.hash}resolve(t,e){if(e.startsWith("http://")||e.startsWith("https://"))return e;if(e.startsWith("//"))return`${this.parseUrl(t).protocol}${e}`;if(e.startsWith("/")){let n=this.parseUrl(t);return`${n.protocol}//${n.host}${e}`}let r=this.parseUrl(t),i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/";return`${r.protocol}//${r.host}${i}${e}`}parseUrl(t){let e=t.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!e)throw new TypeError("Invalid URL");let r=e[2]||"",i=e[4]||"",n=e[5]||"/",a=e[7]?`?${e[7]}`:"",o=e[9]?`#${e[9]}`:"";if(!r&&!i&&!n.startsWith("/")&&!n.includes("/")&&!n.includes("."))throw new TypeError("Invalid URL");let c=i.match(/^([^@]*)@(.+)$/),h="",l="",p=i;if(c){let b=c[1];p=c[2];let v=b.match(/^([^:]*):?(.*)$/);v&&(h=v[1]||"",l=v[2]||"")}let u=p.match(/^([^:]+):?(\d*)$/),d=u?u[1]:p,m=u&&u[2]?u[2]:"";return{protocol:r?`${r}:`:"",username:h,password:l,host:p,hostname:d,port:m,pathname:n,search:a,hash:o}}toString(){let t=this.searchParams.toString(),e=t?`?${t}`:"";return`${this.protocol}//${this.host}${this.pathname}${e}${this.hash}`}toJSON(){return this.toString()}},j=class W{constructor(t,e){if(typeof t=="string")this.url=t;else if(t?.url)this.url=String(t.url);else if(typeof t?.toString=="function")this.url=String(t.toString());else throw new Error("Invalid input for Request");this.method=(e?.method||"GET").toUpperCase(),this.headers=e?.headers instanceof f?e.headers:new f(e?.headers),this.body=e?.body,this.timeout=e?.timeout,this.signal=e?.signal||void 0}clone(){return new W(this.url,{method:this.method,headers:this.headers,body:this.body,timeout:this.timeout})}toString(){return this.url}},H=class{constructor(s,t){this.bodyData=s,this.status=t?.status??200,this.statusText=t?.statusText??"",this.headers=st(t?.headers),this.ok=this.status>=200&&this.status<300}async text(){return typeof this.bodyData=="string"?this.bodyData:this.bodyData==null?"":typeof this.bodyData=="object"?JSON.stringify(this.bodyData):String(this.bodyData)}async json(){if(typeof this.bodyData=="string")try{return JSON.parse(this.bodyData)}catch{}return this.bodyData}async arrayBuffer(){let s=await this.text();return new TextEncoder().encode(s).buffer}};function st(s){return s?new f(s):new f}var it=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 s of Array.from(this.listeners))try{s()}catch{}this.listeners.clear()}}addEventListener(s,t){if(this._aborted){try{t()}catch{}return}this.listeners.add(t)}removeEventListener(s,t){this.listeners.delete(t)}toString(){return"[object AbortSignal]"}},q=class{constructor(){this._signal=new it}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}};var L=class extends Error{constructor(t,e,r){super(t),this.name="NvwaFunctionInvokeError",this.status=e,this.bodyText=r}};function nt(s){if(!s||typeof s!="object")return null;let t=s;return typeof t.error=="string"&&t.error.length>0?t.error:typeof t.message=="string"&&t.message.length>0?t.message:null}function A(s,t){let e=t.trim();if(!e)return`Request failed with status ${s}`;try{let r=JSON.parse(e);return nt(r)??e}catch{return e}}function at(s){if(s!==void 0)return typeof s=="string"||s instanceof FormData||s instanceof Blob||s instanceof File||s instanceof ArrayBuffer||ArrayBuffer.isView(s)||typeof ReadableStream<"u"&&s instanceof ReadableStream?s:typeof s=="object"&&s!==null?JSON.stringify(s):s}var M=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}`,i=await this.http.fetchWithAuth(r,{method:e.method||"POST",body:at(e.body),headers:e.headers});if(!i.ok){let n=await i.text();throw new L(A(i.status,n),i.status,n)}try{return await i.json()}catch(n){let a=n instanceof Error?n.message:String(n);throw new L(`Invalid JSON in function response: ${a}`,i.status)}}};var g="nvwa_current_jwt",P="nvwa_login_token",O="nvwa_user_profile",D="set-auth-token",ot=typeof fetch<"u"?(s,t)=>fetch(s,t):()=>{throw new Error("AuthClient requires fetch")},B={google:{id:"google",name:"Google Login",description:"Sign in with Google account."},github:{id:"github",name:"GitHub Login",description:"Sign in with GitHub account."},"wechat-website":{id:"wechat-website",name:"WeChat QR Login",description:"Sign in with WeChat website QR code."},"wechat-miniprogram":{id:"wechat-miniprogram",name:"WeChat Mini Program Login",description:"Sign in with WeChat mini program code."},"alipay-miniprogram":{id:"alipay-miniprogram",name:"Alipay Mini Program Login",description:"Sign in with Alipay mini program code."},"douyin-miniprogram":{id:"douyin-miniprogram",name:"Douyin Mini Program Login",description:"Sign in with Douyin mini program code."}};function G(s){let t=B[s]??{id:s,name:s,description:""},e="unsupported";switch(s){case"google":e="google_openplatform";break;case"github":e="github_openplatform";break;case"wechat-website":e="wechat_website_openplatform";break;case"wechat-miniprogram":e="wechat_miniprogram_code";break;case"alipay-miniprogram":e="alipay_miniprogram_code";break;case"douyin-miniprogram":e="douyin_miniprogram_code";break;default:break}return{id:t.id,type:t.id,name:t.name,description:t.description,loginKind:e}}function F(s,t){let e=s.socialLogin?.providers?.[t];return e?.enabled?e.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??ot,this.storage=e.storage??null,this.credentials=e.credentials??"omit",this.integrationProviders=e.integrationProviders??{},this.defaultApplicationCode=e.applicationCode?.trim()||null,this.platformType=e.platformType,typeof console<"u"&&(console.warn("[NvwaAuth] init baseUrl:",this.baseUrl||"(empty)"),(!this.baseUrl||!this.baseUrl.startsWith("http://")&&!this.baseUrl.startsWith("https://"))&&console.warn("[NvwaAuth] baseUrl \u5E94\u4E3A\u5B8C\u6574\u5730\u5740\uFF08\u5982 https://xxx.nvwa.app\uFF09\uFF0C\u5426\u5219\u5C0F\u7A0B\u5E8F request \u4F1A\u62A5 invalid url"))}async getSocialProviders(t){let e=this.integrationProviders.socialLogin?.providers??{};return Object.entries(e).filter(([,r])=>r.enabled).map(([r])=>{let i=B[r]??{id:r,name:r,description:""};return{...i,type:i.id}})}async getSocialProviderDescriptors(t){let e=this.integrationProviders.socialLogin?.providers??{};return Object.entries(e).filter(([,r])=>!!r?.enabled).map(([r])=>G(r))}async getAvailableProviders(t){return this.getSocialProviders(t)}async startSocialLogin(t,e){let r=G(t),i=e?.applicationCode?.trim()||this.defaultApplicationCode||void 0,n=e?.returnUrl??(typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:"");switch(r.loginKind){case"google_openplatform":if(!n)throw new Error("startSocialLogin requires returnUrl for google");this.startGoogleOpenPlatformLogin(n,{applicationCode:i,platformCode:e?.platformCode});return;case"github_openplatform":if(!n)throw new Error("startSocialLogin requires returnUrl for github");this.startGithubOpenPlatformLogin(n,{applicationCode:i,platformCode:e?.platformCode});return;case"wechat_website_openplatform":if(!n)throw new Error("startSocialLogin requires returnUrl for wechat-website");this.startWechatWebsiteOpenPlatformLogin(n);return;case"wechat_miniprogram_code":if(!e?.miniProgramCode?.trim()||!i)throw new Error("startSocialLogin requires miniProgramCode and applicationCode for wechat-miniprogram");await this.loginWithWeChatCode(e.miniProgramCode.trim(),i);return;case"alipay_miniprogram_code":if(!e?.miniProgramCode?.trim()||!i)throw new Error("startSocialLogin requires miniProgramCode and applicationCode for alipay-miniprogram");await this.loginWithAlipayCode(e.miniProgramCode.trim(),i);return;case"douyin_miniprogram_code":throw new Error("startSocialLogin does not support douyin-miniprogram yet");default:throw new Error(`startSocialLogin unsupported provider: ${t}`)}}async currentUser(){if(this.storage){let r=await this.storage.get(O);if(r!=null)return r}let{data:t}=await this.getSession(),e=t?.user??null;return e&&this.storage&&await this.storage.set(O,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(P),{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 i=e?.headers.get(D)?.trim()||t.token||t.session?.token;i&&await this.storage.set(P,i),t.user&&await this.storage.set(O,t.user);let n=i??await this.storage.get(P),{data:a}=await this.getToken(n??void 0);a?.token&&await this.storage.set(g,a.token)}async clearLogin(){this.storage&&(await this.storage.remove(P),await this.storage.remove(O),await this.storage.remove(g))}getGoogleOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t}),i=e?.applicationCode?.trim()||this.defaultApplicationCode||"";i&&r.set("application_code",i);let n=e?.platformCode?.trim()??"";n&&r.set("platform_code",n);let a=F(this.integrationProviders,"google");return a&&r.set("oauth_credential_source",a),`${this.url("google/openplatform/login")}?${r.toString()}`}startGoogleOpenPlatformLogin(t,e){let r=this.getGoogleOpenPlatformLoginUrl(t,e);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=r;return}throw new Error("startGoogleOpenPlatformLogin requires a browser environment with location")}async completeGoogleOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeGoogleOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithGoogleExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithGoogleExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(g);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("google/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):null;return!n?.token||!n.user?{error:{message:"invalid_google_login_response",status:502}}:(this.storage&&(await this.storage.set(g,n.token),await this.storage.set(P,n.token),await this.storage.set(O,n.user)),{data:n})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGoogleOpenPlatformIdentity(){try{let t={};if(this.storage){let n=await this.storage.get(g);n!=null&&(t.Authorization=`Bearer ${n}`)}let e=await this.fetchImpl(this.url("google/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_google_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getGithubOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t}),i=e?.applicationCode?.trim()||this.defaultApplicationCode||"";i&&r.set("application_code",i);let n=e?.platformCode?.trim()??"";n&&r.set("platform_code",n);let a=F(this.integrationProviders,"github");return a&&r.set("oauth_credential_source",a),`${this.url("github/openplatform/login")}?${r.toString()}`}startGithubOpenPlatformLogin(t,e){let r=this.getGithubOpenPlatformLoginUrl(t,e);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=r;return}throw new Error("startGithubOpenPlatformLogin requires a browser environment with location")}async completeGithubOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeGithubOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithGithubExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithGithubExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(g);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("github/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):null;return!n?.token||!n.user?{error:{message:"invalid_github_login_response",status:502}}:(this.storage&&(await this.storage.set(g,n.token),await this.storage.set(P,n.token),await this.storage.set(O,n.user)),{data:n})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGithubOpenPlatformIdentity(){try{let t={};if(this.storage){let n=await this.storage.get(g);n!=null&&(t.Authorization=`Bearer ${n}`)}let e=await this.fetchImpl(this.url("github/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_github_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getWechatWebsiteOpenPlatformLoginUrl(t){let e=new URLSearchParams({return_url:t});return`${this.url("wechat-website/openplatform/login")}?${e.toString()}`}startWechatWebsiteOpenPlatformLogin(t){let e=this.getWechatWebsiteOpenPlatformLoginUrl(t);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=e;return}throw new Error("startWechatWebsiteOpenPlatformLogin requires a browser environment with location")}async completeWechatWebsiteOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeWechatWebsiteOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithWechatWebsiteExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithWechatWebsiteExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(g);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("wechat-website/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):null;return!n?.token||!n.user?{error:{message:"invalid_wechat_website_login_response",status:502}}:(this.storage&&(await this.storage.set(g,n.token),await this.storage.set(P,n.token),await this.storage.set(O,n.user)),{data:n})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getWechatWebsiteOpenPlatformIdentity(){try{let t={};if(this.storage){let n=await this.storage.get(g);n!=null&&(t.Authorization=`Bearer ${n}`)}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 r=`${`${this.baseUrl.replace(/\/+$/,"")}/${this.authPath.replace(/^\/+/,"")}`}/${t.replace(/^\/+/,"")}`;return typeof console<"u"&&(console.warn("[NvwaAuth] request URL:",r),!r.startsWith("http://")&&!r.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")),r}async getSession(){try{let t={};if(this.storage){let i=await this.storage.get(P)??await this.storage.get(g);i!=null&&(t.Authorization=`Bearer ${i}`)}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 n=i?JSON.parse(i):void 0;return n&&await this.persistLogin({user:n.user,session:n.session},r),{data:n}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async signOut(){try{let t={"Content-Type":"application/json"};if(this.storage){let r=await this.storage.get(P)??await this.storage.get(g);r!=null&&(t.Authorization=`Bearer ${r}`)}await this.clearLogin();let e=await this.fetchImpl(this.url("sign-out"),{method:"POST",credentials:this.credentials,headers:t,body:"{}"});return e.ok?{}:{error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signUp(t){let e=await this.postJson("sign-up/email",t);return e.data&&await this.persistLogin(e.data,e.response),e}async getToken(t){try{let e={};if(t)e.Authorization=`Bearer ${t}`;else if(this.storage){let a=await this.storage.get(P)??await this.storage.get(g);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("token"),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):void 0;return{data:n?.token!=null?{token:n.token}:void 0}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async signInWithUsername(t,e){let r=await this.postJson("sign-in/username",{username:t,password:e});return r.data&&await this.persistLogin(r.data,r.response),r}async signInWithPhoneNumber(t,e,r){let i=await this.postJson("sign-in/phone-number",{phoneNumber:t,password:e,rememberMe:r});return i.data&&await this.persistLogin(i.data,i.response),i}async sendPhoneNumberOtp(t){let e=await this.postJson("phone-number/send-otp",{phoneNumber:t});return e.error?{error:e.error}:{}}async verifyPhoneNumber(t,e){let r=await this.postJson("phone-number/verify",{phoneNumber:t,code:e});return r.data&&await this.persistLogin(r.data,r.response),r}async loginWithWeChatCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let o=await this.storage.get(g);o!=null&&(r.Authorization=`Bearer ${o}`)}let i=await this.fetchImpl(this.url("wechat/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),n=await i.text();if(!i.ok)return{error:{message:n||i.statusText,status:i.status}};let a=n?JSON.parse(n):null;return!a?.token||!a.user?{error:{message:"invalid_wechat_login_response",status:502}}:(this.storage&&(await this.storage.set(g,a.token),await this.storage.set(P,a.token),await this.storage.set(O,a.user)),{data:a})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async loginWithAlipayCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let o=await this.storage.get(g);o!=null&&(r.Authorization=`Bearer ${o}`)}let i=await this.fetchImpl(this.url("alipay/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),n=await i.text();if(!i.ok)return{error:{message:n||i.statusText,status:i.status}};let a=n?JSON.parse(n):null;return!a?.token||!a.user?{error:{message:"invalid_alipay_login_response",status:502}}:(this.storage&&(await this.storage.set(g,a.token),await this.storage.set(P,a.token),await this.storage.set(O,a.user)),{data:a})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async getWeChatOpenPlatformIdentity(t){try{let e={};if(this.storage){let o=await this.storage.get(g);o!=null&&(e.Authorization=`Bearer ${o}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",i=await this.fetchImpl(this.url(`wechat/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),n=await i.text();if(!i.ok)return{error:{message:n||i.statusText,status:i.status}};let a=n?JSON.parse(n):null;return!a?.openid||!a.appId?{error:{message:"invalid_wechat_identity_response",status:502}}:{data:a}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getAlipayOpenPlatformIdentity(t){try{let e={};if(this.storage){let o=await this.storage.get(g);o!=null&&(e.Authorization=`Bearer ${o}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",i=await this.fetchImpl(this.url(`alipay/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),n=await i.text();if(!i.ok)return{error:{message:n||i.statusText,status:i.status}};let a=n?JSON.parse(n):null;return!a?.openid||!a.appId?{error:{message:"invalid_alipay_identity_response",status:502}}:{data:a}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getMiniProgramIdentity(t){let e=t?.applicationCode?.trim()||this.defaultApplicationCode||void 0;if(this.platformType==="WechatMiniProgram"){let r=await this.getWeChatOpenPlatformIdentity(e);if(!r.data)throw new Error(r.error?.message||"failed to get wechat open platform identity");return{platformType:this.platformType,appId:r.data.appId,platformUserId:r.data.openid,unionid:r.data.unionid}}else if(this.platformType==="AlipayMiniProgram"){let r=await this.getAlipayOpenPlatformIdentity(e);if(!r.data)throw new Error(r.error?.message||"failed to get wechat open platform identity");return{platformType:this.platformType,appId:r.data.appId,platformUserId:r.data.openid,unionid:r.data.unionid}}return null}async postJson(t,e){try{let r=await this.fetchImpl(this.url(t),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify(e)}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):void 0;return{data:n?.data??n??void 0,response:r}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}};var 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),i=new f(e?.headers);r&&i.set("Authorization",`Bearer ${r}`);let n=e?.method||"GET";if((n==="POST"||n==="PUT"||n==="PATCH")&&e?.body){let o=i.get("Content-Type");(!o||o.includes("text/plain"))&&i.set("Content-Type","application/json")}let a=await this.customFetch(t,{...e,headers:i});if(a.status===401)throw this.handleUnauthorized(),new Error("\u672A\u767B\u5F55");return a}};var lt="/storage",ct=lt+"/generateUploadUrl",z=class{constructor(t,e){this.baseUrl=t,this.http=e}async uploadFile(t){let e=await this.http.fetch(this.baseUrl+ct,{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 f({"Content-Type":t.type||t.fileType||"application/octet-stream"})}),{url:n}=await i.json();return{url:n.split("?")[0]}}};var ht=class extends Error{constructor(s){super(s.message),this.name="PostgrestError",this.details=s.details,this.hint=s.hint,this.code=s.code}},pt=class{constructor(s){var t,e,r;this.shouldThrowOnError=!1,this.method=s.method,this.url=s.url,this.headers=new f(s.headers),this.schema=s.schema,this.body=s.body,this.shouldThrowOnError=(t=s.shouldThrowOnError)!==null&&t!==void 0?t:!1,this.signal=s.signal,this.isMaybeSingle=(e=s.isMaybeSingle)!==null&&e!==void 0?e:!1,this.urlLengthLimit=(r=s.urlLengthLimit)!==null&&r!==void 0?r:8e3,s.fetch?this.fetch=s.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(s,t){return this.headers=new f(this.headers),this.headers.set(s,t),this}then(s,t){var e=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 r=this.fetch,i=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{let a=null,o=null,c=null,h=n.status,l=n.statusText;if(n.ok){var p,u;if(e.method!=="HEAD"){var d;let v=await n.text();v===""||(e.headers.get("Accept")==="text/csv"||e.headers.get("Accept")&&(!((d=e.headers.get("Accept"))===null||d===void 0)&&d.includes("application/vnd.pgrst.plan+text"))?o=v:o=JSON.parse(v))}let m=(p=e.headers.get("Prefer"))===null||p===void 0?void 0:p.match(/count=(exact|planned|estimated)/),b=(u=n.headers.get("content-range"))===null||u===void 0?void 0:u.split("/");m&&b&&b.length>1&&(c=parseInt(b[1])),e.isMaybeSingle&&Array.isArray(o)&&(o.length>1?(a={code:"PGRST116",details:`Results contain ${o.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},o=null,c=null,h=406,l="Not Acceptable"):o.length===1?o=o[0]:o=null)}else{let m=await n.text();try{a=JSON.parse(m),Array.isArray(a)&&n.status===404&&(o=[],a=null,h=200,l="OK")}catch{n.status===404&&m===""?(h=204,l="No Content"):a={message:m}}if(a&&e.shouldThrowOnError)throw new ht(a)}return{error:a,data:o,count:c,status:h,statusText:l}});return this.shouldThrowOnError||(i=i.catch(n=>{var a;let o="",c="",h="",l=n?.cause;if(l){var p,u,d,m;let et=(p=l?.message)!==null&&p!==void 0?p:"",U=(u=l?.code)!==null&&u!==void 0?u:"";o=`${(d=n?.name)!==null&&d!==void 0?d:"FetchError"}: ${n?.message}`,o+=`
2
2
 
3
- Caused by: ${(m=l?.name)!==null&&m!==void 0?m:"Error"}: ${Z}`,I&&(o+=` (${I})`),l?.stack&&(o+=`
4
- ${l.stack}`)}else{var b;o=(b=n?.stack)!==null&&b!==void 0?b:""}let v=this.url.toString().length;return n?.name==="AbortError"||n?.code==="ABORT_ERR"?(h="",c="Request was aborted (timeout or manual cancellation)",v>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${v} 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)",v>this.urlLengthLimit&&(c+=`. Your request URL is ${v} 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:`${(a=n?.name)!==null&&a!==void 0?a:"FetchError"}: ${n?.message}`,details:o,hint:c,code:h},data:null,count:null,status:0,statusText:""}})),i.then(s,t)}returns(){return this}overrideTypes(){return this}},ct=class extends lt{select(s){let t=!1,e=(s??"*").split("").map(r=>/\s/.test(r)&&!t?"":(r==='"'&&(t=!t),r)).join("");return this.url.searchParams.set("select",e),this.headers.append("Prefer","return=representation"),this}order(s,{ascending:t=!0,nullsFirst:e,foreignTable:r,referencedTable:i=r}={}){let n=i?`${i}.order`:"order",a=this.url.searchParams.get(n);return this.url.searchParams.set(n,`${a?`${a},`:""}${s}.${t?"asc":"desc"}${e===void 0?"":e?".nullsfirst":".nullslast"}`),this}limit(s,{foreignTable:t,referencedTable:e=t}={}){let r=typeof e>"u"?"limit":`${e}.limit`;return this.url.searchParams.set(r,`${s}`),this}range(s,t,{foreignTable:e,referencedTable:r=e}={}){let i=typeof r>"u"?"offset":`${r}.offset`,n=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${s}`),this.url.searchParams.set(n,`${t-s+1}`),this}abortSignal(s){return this.signal=s,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:s=!1,verbose:t=!1,settings:e=!1,buffers:r=!1,wal:i=!1,format:n="text"}={}){var a;let o=[s?"analyze":null,t?"verbose":null,e?"settings":null,r?"buffers":null,i?"wal":null].filter(Boolean).join("|"),c=(a=this.headers.get("Accept"))!==null&&a!==void 0?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${n}; for="${c}"; options=${o};`),n==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(s){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${s}`),this}},J=new RegExp("[,()]"),L=class extends ct{eq(s,t){return this.url.searchParams.append(s,`eq.${t}`),this}neq(s,t){return this.url.searchParams.append(s,`neq.${t}`),this}gt(s,t){return this.url.searchParams.append(s,`gt.${t}`),this}gte(s,t){return this.url.searchParams.append(s,`gte.${t}`),this}lt(s,t){return this.url.searchParams.append(s,`lt.${t}`),this}lte(s,t){return this.url.searchParams.append(s,`lte.${t}`),this}like(s,t){return this.url.searchParams.append(s,`like.${t}`),this}likeAllOf(s,t){return this.url.searchParams.append(s,`like(all).{${t.join(",")}}`),this}likeAnyOf(s,t){return this.url.searchParams.append(s,`like(any).{${t.join(",")}}`),this}ilike(s,t){return this.url.searchParams.append(s,`ilike.${t}`),this}ilikeAllOf(s,t){return this.url.searchParams.append(s,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(s,t){return this.url.searchParams.append(s,`ilike(any).{${t.join(",")}}`),this}regexMatch(s,t){return this.url.searchParams.append(s,`match.${t}`),this}regexIMatch(s,t){return this.url.searchParams.append(s,`imatch.${t}`),this}is(s,t){return this.url.searchParams.append(s,`is.${t}`),this}isDistinct(s,t){return this.url.searchParams.append(s,`isdistinct.${t}`),this}in(s,t){let e=Array.from(new Set(t)).map(r=>typeof r=="string"&&J.test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(s,`in.(${e})`),this}notIn(s,t){let e=Array.from(new Set(t)).map(r=>typeof r=="string"&&J.test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(s,`not.in.(${e})`),this}contains(s,t){return typeof t=="string"?this.url.searchParams.append(s,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(s,`cs.{${t.join(",")}}`):this.url.searchParams.append(s,`cs.${JSON.stringify(t)}`),this}containedBy(s,t){return typeof t=="string"?this.url.searchParams.append(s,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(s,`cd.{${t.join(",")}}`):this.url.searchParams.append(s,`cd.${JSON.stringify(t)}`),this}rangeGt(s,t){return this.url.searchParams.append(s,`sr.${t}`),this}rangeGte(s,t){return this.url.searchParams.append(s,`nxl.${t}`),this}rangeLt(s,t){return this.url.searchParams.append(s,`sl.${t}`),this}rangeLte(s,t){return this.url.searchParams.append(s,`nxr.${t}`),this}rangeAdjacent(s,t){return this.url.searchParams.append(s,`adj.${t}`),this}overlaps(s,t){return typeof t=="string"?this.url.searchParams.append(s,`ov.${t}`):this.url.searchParams.append(s,`ov.{${t.join(",")}}`),this}textSearch(s,t,{config:e,type:r}={}){let i="";r==="plain"?i="pl":r==="phrase"?i="ph":r==="websearch"&&(i="w");let n=e===void 0?"":`(${e})`;return this.url.searchParams.append(s,`${i}fts${n}.${t}`),this}match(s){return Object.entries(s).filter(([t,e])=>e!==void 0).forEach(([t,e])=>{this.url.searchParams.append(t,`eq.${e}`)}),this}not(s,t,e){return this.url.searchParams.append(s,`not.${t}.${e}`),this}or(s,{foreignTable:t,referencedTable:e=t}={}){let r=e?`${e}.or`:"or";return this.url.searchParams.append(r,`(${s})`),this}filter(s,t,e){return this.url.searchParams.append(s,`${t}.${e}`),this}},ht=class{constructor(s,{headers:t={},schema:e,fetch:r,urlLengthLimit:i=8e3}){this.url=s,this.headers=new f(t),this.schema=e,this.fetch=r,this.urlLengthLimit=i}cloneRequestState(){return{url:new S(this.url.toString()),headers:new f(this.headers)}}select(s,t){let{head:e=!1,count:r}=t??{},i=e?"HEAD":"GET",n=!1,a=(s??"*").split("").map(h=>/\s/.test(h)&&!n?"":(h==='"'&&(n=!n),h)).join(""),{url:o,headers:c}=this.cloneRequestState();return o.searchParams.set("select",a),r&&c.append("Prefer",`count=${r}`),new L({method:i,url:o,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(s,{count:t,defaultToNull:e=!0}={}){var r;let i="POST",{url:n,headers:a}=this.cloneRequestState();if(t&&a.append("Prefer",`count=${t}`),e||a.append("Prefer","missing=default"),Array.isArray(s)){let o=s.reduce((c,h)=>c.concat(Object.keys(h)),[]);if(o.length>0){let c=[...new Set(o)].map(h=>`"${h}"`);n.searchParams.set("columns",c.join(","))}}return new L({method:i,url:n,headers:a,schema:this.schema,body:s,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(s,{onConflict:t,ignoreDuplicates:e=!1,count:r,defaultToNull:i=!0}={}){var n;let a="POST",{url:o,headers:c}=this.cloneRequestState();if(c.append("Prefer",`resolution=${e?"ignore":"merge"}-duplicates`),t!==void 0&&o.searchParams.set("on_conflict",t),r&&c.append("Prefer",`count=${r}`),i||c.append("Prefer","missing=default"),Array.isArray(s)){let h=s.reduce((l,p)=>l.concat(Object.keys(p)),[]);if(h.length>0){let l=[...new Set(h)].map(p=>`"${p}"`);o.searchParams.set("columns",l.join(","))}}return new L({method:a,url:o,headers:c,schema:this.schema,body:s,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}update(s,{count:t}={}){var e;let r="PATCH",{url:i,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new L({method:r,url:i,headers:n,schema:this.schema,body:s,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:s}={}){var t;let e="DELETE",{url:r,headers:i}=this.cloneRequestState();return s&&i.append("Prefer",`count=${s}`),new L({method:e,url:r,headers:i,schema:this.schema,fetch:(t=this.fetch)!==null&&t!==void 0?t:fetch,urlLengthLimit:this.urlLengthLimit})}};function T(s){"@babel/helpers - typeof";return T=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},T(s)}function pt(s,t){if(T(s)!="object"||!s)return s;var e=s[Symbol.toPrimitive];if(e!==void 0){var r=e.call(s,t||"default");if(T(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(s)}function ut(s){var t=pt(s,"string");return T(t)=="symbol"?t:t+""}function dt(s,t,e){return(t=ut(t))in s?Object.defineProperty(s,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):s[t]=e,s}function z(s,t){var e=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(s,i).enumerable})),e.push.apply(e,r)}return e}function E(s){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?z(Object(e),!0).forEach(function(r){dt(s,r,e[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(e)):z(Object(e)).forEach(function(r){Object.defineProperty(s,r,Object.getOwnPropertyDescriptor(e,r))})}return s}var K=class Y{constructor(t,{headers:e={},schema:r,fetch:i,timeout:n,urlLengthLimit:a=8e3}={}){this.url=t,this.headers=new f(e),this.schemaName=r,this.urlLengthLimit=a;let o=i??globalThis.fetch;n!==void 0&&n>0?this.fetch=(c,h)=>{let l=new W,p=setTimeout(()=>l.abort(),n),u=h?.signal;if(u){if(u.aborted)return clearTimeout(p),o(c,h);let d=()=>{clearTimeout(p),l.abort()};return u.addEventListener("abort",d,{once:!0}),o(c,E(E({},h),{},{signal:l.signal})).finally(()=>{clearTimeout(p),u.removeEventListener("abort",d)})}return o(c,E(E({},h),{},{signal:l.signal})).finally(()=>clearTimeout(p))}:this.fetch=o}from(t){if(!t||typeof t!="string"||t.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new ht(new S(`${this.url}/${t}`),{headers:new f(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(t){return new Y(this.url,{headers:this.headers,schema:t,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(t,e={},{head:r=!1,get:i=!1,count:n}={}){var a;let o,c=new S(`${this.url}/rpc/${t}`),h,l=d=>d!==null&&typeof d=="object"&&(!Array.isArray(d)||d.some(l)),p=r&&Object.values(e).some(l);p?(o="POST",h=e):r||i?(o=r?"HEAD":"GET",Object.entries(e).filter(([d,m])=>m!==void 0).map(([d,m])=>[d,Array.isArray(m)?`{${m.join(",")}}`:`${m}`]).forEach(([d,m])=>{c.searchParams.append(d,m)})):(o="POST",h=e);let u=new f(this.headers);return p?u.set("Prefer",n?`count=${n},return=minimal`:"return=minimal"):n&&u.set("Prefer",`count=${n}`),new L({method:o,url:c,headers:u,schema:this.schemaName,body:h,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit})}};var gt="/entities",Zt=(s,t)=>new K(s+gt,{fetch:t.fetchWithAuth.bind(t)});var V=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: ${(m=l?.name)!==null&&m!==void 0?m:"Error"}: ${et}`,U&&(o+=` (${U})`),l?.stack&&(o+=`
4
+ ${l.stack}`)}else{var b;o=(b=n?.stack)!==null&&b!==void 0?b:""}let v=this.url.toString().length;return n?.name==="AbortError"||n?.code==="ABORT_ERR"?(h="",c="Request was aborted (timeout or manual cancellation)",v>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${v} 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)",v>this.urlLengthLimit&&(c+=`. Your request URL is ${v} 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:`${(a=n?.name)!==null&&a!==void 0?a:"FetchError"}: ${n?.message}`,details:o,hint:c,code:h},data:null,count:null,status:0,statusText:""}})),i.then(s,t)}returns(){return this}overrideTypes(){return this}},ut=class extends pt{select(s){let t=!1,e=(s??"*").split("").map(r=>/\s/.test(r)&&!t?"":(r==='"'&&(t=!t),r)).join("");return this.url.searchParams.set("select",e),this.headers.append("Prefer","return=representation"),this}order(s,{ascending:t=!0,nullsFirst:e,foreignTable:r,referencedTable:i=r}={}){let n=i?`${i}.order`:"order",a=this.url.searchParams.get(n);return this.url.searchParams.set(n,`${a?`${a},`:""}${s}.${t?"asc":"desc"}${e===void 0?"":e?".nullsfirst":".nullslast"}`),this}limit(s,{foreignTable:t,referencedTable:e=t}={}){let r=typeof e>"u"?"limit":`${e}.limit`;return this.url.searchParams.set(r,`${s}`),this}range(s,t,{foreignTable:e,referencedTable:r=e}={}){let i=typeof r>"u"?"offset":`${r}.offset`,n=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${s}`),this.url.searchParams.set(n,`${t-s+1}`),this}abortSignal(s){return this.signal=s,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:s=!1,verbose:t=!1,settings:e=!1,buffers:r=!1,wal:i=!1,format:n="text"}={}){var a;let o=[s?"analyze":null,t?"verbose":null,e?"settings":null,r?"buffers":null,i?"wal":null].filter(Boolean).join("|"),c=(a=this.headers.get("Accept"))!==null&&a!==void 0?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${n}; for="${c}"; options=${o};`),n==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(s){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${s}`),this}},K=new RegExp("[,()]"),T=class extends ut{eq(s,t){return this.url.searchParams.append(s,`eq.${t}`),this}neq(s,t){return this.url.searchParams.append(s,`neq.${t}`),this}gt(s,t){return this.url.searchParams.append(s,`gt.${t}`),this}gte(s,t){return this.url.searchParams.append(s,`gte.${t}`),this}lt(s,t){return this.url.searchParams.append(s,`lt.${t}`),this}lte(s,t){return this.url.searchParams.append(s,`lte.${t}`),this}like(s,t){return this.url.searchParams.append(s,`like.${t}`),this}likeAllOf(s,t){return this.url.searchParams.append(s,`like(all).{${t.join(",")}}`),this}likeAnyOf(s,t){return this.url.searchParams.append(s,`like(any).{${t.join(",")}}`),this}ilike(s,t){return this.url.searchParams.append(s,`ilike.${t}`),this}ilikeAllOf(s,t){return this.url.searchParams.append(s,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(s,t){return this.url.searchParams.append(s,`ilike(any).{${t.join(",")}}`),this}regexMatch(s,t){return this.url.searchParams.append(s,`match.${t}`),this}regexIMatch(s,t){return this.url.searchParams.append(s,`imatch.${t}`),this}is(s,t){return this.url.searchParams.append(s,`is.${t}`),this}isDistinct(s,t){return this.url.searchParams.append(s,`isdistinct.${t}`),this}in(s,t){let e=Array.from(new Set(t)).map(r=>typeof r=="string"&&K.test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(s,`in.(${e})`),this}notIn(s,t){let e=Array.from(new Set(t)).map(r=>typeof r=="string"&&K.test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(s,`not.in.(${e})`),this}contains(s,t){return typeof t=="string"?this.url.searchParams.append(s,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(s,`cs.{${t.join(",")}}`):this.url.searchParams.append(s,`cs.${JSON.stringify(t)}`),this}containedBy(s,t){return typeof t=="string"?this.url.searchParams.append(s,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(s,`cd.{${t.join(",")}}`):this.url.searchParams.append(s,`cd.${JSON.stringify(t)}`),this}rangeGt(s,t){return this.url.searchParams.append(s,`sr.${t}`),this}rangeGte(s,t){return this.url.searchParams.append(s,`nxl.${t}`),this}rangeLt(s,t){return this.url.searchParams.append(s,`sl.${t}`),this}rangeLte(s,t){return this.url.searchParams.append(s,`nxr.${t}`),this}rangeAdjacent(s,t){return this.url.searchParams.append(s,`adj.${t}`),this}overlaps(s,t){return typeof t=="string"?this.url.searchParams.append(s,`ov.${t}`):this.url.searchParams.append(s,`ov.{${t.join(",")}}`),this}textSearch(s,t,{config:e,type:r}={}){let i="";r==="plain"?i="pl":r==="phrase"?i="ph":r==="websearch"&&(i="w");let n=e===void 0?"":`(${e})`;return this.url.searchParams.append(s,`${i}fts${n}.${t}`),this}match(s){return Object.entries(s).filter(([t,e])=>e!==void 0).forEach(([t,e])=>{this.url.searchParams.append(t,`eq.${e}`)}),this}not(s,t,e){return this.url.searchParams.append(s,`not.${t}.${e}`),this}or(s,{foreignTable:t,referencedTable:e=t}={}){let r=e?`${e}.or`:"or";return this.url.searchParams.append(r,`(${s})`),this}filter(s,t,e){return this.url.searchParams.append(s,`${t}.${e}`),this}},dt=class{constructor(s,{headers:t={},schema:e,fetch:r,urlLengthLimit:i=8e3}){this.url=s,this.headers=new f(t),this.schema=e,this.fetch=r,this.urlLengthLimit=i}cloneRequestState(){return{url:new S(this.url.toString()),headers:new f(this.headers)}}select(s,t){let{head:e=!1,count:r}=t??{},i=e?"HEAD":"GET",n=!1,a=(s??"*").split("").map(h=>/\s/.test(h)&&!n?"":(h==='"'&&(n=!n),h)).join(""),{url:o,headers:c}=this.cloneRequestState();return o.searchParams.set("select",a),r&&c.append("Prefer",`count=${r}`),new T({method:i,url:o,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(s,{count:t,defaultToNull:e=!0}={}){var r;let i="POST",{url:n,headers:a}=this.cloneRequestState();if(t&&a.append("Prefer",`count=${t}`),e||a.append("Prefer","missing=default"),Array.isArray(s)){let o=s.reduce((c,h)=>c.concat(Object.keys(h)),[]);if(o.length>0){let c=[...new Set(o)].map(h=>`"${h}"`);n.searchParams.set("columns",c.join(","))}}return new T({method:i,url:n,headers:a,schema:this.schema,body:s,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(s,{onConflict:t,ignoreDuplicates:e=!1,count:r,defaultToNull:i=!0}={}){var n;let a="POST",{url:o,headers:c}=this.cloneRequestState();if(c.append("Prefer",`resolution=${e?"ignore":"merge"}-duplicates`),t!==void 0&&o.searchParams.set("on_conflict",t),r&&c.append("Prefer",`count=${r}`),i||c.append("Prefer","missing=default"),Array.isArray(s)){let h=s.reduce((l,p)=>l.concat(Object.keys(p)),[]);if(h.length>0){let l=[...new Set(h)].map(p=>`"${p}"`);o.searchParams.set("columns",l.join(","))}}return new T({method:a,url:o,headers:c,schema:this.schema,body:s,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}update(s,{count:t}={}){var e;let r="PATCH",{url:i,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new T({method:r,url:i,headers:n,schema:this.schema,body:s,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:s}={}){var t;let e="DELETE",{url:r,headers:i}=this.cloneRequestState();return s&&i.append("Prefer",`count=${s}`),new T({method:e,url:r,headers:i,schema:this.schema,fetch:(t=this.fetch)!==null&&t!==void 0?t:fetch,urlLengthLimit:this.urlLengthLimit})}};function E(s){"@babel/helpers - typeof";return E=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},E(s)}function gt(s,t){if(E(s)!="object"||!s)return s;var e=s[Symbol.toPrimitive];if(e!==void 0){var r=e.call(s,t||"default");if(E(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(s)}function mt(s){var t=gt(s,"string");return E(t)=="symbol"?t:t+""}function ft(s,t,e){return(t=mt(t))in s?Object.defineProperty(s,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):s[t]=e,s}function Y(s,t){var e=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(s,i).enumerable})),e.push.apply(e,r)}return e}function x(s){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?Y(Object(e),!0).forEach(function(r){ft(s,r,e[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(e)):Y(Object(e)).forEach(function(r){Object.defineProperty(s,r,Object.getOwnPropertyDescriptor(e,r))})}return s}var V=class Q{constructor(t,{headers:e={},schema:r,fetch:i,timeout:n,urlLengthLimit:a=8e3}={}){this.url=t,this.headers=new f(e),this.schemaName=r,this.urlLengthLimit=a;let o=i??globalThis.fetch;n!==void 0&&n>0?this.fetch=(c,h)=>{let l=new q,p=setTimeout(()=>l.abort(),n),u=h?.signal;if(u){if(u.aborted)return clearTimeout(p),o(c,h);let d=()=>{clearTimeout(p),l.abort()};return u.addEventListener("abort",d,{once:!0}),o(c,x(x({},h),{},{signal:l.signal})).finally(()=>{clearTimeout(p),u.removeEventListener("abort",d)})}return o(c,x(x({},h),{},{signal:l.signal})).finally(()=>clearTimeout(p))}:this.fetch=o}from(t){if(!t||typeof t!="string"||t.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new dt(new S(`${this.url}/${t}`),{headers:new f(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(t){return new Q(this.url,{headers:this.headers,schema:t,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(t,e={},{head:r=!1,get:i=!1,count:n}={}){var a;let o,c=new S(`${this.url}/rpc/${t}`),h,l=d=>d!==null&&typeof d=="object"&&(!Array.isArray(d)||d.some(l)),p=r&&Object.values(e).some(l);p?(o="POST",h=e):r||i?(o=r?"HEAD":"GET",Object.entries(e).filter(([d,m])=>m!==void 0).map(([d,m])=>[d,Array.isArray(m)?`{${m.join(",")}}`:`${m}`]).forEach(([d,m])=>{c.searchParams.append(d,m)})):(o="POST",h=e);let u=new f(this.headers);return p?u.set("Prefer",n?`count=${n},return=minimal`:"return=minimal"):n&&u.set("Prefer",`count=${n}`),new T({method:o,url:c,headers:u,schema:this.schemaName,body:h,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit})}};var yt="/entities",ae=(s,t)=>new V(s+yt,{fetch:t.fetchWithAuth.bind(t)});var 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 b;o=(b=n?.stack)!==null&&b!==void 0?b:""}let v=this.url.to
33
33
  max-width: 400px;
34
34
  word-break: break-all;
35
35
  }
36
- `,document.head.appendChild(t)}createTooltip(){return this.tooltip?this.tooltip:(this.tooltip=document.createElement("div"),this.tooltip.id="__nvwa-inspector-tooltip",document.body.appendChild(this.tooltip),this.tooltip)}createOverlay(t){let e=document.createElement("div");return e.className=`__nvwa-inspector-overlay __nvwa-inspector-overlay-${t}`,document.body.appendChild(e),e}updateOverlayPosition(t,e){if(!e.isConnected)return;let r=e.getBoundingClientRect(),i=window.scrollX||window.pageXOffset,n=window.scrollY||window.pageYOffset;r.width>0&&r.height>0?(t.style.left=`${r.left+i}px`,t.style.top=`${r.top+n}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 c=t.getBoundingClientRect();o.style.left=`${c.left+window.scrollX}px`,o.style.top=`${c.top+window.scrollY-o.offsetHeight-8}px`,c.top<o.offsetHeight+8&&(o.style.top=`${c.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 n=this.createTooltip();e?n.textContent=e:n.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,n.style.display="block";let a=t.getBoundingClientRect();n.style.left=`${a.left+window.scrollX}px`,n.style.top=`${a.top+window.scrollY-n.offsetHeight-8}px`,a.top<n.offsetHeight+8&&(n.style.top=`${a.bottom+window.scrollY+8}px`)}selectElement(t,e){if(!t.isConnected)return;if(this.selectedElement===t&&this.selectedOverlay){this.updateOverlayPosition(this.selectedOverlay,t);return}this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null);let r=this.createOverlay("selected");this.updateOverlayPosition(r,t),this.selectedOverlay=r,this.selectedElement=t;let i=()=>{this.selectedOverlay&&this.selectedElement&&this.selectedElement.isConnected&&this.updateOverlayPosition(this.selectedOverlay,this.selectedElement)};this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler)),this.selectedUpdateHandler=i,window.addEventListener("scroll",i,!0),window.addEventListener("resize",i)}removeHighlight(){this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null),this.hoverElement&&(this.hoverElement=null),this.tooltip&&(this.tooltip.style.display="none"),this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler),this.hoverUpdateHandler=null)}clearSelection(){this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null),this.selectedElement&&(this.selectedElement=null),this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler),this.selectedUpdateHandler=null)}cleanup(){this.removeHighlight(),this.clearSelection(),this.tooltip&&this.tooltip.parentNode&&(this.tooltip.parentNode.removeChild(this.tooltip),this.tooltip=null);let t=document.getElementById("__nvwa-inspector-overlay-style");t&&t.parentNode&&t.parentNode.removeChild(t)}};function re(s="root"){if(typeof document>"u")return null;let t=document.getElementById(s)||document.body;if(!t)return null;let e=t.querySelector("[data-source-location]");if(e){let r=e.getAttribute("data-source-location");if(r)return r}if(t.firstElementChild){let i=t.firstElementChild.getAttribute("data-source-location");if(i)return i}return null}var mt={"wechat-pay":{id:"wechat-pay",name:"WeChat Pay",description:"WeChat payment for web and miniapp."},"wechat-platform":{id:"wechat-platform",name:"WeChat Partner",description:"WeChat partner merchant onboarding."},"alipay-web":{id:"alipay-web",name:"Alipay Web",description:"Alipay page pay (ISV)."},"alipay-mobile-web":{id:"alipay-mobile-web",name:"Alipay Mobile Web",description:"Alipay WAP pay (ISV)."},"alipay-miniprogram":{id:"alipay-miniprogram",name:"Alipay Mini Program",description:"Alipay mini program payment."},stripe:{id:"stripe",name:"Stripe",description:"Stripe payment."}};function ne(s){let t=s;if(typeof t.kind=="string")return t;if(typeof t.tradeNO=="string")return{kind:"alipay_miniprogram",tradeNO:t.tradeNO};if(typeof t.clientSecret=="string")return{kind:"stripe_client_secret",clientSecret:t.clientSecret};if(typeof t.redirectUrl=="string")return{kind:"redirect_url",redirectUrl:t.redirectUrl};if(typeof t.formHtml=="string")return{kind:"alipay_page",formHtml:t.formHtml};if(typeof t.codeUrl=="string")return{kind:"wechat_native_qr",codeUrl:t.codeUrl};let e=t.jsapiPayParams??t;return typeof e.timeStamp=="string"&&typeof e.nonceStr=="string"&&typeof e.package=="string"&&typeof e.paySign=="string"&&typeof e.appId=="string"?{kind:"wechat_jsapi",mode:"jsapi",jsapiPayParams:{appId:e.appId,timeStamp:e.timeStamp,nonceStr:e.nonceStr,package:e.package,signType:e.signType??"RSA",paySign:e.paySign}}:null}function ae(s,t,e){return t.requestPayment(s.payParams,e)}async function oe(s,t){let e=s.payment?.providers??{};return Object.entries(e).filter(([,r])=>r.enabled).map(([r])=>{let i=mt[r]??{id:r,name:r,description:""};return{...i,type:i.id}})}function R(s){return s&&typeof s=="object"?s:{}}function ft(s){let t=R(s),e=t.enabled===!0,r=String(t.oauthCredentialSource??"").toLowerCase();return r?{enabled:e,oauthCredentialSource:r==="custom"?"custom":"nvwa_default"}:{enabled:e}}function Q(s){let t=R(s),e=R(t.providers),r={};for(let[i,n]of Object.entries(e))r[i]=ft(n);return{providers:r}}function X(s){let t=R(s);return{socialLogin:Q(t.socialLogin),payment:Q(t.payment)}}function he(s,t){let e=s[t];return e?Object.entries(e.providers).filter(([,r])=>r.enabled).map(([r])=>r):[]}var yt=["DesktopWeb","MobileWeb","AndroidApp","IosApp","HarmonyApp","WechatMiniProgram","AlipayMiniProgram","DouyinMiniProgram"];function A(s){return yt.includes(s)}function de(s,t){let e=s.payParams;return{orderId:t?.orderId,platformOrderId:s.platformOrderId,payParams:e,codeUrl:typeof e.codeUrl=="string"?e.codeUrl:void 0,formHtml:typeof e.formHtml=="string"?e.formHtml:void 0,order:t?.order}}async function ge(s){let{platformType:t,getMiniProgramIdentity:e}=s;if(t!=="WechatMiniProgram"&&t!=="AlipayMiniProgram")return{platformType:t};if(!e)return{platformType:t};let r=await e();return r?{platformType:r.platformType,platformUserId:r.platformUserId,appId:r.appId,unionid:r.unionid}:{platformType:t}}function C(s){return typeof s=="string"?s.trim():""}function me(s){if(!s||typeof s!="object"||Array.isArray(s))return{ok:!1,error:"Request body must be a JSON object"};let t=s,e=t.client;if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,error:"client is required and must be an object with platformType (use collectPaymentClientContext / nvwa.payment.collectPaymentClientContext)"};let r=e,i=C(r.platformType);if(!i)return{ok:!1,error:"client.platformType is required and must be non-empty"};if(!A(i))return{ok:!1,error:"client.platformType is invalid; use a valid ProjectPlatformType (e.g. DesktopWeb, MobileWeb, WechatMiniProgram)"};let n={platformType:i},a=C(r.platformUserId);a&&(n.platformUserId=a);let o=C(r.appId);o&&(n.appId=o);let c=C(r.unionid);c&&(n.unionid=c);let h=C(t.providerId);if(!h)return{ok:!1,error:"providerId is required"};let l=C(t.bizOrderId);if(!l)return{ok:!1,error:"bizOrderId is required"};let p=t.amount;if(typeof p!="number"||!Number.isFinite(p)||p<=0)return{ok:!1,error:"amount must be a positive number"};let u=C(t.currency),d=C(t.returnUrl),m;if(t.metadata!=null){if(typeof t.metadata!="object"||Array.isArray(t.metadata))return{ok:!1,error:"metadata must be a plain object when provided"};m={...t.metadata}}return{ok:!0,request:{client:n,bizOrderId:l,amount:p,providerId:h,...u?{currency:u}:{},...d?{returnUrl:d}:{},...m?{metadata:m}:{}}}}function Pe(s){if(!s?.trim())return{};try{return JSON.parse(s)}catch{return{}}}function be(s){return X(s.integrationProviders??{})}function Oe(s){let t=s.baseUrl?.trim()??"";if(!t)throw new Error("Nvwa: appConfig.baseUrl is required");let e=s.applicationCode?.trim()??"";if(!e)throw new Error("Nvwa: appConfig.applicationCode is required");let r=s.platformType?.trim()??"";if(!r)throw new Error("Nvwa: appConfig.platformType is required");if(!A(r))throw new Error("Nvwa: appConfig.platformType is invalid");return{baseUrl:t,applicationCode:e,platformType:r}}export{_ as AuthClient,g as CURRENT_JWT_KEY,gt as ENTITIES_BASE_PATH,nt as FILE_STORAGE_BASE_PATH,at as GENERATE_UPLOAD_URL_PATH,f as Headers,P as LOGIN_TOKEN_KEY,O as LOGIN_USER_PROFILE_KEY,H as NvwaEdgeFunctions,B as NvwaFileStorage,D as NvwaHttpClient,V as OverlayManager,yt as PROJECT_PLATFORM_TYPES,$ as Request,j as Response,M as SET_AUTH_TOKEN_HEADER,S as URL,ge as collectPaymentClientContext,Zt as createPostgrestClient,he as getEnabledProvidersByIntegration,oe as getPaymentProvidersFromIntegrationProviders,re as getSourceLocationFromDOM,A as isProjectPlatformType,X as normalizeIntegrationProvidersConfig,ne as normalizePayParams,me as parseCreatePaymentOrderRequest,Pe as parseNvwaAppConfig,ae as requestPaymentFromOrderResult,Oe as requireNvwaAppConfig,be as resolveIntegrationProvidersFromAppConfig,de as toPaymentOrderResultFromGateway};
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,n=window.scrollY||window.pageYOffset;r.width>0&&r.height>0?(t.style.left=`${r.left+i}px`,t.style.top=`${r.top+n}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 c=t.getBoundingClientRect();o.style.left=`${c.left+window.scrollX}px`,o.style.top=`${c.top+window.scrollY-o.offsetHeight-8}px`,c.top<o.offsetHeight+8&&(o.style.top=`${c.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 n=this.createTooltip();e?n.textContent=e:n.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,n.style.display="block";let a=t.getBoundingClientRect();n.style.left=`${a.left+window.scrollX}px`,n.style.top=`${a.top+window.scrollY-n.offsetHeight-8}px`,a.top<n.offsetHeight+8&&(n.style.top=`${a.bottom+window.scrollY+8}px`)}selectElement(t,e){if(!t.isConnected)return;if(this.selectedElement===t&&this.selectedOverlay){this.updateOverlayPosition(this.selectedOverlay,t);return}this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null);let r=this.createOverlay("selected");this.updateOverlayPosition(r,t),this.selectedOverlay=r,this.selectedElement=t;let i=()=>{this.selectedOverlay&&this.selectedElement&&this.selectedElement.isConnected&&this.updateOverlayPosition(this.selectedOverlay,this.selectedElement)};this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler)),this.selectedUpdateHandler=i,window.addEventListener("scroll",i,!0),window.addEventListener("resize",i)}removeHighlight(){this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null),this.hoverElement&&(this.hoverElement=null),this.tooltip&&(this.tooltip.style.display="none"),this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler),this.hoverUpdateHandler=null)}clearSelection(){this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null),this.selectedElement&&(this.selectedElement=null),this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler),this.selectedUpdateHandler=null)}cleanup(){this.removeHighlight(),this.clearSelection(),this.tooltip&&this.tooltip.parentNode&&(this.tooltip.parentNode.removeChild(this.tooltip),this.tooltip=null);let t=document.getElementById("__nvwa-inspector-overlay-style");t&&t.parentNode&&t.parentNode.removeChild(t)}};function ce(s="root"){if(typeof document>"u")return null;let t=document.getElementById(s)||document.body;if(!t)return null;let e=t.querySelector("[data-source-location]");if(e){let r=e.getAttribute("data-source-location");if(r)return r}if(t.firstElementChild){let i=t.firstElementChild.getAttribute("data-source-location");if(i)return i}return null}var wt={"wechat-pay":{id:"wechat-pay",name:"WeChat Pay",description:"WeChat payment for web and miniapp."},"wechat-platform":{id:"wechat-platform",name:"WeChat Partner",description:"WeChat partner merchant onboarding."},"alipay-web":{id:"alipay-web",name:"Alipay Web",description:"Alipay page pay (ISV)."},"alipay-mobile-web":{id:"alipay-mobile-web",name:"Alipay Mobile Web",description:"Alipay WAP pay (ISV)."},"alipay-miniprogram":{id:"alipay-miniprogram",name:"Alipay Mini Program",description:"Alipay mini program payment."},stripe:{id:"stripe",name:"Stripe",description:"Stripe payment."}};function ue(s){let t=s;if(typeof t.kind=="string")return t;if(typeof t.tradeNO=="string")return{kind:"alipay_miniprogram",tradeNO:t.tradeNO};if(typeof t.clientSecret=="string")return{kind:"stripe_client_secret",clientSecret:t.clientSecret};if(typeof t.redirectUrl=="string")return{kind:"redirect_url",redirectUrl:t.redirectUrl};if(typeof t.formHtml=="string")return{kind:"alipay_page",formHtml:t.formHtml};if(typeof t.codeUrl=="string")return{kind:"wechat_native_qr",codeUrl:t.codeUrl};let e=t.jsapiPayParams??t;return typeof e.timeStamp=="string"&&typeof e.nonceStr=="string"&&typeof e.package=="string"&&typeof e.paySign=="string"&&typeof e.appId=="string"?{kind:"wechat_jsapi",mode:"jsapi",jsapiPayParams:{appId:e.appId,timeStamp:e.timeStamp,nonceStr:e.nonceStr,package:e.package,signType:e.signType??"RSA",paySign:e.paySign}}:null}function de(s,t,e){return t.requestPayment(s.payParams,e)}async function ge(s,t){let e=s.payment?.providers??{};return Object.entries(e).filter(([,r])=>r.enabled).map(([r])=>{let i=wt[r]??{id:r,name:r,description:""};return{...i,type:i.id}})}function R(s){return s&&typeof s=="object"?s:{}}function vt(s){let t=R(s),e=t.enabled===!0,r=String(t.oauthCredentialSource??"").toLowerCase();return r?{enabled:e,oauthCredentialSource:r==="custom"?"custom":"nvwa_default"}:{enabled:e}}function Z(s){let t=R(s),e=R(t.providers),r={};for(let[i,n]of Object.entries(e))r[i]=vt(n);return{providers:r}}function tt(s){let t=R(s);return{socialLogin:Z(t.socialLogin),payment:Z(t.payment)}}function ye(s,t){let e=s[t];return e?Object.entries(e.providers).filter(([,r])=>r.enabled).map(([r])=>r):[]}var Pt=["DesktopWeb","MobileWeb","AndroidApp","IosApp","HarmonyApp","WechatMiniProgram","AlipayMiniProgram","DouyinMiniProgram"];function I(s){return Pt.includes(s)}function Pe(s,t){let e=s.payParams;return{orderId:t?.orderId,platformOrderId:s.platformOrderId,payParams:e,codeUrl:typeof e.codeUrl=="string"?e.codeUrl:void 0,formHtml:typeof e.formHtml=="string"?e.formHtml:void 0,order:t?.order}}async function be(s){let{platformType:t,getMiniProgramIdentity:e}=s;if(t!=="WechatMiniProgram"&&t!=="AlipayMiniProgram")return{platformType:t};if(!e)return{platformType:t};let r=await e();return r?{platformType:r.platformType,platformUserId:r.platformUserId,appId:r.appId,unionid:r.unionid}:{platformType:t}}function C(s){return typeof s=="string"?s.trim():""}function Oe(s){if(!s||typeof s!="object"||Array.isArray(s))return{ok:!1,error:"Request body must be a JSON object"};let t=s,e=t.client;if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,error:"client is required and must be an object with platformType (use collectPaymentClientContext / nvwa.payment.collectPaymentClientContext)"};let r=e,i=C(r.platformType);if(!i)return{ok:!1,error:"client.platformType is required and must be non-empty"};if(!I(i))return{ok:!1,error:"client.platformType is invalid; use a valid ProjectPlatformType (e.g. DesktopWeb, MobileWeb, WechatMiniProgram)"};let n={platformType:i},a=C(r.platformUserId);a&&(n.platformUserId=a);let o=C(r.appId);o&&(n.appId=o);let c=C(r.unionid);c&&(n.unionid=c);let h=C(t.providerId);if(!h)return{ok:!1,error:"providerId is required"};let l=C(t.bizOrderId);if(!l)return{ok:!1,error:"bizOrderId is required"};let p=t.amount;if(typeof p!="number"||!Number.isFinite(p)||p<=0)return{ok:!1,error:"amount must be a positive number"};let u=C(t.currency),d=C(t.returnUrl),m;if(t.metadata!=null){if(typeof t.metadata!="object"||Array.isArray(t.metadata))return{ok:!1,error:"metadata must be a plain object when provided"};m={...t.metadata}}return{ok:!0,request:{client:n,bizOrderId:l,amount:p,providerId:h,...u?{currency:u}:{},...d?{returnUrl:d}:{},...m?{metadata:m}:{}}}}function Ee(s){if(!s?.trim())return{};try{return JSON.parse(s)}catch{return{}}}function xe(s){return tt(s.integrationProviders??{})}function Re(s){let t=s.baseUrl?.trim()??"";if(!t)throw new Error("Nvwa: appConfig.baseUrl is required");let e=s.applicationCode?.trim()??"";if(!e)throw new Error("Nvwa: appConfig.applicationCode is required");let r=s.platformType?.trim()??"";if(!r)throw new Error("Nvwa: appConfig.platformType is required");if(!I(r))throw new Error("Nvwa: appConfig.platformType is invalid");return{baseUrl:t,applicationCode:e,platformType:r}}export{k as AuthClient,g as CURRENT_JWT_KEY,yt as ENTITIES_BASE_PATH,lt as FILE_STORAGE_BASE_PATH,ct as GENERATE_UPLOAD_URL_PATH,f as Headers,P as LOGIN_TOKEN_KEY,O as LOGIN_USER_PROFILE_KEY,M as NvwaEdgeFunctions,z as NvwaFileStorage,L as NvwaFunctionInvokeError,J as NvwaHttpClient,X as OverlayManager,Pt as PROJECT_PLATFORM_TYPES,j as Request,H as Response,D as SET_AUTH_TOKEN_HEADER,S as URL,be as collectPaymentClientContext,ae as createPostgrestClient,A as edgeFunctionInvokeErrorMessage,ye as getEnabledProvidersByIntegration,ge as getPaymentProvidersFromIntegrationProviders,ce as getSourceLocationFromDOM,I as isProjectPlatformType,tt as normalizeIntegrationProvidersConfig,ue as normalizePayParams,Oe as parseCreatePaymentOrderRequest,Ee as parseNvwaAppConfig,de as requestPaymentFromOrderResult,Re as requireNvwaAppConfig,xe as resolveIntegrationProvidersFromAppConfig,Pe as toPaymentOrderResultFromGateway};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nvwa-app/sdk-core",
3
- "version": "6.47.0",
3
+ "version": "6.48.0",
4
4
  "description": "NVWA跨端通用工具类核心接口",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -31,7 +31,7 @@
31
31
  "dependencies": {
32
32
  "@nvwa-app/nvwa-http-polyfill": "^0.1.0",
33
33
  "@nvwa-app/postgrest-js": "^2.100.1",
34
- "@nvwa-app/sdk-shared": "^6.47.0"
34
+ "@nvwa-app/sdk-shared": "^6.48.0"
35
35
  },
36
36
  "devDependencies": {
37
37
  "@types/node": "^24.3.0",